@xpert-ai/plugin-sdk 3.7.2 → 3.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/index.cjs.js +1282 -0
  2. package/index.esm.js +1256 -1
  3. package/package.json +2 -1
  4. package/src/index.d.ts +2 -0
  5. package/src/lib/agent/handoff/agent-chat.contract.d.ts +20 -0
  6. package/src/lib/agent/handoff/handoff-processor.decorator.d.ts +11 -0
  7. package/src/lib/agent/handoff/handoff-processor.registry.d.ts +6 -0
  8. package/src/lib/agent/handoff/handoff.interface.d.ts +17 -0
  9. package/src/lib/agent/handoff/index.d.ts +6 -0
  10. package/src/lib/agent/handoff/message-type.d.ts +24 -0
  11. package/src/lib/agent/handoff/types.d.ts +110 -0
  12. package/src/lib/agent/index.d.ts +1 -0
  13. package/src/lib/agent/middleware/runtime.d.ts +2 -0
  14. package/src/lib/agent/middleware/strategy.interface.d.ts +5 -1
  15. package/src/lib/agent/middleware/types.d.ts +2 -2
  16. package/src/lib/ai-model/utils/index.d.ts +1 -0
  17. package/src/lib/ai-model/utils/limits.d.ts +4 -0
  18. package/src/lib/channel/cancel-conversation.command.d.ts +14 -0
  19. package/src/lib/channel/index.d.ts +4 -0
  20. package/src/lib/channel/strategy.decorator.d.ts +23 -0
  21. package/src/lib/channel/strategy.interface.d.ts +345 -0
  22. package/src/lib/channel/strategy.registry.d.ts +30 -0
  23. package/src/lib/core/permissions/analytics.d.ts +46 -0
  24. package/src/lib/core/{permissions.d.ts → permissions/general.d.ts} +9 -12
  25. package/src/lib/core/permissions/handoff.d.ts +36 -0
  26. package/src/lib/core/permissions/index.d.ts +24 -0
  27. package/src/lib/core/permissions/operation.d.ts +8 -0
  28. package/src/lib/core/permissions/user.d.ts +29 -0
  29. package/src/lib/integration/strategy.interface.d.ts +3 -1
  30. package/src/lib/sandbox/index.d.ts +8 -0
  31. package/src/lib/sandbox/protocol.d.ts +383 -0
  32. package/src/lib/sandbox/sandbox.d.ts +103 -0
  33. package/src/lib/sandbox/sandbox.decorator.d.ts +2 -0
  34. package/src/lib/sandbox/sandbox.interface.d.ts +38 -0
  35. package/src/lib/sandbox/sandbox.registry.d.ts +6 -0
  36. package/src/lib/toolset/strategy.interface.d.ts +2 -6
  37. package/src/lib/types.d.ts +7 -1
  38. package/src/lib/workflow/node/strategy.interface.d.ts +4 -2
  39. package/src/lib/workflow/trigger/strategy.interface.d.ts +13 -0
