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.
package/dist/index.d.cts CHANGED
@@ -1,3566 +1,2 @@
1
- import * as _$zod_v30 from "zod/v3";
2
- import * as _langchain from "langchain";
3
- 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";
4
- import * as _langgraph from "@langchain/langgraph";
5
- import { AnnotationRoot, ChatModelStream, Command, Namespace, NativeStreamTransformer, ReducedValue, StateSchema, StreamTransformer } from "@langchain/langgraph";
6
- import { z } from "zod/v4";
7
- import { BaseCheckpointSaver, BaseStore } from "@langchain/langgraph-checkpoint";
8
- import * as _messages from "@langchain/core/messages";
9
- import * as z$2 from "zod";
10
- import { z as z$1 } from "zod";
11
- import * as _$zod_v4_core0 from "zod/v4/core";
12
- import * as _$_langchain_core_tools0 from "@langchain/core/tools";
13
- import { ClientTool, ServerTool, StructuredTool as StructuredTool$1 } from "@langchain/core/tools";
14
- import { InteropZodObject } from "@langchain/core/utils/types";
15
- import { BaseLanguageModel, LanguageModelLike } from "@langchain/core/language_models/base";
16
- import { CaptureSnapshotOptions, CaptureSnapshotOptions as LangSmithCaptureSnapshotOptions, CreateSandboxOptions, Sandbox, Snapshot, Snapshot as LangSmithSnapshot, StartSandboxOptions, StartSandboxOptions as LangSmithStartSandboxOptions } from "langsmith/experimental/sandbox";
17
- import { Runnable } from "@langchain/core/runnables";
18
- import { BaseChatModel } from "@langchain/core/language_models/chat_models";
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">)[]>;
868
- //#endregion
869
- //#region src/backends/state.d.ts
870
- /**
871
- * Backend that stores files in agent state (ephemeral).
872
- *
873
- * Uses LangGraph's state management and checkpointing. Files persist within
874
- * a conversation thread but not across threads. State is automatically
875
- * checkpointed after each agent step.
876
- *
877
- * Special handling: Since LangGraph state must be updated via Command objects
878
- * (not direct mutation), operations return filesUpdate in WriteResult/EditResult
879
- * for the middleware to apply via Command.
880
- */
881
- declare class StateBackend implements BackendProtocolV2 {
882
- private runtime;
883
- private fileFormat;
884
- constructor(options?: BackendOptions);
885
- /**
886
- * @deprecated Pass no `runtime` argument
887
- */
888
- constructor(runtime: BackendRuntime, options?: BackendOptions);
889
- /**
890
- * Whether this instance was constructed with the legacy factory pattern.
891
- *
892
- * When true, state is read from the injected `runtime` and `filesUpdate`
893
- * is returned to the caller. When false, state is read from LangGraph's
894
- * execution context and updates are sent via `__pregel_send`.
895
- */
896
- private get isLegacy();
897
- /**
898
- * Get files from current state.
899
- *
900
- * In legacy mode, reads from the injected {@link BackendRuntime}.
901
- * In zero-arg mode, reads via {@link PREGEL_READ_KEY} with fresh=true,
902
- * which applies any pending task writes through the reducer before returning.
903
- */
904
- private get files();
905
- /**
906
- * Push a files state update through LangGraph's internal send channel.
907
- *
908
- * In zero-arg mode, sends the update via the `__pregel_send` function
909
- * from {@link getConfig}, mirroring Python's `CONFIG_KEY_SEND`.
910
- * In legacy mode, this is a no-op — the caller uses `filesUpdate`
911
- * from the return value instead.
912
- *
913
- * @param update - Map of file paths to their updated {@link FileData}
914
- */
915
- private sendFilesUpdate;
916
- /**
917
- * List files and directories in the specified directory (non-recursive).
918
- *
919
- * @param path - Absolute path to directory
920
- * @returns LsResult with list of FileInfo objects on success or error on failure.
921
- * Directories have a trailing / in their path and is_dir=true.
922
- */
923
- ls(path: string): LsResult;
924
- /**
925
- * Read file content.
926
- *
927
- * Text files are paginated by line offset/limit.
928
- * Binary files return full Uint8Array content (offset/limit ignored).
929
- *
930
- * @param filePath - Absolute file path
931
- * @param offset - Line offset to start reading from (0-indexed)
932
- * @param limit - Maximum number of lines to read
933
- * @returns ReadResult with content on success or error on failure
934
- */
935
- read(filePath: string, offset?: number, limit?: number): ReadResult;
936
- /**
937
- * Read file content as raw FileData.
938
- *
939
- * @param filePath - Absolute file path
940
- * @returns ReadRawResult with raw file data on success or error on failure
941
- */
942
- readRaw(filePath: string): ReadRawResult;
943
- /**
944
- * Create a new file with content.
945
- * Returns WriteResult with filesUpdate to update LangGraph state.
946
- */
947
- write(filePath: string, content: string): WriteResult;
948
- /**
949
- * Edit a file by replacing string occurrences.
950
- * Returns EditResult with filesUpdate and occurrences.
951
- */
952
- edit(filePath: string, oldString: string, newString: string, replaceAll?: boolean): EditResult;
953
- /**
954
- * Search file contents for a literal text pattern.
955
- * Binary files are skipped.
956
- */
957
- grep(pattern: string, path?: string, glob?: string | null): GrepResult;
958
- /**
959
- * Structured glob matching returning FileInfo objects.
960
- */
961
- glob(pattern: string, path?: string): GlobResult;
962
- /**
963
- * Upload multiple files.
964
- *
965
- * Note: Since LangGraph state must be updated via Command objects,
966
- * the caller must apply filesUpdate via Command after calling this method.
967
- *
968
- * @param files - List of [path, content] tuples to upload
969
- * @returns List of FileUploadResponse objects, one per input file
970
- */
971
- uploadFiles(files: Array<[string, Uint8Array]>): FileUploadResponse[] & {
972
- filesUpdate?: Record<string, FileData>;
973
- };
974
- /**
975
- * Download multiple files.
976
- *
977
- * @param paths - List of file paths to download
978
- * @returns List of FileDownloadResponse objects, one per input path
979
- */
980
- downloadFiles(paths: string[]): FileDownloadResponse[];
981
- }
982
- //#endregion
983
- //#region src/backends/store.d.ts
984
- /**
985
- * Context provided to dynamic namespace factory functions.
986
- */
987
- interface StoreBackendContext<StateT = unknown> {
988
- /**
989
- * Current graph state, when available.
990
- *
991
- * In legacy factory mode this is the injected runtime state. In zero-arg mode
992
- * this is read from the current LangGraph execution context.
993
- */
994
- state: StateT;
995
- /**
996
- * Runnable config, when available.
997
- *
998
- * This mirrors the Python implementation's access to config metadata for
999
- * namespace resolution.
1000
- */
1001
- config?: {
1002
- metadata?: Record<string, unknown>;
1003
- configurable?: Record<string, unknown>;
1004
- };
1005
- /**
1006
- * Legacy assistant identifier, resolved from config metadata first and then
1007
- * from the injected runtime for backwards compatibility.
1008
- */
1009
- assistantId?: string;
1010
- }
1011
- type StoreBackendNamespaceFactory<StateT = unknown> = (context: StoreBackendContext<StateT>) => string[];
1012
- /**
1013
- * Options for StoreBackend constructor.
1014
- */
1015
- interface StoreBackendOptions<StateT = unknown> extends BackendOptions {
1016
- /**
1017
- * Explicit store instance to use for persistence.
1018
- *
1019
- * This mirrors the Python API and allows constructing a backend directly with
1020
- * a store instance, e.g. `new StoreBackend({ store })`.
1021
- *
1022
- * When omitted, the backend uses the legacy injected runtime store or the
1023
- * LangGraph execution-context store.
1024
- */
1025
- store?: BaseStore;
1026
- /**
1027
- * Custom namespace for store operations.
1028
- *
1029
- * Accepts either a static namespace array or a factory that derives the
1030
- * namespace from the current backend context.
1031
- *
1032
- * If not provided, falls back to legacy assistant-id detection from config
1033
- * metadata, then the injected runtime's `assistantId`, and finally
1034
- * `["filesystem"]`.
1035
- *
1036
- * @example
1037
- * ```typescript
1038
- * // Static namespace
1039
- * new StoreBackend({
1040
- * namespace: ["memories", orgId, userId, "filesystem"],
1041
- * });
1042
- *
1043
- * // Dynamic namespace
1044
- * new StoreBackend({
1045
- * namespace: ({ state }) => [
1046
- * "memories",
1047
- * (state as { userId: string }).userId,
1048
- * "filesystem",
1049
- * ],
1050
- * });
1051
- * ```
1052
- */
1053
- namespace?: string[] | StoreBackendNamespaceFactory<StateT>;
1054
- }
1055
- /**
1056
- * Backend that stores files in LangGraph's BaseStore (persistent).
1057
- *
1058
- * Uses LangGraph's Store for persistent, cross-conversation storage.
1059
- * Files are organized via namespaces and persist across all threads.
1060
- *
1061
- * The namespace can be customized via a factory function for flexible
1062
- * isolation patterns (user-scoped, org-scoped, etc.), or falls back
1063
- * to legacy assistant_id-based isolation.
1064
- */
1065
- declare class StoreBackend implements BackendProtocolV2 {
1066
- private stateAndStore;
1067
- private storeOverride;
1068
- private _namespace;
1069
- private fileFormat;
1070
- constructor(options?: StoreBackendOptions);
1071
- /**
1072
- * @deprecated Pass no `stateAndStore` argument
1073
- */
1074
- constructor(stateAndStore: StateAndStore, options?: StoreBackendOptions);
1075
- /**
1076
- * Get the BaseStore instance for persistent storage operations.
1077
- *
1078
- * In legacy mode, reads from the injected {@link StateAndStore}.
1079
- * In zero-arg mode, retrieves the store from the LangGraph execution
1080
- * context via {@link getLangGraphStore}.
1081
- *
1082
- * @returns BaseStore instance
1083
- * @throws Error if no store is available in either mode
1084
- */
1085
- private getStore;
1086
- /**
1087
- * Get the current graph state when available.
1088
- */
1089
- private getState;
1090
- /**
1091
- * Get the most relevant runnable config for namespace resolution.
1092
- */
1093
- private getNamespaceConfig;
1094
- /**
1095
- * Legacy assistant-id detection compatible with both Python and the
1096
- * historical TypeScript `assistantId` runtime property.
1097
- */
1098
- private getLegacyAssistantId;
1099
- /**
1100
- * Get the namespace for store operations.
1101
- *
1102
- * Resolution order:
1103
- * 1. Explicit namespace from constructor options
1104
- * 2. Namespace factory resolved from the current backend context
1105
- * 3. Assistant ID from runtime config / LangGraph config metadata
1106
- * 4. Legacy `assistantId` from the injected runtime
1107
- * 5. `["filesystem"]`
1108
- */
1109
- protected getNamespace(): string[];
1110
- /**
1111
- * Convert a store Item to FileData format.
1112
- *
1113
- * @param storeItem - The store Item containing file data
1114
- * @returns FileData object
1115
- * @throws Error if required fields are missing or have incorrect types
1116
- */
1117
- private convertStoreItemToFileData;
1118
- /**
1119
- * Convert FileData to a value suitable for store.put().
1120
- *
1121
- * @param fileData - The FileData to convert
1122
- * @returns Object with content, mimeType, created_at, and modified_at fields
1123
- */
1124
- private convertFileDataToStoreValue;
1125
- /**
1126
- * Search store with automatic pagination to retrieve all results.
1127
- *
1128
- * @param store - The store to search
1129
- * @param namespace - Hierarchical path prefix to search within
1130
- * @param options - Optional query, filter, and page_size
1131
- * @returns List of all items matching the search criteria
1132
- */
1133
- private searchStorePaginated;
1134
- /**
1135
- * List files and directories in the specified directory (non-recursive).
1136
- *
1137
- * @param path - Absolute path to directory
1138
- * @returns LsResult with list of FileInfo objects on success or error on failure.
1139
- * Directories have a trailing / in their path and is_dir=true.
1140
- */
1141
- ls(path: string): Promise<LsResult>;
1142
- /**
1143
- * Read file content.
1144
- *
1145
- * Text files are paginated by line offset/limit.
1146
- * Binary files return full Uint8Array content (offset/limit ignored).
1147
- *
1148
- * @param filePath - Absolute file path
1149
- * @param offset - Line offset to start reading from (0-indexed)
1150
- * @param limit - Maximum number of lines to read
1151
- * @returns ReadResult with content on success or error on failure
1152
- */
1153
- read(filePath: string, offset?: number, limit?: number): Promise<ReadResult>;
1154
- /**
1155
- * Read file content as raw FileData.
1156
- *
1157
- * @param filePath - Absolute file path
1158
- * @returns ReadRawResult with raw file data on success or error on failure
1159
- */
1160
- readRaw(filePath: string): Promise<ReadRawResult>;
1161
- /**
1162
- * Create a new file with content.
1163
- * Returns WriteResult. External storage sets filesUpdate=null.
1164
- */
1165
- write(filePath: string, content: string): Promise<WriteResult>;
1166
- /**
1167
- * Edit a file by replacing string occurrences.
1168
- * Returns EditResult. External storage sets filesUpdate=null.
1169
- */
1170
- edit(filePath: string, oldString: string, newString: string, replaceAll?: boolean): Promise<EditResult>;
1171
- /**
1172
- * Search file contents for a literal text pattern.
1173
- * Binary files are skipped.
1174
- */
1175
- grep(pattern: string, path?: string, glob?: string | null): Promise<GrepResult>;
1176
- /**
1177
- * Structured glob matching returning FileInfo objects.
1178
- */
1179
- glob(pattern: string, path?: string): Promise<GlobResult>;
1180
- /**
1181
- * Upload multiple files.
1182
- *
1183
- * @param files - List of [path, content] tuples to upload
1184
- * @returns List of FileUploadResponse objects, one per input file
1185
- */
1186
- uploadFiles(files: Array<[string, Uint8Array]>): Promise<FileUploadResponse[]>;
1187
- /**
1188
- * Download multiple files.
1189
- *
1190
- * @param paths - List of file paths to download
1191
- * @returns List of FileDownloadResponse objects, one per input path
1192
- */
1193
- downloadFiles(paths: string[]): Promise<FileDownloadResponse[]>;
1194
- }
1195
- //#endregion
1196
- //#region src/backends/filesystem.d.ts
1197
- /**
1198
- * Backend that reads and writes files directly from the filesystem.
1199
- *
1200
- * Files are accessed using their actual filesystem paths. Relative paths are
1201
- * resolved relative to the current working directory. Content is read/written
1202
- * as plain text, and metadata (timestamps) are derived from filesystem stats.
1203
- */
1204
- declare class FilesystemBackend implements BackendProtocolV2 {
1205
- protected cwd: string;
1206
- protected virtualMode: boolean;
1207
- private maxFileSizeBytes;
1208
- constructor(options?: {
1209
- rootDir?: string;
1210
- virtualMode?: boolean;
1211
- maxFileSizeMb?: number;
1212
- });
1213
- /**
1214
- * Resolve a file path with security checks.
1215
- *
1216
- * When virtualMode=true, treat incoming paths as virtual absolute paths under
1217
- * this.cwd, disallow traversal (.., ~) and ensure resolved path stays within root.
1218
- * When virtualMode=false, preserve legacy behavior: absolute paths are allowed
1219
- * as-is; relative paths resolve under cwd.
1220
- *
1221
- * @param key - File path (absolute, relative, or virtual when virtualMode=true)
1222
- * @returns Resolved absolute path string
1223
- * @throws Error if path traversal detected or path outside root
1224
- */
1225
- private resolvePath;
1226
- /**
1227
- * List files and directories in the specified directory (non-recursive).
1228
- *
1229
- * @param dirPath - Absolute directory path to list files from
1230
- * @returns List of FileInfo objects for files and directories directly in the directory.
1231
- * Directories have a trailing / in their path and is_dir=true.
1232
- */
1233
- ls(dirPath: string): Promise<LsResult>;
1234
- /**
1235
- * Read file content with line numbers.
1236
- *
1237
- * @param filePath - Absolute or relative file path
1238
- * @param offset - Line offset to start reading from (0-indexed)
1239
- * @param limit - Maximum number of lines to read
1240
- * @returns Formatted file content with line numbers, or error message
1241
- */
1242
- read(filePath: string, offset?: number, limit?: number): Promise<ReadResult>;
1243
- /**
1244
- * Read file content as raw FileData.
1245
- *
1246
- * @param filePath - Absolute file path
1247
- * @returns ReadRawResult with raw file data on success or error on failure
1248
- */
1249
- readRaw(filePath: string): Promise<ReadRawResult>;
1250
- /**
1251
- * Create a new file with content.
1252
- * Returns WriteResult. External storage sets filesUpdate=null.
1253
- */
1254
- write(filePath: string, content: string): Promise<WriteResult>;
1255
- /**
1256
- * Edit a file by replacing string occurrences.
1257
- * Returns EditResult. External storage sets filesUpdate=null.
1258
- */
1259
- edit(filePath: string, oldString: string, newString: string, replaceAll?: boolean): Promise<EditResult>;
1260
- /**
1261
- * Search for a literal text pattern in files.
1262
- *
1263
- * Uses ripgrep if available, falling back to substring search.
1264
- *
1265
- * @param pattern - Literal string to search for (NOT regex).
1266
- * @param dirPath - Directory or file path to search in. Defaults to current directory.
1267
- * @param glob - Optional glob pattern to filter which files to search.
1268
- * @returns List of GrepMatch dicts containing path, line number, and matched text.
1269
- */
1270
- grep(pattern: string, dirPath?: string, glob?: string | null): Promise<GrepResult>;
1271
- /**
1272
- * Search using ripgrep with fixed-string (literal) mode.
1273
- *
1274
- * @param pattern - Literal string to search for (unescaped).
1275
- * @param baseFull - Resolved base path to search in.
1276
- * @param includeGlob - Optional glob pattern to filter files.
1277
- * @returns Dict mapping file paths to list of (line_number, line_text) tuples.
1278
- * Returns null if ripgrep is unavailable or times out.
1279
- */
1280
- private ripgrepSearch;
1281
- /**
1282
- * Fallback search using literal substring matching when ripgrep is unavailable.
1283
- *
1284
- * Recursively searches files, respecting maxFileSizeBytes limit.
1285
- *
1286
- * @param pattern - Literal string to search for.
1287
- * @param baseFull - Resolved base path to search in.
1288
- * @param includeGlob - Optional glob pattern to filter files by name.
1289
- * @returns Dict mapping file paths to list of (line_number, line_text) tuples.
1290
- */
1291
- private literalSearch;
1292
- /**
1293
- * Structured glob matching returning FileInfo objects.
1294
- */
1295
- glob(pattern: string, searchPath?: string): Promise<GlobResult>;
1296
- /**
1297
- * Upload multiple files to the filesystem.
1298
- *
1299
- * @param files - List of [path, content] tuples to upload
1300
- * @returns List of FileUploadResponse objects, one per input file
1301
- */
1302
- uploadFiles(files: Array<[string, Uint8Array]>): Promise<FileUploadResponse[]>;
1303
- /**
1304
- * Download multiple files from the filesystem.
1305
- *
1306
- * @param paths - List of file paths to download
1307
- * @returns List of FileDownloadResponse objects, one per input path
1308
- */
1309
- downloadFiles(paths: string[]): Promise<FileDownloadResponse[]>;
1310
- }
1311
- //#endregion
1312
- //#region src/backends/composite.d.ts
1313
- /**
1314
- * Backend that routes file operations to different backends based on path prefix.
1315
- *
1316
- * This enables hybrid storage strategies like:
1317
- * - `/memories/` → StoreBackend (persistent, cross-thread)
1318
- * - Everything else → StateBackend (ephemeral, per-thread)
1319
- *
1320
- * The CompositeBackend handles path prefix stripping/re-adding transparently.
1321
- */
1322
- declare class CompositeBackend implements BackendProtocolV2 {
1323
- private default;
1324
- private routes;
1325
- private sortedRoutes;
1326
- constructor(defaultBackend: AnyBackendProtocol, routes: Record<string, AnyBackendProtocol>);
1327
- /** Delegates to default backend's id if it is a sandbox, otherwise empty string. */
1328
- get id(): string;
1329
- /** Route prefixes registered on this backend (e.g. `["/workspace"]`). */
1330
- get routePrefixes(): string[];
1331
- /**
1332
- * Type guard — returns true if `backend` is a {@link CompositeBackend}.
1333
- *
1334
- * Uses duck-typing on `routePrefixes` so it works across module boundaries
1335
- * where `instanceof` may fail.
1336
- */
1337
- static isInstance(backend: unknown): backend is CompositeBackend;
1338
- /**
1339
- * Determine which backend handles this key and strip prefix.
1340
- *
1341
- * @param key - Original file path
1342
- * @returns Tuple of [backend, stripped_key] where stripped_key has the route
1343
- * prefix removed (but keeps leading slash).
1344
- */
1345
- private getBackendAndKey;
1346
- /**
1347
- * List files and directories in the specified directory (non-recursive).
1348
- *
1349
- * @param path - Absolute path to directory
1350
- * @returns LsResult with list of FileInfo objects (with route prefixes added) on success or error on failure.
1351
- * Directories have a trailing / in their path and is_dir=true.
1352
- */
1353
- ls(path: string): Promise<LsResult>;
1354
- /**
1355
- * Read file content, routing to appropriate backend.
1356
- *
1357
- * @param filePath - Absolute file path
1358
- * @param offset - Line offset to start reading from (0-indexed)
1359
- * @param limit - Maximum number of lines to read
1360
- * @returns Formatted file content with line numbers, or error message
1361
- */
1362
- read(filePath: string, offset?: number, limit?: number): Promise<ReadResult>;
1363
- /**
1364
- * Read file content as raw FileData.
1365
- *
1366
- * @param filePath - Absolute file path
1367
- * @returns ReadRawResult with raw file data on success or error on failure
1368
- */
1369
- readRaw(filePath: string): Promise<ReadRawResult>;
1370
- /**
1371
- * Structured search results or error string for invalid input.
1372
- */
1373
- grep(pattern: string, path?: string, glob?: string | null): Promise<GrepResult>;
1374
- /**
1375
- * Structured glob matching returning FileInfo objects.
1376
- */
1377
- glob(pattern: string, path?: string): Promise<GlobResult>;
1378
- /**
1379
- * Create a new file, routing to appropriate backend.
1380
- *
1381
- * @param filePath - Absolute file path
1382
- * @param content - File content as string
1383
- * @returns WriteResult with path or error
1384
- */
1385
- write(filePath: string, content: string): Promise<WriteResult>;
1386
- /**
1387
- * Edit a file, routing to appropriate backend.
1388
- *
1389
- * @param filePath - Absolute file path
1390
- * @param oldString - String to find and replace
1391
- * @param newString - Replacement string
1392
- * @param replaceAll - If true, replace all occurrences
1393
- * @returns EditResult with path, occurrences, or error
1394
- */
1395
- edit(filePath: string, oldString: string, newString: string, replaceAll?: boolean): Promise<EditResult>;
1396
- /**
1397
- * Execute a command via the default backend.
1398
- * Execution is not path-specific, so it always delegates to the default backend.
1399
- *
1400
- * @param command - Full shell command string to execute
1401
- * @returns ExecuteResponse with combined output, exit code, and truncation flag
1402
- * @throws Error if the default backend doesn't support command execution
1403
- */
1404
- execute(command: string): Promise<ExecuteResponse>;
1405
- /**
1406
- * Upload multiple files, batching by backend for efficiency.
1407
- *
1408
- * @param files - List of [path, content] tuples to upload
1409
- * @returns List of FileUploadResponse objects, one per input file
1410
- */
1411
- uploadFiles(files: Array<[string, Uint8Array]>): Promise<FileUploadResponse[]>;
1412
- /**
1413
- * Download multiple files, batching by backend for efficiency.
1414
- *
1415
- * @param paths - List of file paths to download
1416
- * @returns List of FileDownloadResponse objects, one per input path
1417
- */
1418
- downloadFiles(paths: string[]): Promise<FileDownloadResponse[]>;
1419
- }
1420
- //#endregion
1421
- //#region src/backends/local-shell.d.ts
1422
- /**
1423
- * Options for creating a LocalShellBackend instance.
1424
- */
1425
- interface LocalShellBackendOptions {
1426
- /**
1427
- * Working directory for both filesystem operations and shell commands.
1428
- * @defaultValue `process.cwd()`
1429
- */
1430
- rootDir?: string;
1431
- /**
1432
- * Enable virtual path mode for filesystem operations.
1433
- * When true, treats rootDir as a virtual root filesystem.
1434
- * Does NOT restrict shell commands.
1435
- * @defaultValue `false`
1436
- */
1437
- virtualMode?: boolean;
1438
- /**
1439
- * Maximum time in seconds to wait for shell command execution.
1440
- * Commands exceeding this timeout will be terminated.
1441
- * @defaultValue `120`
1442
- */
1443
- timeout?: number;
1444
- /**
1445
- * Maximum number of bytes to capture from command output.
1446
- * Output exceeding this limit will be truncated.
1447
- * @defaultValue `100_000`
1448
- */
1449
- maxOutputBytes?: number;
1450
- /**
1451
- * Environment variables for shell commands. If undefined, starts with an empty
1452
- * environment (unless inheritEnv is true).
1453
- * @defaultValue `undefined`
1454
- */
1455
- env?: Record<string, string>;
1456
- /**
1457
- * Whether to inherit the parent process's environment variables.
1458
- * When false, only variables in env dict are available.
1459
- * When true, inherits all process.env variables and applies env overrides.
1460
- * @defaultValue `false`
1461
- */
1462
- inheritEnv?: boolean;
1463
- /**
1464
- * Files to create on disk during `create()`.
1465
- * Keys are file paths (resolved via the backend's path handling),
1466
- * values are string content.
1467
- * @defaultValue `undefined`
1468
- */
1469
- initialFiles?: Record<string, string>;
1470
- }
1471
- /**
1472
- * Filesystem backend with unrestricted local shell command execution.
1473
- *
1474
- * This backend extends FilesystemBackend to add shell command execution
1475
- * capabilities. Commands are executed directly on the host system without any
1476
- * sandboxing, process isolation, or security restrictions.
1477
- *
1478
- * **Security Warning:**
1479
- * This backend grants agents BOTH direct filesystem access AND unrestricted
1480
- * shell execution on your local machine. Use with extreme caution and only in
1481
- * appropriate environments.
1482
- *
1483
- * **Appropriate use cases:**
1484
- * - Local development CLIs (coding assistants, development tools)
1485
- * - Personal development environments where you trust the agent's code
1486
- * - CI/CD pipelines with proper secret management
1487
- *
1488
- * **Inappropriate use cases:**
1489
- * - Production environments (e.g., web servers, APIs, multi-tenant systems)
1490
- * - Processing untrusted user input or executing untrusted code
1491
- *
1492
- * Use StateBackend, StoreBackend, or extend BaseSandbox for production.
1493
- *
1494
- * @example
1495
- * ```typescript
1496
- * import { LocalShellBackend } from "@langchain/deepagents";
1497
- *
1498
- * // Create backend with explicit environment
1499
- * const backend = new LocalShellBackend({
1500
- * rootDir: "/home/user/project",
1501
- * env: { PATH: "/usr/bin:/bin" },
1502
- * });
1503
- *
1504
- * // Execute shell commands (runs directly on host)
1505
- * const result = await backend.execute("ls -la");
1506
- * console.log(result.output);
1507
- * console.log(result.exitCode);
1508
- *
1509
- * // Use filesystem operations (inherited from FilesystemBackend)
1510
- * const content = await backend.read("/README.md");
1511
- * await backend.write("/output.txt", "Hello world");
1512
- *
1513
- * // Inherit all environment variables
1514
- * const backend2 = new LocalShellBackend({
1515
- * rootDir: "/home/user/project",
1516
- * inheritEnv: true,
1517
- * });
1518
- * ```
1519
- */
1520
- declare class LocalShellBackend extends FilesystemBackend implements SandboxBackendProtocolV2 {
1521
- #private;
1522
- constructor(options?: LocalShellBackendOptions);
1523
- /** Unique identifier for this backend instance (format: "local-{random_hex}"). */
1524
- get id(): string;
1525
- /** Whether the backend has been initialized and is ready to use. */
1526
- get isInitialized(): boolean;
1527
- /** Alias for `isInitialized`, matching the standard sandbox interface. */
1528
- get isRunning(): boolean;
1529
- /**
1530
- * Initialize the backend by ensuring the rootDir exists.
1531
- *
1532
- * Creates the rootDir (and any parent directories) if it does not already
1533
- * exist. Safe to call on an existing directory. Must be called before
1534
- * `execute()`, or use the static `LocalShellBackend.create()` factory.
1535
- *
1536
- * @throws {SandboxError} If already initialized (`ALREADY_INITIALIZED`)
1537
- */
1538
- initialize(): Promise<void>;
1539
- /**
1540
- * Mark the backend as no longer running.
1541
- *
1542
- * For local shell backends there is no remote resource to tear down,
1543
- * so this simply flips the `isRunning` / `isInitialized` flag.
1544
- */
1545
- close(): Promise<void>;
1546
- /**
1547
- * Read a file, adapting error messages to the standard sandbox format.
1548
- */
1549
- read(filePath: string, offset?: number, limit?: number): Promise<ReadResult>;
1550
- /**
1551
- * Edit a file, adapting error messages to the standard sandbox format.
1552
- */
1553
- edit(filePath: string, oldString: string, newString: string, replaceAll?: boolean): Promise<EditResult>;
1554
- /**
1555
- * List directory contents, returning paths relative to rootDir.
1556
- */
1557
- ls(dirPath: string): Promise<LsResult>;
1558
- /**
1559
- * Glob matching that returns relative paths and includes directories.
1560
- */
1561
- glob(pattern: string, searchPath?: string): Promise<GlobResult>;
1562
- /**
1563
- * Execute a shell command directly on the host system.
1564
- *
1565
- * Commands are executed directly on your host system using `spawn()`
1566
- * with `shell: true`. There is NO sandboxing, isolation, or security
1567
- * restrictions. The command runs with your user's full permissions.
1568
- *
1569
- * The command is executed using the system shell with the working directory
1570
- * set to the backend's rootDir. Stdout and stderr are combined into a single
1571
- * output stream, with stderr lines prefixed with `[stderr]`.
1572
- *
1573
- * @param command - Shell command string to execute
1574
- * @returns ExecuteResponse containing output, exit code, and truncation flag
1575
- */
1576
- execute(command: string): Promise<ExecuteResponse>;
1577
- /**
1578
- * Create and initialize a new LocalShellBackend in one step.
1579
- *
1580
- * This is the recommended way to create a backend when the rootDir may
1581
- * not exist yet. It combines construction and initialization (ensuring
1582
- * rootDir exists) into a single async operation.
1583
- *
1584
- * @param options - Configuration options for the backend
1585
- * @returns An initialized and ready-to-use backend
1586
- */
1587
- static create(options?: LocalShellBackendOptions): Promise<LocalShellBackend>;
1588
- }
1589
- //#endregion
1590
- //#region src/backends/sandbox.d.ts
1591
- /**
1592
- * Base sandbox implementation with execute() as the only abstract method.
1593
- *
1594
- * This class provides default implementations for all SandboxBackendProtocol
1595
- * methods using shell commands executed via execute(). Concrete implementations
1596
- * only need to implement execute(), uploadFiles(), and downloadFiles().
1597
- *
1598
- * All shell commands use pure POSIX utilities (awk, grep, find, stat) that are
1599
- * available on any Linux including Alpine/busybox. No Python, Node.js, or
1600
- * other runtime is required on the sandbox host.
1601
- */
1602
- declare abstract class BaseSandbox implements SandboxBackendProtocolV2 {
1603
- /** Unique identifier for the sandbox backend */
1604
- abstract readonly id: string;
1605
- /**
1606
- * Execute a command in the sandbox.
1607
- * This is the only method concrete implementations must provide.
1608
- */
1609
- abstract execute(command: string): MaybePromise<ExecuteResponse>;
1610
- /**
1611
- * Upload multiple files to the sandbox.
1612
- * Implementations must support partial success.
1613
- */
1614
- abstract uploadFiles(files: Array<[string, Uint8Array]>): MaybePromise<FileUploadResponse[]>;
1615
- /**
1616
- * Download multiple files from the sandbox.
1617
- * Implementations must support partial success.
1618
- */
1619
- abstract downloadFiles(paths: string[]): MaybePromise<FileDownloadResponse[]>;
1620
- /**
1621
- * List files and directories in the specified directory (non-recursive).
1622
- *
1623
- * Uses pure POSIX shell (find + stat) via execute() — works on any Linux
1624
- * including Alpine. No Python or Node.js needed.
1625
- *
1626
- * @param path - Absolute path to directory
1627
- * @returns LsResult with list of FileInfo objects on success or error on failure.
1628
- */
1629
- ls(path: string): Promise<LsResult>;
1630
- /**
1631
- * Read file content with line numbers.
1632
- *
1633
- * Uses pure POSIX shell (awk) via execute() — only the requested slice
1634
- * is returned over the wire, making this efficient for large files.
1635
- * Works on any Linux including Alpine (no Python or Node.js needed).
1636
- *
1637
- * @param filePath - Absolute file path
1638
- * @param offset - Line offset to start reading from (0-indexed)
1639
- * @param limit - Maximum number of lines to read
1640
- * @returns Formatted file content with line numbers, or error message
1641
- */
1642
- read(filePath: string, offset?: number, limit?: number): Promise<ReadResult>;
1643
- /**
1644
- * Read file content as raw FileData.
1645
- *
1646
- * Uses downloadFiles() directly — no runtime needed on the sandbox host.
1647
- *
1648
- * @param filePath - Absolute file path
1649
- * @returns ReadRawResult with raw file data on success or error on failure
1650
- */
1651
- readRaw(filePath: string): Promise<ReadRawResult>;
1652
- /**
1653
- * Search for a literal text pattern in files using grep.
1654
- *
1655
- * @param pattern - Literal string to search for (NOT regex).
1656
- * @param path - Directory or file path to search in.
1657
- * @param glob - Optional glob pattern to filter which files to search.
1658
- * @returns List of GrepMatch dicts containing path, line number, and matched text.
1659
- */
1660
- grep(pattern: string, path?: string, glob?: string | null): Promise<GrepResult>;
1661
- /**
1662
- * Structured glob matching returning FileInfo objects.
1663
- *
1664
- * Uses pure POSIX shell (find + stat) via execute() to list all files,
1665
- * then applies glob-to-regex matching in TypeScript. No Python or Node.js
1666
- * needed on the sandbox host.
1667
- *
1668
- * Glob patterns are matched against paths relative to the search base:
1669
- * - `*` matches any characters except `/`
1670
- * - `**` matches any characters including `/` (recursive)
1671
- * - `?` matches a single character except `/`
1672
- * - `[...]` character classes
1673
- */
1674
- glob(pattern: string, path?: string): Promise<GlobResult>;
1675
- /**
1676
- * Create a new file with content.
1677
- *
1678
- * Uses downloadFiles() to check existence and uploadFiles() to write.
1679
- * No runtime needed on the sandbox host.
1680
- */
1681
- write(filePath: string, content: string): Promise<WriteResult>;
1682
- /**
1683
- * Edit a file by replacing string occurrences.
1684
- *
1685
- * Uses downloadFiles() to read, performs string replacement in TypeScript,
1686
- * then uploadFiles() to write back. No runtime needed on the sandbox host.
1687
- *
1688
- * Memory-conscious: releases intermediate references early so the GC can
1689
- * reclaim buffers before the next large allocation is made.
1690
- */
1691
- edit(filePath: string, oldString: string, newString: string, replaceAll?: boolean): Promise<EditResult>;
1692
- }
1693
- //#endregion
1694
- //#region src/backends/langsmith.d.ts
1695
- /** Options for constructing a LangSmithSandbox from an existing Sandbox instance. */
1696
- interface LangSmithSandboxOptions {
1697
- /** An already-created LangSmith Sandbox instance to wrap. */
1698
- sandbox: Sandbox;
1699
- /**
1700
- * Default command timeout in seconds.
1701
- * @default 1800 (30 minutes)
1702
- */
1703
- defaultTimeout?: number;
1704
- }
1705
- /** Options for the `LangSmithSandbox.create()` static factory. */
1706
- interface LangSmithSandboxCreateOptions extends Omit<CreateSandboxOptions, "name" | "timeout" | "waitForReady" | "snapshotName"> {
1707
- /**
1708
- * Snapshot ID to boot from.
1709
- * Mutually exclusive with `templateName`.
1710
- */
1711
- snapshotId?: string;
1712
- /**
1713
- * Name of the LangSmith sandbox template to use.
1714
- * Mutually exclusive with `snapshotId`.
1715
- * @deprecated Use `snapshotId` instead. Template-based creation will be
1716
- * removed in a future release.
1717
- */
1718
- templateName?: string;
1719
- /**
1720
- * LangSmith API key. Defaults to the `LANGSMITH_API_KEY` environment variable.
1721
- */
1722
- apiKey?: string;
1723
- /**
1724
- * Default command timeout in seconds.
1725
- * @default 1800 (30 minutes)
1726
- */
1727
- defaultTimeout?: number;
1728
- }
1729
- /**
1730
- * LangSmith Sandbox backend for deepagents.
1731
- *
1732
- * Extends `BaseSandbox` to provide command execution and file operations
1733
- * via the LangSmith Sandbox API.
1734
- *
1735
- * Use the static `LangSmithSandbox.create()` factory for the simplest setup,
1736
- * or construct directly with an existing `Sandbox` instance.
1737
- *
1738
- * @experimental This feature is experimental, and breaking changes are expected.
1739
- */
1740
- declare class LangSmithSandbox extends BaseSandbox {
1741
- #private;
1742
- constructor(options: LangSmithSandboxOptions);
1743
- /** Whether the sandbox is currently active. */
1744
- get isRunning(): boolean;
1745
- /** Return the LangSmith sandbox name as the unique identifier. */
1746
- get id(): string;
1747
- /**
1748
- * Execute a shell command in the LangSmith sandbox.
1749
- *
1750
- * @param command - Shell command string to execute
1751
- * @param options.timeout - Override timeout in seconds; 0 disables timeout
1752
- */
1753
- execute(command: string, options?: {
1754
- timeout?: number;
1755
- }): Promise<ExecuteResponse>;
1756
- /**
1757
- * Download files from the sandbox using LangSmith's native file read API.
1758
- * @param paths - List of file paths to download
1759
- * @returns List of FileDownloadResponse objects, one per input path
1760
- */
1761
- downloadFiles(paths: string[]): Promise<FileDownloadResponse[]>;
1762
- /**
1763
- * Upload files to the sandbox using LangSmith's native file write API.
1764
- * @param files - List of [path, content] tuples to upload
1765
- * @returns List of FileUploadResponse objects, one per input file
1766
- */
1767
- uploadFiles(files: Array<[string, Uint8Array]>): Promise<FileUploadResponse[]>;
1768
- /**
1769
- * Delete this sandbox and mark it as no longer running.
1770
- *
1771
- * After calling this, `isRunning` will be `false` and the sandbox
1772
- * cannot be used again.
1773
- */
1774
- close(): Promise<void>;
1775
- /**
1776
- * Start a stopped sandbox and wait until it is ready.
1777
- *
1778
- * After calling this, `isRunning` will be `true` and the sandbox
1779
- * can be used for command execution and file operations again.
1780
- *
1781
- * @param options - Start options (timeout, signal).
1782
- */
1783
- start(options?: StartSandboxOptions): Promise<void>;
1784
- /**
1785
- * Stop the sandbox without deleting it.
1786
- *
1787
- * Sandbox files are preserved and the sandbox can be restarted later
1788
- * with `start()`. After calling this, `isRunning` will be `false`.
1789
- */
1790
- stop(): Promise<void>;
1791
- /**
1792
- * Capture a snapshot from this running sandbox.
1793
- *
1794
- * Snapshots can be used to create new sandboxes via
1795
- * `LangSmithSandbox.create({ snapshotId })`.
1796
- *
1797
- * @param name - Name for the snapshot.
1798
- * @param options - Capture options (checkpoint, timeout).
1799
- * @returns The created Snapshot in "ready" status.
1800
- */
1801
- captureSnapshot(name: string, options?: CaptureSnapshotOptions): Promise<Snapshot>;
1802
- /**
1803
- * Create and return a new LangSmithSandbox in one step.
1804
- *
1805
- * This is the recommended way to create a sandbox — no need to import
1806
- * anything from `langsmith/experimental/sandbox` directly.
1807
- *
1808
- * @example
1809
- * ```typescript
1810
- * const sandbox = await LangSmithSandbox.create({
1811
- * snapshotId: "abc-123",
1812
- * });
1813
- *
1814
- * try {
1815
- * const agent = createDeepAgent({ model, backend: sandbox });
1816
- * await agent.invoke({ messages: [...] });
1817
- * } finally {
1818
- * await sandbox.close();
1819
- * }
1820
- * ```
1821
- */
1822
- static create(options: LangSmithSandboxCreateOptions): Promise<LangSmithSandbox>;
1823
- }
1824
- //#endregion
1825
- //#region src/backends/utils.d.ts
1826
- /**
1827
- * Adapt a v1 {@link BackendProtocol} to {@link BackendProtocolV2}.
1828
- *
1829
- * If the backend already implements v2, it is returned as-is.
1830
- * For v1 backends, wraps returns in Result types:
1831
- * - `read()` string returns wrapped in {@link ReadResult}
1832
- * - `readRaw()` FileData returns wrapped in {@link ReadRawResult}
1833
- * - `grep()` returns wrapped in {@link GrepResult}
1834
- * - `ls()` FileInfo[] returns wrapped in {@link LsResult}
1835
- * - `glob()` FileInfo[] returns wrapped in {@link GlobResult}
1836
- *
1837
- * Note: For sandbox instances, use {@link adaptSandboxProtocol} instead.
1838
- *
1839
- * @param backend - Backend instance (v1 or v2)
1840
- * @returns BackendProtocolV2-compatible backend
1841
- */
1842
- declare function adaptBackendProtocol(backend: AnyBackendProtocol): BackendProtocolV2;
1843
- /**
1844
- * Adapt a sandbox backend from v1 to v2 interface.
1845
- *
1846
- * This extends {@link adaptBackendProtocol} to also preserve sandbox-specific
1847
- * properties from {@link SandboxBackendProtocol}: `execute` and `id`.
1848
- *
1849
- * @param sandbox - Sandbox backend (v1 or v2)
1850
- * @returns SandboxBackendProtocolV2-compatible sandbox
1851
- */
1852
- declare function adaptSandboxProtocol(sandbox: AnySandboxProtocol): SandboxBackendProtocolV2;
1853
- //#endregion
1854
- //#region src/middleware/subagents.d.ts
1855
- /**
1856
- * Default system prompt for subagents.
1857
- * Provides a minimal base prompt that can be extended by specific subagent configurations.
1858
- */
1859
- 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.";
1860
- /**
1861
- * Default description for the general-purpose subagent.
1862
- * This description is shown to the model when selecting which subagent to use.
1863
- */
1864
- 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.";
1865
- /**
1866
- * System prompt section that explains how to use the task tool for spawning subagents.
1867
- *
1868
- * This prompt is automatically appended to the main agent's system prompt when
1869
- * using `createSubAgentMiddleware`. It provides guidance on:
1870
- * - When to use the task tool
1871
- * - Subagent lifecycle (spawn → run → return → reconcile)
1872
- * - When NOT to use the task tool
1873
- * - Best practices for parallel task execution
1874
- *
1875
- * You can provide a custom `systemPrompt` to `createSubAgentMiddleware` to override
1876
- * or extend this default.
1877
- */
1878
- declare const TASK_SYSTEM_PROMPT: string;
1879
- /**
1880
- * Type definitions for pre-compiled agents.
1881
- *
1882
- * @typeParam TRunnable - The type of the runnable (ReactAgent or Runnable).
1883
- * When using `createAgent` or `createDeepAgent`, this preserves the middleware
1884
- * types for type inference. Uses `ReactAgent<any>` to accept agents with any
1885
- * type configuration (including DeepAgent instances).
1886
- */
1887
- interface CompiledSubAgent<TRunnable extends ReactAgent<any> | Runnable = ReactAgent<any> | Runnable> {
1888
- /** The name of the agent */
1889
- name: string;
1890
- /** The description of the agent */
1891
- description: string;
1892
- /** The agent instance */
1893
- runnable: TRunnable;
1894
- }
1895
- /**
1896
- * Specification for a subagent that can be dynamically created.
1897
- *
1898
- * When using `createDeepAgent`, subagents automatically receive a default middleware
1899
- * stack (todoListMiddleware, filesystemMiddleware, summarizationMiddleware, etc.) before
1900
- * any custom `middleware` specified in this spec.
1901
- *
1902
- * Required fields:
1903
- * - `name`: Identifier used to select this subagent in the task tool
1904
- * - `description`: Shown to the model for subagent selection
1905
- * - `systemPrompt`: The system prompt for the subagent
1906
- *
1907
- * Optional fields:
1908
- * - `model`: Override the default model for this subagent
1909
- * - `tools`: Override the default tools for this subagent
1910
- * - `middleware`: Additional middleware appended after defaults
1911
- * - `interruptOn`: Human-in-the-loop configuration for specific tools
1912
- * - `skills`: Skill source paths for SkillsMiddleware (e.g., `["/skills/user/", "/skills/project/"]`)
1913
- *
1914
- * @example
1915
- * ```typescript
1916
- * const researcher: SubAgent = {
1917
- * name: "researcher",
1918
- * description: "Research assistant for complex topics",
1919
- * systemPrompt: "You are a research assistant.",
1920
- * tools: [webSearchTool],
1921
- * skills: ["/skills/research/"],
1922
- * };
1923
- * ```
1924
- */
1925
- interface SubAgent {
1926
- /** Identifier used to select this subagent in the task tool */
1927
- name: string;
1928
- /** Description shown to the model for subagent selection */
1929
- description: string;
1930
- /** The system prompt to use for the agent */
1931
- systemPrompt: string;
1932
- /** The tools to use for the agent (tool instances, not names). Defaults to defaultTools */
1933
- tools?: StructuredTool[];
1934
- /** The model for the agent. Defaults to defaultModel */
1935
- model?: LanguageModelLike | string;
1936
- /** Additional middleware to append after default_middleware */
1937
- middleware?: readonly AgentMiddleware$1[];
1938
- /** Human-in-the-loop configuration for specific tools. Requires a checkpointer. */
1939
- interruptOn?: Record<string, boolean | InterruptOnConfig>;
1940
- /**
1941
- * Skill source paths for SkillsMiddleware.
1942
- *
1943
- * List of paths to skill directories (e.g., `["/skills/user/", "/skills/project/"]`).
1944
- * When specified, the subagent will have its own SkillsMiddleware that loads skills
1945
- * from these paths. This allows subagents to have different skill sets than the main agent.
1946
- *
1947
- * Note: Custom subagents do NOT inherit skills from the main agent by default.
1948
- * Only the general-purpose subagent inherits the main agent's skills.
1949
- *
1950
- * @example
1951
- * ```typescript
1952
- * const researcher: SubAgent = {
1953
- * name: "researcher",
1954
- * description: "Research assistant",
1955
- * systemPrompt: "You are a researcher.",
1956
- * skills: ["/skills/research/", "/skills/web-search/"],
1957
- * };
1958
- * ```
1959
- */
1960
- skills?: string[];
1961
- /**
1962
- * Structured output response format for the subagent.
1963
- *
1964
- * When specified, the subagent will produce a `structuredResponse` conforming to the
1965
- * given schema. The structured response is JSON-serialized and returned as the
1966
- * ToolMessage content to the parent agent, replacing the default last-message extraction.
1967
- *
1968
- * Accepts any format supported by `createAgent`: Zod schemas, JSON schema objects,
1969
- * `toolStrategy(schema)`, `providerStrategy(schema)`, etc.
1970
- *
1971
- * @example
1972
- * ```typescript
1973
- * import { z } from "zod"
1974
- *
1975
- * const analyzer: SubAgent = {
1976
- * name: "analyzer",
1977
- * description: "Analyzes data and returns structured findings",
1978
- * systemPrompt: "Analyze the data and return your findings.",
1979
- * responseFormat: z.object({
1980
- * findings: z.string(),
1981
- * confidence: z.number(),
1982
- * }),
1983
- * };
1984
- * ```
1985
- */
1986
- responseFormat?: CreateAgentParams["responseFormat"];
1987
- /**
1988
- * Filesystem permission rules for this subagent.
1989
- *
1990
- * When specified, these rules **replace** the parent agent's permissions
1991
- * for all tool calls made by this subagent. When omitted, the subagent
1992
- * inherits the parent agent's permissions.
1993
- *
1994
- * Subagent permissions are a full replacement, not a merge.
1995
- *
1996
- * @example
1997
- * ```ts
1998
- * // Parent denies /restricted/**; this subagent can read it.
1999
- * const reader: SubAgent = {
2000
- * name: "reader",
2001
- * permissions: [
2002
- * { operations: ["read"], paths: ["/restricted/**"] },
2003
- * ],
2004
- * };
2005
- * ```
2006
- */
2007
- permissions?: FilesystemPermission[];
2008
- }
2009
- /**
2010
- * Base specification for the general-purpose subagent.
2011
- *
2012
- * This constant provides the default configuration for the general-purpose subagent
2013
- * that is automatically included when `generalPurposeAgent: true` (the default).
2014
- *
2015
- * The general-purpose subagent:
2016
- * - Has access to all tools from the main agent
2017
- * - Inherits skills from the main agent (when skills are configured)
2018
- * - Uses the same model as the main agent (by default)
2019
- * - Is ideal for delegating complex, multi-step tasks
2020
- *
2021
- * You can spread this constant and override specific properties when creating
2022
- * custom subagents that should behave similarly to the general-purpose agent:
2023
- *
2024
- * @example
2025
- * ```typescript
2026
- * import { GENERAL_PURPOSE_SUBAGENT, createDeepAgent } from "@anthropic/deepagents";
2027
- *
2028
- * // Use as-is (automatically included with generalPurposeAgent: true)
2029
- * const agent = createDeepAgent({ model: "claude-sonnet-4-5-20250929" });
2030
- *
2031
- * // Or create a custom variant with different tools
2032
- * const customGP: SubAgent = {
2033
- * ...GENERAL_PURPOSE_SUBAGENT,
2034
- * name: "research-gp",
2035
- * tools: [webSearchTool, readFileTool],
2036
- * };
2037
- *
2038
- * const agent = createDeepAgent({
2039
- * model: "claude-sonnet-4-5-20250929",
2040
- * subagents: [customGP],
2041
- * // Disable the default general-purpose agent since we're providing our own
2042
- * // (handled automatically when using createSubAgentMiddleware directly)
2043
- * });
2044
- * ```
2045
- */
2046
- declare const GENERAL_PURPOSE_SUBAGENT: Pick<SubAgent, "name" | "description" | "systemPrompt">;
2047
- /**
2048
- * Options for creating subagent middleware
2049
- */
2050
- interface SubAgentMiddlewareOptions {
2051
- /** The model to use for subagents */
2052
- defaultModel: LanguageModelLike | string;
2053
- /** The tools to use for the default general-purpose subagent */
2054
- defaultTools?: StructuredTool[];
2055
- /** Default middleware to apply to custom subagents (WITHOUT skills from main agent) */
2056
- defaultMiddleware?: AgentMiddleware$1[] | null;
2057
- /**
2058
- * Middleware specifically for the general-purpose subagent (includes skills from main agent).
2059
- * If not provided, falls back to defaultMiddleware.
2060
- */
2061
- generalPurposeMiddleware?: AgentMiddleware$1[] | null;
2062
- /** The tool configs for the default general-purpose subagent */
2063
- defaultInterruptOn?: Record<string, boolean | InterruptOnConfig> | null;
2064
- /** A list of additional subagents to provide to the agent */
2065
- subagents?: (SubAgent | CompiledSubAgent)[];
2066
- /** Full system prompt override */
2067
- systemPrompt?: string | null;
2068
- /** Whether to include the general-purpose agent */
2069
- generalPurposeAgent?: boolean;
2070
- /** Custom description for the task tool */
2071
- taskDescription?: string | null;
2072
- }
2073
- /**
2074
- * Create subagent middleware with task tool
2075
- */
2076
- declare function createSubAgentMiddleware(options: SubAgentMiddlewareOptions): AgentMiddleware$1<undefined, undefined, unknown, readonly [_langchain.DynamicStructuredTool<z.ZodObject<{
2077
- description: z.ZodString;
2078
- subagent_type: z.ZodString;
2079
- }, z.core.$strip>, {
2080
- description: string;
2081
- subagent_type: string;
2082
- }, {
2083
- description: string;
2084
- subagent_type: string;
2085
- }, string | Command<unknown, Record<string, unknown>, string>, unknown, "task">]>;
2086
- //#endregion
2087
- //#region src/middleware/patch_tool_calls.d.ts
2088
- /**
2089
- * Create middleware that enforces strict tool call / tool response parity in
2090
- * the messages history.
2091
- *
2092
- * Two kinds of violations are repaired:
2093
- * 1. **Dangling tool_calls** — an AIMessage contains tool_calls with no
2094
- * matching ToolMessage responses. Synthetic cancellation ToolMessages are
2095
- * injected so every tool_call has a response.
2096
- * 2. **Orphaned ToolMessages** — a ToolMessage exists whose `tool_call_id`
2097
- * does not match any tool_call in a preceding AIMessage. These are removed.
2098
- *
2099
- * This is critical for providers like Google Gemini that reject requests with
2100
- * mismatched function call / function response counts (400 INVALID_ARGUMENT).
2101
- *
2102
- * This middleware patches in two places:
2103
- * 1. `beforeAgent`: Patches state at the start of the agent loop (handles most cases)
2104
- * 2. `wrapModelCall`: Patches the request right before model invocation (handles
2105
- * edge cases like HITL rejection during graph resume where state updates from
2106
- * beforeAgent may not be applied in time)
2107
- *
2108
- * @returns AgentMiddleware that enforces tool call / response parity
2109
- *
2110
- * @example
2111
- * ```typescript
2112
- * import { createAgent } from "langchain";
2113
- * import { createPatchToolCallsMiddleware } from "./middleware/patch_tool_calls";
2114
- *
2115
- * const agent = createAgent({
2116
- * model: "claude-sonnet-4-5-20250929",
2117
- * middleware: [createPatchToolCallsMiddleware()],
2118
- * });
2119
- * ```
2120
- */
2121
- declare function createPatchToolCallsMiddleware(): AgentMiddleware<undefined, undefined, unknown, readonly (_$_langchain_core_tools0.ClientTool | _$_langchain_core_tools0.ServerTool)[]>;
2122
- //#endregion
2123
- //#region src/middleware/memory.d.ts
2124
- /**
2125
- * Options for the memory middleware.
2126
- */
2127
- interface MemoryMiddlewareOptions {
2128
- /**
2129
- * Backend instance or factory function for file operations.
2130
- * Use a factory for StateBackend since it requires runtime state.
2131
- */
2132
- backend: AnyBackendProtocol | BackendFactory | ((config: {
2133
- state: unknown;
2134
- store?: BaseStore;
2135
- }) => StateBackend);
2136
- /**
2137
- * List of memory file paths to load (e.g., ["~/.deepagents/AGENTS.md", "./.deepagents/AGENTS.md"]).
2138
- * Display names are automatically derived from the paths.
2139
- * Sources are loaded in order.
2140
- */
2141
- sources: string[];
2142
- /**
2143
- * Whether to add cache_control breakpoints to the memory content block.
2144
- * When true, the memory block is tagged with `cache_control: { type: "ephemeral" }`
2145
- * to enable prompt caching for providers that support it (e.g., Anthropic).
2146
- * @default false
2147
- */
2148
- addCacheControl?: boolean;
2149
- }
2150
- /**
2151
- * Create middleware for loading agent memory from AGENTS.md files.
2152
- *
2153
- * Loads memory content from configured sources and injects into the system prompt.
2154
- * Supports multiple sources that are combined together.
2155
- *
2156
- * @param options - Configuration options
2157
- * @returns AgentMiddleware for memory loading and injection
2158
- *
2159
- * @example
2160
- * ```typescript
2161
- * const middleware = createMemoryMiddleware({
2162
- * backend: new FilesystemBackend({ rootDir: "/" }),
2163
- * sources: [
2164
- * "~/.deepagents/AGENTS.md",
2165
- * "./.deepagents/AGENTS.md",
2166
- * ],
2167
- * });
2168
- * ```
2169
- */
2170
- declare function createMemoryMiddleware(options: MemoryMiddlewareOptions): AgentMiddleware<StateSchema<{
2171
- /**
2172
- * Dict mapping source paths to their loaded content.
2173
- * Marked as private so it's not included in the final agent state.
2174
- */
2175
- memoryContents: z$1.ZodOptional<z$1.ZodRecord<z$1.ZodString, z$1.ZodString>>;
2176
- files: _langgraph.ReducedValue<FilesRecord | undefined, FilesRecordUpdate | undefined>;
2177
- }>, undefined, unknown, readonly (_$_langchain_core_tools0.ClientTool | _$_langchain_core_tools0.ServerTool)[]>;
2178
- //#endregion
2179
- //#region src/middleware/skills.d.ts
2180
- declare const MAX_SKILL_FILE_SIZE: number;
2181
- declare const MAX_SKILL_NAME_LENGTH = 64;
2182
- declare const MAX_SKILL_DESCRIPTION_LENGTH = 1024;
2183
- /**
2184
- * Metadata for a skill per Agent Skills specification.
2185
- */
2186
- interface SkillMetadata$1 {
2187
- /**
2188
- * Skill identifier.
2189
- *
2190
- * Constraints per Agent Skills specification:
2191
- *
2192
- * - 1-64 characters
2193
- * - Unicode lowercase alphanumeric and hyphens only (`a-z` and `-`).
2194
- * - Must not start or end with `-`
2195
- * - Must not contain consecutive `--`
2196
- * - Must match the parent directory name containing the `SKILL.md` file
2197
- */
2198
- name: string;
2199
- /**
2200
- * What the skill does.
2201
- *
2202
- * Constraints per Agent Skills specification:
2203
- *
2204
- * - 1-1024 characters
2205
- * - Should describe both what the skill does and when to use it
2206
- * - Should include specific keywords that help agents identify relevant tasks
2207
- */
2208
- description: string;
2209
- /** Path to the SKILL.md file in the backend */
2210
- path: string;
2211
- /** License name or reference to bundled license file. */
2212
- license?: string | null;
2213
- /**
2214
- * Environment requirements.
2215
- *
2216
- * Constraints per Agent Skills specification:
2217
- *
2218
- * - 1-500 characters if provided
2219
- * - Should only be included if there are specific compatibility requirements
2220
- * - Can indicate intended product, required packages, etc.
2221
- */
2222
- compatibility?: string | null;
2223
- /**
2224
- * Arbitrary key-value mapping for additional metadata.
2225
- *
2226
- * Clients can use this to store additional properties not defined by the spec.
2227
- *
2228
- * It is recommended to keep key names unique to avoid conflicts.
2229
- */
2230
- metadata?: Record<string, string>;
2231
- /**
2232
- * Tool names the skill recommends using.
2233
- *
2234
- * Warning: this is experimental.
2235
- *
2236
- * Constraints per Agent Skills specification:
2237
- *
2238
- * - Space-delimited list of tool names
2239
- */
2240
- allowedTools?: string[];
2241
- /**
2242
- * Path to a JS/TS entrypoint file for a QuickJS REPL module, relative to the skill
2243
- * directory.
2244
- */
2245
- module?: string;
2246
- }
2247
- /**
2248
- * Options for the skills middleware.
2249
- */
2250
- interface SkillsMiddlewareOptions {
2251
- /**
2252
- * Backend instance or factory function for file operations.
2253
- * Use a factory for StateBackend since it requires runtime state.
2254
- */
2255
- backend: AnyBackendProtocol | BackendFactory | ((config: {
2256
- state: unknown;
2257
- store?: BaseStore;
2258
- }) => StateBackend);
2259
- /**
2260
- * List of skill source paths to load (e.g., ["/skills/user/", "/skills/project/"]).
2261
- * Paths must use POSIX conventions (forward slashes).
2262
- * Later sources override earlier ones for skills with the same name (last one wins).
2263
- */
2264
- sources: string[];
2265
- }
2266
- /**
2267
- * Create backend-agnostic middleware for loading and exposing agent skills.
2268
- *
2269
- * This middleware loads skills from configurable backend sources and injects
2270
- * skill metadata into the system prompt. It implements the progressive disclosure
2271
- * pattern: skill names and descriptions are shown in the prompt, but the agent
2272
- * reads full SKILL.md content only when needed.
2273
- *
2274
- * @param options - Configuration options
2275
- * @returns AgentMiddleware for skills loading and injection
2276
- *
2277
- * @example
2278
- * ```typescript
2279
- * const middleware = createSkillsMiddleware({
2280
- * backend: new FilesystemBackend({ rootDir: "/" }),
2281
- * sources: ["/skills/user/", "/skills/project/"],
2282
- * });
2283
- * ```
2284
- */
2285
- declare function createSkillsMiddleware(options: SkillsMiddlewareOptions): AgentMiddleware<StateSchema<{
2286
- skillsMetadata: ReducedValue<{
2287
- name: string;
2288
- description: string;
2289
- path: string;
2290
- license?: string | null | undefined;
2291
- compatibility?: string | null | undefined;
2292
- metadata?: Record<string, string> | undefined;
2293
- allowedTools?: string[] | undefined;
2294
- module?: string | undefined;
2295
- }[] | undefined, {
2296
- name: string;
2297
- description: string;
2298
- path: string;
2299
- license?: string | null | undefined;
2300
- compatibility?: string | null | undefined;
2301
- metadata?: Record<string, string> | undefined;
2302
- allowedTools?: string[] | undefined;
2303
- module?: string | undefined;
2304
- }[] | undefined>;
2305
- files: ReducedValue<FilesRecord | undefined, FilesRecordUpdate | undefined>;
2306
- }>, undefined, unknown, readonly (_$_langchain_core_tools0.ClientTool | _$_langchain_core_tools0.ServerTool)[]>;
2307
- //#endregion
2308
- //#region src/middleware/completion_callback.d.ts
2309
- /**
2310
- * Options for creating the completion callback middleware.
2311
- */
2312
- interface CompletionCallbackOptions {
2313
- /**
2314
- * Callback graph or assistant identifier. Used as the `assistant_id`
2315
- * argument in `runs.create()`.
2316
- */
2317
- callbackGraphId: string;
2318
- /**
2319
- * URL of the callback LangGraph server. Omit to use same-deployment
2320
- * ASGI transport.
2321
- */
2322
- url?: string;
2323
- /**
2324
- * Additional headers to include in requests to the callback server.
2325
- */
2326
- headers?: Record<string, string>;
2327
- }
2328
- /**
2329
- * Create a completion callback middleware for async subagents.
2330
- *
2331
- * **Experimental** — this middleware is experimental and may change.
2332
- *
2333
- * This middleware is added to a subagent's middleware stack. On success or
2334
- * model-call error, it sends a notification to the configured callback
2335
- * thread by calling `runs.create()`.
2336
- *
2337
- * The callback destination is configured with `callbackGraphId` and
2338
- * optional `url` and `headers`. The target thread is read from
2339
- * `callbackThreadId` in the subagent state.
2340
- *
2341
- * If `callbackThreadId` is not present in state, the middleware does
2342
- * nothing.
2343
- *
2344
- * @param options - Configuration options.
2345
- * @returns An `AgentMiddleware` instance.
2346
- *
2347
- * @example
2348
- * ```typescript
2349
- * import { createCompletionCallbackMiddleware } from "deepagents";
2350
- *
2351
- * const notifier = createCompletionCallbackMiddleware({
2352
- * callbackGraphId: "supervisor",
2353
- * });
2354
- *
2355
- * const agent = createDeepAgent({
2356
- * model: "claude-sonnet-4-5-20250929",
2357
- * middleware: [notifier],
2358
- * });
2359
- * ```
2360
- */
2361
- declare function createCompletionCallbackMiddleware(options: CompletionCallbackOptions): AgentMiddleware<z$2.ZodObject<{
2362
- callbackThreadId: z$2.ZodOptional<z$2.ZodString>;
2363
- }, z$2.core.$strip>, undefined, unknown, readonly (_$_langchain_core_tools0.ClientTool | _$_langchain_core_tools0.ServerTool)[]>;
2364
- //#endregion
2365
- //#region src/middleware/summarization.d.ts
2366
- /**
2367
- * Context size specification for summarization triggers and retention policies.
2368
- */
2369
- interface ContextSize {
2370
- /** Type of context measurement */
2371
- type: "messages" | "tokens" | "fraction";
2372
- /** Threshold value */
2373
- value: number;
2374
- }
2375
- /**
2376
- * Settings for truncating large tool arguments in old messages.
2377
- */
2378
- interface TruncateArgsSettings {
2379
- /**
2380
- * Threshold to trigger argument truncation.
2381
- * If not provided, truncation is disabled.
2382
- */
2383
- trigger?: ContextSize;
2384
- /**
2385
- * Context retention policy for message truncation.
2386
- * Defaults to keeping last 20 messages.
2387
- */
2388
- keep?: ContextSize;
2389
- /**
2390
- * Maximum character length for tool arguments before truncation.
2391
- * Defaults to 2000.
2392
- */
2393
- maxLength?: number;
2394
- /**
2395
- * Text to replace truncated arguments with.
2396
- * Defaults to "...(argument truncated)".
2397
- */
2398
- truncationText?: string;
2399
- }
2400
- /**
2401
- * Options for the summarization middleware.
2402
- */
2403
- interface SummarizationMiddlewareOptions {
2404
- /**
2405
- * The language model to use for generating summaries.
2406
- * Can be a model string (e.g., "gpt-4o-mini") or a language model instance.
2407
- * If omitted, middleware will use the active request model.
2408
- */
2409
- model?: string | BaseChatModel | BaseLanguageModel;
2410
- /**
2411
- * Backend instance or factory for persisting conversation history.
2412
- */
2413
- backend: AnyBackendProtocol | BackendFactory | ((config: {
2414
- state: unknown;
2415
- store?: BaseStore;
2416
- }) => StateBackend);
2417
- /**
2418
- * Threshold(s) that trigger summarization.
2419
- * Can be a single ContextSize or an array for multiple triggers.
2420
- */
2421
- trigger?: ContextSize | ContextSize[];
2422
- /**
2423
- * Context retention policy after summarization.
2424
- * Defaults to keeping last 20 messages.
2425
- */
2426
- keep?: ContextSize;
2427
- /**
2428
- * Prompt template for generating summaries.
2429
- */
2430
- summaryPrompt?: string;
2431
- /**
2432
- * Max tokens to include when generating summary.
2433
- * Defaults to 4000.
2434
- */
2435
- trimTokensToSummarize?: number;
2436
- /**
2437
- * Path prefix for storing conversation history.
2438
- * Defaults to "/conversation_history".
2439
- */
2440
- historyPathPrefix?: string;
2441
- /**
2442
- * Settings for truncating large tool arguments in old messages.
2443
- * If not provided, argument truncation is disabled.
2444
- */
2445
- truncateArgsSettings?: TruncateArgsSettings;
2446
- }
2447
- /**
2448
- * Compute summarization defaults based on model profile.
2449
- * Mirrors Python's `_compute_summarization_defaults`.
2450
- *
2451
- * If the model has a profile with `maxInputTokens`, uses fraction-based
2452
- * settings. Otherwise, uses fixed token/message counts.
2453
- *
2454
- * @param resolvedModel - The resolved chat model instance.
2455
- */
2456
- declare function computeSummarizationDefaults(resolvedModel: BaseChatModel): {
2457
- trigger: ContextSize;
2458
- keep: ContextSize;
2459
- truncateArgsSettings: TruncateArgsSettings;
2460
- };
2461
- /**
2462
- * Create summarization middleware with backend support for conversation history offloading.
2463
- *
2464
- * This middleware:
2465
- * 1. Monitors conversation length against configured thresholds
2466
- * 2. When triggered, offloads old messages to backend storage
2467
- * 3. Generates a summary of offloaded messages
2468
- * 4. Replaces old messages with the summary, preserving recent context
2469
- *
2470
- * @param options - Configuration options
2471
- * @returns AgentMiddleware for summarization and history offloading
2472
- */
2473
- declare function createSummarizationMiddleware(options: SummarizationMiddlewareOptions): AgentMiddleware<z$1.ZodObject<{
2474
- _summarizationSessionId: z$1.ZodOptional<z$1.ZodString>;
2475
- _summarizationEvent: z$1.ZodOptional<z$1.ZodObject<{
2476
- cutoffIndex: z$1.ZodNumber;
2477
- summaryMessage: z$1.ZodCustom<HumanMessage<_messages.MessageStructure<_messages.MessageToolSet>>, HumanMessage<_messages.MessageStructure<_messages.MessageToolSet>>>;
2478
- filePath: z$1.ZodNullable<z$1.ZodString>;
2479
- }, z$1.core.$strip>>;
2480
- }, z$1.core.$strip>, undefined, unknown, readonly (ClientTool | ServerTool)[]>;
2481
- //#endregion
2482
- //#region src/middleware/async_subagents.d.ts
2483
- /**
2484
- * Specification for an async subagent running on a remote [Agent Protocol](https://github.com/langchain-ai/agent-protocol)
2485
- * server.
2486
- *
2487
- * Async subagents connect to any Agent Protocol-compliant server via the
2488
- * LangGraph SDK. They run as background tasks that the main agent can
2489
- * monitor and update.
2490
- *
2491
- * Compatible with LangGraph Platform (managed) and self-hosted servers.
2492
- * Authentication for LangGraph Platform is handled automatically by the SDK
2493
- * via environment variables (`LANGGRAPH_API_KEY`, `LANGSMITH_API_KEY`, or
2494
- * `LANGCHAIN_API_KEY`). For self-hosted servers, pass custom auth via `headers`.
2495
- */
2496
- interface AsyncSubAgent {
2497
- /** Unique identifier for the async subagent. */
2498
- name: string;
2499
- /** What this subagent does. The main agent uses this to decide when to delegate. */
2500
- description: string;
2501
- /** The graph name or assistant ID on the Agent Protocol server. */
2502
- graphId: string;
2503
- /** URL of the Agent Protocol server. Defaults to the LangGraph SDK's default endpoint. */
2504
- url?: string;
2505
- /** Additional headers to include in requests to the server (e.g. for custom auth). */
2506
- headers?: Record<string, string>;
2507
- }
2508
- /**
2509
- * Possible statuses for an async subagent task.
2510
- *
2511
- * Statuses set by the middleware tools: `"running"`, `"success"`, `"error"`, `"cancelled"`.
2512
- * Statuses that may be returned by the remote server: `"pending"`, `"timeout"`, `"interrupted"`.
2513
- */
2514
- type AsyncTaskStatus = "pending" | "running" | "success" | "error" | "cancelled" | "timeout" | "interrupted";
2515
- /**
2516
- * A tracked async subagent task persisted in agent state.
2517
- *
2518
- * Each task maps to a single thread + run on a remote Agent Protocol server.
2519
- * The `taskId` is the same as `threadId`, so it can be used to look up
2520
- * the thread directly via the SDK.
2521
- */
2522
- interface AsyncTask {
2523
- /** Unique identifier for the task (same as thread id). */
2524
- taskId: string;
2525
- /** Name of the async subagent type that is running. */
2526
- agentName: string;
2527
- /** Thread ID on the remote server. */
2528
- threadId: string;
2529
- /** Run ID for the current execution on the thread. */
2530
- runId: string;
2531
- /** Current task status. */
2532
- status: AsyncTaskStatus;
2533
- /** ISO timestamp of when the task was launched. */
2534
- createdAt: string;
2535
- /** The prompt/description passed to the subagent when the task was launched. */
2536
- description?: string;
2537
- /** 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. */
2538
- updatedAt?: string;
2539
- /** ISO timestamp of the most recent status poll via the check tool. */
2540
- checkedAt?: string;
2541
- }
2542
- /**
2543
- * Task statuses that will never change.
2544
- *
2545
- * When listing tasks, live-status fetches are skipped for tasks whose
2546
- * cached status is in this set, since they are guaranteed to be final.
2547
- */
2548
- /**
2549
- * Names of the tools added by the async subagent middleware.
2550
- *
2551
- * Exported so `agent.ts` can include them in `BUILTIN_TOOL_NAMES` and
2552
- * surface a `ConfigurationError` if a user-provided tool collides.
2553
- */
2554
- declare const ASYNC_TASK_TOOL_NAMES: readonly ["start_async_task", "check_async_task", "update_async_task", "cancel_async_task", "list_async_tasks"];
2555
- /**
2556
- * Options for creating async subagent middleware.
2557
- */
2558
- interface AsyncSubAgentMiddlewareOptions {
2559
- /** List of async subagent specifications. Must have at least one. */
2560
- asyncSubAgents: AsyncSubAgent[];
2561
- /** System prompt override. Set to `null` to disable. Defaults to {@link ASYNC_TASK_SYSTEM_PROMPT}. */
2562
- systemPrompt?: string;
2563
- }
2564
- /**
2565
- * Create middleware that adds async subagent tools to an agent.
2566
- *
2567
- * Provides five tools for launching, checking, updating, cancelling, and
2568
- * listing background tasks on remote Agent Protocol servers. Task state is
2569
- * persisted in the `asyncTasks` state channel so it survives
2570
- * context compaction.
2571
- *
2572
- * Works with any Agent Protocol-compliant server — LangGraph Platform (managed)
2573
- * or self-hosted (e.g. a Hono/Express server implementing the Agent Protocol spec).
2574
- *
2575
- * @throws {Error} If no async subagents are provided or names are duplicated.
2576
- *
2577
- * @example
2578
- * ```ts
2579
- * const middleware = createAsyncSubAgentMiddleware({
2580
- * asyncSubAgents: [{
2581
- * name: "researcher",
2582
- * description: "Research agent for deep analysis",
2583
- * url: "https://my-agent-protocol-server.example.com",
2584
- * graphId: "research_agent",
2585
- * }],
2586
- * });
2587
- * ```
2588
- */
2589
- /**
2590
- * Type guard to distinguish async SubAgents from sync SubAgents/CompiledSubAgents.
2591
- *
2592
- * Uses the presence of the `graphId` field as the runtime discriminant —
2593
- * `AsyncSubAgent` requires it, while `SubAgent` and `CompiledSubAgent` do not have it.
2594
- */
2595
- declare function isAsyncSubAgent(subAgent: AnySubAgent): subAgent is AsyncSubAgent;
2596
- declare function createAsyncSubAgentMiddleware(options: AsyncSubAgentMiddlewareOptions): _langchain.AgentMiddleware<StateSchema<{
2597
- asyncTasks: ReducedValue<Record<string, {
2598
- taskId: string;
2599
- agentName: string;
2600
- threadId: string;
2601
- runId: string;
2602
- status: string;
2603
- createdAt: string;
2604
- description?: string | undefined;
2605
- updatedAt?: string | undefined;
2606
- checkedAt?: string | undefined;
2607
- }> | undefined, Record<string, {
2608
- taskId: string;
2609
- agentName: string;
2610
- threadId: string;
2611
- runId: string;
2612
- status: string;
2613
- createdAt: string;
2614
- description?: string | undefined;
2615
- updatedAt?: string | undefined;
2616
- checkedAt?: string | undefined;
2617
- }> | undefined>;
2618
- }>, undefined, unknown, (_langchain.DynamicStructuredTool<z.ZodObject<{
2619
- description: z.ZodString;
2620
- agentName: z.ZodString;
2621
- }, z.core.$strip>, {
2622
- description: string;
2623
- agentName: string;
2624
- }, {
2625
- description: string;
2626
- agentName: string;
2627
- }, string | Command<unknown, Record<string, unknown>, string>, unknown, "start_async_task"> | _langchain.DynamicStructuredTool<z.ZodObject<{
2628
- taskId: z.ZodString;
2629
- }, z.core.$strip>, {
2630
- taskId: string;
2631
- }, {
2632
- taskId: string;
2633
- }, string | Command<unknown, Record<string, unknown>, string>, unknown, "check_async_task"> | _langchain.DynamicStructuredTool<z.ZodObject<{
2634
- taskId: z.ZodString;
2635
- message: z.ZodString;
2636
- }, z.core.$strip>, {
2637
- taskId: string;
2638
- message: string;
2639
- }, {
2640
- taskId: string;
2641
- message: string;
2642
- }, string | Command<unknown, Record<string, unknown>, string>, unknown, "update_async_task"> | _langchain.DynamicStructuredTool<z.ZodObject<{
2643
- taskId: z.ZodString;
2644
- }, z.core.$strip>, {
2645
- taskId: string;
2646
- }, {
2647
- taskId: string;
2648
- }, string | Command<unknown, Record<string, unknown>, string>, unknown, "cancel_async_task"> | _langchain.DynamicStructuredTool<z.ZodObject<{
2649
- statusFilter: z.ZodOptional<z.ZodNullable<z.ZodString>>;
2650
- }, z.core.$strip>, {
2651
- statusFilter?: string | null | undefined;
2652
- }, {
2653
- statusFilter?: string | null | undefined;
2654
- }, string | Command<unknown, Record<string, unknown>, string>, unknown, "list_async_tasks">)[]>;
2655
- //#endregion
2656
- //#region src/stream.d.ts
2657
- /**
2658
- * Represents a single subagent invocation observed during a deep agent run.
2659
- *
2660
- * @typeParam TOutput - The subagent's output state type. Defaults to
2661
- * `unknown`; inferred to the subagent's `MergedAgentState` for
2662
- * `CompiledSubAgent` via {@link SubagentRunStreamUnion}.
2663
- */
2664
- interface SubagentRunStream<TOutput = unknown, TTools extends readonly (ClientTool | ServerTool)[] = readonly (ClientTool | ServerTool)[]> {
2665
- readonly name: string;
2666
- readonly taskInput: Promise<string>;
2667
- readonly output: Promise<TOutput>;
2668
- readonly messages: AsyncIterable<ChatModelStream>;
2669
- readonly toolCalls: AsyncIterable<ToolCallStreamUnion<TTools>>;
2670
- readonly subagents: AsyncIterable<SubagentRunStream>;
2671
- }
2672
- /**
2673
- * Extract the output state type from a subagent spec.
2674
- * For `CompiledSubAgent<ReactAgent<Types>>`, resolves to the agent's
2675
- * invoke return type. Falls back to `unknown` for `SubAgent` and
2676
- * `AsyncSubAgent`.
2677
- */
2678
- type SubagentOutputOf<T extends AnySubAgent> = T extends CompiledSubAgent<infer R> ? R extends ReactAgent<infer Types> ? Awaited<ReturnType<ReactAgent<Types>["invoke"]>> : unknown : unknown;
2679
- /**
2680
- * Extract the tools tuple from a subagent spec.
2681
- * For `CompiledSubAgent<ReactAgent<Types>>`, resolves to `Types["Tools"]`.
2682
- * Falls back to the default `(ClientTool | ServerTool)[]` for `SubAgent`
2683
- * and `AsyncSubAgent`.
2684
- */
2685
- type SubagentToolsOf<T extends AnySubAgent> = T extends CompiledSubAgent<infer R> ? R extends ReactAgent<infer Types> ? Types["Tools"] : readonly (ClientTool | ServerTool)[] : readonly (ClientTool | ServerTool)[];
2686
- /**
2687
- * A typed `SubagentRunStream` variant for a single subagent spec.
2688
- * Narrows `.name` to the literal string type, `.output` to the
2689
- * inferred state type, and `.toolCalls` to the subagent's tools
2690
- * when available.
2691
- */
2692
- type NamedSubagentRunStream<T extends AnySubAgent> = T extends {
2693
- name: infer N extends string;
2694
- } ? SubagentRunStream<SubagentOutputOf<T>, SubagentToolsOf<T>> & {
2695
- readonly name: N;
2696
- } : SubagentRunStream;
2697
- /**
2698
- * Discriminated union of {@link SubagentRunStream} variants, one per
2699
- * subagent in `TSubagents`. Enables TypeScript to narrow `.output`
2700
- * when the consumer checks `sub.name === "someSubagentName"`.
2701
- */
2702
- type SubagentRunStreamUnion<TSubagents extends readonly AnySubAgent[]> = { [K in keyof TSubagents]: NamedSubagentRunStream<TSubagents[K]> }[number];
2703
- /**
2704
- * An {@link AgentRunStream} with native deep-agent projections assigned
2705
- * directly on the instance by `createGraphRunStream` (via `__native`
2706
- * transformers).
2707
- *
2708
- * This is a pure type overlay — no runtime class exists. The
2709
- * `subagents` property is populated at runtime by the
2710
- * `createSubagentTransformer` registered at compile time.
2711
- */
2712
- 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> & {
2713
- /** Subagent invocation streams from the native SubagentTransformer. */subagents: AsyncIterable<SubagentRunStreamUnion<TSubagents>>;
2714
- };
2715
- interface SubagentProjection {
2716
- subagents: AsyncIterable<SubagentRunStream>;
2717
- }
2718
- /**
2719
- * Native transformer that correlates `task` tool calls into
2720
- * {@link SubagentRunStream} objects and routes child-namespace
2721
- * `tools` and `messages` events into per-subagent channels.
2722
- *
2723
- * Marked `__native: true` — the `subagents` projection key lands
2724
- * directly on the `GraphRunStream` instance as `run.subagents`.
2725
- */
2726
- declare function createSubagentTransformer(path: Namespace): () => NativeStreamTransformer<SubagentProjection>;
2727
- //#endregion
2728
- //#region src/types.d.ts
2729
- type AnyAnnotationRoot = AnnotationRoot<any>;
2730
- /**
2731
- * Literal union of all built-in deep agent tool names.
2732
- * These are always present on the agent regardless of user-provided tools.
2733
- */
2734
- type DeepAgentBuiltinToolName = (typeof FILESYSTEM_TOOL_NAMES)[number] | (typeof ASYNC_TASK_TOOL_NAMES)[number] | "task" | "write_todos";
2735
- /**
2736
- * A placeholder StructuredTool type with a literal `name` for each
2737
- * built-in tool. Used to thread built-in tool names into the
2738
- * `ToolCallStreamUnion` so they appear in `run.toolCalls` alongside
2739
- * user-provided tools.
2740
- */
2741
- type BuiltinToolPlaceholder<N extends string> = {
2742
- name: N;
2743
- } & StructuredTool$1;
2744
- /**
2745
- * Tuple of placeholder tool types for all built-in deep agent tools.
2746
- * Combined with `TTypes["Tools"]` in the `DeepAgentRunStream` return type.
2747
- */
2748
- type DeepAgentBuiltinToolsTuple = { [K in DeepAgentBuiltinToolName]: BuiltinToolPlaceholder<K> }[DeepAgentBuiltinToolName][];
2749
- 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>;
2750
- /** Any subagent specification — sync, compiled, or async. */
2751
- type AnySubAgent = SubAgent | CompiledSubAgent | AsyncSubAgent;
2752
- interface TypedToolStrategy<T = unknown> extends Array<ToolStrategy<any>> {
2753
- _schemaType?: T;
2754
- }
2755
- /**
2756
- * Helper type to extract middleware from a SubAgent definition
2757
- * Handles both mutable and readonly middleware arrays
2758
- */
2759
- type ExtractSubAgentMiddleware<T> = T extends {
2760
- middleware?: infer M;
2761
- } ? M extends readonly AgentMiddleware[] ? M : M extends AgentMiddleware[] ? M : readonly [] : readonly [];
2762
- /**
2763
- * Helper type to flatten and merge middleware from all subagents
2764
- */
2765
- 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 [];
2766
- /**
2767
- * Helper type to merge states from subagent middleware
2768
- */
2769
- type InferSubAgentMiddlewareStates<T extends readonly AnySubAgent[]> = InferMiddlewareStates<FlattenSubAgentMiddleware<T>>;
2770
- /**
2771
- * Combined state type including custom middleware and subagent middleware states
2772
- */
2773
- type MergedDeepAgentState<TMiddleware extends readonly AgentMiddleware[], TSubagents extends readonly AnySubAgent[]> = InferMiddlewareStates<TMiddleware> & InferSubAgentMiddlewareStates<TSubagents>;
2774
- /**
2775
- * Union of all response format types accepted by `createDeepAgent`.
2776
- *
2777
- * Matches the formats supported by LangChain's `createAgent`:
2778
- * - `ToolStrategy<T>` — from `ToolStrategy.fromSchema(schema)`
2779
- * - `ProviderStrategy<T>` — from `providerStrategy(schema)`
2780
- * - `TypedToolStrategy<T>` — from `toolStrategy(schema)`
2781
- * - `ResponseFormat` — the base union of the above single-strategy types
2782
- */
2783
- type SupportedResponseFormat = ResponseFormat | TypedToolStrategy<any>;
2784
- /**
2785
- * Utility type to extract the parsed response type from a ResponseFormat strategy.
2786
- *
2787
- * Maps `ToolStrategy<T>`, `ProviderStrategy<T>`, and `TypedToolStrategy<T>` to `T`
2788
- * (the parsed output type), so that `structuredResponse` is correctly typed as the
2789
- * schema's inferred type rather than the strategy wrapper.
2790
- *
2791
- * When no `responseFormat` is provided (i.e. `T` defaults to the full
2792
- * `SupportedResponseFormat` union), this resolves to `ResponseFormatUndefined` so
2793
- * that `structuredResponse` is excluded from the agent's output state.
2794
- *
2795
- * @example
2796
- * ```typescript
2797
- * type T1 = InferStructuredResponse<ToolStrategy<{ city: string }>>; // { city: string }
2798
- * type T2 = InferStructuredResponse<ProviderStrategy<{ answer: string }>>; // { answer: string }
2799
- * type T3 = InferStructuredResponse<TypedToolStrategy<{ city: string }>>; // { city: string }
2800
- * type T4 = InferStructuredResponse<SupportedResponseFormat>; // ResponseFormatUndefined (default/unset)
2801
- * ```
2802
- */
2803
- 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;
2804
- /**
2805
- * Type bag that extends AgentTypeConfig with subagent type information.
2806
- *
2807
- * This interface bundles all the generic type parameters used throughout the deep agent system
2808
- * including subagent types for type-safe streaming and delegation.
2809
- *
2810
- * @typeParam TResponse - The structured response type when using `responseFormat`.
2811
- * @typeParam TState - The custom state schema type.
2812
- * @typeParam TContext - The context schema type.
2813
- * @typeParam TMiddleware - The middleware array type.
2814
- * @typeParam TTools - The combined tools type.
2815
- * @typeParam TSubagents - The subagents array type for type-safe streaming.
2816
- *
2817
- * @example
2818
- * ```typescript
2819
- * const agent = createDeepAgent({
2820
- * middleware: [ResearchMiddleware],
2821
- * subagents: [
2822
- * { name: "researcher", description: "...", middleware: [CounterMiddleware] }
2823
- * ] as const,
2824
- * });
2825
- *
2826
- * // Type inference for streaming
2827
- * type Types = InferDeepAgentType<typeof agent, "Subagents">;
2828
- * ```
2829
- */
2830
- interface DeepAgentTypeConfig<TResponse extends Record<string, any> | ResponseFormatUndefined = Record<string, any> | ResponseFormatUndefined, TState extends AnyAnnotationRoot | InteropZodObject | undefined = AnyAnnotationRoot | InteropZodObject | 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> {
2831
- /** The subagents array type for type-safe streaming */
2832
- Subagents: TSubagents;
2833
- }
2834
- /**
2835
- * Default type configuration for deep agents.
2836
- * Used when no explicit type parameters are provided.
2837
- */
2838
- interface DefaultDeepAgentTypeConfig extends DeepAgentTypeConfig {
2839
- Response: Record<string, any>;
2840
- State: undefined;
2841
- Context: AnyAnnotationRoot;
2842
- Middleware: readonly AgentMiddleware[];
2843
- Tools: readonly (ClientTool | ServerTool)[];
2844
- Subagents: readonly AnySubAgent[];
2845
- StreamTransformers: readonly [];
2846
- }
2847
- /**
2848
- * DeepAgent extends ReactAgent with additional subagent type information.
2849
- *
2850
- * This type wraps ReactAgent but includes the DeepAgentTypeConfig which
2851
- * contains subagent types for type-safe streaming and delegation.
2852
- *
2853
- * @typeParam TTypes - The DeepAgentTypeConfig containing all type parameters
2854
- *
2855
- * @example
2856
- * ```typescript
2857
- * const agent: DeepAgent<DeepAgentTypeConfig<...>> = createDeepAgent({ ... });
2858
- *
2859
- * // Access subagent types for streaming
2860
- * type Subagents = InferDeepAgentSubagents<typeof agent>;
2861
- * ```
2862
- */
2863
- interface DeepAgent<TTypes extends DeepAgentTypeConfig = DeepAgentTypeConfig> extends ReactAgent<TTypes> {
2864
- /** Type brand for DeepAgent type inference */
2865
- readonly "~deepAgentTypes": TTypes;
2866
- /**
2867
- * Executes the agent with the v3 streaming interface, returning an
2868
- * {@link DeepAgentRunStream} that provides ergonomic, typed projections for
2869
- * messages, tool calls, subagents, and middleware events.
2870
- *
2871
- * Pass `version: "v3"` to opt into this projection-oriented stream. Omitting
2872
- * `version` preserves the legacy internal LangGraph event-stream behavior
2873
- * for compatibility with LangGraph Platform integrations.
2874
- *
2875
- * This v3 stream is experimental and its API may change in future releases.
2876
- * It will become the default in a future major release.
2877
- *
2878
- * @param state - The initial state for the agent execution. Can be:
2879
- * - An object containing `messages` array and any middleware-specific state properties
2880
- * - A Command object for more advanced control flow
2881
- *
2882
- * @param config - Runtime configuration including:
2883
- * @param config.version - Must be `"v3"` to use the {@link DeepAgentRunStream}
2884
- * interface. The default legacy event stream is maintained for internal
2885
- * integrations and should not be used for new user-facing agent streaming.
2886
- * @param config.context - The context for the agent execution.
2887
- * @param config.configurable - LangGraph configuration options like `thread_id`, `run_id`, etc.
2888
- * @param config.store - The store for the agent execution for persisting state.
2889
- * @param config.signal - An optional AbortSignal for the agent execution.
2890
- * @param config.recursionLimit - The recursion limit for the agent execution.
2891
- *
2892
- * @returns A Promise that resolves to an {@link DeepAgentRunStream} providing:
2893
- * - `run.messages` — all AI message lifecycles with streaming `.text` and `.reasoning`
2894
- * - `run.toolCalls` — individual tool call streams with `.input`, `.output`, `.status`
2895
- * - `run.subagents` — subagent delegation streams
2896
- * - `run.middleware` — middleware lifecycle events (before/after agent/model)
2897
- * - `run.values` — state snapshots (async iterable + promise-like)
2898
- * - `run.output` — final agent state when the run completes
2899
- * - `run.subgraphs` — child subgraph run streams
2900
- * - `run.extensions` — merged projections from user-supplied transformers
2901
- *
2902
- * @example
2903
- * ```typescript
2904
- * const run = await agent.streamEvents(
2905
- * {
2906
- * messages: [{ role: "user", content: "What's the weather in Paris?" }],
2907
- * },
2908
- * { version: "v3" }
2909
- * );
2910
- *
2911
- * // Stream all messages
2912
- * for await (const msg of run.messages) {
2913
- * for await (const token of msg.text) {
2914
- * process.stdout.write(token);
2915
- * }
2916
- * }
2917
- *
2918
- * // Observe tool calls
2919
- * for await (const call of run.toolCalls) {
2920
- * console.log(`Tool: ${call.name}`, call.input);
2921
- * console.log(`Result:`, await call.output);
2922
- * }
2923
- *
2924
- * // Observe subagent delegations
2925
- * for await (const subagent of run.subagents) {
2926
- * console.log(`Subagent: ${subagent.name}`);
2927
- *
2928
- * for await (const msg of subagent.messages) {
2929
- * for await (const token of msg.text) {
2930
- * process.stdout.write(token);
2931
- * }
2932
- * }
2933
- * }
2934
- *
2935
- * // Get final state
2936
- * const state = await run.output;
2937
- * ```
2938
- */
2939
- streamEvents: ((state: Parameters<ReactAgent<TTypes>["invoke"]>[0], config: NonNullable<Parameters<ReactAgent<TTypes>["invoke"]>[1]> & {
2940
- version: "v3";
2941
- }) => Promise<DeepAgentRunStream<Awaited<ReturnType<ReactAgent<TTypes>["invoke"]>>, readonly [...TTypes["Tools"], ...DeepAgentBuiltinToolsTuple], TTypes["Subagents"], InferDeepAgentStreamExtensions<TTypes["StreamTransformers"]>>>) & ReactAgent<TTypes>["streamEvents"];
2942
- }
2943
- /**
2944
- * Helper type to resolve a DeepAgentTypeConfig from either:
2945
- * - A DeepAgentTypeConfig directly
2946
- * - A DeepAgent instance (using `typeof agent`)
2947
- *
2948
- * @example
2949
- * ```typescript
2950
- * const agent = createDeepAgent({ ... });
2951
- * type Types = ResolveDeepAgentTypeConfig<typeof agent>;
2952
- * ```
2953
- */
2954
- type ResolveDeepAgentTypeConfig<T> = T extends {
2955
- "~deepAgentTypes": infer Types;
2956
- } ? Types extends DeepAgentTypeConfig ? Types : never : T extends DeepAgentTypeConfig ? T : never;
2957
- /**
2958
- * Helper type to extract any property from a DeepAgentTypeConfig or DeepAgent.
2959
- *
2960
- * @typeParam T - The DeepAgentTypeConfig or DeepAgent to extract from
2961
- * @typeParam K - The property key to extract
2962
- *
2963
- * @example
2964
- * ```typescript
2965
- * const agent = createDeepAgent({ subagents: [...] });
2966
- * type Subagents = InferDeepAgentType<typeof agent, "Subagents">;
2967
- * ```
2968
- */
2969
- type InferDeepAgentType<T, K extends keyof DeepAgentTypeConfig> = ResolveDeepAgentTypeConfig<T>[K];
2970
- /**
2971
- * Shorthand helper to extract the Subagents type from a DeepAgentTypeConfig or DeepAgent.
2972
- *
2973
- * @example
2974
- * ```typescript
2975
- * const agent = createDeepAgent({ subagents: [subagent1, subagent2] });
2976
- * type Subagents = InferDeepAgentSubagents<typeof agent>;
2977
- * ```
2978
- */
2979
- type InferDeepAgentSubagents<T> = InferDeepAgentType<T, "Subagents">;
2980
- /**
2981
- * Helper type to extract a subagent by name from a DeepAgent.
2982
- *
2983
- * @typeParam T - The DeepAgent to extract from
2984
- * @typeParam TName - The name of the subagent to extract
2985
- *
2986
- * @example
2987
- * ```typescript
2988
- * const agent = createDeepAgent({
2989
- * subagents: [
2990
- * { name: "researcher", description: "...", middleware: [ResearchMiddleware] }
2991
- * ] as const,
2992
- * });
2993
- *
2994
- * type ResearcherAgent = InferSubagentByName<typeof agent, "researcher">;
2995
- * ```
2996
- */
2997
- type InferSubagentByName<T, TName extends string> = InferDeepAgentSubagents<T> extends readonly (infer SA)[] ? SA extends {
2998
- name: TName;
2999
- } ? SA : never : never;
3000
- /**
3001
- * Helper type to extract the ReactAgent type from a subagent definition.
3002
- * This is useful for type-safe streaming of subagent events.
3003
- *
3004
- * @typeParam TSubagent - The subagent definition
3005
- *
3006
- * @example
3007
- * ```typescript
3008
- * type SubagentMiddleware = ExtractSubAgentMiddleware<typeof subagent>;
3009
- * type SubagentState = InferMiddlewareStates<SubagentMiddleware>;
3010
- * ```
3011
- */
3012
- type InferSubagentReactAgentType<TSubagent extends SubAgent | CompiledSubAgent> = TSubagent extends CompiledSubAgent ? TSubagent["runnable"] : TSubagent extends SubAgent ? ReactAgent<AgentTypeConfig<ResponseFormatUndefined, undefined, AnyAnnotationRoot, ExtractSubAgentMiddleware<TSubagent>, readonly []>> : never;
3013
- /**
3014
- * Configuration parameters for creating a Deep Agent
3015
- * Matches Python's create_deep_agent parameters
3016
- *
3017
- * @typeParam TResponse - The structured response type when using responseFormat
3018
- * @typeParam ContextSchema - The context schema type
3019
- * @typeParam TMiddleware - The middleware array type for proper type inference
3020
- * @typeParam TSubagents - The subagents array type for extracting subagent middleware states
3021
- * @typeParam TTools - The tools array type
3022
- * @typeParam TStreamTransformers - Custom stream transformer factories
3023
- */
3024
- 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 []> {
3025
- /** The model to use (model name string or LanguageModelLike instance). Defaults to claude-sonnet-4-5-20250929 */
3026
- model?: BaseLanguageModel | string;
3027
- /** Tools the agent should have access to */
3028
- tools?: TTools | StructuredTool$1[];
3029
- /** Custom system prompt for the agent. This will be combined with the base agent prompt */
3030
- systemPrompt?: string | SystemMessage;
3031
- /** Custom middleware to apply after standard middleware */
3032
- middleware?: TMiddleware;
3033
- /**
3034
- * List of subagent specifications for task delegation.
3035
- *
3036
- * Supports sync SubAgents, CompiledSubAgents, and AsyncSubAgents in the same array.
3037
- * AsyncSubAgents (identified by their `graphId` field) are automatically separated
3038
- * at runtime and wired to the async SubAgent middleware.
3039
- */
3040
- subagents?: TSubagents;
3041
- /** Structured output response format for the agent (Zod schema or other format) */
3042
- responseFormat?: TResponse;
3043
- /** Optional schema for context (not persisted between invocations) */
3044
- contextSchema?: ContextSchema;
3045
- /** Optional checkpointer for persisting agent state between runs */
3046
- checkpointer?: BaseCheckpointSaver | boolean;
3047
- /** Optional store for persisting longterm memories */
3048
- store?: BaseStore;
3049
- /**
3050
- * Optional backend for filesystem operations.
3051
- * Can be either a backend instance or a factory function that creates one.
3052
- * The factory receives a config object with state and store.
3053
- */
3054
- backend?: AnyBackendProtocol | ((config: {
3055
- state: unknown;
3056
- store?: BaseStore;
3057
- }) => AnyBackendProtocol);
3058
- /** Optional interrupt configuration mapping tool names to interrupt configs */
3059
- interruptOn?: Record<string, boolean | InterruptOnConfig>;
3060
- /** The name of the agent */
3061
- name?: string;
3062
- /**
3063
- * Optional list of memory file paths (AGENTS.md files) to load
3064
- * (e.g., ["~/.deepagents/AGENTS.md", "./.deepagents/AGENTS.md"]).
3065
- * Display names are automatically derived from paths.
3066
- * Memory is loaded at agent startup and added into the system prompt.
3067
- */
3068
- memory?: string[];
3069
- /**
3070
- * Optional list of skill source paths (e.g., `["/skills/user/", "/skills/project/"]`).
3071
- *
3072
- * Paths use POSIX conventions (forward slashes) and are relative to the backend's root.
3073
- * Later sources override earlier ones for skills with the same name (last one wins).
3074
- *
3075
- * @example
3076
- * ```typescript
3077
- * // With FilesystemBackend - skills loaded from disk
3078
- * const agent = await createDeepAgent({
3079
- * backend: new FilesystemBackend({ rootDir: "/home/user/.deepagents" }),
3080
- * skills: ["/skills/"],
3081
- * });
3082
- *
3083
- * // With StateBackend - skills provided in state
3084
- * const agent = await createDeepAgent({
3085
- * skills: ["/skills/"],
3086
- * });
3087
- * const result = await agent.invoke({
3088
- * messages: [...],
3089
- * files: {
3090
- * "/skills/my-skill/SKILL.md": {
3091
- * content: ["---", "name: my-skill", "description: ...", "---", "# My Skill"],
3092
- * created_at: new Date().toISOString(),
3093
- * modified_at: new Date().toISOString(),
3094
- * },
3095
- * },
3096
- * });
3097
- * ```
3098
- */
3099
- skills?: string[];
3100
- /**
3101
- * Filesystem permission rules for this agent.
3102
- *
3103
- * Rules are evaluated in declaration order; first match wins; permissive
3104
- * default. Applied to `ls`, `read_file`, `write_file`, `edit_file`, `glob`,
3105
- * and `grep`. Subagents inherit these rules unless they specify their own
3106
- * `permissions` field.
3107
- *
3108
- * @example
3109
- * ```ts
3110
- * createDeepAgent({
3111
- * permissions: [
3112
- * { operations: ["read"], paths: ["/workspace/**"] },
3113
- * { operations: ["read"], paths: ["/**"], mode: "deny" },
3114
- * ],
3115
- * });
3116
- * ```
3117
- */
3118
- permissions?: FilesystemPermission[];
3119
- /**
3120
- * Optional {@link StreamTransformer} factories to register with the underlying agent.
3121
- *
3122
- * Deepagents always registers its built-in subagent transformer; custom
3123
- * transformers are appended after it and are exposed on `run.extensions`
3124
- * when using `streamEvents(..., { version: "v3" })`.
3125
- */
3126
- streamTransformers?: TStreamTransformers;
3127
- }
3128
- //#endregion
3129
- //#region src/agent.d.ts
3130
- /**
3131
- * Create a Deep Agent.
3132
- *
3133
- * This is the main entry point for building a production-style agent with
3134
- * deepagents. It gives you a strong default runtime (filesystem, tasks,
3135
- * subagents, summarization) and lets you opt into skills, memory,
3136
- * human-in-the-loop interrupts, async subagents, and custom middleware.
3137
- *
3138
- * The runtime is intentionally opinionated: defaults work out of the box, and
3139
- * when you customize behavior, the middleware ordering stays deterministic.
3140
- *
3141
- * @param params Configuration parameters for the agent
3142
- * @returns Deep Agent instance with inferred state/response types
3143
- *
3144
- * @example
3145
- * ```typescript
3146
- * // Middleware with custom state
3147
- * const ResearchMiddleware = createMiddleware({
3148
- * name: "ResearchMiddleware",
3149
- * stateSchema: z.object({ research: z.string().default("") }),
3150
- * });
3151
- *
3152
- * const agent = createDeepAgent({
3153
- * middleware: [ResearchMiddleware],
3154
- * });
3155
- *
3156
- * const result = await agent.invoke({ messages: [...] });
3157
- * // result.research is properly typed as string
3158
- * ```
3159
- */
3160
- 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 []>(params?: CreateDeepAgentParams<TResponse, ContextSchema, TMiddleware, TSubagents, TTools, TStreamTransformers>): DeepAgent<DeepAgentTypeConfig<InferStructuredResponse<TResponse>, undefined, ContextSchema, readonly [AgentMiddleware<_$zod_v30.ZodObject<{
3161
- todos: _$zod_v30.ZodDefault<_$zod_v30.ZodArray<_$zod_v30.ZodObject<{
3162
- content: _$zod_v30.ZodString;
3163
- status: _$zod_v30.ZodEnum<["pending", "in_progress", "completed"]>;
3164
- }, "strip", _$zod_v30.ZodTypeAny, {
3165
- content: string;
3166
- status: "completed" | "in_progress" | "pending";
3167
- }, {
3168
- content: string;
3169
- status: "completed" | "in_progress" | "pending";
3170
- }>, "many">>;
3171
- }, "strip", _$zod_v30.ZodTypeAny, {
3172
- todos: {
3173
- content: string;
3174
- status: "completed" | "in_progress" | "pending";
3175
- }[];
3176
- }, {
3177
- todos?: {
3178
- content: string;
3179
- status: "completed" | "in_progress" | "pending";
3180
- }[] | undefined;
3181
- }>, undefined, unknown, readonly [_langchain.DynamicStructuredTool<_$zod_v30.ZodObject<{
3182
- todos: _$zod_v30.ZodArray<_$zod_v30.ZodObject<{
3183
- content: _$zod_v30.ZodString;
3184
- status: _$zod_v30.ZodEnum<["pending", "in_progress", "completed"]>;
3185
- }, "strip", _$zod_v30.ZodTypeAny, {
3186
- content: string;
3187
- status: "completed" | "in_progress" | "pending";
3188
- }, {
3189
- content: string;
3190
- status: "completed" | "in_progress" | "pending";
3191
- }>, "many">;
3192
- }, "strip", _$zod_v30.ZodTypeAny, {
3193
- todos: {
3194
- content: string;
3195
- status: "completed" | "in_progress" | "pending";
3196
- }[];
3197
- }, {
3198
- todos: {
3199
- content: string;
3200
- status: "completed" | "in_progress" | "pending";
3201
- }[];
3202
- }>, {
3203
- todos: {
3204
- content: string;
3205
- status: "completed" | "in_progress" | "pending";
3206
- }[];
3207
- }, {
3208
- todos: {
3209
- content: string;
3210
- status: "completed" | "in_progress" | "pending";
3211
- }[];
3212
- }, _langgraph.Command<unknown, {
3213
- todos: {
3214
- content: string;
3215
- status: "completed" | "in_progress" | "pending";
3216
- }[];
3217
- messages: _messages.ToolMessage<_messages.MessageStructure<_messages.MessageToolSet>>[];
3218
- }, string>, unknown, "write_todos">]>, AgentMiddleware<_langgraph.StateSchema<{
3219
- files: _langgraph.ReducedValue<FilesRecord | undefined, FilesRecordUpdate | undefined>;
3220
- }>, undefined, unknown, (_langchain.DynamicStructuredTool<z$2.ZodObject<{
3221
- path: z$2.ZodDefault<z$2.ZodOptional<z$2.ZodString>>;
3222
- }, _$zod_v4_core0.$strip>, {
3223
- path: string;
3224
- }, {
3225
- path?: string | undefined;
3226
- }, string, unknown, "ls"> | _langchain.DynamicStructuredTool<z$2.ZodObject<{
3227
- file_path: z$2.ZodString;
3228
- offset: z$2.ZodDefault<z$2.ZodOptional<z$2.ZodCoercedNumber<unknown>>>;
3229
- limit: z$2.ZodDefault<z$2.ZodOptional<z$2.ZodCoercedNumber<unknown>>>;
3230
- }, _$zod_v4_core0.$strip>, {
3231
- file_path: string;
3232
- offset: number;
3233
- limit: number;
3234
- }, {
3235
- file_path: string;
3236
- offset?: unknown;
3237
- limit?: unknown;
3238
- }, {
3239
- type: string;
3240
- text: string;
3241
- }[] | {
3242
- type: string;
3243
- mimeType: string;
3244
- data: string;
3245
- }[], unknown, "read_file"> | _langchain.DynamicStructuredTool<z$2.ZodObject<{
3246
- file_path: z$2.ZodString;
3247
- content: z$2.ZodDefault<z$2.ZodString>;
3248
- }, _$zod_v4_core0.$strip>, {
3249
- file_path: string;
3250
- content: string;
3251
- }, {
3252
- file_path: string;
3253
- content?: string | undefined;
3254
- }, string | _messages.ToolMessage<_messages.MessageStructure<_messages.MessageToolSet>> | _langgraph.Command<unknown, {
3255
- files: Record<string, FileData>;
3256
- messages: _messages.ToolMessage<_messages.MessageStructure<_messages.MessageToolSet>>[];
3257
- }, string>, unknown, "write_file"> | _langchain.DynamicStructuredTool<z$2.ZodObject<{
3258
- file_path: z$2.ZodString;
3259
- old_string: z$2.ZodString;
3260
- new_string: z$2.ZodString;
3261
- replace_all: z$2.ZodDefault<z$2.ZodOptional<z$2.ZodBoolean>>;
3262
- }, _$zod_v4_core0.$strip>, {
3263
- file_path: string;
3264
- old_string: string;
3265
- new_string: string;
3266
- replace_all: boolean;
3267
- }, {
3268
- file_path: string;
3269
- old_string: string;
3270
- new_string: string;
3271
- replace_all?: boolean | undefined;
3272
- }, string | _messages.ToolMessage<_messages.MessageStructure<_messages.MessageToolSet>> | _langgraph.Command<unknown, {
3273
- files: Record<string, FileData>;
3274
- messages: _messages.ToolMessage<_messages.MessageStructure<_messages.MessageToolSet>>[];
3275
- }, string>, unknown, "edit_file"> | _langchain.DynamicStructuredTool<z$2.ZodObject<{
3276
- pattern: z$2.ZodString;
3277
- path: z$2.ZodDefault<z$2.ZodOptional<z$2.ZodString>>;
3278
- }, _$zod_v4_core0.$strip>, {
3279
- pattern: string;
3280
- path: string;
3281
- }, {
3282
- pattern: string;
3283
- path?: string | undefined;
3284
- }, string, unknown, "glob"> | _langchain.DynamicStructuredTool<z$2.ZodObject<{
3285
- pattern: z$2.ZodString;
3286
- path: z$2.ZodDefault<z$2.ZodOptional<z$2.ZodString>>;
3287
- glob: z$2.ZodDefault<z$2.ZodNullable<z$2.ZodOptional<z$2.ZodString>>>;
3288
- }, _$zod_v4_core0.$strip>, {
3289
- pattern: string;
3290
- path: string;
3291
- glob: string | null;
3292
- }, {
3293
- pattern: string;
3294
- path?: string | undefined;
3295
- glob?: string | null | undefined;
3296
- }, string, unknown, "grep"> | _langchain.DynamicStructuredTool<z$2.ZodObject<{
3297
- command: z$2.ZodString;
3298
- }, _$zod_v4_core0.$strip>, {
3299
- command: string;
3300
- }, {
3301
- command: string;
3302
- }, string, unknown, "execute">)[]>, AgentMiddleware<undefined, undefined, unknown, readonly [_langchain.DynamicStructuredTool<z$2.ZodObject<{
3303
- description: z$2.ZodString;
3304
- subagent_type: z$2.ZodString;
3305
- }, _$zod_v4_core0.$strip>, {
3306
- description: string;
3307
- subagent_type: string;
3308
- }, {
3309
- description: string;
3310
- subagent_type: string;
3311
- }, string | _langgraph.Command<unknown, Record<string, unknown>, string>, unknown, "task">]>, AgentMiddleware<z$2.ZodObject<{
3312
- _summarizationSessionId: z$2.ZodOptional<z$2.ZodString>;
3313
- _summarizationEvent: z$2.ZodOptional<z$2.ZodObject<{
3314
- cutoffIndex: z$2.ZodNumber;
3315
- summaryMessage: z$2.ZodCustom<_messages.HumanMessage<_messages.MessageStructure<_messages.MessageToolSet>>, _messages.HumanMessage<_messages.MessageStructure<_messages.MessageToolSet>>>;
3316
- filePath: z$2.ZodNullable<z$2.ZodString>;
3317
- }, _$zod_v4_core0.$strip>>;
3318
- }, _$zod_v4_core0.$strip>, undefined, unknown, readonly (ClientTool | ServerTool)[]>, AgentMiddleware<undefined, undefined, unknown, readonly (ClientTool | ServerTool)[]>, ...TMiddleware, ...FlattenSubAgentMiddleware<TSubagents>], TTools, TSubagents, TStreamTransformers>>;
3319
- //#endregion
3320
- //#region src/errors.d.ts
3321
- /**
3322
- * Error codes for {@link ConfigurationError}.
3323
- *
3324
- * Each code represents a distinct misconfiguration that can be detected at
3325
- * agent-construction time. Add new codes here as new validations are added.
3326
- */
3327
- type ConfigurationErrorCode = "TOOL_NAME_COLLISION";
3328
- declare const CONFIGURATION_ERROR_SYMBOL: unique symbol;
3329
- /**
3330
- * Thrown when `createDeepAgent` receives invalid configuration.
3331
- *
3332
- * Follows the same pattern as {@link SandboxError}: a human-readable
3333
- * `message`, a structured `code` for programmatic handling, and a
3334
- * static `isInstance` guard that works across realms.
3335
- *
3336
- * @example
3337
- * ```typescript
3338
- * try {
3339
- * createDeepAgent({ tools: [myTool] });
3340
- * } catch (error) {
3341
- * if (ConfigurationError.isInstance(error)) {
3342
- * switch (error.code) {
3343
- * case "TOOL_NAME_COLLISION":
3344
- * console.error("Rename your tool:", error.message);
3345
- * break;
3346
- * }
3347
- * }
3348
- * }
3349
- * ```
3350
- */
3351
- declare class ConfigurationError extends Error {
3352
- readonly code: ConfigurationErrorCode;
3353
- readonly cause?: Error | undefined;
3354
- [CONFIGURATION_ERROR_SYMBOL]: true;
3355
- readonly name: string;
3356
- constructor(message: string, code: ConfigurationErrorCode, cause?: Error | undefined);
3357
- static isInstance(error: unknown): error is ConfigurationError;
3358
- }
3359
- //#endregion
3360
- //#region src/config.d.ts
3361
- /**
3362
- * Configuration and settings for deepagents.
3363
- *
3364
- * Provides project detection, path management, and environment configuration
3365
- * for skills and agent memory middleware.
3366
- */
3367
- /**
3368
- * Options for creating a Settings instance.
3369
- */
3370
- interface SettingsOptions {
3371
- /** Starting directory for project detection (defaults to cwd) */
3372
- startPath?: string;
3373
- }
3374
- /**
3375
- * Settings interface for project detection and path management.
3376
- *
3377
- * Provides access to:
3378
- * - Project root detection (via .git directory)
3379
- * - User-level deepagents directory (~/.deepagents)
3380
- * - Agent-specific directories and files
3381
- * - Skills directories (user and project level)
3382
- */
3383
- interface Settings {
3384
- /** Detected project root directory, or null if not in a git project */
3385
- readonly projectRoot: string | null;
3386
- /** Base user-level .deepagents directory (~/.deepagents) */
3387
- readonly userDeepagentsDir: string;
3388
- /** Check if currently in a git project */
3389
- readonly hasProject: boolean;
3390
- /**
3391
- * Get the agent directory path.
3392
- * @param agentName - Name of the agent
3393
- * @returns Path to ~/.deepagents/{agentName}
3394
- * @throws Error if agent name is invalid
3395
- */
3396
- getAgentDir(agentName: string): string;
3397
- /**
3398
- * Ensure agent directory exists and return path.
3399
- * @param agentName - Name of the agent
3400
- * @returns Path to ~/.deepagents/{agentName}
3401
- * @throws Error if agent name is invalid
3402
- */
3403
- ensureAgentDir(agentName: string): string;
3404
- /**
3405
- * Get user-level agent.md path for a specific agent.
3406
- * @param agentName - Name of the agent
3407
- * @returns Path to ~/.deepagents/{agentName}/agent.md
3408
- */
3409
- getUserAgentMdPath(agentName: string): string;
3410
- /**
3411
- * Get project-level agent.md path.
3412
- * @returns Path to {projectRoot}/.deepagents/agent.md, or null if not in a project
3413
- */
3414
- getProjectAgentMdPath(): string | null;
3415
- /**
3416
- * Get user-level skills directory path for a specific agent.
3417
- * @param agentName - Name of the agent
3418
- * @returns Path to ~/.deepagents/{agentName}/skills/
3419
- */
3420
- getUserSkillsDir(agentName: string): string;
3421
- /**
3422
- * Ensure user-level skills directory exists and return path.
3423
- * @param agentName - Name of the agent
3424
- * @returns Path to ~/.deepagents/{agentName}/skills/
3425
- */
3426
- ensureUserSkillsDir(agentName: string): string;
3427
- /**
3428
- * Get project-level skills directory path.
3429
- * @returns Path to {projectRoot}/.deepagents/skills/, or null if not in a project
3430
- */
3431
- getProjectSkillsDir(): string | null;
3432
- /**
3433
- * Ensure project-level skills directory exists and return path.
3434
- * @returns Path to {projectRoot}/.deepagents/skills/, or null if not in a project
3435
- */
3436
- ensureProjectSkillsDir(): string | null;
3437
- /**
3438
- * Ensure project .deepagents directory exists.
3439
- * @returns Path to {projectRoot}/.deepagents/, or null if not in a project
3440
- */
3441
- ensureProjectDeepagentsDir(): string | null;
3442
- }
3443
- /**
3444
- * Find the project root by looking for .git directory.
3445
- *
3446
- * Walks up the directory tree from startPath (or cwd) looking for a .git
3447
- * directory, which indicates the project root.
3448
- *
3449
- * @param startPath - Directory to start searching from. Defaults to current working directory.
3450
- * @returns Path to the project root if found, null otherwise.
3451
- */
3452
- declare function findProjectRoot(startPath?: string): string | null;
3453
- /**
3454
- * Create a Settings instance with detected environment.
3455
- *
3456
- * @param options - Configuration options
3457
- * @returns Settings instance with project detection and path management
3458
- */
3459
- declare function createSettings(options?: SettingsOptions): Settings;
3460
- //#endregion
3461
- //#region src/values.d.ts
3462
- /**
3463
- * Shared ReducedValue for file data state management.
3464
- *
3465
- * This provides a reusable pattern for managing file state with automatic
3466
- * merging of concurrent updates from parallel subagents. Files can be updated
3467
- * or deleted (using null values) and the reducer handles the merge logic.
3468
- *
3469
- * Similar to LangGraph's messagesValue, this encapsulates the common pattern
3470
- * of managing files in agent state so you don't have to manually configure
3471
- * the ReducedValue each time.
3472
- *
3473
- * @example
3474
- * ```typescript
3475
- * import { filesValue } from "@anthropic/deepagents";
3476
- * import { StateSchema } from "@langchain/langgraph";
3477
- *
3478
- * const MyStateSchema = new StateSchema({
3479
- * files: filesValue,
3480
- * // ... other state fields
3481
- * });
3482
- * ```
3483
- */
3484
- declare const filesValue: ReducedValue<FilesRecord | undefined, FilesRecordUpdate | undefined>;
3485
- //#endregion
3486
- //#region src/middleware/agent-memory.d.ts
3487
- /**
3488
- * Options for the agent memory middleware.
3489
- */
3490
- interface AgentMemoryMiddlewareOptions {
3491
- /** Settings instance with project detection and paths */
3492
- settings: Settings;
3493
- /** The agent identifier */
3494
- assistantId: string;
3495
- /** Optional custom template for injecting agent memory into system prompt */
3496
- systemPromptTemplate?: string;
3497
- }
3498
- /**
3499
- * Create middleware for loading agent-specific long-term memory.
3500
- *
3501
- * This middleware loads the agent's long-term memory from a file (agent.md)
3502
- * and injects it into the system prompt. The memory is loaded once at the
3503
- * start of the conversation and stored in state.
3504
- *
3505
- * @param options - Configuration options
3506
- * @returns AgentMiddleware for memory loading and injection
3507
- *
3508
- * @deprecated Use `createMemoryMiddleware` from `./memory.js` instead.
3509
- * This function uses direct filesystem access which limits portability.
3510
- */
3511
- declare function createAgentMemoryMiddleware(options: AgentMemoryMiddlewareOptions): AgentMiddleware<any, undefined, unknown, readonly (_$_langchain_core_tools0.ClientTool | _$_langchain_core_tools0.ServerTool)[]>;
3512
- //#endregion
3513
- //#region src/skills/loader.d.ts
3514
- /**
3515
- * Metadata for a skill per Agent Skills spec.
3516
- * @see https://agentskills.io/specification
3517
- */
3518
- interface SkillMetadata {
3519
- /** Name of the skill (max 64 chars, lowercase alphanumeric and hyphens) */
3520
- name: string;
3521
- /** Description of what the skill does (max 1024 chars) */
3522
- description: string;
3523
- /** Absolute path to the SKILL.md file */
3524
- path: string;
3525
- /** Source of the skill ('user' or 'project') */
3526
- source: "user" | "project";
3527
- /** Optional: License name or reference to bundled license file */
3528
- license?: string;
3529
- /** Optional: Environment requirements (max 500 chars) */
3530
- compatibility?: string;
3531
- /** Optional: Arbitrary key-value mapping for additional metadata */
3532
- metadata?: Record<string, string>;
3533
- /** Optional: Space-delimited list of pre-approved tools */
3534
- allowedTools?: string;
3535
- }
3536
- /**
3537
- * Options for listing skills.
3538
- */
3539
- interface ListSkillsOptions {
3540
- /** Path to user-level skills directory */
3541
- userSkillsDir?: string | null;
3542
- /** Path to project-level skills directory */
3543
- projectSkillsDir?: string | null;
3544
- }
3545
- /**
3546
- * Parse YAML frontmatter from a SKILL.md file per Agent Skills spec.
3547
- *
3548
- * @param skillMdPath - Path to the SKILL.md file
3549
- * @param source - Source of the skill ('user' or 'project')
3550
- * @returns SkillMetadata with all fields, or null if parsing fails
3551
- */
3552
- declare function parseSkillMetadata(skillMdPath: string, source: "user" | "project"): SkillMetadata | null;
3553
- /**
3554
- * List skills from user and/or project directories.
3555
- *
3556
- * When both directories are provided, project skills with the same name as
3557
- * user skills will override them.
3558
- *
3559
- * @param options - Options specifying which directories to search
3560
- * @returns Merged list of skill metadata from both sources, with project skills
3561
- * taking precedence over user skills when names conflict
3562
- */
3563
- declare function listSkills(options: ListSkillsOptions): SkillMetadata[];
3564
- //#endregion
3565
- export { type AgentMemoryMiddlewareOptions, type AnyBackendProtocol, type AnySubAgent, type AsyncSubAgent, type AsyncSubAgentMiddlewareOptions, type AsyncTask, type AsyncTaskStatus, type BackendFactory, type BackendProtocol, type BackendProtocolV1, type BackendProtocolV2, type BackendRuntime, BaseSandbox, type CompiledSubAgent, type CompletionCallbackOptions, CompositeBackend, ConfigurationError, type ConfigurationErrorCode, type CreateDeepAgentParams, DEFAULT_GENERAL_PURPOSE_DESCRIPTION, DEFAULT_SUBAGENT_PROMPT, type DeepAgent, type DeepAgentRunStream, type DeepAgentTypeConfig, type DefaultDeepAgentTypeConfig, type EditResult, type ExecuteResponse, type ExtractSubAgentMiddleware, type FileData, type FileDownloadResponse, type FileInfo, type FileOperationError, type FileUploadResponse, FilesystemBackend, type FilesystemMiddlewareOptions, type FilesystemOperation, type FilesystemPermission, type FlattenSubAgentMiddleware, GENERAL_PURPOSE_SUBAGENT, type GlobResult, type GrepMatch, type GrepResult, type InferDeepAgentSubagents, type InferDeepAgentType, type InferStructuredResponse, type InferSubAgentMiddlewareStates, type InferSubagentByName, type InferSubagentReactAgentType, type LangSmithCaptureSnapshotOptions, LangSmithSandbox, type LangSmithSandboxCreateOptions, type LangSmithSandboxOptions, type LangSmithSnapshot, type LangSmithStartSandboxOptions, type ListSkillsOptions, type SkillMetadata as LoaderSkillMetadata, LocalShellBackend, type LocalShellBackendOptions, type LsResult, MAX_SKILL_DESCRIPTION_LENGTH, MAX_SKILL_FILE_SIZE, MAX_SKILL_NAME_LENGTH, type MaybePromise, type MemoryMiddlewareOptions, type MergedDeepAgentState, type PermissionMode, type ReadRawResult, type ReadResult, type ResolveDeepAgentTypeConfig, type SandboxBackendProtocol, type SandboxBackendProtocolV1, type SandboxBackendProtocolV2, type SandboxDeleteOptions, SandboxError, type SandboxErrorCode, type SandboxGetOrCreateOptions, type SandboxInfo, type SandboxListOptions, type SandboxListResponse, type Settings, type SettingsOptions, type SkillMetadata$1 as SkillMetadata, type SkillsMiddlewareOptions, type StateAndStore, StateBackend, StoreBackend, type StoreBackendContext, type StoreBackendNamespaceFactory, type StoreBackendOptions, type SubAgent, type SubAgentMiddlewareOptions, type SubagentRunStream, type SupportedResponseFormat, TASK_SYSTEM_PROMPT, type WriteResult, adaptBackendProtocol, adaptSandboxProtocol, computeSummarizationDefaults, createAgentMemoryMiddleware, createAsyncSubAgentMiddleware, createCompletionCallbackMiddleware, createDeepAgent, createFilesystemMiddleware, createMemoryMiddleware, createPatchToolCallsMiddleware, createSettings, createSkillsMiddleware, createSubAgentMiddleware, createSubagentTransformer, createSummarizationMiddleware, filesValue, findProjectRoot, isAsyncSubAgent, isSandboxBackend, isSandboxProtocol, listSkills, parseSkillMetadata, resolveBackend };
3566
- //# sourceMappingURL=index.d.cts.map
1
+ import { $ as AsyncTaskStatus, $t as FileDownloadResponse, A as findProjectRoot, At as harnessProfileConfigSchema, B as FlattenSubAgentMiddleware, Bt as ConfigurationErrorCode, C as parseSkillMetadata, Cn as BackendProtocolV2, Ct as TASK_SYSTEM_PROMPT, D as Settings, Dt as registerHarnessProfile, E as filesValue, En as SandboxBackendProtocolV1, Et as getHarnessProfile, F as CreateDeepAgentParams, Ft as GeneralPurposeSubagentConfig, G as InferSubagentByName, Gt as PermissionMode, H as InferDeepAgentType, Ht as createFilesystemMiddleware, I as DeepAgent, It as HarnessProfile, J as ResolveDeepAgentTypeConfig, Jt as BackendProtocol, K as InferSubagentReactAgentType, Kt as AnyBackendProtocol, L as DeepAgentTypeConfig, Lt as HarnessProfileOptions, M as SubagentRunStream, Mt as serializeProfile, N as createSubagentTransformer, Nt as EMPTY_HARNESS_PROFILE, O as SettingsOptions, Ot as HarnessProfileConfigData, P as AnySubAgent, Pt as createHarnessProfile, Q as AsyncTask, Qt as FileData, R as DefaultDeepAgentTypeConfig, Rt as REQUIRED_MIDDLEWARE_NAMES, S as listSkills, Sn as resolveBackend, St as SubAgentMiddlewareOptions, T as createAgentMemoryMiddleware, Tn as BackendProtocolV1, Tt as createSubAgentMiddleware, U as InferStructuredResponse, Ut as FilesystemOperation, V as InferDeepAgentSubagents, Vt as FilesystemMiddlewareOptions, W as InferSubAgentMiddlewareStates, Wt as FilesystemPermission, X as AsyncSubAgent, Xt as EditResult, Y as SupportedResponseFormat, Yt as BackendRuntime, Z as AsyncSubAgentMiddlewareOptions, Zt as ExecuteResponse, _ as StoreBackendContext, _n as SandboxListResponse, _t as DEFAULT_GENERAL_PURPOSE_DESCRIPTION, a as adaptBackendProtocol, an as GrepResult, at as createCompletionCallbackMiddleware, b as ListSkillsOptions, bn as isSandboxBackend, bt as SUBAGENT_RESPONSE_FORMAT_CONFIG_KEY, c as LangSmithSandboxCreateOptions, cn as ReadRawResult, ct as MAX_SKILL_NAME_LENGTH, d as LocalShellBackend, dn as SandboxDeleteOptions, dt as createSkillsMiddleware, en as FileInfo, et as createAsyncSubAgentMiddleware, f as LocalShellBackendOptions, fn as SandboxError, ft as MemoryMiddlewareOptions, g as StoreBackend, gn as SandboxListOptions, gt as CompiledSubAgent, h as FilesystemBackend, hn as SandboxInfo, ht as createPatchToolCallsMiddleware, i as LangSmithStartSandboxOptions, in as GrepMatch, it as CompletionCallbackOptions, j as DeepAgentRunStream, jt as parseHarnessProfileConfig, k as createSettings, kt as generalPurposeSubagentConfigSchema, l as LangSmithSandboxOptions, ln as ReadResult, lt as SkillMetadata$1, m as CompositeBackend, mn as SandboxGetOrCreateOptions, mt as StateBackend, n as LangSmithCaptureSnapshotOptions, nn as FileUploadResponse, nt as computeSummarizationDefaults, o as adaptSandboxProtocol, on as LsResult, ot as MAX_SKILL_DESCRIPTION_LENGTH, p as ContextHubBackend, pn as SandboxErrorCode, pt as createMemoryMiddleware, q as MergedDeepAgentState, qt as BackendFactory, r as LangSmithSnapshot, rn as GlobResult, rt as createSummarizationMiddleware, s as LangSmithSandbox, sn as MaybePromise, st as MAX_SKILL_FILE_SIZE, t as createDeepAgent, tn as FileOperationError, tt as isAsyncSubAgent, u as BaseSandbox, un as SandboxBackendProtocol, ut as SkillsMiddlewareOptions, v as StoreBackendNamespaceFactory, vn as StateAndStore, vt as DEFAULT_SUBAGENT_PROMPT, w as AgentMemoryMiddlewareOptions, wn as SandboxBackendProtocolV2, wt as createSubAgent, x as SkillMetadata, xn as isSandboxProtocol, xt as SubAgent, y as StoreBackendOptions, yn as WriteResult, yt as GENERAL_PURPOSE_SUBAGENT, z as ExtractSubAgentMiddleware, zt as ConfigurationError } from "./agent-DNSq5NSK.cjs";
2
+ export { type AgentMemoryMiddlewareOptions, type AnyBackendProtocol, type AnySubAgent, type AsyncSubAgent, type AsyncSubAgentMiddlewareOptions, type AsyncTask, type AsyncTaskStatus, type BackendFactory, type BackendProtocol, type BackendProtocolV1, type BackendProtocolV2, type BackendRuntime, BaseSandbox, type CompiledSubAgent, type CompletionCallbackOptions, CompositeBackend, ConfigurationError, type ConfigurationErrorCode, ContextHubBackend, type CreateDeepAgentParams, DEFAULT_GENERAL_PURPOSE_DESCRIPTION, DEFAULT_SUBAGENT_PROMPT, type DeepAgent, type DeepAgentRunStream, type DeepAgentTypeConfig, type DefaultDeepAgentTypeConfig, EMPTY_HARNESS_PROFILE, type EditResult, type ExecuteResponse, type ExtractSubAgentMiddleware, type FileData, type FileDownloadResponse, type FileInfo, type FileOperationError, type FileUploadResponse, FilesystemBackend, type FilesystemMiddlewareOptions, type FilesystemOperation, type FilesystemPermission, type FlattenSubAgentMiddleware, GENERAL_PURPOSE_SUBAGENT, type GeneralPurposeSubagentConfig, type GlobResult, type GrepMatch, type GrepResult, type HarnessProfile, type HarnessProfileConfigData, type HarnessProfileOptions, type InferDeepAgentSubagents, type InferDeepAgentType, type InferStructuredResponse, type InferSubAgentMiddlewareStates, type InferSubagentByName, type InferSubagentReactAgentType, type LangSmithCaptureSnapshotOptions, LangSmithSandbox, type LangSmithSandboxCreateOptions, type LangSmithSandboxOptions, type LangSmithSnapshot, type LangSmithStartSandboxOptions, type ListSkillsOptions, type SkillMetadata as LoaderSkillMetadata, LocalShellBackend, type LocalShellBackendOptions, type LsResult, MAX_SKILL_DESCRIPTION_LENGTH, MAX_SKILL_FILE_SIZE, MAX_SKILL_NAME_LENGTH, type MaybePromise, type MemoryMiddlewareOptions, type MergedDeepAgentState, type PermissionMode, REQUIRED_MIDDLEWARE_NAMES, type ReadRawResult, type ReadResult, type ResolveDeepAgentTypeConfig, SUBAGENT_RESPONSE_FORMAT_CONFIG_KEY, type SandboxBackendProtocol, type SandboxBackendProtocolV1, type SandboxBackendProtocolV2, type SandboxDeleteOptions, SandboxError, type SandboxErrorCode, type SandboxGetOrCreateOptions, type SandboxInfo, type SandboxListOptions, type SandboxListResponse, type Settings, type SettingsOptions, type SkillMetadata$1 as SkillMetadata, type SkillsMiddlewareOptions, type StateAndStore, StateBackend, StoreBackend, type StoreBackendContext, type StoreBackendNamespaceFactory, type StoreBackendOptions, type SubAgent, type SubAgentMiddlewareOptions, type SubagentRunStream, type SupportedResponseFormat, TASK_SYSTEM_PROMPT, type WriteResult, adaptBackendProtocol, adaptSandboxProtocol, computeSummarizationDefaults, createAgentMemoryMiddleware, createAsyncSubAgentMiddleware, createCompletionCallbackMiddleware, createDeepAgent, createFilesystemMiddleware, createHarnessProfile, createMemoryMiddleware, createPatchToolCallsMiddleware, createSettings, createSkillsMiddleware, createSubAgent, createSubAgentMiddleware, createSubagentTransformer, createSummarizationMiddleware, filesValue, findProjectRoot, generalPurposeSubagentConfigSchema, getHarnessProfile, harnessProfileConfigSchema, isAsyncSubAgent, isSandboxBackend, isSandboxProtocol, listSkills, parseHarnessProfileConfig, parseSkillMetadata, registerHarnessProfile, resolveBackend, serializeProfile };