deepagents 1.10.2 → 1.10.5

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