@@ -0,0 +1,30 @@
1
+ import { DiscoveryService, Reflector } from '@nestjs/core';
2
+ import { BaseStrategyRegistry } from '../strategy';
3
+ import { IChatChannel } from './strategy.interface';
4
+ /**
5
+ * Chat Channel Registry
6
+ *
7
+ * Manages all registered chat channel implementations.
8
+ * Channels are automatically discovered and registered via @ChatChannel decorator.
9
+ *
10
+ * Supports:
11
+ * - Organization-scoped channels
12
+ * - Global channels (fallback)
13
+ * - Plugin-based registration/removal
14
+ * - Dynamic channel lookup
15
+ *
16
+ * @example
17
+ * ```typescript
18
+ * // Get channel by type
19
+ * const channel = registry.get('lark')
20
+ *
21
+ * // List all available channels for an organization
22
+ * const channels = registry.list(organizationId)
23
+ *
24
+ * // Send message using a channel
25
+ * await channel.sendText(ctx, 'Hello!')
26
+ * ```
27
+ */
28
+ export declare class ChatChannelRegistry extends BaseStrategyRegistry<IChatChannel> {
29
+ constructor(discoveryService: DiscoveryService, reflector: Reflector);
30
+ }
@@ -0,0 +1,46 @@
1
+ import type { DSCoreService } from '@metad/ocap-core';
2
+ import type { BasePermission } from './general';
3
+ export type AnalyticsPermissionOperation = 'dscore' | 'query' | 'model' | 'indicator' | 'create_indicator';
4
+ /**
5
+ * Analytics Permission
6
+ * Example: { type: 'analytics', operations: ['dscore'] }
7
+ */
8
+ export interface AnalyticsPermission extends BasePermission {
9
+ type: 'analytics';
10
+ operations?: AnalyticsPermissionOperation[];
11
+ scope?: string[];
12
+ }
13
+ /**
14
+ * System token for resolving analytics permission service from plugin context.
15
+ */
16
+ export declare const ANALYTICS_PERMISSION_SERVICE_TOKEN = "XPERT_PLUGIN_ANALYTICS_PERMISSION_SERVICE";
17
+ export interface AnalyticsResolvedChatBIModel {
18
+ chatbiModelId: string;
19
+ modelId: string;
20
+ modelKey?: string;
21
+ cubeName: string;
22
+ entityCaption?: string;
23
+ entityDescription?: string;
24
+ prompts?: string[];
25
+ }
26
+ export interface AnalyticsDSCoreInput {
27
+ modelIds?: string[];
28
+ indicatorDraft?: boolean;
29
+ semanticModelDraft?: boolean;
30
+ }
31
+ export interface AnalyticsIndicatorValidationInput {
32
+ modelIds?: string[];
33
+ semanticModelId: string;
34
+ modelKey?: string;
35
+ statement: string;
36
+ }
37
+ /**
38
+ * Analytics service exposed to plugins under permission control.
39
+ */
40
+ export interface AnalyticsPermissionService {
41
+ resolveChatBIModels(modelIds: string[]): Promise<AnalyticsResolvedChatBIModel[]>;
42
+ getDSCoreService(input?: AnalyticsDSCoreInput): Promise<DSCoreService>;
43
+ visitChatBIModel(modelId: string, cubeName: string): Promise<void>;
44
+ ensureCreateIndicatorAccess(): Promise<void>;
45
+ validateIndicatorStatement(input: AnalyticsIndicatorValidationInput): Promise<void>;
46
+ }
@@ -1,10 +1,4 @@
1
- /**
2
- * ===============================
3
- * Unified Permissions Definition
4
- * ===============================
5
- * Used by Agent / Plugin developers to declare required capabilities.
6
- * Core system will check and inject allowed resources accordingly.
7
- */
1
+ import type { IIntegration } from '@metad/contracts';
8
2
  /**
9
3
  * Base Permission type
10
4
  */
@@ -12,6 +6,7 @@ export interface BasePermission {
12
6
  type: string;
13
7
  description?: string;
14
8
  }
9
+ export type IntegrationPermissionOperation = 'read' | 'write' | 'update' | 'delete';
15
10
  /**
16
11
  * 1. LLM Permission
17
12
  * Example: { type: 'llm', provider: 'openai', capability: 'vision' }
@@ -61,14 +56,16 @@ export interface FileSystemPermission extends BasePermission {
61
56
  export interface IntegrationPermission extends BasePermission {
62
57
  type: 'integration';
63
58
  service: string;
64
- operations?: Array<'read' | 'write' | 'update' | 'delete'>;
59
+ operations?: IntegrationPermissionOperation[];
65
60
  scope?: string[];
66
61
  }
67
62
  /**
68
- * Union type for all permissions
63
+ * System token for resolving integration read service from plugin context.
69
64
  */
