@dexto/core 1.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,379 @@
1
+ import { ZodError } from 'zod';
2
+
3
+ /**
4
+ * Utility functions for converting various error types to proper Error instances
5
+ * with meaningful messages instead of "[object Object]"
6
+ */
7
+ /**
8
+ * Converts any error value to an Error instance with a meaningful message
9
+ *
10
+ * @param error - The error value to convert (can be Error, object, string, etc.)
11
+ * @returns Error instance with extracted or serialized message
12
+ */
13
+ declare function toError(error: unknown): Error;
14
+
15
+ /**
16
+ * Agent-specific error codes
17
+ * Includes agent configuration and lifecycle errors only
18
+ * Domain-specific errors (LLM, Session, MCP, etc.) belong in their respective modules
19
+ */
20
+ declare enum AgentErrorCode {
21
+ NOT_STARTED = "agent_not_started",
22
+ ALREADY_STARTED = "agent_already_started",
23
+ STOPPED = "agent_stopped",
24
+ INITIALIZATION_FAILED = "agent_initialization_failed",
25
+ API_VALIDATION_ERROR = "agent_api_validation_error"
26
+ }
27
+
28
+ /**
29
+ * Config-specific error codes
30
+ * Includes file operations, parsing, and validation errors for configuration management
31
+ */
32
+ declare enum ConfigErrorCode {
33
+ FILE_NOT_FOUND = "config_file_not_found",
34
+ FILE_READ_ERROR = "config_file_read_error",
35
+ FILE_WRITE_ERROR = "config_file_write_error",
36
+ PARSE_ERROR = "config_parse_error",
37
+ NO_PROJECT_DEFAULT = "config_no_project_default",
38
+ NO_GLOBAL_PREFERENCES = "config_no_global_preferences",
39
+ SETUP_INCOMPLETE = "config_setup_incomplete",
40
+ BUNDLED_NOT_FOUND = "config_bundled_not_found",
41
+ UNKNOWN_CONTEXT = "config_unknown_context"
42
+ }
43
+
44
+ /**
45
+ * Context-specific error codes
46
+ * Includes initialization, message validation, token processing, and formatting errors
47
+ */
48
+ declare enum ContextErrorCode {
49
+ MESSAGE_ROLE_MISSING = "context_message_role_missing",
50
+ MESSAGE_CONTENT_EMPTY = "context_message_content_empty",
51
+ USER_MESSAGE_CONTENT_INVALID = "context_user_message_content_invalid",
52
+ ASSISTANT_MESSAGE_CONTENT_OR_TOOLS_REQUIRED = "context_assistant_message_content_or_tools_required",
53
+ ASSISTANT_MESSAGE_TOOL_CALLS_INVALID = "context_assistant_message_tool_calls_invalid",
54
+ TOOL_MESSAGE_FIELDS_MISSING = "context_tool_message_fields_missing",
55
+ TOOL_CALL_ID_NAME_REQUIRED = "context_tool_call_id_name_required",
56
+ SYSTEM_MESSAGE_CONTENT_INVALID = "context_system_message_content_invalid",
57
+ TOKEN_COUNT_FAILED = "context_token_count_failed",
58
+ PRESERVE_VALUES_NEGATIVE = "context_preserve_values_negative",
59
+ MIN_MESSAGES_NEGATIVE = "context_min_messages_negative"
60
+ }
61
+
62
+ /**
63
+ * LLM-specific error codes
64
+ * Includes configuration, validation, and runtime errors for LLM operations
65
+ */
66
+ declare enum LLMErrorCode {
67
+ API_KEY_MISSING = "llm_api_key_missing",
68
+ API_KEY_INVALID = "llm_api_key_invalid",// Too short, wrong format
69
+ API_KEY_CANDIDATE_MISSING = "llm_api_key_candidate_missing",
70
+ BASE_URL_MISSING = "llm_base_url_missing",
71
+ BASE_URL_INVALID = "llm_base_url_invalid",
72
+ MODEL_INCOMPATIBLE = "llm_model_incompatible",
73
+ MODEL_UNKNOWN = "llm_model_unknown",
74
+ PROVIDER_UNSUPPORTED = "llm_provider_unsupported",
75
+ ROUTER_UNSUPPORTED = "llm_router_unsupported",
76
+ INPUT_FILE_UNSUPPORTED = "llm_input_file_unsupported",
77
+ INPUT_IMAGE_UNSUPPORTED = "llm_input_image_unsupported",
78
+ INPUT_TEXT_INVALID = "llm_input_text_invalid",
79
+ TOKENS_EXCEEDED = "llm_tokens_exceeded",
80
+ RATE_LIMIT_EXCEEDED = "llm_rate_limit_exceeded",
81
+ SWITCH_FAILED = "llm_switch_failed",
82
+ GENERATION_FAILED = "llm_generation_failed",
83
+ SWITCH_INPUT_MISSING = "llm_switch_input_missing",// At least model or provider must be specified
84
+ REQUEST_INVALID_SCHEMA = "llm_request_invalid_schema"
85
+ }
86
+
87
+ /**
88
+ * MCP-specific error codes
89
+ * Includes server configuration, connection, and protocol errors
90
+ */
91
+ declare enum MCPErrorCode {
92
+ SCHEMA_VALIDATION = "mcp_schema_validation",
93
+ COMMAND_MISSING = "mcp_command_missing",
94
+ DUPLICATE_NAME = "mcp_duplicate_name",
95
+ CONNECTION_FAILED = "mcp_connection_failed",
96
+ PROTOCOL_ERROR = "mcp_protocol_error",
97
+ TOOL_NOT_FOUND = "mcp_tool_not_found",
98
+ PROMPT_NOT_FOUND = "mcp_prompt_not_found",
99
+ RESOURCE_NOT_FOUND = "mcp_resource_not_found"
100
+ }
101
+
102
+ /**
103
+ * Session-specific error codes
104
+ * Includes session lifecycle, management, and state errors
105
+ */
106
+ declare enum SessionErrorCode {
107
+ SESSION_NOT_FOUND = "session_not_found",
108
+ SESSION_INITIALIZATION_FAILED = "session_initialization_failed",
109
+ SESSION_MAX_SESSIONS_EXCEEDED = "session_max_sessions_exceeded",
110
+ SESSION_STORAGE_FAILED = "session_storage_failed",
111
+ SESSION_RESET_FAILED = "session_reset_failed"
112
+ }
113
+
114
+ /**
115
+ * Storage-specific error codes
116
+ * Includes database, file system, and persistence errors
117
+ */
118
+ declare enum StorageErrorCode {
119
+ CONNECTION_FAILED = "storage_connection_failed",
120
+ CONNECTION_CONFIG_MISSING = "storage_connection_config_missing",
121
+ READ_FAILED = "storage_read_failed",
122
+ WRITE_FAILED = "storage_write_failed",
123
+ DELETE_FAILED = "storage_delete_failed",
124
+ MIGRATION_FAILED = "storage_migration_failed"
125
+ }
126
+
127
+ /**
128
+ * SystemPrompt-specific error codes
129
+ * Includes file processing and configuration errors
130
+ */
131
+ declare enum SystemPromptErrorCode {
132
+ FILE_INVALID_TYPE = "systemprompt_file_invalid_type",
133
+ FILE_TOO_LARGE = "systemprompt_file_too_large",
134
+ FILE_READ_FAILED = "systemprompt_file_read_failed",
135
+ CONTRIBUTOR_SOURCE_UNKNOWN = "systemprompt_contributor_source_unknown",
136
+ CONTRIBUTOR_CONFIG_INVALID = "systemprompt_contributor_config_invalid"
137
+ }
138
+
139
+ /**
140
+ * Tools-specific error codes
141
+ * Includes tool execution, confirmation, and authorization errors
142
+ */
143
+ declare enum ToolErrorCode {
144
+ EXECUTION_DENIED = "tools_execution_denied",
145
+ EXECUTION_TIMEOUT = "tools_execution_timeout",
146
+ EXECUTION_FAILED = "tools_execution_failed",
147
+ CONFIRMATION_HANDLER_MISSING = "tools_confirmation_handler_missing",
148
+ CONFIRMATION_TIMEOUT = "tools_confirmation_timeout",
149
+ CONFIRMATION_CANCELLED = "tools_confirmation_cancelled",
150
+ TOOL_NOT_FOUND = "tools_tool_not_found",
151
+ TOOL_INVALID_ARGS = "tools_invalid_args",
152
+ TOOL_UNAUTHORIZED = "tools_unauthorized",
153
+ CONFIG_INVALID = "tools_config_invalid"
154
+ }
155
+
156
+ declare enum PreferenceErrorCode {
157
+ FILE_NOT_FOUND = "preference_file_not_found",
158
+ FILE_READ_ERROR = "preference_file_read_error",
159
+ FILE_WRITE_ERROR = "preference_file_write_error",
160
+ VALIDATION_ERROR = "preference_validation_error",
161
+ MODEL_INCOMPATIBLE = "preference_model_incompatible"
162
+ }
163
+
164
+ /**
165
+ * Registry-specific error codes
166
+ * Includes agent resolution, installation, and registry management errors
167
+ */
168
+ declare enum RegistryErrorCode {
169
+ AGENT_NOT_FOUND = "registry_agent_not_found",
170
+ AGENT_INVALID_ENTRY = "registry_agent_invalid_entry",
171
+ INSTALLATION_FAILED = "registry_installation_failed",
172
+ INSTALLATION_VALIDATION_FAILED = "registry_installation_validation_failed",
173
+ REGISTRY_NOT_FOUND = "registry_file_not_found",
174
+ REGISTRY_PARSE_ERROR = "registry_parse_error",
175
+ CONFIG_NOT_FOUND = "registry_config_not_found",
176
+ MAIN_CONFIG_MISSING = "registry_main_config_missing",
177
+ AGENT_NOT_INSTALLED = "registry_agent_not_installed",
178
+ AGENT_PROTECTED = "registry_agent_protected",
179
+ UNINSTALLATION_FAILED = "registry_uninstallation_failed",
180
+ AGENT_NOT_INSTALLED_AUTO_INSTALL_DISABLED = "registry_agent_not_installed_auto_install_disabled"
181
+ }
182
+
183
+ /**
184
+ * Error scopes representing functional domains in the system
185
+ * Each scope owns its validation and error logic
186
+ */
187
+ declare enum ErrorScope {
188
+ LLM = "llm",// LLM operations, model compatibility, input validation for LLMs
189
+ AGENT = "agent",// Agent lifecycle, configuration
190
+ CONFIG = "config",// Configuration file operations, parsing, validation
191
+ CONTEXT = "context",// Context management, message validation, token processing
192
+ SESSION = "session",// Session lifecycle, management, and state
193
+ MCP = "mcp",// MCP server connections and protocol
194
+ TOOLS = "tools",// Tool execution and authorization
195
+ STORAGE = "storage",// Storage backend operations
196
+ SYSTEM_PROMPT = "system_prompt",// System prompt contributors and file processing
197
+ PREFERENCE = "preference",// Global preferences file operations and validation
198
+ AGENT_REGISTRY = "agent_registry"
199
+ }
200
+ /**
201
+ * Error types that map directly to HTTP status codes
202
+ * Each type represents the nature of the error
203
+ */
204
+ declare enum ErrorType {
205
+ USER = "user",// 400 - bad input, config errors, validation failures
206
+ NOT_FOUND = "not_found",// 404 - resource doesn't exist (session, file, etc.)
207
+ FORBIDDEN = "forbidden",// 403 - permission denied, unauthorized
208
+ TIMEOUT = "timeout",// 408 - operation timed out
209
+ RATE_LIMIT = "rate_limit",// 429 - too many requests
210
+ SYSTEM = "system",// 500 - bugs, internal failures, unexpected states
211
+ THIRD_PARTY = "third_party",// 502 - upstream provider failures, API errors
212
+ UNKNOWN = "unknown"
213
+ }
214
+ /**
215
+ * Union type for all error codes across domains
216
+ * Provides type safety for error handling
217
+ */
218
+ type DextoErrorCode = LLMErrorCode | AgentErrorCode | ConfigErrorCode | ContextErrorCode | SessionErrorCode | MCPErrorCode | ToolErrorCode | StorageErrorCode | SystemPromptErrorCode | PreferenceErrorCode | RegistryErrorCode;
219
+ /** Severity of an issue */
220
+ type Severity = 'error' | 'warning';
221
+ /** Generic issue type for validation results */
222
+ interface Issue<C = unknown> {
223
+ code: DextoErrorCode;
224
+ message: string;
225
+ scope: ErrorScope;
226
+ type: ErrorType;
227
+ severity: Severity;
228
+ path?: Array<string | number>;
229
+ context?: C;
230
+ }
231
+
232
+ /**
233
+ * Convert Zod validation errors to standardized Issue format for Result pattern.
234
+ *
235
+ * **Usage Guidelines:**
236
+ * - Use in schema validation functions to convert Zod errors to our Issue format
237
+ * - Allows custom error codes via Zod's params.code field in custom refinements
238
+ * - Falls back to SCHEMA_VALIDATION code for standard Zod validation errors
239
+ * - Typically used with severity: 'error' for blocking validation failures
240
+ *
241
+ * @param err - ZodError from failed schema validation
242
+ * @param severity - Issue severity level (defaults to 'error')
243
+ * @returns Array of Issues in our standardized format
244
+ *
245
+ * @example
246
+ * ```typescript
247
+ * // In a validation function
248
+ * const result = MySchema.safeParse(data);
249
+ * if (!result.success) {
250
+ * const issues = zodToIssues(result.error);
251
+ * return fail(issues);
252
+ * }
253
+ *
254
+ * // Custom error codes in Zod schema
255
+ * const schema = z.string().refine(val => val.length > 0, {
256
+ * message: 'Field is required',
257
+ * params: { code: LLMErrorCode.API_KEY_MISSING }
258
+ * });
259
+ * ```
260
+ */
261
+ declare function zodToIssues<C = unknown>(err: ZodError, severity?: 'error' | 'warning'): Issue<C>[];
262
+
263
+ declare const LLM_PROVIDERS: readonly ["openai", "openai-compatible", "anthropic", "google", "groq", "xai", "cohere"];
264
+ type LLMProvider = (typeof LLM_PROVIDERS)[number];
265
+ declare const LLM_ROUTERS: readonly ["vercel", "in-built"];
266
+ type LLMRouter = (typeof LLM_ROUTERS)[number];
267
+ declare const SUPPORTED_FILE_TYPES: readonly ["pdf", "image", "audio"];
268
+
269
+ /**
270
+ * Internal representation of a message in a conversation.
271
+ * Standardizes message format across different LLM providers.
272
+ */
273
+ interface ImageData {
274
+ image: string | Uint8Array | Buffer | ArrayBuffer | URL;
275
+ mimeType?: string;
276
+ }
277
+ interface FileData {
278
+ data: string | Uint8Array | Buffer | ArrayBuffer | URL;
279
+ mimeType: string;
280
+ filename?: string;
281
+ }
282
+ interface TextPart {
283
+ type: 'text';
284
+ text: string;
285
+ }
286
+ interface ImagePart extends ImageData {
287
+ type: 'image';
288
+ }
289
+ interface FilePart extends FileData {
290
+ type: 'file';
291
+ }
292
+ interface InternalMessage {
293
+ /**
294
+ * The role of the entity sending the message.
295
+ * - 'system': System instructions or context
296
+ * - 'user': End-user input
297
+ * - 'assistant': LLM response
298
+ * - 'tool': Result from a tool execution
299
+ */
300
+ role: 'system' | 'user' | 'assistant' | 'tool';
301
+ /**
302
+ * Timestamp when the message was created (Unix timestamp in milliseconds).
303
+ * TODO: Populate this field when messages are created. Currently not implemented.
304
+ * @see https://github.com/truffle-ai/dexto/issues/XXX
305
+ */
306
+ timestamp?: number;
307
+ /**
308
+ * The content of the message.
309
+ * - String for system, assistant (text only), and tool messages.
310
+ * - Array of parts for user messages (can include text, images, and files).
311
+ * - null if an assistant message only contains tool calls.
312
+ */
313
+ content: string | null | Array<TextPart | ImagePart | FilePart>;
314
+ /**
315
+ * Optional model reasoning text associated with an assistant response.
316
+ * Present when the provider supports reasoning and returns a final reasoning trace.
317
+ */
318
+ reasoning?: string;
319
+ /**
320
+ * Optional token usage accounting for this assistant response.
321
+ */
322
+ tokenUsage?: {
323
+ inputTokens?: number;
324
+ outputTokens?: number;
325
+ reasoningTokens?: number;
326
+ totalTokens?: number;
327
+ };
328
+ /**
329
+ * Optional model identifier for assistant messages.
330
+ * Indicates which LLM model generated this response.
331
+ */
332
+ model?: string;
333
+ /** Optional provider identifier for assistant messages. */
334
+ provider?: LLMProvider;
335
+ /**
336
+ * Optional router metadata for assistant messages.
337
+ * Indicates which router was used to route the request.
338
+ */
339
+ router?: LLMRouter;
340
+ /**
341
+ * Tool calls made by the assistant.
342
+ * Only present in assistant messages when the LLM requests tool execution.
343
+ */
344
+ toolCalls?: Array<{
345
+ /**
346
+ * Unique identifier for this tool call
347
+ */
348
+ id: string;
349
+ /**
350
+ * The type of tool call (currently only 'function' is supported)
351
+ */
352
+ type: 'function';
353
+ /**
354
+ * Function call details
355
+ */
356
+ function: {
357
+ /**
358
+ * Name of the function to call
359
+ */
360
+ name: string;
361
+ /**
362
+ * Arguments for the function in JSON string format
363
+ */
364
+ arguments: string;
365
+ };
366
+ }>;
367
+ /**
368
+ * ID of the tool call this message is responding to.
369
+ * Only present in tool messages.
370
+ */
371
+ toolCallId?: string;
372
+ /**
373
+ * Name of the tool that produced this result.
374
+ * Only present in tool messages.
375
+ */
376
+ name?: string;
377
+ }
378
+
379
+ export { type DextoErrorCode, ErrorScope, ErrorType, type FilePart, type ImagePart, type InternalMessage, type Issue, type LLMProvider, type LLMRouter, LLM_PROVIDERS, LLM_ROUTERS, SUPPORTED_FILE_TYPES, type Severity, type TextPart, toError, zodToIssues };