70
- export type Permission = LLMPermission | VectorStorePermission | KnowledgePermission | FileSystemPermission | IntegrationPermission;
65
+ export declare const INTEGRATION_PERMISSION_SERVICE_TOKEN = "XPERT_PLUGIN_INTEGRATION_PERMISSION_SERVICE";
71
66
  /**
72
- * Permissions array type
67
+ * Read-only integration permission service exposed to plugins.
73
68
  */
74
- export type Permissions = Permission[];
69
+ export interface IntegrationPermissionService {
70
+ read<TIntegration = IIntegration>(id: string, options?: Record<string, any>): Promise<TIntegration | null>;
71
+ }
@@ -0,0 +1,36 @@
1
+ import type { HandoffMessage, ProcessResult } from '../../agent/handoff/types';
2
+ export type HandoffPermissionOperation = 'enqueue' | 'wait';
3
+ /**
4
+ * Handoff Queue Permission
5
+ * Example: { type: 'handoff', operations: ['enqueue', 'wait'] }
6
+ */
7
+ export interface HandoffPermission {
8
+ type: 'handoff';
9
+ operations?: HandoffPermissionOperation[];
10
+ scope?: string[];
11
+ description?: string;
12
+ }
13
+ /**
14
+ * System token for resolving handoff queue service from plugin context.
15
+ */
16
+ export declare const HANDOFF_PERMISSION_SERVICE_TOKEN = "XPERT_PLUGIN_HANDOFF_PERMISSION_SERVICE";
17
+ /**
18
+ * Internal system token used by core to expose the handoff queue bridge.
19
+ */
20
+ export declare const HANDOFF_QUEUE_SERVICE_TOKEN = "XPERT_HANDOFF_QUEUE_SERVICE";
21
+ export interface HandoffEnqueueOptions {
22
+ delayMs?: number;
23
+ }
24
+ export interface HandoffEnqueueAndWaitOptions extends HandoffEnqueueOptions {
25
+ timeoutMs?: number;
26
+ onEvent?: (event: unknown) => void;
27
+ }
28
+ /**
29
+ * Handoff queue service exposed to plugins under permission control.
30
+ */
31
+ export interface HandoffPermissionService {
32
+ enqueue(message: HandoffMessage, options?: HandoffEnqueueOptions): Promise<{
33
+ id: string;
34
+ }>;
35
+ enqueueAndWait(message: HandoffMessage, options?: HandoffEnqueueAndWaitOptions): Promise<ProcessResult>;
36
+ }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * ===============================
3
+ * Unified Permissions Definition
4
+ * ===============================
5
+ * Used by Agent / Plugin developers to declare required capabilities.
6
+ * Core system will check and inject allowed resources accordingly.
7
+ */
8
+ export * from './general';
9
+ export * from './analytics';
10
+ export * from './operation';
11
+ export * from './handoff';
12
+ export * from './user';
13
+ import type { FileSystemPermission, IntegrationPermission, KnowledgePermission, LLMPermission, VectorStorePermission } from './general';
14
+ import type { AnalyticsPermission } from './analytics';
15
+ import type { HandoffPermission } from './handoff';
16
+ import type { UserPermission } from './user';
17
+ /**
18
+ * Union type for all permissions
19
+ */
20
+ export type Permission = LLMPermission | VectorStorePermission | KnowledgePermission | FileSystemPermission | IntegrationPermission | AnalyticsPermission | UserPermission | HandoffPermission;
21
+ /**
22
+ * Permissions array type
23
+ */
24
+ export type Permissions = Permission[];
@@ -0,0 +1,8 @@
1
+ export interface PermissionOperationMetadata<TPermissionType extends string = string, TOperation extends string = string> {
2
+ permissionType: TPermissionType;
3
+ operation: TOperation;
4
+ }
5
+ export declare const PERMISSION_OPERATION_METADATA_KEY = "XPERT_PLUGIN_PERMISSION_OPERATION";
6
+ export declare function RequirePermissionOperation<TPermissionType extends string, TOperation extends string>(permissionType: TPermissionType, operation: TOperation): MethodDecorator;
7
+ export declare function getPermissionOperationMetadata(method: unknown): PermissionOperationMetadata | undefined;
8
+ export declare function getRequiredPermissionOperation<TOperation extends string = string>(method: unknown, permissionType: string): TOperation | undefined;
@@ -0,0 +1,29 @@
1
+ import type { IUser } from '@metad/contracts';
2
+ import type { BasePermission } from './general';
3
+ export type UserPermissionOperation = 'read' | 'write' | 'update' | 'delete';
4
+ /**
5
+ * User Permission
6
+ * Example: { type: 'user', operations: ['read'] }
7
+ */
8
+ export interface UserPermission extends BasePermission {
9
+ type: 'user';
10
+ operations?: UserPermissionOperation[];
11
+ scope?: string[];
12
+ }
13
+ /**
14
+ * System token for resolving user permission service from plugin context.
15
+ */
16
+ export declare const USER_PERMISSION_SERVICE_TOKEN = "XPERT_PLUGIN_USER_PERMISSION_SERVICE";
17
+ export interface UserProvisionByThirdPartyIdentityInput {
18
+ tenantId: string;
19
+ thirdPartyId: string;
20
+ profile?: Partial<Pick<IUser, 'username' | 'email' | 'mobile' | 'imageUrl' | 'firstName' | 'lastName' | 'preferredLanguage'>>;
21
+ defaults?: {
22
+ roleId?: string;
23
+ roleName?: string;
24
+ };
25
+ }
26
+ export interface UserPermissionService {
27
+ read<TUser = IUser>(criteria: Record<string, any>): Promise<TUser | null>;
28
+ provisionByThirdPartyIdentity<TUser = IUser>(input: UserProvisionByThirdPartyIdentityInput): Promise<TUser | null>;
29
+ }
@@ -5,5 +5,7 @@ export type TIntegrationStrategyParams = {
5
5
  export interface IntegrationStrategy<T = unknown> {
6
6
  meta: TIntegrationProvider;
7
7
  execute(integration: IIntegration<T>, payload: TIntegrationStrategyParams): Promise<any>;
8
- validateConfig?(config: T): Promise<void>;
8
+ validateConfig?(config: T, integration?: IIntegration<T>): Promise<void | {
9
+ webhookUrl: string;
10
+ }>;
9
11
  }
@@ -0,0 +1,8 @@
1
+ export * from './protocol';
2
+ export * from './sandbox';
3
+ export * from './sandbox.decorator';
4
+ export * from './sandbox.interface';
5
+ export * from './sandbox.registry';
6
+ export * from './sandbox.interface';
7
+ export * from './sandbox.decorator';
8
+ export * from './sandbox.registry';
@@ -0,0 +1,383 @@
1
+ /**
2
+ * Protocol definition for pluggable memory backends.
3
+ *
4
+ * This module defines the BackendProtocol that all backend implementations
5
+ * must follow. Backends can store files in different locations (state, filesystem,
6
+ * database, etc.) and provide a uniform interface for file operations.
7
+ */
8
+ export type MaybePromise<T> = T | Promise<T>;
9
+ /**
10
+ * Structured file listing info.
11
+ *
12
+ * Minimal contract used across backends. Only "path" is required.
13
+ * Other fields are best-effort and may be absent depending on backend.
14
+ */
15
+ export interface FileInfo {
16
+ /** File path */
17
+ path: string;
18
+ /** Whether this is a directory */
19
+ is_dir?: boolean;
20
+ /** File size in bytes (approximate) */
21
+ size?: number;
22
+ /** ISO 8601 timestamp of last modification */
23
+ modified_at?: string;
24
+ }
25
+ /**
26
+ * Structured grep match entry.
27
+ */
28
+ export interface GrepMatch {
29
+ /** File path where match was found */
30
+ path: string;
31
+ /** Line number (1-indexed) */
32
+ line: number;
33
+ /** The matching line text */
34
+ text: string;
35
+ }
36
+ /**
37
+ * Read mode for file reading operations.
38
+ */
39
+ export type ReadMode = 'slice' | 'indentation';
40
+ /**
41
+ * Configuration for indentation-aware file reading.
42
+ */
43
+ export interface IndentationOptions {
44
+ /** Anchor line number (1-indexed), defaults to offset */
45
+ anchor_line?: number;
46
+ /** Maximum indentation depth to collect; 0 means unlimited */
47
+ max_levels?: number;
48
+ /** Whether to include sibling blocks at the same indentation level */
49
+ include_siblings?: boolean;
50
+ /** Whether to include header lines (comments) above the anchor block */
51
+ include_header?: boolean;
52
+ /** Hard cap on returned lines */
53
+ max_lines?: number;
54
+ }
55
+ /**
56
+ * File data structure used by backends.
57
+ *
58
+ * All file data is represented as objects with this structure:
59
+ */
60
+ export interface FileData {
61
+ /** Lines of text content */
62
+ content: string[];
63
+ /** ISO format timestamp of creation */
64
+ created_at: string;
65
+ /** ISO format timestamp of last modification */
66
+ modified_at: string;
67
+ }
68
+ /**
69
+ * Result from backend write operations.
70
+ *
71
+ * Checkpoint backends populate filesUpdate with {file_path: file_data} for LangGraph state.
72
+ * External backends set filesUpdate to null (already persisted to disk/S3/database/etc).
73
+ */
74
+ export interface WriteResult {
75
+ /** Error message on failure, undefined on success */
76
+ error?: string;
77
+ /** File path of written file, undefined on failure */
78
+ path?: string;
79
+ /**
80
+ * State update dict for checkpoint backends, null for external storage.
81
+ * Checkpoint backends populate this with {file_path: file_data} for LangGraph state.
82
+ * External backends set null (already persisted to disk/S3/database/etc).
83
+ */
84
+ filesUpdate?: Record<string, FileData> | null;
85
+ /** Metadata for the write operation, attached to the ToolMessage */
86
+ metadata?: Record<string, unknown>;
87
+ }
88
+ /**
89
+ * Result from backend edit operations.
90
+ *
91
+ * Checkpoint backends populate filesUpdate with {file_path: file_data} for LangGraph state.
92
+ * External backends set filesUpdate to null (already persisted to disk/S3/database/etc).
93
+ */
94
+ export interface EditResult {
95
+ /** Error message on failure, undefined on success */
96
+ error?: string;
97
+ /** File path of edited file, undefined on failure */
98
+ path?: string;
99
+ /**
100
+ * State update dict for checkpoint backends, null for external storage.
101
+ * Checkpoint backends populate this with {file_path: file_data} for LangGraph state.
102
+ * External backends set null (already persisted to disk/S3/database/etc).
103
+ */
104
+ filesUpdate?: Record<string, FileData> | null;
105
+ /** Number of replacements made, undefined on failure */
106
+ occurrences?: number;
107
+ /** Metadata for the edit operation, attached to the ToolMessage */
108
+ metadata?: Record<string, unknown>;
109
+ }
110
+ /**
111
+ * Single edit operation for multi-edit.
112
+ */
113
+ export interface EditOperation {
114
+ /** String to find and replace */
115
+ oldString: string;
116
+ /** Replacement string */
117
+ newString: string;
118
+ /** If true, replace all occurrences (default: false) */
119
+ replaceAll?: boolean;
120
+ }
121
+ /**
122
+ * Result from backend multi-edit operations.
123
+ *
124
+ * Checkpoint backends populate filesUpdate with {file_path: file_data} for LangGraph state.
125
+ * External backends set filesUpdate to null (already persisted to disk/S3/database/etc).
126
+ */
127
+ export interface MultiEditResult {
128
+ /** Error message on failure, undefined on success */
129
+ error?: string;
130
+ /** File path of edited file, undefined on failure */
131
+ path?: string;
132
+ /**
133
+ * State update dict for checkpoint backends, null for external storage.
134
+ * Checkpoint backends populate this with {file_path: file_data} for LangGraph state.
135
+ * External backends set null (already persisted to disk/S3/database/etc).
136
+ */
137
+ filesUpdate?: Record<string, FileData> | null;
138
+ /** Results from each individual edit operation */
139
+ results?: EditResult[];
140
+ /** Metadata for the multi-edit operation, attached to the ToolMessage */
141
+ metadata?: Record<string, unknown>;
142
+ }
143
+ /**
144
+ * Result of code execution.
145
+ * Simplified schema optimized for LLM consumption.
146
+ */
147
+ export interface ExecuteResponse {
148
+ /** Combined stdout and stderr output of the executed command */
149
+ output: string;
150
+ /** The process exit code. 0 indicates success, non-zero indicates failure */
151
+ exitCode: number | null;
152
+ /** Whether the output was truncated due to backend limitations */
153
+ truncated: boolean;
154
+ }
155
+ /**
156
+ * Standardized error codes for file upload/download operations.
157
+ */
158
+ export type FileOperationError = "file_not_found" | "permission_denied" | "is_directory" | "invalid_path";
159
+ /**
160
+ * Result of a single file download operation.
161
+ */
162
+ export interface FileDownloadResponse {
163
+ /** The file path that was requested */
164
+ path: string;
165
+ /** File contents as Uint8Array on success, null on failure */
166
+ content: Uint8Array | null;
167
+ /** Standardized error code on failure, null on success */
168
+ error: FileOperationError | null;
169
+ }
170
+ /**
171
+ * Result of a single file upload operation.
172
+ */
173
+ export interface FileUploadResponse {
174
+ /** The file path that was requested */
175
+ path: string;
176
+ /** Standardized error code on failure, null on success */
177
+ error: FileOperationError | null;
178
+ }
179
+ /**
180
+ * Protocol for pluggable memory backends (single, unified).
181
+ *
182
+ * Backends can store files in different locations (state, filesystem, database, etc.)
183
+ * and provide a uniform interface for file operations.
184
+ *
185
+ * All file data is represented as objects with the FileData structure.
186
+ *
187
+ * Methods can return either direct values or Promises, allowing both
188
+ * synchronous and asynchronous implementations.
189
+ */
190
+ export interface BackendProtocol {
191
+ /**
192
+ * Structured listing with file metadata.
193
+ *
194
+ * Lists files and directories in the specified directory (non-recursive).
195
+ * Directories have a trailing / in their path and is_dir=true.
196
+ *
197
+ * @param path - Absolute path to directory
198
+ * @returns List of FileInfo objects for files and directories directly in the directory
199
+ */
200
+ lsInfo(path: string): MaybePromise<FileInfo[]>;
201
+ /**
202
+ * List directory contents recursively with depth control and pagination.
203
+ *
204
+ * @param dirPath - Absolute path to directory
205
+ * @param offset - 1-indexed entry number to start from (default: 1)
206
+ * @param limit - Maximum number of entries to return (default: 25)
207
+ * @param depth - Maximum depth to traverse (default: 2)
208
+ * @returns Human-readable directory tree with indentation
209
+ */
210
+ listDir(dirPath: string, offset?: number, limit?: number, depth?: number): MaybePromise<string>;
211
+ /**
212
+ * Read file content with line numbers or an error string.
213
+ *
214
+ * @param filePath - Absolute file path
215
+ * @param offset - Line offset to start reading from (1-indexed), default 1
216
+ * @param limit - Maximum number of lines to read, default 2000
217
+ * @param mode - Read mode: 'slice' (default) or 'indentation'
218
+ * @param indentation - Configuration for indentation mode
219
+ * @returns Formatted file content with line numbers, or error message
220
+ */
221
+ read(filePath: string, offset?: number, limit?: number, mode?: ReadMode, indentation?: IndentationOptions): MaybePromise<string>;
222
+ /**
223
+ * Structured search results or error string for invalid input.
224
+ *
225
+ * Searches file contents for a regex pattern.
226
+ *
227
+ * @param pattern - Regex pattern to search for
228
+ * @param path - Base path to search from (default: null)
229
+ * @param include - Optional glob pattern to filter files (e.g., "*.py")
230
+ * @returns List of GrepMatch objects or error string for invalid regex
231
+ */
232
+ grepRaw(pattern: string, path?: string | null, include?: string | null): MaybePromise<GrepMatch[] | string>;
233
+ /**
234
+ * Search file contents for a regex pattern, returning human-readable output.
235
+ *
236
+ * @param pattern - Regex pattern to search for
237
+ * @param path - Base path to search from (default: workspace root)
238
+ * @param include - Optional glob pattern to filter files (e.g., "*.js", "*.{ts,tsx}")
239
+ * @returns Human-readable output with matches grouped by file
240
+ */
241
+ grep(pattern: string, path?: string | null, include?: string | null): MaybePromise<string>;
242
+ /**
243
+ * Structured glob matching returning FileInfo objects.
244
+ *
245
+ * @param pattern - Glob pattern (e.g., `*.py`, `**\/*.ts`)
246
+ * @param path - Base path to search from (default: "/")
247
+ * @returns List of FileInfo objects matching the pattern
248
+ */
249
+ globInfo(pattern: string, path?: string): MaybePromise<FileInfo[]>;
250
+ /**
251
+ * Find files matching a glob pattern, returning human-readable output.
252
+ *
253
+ * @param pattern - Glob pattern (e.g., `*.py`, `**\/*.ts`)
254
+ * @param path - Base path to search from (default: workspace root)
255
+ * @returns Human-readable output with matching file paths
256
+ */
257
+ glob(pattern: string, path?: string): MaybePromise<string>;
258
+ /**
259
+ * Create a new file.
260
+ *
261
+ * @param filePath - Absolute file path
262
+ * @param content - File content as string
263
+ * @returns WriteResult with error populated on failure
264
+ */
265
+ write(filePath: string, content: string): MaybePromise<WriteResult>;
266
+ /**
267
+ * Append content to a file. Creates the file if it doesn't exist.
268
+ *
269
+ * @param filePath - Absolute file path
270
+ * @param content - Content to append
271
+ * @returns WriteResult with error populated on failure
272
+ */
273
+ append(filePath: string, content: string): MaybePromise<WriteResult>;
274
+ /**
275
+ * Edit a file by replacing string occurrences.
276
+ *
277
+ * @param filePath - Absolute file path
278
+ * @param oldString - String to find and replace
279
+ * @param newString - Replacement string
280
+ * @param replaceAll - If true, replace all occurrences (default: false)
281
+ * @returns EditResult with error, path, filesUpdate, and occurrences
282
+ */
283
+ edit(filePath: string, oldString: string, newString: string, replaceAll?: boolean): MaybePromise<EditResult>;
284
+ /**
285
+ * Perform multiple sequential edits on a single file.
286
+ * All edits are applied sequentially, with each edit operating on the result of the previous edit.
287
+ * All edits must succeed for the operation to succeed (atomic).
288
+ *
289
+ * @param filePath - Absolute file path
290
+ * @param edits - Array of edit operations to perform sequentially
291
+ * @returns MultiEditResult with error, path, filesUpdate, and individual results
292
+ */
293
+ multiEdit(filePath: string, edits: EditOperation[]): MaybePromise<MultiEditResult>;
294
+ /**
295
+ * Upload multiple files.
296
+ *
297
+ * @param files - List of [path, content] tuples to upload
298
+ * @returns List of FileUploadResponse objects, one per input file
299
+ */
300
+ uploadFiles(files: Array<[string, Uint8Array]>): MaybePromise<FileUploadResponse[]>;
301
+ /**
302
+ * Download multiple files.
303
+ *
304
+ * @param paths - List of file paths to download
305
+ * @returns List of FileDownloadResponse objects, one per input path
306
+ */
307
+ downloadFiles(paths: string[]): MaybePromise<FileDownloadResponse[]>;
308
+ }
309
+ /**
310
+ * Protocol for sandboxed backends with isolated runtime.
311
+ * Sandboxed backends run in isolated environments (e.g., containers)
312
+ * and communicate via defined interfaces.
313
+ */
314
+ export interface SandboxBackendProtocol extends BackendProtocol {
315
+ /**
316
+ * Execute a command in the sandbox.
317
+ *
318
+ * @param command - Full shell command string to execute
319
+ * @returns ExecuteResponse with combined output, exit code, and truncation flag
320
+ */
321
+ execute(command: string): MaybePromise<ExecuteResponse>;
322
+ /**
323
+ * Execute a command with line-by-line streaming output.
324
+ *
325
+ * When implemented, the middleware layer can push incremental output
326
+ * to the frontend as each line arrives, rather than waiting for the
327
+ * command to finish. Implementations MUST buffer partial lines and
328
+ * only invoke `onLine` with complete lines (LF-terminated).
329
+ *
330
+ * The returned `ExecuteResponse.output` contains the full collected
331
+ * output, identical to what `execute()` would return.
332
+ *
333
+ * Falls back to `execute()` + single `onLine` call in `BaseSandbox`
334
+ * when a concrete backend does not override this method.
335
+ *
336
+ * @param command - Full shell command string to execute
337
+ * @param onLine - Callback invoked once per complete output line
338
+ * @returns ExecuteResponse with combined output, exit code, and truncation flag
339
+ */
340
+ streamExecute?(command: string, onLine: (line: string) => void): MaybePromise<ExecuteResponse>;
341
+ /** Unique identifier for the sandbox backend instance */
342
+ readonly id: string;
343
+ }
344
+ /**
345
+ * Type guard to check if a backend supports execution.
346
+ *
347
+ * @param backend - Backend instance to check
348
+ * @returns True if the backend implements SandboxBackendProtocol
349
+ */
350
+ export declare function isSandboxBackend(backend: BackendProtocol): backend is SandboxBackendProtocol;
351
+ /**
352
+ * State and store container for backend initialization.
353
+ *
354
+ * This provides a clean interface for what backends need to access:
355
+ * - state: Current agent state (with files, messages, etc.)
356
+ * - store: Optional persistent store for cross-conversation data
357
+ *
358
+ * Different contexts build this differently:
359
+ * - Tools: Extract state via getCurrentTaskInput(config)
360
+ * - Middleware: Use request.state directly
361
+ */
362
+ export interface StateAndStore {
363
+ /** Current agent state with files, messages, etc. */
364
+ state: unknown;
365
+ /** Optional BaseStore for persistent cross-conversation storage */
366
+ /** Optional assistant ID for per-assistant isolation in store */
367
+ assistantId?: string;
368
+ }
369
+ /**
370
+ * Factory function type for creating backend instances.
371
+ *
372
+ * Backends receive StateAndStore which contains the current state
373
+ * and optional store, extracted from the execution context.
374
+ *
375
+ * @example
376
+ * ```typescript
377
+ * // Using in middleware
378
+ * const middleware = createFilesystemMiddleware({
379
+ * backend: (stateAndStore) => new StateBackend(stateAndStore)
380
+ * });
381
+ * ```
382
+ */
383
+ export type BackendFactory = (stateAndStore: StateAndStore) => BackendProtocol;