art-framework 0.2.8 → 0.3.0

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.ts CHANGED
@@ -51,47 +51,126 @@ declare class TypedSocket<DataType, FilterType = any> {
51
51
  clearAllSubscriptions(): void;
52
52
  }
53
53
 
54
- /** Entry defining an available provider adapter */
54
+ /**
55
+ * Entry defining an available provider adapter.
56
+ *
57
+ * @interface AvailableProviderEntry
58
+ */
55
59
  interface AvailableProviderEntry {
60
+ /**
61
+ * Unique key, e.g., 'openai', 'anthropic', 'ollama_local'.
62
+ * @property {string} name
63
+ */
56
64
  name: string;
65
+ /**
66
+ * The adapter class.
67
+ * @property {new (options: any) => ProviderAdapter} adapter
68
+ */
57
69
  adapter: new (options: any) => ProviderAdapter;
70
+ /**
71
+ * Optional base config (rarely needed if options are per-call).
72
+ * @property {any} [baseOptions]
73
+ */
58
74
  baseOptions?: any;
75
+ /**
76
+ * Default: false. Determines singleton vs. pooling behavior.
77
+ * @property {boolean} [isLocal]
78
+ */
59
79
  isLocal?: boolean;
60
80
  }
61
- /** Configuration for the ProviderManager passed during ART initialization */
81
+ /**
82
+ * Configuration for the ProviderManager passed during ART initialization.
83
+ *
84
+ * @interface ProviderManagerConfig
85
+ */
62
86
  interface ProviderManagerConfig {
87
+ /**
88
+ * @property {AvailableProviderEntry[]} availableProviders
89
+ */
63
90
  availableProviders: AvailableProviderEntry[];
64
- /** Max concurrent ACTIVE instances per API-based provider NAME. Default: 5 */
91
+ /**
92
+ * Max concurrent ACTIVE instances per API-based provider NAME. Default: 5.
93
+ * @property {number} [maxParallelApiInstancesPerProvider]
94
+ */
65
95
  maxParallelApiInstancesPerProvider?: number;
66
- /** Time in seconds an API adapter instance can be idle before being eligible for removal. Default: 300 */
96
+ /**
97
+ * Time in seconds an API adapter instance can be idle before being eligible for removal. Default: 300.
98
+ * @property {number} [apiInstanceIdleTimeoutSeconds]
99
+ */
67
100
  apiInstanceIdleTimeoutSeconds?: number;
68
101
  }
69
- /** Configuration passed AT RUNTIME for a specific LLM call */
102
+ /**
103
+ * Configuration passed AT RUNTIME for a specific LLM call.
104
+ *
105
+ * @interface RuntimeProviderConfig
106
+ */
70
107
  interface RuntimeProviderConfig {
108
+ /**
109
+ * Must match a name in AvailableProviderEntry.
110
+ * @property {string} providerName
111
+ */
71
112
  providerName: string;
113
+ /**
114
+ * Specific model identifier (e.g., 'gpt-4o', 'llama3:latest').
115
+ * @property {string} modelId
116
+ */
72
117
  modelId: string;
118
+ /**
119
+ * Specific options for THIS instance (apiKey, temperature, contextSize, baseUrl, etc.).
120
+ * @property {any} adapterOptions
121
+ */
73
122
  adapterOptions: any;
74
123
  }
75
- /** Object returned by ProviderManager granting access to an adapter instance */
124
+ /**
125
+ * Object returned by ProviderManager granting access to an adapter instance.
126
+ *
127
+ * @interface ManagedAdapterAccessor
128
+ */
76
129
  interface ManagedAdapterAccessor {
130
+ /**
131
+ * The ready-to-use adapter instance.
132
+ * @property {ProviderAdapter} adapter
133
+ */
77
134
  adapter: ProviderAdapter;
78
- /** Signals that the current call using this adapter instance is finished. */
135
+ /**
136
+ * Signals that the current call using this adapter instance is finished.
137
+ * @property {() => void} release
138
+ */
79
139
  release: () => void;
80
140
  }
81
- /** Interface for the ProviderManager */
141
+ /**
142
+ * Interface for the ProviderManager.
143
+ *
144
+ * @interface IProviderManager
145
+ */
82
146
  interface IProviderManager {
83
- /** Returns identifiers for all registered potential providers */
147
+ /**
148
+ * Returns identifiers for all registered potential providers.
149
+ * @returns {string[]}
150
+ */
84
151
  getAvailableProviders(): string[];
85
152
  /**
86
153
  * Gets a managed adapter instance based on the runtime config.
154
+ *
155
+ * @remarks
87
156
  * Handles instance creation, caching, pooling limits, and singleton constraints.
88
157
  * May queue requests or throw errors based on concurrency limits.
158
+ *
159
+ * @param {RuntimeProviderConfig} config
160
+ * @returns {Promise<ManagedAdapterAccessor>}
89
161
  */
90
162
  getAdapter(config: RuntimeProviderConfig): Promise<ManagedAdapterAccessor>;
91
163
  }
92
164
 
165
+ /**
166
+ * @module utils/logger
167
+ * Provides a simple, static, and configurable logger for the ART framework.
168
+ * It supports different log levels and can be enabled or disabled globally.
169
+ */
93
170
  /**
94
171
  * Defines the available logging levels, ordered from most verbose to least verbose.
172
+ *
173
+ * @enum {number}
95
174
  */
96
175
  declare enum LogLevel {
97
176
  /** Detailed debugging information, useful for development. */
@@ -105,114 +184,276 @@ declare enum LogLevel {
105
184
  }
106
185
  /**
107
186
  * Configuration options for the static Logger class.
187
+ *
188
+ * @interface LoggerConfig
108
189
  */
109
190
  interface LoggerConfig {
110
- /** The minimum log level to output messages for. Messages below this level will be ignored. */
191
+ /**
192
+ * The minimum log level to output messages for. Messages below this level will be ignored.
193
+ * @property {LogLevel} level
194
+ */
111
195
  level: LogLevel;
112
- /** An optional prefix string to prepend to all log messages (e.g., '[MyApp]'). Defaults to '[ART]'. */
196
+ /**
197
+ * An optional prefix string to prepend to all log messages (e.g., '[MyApp]'). Defaults to '[ART]'.
198
+ * @property {string} [prefix]
199
+ */
113
200
  prefix?: string;
114
201
  }
115
202
  /**
116
203
  * A simple static logger class for outputting messages to the console at different levels.
204
+ *
205
+ * @remarks
117
206
  * Configuration is global via the static `configure` method.
207
+ *
208
+ * @class Logger
118
209
  */
119
210
  declare class Logger {
120
211
  private static config;
121
212
  /**
122
213
  * Configures the static logger settings.
123
- * @param config - A partial `LoggerConfig` object. Provided settings will override defaults.
214
+ *
215
+ * @param config A partial `LoggerConfig` object. Provided settings will override defaults.
124
216
  */
125
217
  static configure(config: Partial<LoggerConfig>): void;
126
218
  /**
127
219
  * Logs a message at the DEBUG level.
220
+ *
221
+ * @remarks
128
222
  * Only outputs if the configured log level is DEBUG.
129
- * @param message - The main log message string.
130
- * @param args - Additional arguments to include in the console output (e.g., objects, arrays).
223
+ *
224
+ * @param message The main log message string.
225
+ * @param args Additional arguments to include in the console output (e.g., objects, arrays).
131
226
  */
132
227
  static debug(message: string, ...args: any[]): void;
133
228
  /**
134
229
  * Logs a message at the INFO level.
230
+ *
231
+ * @remarks
135
232
  * Outputs if the configured log level is INFO or DEBUG.
136
- * @param message - The main log message string.
137
- * @param args - Additional arguments to include in the console output.
233
+ *
234
+ * @param message The main log message string.
235
+ * @param args Additional arguments to include in the console output.
138
236
  */
139
237
  static info(message: string, ...args: any[]): void;
140
238
  /**
141
239
  * Logs a message at the WARN level.
240
+ *
241
+ * @remarks
142
242
  * Outputs if the configured log level is WARN, INFO, or DEBUG.
143
- * @param message - The main log message string.
144
- * @param args - Additional arguments to include in the console output.
243
+ *
244
+ * @param message The main log message string.
245
+ * @param args Additional arguments to include in the console output.
145
246
  */
146
247
  static warn(message: string, ...args: any[]): void;
147
248
  /**
148
249
  * Logs a message at the ERROR level.
250
+ *
251
+ * @remarks
149
252
  * Outputs if the configured log level is ERROR, WARN, INFO, or DEBUG.
150
- * @param message - The main log message string.
151
- * @param args - Additional arguments to include in the console output (often an error object).
253
+ *
254
+ * @param message The main log message string.
255
+ * @param args Additional arguments to include in the console output (often an error object).
152
256
  */
153
257
  static error(message: string, ...args: any[]): void;
154
258
  }
155
259
 
156
260
  /**
157
261
  * Defines standard error codes for the ART framework.
262
+ * These codes categorize errors originating from different subsystems.
158
263
  */
159
264
  declare enum ErrorCode {
265
+ /** Invalid or malformed configuration provided. */
160
266
  INVALID_CONFIG = "INVALID_CONFIG",
161
- MISSING_API_KEY = "MISSING_API_KEY",
267
+ /** A required API key was not provided. */
268
+ MISSING_API_key = "MISSING_API_KEY",
269
+ /** General configuration-related error. */
270
+ CONFIGURATION_ERROR = "CONFIGURATION_ERROR",
271
+ /** A generic error occurred in the storage layer. */
162
272
  STORAGE_ERROR = "STORAGE_ERROR",
273
+ /** The requested thread could not be found in storage. */
163
274
  THREAD_NOT_FOUND = "THREAD_NOT_FOUND",
275
+ /** Failed to save data to the storage layer. */
164
276
  SAVE_FAILED = "SAVE_FAILED",
277
+ /** An error occurred while communicating with the LLM provider. */
165
278
  LLM_PROVIDER_ERROR = "LLM_PROVIDER_ERROR",
279
+ /** Failed to generate a prompt. */
166
280
  PROMPT_GENERATION_FAILED = "PROMPT_GENERATION_FAILED",
281
+ /** Failed to parse the output from the LLM. */
167
282
  OUTPUT_PARSING_FAILED = "OUTPUT_PARSING_FAILED",
168
- PROMPT_ASSEMBLY_FAILED = "PROMPT_ASSEMBLY_FAILED",// Error during prompt template rendering or initial structure creation (legacy, might be removed)
169
- PROMPT_FRAGMENT_NOT_FOUND = "PROMPT_FRAGMENT_NOT_FOUND",// Requested prompt fragment does not exist
170
- PROMPT_VALIDATION_FAILED = "PROMPT_VALIDATION_FAILED",// Constructed prompt object failed schema validation
171
- PROMPT_TRANSLATION_FAILED = "PROMPT_TRANSLATION_FAILED",// Added for Adapter translation
283
+ /** Error during prompt template rendering or initial structure creation. */
284
+ PROMPT_ASSEMBLY_FAILED = "PROMPT_ASSEMBLY_FAILED",
285
+ /** The requested prompt fragment does not exist. */
286
+ PROMPT_FRAGMENT_NOT_FOUND = "PROMPT_FRAGMENT_NOT_FOUND",
287
+ /** The constructed prompt object failed schema validation. */
288
+ PROMPT_VALIDATION_FAILED = "PROMPT_VALIDATION_FAILED",
289
+ /** Failed to translate the ART standard prompt to a provider-specific format. */
290
+ PROMPT_TRANSLATION_FAILED = "PROMPT_TRANSLATION_FAILED",
291
+ /** The requested tool could not be found in the registry. */
172
292
  TOOL_NOT_FOUND = "TOOL_NOT_FOUND",
293
+ /** The provided tool schema failed validation. */
173
294
  TOOL_SCHEMA_VALIDATION_FAILED = "TOOL_SCHEMA_VALIDATION_FAILED",
174
- TOOL_EXECUTION_ERROR = "TOOL_EXECUTION_ERROR",// Generic tool execution error
295
+ /** A generic error occurred during tool execution. */
296
+ TOOL_EXECUTION_ERROR = "TOOL_EXECUTION_ERROR",
297
+ /** The requested tool is disabled for the current thread. */
175
298
  TOOL_DISABLED = "TOOL_DISABLED",
299
+ /** The planning phase of the agent failed. */
176
300
  PLANNING_FAILED = "PLANNING_FAILED",
177
- TOOL_EXECUTION_FAILED = "TOOL_EXECUTION_FAILED",// Error within the ToolSystem execution loop
301
+ /** An error occurred within the ToolSystem execution loop. */
302
+ TOOL_EXECUTION_FAILED = "TOOL_EXECUTION_FAILED",
303
+ /** The synthesis phase of the agent failed. */
178
304
  SYNTHESIS_FAILED = "SYNTHESIS_FAILED",
179
- AGENT_PROCESSING_ERROR = "AGENT_PROCESSING_ERROR",// General error during agent.process
305
+ /** A general error occurred during the agent's process method. */
306
+ AGENT_PROCESSING_ERROR = "AGENT_PROCESSING_ERROR",
307
+ /** An A2A (Agent-to-Agent) task delegation failed. */
308
+ DELEGATION_FAILED = "DELEGATION_FAILED",
309
+ /** A network error occurred. */
180
310
  NETWORK_ERROR = "NETWORK_ERROR",
311
+ /** An operation timed out. */
181
312
  TIMEOUT_ERROR = "TIMEOUT_ERROR",
313
+ /** An operation timed out (duplicate of TIMEOUT_ERROR). */
314
+ TIMEOUT = "TIMEOUT",
315
+ /** An error occurred with an external service. */
316
+ EXTERNAL_SERVICE_ERROR = "EXTERNAL_SERVICE_ERROR",
317
+ /** The requested task was not found. */
318
+ TASK_NOT_FOUND = "TASK_NOT_FOUND",
319
+ /** Input data failed validation. */
320
+ VALIDATION_ERROR = "VALIDATION_ERROR",
321
+ /** The request was invalid or malformed. */
322
+ INVALID_REQUEST = "INVALID_REQUEST",
323
+ /** A task with the same ID already exists. */
324
+ DUPLICATE_TASK_ID = "DUPLICATE_TASK_ID",
325
+ /** A generic error occurred in a repository. */
326
+ REPOSITORY_ERROR = "REPOSITORY_ERROR",
327
+ /** A connection is already established. */
328
+ ALREADY_CONNECTED = "ALREADY_CONNECTED",
329
+ /** A required configuration is missing. */
330
+ MISSING_CONFIG = "MISSING_CONFIG",
331
+ /** The requested feature is not implemented. */
332
+ NOT_IMPLEMENTED = "NOT_IMPLEMENTED",
333
+ /** No active connection is available. */
334
+ NOT_CONNECTED = "NOT_CONNECTED",
335
+ /** The request timed out. */
336
+ REQUEST_TIMEOUT = "REQUEST_TIMEOUT",
337
+ /** Standard input is not available. */
338
+ NO_STDIN = "NO_STDIN",
339
+ /** The provided URL is not an HTTP/HTTPS URL. */
340
+ NO_HTTP_URL = "NO_HTTP_URL",
341
+ /** An HTTP error occurred. */
342
+ HTTP_ERROR = "HTTP_ERROR",
343
+ /** The requested server was not found. */
344
+ SERVER_NOT_FOUND = "SERVER_NOT_FOUND",
345
+ /** A health check for a service failed. */
346
+ HEALTH_CHECK_FAILED = "HEALTH_CHECK_FAILED",
347
+ /** Failed to discover tools from a remote source. */
348
+ TOOL_DISCOVERY_FAILED = "TOOL_DISCOVERY_FAILED",
349
+ /** The requested transport protocol is not supported. */
350
+ UNSUPPORTED_TRANSPORT = "UNSUPPORTed_TRANSPORT",
351
+ /** A CORS browser extension is required to proceed. */
352
+ CORS_EXTENSION_REQUIRED = "CORS_EXTENSION_REQUIRED",
353
+ /** CORS permissions are required but have not been granted. */
354
+ CORS_PERMISSION_REQUIRED = "CORS_PERMISSION_REQUIRED",
355
+ /** An unknown or unexpected error occurred. */
182
356
  UNKNOWN_ERROR = "UNKNOWN_ERROR",
183
- UNKNOWN_PROVIDER = "UNKNOWN_PROVIDER",// Checklist item 4.7
184
- LOCAL_PROVIDER_CONFLICT = "LOCAL_PROVIDER_CONFLICT",// Checklist item 4.7
185
- LOCAL_INSTANCE_BUSY = "LOCAL_INSTANCE_BUSY",// Checklist item 4.7
186
- API_QUEUE_TIMEOUT = "API_QUEUE_TIMEOUT",// Checklist item 4.7 (optional)
357
+ /** The requested LLM provider is not known or configured. */
358
+ UNKNOWN_PROVIDER = "UNKNOWN_PROVIDER",
359
+ /** Attempted to activate a local provider when another is already active. */
360
+ LOCAL_PROVIDER_CONFLICT = "LOCAL_PROVIDER_CONFLICT",
361
+ /** The requested local LLM instance is currently busy. */
362
+ LOCAL_INSTANCE_BUSY = "LOCAL_INSTANCE_BUSY",
363
+ /** Timeout waiting for an available instance of an API provider. */
364
+ API_QUEUE_TIMEOUT = "API_QUEUE_TIMEOUT",
365
+ /** Failed to instantiate an adapter for a provider. */
187
366
  ADAPTER_INSTANTIATION_ERROR = "ADAPTER_INSTANTIATION_ERROR"
188
367
  }
189
368
  /**
190
369
  * Custom error class for ART framework specific errors.
370
+ * It includes an error code, an optional original error for chaining,
371
+ * and a details object for additional context.
191
372
  */
192
373
  declare class ARTError extends Error {
374
+ /** The specific error code from the ErrorCode enum. */
193
375
  readonly code: ErrorCode;
376
+ /** The original error that caused this error, if any. */
194
377
  readonly originalError?: Error;
195
- constructor(message: string, code: ErrorCode, originalError?: Error);
378
+ /** A record of additional details about the error. */
379
+ details: Record<string, any>;
380
+ /**
381
+ * Creates an instance of ARTError.
382
+ * @param {string} message - The error message.
383
+ * @param {ErrorCode} code - The error code.
384
+ * @param {Error} [originalError] - The original error, if any.
385
+ * @param {Record<string, any>} [details={}] - Additional details about the error.
386
+ */
387
+ constructor(message: string, code: ErrorCode, originalError?: Error, details?: Record<string, any>);
388
+ /**
389
+ * Returns a string representation of the error, including the original error if present.
390
+ * @returns {string} The string representation of the error.
391
+ */
196
392
  toString(): string;
197
393
  }
394
+ /**
395
+ * Error thrown when a requested LLM provider is not known or configured.
396
+ */
198
397
  declare class UnknownProviderError extends ARTError {
199
398
  constructor(providerName: string);
200
399
  }
400
+ /**
401
+ * Error thrown when attempting to activate a local provider while another is already active.
402
+ */
201
403
  declare class LocalProviderConflictError extends ARTError {
202
404
  constructor(requestedProvider: string, activeProvider: string);
203
405
  }
406
+ /**
407
+ * Error thrown when a requested local LLM instance is currently busy.
408
+ */
204
409
  declare class LocalInstanceBusyError extends ARTError {
205
410
  constructor(providerName: string, modelId: string);
206
411
  }
412
+ /**
413
+ * Error thrown when a timeout occurs while waiting for an available instance of an API provider.
414
+ */
207
415
  declare class ApiQueueTimeoutError extends ARTError {
208
416
  constructor(providerName: string);
209
417
  }
418
+ /**
419
+ * Error thrown when an adapter for a provider fails to instantiate.
420
+ */
210
421
  declare class AdapterInstantiationError extends ARTError {
211
422
  constructor(providerName: string, originalError: Error);
212
423
  }
213
424
 
425
+ type StreamEventTypeFilter = StreamEvent['type'] | Array<StreamEvent['type']>;
426
+ /**
427
+ * A dedicated socket for broadcasting LLM stream events (`StreamEvent`) to UI subscribers.
428
+ * Extends the generic TypedSocket and implements filtering based on `StreamEvent.type`.
429
+ */
430
+ declare class LLMStreamSocket extends TypedSocket<StreamEvent, StreamEventTypeFilter> {
431
+ constructor();
432
+ /**
433
+ * Notifies subscribers about a new LLM stream event.
434
+ * Filters based on event type if a filter is provided during subscription.
435
+ * @param event - The StreamEvent data.
436
+ */
437
+ notifyStreamEvent(event: StreamEvent): void;
438
+ }
439
+
440
+ /**
441
+ * @module types/schemas
442
+ * This module defines Zod schemas for validating the core data structures of the ART framework,
443
+ * ensuring type safety and data integrity at runtime.
444
+ */
445
+
214
446
  /**
215
- * Zod schema for validating a single ArtStandardMessage object.
447
+ * Zod schema for validating a single {@link ArtStandardMessage} object.
448
+ *
449
+ * @remarks
450
+ * This schema enforces the structural and type requirements for each message, including:
451
+ * - A valid `role` from the {@link ArtStandardMessageRole} enum.
452
+ * - `content` that matches the expected type for a given role (e.g., string for 'user', string or null for 'assistant').
453
+ * - The presence of `tool_call_id` for 'tool' or 'tool_result' roles.
454
+ * - The structure of `tool_calls` when present in an 'assistant' message.
455
+ *
456
+ * It uses a `.refine()` method to implement context-aware validation based on the message's `role`.
216
457
  */
217
458
  declare const ArtStandardMessageSchema: z.ZodEffects<z.ZodObject<{
218
459
  role: z.ZodType<ArtStandardMessageRole, z.ZodTypeDef, ArtStandardMessageRole>;
@@ -301,7 +542,11 @@ declare const ArtStandardMessageSchema: z.ZodEffects<z.ZodObject<{
301
542
  tool_call_id?: string | undefined;
302
543
  }>;
303
544
  /**
304
- * Zod schema for validating an entire ArtStandardPrompt (an array of messages).
545
+ * Zod schema for validating an entire {@link ArtStandardPrompt} (an array of messages).
546
+ *
547
+ * @remarks
548
+ * This is a straightforward array schema that applies the {@link ArtStandardMessageSchema} to each element,
549
+ * ensuring that every message in the prompt conforms to the required structure.
305
550
  */
306
551
  declare const ArtStandardPromptSchema: z.ZodArray<z.ZodEffects<z.ZodObject<{
307
552
  role: z.ZodType<ArtStandardMessageRole, z.ZodTypeDef, ArtStandardMessageRole>;
@@ -390,38 +635,352 @@ declare const ArtStandardPromptSchema: z.ZodArray<z.ZodEffects<z.ZodObject<{
390
635
  tool_call_id?: string | undefined;
391
636
  }>, "many">;
392
637
 
638
+ /**
639
+ * @module systems/mcp/types
640
+ * This module defines the public and internal types used for configuring
641
+ * and managing the state of the MCP (Multi-Capability Provider) system.
642
+ */
643
+ /**
644
+ * Defines the connection details for a streamable HTTP-based MCP server.
645
+ * This is the primary transport mechanism for browser-based MCP communication.
646
+ *
647
+ * @interface StreamableHttpConnection
648
+ */
649
+ interface StreamableHttpConnection {
650
+ /**
651
+ * The base URL of the MCP server.
652
+ * @property {string} url
653
+ */
654
+ url: string;
655
+ /**
656
+ * Optional headers to include in every request to the server.
657
+ * @property {Record<string, string>} [headers]
658
+ */
659
+ headers?: Record<string, string>;
660
+ /**
661
+ * The ID of an authentication strategy to use for this connection.
662
+ * @property {string} [authStrategyId]
663
+ */
664
+ authStrategyId?: string;
665
+ /**
666
+ * Optional OAuth configuration for automatic PKCE setup per server.
667
+ * This enables secure, per-server authentication without manual token handling.
668
+ * @property {object} [oauth]
669
+ */
670
+ oauth?: {
671
+ /**
672
+ * The type of OAuth flow, currently supporting 'pkce'.
673
+ * @property {'pkce'} type
674
+ */
675
+ type: 'pkce';
676
+ /**
677
+ * The OAuth 2.1 Authorization Endpoint URL.
678
+ * @property {string} authorizationEndpoint
679
+ */
680
+ authorizationEndpoint: string;
681
+ /**
682
+ * The OAuth 2.1 Token Endpoint URL.
683
+ * @property {string} tokenEndpoint
684
+ */
685
+ tokenEndpoint: string;
686
+ /**
687
+ * The public client ID for the OAuth application.
688
+ * @property {string} clientId
689
+ */
690
+ clientId: string;
691
+ /**
692
+ * A space-delimited string of OAuth scopes to request.
693
+ * @property {string} scopes
694
+ */
695
+ scopes: string;
696
+ /**
697
+ * The redirect URI that will handle the OAuth callback.
698
+ * @property {string} redirectUri
699
+ */
700
+ redirectUri: string;
701
+ /**
702
+ * Optional 'resource' parameter for OAuth 2.1, often used as an audience identifier.
703
+ * @property {string} [resource]
704
+ */
705
+ resource?: string;
706
+ /**
707
+ * Determines whether to open the login page in a new tab.
708
+ * Defaults to true if omitted.
709
+ * @property {boolean} [openInNewTab]
710
+ */
711
+ openInNewTab?: boolean;
712
+ /**
713
+ * An optional BroadcastChannel name for delivering tokens, useful in multi-window scenarios.
714
+ * @property {string} [channelName]
715
+ */
716
+ channelName?: string;
717
+ };
718
+ }
719
+ /**
720
+ * Defines the schema for a tool provided by an MCP server.
721
+ *
722
+ * @interface McpToolDefinition
723
+ */
724
+ interface McpToolDefinition {
725
+ /**
726
+ * The name of the tool.
727
+ * @property {string} name
728
+ */
729
+ name: string;
730
+ /**
731
+ * A description of what the tool does.
732
+ * @property {string} [description]
733
+ */
734
+ description?: string;
735
+ /**
736
+ * The JSON schema for the tool's input.
737
+ * @property {any} inputSchema
738
+ */
739
+ inputSchema: any;
740
+ /**
741
+ * The JSON schema for the tool's output.
742
+ * @property {any} [outputSchema]
743
+ */
744
+ outputSchema?: any;
745
+ }
746
+ /**
747
+ * Defines a static resource provided by an MCP server.
748
+ *
749
+ * @interface McpResource
750
+ */
751
+ interface McpResource {
752
+ /**
753
+ * The URI of the resource.
754
+ * @property {string} uri
755
+ */
756
+ uri: string;
757
+ /**
758
+ * The name of the resource.
759
+ * @property {string} name
760
+ */
761
+ name: string;
762
+ /**
763
+ * The MIME type of the resource.
764
+ * @property {string} [mimeType]
765
+ */
766
+ mimeType?: string;
767
+ /**
768
+ * A description of the resource.
769
+ * @property {string} [description]
770
+ */
771
+ description?: string;
772
+ }
773
+ /**
774
+ * Defines a template for a resource provided by an MCP server.
775
+ *
776
+ * @interface McpResourceTemplate
777
+ */
778
+ interface McpResourceTemplate {
779
+ /**
780
+ * The URI template for the resource.
781
+ * @property {string} uriTemplate
782
+ */
783
+ uriTemplate: string;
784
+ /**
785
+ * The name of the resource template.
786
+ * @property {string} name
787
+ */
788
+ name: string;
789
+ /**
790
+ * A description of the resource template.
791
+ * @property {string} [description]
792
+ */
793
+ description?: string;
794
+ /**
795
+ * The MIME type of the resource.
796
+ * @property {string} [mimeType]
797
+ */
798
+ mimeType?: string;
799
+ }
800
+ /**
801
+ * Represents the configuration for a single MCP server.
802
+ *
803
+ * @remarks
804
+ * This is the format for each server entry in the `art_mcp_config.json` file.
805
+ * It contains all the necessary information for discovering, installing, and connecting to an MCP server.
806
+ *
807
+ * @typedef {object} McpServerConfig
808
+ */
809
+ type McpServerConfig = {
810
+ /**
811
+ * A unique identifier for the server.
812
+ * @property {string} id
813
+ */
814
+ id: string;
815
+ /**
816
+ * The transport type for the server, currently only 'streamable-http' is supported.
817
+ * @property {'streamable-http'} type
818
+ */
819
+ type: 'streamable-http';
820
+ /**
821
+ * Whether the server is enabled and should be connected to.
822
+ * @property {boolean} enabled
823
+ */
824
+ enabled: boolean;
825
+ /**
826
+ * A user-friendly name for the server.
827
+ * @property {string} [displayName]
828
+ */
829
+ displayName?: string;
830
+ /**
831
+ * A description of the server and its capabilities.
832
+ * @property {string} [description]
833
+ */
834
+ description?: string;
835
+ /**
836
+ * The connection details for the server.
837
+ * @see module:systems/mcp/types.StreamableHttpConnection
838
+ */
839
+ connection: StreamableHttpConnection;
840
+ /**
841
+ * Information about how the server was installed (e.g., 'git', 'npm', 'manual').
842
+ * @property {object} [installation]
843
+ */
844
+ installation?: {
845
+ source: 'git' | 'npm' | 'manual';
846
+ [key: string]: any;
847
+ };
848
+ /**
849
+ * The timeout in milliseconds for requests to the server.
850
+ * @property {number} [timeout]
851
+ */
852
+ timeout?: number;
853
+ /**
854
+ * The tools provided by the server.
855
+ * @property {McpToolDefinition[]} tools
856
+ */
857
+ tools: McpToolDefinition[];
858
+ /**
859
+ * The static resources provided by the server.
860
+ * @property {McpResource[]} resources
861
+ */
862
+ resources: McpResource[];
863
+ /**
864
+ * The resource templates provided by the server.
865
+ * @property {McpResourceTemplate[]} resourceTemplates
866
+ */
867
+ resourceTemplates: McpResourceTemplate[];
868
+ };
869
+ /**
870
+ * Represents the internal status of an MCP server connection.
871
+ * This is not part of the public configuration.
872
+ *
873
+ * @interface McpServerStatus
874
+ */
875
+ interface McpServerStatus {
876
+ /**
877
+ * The unique identifier for the server.
878
+ * @property {string} id
879
+ */
880
+ id: string;
881
+ /**
882
+ * The current connection status of the server.
883
+ * @property {'connected' | 'disconnected' | 'error' | 'connecting'} status
884
+ */
885
+ status: 'connected' | 'disconnected' | 'error' | 'connecting';
886
+ /**
887
+ * The timestamp of the last successful connection.
888
+ * @property {Date} [lastConnected]
889
+ */
890
+ lastConnected?: Date;
891
+ /**
892
+ * The last error message received from the server.
893
+ * @property {string} [lastError]
894
+ */
895
+ lastError?: string;
896
+ /**
897
+ * The number of tools registered from this server.
898
+ * @property {number} toolCount
899
+ */
900
+ toolCount: number;
901
+ }
902
+ /**
903
+ * Defines the configuration for the McpManager.
904
+ *
905
+ * @interface McpManagerConfig
906
+ */
907
+ interface McpManagerConfig {
908
+ /**
909
+ * Whether to enable MCP functionality. Defaults to false.
910
+ * @property {boolean} enabled
911
+ */
912
+ enabled: boolean;
913
+ /**
914
+ * An optional endpoint URL for discovering MCP servers.
915
+ * Defaults to the Zyntopia API if not provided.
916
+ * @property {string} [discoveryEndpoint]
917
+ */
918
+ discoveryEndpoint?: string;
919
+ }
920
+
393
921
  /**
394
922
  * Represents the role of a message sender in a conversation.
923
+ *
924
+ * @enum {string}
395
925
  */
396
926
  declare enum MessageRole {
927
+ /** The end-user interacting with the agent. */
397
928
  USER = "USER",
929
+ /** The AI agent. */
398
930
  AI = "AI",
399
- SYSTEM = "SYSTEM",// Added for system prompts, though not explicitly in checklist message interface
931
+ /** A system-level message providing context or instructions. */
932
+ SYSTEM = "SYSTEM",
933
+ /** A message containing the result of a tool execution. */
400
934
  TOOL = "TOOL"
401
935
  }
402
936
  /**
403
937
  * Represents a single message within a conversation thread.
938
+ *
939
+ * @interface ConversationMessage
404
940
  */
405
941
  interface ConversationMessage {
406
- /** A unique identifier for this specific message. */
942
+ /**
943
+ * A unique identifier for this specific message.
944
+ * @property {string} messageId
945
+ */
407
946
  messageId: string;
408
- /** The identifier of the conversation thread this message belongs to. */
947
+ /**
948
+ * The identifier of the conversation thread this message belongs to.
949
+ * @property {string} threadId
950
+ */
409
951
  threadId: string;
410
- /** The role of the sender (User, AI, System, or Tool). */
952
+ /**
953
+ * The role of the sender (User, AI, System, or Tool).
954
+ * @property {MessageRole} role
955
+ */
411
956
  role: MessageRole;
412
- /** The textual content of the message. */
957
+ /**
958
+ * The textual content of the message.
959
+ * @property {string} content
960
+ */
413
961
  content: string;
414
- /** A Unix timestamp (in milliseconds) indicating when the message was created. */
962
+ /**
963
+ * A Unix timestamp (in milliseconds) indicating when the message was created.
964
+ * @property {number} timestamp
965
+ */
415
966
  timestamp: number;
416
- /** Optional metadata associated with the message (e.g., related observation IDs, tool call info, UI state). */
967
+ /**
968
+ * Optional metadata associated with the message (e.g., related observation IDs, tool call info, UI state).
969
+ * @property {Record<string, any>} [metadata]
970
+ */
417
971
  metadata?: Record<string, any>;
418
972
  }
419
973
  /**
420
974
  * Represents the type of an observation record, capturing significant events during agent execution.
975
+ *
976
+ * @enum {string}
421
977
  */
422
978
  declare enum ObservationType {
979
+ /** The user's inferred intent. */
423
980
  INTENT = "INTENT",
981
+ /** The agent's step-by-step plan to address the intent. */
424
982
  PLAN = "PLAN",
983
+ /** The agent's internal monologue or reasoning process. */
425
984
  THOUGHTS = "THOUGHTS",
426
985
  /** Records the LLM's decision to call one or more tools (part of the plan). */
427
986
  TOOL_CALL = "TOOL_CALL",
@@ -447,49 +1006,89 @@ declare enum ObservationType {
447
1006
  /**
448
1007
  * Represents the different capabilities a model might possess.
449
1008
  * Used for model selection and validation.
1009
+ *
1010
+ * @enum {string}
450
1011
  */
451
1012
  declare enum ModelCapability {
452
- TEXT = "text",// Basic text generation/understanding
453
- VISION = "vision",// Ability to process and understand images
454
- STREAMING = "streaming",// Supports streaming responses chunk by chunk
455
- TOOL_USE = "tool_use",// Capable of using tools/function calling
456
- RAG = "rag",// Built-in or optimized for Retrieval-Augmented Generation
457
- CODE = "code",// Specialized in understanding or generating code
1013
+ /** Basic text generation/understanding. */
1014
+ TEXT = "text",
1015
+ /** Ability to process and understand images. */
1016
+ VISION = "vision",
1017
+ /** Supports streaming responses chunk by chunk. */
1018
+ STREAMING = "streaming",
1019
+ /** Capable of using tools/function calling. */
1020
+ TOOL_USE = "tool_use",
1021
+ /** Built-in or optimized for Retrieval-Augmented Generation. */
1022
+ RAG = "rag",
1023
+ /** Specialized in understanding or generating code. */
1024
+ CODE = "code",
1025
+ /** Advanced reasoning, planning, complex instruction following. */
458
1026
  REASONING = "reasoning"
459
1027
  }
460
1028
  /**
461
1029
  * Represents a recorded event during the agent's execution.
1030
+ *
1031
+ * @interface Observation
462
1032
  */
463
1033
  interface Observation {
464
- /** A unique identifier for this specific observation record. */
1034
+ /**
1035
+ * A unique identifier for this specific observation record.
1036
+ * @property {string} id
1037
+ */
465
1038
  id: string;
466
- /** The identifier of the conversation thread this observation relates to. */
1039
+ /**
1040
+ * The identifier of the conversation thread this observation relates to.
1041
+ * @property {string} threadId
1042
+ */
467
1043
  threadId: string;
468
- /** An optional identifier for tracing a request across multiple systems or components. */
1044
+ /**
1045
+ * An optional identifier for tracing a request across multiple systems or components.
1046
+ * @property {string} [traceId]
1047
+ */
469
1048
  traceId?: string;
470
- /** A Unix timestamp (in milliseconds) indicating when the observation was recorded. */
1049
+ /**
1050
+ * A Unix timestamp (in milliseconds) indicating when the observation was recorded.
1051
+ * @property {number} timestamp
1052
+ */
471
1053
  timestamp: number;
472
- /** The category of the event being observed (e.g., PLAN, THOUGHTS, TOOL_EXECUTION). */
1054
+ /**
1055
+ * The category of the event being observed (e.g., PLAN, THOUGHTS, TOOL_EXECUTION).
1056
+ * @property {ObservationType} type
1057
+ */
473
1058
  type: ObservationType;
474
- /** A concise, human-readable title summarizing the observation (often generated based on type/metadata). */
1059
+ /**
1060
+ * A concise, human-readable title summarizing the observation (often generated based on type/metadata).
1061
+ * @property {string} title
1062
+ */
475
1063
  title: string;
476
- /** The main data payload of the observation, structure depends on the `type`. */
1064
+ /**
1065
+ * The main data payload of the observation, structure depends on the `type`.
1066
+ * @property {any} content
1067
+ */
477
1068
  content: any;
478
- /** Optional metadata providing additional context (e.g., source phase, related IDs, status). */
1069
+ /**
1070
+ * Optional metadata providing additional context (e.g., source phase, related IDs, status).
1071
+ * @property {Record<string, any>} [metadata]
1072
+ */
479
1073
  metadata?: Record<string, any>;
480
1074
  }
481
1075
  /**
482
1076
  * Represents a single event emitted from an asynchronous LLM stream (`ReasoningEngine.call`).
1077
+ *
1078
+ * @remarks
483
1079
  * Allows for real-time delivery of tokens, metadata, errors, and lifecycle signals.
484
1080
  * Adapters are responsible for translating provider-specific stream chunks into these standard events.
1081
+ *
1082
+ * @interface StreamEvent
485
1083
  */
486
1084
  interface StreamEvent {
487
1085
  /**
488
- * The type of the stream event:
1086
+ * The type of the stream event.
489
1087
  * - `TOKEN`: A chunk of text generated by the LLM.
490
1088
  * - `METADATA`: Information about the LLM call (e.g., token counts, stop reason), typically sent once at the end.
491
1089
  * - `ERROR`: An error occurred during the LLM call or stream processing. `data` will contain the Error object.
492
1090
  * - `END`: Signals the successful completion of the stream. `data` is typically null.
1091
+ * @property {'TOKEN' | 'METADATA' | 'ERROR' | 'END'} type
493
1092
  */
494
1093
  type: 'TOKEN' | 'METADATA' | 'ERROR' | 'END';
495
1094
  /**
@@ -498,6 +1097,7 @@ interface StreamEvent {
498
1097
  * - For `METADATA`: `LLMMetadata` object.
499
1098
  * - For `ERROR`: `Error` object or error details.
500
1099
  * - For `END`: null.
1100
+ * @property {any} data
501
1101
  */
502
1102
  data: any;
503
1103
  /**
@@ -513,24 +1113,43 @@ interface StreamEvent {
513
1113
  * - `FINAL_SYNTHESIS_LLM_THINKING`: Token from an LLM call made in the 'FINAL_SYNTHESIS' context, identified as thinking.
514
1114
  * - `FINAL_SYNTHESIS_LLM_RESPONSE`: Token from an LLM call made in the 'FINAL_SYNTHESIS' context, identified as response (part of the final answer to the user).
515
1115
  *
516
- * Note: Not all adapters can reliably distinguish 'LLM_THINKING' vs 'LLM_RESPONSE'.
1116
+ * @remarks
1117
+ * Not all adapters can reliably distinguish 'LLM_THINKING' vs 'LLM_RESPONSE'.
517
1118
  * Adapters should prioritize setting the agent context part (`AGENT_THOUGHT_...` or `FINAL_SYNTHESIS_...`) based on `CallOptions.callContext`.
518
1119
  * If thinking detection is unavailable, adapters should default to `AGENT_THOUGHT_LLM_RESPONSE` or `FINAL_SYNTHESIS_LLM_RESPONSE`.
1120
+ * @property {'LLM_THINKING' | 'LLM_RESPONSE' | 'AGENT_THOUGHT_LLM_THINKING' | 'AGENT_THOUGHT_LLM_RESPONSE' | 'FINAL_SYNTHESIS_LLM_THINKING' | 'FINAL_SYNTHESIS_LLM_RESPONSE'} [tokenType]
519
1121
  */
520
1122
  tokenType?: 'LLM_THINKING' | 'LLM_RESPONSE' | 'AGENT_THOUGHT_LLM_THINKING' | 'AGENT_THOUGHT_LLM_RESPONSE' | 'FINAL_SYNTHESIS_LLM_THINKING' | 'FINAL_SYNTHESIS_LLM_RESPONSE';
521
- /** The identifier of the conversation thread this event belongs to. */
1123
+ /**
1124
+ * The identifier of the conversation thread this event belongs to.
1125
+ * @property {string} threadId
1126
+ */
522
1127
  threadId: string;
523
- /** The identifier tracing the specific agent execution cycle this event is part of. */
1128
+ /**
1129
+ * The identifier tracing the specific agent execution cycle this event is part of.
1130
+ * @property {string} traceId
1131
+ */
524
1132
  traceId: string;
525
- /** Optional identifier linking the event to a specific UI tab/window. */
1133
+ /**
1134
+ * Optional identifier linking the event to a specific UI tab/window.
1135
+ * @property {string} [sessionId]
1136
+ */
526
1137
  sessionId?: string;
527
1138
  }
528
1139
  /**
529
1140
  * Represents a basic JSON Schema definition, focusing on object types commonly used for tool inputs/outputs.
530
1141
  * This is a simplified representation and doesn't cover all JSON Schema features.
1142
+ *
1143
+ * @interface JsonObjectSchema
531
1144
  */
532
1145
  interface JsonObjectSchema {
1146
+ /**
1147
+ * @property {'object'} type
1148
+ */
533
1149
  type: 'object';
1150
+ /**
1151
+ * @property {object} properties
1152
+ */
534
1153
  properties: {
535
1154
  [key: string]: {
536
1155
  type: string;
@@ -557,39 +1176,82 @@ type JsonSchema = JsonObjectSchema | {
557
1176
  /**
558
1177
  * Structure for holding metadata about an LLM call, typically received via a `METADATA` `StreamEvent`
559
1178
  * or parsed from a non-streaming response. Fields are optional as availability varies by provider and stream state.
1179
+ *
1180
+ * @interface LLMMetadata
560
1181
  */
561
1182
  interface LLMMetadata {
562
- /** The number of tokens in the input prompt, if available. */
1183
+ /**
1184
+ * The number of tokens in the input prompt, if available.
1185
+ * @property {number} [inputTokens]
1186
+ */
563
1187
  inputTokens?: number;
564
- /** The number of tokens generated in the output response, if available. */
1188
+ /**
1189
+ * The number of tokens generated in the output response, if available.
1190
+ * @property {number} [outputTokens]
1191
+ */
565
1192
  outputTokens?: number;
566
- /** The number of tokens identified as part of the LLM's internal thinking process (if available from provider). */
1193
+ /**
1194
+ * The number of tokens identified as part of the LLM's internal thinking process (if available from provider).
1195
+ * @property {number} [thinkingTokens]
1196
+ */
567
1197
  thinkingTokens?: number;
568
- /** The time elapsed (in milliseconds) until the first token was generated in a streaming response, if applicable and available. */
1198
+ /**
1199
+ * The time elapsed (in milliseconds) until the first token was generated in a streaming response, if applicable and available.
1200
+ * @property {number} [timeToFirstTokenMs]
1201
+ */
569
1202
  timeToFirstTokenMs?: number;
570
- /** The total time elapsed (in milliseconds) for the entire generation process, if available. */
1203
+ /**
1204
+ * The total time elapsed (in milliseconds) for the entire generation process, if available.
1205
+ * @property {number} [totalGenerationTimeMs]
1206
+ */
571
1207
  totalGenerationTimeMs?: number;
572
- /** The reason the LLM stopped generating tokens (e.g., 'stop_sequence', 'max_tokens', 'tool_calls'), if available. */
1208
+ /**
1209
+ * The reason the LLM stopped generating tokens (e.g., 'stop_sequence', 'max_tokens', 'tool_calls'), if available.
1210
+ * @property {string} [stopReason]
1211
+ */
573
1212
  stopReason?: string;
574
- /** Optional raw usage data provided directly by the LLM provider for extensibility (structure depends on provider). */
1213
+ /**
1214
+ * Optional raw usage data provided directly by the LLM provider for extensibility (structure depends on provider).
1215
+ * @property {any} [providerRawUsage]
1216
+ */
575
1217
  providerRawUsage?: any;
576
- /** The trace ID associated with the LLM call, useful for correlating metadata with the specific request. */
1218
+ /**
1219
+ * The trace ID associated with the LLM call, useful for correlating metadata with the specific request.
1220
+ * @property {string} [traceId]
1221
+ */
577
1222
  traceId?: string;
578
1223
  }
579
1224
  /**
580
1225
  * Defines the schema for a tool, including its input parameters.
581
1226
  * Uses JSON Schema format for inputSchema.
1227
+ *
1228
+ * @interface ToolSchema
582
1229
  */
583
1230
  interface ToolSchema {
584
- /** A unique name identifying the tool (used in LLM prompts and registry lookups). Must be unique. */
1231
+ /**
1232
+ * A unique name identifying the tool (used in LLM prompts and registry lookups). Must be unique.
1233
+ * @property {string} name
1234
+ */
585
1235
  name: string;
586
- /** A clear description of what the tool does, intended for the LLM to understand its purpose and usage. */
1236
+ /**
1237
+ * A clear description of what the tool does, intended for the LLM to understand its purpose and usage.
1238
+ * @property {string} description
1239
+ */
587
1240
  description: string;
588
- /** A JSON Schema object defining the structure, types, and requirements of the input arguments the tool expects. */
1241
+ /**
1242
+ * A JSON Schema object defining the structure, types, and requirements of the input arguments the tool expects.
1243
+ * @property {JsonSchema} inputSchema
1244
+ */
589
1245
  inputSchema: JsonSchema;
590
- /** An optional JSON Schema object defining the expected structure of the data returned in the `output` field of a successful `ToolResult`. */
1246
+ /**
1247
+ * An optional JSON Schema object defining the expected structure of the data returned in the `output` field of a successful `ToolResult`.
1248
+ * @property {JsonSchema} [outputSchema]
1249
+ */
591
1250
  outputSchema?: JsonSchema;
592
- /** Optional array of examples demonstrating how to use the tool, useful for few-shot prompting of the LLM. */
1251
+ /**
1252
+ * Optional array of examples demonstrating how to use the tool, useful for few-shot prompting of the LLM.
1253
+ * @property {Array<{ input: any; output?: any; description?: string }>} [examples]
1254
+ */
593
1255
  examples?: Array<{
594
1256
  input: any;
595
1257
  output?: any;
@@ -598,183 +1260,463 @@ interface ToolSchema {
598
1260
  }
599
1261
  /**
600
1262
  * Represents the structured result of a tool execution.
1263
+ *
1264
+ * @interface ToolResult
601
1265
  */
602
1266
  interface ToolResult {
603
- /** The unique identifier of the corresponding `ParsedToolCall` that initiated this execution attempt. */
1267
+ /**
1268
+ * The unique identifier of the corresponding `ParsedToolCall` that initiated this execution attempt.
1269
+ * @property {string} callId
1270
+ */
604
1271
  callId: string;
605
- /** The name of the tool that was executed. */
1272
+ /**
1273
+ * The name of the tool that was executed.
1274
+ * @property {string} toolName
1275
+ */
606
1276
  toolName: string;
607
- /** Indicates whether the tool execution succeeded or failed. */
1277
+ /**
1278
+ * Indicates whether the tool execution succeeded or failed.
1279
+ * @property {'success' | 'error'} status
1280
+ */
608
1281
  status: 'success' | 'error';
609
- /** The data returned by the tool upon successful execution. Structure may be validated against `outputSchema`. */
1282
+ /**
1283
+ * The data returned by the tool upon successful execution. Structure may be validated against `outputSchema`.
1284
+ * @property {any} [output]
1285
+ */
610
1286
  output?: any;
611
- /** A descriptive error message if the execution failed (`status` is 'error'). */
1287
+ /**
1288
+ * A descriptive error message if the execution failed (`status` is 'error').
1289
+ * @property {string} [error]
1290
+ */
612
1291
  error?: string;
613
- /** Optional metadata about the execution (e.g., duration, cost, logs). */
614
- metadata?: Record<string, any>;
1292
+ /**
1293
+ * Optional metadata about the execution (e.g., duration, cost, logs).
1294
+ * @property {object} [metadata]
1295
+ */
1296
+ metadata?: {
1297
+ sources?: Array<{
1298
+ sourceName: string;
1299
+ url?: string;
1300
+ [key: string]: any;
1301
+ }>;
1302
+ [key: string]: any;
1303
+ };
1304
+ }
1305
+ /**
1306
+ * Strategy for combining custom system prompt content across precedence levels.
1307
+ *
1308
+ * @typedef {'append' | 'prepend'} SystemPromptMergeStrategy
1309
+ */
1310
+ type SystemPromptMergeStrategy = 'append' | 'prepend';
1311
+ /**
1312
+ * Named preset for system prompts, supporting variables and a default merge strategy.
1313
+ *
1314
+ * @interface SystemPromptSpec
1315
+ */
1316
+ interface SystemPromptSpec {
1317
+ /**
1318
+ * Optional explicit ID; when in a registry map, the key is typically the tag.
1319
+ * @property {string} [id]
1320
+ */
1321
+ id?: string;
1322
+ /**
1323
+ * Template string. Supports simple {{variable}} placeholders and {{fragment:name}} for PromptManager fragments.
1324
+ * @property {string} template
1325
+ */
1326
+ template: string;
1327
+ /**
1328
+ * Default variables applied if not provided at use time.
1329
+ * @property {Record<string, any>} [defaultVariables]
1330
+ */
1331
+ defaultVariables?: Record<string, any>;
1332
+ /**
1333
+ * Default strategy to combine this spec with lower levels. Defaults to 'append'.
1334
+ * @property {SystemPromptMergeStrategy} [mergeStrategy]
1335
+ */
1336
+ mergeStrategy?: SystemPromptMergeStrategy;
1337
+ }
1338
+ /**
1339
+ * Registry of available system prompt presets (tags) at the instance level.
1340
+ *
1341
+ * @interface SystemPromptsRegistry
1342
+ */
1343
+ interface SystemPromptsRegistry {
1344
+ /**
1345
+ * Tag to use when no other tag is specified.
1346
+ * @property {string} [defaultTag]
1347
+ */
1348
+ defaultTag?: string;
1349
+ /**
1350
+ * Mapping of tag -> spec.
1351
+ * @property {Record<string, SystemPromptSpec>} specs
1352
+ */
1353
+ specs: Record<string, SystemPromptSpec>;
1354
+ }
1355
+ /**
1356
+ * Override provided at instance/thread/call level to select a tag and/or provide variables,
1357
+ * or to provide freeform content and a merge strategy.
1358
+ *
1359
+ * @interface SystemPromptOverride
1360
+ */
1361
+ interface SystemPromptOverride {
1362
+ /**
1363
+ * Preset tag from the registry (e.g., 'default', 'legal_advisor').
1364
+ * @property {string} [tag]
1365
+ */
1366
+ tag?: string;
1367
+ /**
1368
+ * Variables to substitute in the selected template.
1369
+ * @property {Record<string, any>} [variables]
1370
+ */
1371
+ variables?: Record<string, any>;
1372
+ /**
1373
+ * Freeform content to apply directly (escape hatch).
1374
+ * @property {string} [content]
1375
+ */
1376
+ content?: string;
1377
+ /**
1378
+ * Merge behavior against previous level: append | prepend.
1379
+ * @property {SystemPromptMergeStrategy} [strategy]
1380
+ */
1381
+ strategy?: SystemPromptMergeStrategy;
615
1382
  }
616
1383
  /**
617
1384
  * Represents a parsed request from the LLM to call a specific tool.
1385
+ *
1386
+ * @interface ParsedToolCall
618
1387
  */
619
1388
  interface ParsedToolCall {
620
- /** A unique identifier generated by the OutputParser for this specific tool call request within a plan. */
1389
+ /**
1390
+ * A unique identifier generated by the OutputParser for this specific tool call request within a plan.
1391
+ * @property {string} callId
1392
+ */
621
1393
  callId: string;
622
- /** The name of the tool the LLM intends to call. Must match a registered tool's schema name. */
1394
+ /**
1395
+ * The name of the tool the LLM intends to call. Must match a registered tool's schema name.
1396
+ * @property {string} toolName
1397
+ */
623
1398
  toolName: string;
624
- /** The arguments object, parsed from the LLM response, intended to be passed to the tool's `execute` method after validation. */
1399
+ /**
1400
+ * The arguments object, parsed from the LLM response, intended to be passed to the tool's `execute` method after validation.
1401
+ * @property {any} arguments
1402
+ */
625
1403
  arguments: any;
626
1404
  }
627
1405
  /**
628
1406
  * Configuration specific to a conversation thread.
1407
+ *
1408
+ * @interface ThreadConfig
629
1409
  */
630
1410
  interface ThreadConfig {
631
- /** Default provider configuration for this thread. */
1411
+ /**
1412
+ * Default provider configuration for this thread.
1413
+ * @property {RuntimeProviderConfig} providerConfig
1414
+ */
632
1415
  providerConfig: RuntimeProviderConfig;
633
- /** An array of tool names (matching `ToolSchema.name`) that are permitted for use within this thread. */
1416
+ /**
1417
+ * An array of tool names (matching `ToolSchema.name`) that are permitted for use within this thread.
1418
+ * @property {string[]} enabledTools
1419
+ */
634
1420
  enabledTools: string[];
635
- /** The maximum number of past messages (`ConversationMessage` objects) to retrieve for context. */
1421
+ /**
1422
+ * The maximum number of past messages (`ConversationMessage` objects) to retrieve for context.
1423
+ * @property {number} historyLimit
1424
+ */
636
1425
  historyLimit: number;
637
- /** Optional system prompt string to be used for this thread, overriding instance or agent defaults. */
638
- systemPrompt?: string;
1426
+ /**
1427
+ * Optional system prompt override to be used for this thread, overriding instance or agent defaults.
1428
+ * @property {string | SystemPromptOverride} [systemPrompt]
1429
+ */
1430
+ systemPrompt?: string | SystemPromptOverride;
1431
+ /**
1432
+ * Optional: Defines the identity and high-level guidance for the agent for this specific thread.
1433
+ * This overrides the instance-level persona.
1434
+ * @property {Partial<AgentPersona>} [persona]
1435
+ */
1436
+ persona?: Partial<AgentPersona>;
639
1437
  }
640
1438
  /**
641
1439
  * Represents non-configuration state associated with an agent or thread.
642
1440
  * Could include user preferences, accumulated knowledge, etc. (Less defined for v1.0)
1441
+ *
1442
+ * @interface AgentState
643
1443
  */
644
1444
  interface AgentState {
645
- /** The primary data payload of the agent's state. Structure is application-defined. */
1445
+ /**
1446
+ * The primary data payload of the agent's state. Structure is application-defined.
1447
+ * @property {any} data
1448
+ */
646
1449
  data: any;
647
- /** An optional version number for the agent's state, useful for migrations or tracking changes. */
1450
+ /**
1451
+ * An optional version number for the agent's state, useful for migrations or tracking changes.
1452
+ * @property {number} [version]
1453
+ */
648
1454
  version?: number;
649
- /** Allows for other arbitrary properties to be stored in the agent's state. */
1455
+ /**
1456
+ * Allows for other arbitrary properties to be stored in the agent's state.
1457
+ * @property {any} [key: string]
1458
+ */
650
1459
  [key: string]: any;
651
1460
  }
652
1461
  /**
653
1462
  * Encapsulates the configuration and state for a specific thread.
1463
+ *
1464
+ * @interface ThreadContext
654
1465
  */
655
1466
  interface ThreadContext {
656
- /** The configuration settings (`ThreadConfig`) currently active for the thread. */
1467
+ /**
1468
+ * The configuration settings (`ThreadConfig`) currently active for the thread.
1469
+ * @property {ThreadConfig} config
1470
+ */
657
1471
  config: ThreadConfig;
658
- /** The persistent state (`AgentState`) associated with the thread, or `null` if no state exists. */
1472
+ /**
1473
+ * The persistent state (`AgentState`) associated with the thread, or `null` if no state exists.
1474
+ * @property {AgentState | null} state
1475
+ */
659
1476
  state: AgentState | null;
660
1477
  }
661
1478
  /**
662
1479
  * Properties required to initiate an agent processing cycle.
1480
+ *
1481
+ * @interface AgentProps
663
1482
  */
664
1483
  interface AgentProps {
665
- /** The user's input query or request to the agent. */
1484
+ /**
1485
+ * The user's input query or request to the agent.
1486
+ * @property {string} query
1487
+ */
666
1488
  query: string;
667
- /** The mandatory identifier for the conversation thread. All context is scoped to this ID. */
1489
+ /**
1490
+ * The mandatory identifier for the conversation thread. All context is scoped to this ID.
1491
+ * @property {string} threadId
1492
+ */
668
1493
  threadId: string;
669
- /** An optional identifier for the specific UI session, useful for targeting UI updates. */
1494
+ /**
1495
+ * An optional identifier for the specific UI session, useful for targeting UI updates.
1496
+ * @property {string} [sessionId]
1497
+ */
670
1498
  sessionId?: string;
671
- /** An optional identifier for the user interacting with the agent. */
1499
+ /**
1500
+ * An optional identifier for the user interacting with the agent.
1501
+ * @property {string} [userId]
1502
+ */
672
1503
  userId?: string;
673
- /** An optional identifier used for tracing a request across multiple systems or services. */
1504
+ /**
1505
+ * An optional identifier used for tracing a request across multiple systems or services.
1506
+ * @property {string} [traceId]
1507
+ */
674
1508
  traceId?: string;
675
- /** Optional runtime options that can override default behaviors for this specific `process` call. */
1509
+ /**
1510
+ * Optional runtime options that can override default behaviors for this specific `process` call.
1511
+ * @property {AgentOptions} [options]
1512
+ */
676
1513
  options?: AgentOptions;
677
1514
  }
678
1515
  /**
679
1516
  * Options to override agent behavior at runtime.
1517
+ *
1518
+ * @interface AgentOptions
680
1519
  */
681
1520
  interface AgentOptions {
682
- /** Override specific LLM parameters (e.g., temperature, max_tokens) for this call only. */
1521
+ /**
1522
+ * Override specific LLM parameters (e.g., temperature, max_tokens) for this call only.
1523
+ * @property {Record<string, any>} [llmParams]
1524
+ */
683
1525
  llmParams?: Record<string, any>;
684
- /** Override provider configuration for this specific call. */
1526
+ /**
1527
+ * Override provider configuration for this specific call.
1528
+ * @property {RuntimeProviderConfig} [providerConfig]
1529
+ */
685
1530
  providerConfig?: RuntimeProviderConfig;
686
- /** Force the use of specific tools, potentially overriding the thread's `enabledTools` for this call (use with caution). */
1531
+ /**
1532
+ * Force the use of specific tools, potentially overriding the thread's `enabledTools` for this call (use with caution).
1533
+ * @property {string[]} [forceTools]
1534
+ */
687
1535
  forceTools?: string[];
688
- /** Specify a particular reasoning model to use for this call, overriding the thread's default. */
1536
+ /**
1537
+ * Specify a particular reasoning model to use for this call, overriding the thread's default.
1538
+ * @property {{ provider: string; model: string }} [overrideModel]
1539
+ */
689
1540
  overrideModel?: {
690
1541
  provider: string;
691
1542
  model: string;
692
1543
  };
693
- /** Request a streaming response for this specific agent process call. */
1544
+ /**
1545
+ * Request a streaming response for this specific agent process call.
1546
+ * @property {boolean} [stream]
1547
+ */
694
1548
  stream?: boolean;
695
- /** Override the prompt template used for this specific call. */
1549
+ /**
1550
+ * Override the prompt template used for this specific call.
1551
+ * @property {string} [promptTemplateId]
1552
+ */
696
1553
  promptTemplateId?: string;
697
- /** Optional system prompt string to override thread, instance, or agent defaults for this specific call. */
698
- systemPrompt?: string;
1554
+ /**
1555
+ * Optional system prompt override/tag to override thread, instance, or agent defaults for this specific call.
1556
+ * @property {string | SystemPromptOverride} [systemPrompt]
1557
+ */
1558
+ systemPrompt?: string | SystemPromptOverride;
1559
+ /**
1560
+ * Optional: Defines the identity and high-level guidance for the agent for this specific call.
1561
+ * This overrides both the instance-level and thread-level persona.
1562
+ * @property {Partial<AgentPersona>} [persona]
1563
+ */
1564
+ persona?: Partial<AgentPersona>;
699
1565
  }
700
1566
  /**
701
1567
  * The final structured response returned by the agent core after processing.
1568
+ *
1569
+ * @interface AgentFinalResponse
702
1570
  */
703
1571
  interface AgentFinalResponse {
704
- /** The final `ConversationMessage` generated by the AI, which has also been persisted. */
1572
+ /**
1573
+ * The final `ConversationMessage` generated by the AI, which has also been persisted.
1574
+ * @property {ConversationMessage} response
1575
+ */
705
1576
  response: ConversationMessage;
706
- /** Metadata summarizing the execution cycle that produced this response. */
1577
+ /**
1578
+ * Metadata summarizing the execution cycle that produced this response.
1579
+ * @property {ExecutionMetadata} metadata
1580
+ */
707
1581
  metadata: ExecutionMetadata;
708
1582
  }
709
1583
  /**
710
1584
  * Metadata summarizing an agent execution cycle, including performance metrics and outcomes.
1585
+ *
1586
+ * @interface ExecutionMetadata
711
1587
  */
712
1588
  interface ExecutionMetadata {
713
- /** The thread ID associated with this execution cycle. */
1589
+ /**
1590
+ * The thread ID associated with this execution cycle.
1591
+ * @property {string} threadId
1592
+ */
714
1593
  threadId: string;
715
- /** The trace ID used during this execution, if provided. */
1594
+ /**
1595
+ * The trace ID used during this execution, if provided.
1596
+ * @property {string} [traceId]
1597
+ */
716
1598
  traceId?: string;
717
- /** The user ID associated with the execution, if provided. */
1599
+ /**
1600
+ * The user ID associated with the execution, if provided.
1601
+ * @property {string} [userId]
1602
+ */
718
1603
  userId?: string;
719
- /** The overall status of the execution ('success', 'error', or 'partial' if some steps failed but a response was generated). */
1604
+ /**
1605
+ * The overall status of the execution ('success', 'error', or 'partial' if some steps failed but a response was generated).
1606
+ * @property {'success' | 'error' | 'partial'} status
1607
+ */
720
1608
  status: 'success' | 'error' | 'partial';
721
- /** The total duration of the `agent.process()` call in milliseconds. */
1609
+ /**
1610
+ * The total duration of the `agent.process()` call in milliseconds.
1611
+ * @property {number} totalDurationMs
1612
+ */
722
1613
  totalDurationMs: number;
723
- /** The number of calls made to the `ReasoningEngine`. */
1614
+ /**
1615
+ * The number of calls made to the `ReasoningEngine`.
1616
+ * @property {number} llmCalls
1617
+ */
724
1618
  llmCalls: number;
725
- /** The number of tool execution attempts made by the `ToolSystem`. */
1619
+ /**
1620
+ * The number of tool execution attempts made by the `ToolSystem`.
1621
+ * @property {number} toolCalls
1622
+ */
726
1623
  toolCalls: number;
727
- /** An optional estimated cost for the LLM calls made during this execution. */
1624
+ /**
1625
+ * An optional estimated cost for the LLM calls made during this execution.
1626
+ * @property {number} [llmCost]
1627
+ */
728
1628
  llmCost?: number;
729
- /** A top-level error message if the overall status is 'error' or 'partial'. */
1629
+ /**
1630
+ * A top-level error message if the overall status is 'error' or 'partial'.
1631
+ * @property {string} [error]
1632
+ */
730
1633
  error?: string;
731
- /** Aggregated metadata from LLM calls made during the execution. */
1634
+ /**
1635
+ * Aggregated metadata from LLM calls made during the execution.
1636
+ * @property {LLMMetadata} [llmMetadata]
1637
+ */
732
1638
  llmMetadata?: LLMMetadata;
733
1639
  }
734
1640
  /**
735
1641
  * Context provided to a tool during its execution.
1642
+ *
1643
+ * @interface ExecutionContext
736
1644
  */
737
1645
  interface ExecutionContext {
738
- /** The ID of the thread in which the tool is being executed. */
1646
+ /**
1647
+ * The ID of the thread in which the tool is being executed.
1648
+ * @property {string} threadId
1649
+ */
739
1650
  threadId: string;
740
- /** The trace ID for this execution cycle, if available. */
1651
+ /**
1652
+ * The trace ID for this execution cycle, if available.
1653
+ * @property {string} [traceId]
1654
+ */
741
1655
  traceId?: string;
742
- /** The user ID associated with the execution, if available. */
1656
+ /**
1657
+ * The user ID associated with the execution, if available.
1658
+ * @property {string} [userId]
1659
+ */
743
1660
  userId?: string;
744
1661
  }
745
1662
  /**
746
1663
  * Options for configuring an LLM call, including streaming and context information.
1664
+ *
1665
+ * @interface CallOptions
747
1666
  */
748
1667
  interface CallOptions {
749
- /** The mandatory thread ID, used by the ReasoningEngine to fetch thread-specific configuration (e.g., model, params) via StateManager. */
1668
+ /**
1669
+ * The mandatory thread ID, used by the ReasoningEngine to fetch thread-specific configuration (e.g., model, params) via StateManager.
1670
+ * @property {string} threadId
1671
+ */
750
1672
  threadId: string;
751
- /** Optional trace ID for correlation. */
1673
+ /**
1674
+ * Optional trace ID for correlation.
1675
+ * @property {string} [traceId]
1676
+ */
752
1677
  traceId?: string;
753
- /** Optional user ID. */
1678
+ /**
1679
+ * Optional user ID.
1680
+ * @property {string} [userId]
1681
+ */
754
1682
  userId?: string;
755
- /** Optional session ID. */
1683
+ /**
1684
+ * Optional session ID.
1685
+ * @property {string} [sessionId]
1686
+ */
756
1687
  sessionId?: string;
757
1688
  /**
758
1689
  * Request a streaming response from the LLM provider.
759
1690
  * Adapters MUST check this flag.
1691
+ * @property {boolean} [stream]
760
1692
  */
761
1693
  stream?: boolean;
762
1694
  /**
763
1695
  * Provides context for the LLM call, allowing adapters to differentiate
764
1696
  * between agent-level thoughts and final synthesis calls for token typing.
765
1697
  * Agent Core MUST provide this.
1698
+ * @property {'AGENT_THOUGHT' | 'FINAL_SYNTHESIS' | string} [callContext]
766
1699
  */
767
1700
  callContext?: 'AGENT_THOUGHT' | 'FINAL_SYNTHESIS' | string;
768
- /** An optional callback function invoked when the LLM streams intermediate 'thoughts' or reasoning steps.
1701
+ /**
1702
+ * An optional callback function invoked when the LLM streams intermediate 'thoughts' or reasoning steps.
769
1703
  * @deprecated Prefer using StreamEvent with appropriate tokenType for thoughts. Kept for potential transitional compatibility.
770
1704
  */
771
- /** Carries the specific target provider and configuration for this call. */
1705
+ /**
1706
+ * Carries the specific target provider and configuration for this call.
1707
+ * @property {RuntimeProviderConfig} providerConfig
1708
+ */
772
1709
  providerConfig: RuntimeProviderConfig;
773
- /** Additional key-value pairs representing provider-specific parameters (e.g., `temperature`, `max_tokens`, `top_p`). These often override defaults set in `ThreadConfig`. */
1710
+ /**
1711
+ * Additional key-value pairs representing provider-specific parameters (e.g., `temperature`, `max_tokens`, `top_p`). These often override defaults set in `ThreadConfig`.
1712
+ * @property {any} [key: string]
1713
+ */
774
1714
  [key: string]: any;
775
1715
  }
776
1716
  /**
777
1717
  * Defines the standard roles for messages within the `ArtStandardPrompt` format.
1718
+ *
1719
+ * @remarks
778
1720
  * These roles are chosen for broad compatibility across major LLM providers (like OpenAI, Anthropic, Gemini).
779
1721
  * Provider Adapters are responsible for translating these standard roles into the specific formats
780
1722
  * required by their respective APIs (e.g., 'assistant' might become 'model' for Gemini).
@@ -784,14 +1726,23 @@ interface CallOptions {
784
1726
  * - `assistant`: Responses generated by the AI model. Can contain text content and/or `tool_calls`.
785
1727
  * - `tool_request`: Represents the LLM's request to use tools (often implicitly part of an `assistant` message with `tool_calls`). Included for potential future explicit use.
786
1728
  * - `tool_result`: The outcome (output or error) of executing a requested tool call.
1729
+ *
1730
+ * @typedef {'system' | 'user' | 'assistant' | 'tool_request' | 'tool_result' | 'tool'} ArtStandardMessageRole
787
1731
  */
788
1732
  type ArtStandardMessageRole = 'system' | 'user' | 'assistant' | 'tool_request' | 'tool_result' | 'tool';
789
1733
  /**
790
1734
  * Represents a single message in the standardized, provider-agnostic `ArtStandardPrompt` format.
1735
+ *
1736
+ * @remarks
791
1737
  * This structure aims to capture common message elements used by various LLM APIs.
1738
+ *
1739
+ * @interface ArtStandardMessage
792
1740
  */
793
1741
  interface ArtStandardMessage {
794
- /** The role indicating the source or type of the message. */
1742
+ /**
1743
+ * The role indicating the source or type of the message.
1744
+ * @property {ArtStandardMessageRole} role
1745
+ */
795
1746
  role: ArtStandardMessageRole;
796
1747
  /**
797
1748
  * The primary content of the message. The type and interpretation depend on the `role`:
@@ -800,14 +1751,22 @@ interface ArtStandardMessage {
800
1751
  * - `assistant`: string | null (The AI's text response, or null/empty if only making `tool_calls`).
801
1752
  * - `tool_request`: object | null (Structured representation of the tool call, often implicitly handled via `assistant` message's `tool_calls`).
802
1753
  * - `tool_result`: string (Stringified JSON output or error message from the tool execution).
1754
+ * @property {string | object | null} content
803
1755
  */
804
1756
  content: string | object | null;
805
- /** Optional name associated with the message. Primarily used for `tool_result` role to specify the name of the tool that was executed. */
1757
+ /**
1758
+ * Optional name associated with the message. Primarily used for `tool_result` role to specify the name of the tool that was executed.
1759
+ * @property {string} [name]
1760
+ */
806
1761
  name?: string;
807
1762
  /**
808
1763
  * Optional array of tool calls requested by the assistant.
1764
+ *
1765
+ * @remarks
809
1766
  * Only relevant for 'assistant' role messages that trigger tool usage.
810
1767
  * Structure mirrors common provider formats (e.g., OpenAI).
1768
+ *
1769
+ * @property {Array<{ id: string; type: 'function'; function: { name: string; arguments: string; }; }>} [tool_calls]
811
1770
  */
812
1771
  tool_calls?: Array<{
813
1772
  /** A unique identifier for this specific tool call request. */
@@ -826,170 +1785,839 @@ interface ArtStandardMessage {
826
1785
  * Optional identifier linking a 'tool_result' message back to the specific 'tool_calls' entry
827
1786
  * in the preceding 'assistant' message that requested it.
828
1787
  * Required for 'tool_result' role.
1788
+ * @property {string} [tool_call_id]
1789
+ */
1790
+ tool_call_id?: string;
1791
+ }
1792
+ /**
1793
+ * Represents the entire prompt as an array of standardized messages (`ArtStandardMessage`).
1794
+ *
1795
+ * @remarks
1796
+ * Constructed by agent logic (e.g., `PESAgent`) and optionally validated via
1797
+ * `PromptManager.validatePrompt` before being sent to the `ReasoningEngine` and
1798
+ * translated by a `ProviderAdapter` for provider-specific API formats.
1799
+ *
1800
+ * @typedef {ArtStandardMessage[]} ArtStandardPrompt
1801
+ */
1802
+ type ArtStandardPrompt = ArtStandardMessage[];
1803
+ /**
1804
+ * Represents the contextual data gathered by Agent Logic (e.g., `PESAgent`) to be injected
1805
+ * into a Mustache blueprint/template by the `PromptManager.assemblePrompt` method.
1806
+ *
1807
+ * @remarks
1808
+ * Contains standard fields commonly needed for prompts, plus allows for arbitrary
1809
+ * additional properties required by specific agent blueprints. Agent logic is responsible
1810
+ * for populating this context appropriately before calling `assemblePrompt`.
1811
+ *
1812
+ * @interface PromptContext
1813
+ */
1814
+ interface PromptContext {
1815
+ /**
1816
+ * The user's current query or input relevant to this prompt generation step.
1817
+ * @property {string} [query]
1818
+ */
1819
+ query?: string;
1820
+ /**
1821
+ * The conversation history, typically formatted as an array suitable for the blueprint
1822
+ * (e.g., array of objects with `role` and `content`). Agent logic should pre-format this.
1823
+ *
1824
+ * @remarks
1825
+ * While `ArtStandardPrompt` could be used, simpler structures might be preferred for blueprints.
1826
+ *
1827
+ * @property {Array<{ role: string; content: string; [key: string]: any }>} [history]
1828
+ */
1829
+ history?: Array<{
1830
+ role: string;
1831
+ content: string;
1832
+ [key: string]: any;
1833
+ }>;
1834
+ /**
1835
+ * The schemas of the tools available for use, potentially pre-formatted for the blueprint
1836
+ * (e.g., with `inputSchemaJson` pre-stringified).
1837
+ * @property {Array<ToolSchema & { inputSchemaJson?: string }>} [availableTools]
1838
+ */
1839
+ availableTools?: Array<ToolSchema & {
1840
+ inputSchemaJson?: string;
1841
+ }>;
1842
+ /**
1843
+ * The results from any tools executed in a previous step, potentially pre-formatted for the blueprint
1844
+ * (e.g., with `outputJson` pre-stringified).
1845
+ * @property {Array<ToolResult & { outputJson?: string }>} [toolResults]
1846
+ */
1847
+ toolResults?: Array<ToolResult & {
1848
+ outputJson?: string;
1849
+ }>;
1850
+ /**
1851
+ * The system prompt string to be used (resolved by agent logic from config or defaults).
1852
+ * @property {string} [systemPrompt]
1853
+ */
1854
+ systemPrompt?: string;
1855
+ /**
1856
+ * Allows agent patterns (like PES) to pass any other custom data needed by their specific blueprints (e.g., `intent`, `plan`).
1857
+ * @property {any} [key: string]
1858
+ */
1859
+ [key: string]: any;
1860
+ }
1861
+ /**
1862
+ * Represents a Mustache template that can be rendered with a PromptContext to produce an ArtStandardPrompt.
1863
+ * Used by the PromptManager.assemblePrompt method.
1864
+ *
1865
+ * @interface PromptBlueprint
1866
+ */
1867
+ interface PromptBlueprint {
1868
+ /**
1869
+ * The Mustache template string that will be rendered with context data to produce a JSON string representing an ArtStandardPrompt
1870
+ * @property {string} template
1871
+ */
1872
+ template: string;
1873
+ }
1874
+ /**
1875
+ * Represents the prompt data formatted for a specific LLM provider.
1876
+ * Can be a simple string or a complex object (e.g., for OpenAI Chat Completion API).
1877
+ *
1878
+ * @deprecated Use `ArtStandardPrompt` as the standard intermediate format. ProviderAdapters handle final formatting.
1879
+ * @typedef {ArtStandardPrompt} FormattedPrompt
1880
+ */
1881
+ type FormattedPrompt = ArtStandardPrompt;
1882
+ /**
1883
+ * Options for filtering data retrieved from storage.
1884
+ * Structure depends heavily on the underlying adapter's capabilities.
1885
+ *
1886
+ * @interface FilterOptions
1887
+ */
1888
+ interface FilterOptions {
1889
+ /**
1890
+ * An object defining filter criteria (e.g., `{ threadId: 'abc', type: 'TOOL_EXECUTION' }`). Structure may depend on adapter capabilities.
1891
+ * @property {Record<string, any>} [filter]
1892
+ */
1893
+ filter?: Record<string, any>;
1894
+ /**
1895
+ * An object defining sorting criteria (e.g., `{ timestamp: 'desc' }`).
1896
+ * @property {Record<string, 'asc' | 'desc'>} [sort]
1897
+ */
1898
+ sort?: Record<string, 'asc' | 'desc'>;
1899
+ /**
1900
+ * The maximum number of records to return.
1901
+ * @property {number} [limit]
1902
+ */
1903
+ limit?: number;
1904
+ /**
1905
+ * The number of records to skip (for pagination).
1906
+ * @property {number} [skip]
1907
+ */
1908
+ skip?: number;
1909
+ }
1910
+ /**
1911
+ * Options for retrieving conversation messages.
1912
+ *
1913
+ * @interface MessageOptions
1914
+ */
1915
+ interface MessageOptions {
1916
+ /**
1917
+ * The maximum number of messages to retrieve.
1918
+ * @property {number} [limit]
1919
+ */
1920
+ limit?: number;
1921
+ /**
1922
+ * Retrieve messages created before this Unix timestamp (milliseconds).
1923
+ * @property {number} [beforeTimestamp]
1924
+ */
1925
+ beforeTimestamp?: number;
1926
+ /**
1927
+ * Retrieve messages created after this Unix timestamp (milliseconds).
1928
+ * @property {number} [afterTimestamp]
1929
+ */
1930
+ afterTimestamp?: number;
1931
+ /**
1932
+ * Optionally filter messages by role (e.g., retrieve only 'AI' messages).
1933
+ * @property {MessageRole[]} [roles]
1934
+ */
1935
+ roles?: MessageRole[];
1936
+ }
1937
+ /**
1938
+ * Options for filtering observations.
1939
+ *
1940
+ * @interface ObservationFilter
1941
+ */
1942
+ interface ObservationFilter {
1943
+ /**
1944
+ * An array of `ObservationType` enums to filter by. If provided, only observations matching these types are returned.
1945
+ * @property {ObservationType[]} [types]
1946
+ */
1947
+ types?: ObservationType[];
1948
+ /**
1949
+ * Retrieve observations recorded before this Unix timestamp (milliseconds).
1950
+ * @property {number} [beforeTimestamp]
1951
+ */
1952
+ beforeTimestamp?: number;
1953
+ /**
1954
+ * Retrieve observations recorded after this Unix timestamp (milliseconds).
1955
+ * @property {number} [afterTimestamp]
1956
+ */
1957
+ afterTimestamp?: number;
1958
+ }
1959
+ /**
1960
+ * Defines the strategy for saving AgentState.
1961
+ *
1962
+ * @remarks
1963
+ * - 'explicit': AgentState is only saved when `StateManager.setAgentState()` is explicitly called by the agent.
1964
+ * `StateManager.saveStateIfModified()` will be a no-op for AgentState persistence.
1965
+ * - 'implicit': AgentState is loaded by `StateManager.loadThreadContext()`, and if modified by the agent,
1966
+ * `StateManager.saveStateIfModified()` will attempt to automatically persist these changes
1967
+ * by comparing the current state with a snapshot taken at load time.
1968
+ * `StateManager.setAgentState()` will still work for explicit saves.
1969
+ *
1970
+ * @typedef {'explicit' | 'implicit'} StateSavingStrategy
1971
+ */
1972
+ type StateSavingStrategy = 'explicit' | 'implicit';
1973
+
1974
+ /**
1975
+ * Configuration for creating an ART instance.
1976
+ *
1977
+ * @interface ArtInstanceConfig
1978
+ */
1979
+ interface ArtInstanceConfig {
1980
+ /**
1981
+ * Configuration for the storage adapter.
1982
+ * Can be a pre-configured `StorageAdapter` instance,
1983
+ * or an object specifying the type and options for a built-in adapter.
1984
+ *
1985
+ * @example { type: 'indexedDB', dbName: 'MyArtDB' }
1986
+ *
1987
+ * @property {StorageAdapter | { type: 'memory' | 'indexedDB', dbName?: string, version?: number, objectStores?: any[] }} storage
1988
+ */
1989
+ storage: StorageAdapter | {
1990
+ type: 'memory' | 'indexedDB';
1991
+ dbName?: string;
1992
+ version?: number;
1993
+ objectStores?: any[];
1994
+ };
1995
+ /**
1996
+ * Configuration for the ProviderManager, defining available LLM provider adapters.
1997
+ * @property {PMConfig} providers
1998
+ */
1999
+ providers: ProviderManagerConfig;
2000
+ /**
2001
+ * The agent core implementation class to use.
2002
+ * Defaults to `PESAgent` if not provided.
2003
+ *
2004
+ * @example MyCustomAgentClass
2005
+ *
2006
+ * @property {new (dependencies: any) => IAgentCore} [agentCore]
2007
+ */
2008
+ agentCore?: new (dependencies: any) => IAgentCore;
2009
+ /**
2010
+ * An optional array of tool executor instances to register at initialization.
2011
+ * @property {IToolExecutor[]} [tools]
2012
+ */
2013
+ tools?: IToolExecutor[];
2014
+ /**
2015
+ * Defines the strategy for saving `AgentState`. Defaults to 'explicit'.
2016
+ *
2017
+ * @remarks
2018
+ * - 'explicit': `AgentState` is only saved when `StateManager.setAgentState()` is explicitly called by the agent.
2019
+ * `StateManager.saveStateIfModified()` will be a no-op for `AgentState` persistence.
2020
+ * - 'implicit': `AgentState` is loaded by `StateManager.loadThreadContext()`. If modified by the agent,
2021
+ * `StateManager.saveStateIfModified()` will attempt to automatically persist these changes.
2022
+ * `StateManager.setAgentState()` will still work for explicit saves in this mode.
2023
+ *
2024
+ * @property {StateSavingStrategy} [stateSavingStrategy]
2025
+ */
2026
+ stateSavingStrategy?: StateSavingStrategy;
2027
+ /**
2028
+ * Optional configuration for the framework's logger.
2029
+ * @property {{ level?: LogLevel }} [logger]
2030
+ */
2031
+ logger?: {
2032
+ /** Minimum log level to output. Defaults to 'info'. */
2033
+ level?: LogLevel;
2034
+ };
2035
+ /**
2036
+ * Optional: Defines the default identity and high-level guidance for the agent.
2037
+ * This can be overridden at the thread or call level.
2038
+ * @property {AgentPersona} [persona]
2039
+ */
2040
+ persona?: AgentPersona;
2041
+ /**
2042
+ * Optional configuration for MCP (Model Context Protocol) manager.
2043
+ * Enables connection to external MCP servers for dynamic tool loading.
2044
+ * @property {McpManagerConfig} [mcpConfig]
2045
+ */
2046
+ mcpConfig?: McpManagerConfig;
2047
+ /**
2048
+ * Optional configuration for authentication strategies.
2049
+ * Used for secure connections to external services and MCP servers.
2050
+ * @property {object} [authConfig]
2051
+ */
2052
+ authConfig?: {
2053
+ /**
2054
+ * Whether to enable authentication manager. Defaults to false.
2055
+ * @property {boolean} [enabled]
2056
+ */
2057
+ enabled?: boolean;
2058
+ /**
2059
+ * Pre-configured authentication strategies to register at startup.
2060
+ * @property {Array<{ id: string; strategy: any }>} [strategies]
2061
+ */
2062
+ strategies?: Array<{
2063
+ id: string;
2064
+ strategy: any;
2065
+ }>;
2066
+ };
2067
+ /**
2068
+ * Optional: Configuration for A2A services.
2069
+ * @property {object} [a2aConfig]
2070
+ */
2071
+ a2aConfig?: {
2072
+ /**
2073
+ * The endpoint for discovering A2A agents.
2074
+ * @property {string} [discoveryEndpoint]
2075
+ */
2076
+ discoveryEndpoint?: string;
2077
+ /**
2078
+ * The callback URL for receiving A2A task updates.
2079
+ * @property {string} [callbackUrl]
2080
+ */
2081
+ callbackUrl?: string;
2082
+ };
2083
+ }
2084
+ /**
2085
+ * Represents the possible states of an A2A (Agent-to-Agent) task.
2086
+ *
2087
+ * @enum {string}
2088
+ */
2089
+ declare enum A2ATaskStatus {
2090
+ /** Task has been created but not yet assigned to an agent. */
2091
+ PENDING = "PENDING",
2092
+ /** Task has been assigned to an agent and is being processed. */
2093
+ IN_PROGRESS = "IN_PROGRESS",
2094
+ /** Task has been completed successfully. */
2095
+ COMPLETED = "COMPLETED",
2096
+ /** Task has failed during execution. */
2097
+ FAILED = "FAILED",
2098
+ /** Task has been cancelled before completion. */
2099
+ CANCELLED = "CANCELLED",
2100
+ /** Task is waiting for external dependencies or manual intervention. */
2101
+ WAITING = "WAITING",
2102
+ /** Task is being reviewed for quality assurance. */
2103
+ REVIEW = "REVIEW"
2104
+ }
2105
+ /**
2106
+ * Represents the priority level of an A2A task.
2107
+ *
2108
+ * @enum {string}
2109
+ */
2110
+ declare enum A2ATaskPriority {
2111
+ /** Low priority. */
2112
+ LOW = "LOW",
2113
+ /** Medium priority. */
2114
+ MEDIUM = "MEDIUM",
2115
+ /** High priority. */
2116
+ HIGH = "HIGH",
2117
+ /** Urgent priority. */
2118
+ URGENT = "URGENT"
2119
+ }
2120
+ /**
2121
+ * Represents agent information for A2A task assignment.
2122
+ *
2123
+ * @interface A2AAgentInfo
2124
+ */
2125
+ interface A2AAgentInfo {
2126
+ /**
2127
+ * Unique identifier for the agent.
2128
+ * @property {string} agentId
2129
+ */
2130
+ agentId: string;
2131
+ /**
2132
+ * Human-readable name for the agent.
2133
+ * @property {string} agentName
2134
+ */
2135
+ agentName: string;
2136
+ /**
2137
+ * The type or role of the agent (e.g., 'reasoning', 'data-processing', 'synthesis').
2138
+ * @property {string} agentType
2139
+ */
2140
+ agentType: string;
2141
+ /**
2142
+ * Base URL or endpoint for communicating with the agent.
2143
+ * @property {string} [endpoint]
2144
+ */
2145
+ endpoint?: string;
2146
+ /**
2147
+ * Agent capabilities or specializations.
2148
+ * @property {string[]} [capabilities]
2149
+ */
2150
+ capabilities?: string[];
2151
+ /**
2152
+ * Current load or availability status of the agent.
2153
+ * @property {'available' | 'busy' | 'offline'} [status]
2154
+ */
2155
+ status?: 'available' | 'busy' | 'offline';
2156
+ /**
2157
+ * Authentication configuration for communicating with the agent.
2158
+ * @property {object} [authentication]
2159
+ */
2160
+ authentication?: {
2161
+ /**
2162
+ * Type of authentication required.
2163
+ * @property {'bearer' | 'api_key' | 'none'} type
2164
+ */
2165
+ type: 'bearer' | 'api_key' | 'none';
2166
+ /**
2167
+ * Bearer token for authorization (if type is 'bearer').
2168
+ * @property {string} [token]
2169
+ */
2170
+ token?: string;
2171
+ /**
2172
+ * API key for authorization (if type is 'api_key').
2173
+ * @property {string} [apiKey]
2174
+ */
2175
+ apiKey?: string;
2176
+ };
2177
+ }
2178
+ /**
2179
+ * Represents metadata about A2A task execution.
2180
+ *
2181
+ * @interface A2ATaskMetadata
2182
+ */
2183
+ interface A2ATaskMetadata {
2184
+ /**
2185
+ * Timestamp when the task was created (Unix timestamp in milliseconds).
2186
+ * @property {number} createdAt
2187
+ */
2188
+ createdAt: number;
2189
+ /**
2190
+ * Timestamp when the task was last updated (Unix timestamp in milliseconds).
2191
+ * @property {number} updatedAt
2192
+ */
2193
+ updatedAt: number;
2194
+ /**
2195
+ * Timestamp when the task was started (if applicable).
2196
+ * @property {number} [startedAt]
2197
+ */
2198
+ startedAt?: number;
2199
+ /**
2200
+ * Timestamp when the task was completed/failed (if applicable).
2201
+ * @property {number} [completedAt]
2202
+ */
2203
+ completedAt?: number;
2204
+ /**
2205
+ * Timestamp when the task was delegated to a remote agent (if applicable).
2206
+ * @property {number} [delegatedAt]
2207
+ */
2208
+ delegatedAt?: number;
2209
+ /**
2210
+ * Timestamp when the task was last updated (for compatibility).
2211
+ * @property {number} [lastUpdated]
2212
+ */
2213
+ lastUpdated?: number;
2214
+ /**
2215
+ * The user or system that initiated this task.
2216
+ * @property {string} [initiatedBy]
2217
+ */
2218
+ initiatedBy?: string;
2219
+ /**
2220
+ * Correlation ID for tracking related tasks across the system.
2221
+ * @property {string} [correlationId]
2222
+ */
2223
+ correlationId?: string;
2224
+ /**
2225
+ * Number of retry attempts made for this task.
2226
+ * @property {number} [retryCount]
2227
+ */
2228
+ retryCount?: number;
2229
+ /**
2230
+ * Maximum number of retry attempts allowed.
2231
+ * @property {number} [maxRetries]
2232
+ */
2233
+ maxRetries?: number;
2234
+ /**
2235
+ * Timeout duration in milliseconds.
2236
+ * @property {number} [timeoutMs]
2237
+ */
2238
+ timeoutMs?: number;
2239
+ /**
2240
+ * Estimated completion time in milliseconds (if provided by remote agent).
2241
+ * @property {number} [estimatedCompletionMs]
2242
+ */
2243
+ estimatedCompletionMs?: number;
2244
+ /**
2245
+ * Tags or labels for categorizing tasks.
2246
+ * @property {string[]} [tags]
2247
+ */
2248
+ tags?: string[];
2249
+ }
2250
+ /**
2251
+ * Represents the result of an A2A task execution.
2252
+ *
2253
+ * @interface A2ATaskResult
2254
+ */
2255
+ interface A2ATaskResult {
2256
+ /**
2257
+ * Whether the task execution was successful.
2258
+ * @property {boolean} success
2259
+ */
2260
+ success: boolean;
2261
+ /**
2262
+ * The data returned by the task execution.
2263
+ * @property {any} [data]
2264
+ */
2265
+ data?: any;
2266
+ /**
2267
+ * Error message if the task failed.
2268
+ * @property {string} [error]
2269
+ */
2270
+ error?: string;
2271
+ /**
2272
+ * Additional metadata about the execution.
2273
+ * @property {object} [metadata]
2274
+ */
2275
+ metadata?: {
2276
+ sources?: Array<{
2277
+ sourceName: string;
2278
+ url?: string;
2279
+ [key: string]: any;
2280
+ }>;
2281
+ [key: string]: any;
2282
+ };
2283
+ /**
2284
+ * Execution duration in milliseconds.
2285
+ * @property {number} [durationMs]
2286
+ */
2287
+ durationMs?: number;
2288
+ }
2289
+ /**
2290
+ * Represents a task for Agent-to-Agent (A2A) communication and delegation.
2291
+ * Used for asynchronous task delegation between AI agents in distributed systems.
2292
+ *
2293
+ * @interface A2ATask
2294
+ */
2295
+ interface A2ATask {
2296
+ /**
2297
+ * Unique identifier for the task.
2298
+ * @property {string} taskId
2299
+ */
2300
+ taskId: string;
2301
+ /**
2302
+ * The thread this task belongs to (top-level for efficient filtering).
2303
+ * @property {string} threadId
2304
+ */
2305
+ threadId: string;
2306
+ /**
2307
+ * Current status of the task.
2308
+ * @property {A2ATaskStatus} status
2309
+ */
2310
+ status: A2ATaskStatus;
2311
+ /**
2312
+ * The data payload containing task parameters and context.
2313
+ * @property {object} payload
2314
+ */
2315
+ payload: {
2316
+ /**
2317
+ * The type of task to be executed (e.g., 'analyze', 'synthesize', 'transform').
2318
+ * @property {string} taskType
2319
+ */
2320
+ taskType: string;
2321
+ /**
2322
+ * Input data required for task execution.
2323
+ * @property {any} input
2324
+ */
2325
+ input: any;
2326
+ /**
2327
+ * Instructions or configuration for the task.
2328
+ * @property {string} [instructions]
2329
+ */
2330
+ instructions?: string;
2331
+ /**
2332
+ * Additional parameters specific to the task type.
2333
+ * @property {Record<string, any>} [parameters]
2334
+ */
2335
+ parameters?: Record<string, any>;
2336
+ };
2337
+ /**
2338
+ * Information about the agent that created/requested this task.
2339
+ * @property {A2AAgentInfo} sourceAgent
2340
+ */
2341
+ sourceAgent: A2AAgentInfo;
2342
+ /**
2343
+ * Information about the agent assigned to execute this task (if assigned).
2344
+ * @property {A2AAgentInfo} [targetAgent]
2345
+ */
2346
+ targetAgent?: A2AAgentInfo;
2347
+ /**
2348
+ * Task priority level.
2349
+ * @property {A2ATaskPriority} priority
2350
+ */
2351
+ priority: A2ATaskPriority;
2352
+ /**
2353
+ * Task execution metadata.
2354
+ * @property {A2ATaskMetadata} metadata
2355
+ */
2356
+ metadata: A2ATaskMetadata;
2357
+ /**
2358
+ * The result of task execution (if completed).
2359
+ * @property {A2ATaskResult} [result]
2360
+ */
2361
+ result?: A2ATaskResult;
2362
+ /**
2363
+ * Callback URL or identifier for task completion notifications.
2364
+ * @property {string} [callbackUrl]
2365
+ */
2366
+ callbackUrl?: string;
2367
+ /**
2368
+ * Dependencies that must be completed before this task can start.
2369
+ * @property {string[]} [dependencies]
2370
+ */
2371
+ dependencies?: string[];
2372
+ }
2373
+ /**
2374
+ * Represents a request to create a new A2A task.
2375
+ *
2376
+ * @interface CreateA2ATaskRequest
2377
+ */
2378
+ interface CreateA2ATaskRequest {
2379
+ /**
2380
+ * The type of task to be executed.
2381
+ * @property {string} taskType
2382
+ */
2383
+ taskType: string;
2384
+ /**
2385
+ * Input data for the task.
2386
+ * @property {any} input
2387
+ */
2388
+ input: any;
2389
+ /**
2390
+ * Instructions for task execution.
2391
+ * @property {string} [instructions]
2392
+ */
2393
+ instructions?: string;
2394
+ /**
2395
+ * Task parameters.
2396
+ * @property {Record<string, any>} [parameters]
2397
+ */
2398
+ parameters?: Record<string, any>;
2399
+ /**
2400
+ * Task priority.
2401
+ * @property {A2ATaskPriority} [priority]
2402
+ */
2403
+ priority?: A2ATaskPriority;
2404
+ /**
2405
+ * Source agent information.
2406
+ * @property {A2AAgentInfo} sourceAgent
2407
+ */
2408
+ sourceAgent: A2AAgentInfo;
2409
+ /**
2410
+ * Preferred target agent (if any).
2411
+ * @property {A2AAgentInfo} [preferredTargetAgent]
2412
+ */
2413
+ preferredTargetAgent?: A2AAgentInfo;
2414
+ /**
2415
+ * Task dependencies.
2416
+ * @property {string[]} [dependencies]
2417
+ */
2418
+ dependencies?: string[];
2419
+ /**
2420
+ * Callback URL for notifications.
2421
+ * @property {string} [callbackUrl]
2422
+ */
2423
+ callbackUrl?: string;
2424
+ /**
2425
+ * Task timeout in milliseconds.
2426
+ * @property {number} [timeoutMs]
2427
+ */
2428
+ timeoutMs?: number;
2429
+ /**
2430
+ * Maximum retry attempts.
2431
+ * @property {number} [maxRetries]
829
2432
  */
830
- tool_call_id?: string;
2433
+ maxRetries?: number;
2434
+ /**
2435
+ * Task tags.
2436
+ * @property {string[]} [tags]
2437
+ */
2438
+ tags?: string[];
831
2439
  }
832
2440
  /**
833
- * Represents the entire prompt as an array of standardized messages (`ArtStandardMessage`).
834
- * This is the standard format produced by `PromptManager.assemblePrompt` and consumed
835
- * by `ProviderAdapter.call` for translation into provider-specific API formats.
836
- */
837
- type ArtStandardPrompt = ArtStandardMessage[];
838
- /**
839
- * Represents the contextual data gathered by Agent Logic (e.g., `PESAgent`) to be injected
840
- * into a Mustache blueprint/template by the `PromptManager.assemblePrompt` method.
2441
+ * Represents an update to an existing A2A task.
841
2442
  *
842
- * Contains standard fields commonly needed for prompts, plus allows for arbitrary
843
- * additional properties required by specific agent blueprints. Agent logic is responsible
844
- * for populating this context appropriately before calling `assemblePrompt`.
2443
+ * @interface UpdateA2ATaskRequest
845
2444
  */
846
- interface PromptContext {
847
- /** The user's current query or input relevant to this prompt generation step. */
848
- query?: string;
2445
+ interface UpdateA2ATaskRequest {
849
2446
  /**
850
- * The conversation history, typically formatted as an array suitable for the blueprint
851
- * (e.g., array of objects with `role` and `content`). Agent logic should pre-format this.
852
- * Note: While `ArtStandardPrompt` could be used, simpler structures might be preferred for blueprints.
2447
+ * Task ID to update.
2448
+ * @property {string} taskId
853
2449
  */
854
- history?: Array<{
855
- role: string;
856
- content: string;
857
- [key: string]: any;
858
- }>;
2450
+ taskId: string;
859
2451
  /**
860
- * The schemas of the tools available for use, potentially pre-formatted for the blueprint
861
- * (e.g., with `inputSchemaJson` pre-stringified).
2452
+ * New task status (if changing).
2453
+ * @property {A2ATaskStatus} [status]
862
2454
  */
863
- availableTools?: Array<ToolSchema & {
864
- inputSchemaJson?: string;
865
- }>;
2455
+ status?: A2ATaskStatus;
866
2456
  /**
867
- * The results from any tools executed in a previous step, potentially pre-formatted for the blueprint
868
- * (e.g., with `outputJson` pre-stringified).
2457
+ * Target agent assignment (if assigning/reassigning).
2458
+ * @property {A2AAgentInfo} [targetAgent]
869
2459
  */
870
- toolResults?: Array<ToolResult & {
871
- outputJson?: string;
872
- }>;
873
- /** The system prompt string to be used (resolved by agent logic from config or defaults). */
874
- systemPrompt?: string;
875
- /** Allows agent patterns (like PES) to pass any other custom data needed by their specific blueprints (e.g., `intent`, `plan`). */
876
- [key: string]: any;
2460
+ targetAgent?: A2AAgentInfo;
2461
+ /**
2462
+ * Task result (if completing).
2463
+ * @property {A2ATaskResult} [result]
2464
+ */
2465
+ result?: A2ATaskResult;
2466
+ /**
2467
+ * Additional metadata updates.
2468
+ * @property {Partial<A2ATaskMetadata>} [metadata]
2469
+ */
2470
+ metadata?: Partial<A2ATaskMetadata>;
877
2471
  }
878
2472
  /**
879
- * Represents the prompt data formatted for a specific LLM provider.
880
- * Can be a simple string or a complex object (e.g., for OpenAI Chat Completion API).
881
- * @deprecated Use `ArtStandardPrompt` as the standard intermediate format. ProviderAdapters handle final formatting.
882
- */
883
- type FormattedPrompt = ArtStandardPrompt;
884
- /**
885
- * Options for filtering data retrieved from storage.
886
- * Structure depends heavily on the underlying adapter's capabilities.
2473
+ * Defines the default identity and high-level guidance for an agent.
2474
+ * This is provided at the instance level and can be overridden by thread or call-specific prompts.
2475
+ *
2476
+ * @interface AgentPersona
887
2477
  */
888
- interface FilterOptions {
889
- /** An object defining filter criteria (e.g., `{ threadId: 'abc', type: 'TOOL_EXECUTION' }`). Structure may depend on adapter capabilities. */
890
- filter?: Record<string, any>;
891
- /** An object defining sorting criteria (e.g., `{ timestamp: 'desc' }`). */
892
- sort?: Record<string, 'asc' | 'desc'>;
893
- /** The maximum number of records to return. */
894
- limit?: number;
895
- /** The number of records to skip (for pagination). */
896
- skip?: number;
2478
+ interface AgentPersona {
2479
+ /**
2480
+ * The name or identity of the agent (e.g., "Zoi").
2481
+ * This will be used in the synthesis prompt.
2482
+ * @property {string} name
2483
+ */
2484
+ name: string;
2485
+ /**
2486
+ * The default system prompt that provides high-level guidance.
2487
+ * This serves as the base layer in the system prompt resolution hierarchy.
2488
+ * @property {string} defaultSystemPrompt
2489
+ */
2490
+ prompts: StageSpecificPrompts;
897
2491
  }
898
2492
  /**
899
- * Options for retrieving conversation messages.
2493
+ * Defines stage-specific system prompts for planning and synthesis.
2494
+ *
2495
+ * @interface StageSpecificPrompts
900
2496
  */
901
- interface MessageOptions {
902
- /** The maximum number of messages to retrieve. */
903
- limit?: number;
904
- /** Retrieve messages created before this Unix timestamp (milliseconds). */
905
- beforeTimestamp?: number;
906
- /** Retrieve messages created after this Unix timestamp (milliseconds). */
907
- afterTimestamp?: number;
908
- /** Optionally filter messages by role (e.g., retrieve only 'AI' messages). */
909
- roles?: MessageRole[];
2497
+ interface StageSpecificPrompts {
2498
+ /**
2499
+ * System prompt to guide the planning phase.
2500
+ * Focuses on reasoning, expertise, and tool selection.
2501
+ * @property {string} [planning]
2502
+ */
2503
+ planning?: string;
2504
+ /**
2505
+ * System prompt to guide the synthesis phase.
2506
+ * Focuses on tone, formatting, and final response structure.
2507
+ * @property {string} [synthesis]
2508
+ */
2509
+ synthesis?: string;
910
2510
  }
2511
+
911
2512
  /**
912
- * Options for filtering observations.
2513
+ * Filter type for A2A task notifications.
2514
+ * Allows filtering by task status, task type, agent, or priority.
913
2515
  */
914
- interface ObservationFilter {
915
- /** An array of `ObservationType` enums to filter by. If provided, only observations matching these types are returned. */
916
- types?: ObservationType[];
917
- /** Retrieve observations recorded before this Unix timestamp (milliseconds). */
918
- beforeTimestamp?: number;
919
- /** Retrieve observations recorded after this Unix timestamp (milliseconds). */
920
- afterTimestamp?: number;
2516
+ interface A2ATaskFilter {
2517
+ /** Filter by task status (single status or array of statuses) */
2518
+ status?: A2ATaskStatus | A2ATaskStatus[];
2519
+ /** Filter by task type (e.g., 'analyze', 'synthesize', 'transform') */
2520
+ taskType?: string | string[];
2521
+ /** Filter by source agent ID */
2522
+ sourceAgentId?: string;
2523
+ /** Filter by target agent ID */
2524
+ targetAgentId?: string;
2525
+ /** Filter by task priority */
2526
+ priority?: A2ATaskPriority | string;
2527
+ /** Filter by thread ID */
2528
+ threadId?: string;
921
2529
  }
922
2530
  /**
923
- * Defines the strategy for saving AgentState.
924
- * - 'explicit': AgentState is only saved when `StateManager.setAgentState()` is explicitly called by the agent.
925
- * `StateManager.saveStateIfModified()` will be a no-op for AgentState persistence.
926
- * - 'implicit': AgentState is loaded by `StateManager.loadThreadContext()`, and if modified by the agent,
927
- * `StateManager.saveStateIfModified()` will attempt to automatically persist these changes
928
- * by comparing the current state with a snapshot taken at load time.
929
- * `StateManager.setAgentState()` will still work for explicit saves.
2531
+ * Event data structure for A2A task updates.
2532
+ * Contains the updated task and metadata about the change.
930
2533
  */
931
- type StateSavingStrategy = 'explicit' | 'implicit';
932
-
2534
+ interface A2ATaskEvent {
2535
+ /** The A2A task that was updated */
2536
+ task: A2ATask;
2537
+ /** The type of event that occurred */
2538
+ eventType: 'created' | 'updated' | 'completed' | 'failed' | 'cancelled' | 'status_changed' | 'delegated';
2539
+ /** Timestamp when the event occurred */
2540
+ timestamp: number;
2541
+ /** Previous status (if applicable) for status change events */
2542
+ previousStatus?: A2ATaskStatus;
2543
+ /** Additional metadata about the event */
2544
+ metadata?: {
2545
+ /** Whether this was an automatic update or manual */
2546
+ automatic?: boolean;
2547
+ /** The component that triggered the update */
2548
+ source?: string;
2549
+ /** Any additional context */
2550
+ context?: Record<string, any>;
2551
+ };
2552
+ }
933
2553
  /**
934
- * Configuration for creating an ART instance.
2554
+ * A specialized TypedSocket for handling A2A task status updates and events.
2555
+ * Allows filtering by task status, type, agent, and other criteria.
2556
+ * Can optionally fetch historical task data from a repository.
935
2557
  */
936
- interface ArtInstanceConfig {
2558
+ declare class A2ATaskSocket extends TypedSocket<A2ATaskEvent, A2ATaskFilter> {
2559
+ private taskRepository?;
2560
+ constructor(taskRepository?: IA2ATaskRepository);
937
2561
  /**
938
- * Configuration for the storage adapter.
939
- * Can be a pre-configured `StorageAdapter` instance,
940
- * or an object specifying the type and options for a built-in adapter.
941
- * Example: `{ type: 'indexedDB', dbName: 'MyArtDB' }`
2562
+ * Notifies subscribers about a new A2A task event.
2563
+ * @param event - The A2A task event data.
942
2564
  */
943
- storage: StorageAdapter | {
944
- type: 'memory' | 'indexedDB';
945
- dbName?: string;
946
- version?: number;
947
- objectStores?: any[];
948
- };
949
- /** Configuration for the ProviderManager, defining available LLM provider adapters. */
950
- providers: ProviderManagerConfig;
2565
+ notifyTaskEvent(event: A2ATaskEvent): void;
951
2566
  /**
952
- * The agent core implementation class to use.
953
- * Defaults to `PESAgent` if not provided.
954
- * Example: `MyCustomAgentClass`
2567
+ * Convenience method to notify about a task creation.
2568
+ * @param task - The newly created A2A task.
2569
+ * @param metadata - Optional additional metadata about the creation.
955
2570
  */
956
- agentCore?: new (dependencies: any) => IAgentCore;
957
- /** An optional array of tool executor instances to register at initialization. */
958
- tools?: IToolExecutor[];
2571
+ notifyTaskCreated(task: A2ATask, metadata?: A2ATaskEvent['metadata']): void;
959
2572
  /**
960
- * Defines the strategy for saving `AgentState`. Defaults to 'explicit'.
961
- * - 'explicit': `AgentState` is only saved when `StateManager.setAgentState()` is explicitly called by the agent.
962
- * `StateManager.saveStateIfModified()` will be a no-op for `AgentState` persistence.
963
- * - 'implicit': `AgentState` is loaded by `StateManager.loadThreadContext()`. If modified by the agent,
964
- * `StateManager.saveStateIfModified()` will attempt to automatically persist these changes.
965
- * `StateManager.setAgentState()` will still work for explicit saves in this mode.
2573
+ * Convenience method to notify about a task update.
2574
+ * @param task - The updated A2A task.
2575
+ * @param previousStatus - The previous status of the task (if status changed).
2576
+ * @param metadata - Optional additional metadata about the update.
966
2577
  */
967
- stateSavingStrategy?: StateSavingStrategy;
968
- /** Optional configuration for the framework's logger. */
969
- logger?: {
970
- /** Minimum log level to output. Defaults to 'info'. */
971
- level?: LogLevel;
972
- };
2578
+ notifyTaskUpdated(task: A2ATask, previousStatus?: A2ATaskStatus, metadata?: A2ATaskEvent['metadata']): void;
973
2579
  /**
974
- * Optional default system prompt string to be used for the entire ART instance.
975
- * This can be overridden at the thread level or at the individual call level.
2580
+ * Convenience method to notify about task delegation.
2581
+ * @param task - The delegated A2A task.
2582
+ * @param metadata - Optional additional metadata about the delegation.
976
2583
  */
977
- defaultSystemPrompt?: string;
978
- }
979
-
980
- type StreamEventTypeFilter = StreamEvent['type'] | Array<StreamEvent['type']>;
981
- /**
982
- * A dedicated socket for broadcasting LLM stream events (`StreamEvent`) to UI subscribers.
983
- * Extends the generic TypedSocket and implements filtering based on `StreamEvent.type`.
984
- */
985
- declare class LLMStreamSocket extends TypedSocket<StreamEvent, StreamEventTypeFilter> {
986
- constructor();
2584
+ notifyTaskDelegated(task: A2ATask, metadata?: A2ATaskEvent['metadata']): void;
987
2585
  /**
988
- * Notifies subscribers about a new LLM stream event.
989
- * Filters based on event type if a filter is provided during subscription.
990
- * @param event - The StreamEvent data.
2586
+ * Convenience method to notify about task completion.
2587
+ * @param task - The completed A2A task.
2588
+ * @param metadata - Optional additional metadata about the completion.
991
2589
  */
992
- notifyStreamEvent(event: StreamEvent): void;
2590
+ notifyTaskCompleted(task: A2ATask, metadata?: A2ATaskEvent['metadata']): void;
2591
+ /**
2592
+ * Convenience method to notify about task failure.
2593
+ * @param task - The failed A2A task.
2594
+ * @param metadata - Optional additional metadata about the failure.
2595
+ */
2596
+ notifyTaskFailed(task: A2ATask, metadata?: A2ATaskEvent['metadata']): void;
2597
+ /**
2598
+ * Retrieves historical A2A task events, optionally filtered by criteria.
2599
+ * Note: This method constructs events from stored tasks, not from a dedicated event log.
2600
+ * @param filter - Optional A2ATaskFilter to filter the tasks.
2601
+ * @param options - Optional threadId and limit.
2602
+ * @returns A promise resolving to an array of A2A task events.
2603
+ */
2604
+ getHistory(filter?: A2ATaskFilter, options?: {
2605
+ threadId?: string;
2606
+ limit?: number;
2607
+ }): Promise<A2ATaskEvent[]>;
2608
+ /**
2609
+ * Converts an A2ATask to an A2ATaskEvent for historical data.
2610
+ * @param task - The A2ATask to convert.
2611
+ * @returns An A2ATaskEvent representing the current state of the task.
2612
+ */
2613
+ private taskToEvent;
2614
+ /**
2615
+ * Checks if an A2A task event matches the specified filter criteria.
2616
+ * @param event - The A2A task event to check.
2617
+ * @param filter - The filter criteria (optional).
2618
+ * @returns True if the event matches the filter, false otherwise.
2619
+ */
2620
+ private matchesFilter;
993
2621
  }
994
2622
 
995
2623
  /**
@@ -997,7 +2625,7 @@ declare class LLMStreamSocket extends TypedSocket<StreamEvent, StreamEventTypeFi
997
2625
  * Allows filtering by ObservationType.
998
2626
  * Can optionally fetch historical observations from a repository.
999
2627
  */
1000
- declare class ObservationSocket$1 extends TypedSocket<Observation, ObservationType | ObservationType[]> {
2628
+ declare class ObservationSocket extends TypedSocket<Observation, ObservationType | ObservationType[]> {
1001
2629
  private observationRepository?;
1002
2630
  constructor(observationRepository?: IObservationRepository);
1003
2631
  /**
@@ -1023,7 +2651,7 @@ declare class ObservationSocket$1 extends TypedSocket<Observation, ObservationTy
1023
2651
  * Allows filtering by MessageRole.
1024
2652
  * Can optionally fetch historical messages from a repository.
1025
2653
  */
1026
- declare class ConversationSocket$1 extends TypedSocket<ConversationMessage, MessageRole | MessageRole[]> {
2654
+ declare class ConversationSocket extends TypedSocket<ConversationMessage, MessageRole | MessageRole[]> {
1027
2655
  private conversationRepository?;
1028
2656
  constructor(conversationRepository?: IConversationRepository);
1029
2657
  /**
@@ -1044,6 +2672,78 @@ declare class ConversationSocket$1 extends TypedSocket<ConversationMessage, Mess
1044
2672
  }): Promise<ConversationMessage[]>;
1045
2673
  }
1046
2674
 
2675
+ /**
2676
+ * Central authentication manager for handling multiple authentication strategies.
2677
+ * Manages registration and retrieval of different auth strategies for secure connections
2678
+ * to remote services like MCP servers and A2A agents.
2679
+ */
2680
+ declare class AuthManager {
2681
+ private strategies;
2682
+ constructor();
2683
+ /**
2684
+ * Registers an authentication strategy with the given ID.
2685
+ * @param strategyId - Unique identifier for the strategy (e.g., 'default_zyntopia_auth', 'api_key_strategy')
2686
+ * @param strategy - Implementation of IAuthStrategy
2687
+ * @throws {ARTError} If strategyId is empty or null
2688
+ */
2689
+ registerStrategy(strategyId: string, strategy: IAuthStrategy): void;
2690
+ /**
2691
+ * Retrieves authentication headers from the specified strategy.
2692
+ * @param strategyId - The ID of the registered strategy to use
2693
+ * @returns Promise resolving to authentication headers
2694
+ * @throws {ARTError} If strategy is not found or authentication fails
2695
+ */
2696
+ getHeaders(strategyId: string): Promise<Record<string, string>>;
2697
+ /**
2698
+ * Checks if a strategy with the given ID is registered.
2699
+ * @param strategyId - The ID to check
2700
+ * @returns True if the strategy exists, false otherwise
2701
+ */
2702
+ hasStrategy(strategyId: string): boolean;
2703
+ /**
2704
+ * Lists all registered strategy IDs.
2705
+ * @returns Array of registered strategy IDs
2706
+ */
2707
+ getRegisteredStrategyIds(): string[];
2708
+ /**
2709
+ * Removes a registered strategy.
2710
+ * @param strategyId - The ID of the strategy to remove
2711
+ * @returns True if strategy was removed, false if it didn't exist
2712
+ */
2713
+ removeStrategy(strategyId: string): boolean;
2714
+ /**
2715
+ * Clears all registered strategies.
2716
+ * Useful for testing or complete reconfiguration.
2717
+ */
2718
+ clearAllStrategies(): void;
2719
+ /**
2720
+ * Initiates the login flow for a specific strategy.
2721
+ * @param {string} strategyId - The ID of the strategy to use for login.
2722
+ * @returns {Promise<void>} A promise that resolves when the login process is initiated.
2723
+ * @throws {ARTError} If the strategy is not found or does not support login.
2724
+ */
2725
+ login(strategyId: string): Promise<void>;
2726
+ /**
2727
+ * Handles the redirect from an OAuth provider.
2728
+ * @param {string} strategyId - The ID of the strategy that initiated the redirect.
2729
+ * @returns {Promise<void>} A promise that resolves when the redirect has been handled.
2730
+ * @throws {ARTError} If the strategy is not found or does not support handling redirects.
2731
+ */
2732
+ handleRedirect(strategyId: string): Promise<void>;
2733
+ /**
2734
+ * Logs the user out of a specific strategy.
2735
+ * @param {string} strategyId - The ID of the strategy to use for logout.
2736
+ * @throws {ARTError} If the strategy is not found or does not support logout.
2737
+ */
2738
+ logout(strategyId: string): void;
2739
+ /**
2740
+ * Checks if the user is authenticated with a specific strategy.
2741
+ * @param {string} strategyId - The ID of the strategy to check.
2742
+ * @returns {Promise<boolean>} A promise that resolves to true if authenticated, false otherwise.
2743
+ */
2744
+ isAuthenticated(strategyId: string): Promise<boolean>;
2745
+ }
2746
+
1047
2747
  /**
1048
2748
  * Interface for the central agent orchestrator.
1049
2749
  */
@@ -1100,6 +2800,28 @@ interface PromptManager {
1100
2800
  * @throws {ZodError} If validation fails (can be caught and wrapped in ARTError).
1101
2801
  */
1102
2802
  validatePrompt(prompt: ArtStandardPrompt): ArtStandardPrompt;
2803
+ /**
2804
+ * Assembles a prompt using a Mustache template (blueprint) and context data.
2805
+ * Renders the template with the provided context and parses the result as an ArtStandardPrompt.
2806
+ *
2807
+ * @param blueprint - The Mustache template containing the prompt structure.
2808
+ * @param context - The context data to inject into the template.
2809
+ * @returns A promise resolving to the assembled ArtStandardPrompt.
2810
+ * @throws {ARTError} If template rendering or JSON parsing fails.
2811
+ */
2812
+ assemblePrompt(blueprint: PromptBlueprint, context: PromptContext): Promise<ArtStandardPrompt>;
2813
+ }
2814
+ /**
2815
+ * Resolves the final system prompt from base + instance/thread/call overrides
2816
+ * using tag+variables and merge strategies.
2817
+ */
2818
+ interface SystemPromptResolver {
2819
+ resolve(input: {
2820
+ base: string;
2821
+ instance?: string | SystemPromptOverride;
2822
+ thread?: string | SystemPromptOverride;
2823
+ call?: string | SystemPromptOverride;
2824
+ }, traceId?: string): Promise<string>;
1103
2825
  }
1104
2826
  /**
1105
2827
  * Interface for parsing structured output from LLM responses.
@@ -1174,6 +2896,16 @@ interface ToolRegistry {
1174
2896
  getAvailableTools(filter?: {
1175
2897
  enabledForThreadId?: string;
1176
2898
  }): Promise<ToolSchema[]>;
2899
+ /**
2900
+ * Unregisters a tool by its unique name.
2901
+ * Implementations should silently succeed if the tool does not exist.
2902
+ */
2903
+ unregisterTool?(toolName: string): Promise<void>;
2904
+ /**
2905
+ * Unregisters multiple tools that match a predicate. Returns the number of tools removed.
2906
+ * This is useful for removing all tools belonging to a specific MCP server by name prefix.
2907
+ */
2908
+ unregisterTools?(predicate: (schema: ToolSchema) => boolean): Promise<number>;
1177
2909
  }
1178
2910
  /**
1179
2911
  * Interface for the system responsible for orchestrating tool execution.
@@ -1245,6 +2977,34 @@ interface StateManager {
1245
2977
  * @throws {ARTError} If no ThreadConfig exists for the threadId, or if the repository fails.
1246
2978
  */
1247
2979
  setAgentState(threadId: string, state: AgentState): Promise<void>;
2980
+ /**
2981
+ * Enables specific tools for a conversation thread by adding them to the thread's enabled tools list.
2982
+ * This method loads the current thread configuration, updates the enabledTools array,
2983
+ * and persists the changes. Cache is invalidated to ensure fresh data on next load.
2984
+ * @param threadId - The unique identifier of the thread.
2985
+ * @param toolNames - Array of tool names to enable for this thread.
2986
+ * @returns A promise that resolves when the tools are enabled and configuration is saved.
2987
+ * @throws {ARTError} If no ThreadConfig exists for the threadId, or if the repository fails.
2988
+ */
2989
+ enableToolsForThread(threadId: string, toolNames: string[]): Promise<void>;
2990
+ /**
2991
+ * Disables specific tools for a conversation thread by removing them from the thread's enabled tools list.
2992
+ * This method loads the current thread configuration, updates the enabledTools array,
2993
+ * and persists the changes. Cache is invalidated to ensure fresh data on next load.
2994
+ * @param threadId - The unique identifier of the thread.
2995
+ * @param toolNames - Array of tool names to disable for this thread.
2996
+ * @returns A promise that resolves when the tools are disabled and configuration is saved.
2997
+ * @throws {ARTError} If no ThreadConfig exists for the threadId, or if the repository fails.
2998
+ */
2999
+ disableToolsForThread(threadId: string, toolNames: string[]): Promise<void>;
3000
+ /**
3001
+ * Gets the list of currently enabled tools for a specific thread.
3002
+ * This is a convenience method that loads the thread context and returns the enabledTools array.
3003
+ * @param threadId - The unique identifier of the thread.
3004
+ * @returns A promise that resolves to an array of enabled tool names, or empty array if no tools are enabled.
3005
+ * @throws {ARTError} If the thread context cannot be loaded.
3006
+ */
3007
+ getEnabledToolsForThread(threadId: string): Promise<string[]>;
1248
3008
  }
1249
3009
  /**
1250
3010
  * Interface for managing conversation history.
@@ -1319,29 +3079,18 @@ interface ITypedSocket<DataType, FilterType = any> {
1319
3079
  limit?: number;
1320
3080
  }): Promise<DataType[]>;
1321
3081
  }
1322
- /**
1323
- * TypedSocket specifically for Observation data.
1324
- * FilterType is ObservationType or array of ObservationType.
1325
- */
1326
- interface ObservationSocket extends ITypedSocket<Observation, ObservationType | ObservationType[]> {
1327
- }
1328
- /**
1329
- * TypedSocket specifically for ConversationMessage data.
1330
- * FilterType is MessageRole or array of MessageRole.
1331
- */
1332
- interface ConversationSocket extends ITypedSocket<ConversationMessage, MessageRole | MessageRole[]> {
1333
- }
1334
-
1335
3082
  /**
1336
3083
  * Interface for the system providing access to UI communication sockets.
1337
3084
  */
1338
3085
  interface UISystem {
1339
3086
  /** Returns the singleton instance of the ObservationSocket. */
1340
- getObservationSocket(): ObservationSocket$1;
3087
+ getObservationSocket(): ObservationSocket;
1341
3088
  /** Returns the singleton instance of the ConversationSocket. */
1342
- getConversationSocket(): ConversationSocket$1;
3089
+ getConversationSocket(): ConversationSocket;
1343
3090
  /** Returns the singleton instance of the LLMStreamSocket. */
1344
3091
  getLLMStreamSocket(): LLMStreamSocket;
3092
+ /** Returns the singleton instance of the A2ATaskSocket. */
3093
+ getA2ATaskSocket(): A2ATaskSocket;
1345
3094
  }
1346
3095
  /**
1347
3096
  * Interface for a storage adapter, providing a generic persistence layer.
@@ -1401,10 +3150,92 @@ interface IStateRepository {
1401
3150
  setThreadContext(threadId: string, context: ThreadContext): Promise<void>;
1402
3151
  }
1403
3152
  /**
1404
- * Represents the fully initialized and configured ART Framework client instance.
1405
- * This object is the main entry point for interacting with the framework after setup.
1406
- * It provides access to the core processing method and key subsystems.
3153
+ * Interface for managing A2A (Agent-to-Agent) task persistence and retrieval.
3154
+ */
3155
+ interface IA2ATaskRepository {
3156
+ /**
3157
+ * Creates a new A2A task in the repository.
3158
+ * @param task - The A2ATask object to create.
3159
+ * @returns A promise that resolves when the task is successfully stored.
3160
+ * @throws {ARTError} If the task cannot be created (e.g., duplicate taskId, validation errors).
3161
+ */
3162
+ createTask(task: A2ATask): Promise<void>;
3163
+ /**
3164
+ * Retrieves an A2A task by its unique identifier.
3165
+ * @param taskId - The unique identifier of the task.
3166
+ * @returns A promise resolving to the A2ATask object if found, or null if not found.
3167
+ * @throws {ARTError} If an error occurs during retrieval.
3168
+ */
3169
+ getTask(taskId: string): Promise<A2ATask | null>;
3170
+ /**
3171
+ * Updates an existing A2A task with new information.
3172
+ * @param taskId - The unique identifier of the task to update.
3173
+ * @param updates - Partial A2ATask object containing the fields to update.
3174
+ * @returns A promise that resolves when the task is successfully updated.
3175
+ * @throws {ARTError} If the task is not found or cannot be updated.
3176
+ */
3177
+ updateTask(taskId: string, updates: Partial<A2ATask>): Promise<void>;
3178
+ /**
3179
+ * Removes an A2A task from the repository.
3180
+ * @param taskId - The unique identifier of the task to delete.
3181
+ * @returns A promise that resolves when the task is successfully deleted.
3182
+ * @throws {ARTError} If the task is not found or cannot be deleted.
3183
+ */
3184
+ deleteTask(taskId: string): Promise<void>;
3185
+ /**
3186
+ * Retrieves tasks associated with a specific thread.
3187
+ * @param threadId - The thread identifier to filter tasks.
3188
+ * @param filter - Optional filter criteria for task status, priority, or assigned agent.
3189
+ * @returns A promise resolving to an array of A2ATask objects matching the criteria.
3190
+ */
3191
+ getTasksByThread(threadId: string, filter?: {
3192
+ status?: A2ATaskStatus | A2ATaskStatus[];
3193
+ priority?: A2ATaskPriority;
3194
+ assignedAgentId?: string;
3195
+ }): Promise<A2ATask[]>;
3196
+ /**
3197
+ * Retrieves tasks assigned to a specific agent.
3198
+ * @param agentId - The agent identifier to filter tasks.
3199
+ * @param filter - Optional filter criteria for task status or priority.
3200
+ * @returns A promise resolving to an array of A2ATask objects assigned to the agent.
3201
+ */
3202
+ getTasksByAgent(agentId: string, filter?: {
3203
+ status?: A2ATaskStatus | A2ATaskStatus[];
3204
+ priority?: A2ATaskPriority;
3205
+ }): Promise<A2ATask[]>;
3206
+ /**
3207
+ * Retrieves tasks based on their current status.
3208
+ * @param status - The task status(es) to filter by.
3209
+ * @param options - Optional query parameters like limit and pagination.
3210
+ * @returns A promise resolving to an array of A2ATask objects with the specified status.
3211
+ */
3212
+ getTasksByStatus(status: A2ATaskStatus | A2ATaskStatus[], options?: {
3213
+ limit?: number;
3214
+ offset?: number;
3215
+ }): Promise<A2ATask[]>;
3216
+ }
3217
+ /**
3218
+ * Interface for an authentication strategy that can provide authorization headers.
3219
+ * This enables pluggable security for remote service connections (MCP servers, A2A agents, etc.)
1407
3220
  */
3221
+ interface IAuthStrategy {
3222
+ /**
3223
+ * Asynchronously retrieves the authentication headers.
3224
+ * This might involve checking a cached token, refreshing it if expired, and then returning it.
3225
+ * @returns A promise that resolves to a record of header keys and values.
3226
+ * @throws {ARTError} If authentication fails or cannot be obtained.
3227
+ */
3228
+ getAuthHeaders(): Promise<Record<string, string>>;
3229
+ /** Optional: Initiates the login flow for the strategy. */
3230
+ login?(): Promise<void>;
3231
+ /** Optional: Handles the redirect from the authentication server. */
3232
+ handleRedirect?(): Promise<void>;
3233
+ /** Optional: Logs the user out. */
3234
+ logout?(): void;
3235
+ /** Optional: Checks if the user is authenticated. */
3236
+ isAuthenticated?(): Promise<boolean>;
3237
+ }
3238
+
1408
3239
  interface ArtInstance {
1409
3240
  /** The main method to process a user query using the configured Agent Core. */
1410
3241
  readonly process: IAgentCore['process'];
@@ -1418,6 +3249,206 @@ interface ArtInstance {
1418
3249
  readonly toolRegistry: ToolRegistry;
1419
3250
  /** Accessor for the Observation Manager, used for recording and retrieving observations. */
1420
3251
  readonly observationManager: ObservationManager;
3252
+ /** Accessor for the Auth Manager, used for handling authentication. */
3253
+ readonly authManager?: AuthManager | null;
3254
+ }
3255
+
3256
+ /**
3257
+ * @class McpClientController
3258
+ * Controls the MCP client, including OAuth flow, connection, and tool calls.
3259
+ */
3260
+ declare class McpClientController {
3261
+ baseUrl: URL;
3262
+ private scopes;
3263
+ private client;
3264
+ private transport;
3265
+ private oauthDiscovery;
3266
+ private tokenManager;
3267
+ private sessionId;
3268
+ private readonly protocolVersion;
3269
+ /**
3270
+ * Creates an instance of McpClientController.
3271
+ * @private
3272
+ * @param {string} baseUrl - The base URL of the MCP server.
3273
+ * @param {string[]} [scopes] - The OAuth scopes to request.
3274
+ */
3275
+ private constructor();
3276
+ /**
3277
+ * Creates a new instance of McpClientController.
3278
+ * @param {string} baseUrl - The base URL of the MCP server.
3279
+ * @param {string[]} [scopes] - The OAuth scopes to request.
3280
+ * @returns {McpClientController} A new instance of McpClientController.
3281
+ */
3282
+ static create(baseUrl: string, scopes?: string[]): McpClientController;
3283
+ /**
3284
+ * Discovers the authorization server metadata.
3285
+ * @private
3286
+ * @returns {Promise<void>}
3287
+ */
3288
+ private discoverAuthorizationServer;
3289
+ /**
3290
+ * Registers the client with the authorization server.
3291
+ * @private
3292
+ * @returns {Promise<string>} A promise that resolves to the client ID.
3293
+ */
3294
+ private registerClient;
3295
+ /**
3296
+ * Starts the OAuth flow by redirecting the user to the authorization server.
3297
+ * @returns {Promise<void>}
3298
+ */
3299
+ startOAuth(): Promise<void>;
3300
+ /**
3301
+ * Handles the OAuth callback, exchanging the authorization code for an access token.
3302
+ * @returns {Promise<boolean>} A promise that resolves to true if the callback was handled, false otherwise.
3303
+ */
3304
+ maybeHandleCallback(): Promise<boolean>;
3305
+ /**
3306
+ * Loads an existing session from session storage.
3307
+ */
3308
+ loadExistingSession(): void;
3309
+ /**
3310
+ * Checks if the user is authenticated.
3311
+ * @returns {boolean} True if the user is authenticated, false otherwise.
3312
+ */
3313
+ isAuthenticated(): boolean;
3314
+ /**
3315
+ * Connects to the MCP server.
3316
+ * @returns {Promise<void>}
3317
+ */
3318
+ connect(): Promise<void>;
3319
+ /**
3320
+ * Ensures that the client is connected to the MCP server.
3321
+ * @returns {Promise<void>}
3322
+ */
3323
+ ensureConnected(): Promise<void>;
3324
+ /**
3325
+ * Lists the available tools on the MCP server.
3326
+ * @returns {Promise<{ name: string; description?: string }[]>} A promise that resolves to a list of tools.
3327
+ */
3328
+ listTools(): Promise<{
3329
+ name: string;
3330
+ description?: string;
3331
+ }[]>;
3332
+ /**
3333
+ * Calls a tool on the MCP server.
3334
+ * @param {string} name - The name of the tool to call.
3335
+ * @param {any} args - The arguments to pass to the tool.
3336
+ * @returns {Promise<any>} A promise that resolves to the result of the tool call.
3337
+ */
3338
+ callTool(name: string, args: any): Promise<any>;
3339
+ /**
3340
+ * Logs out from the MCP server and clears the session.
3341
+ * @returns {Promise<void>}
3342
+ */
3343
+ logout(): Promise<void>;
3344
+ }
3345
+
3346
+ /**
3347
+ * Manages MCP (Model Context Protocol) server connections and tool registration.
3348
+ *
3349
+ * @remarks
3350
+ * The `McpManager` is responsible for:
3351
+ * - Connecting to configured MCP servers.
3352
+ * - Discovering available tools from servers.
3353
+ * - Creating proxy tools that wrap MCP server tools.
3354
+ * - Registering proxy tools with the {@link ToolRegistry}.
3355
+ * - Managing server health and status.
3356
+ * - Handling thread-specific tool activation/deactivation.
3357
+ *
3358
+ * This enables dynamic tool loading from external MCP servers while maintaining
3359
+ * seamless integration with the ART Framework's tool system.
3360
+ *
3361
+ * @see {@link McpProxyTool} for the tool wrapper implementation.
3362
+ * @see {@link McpClientController} for the underlying client implementation.
3363
+ *
3364
+ * @class McpManager
3365
+ */
3366
+ declare class McpManager {
3367
+ private configManager;
3368
+ private toolRegistry;
3369
+ private authManager?;
3370
+ private activeConnections;
3371
+ /**
3372
+ * Creates an instance of McpManager.
3373
+ *
3374
+ * @param toolRegistry The tool registry to register proxy tools with.
3375
+ * @param _stateManager The state manager (not currently used).
3376
+ * @param authManager The authentication manager.
3377
+ */
3378
+ constructor(toolRegistry: ToolRegistry, _stateManager: StateManager, authManager?: AuthManager);
3379
+ /**
3380
+ * Initializes the McpManager, discovers and registers tools from configured servers.
3381
+ *
3382
+ * @param mcpConfig The MCP configuration.
3383
+ * @param [mcpConfig.enabled=true] Whether MCP is enabled.
3384
+ * @param mcpConfig.discoveryEndpoint The endpoint for discovering MCP servers.
3385
+ * @returns A promise that resolves when initialization is complete.
3386
+ */
3387
+ initialize(mcpConfig?: {
3388
+ enabled?: boolean;
3389
+ discoveryEndpoint?: string;
3390
+ }): Promise<void>;
3391
+ /**
3392
+ * Shuts down all active MCP connections.
3393
+ *
3394
+ * @returns A promise that resolves when all connections are shut down.
3395
+ */
3396
+ shutdown(): Promise<void>;
3397
+ /**
3398
+ * Gets an existing connection or creates a new one for a given server ID.
3399
+ *
3400
+ * @param serverId The ID of the server to connect to.
3401
+ * @returns A promise that resolves to the MCP client controller.
3402
+ */
3403
+ getOrCreateConnection(serverId: string): Promise<McpClientController>;
3404
+ /**
3405
+ * Ensures that the application has CORS access to the target URL.
3406
+ *
3407
+ * @private
3408
+ * @param targetUrl The URL to check for CORS access.
3409
+ * @returns A promise that resolves when CORS access is confirmed or granted.
3410
+ */
3411
+ private ensureCorsAccess;
3412
+ /**
3413
+ * Searches a discovery service for available MCP servers.
3414
+ *
3415
+ * @param [discoveryEndpoint] The URL of the discovery service.
3416
+ * @returns A promise resolving to an array of McpServerConfig.
3417
+ */
3418
+ discoverAvailableServers(discoveryEndpoint?: string): Promise<McpServerConfig[]>;
3419
+ /**
3420
+ * Converts a Zyntopia service entry to an McpServerConfig.
3421
+ *
3422
+ * @private
3423
+ * @param service The service entry to convert.
3424
+ * @returns The converted McpServerConfig or null if conversion fails.
3425
+ */
3426
+ private convertServiceToMcpCard;
3427
+ /**
3428
+ * Installs a server by persisting its config, discovering tools via MCP, and
3429
+ * registering proxy tools. Returns the finalized config with accurate tools.
3430
+ *
3431
+ * @param server The server configuration to install.
3432
+ * @returns A promise that resolves to the finalized server configuration.
3433
+ */
3434
+ installServer(server: McpServerConfig): Promise<McpServerConfig>;
3435
+ /**
3436
+ * Waits for the client to be authenticated.
3437
+ *
3438
+ * @private
3439
+ * @param client The MCP client controller.
3440
+ * @param timeoutMs The timeout in milliseconds.
3441
+ * @returns A promise that resolves when the client is authenticated.
3442
+ * @throws {ARTError} If the authentication window times out.
3443
+ */
3444
+ private waitForAuth;
3445
+ /**
3446
+ * Uninstalls a server: disconnects, removes registered proxy tools, and deletes config.
3447
+ *
3448
+ * @param serverId The ID of the server to uninstall.
3449
+ * @returns A promise that resolves when the server is uninstalled.
3450
+ */
3451
+ uninstallServer(serverId: string): Promise<void>;
1421
3452
  }
1422
3453
 
1423
3454
  /**
@@ -1438,9 +3469,199 @@ interface ArtInstance {
1438
3469
  declare function createArtInstance(config: ArtInstanceConfig): Promise<ArtInstance>;
1439
3470
 
1440
3471
  /**
1441
- * Defines the dependencies required by the PESAgent constructor.
1442
- * These are typically provided by the AgentFactory during instantiation.
3472
+ * Configuration for the AgentDiscoveryService
3473
+ */
3474
+ interface AgentDiscoveryConfig {
3475
+ /** Base URL for the discovery endpoint. If not provided, a default will be used. */
3476
+ discoveryEndpoint?: string;
3477
+ /** Timeout for discovery requests in milliseconds */
3478
+ timeoutMs?: number;
3479
+ /** Whether to cache discovered agents */
3480
+ enableCaching?: boolean;
3481
+ /** Cache TTL in milliseconds */
3482
+ cacheTtlMs?: number;
3483
+ }
3484
+ /**
3485
+ * Service for discovering A2A protocol compatible agents.
3486
+ * Implements the A2A discovery standards for finding and identifying compatible agents.
3487
+ */
3488
+ declare class AgentDiscoveryService {
3489
+ private readonly config;
3490
+ private agentCache;
3491
+ /**
3492
+ * Creates an instance of AgentDiscoveryService.
3493
+ * @param {Partial<AgentDiscoveryConfig>} config - The configuration for the service.
3494
+ * @see A2AAgentCard
3495
+ */
3496
+ constructor(config?: Partial<AgentDiscoveryConfig>);
3497
+ /**
3498
+ * Discovers all available A2A agents from the discovery endpoint.
3499
+ * @param traceId - Optional trace ID for request tracking
3500
+ * @returns Promise resolving to array of discovered A2A agents
3501
+ * @throws {ARTError} If discovery fails or no agents are found
3502
+ */
3503
+ discoverAgents(traceId?: string): Promise<A2AAgentInfo[]>;
3504
+ /**
3505
+ * Finds the top K A2A agents for a specific task type, ranked by suitability.
3506
+ * This method acts as a pre-filter, returning a list of the most promising candidates
3507
+ * for an LLM to make the final selection from.
3508
+ * @param taskType - The type of task (e.g., 'analysis', 'research', 'generation')
3509
+ * @param topK - The maximum number of agents to return.
3510
+ * @param traceId - Optional trace ID for request tracking.
3511
+ * @returns Promise resolving to a ranked array of matching agents.
3512
+ * @remarks TODO: Revisit and enhance the scoring algorithm.
3513
+ */
3514
+ findTopAgentsForTask(taskType: string, topK?: number, traceId?: string): Promise<A2AAgentInfo[]>;
3515
+ /**
3516
+ * Calculates semantic similarity score between capability and task type.
3517
+ * This uses common word patterns to identify relationships without hardcoded mappings.
3518
+ * @private
3519
+ */
3520
+ private calculateSemanticScore;
3521
+ /**
3522
+ * Finds agents by specific capabilities.
3523
+ * @param capabilities - Array of required capabilities
3524
+ * @param traceId - Optional trace ID for request tracking
3525
+ * @returns Promise resolving to agents that have all specified capabilities
3526
+ */
3527
+ findAgentsByCapabilities(capabilities: string[], traceId?: string): Promise<A2AAgentInfo[]>;
3528
+ /**
3529
+ * Clears the agent cache.
3530
+ */
3531
+ clearCache(): void;
3532
+ /**
3533
+ * Gets cached agents if they exist and are not expired.
3534
+ * @private
3535
+ */
3536
+ private getCachedAgents;
3537
+ /**
3538
+ * Sets agents in cache with current timestamp.
3539
+ * @private
3540
+ */
3541
+ private setCachedAgents;
3542
+ /**
3543
+ * Transforms an A2A Agent Card to the ART framework's A2AAgentInfo format.
3544
+ * @private
3545
+ */
3546
+ private transformToA2AAgentInfo;
3547
+ }
3548
+
3549
+ /**
3550
+ * Configuration options for the TaskDelegationService
3551
+ */
3552
+ interface TaskDelegationConfig {
3553
+ /** Default timeout for task delegation requests in milliseconds */
3554
+ defaultTimeoutMs?: number;
3555
+ /** Maximum number of retry attempts for failed requests */
3556
+ maxRetries?: number;
3557
+ /** Base delay between retry attempts in milliseconds */
3558
+ retryDelayMs?: number;
3559
+ /** Whether to use exponential backoff for retries */
3560
+ useExponentialBackoff?: boolean;
3561
+ /** The base callback URL for receiving A2A task updates. */
3562
+ callbackUrl?: string;
3563
+ }
3564
+ /**
3565
+ * Response structure for A2A task status queries
1443
3566
  */
3567
+ interface TaskStatusResponse {
3568
+ /** The task ID */
3569
+ taskId: string;
3570
+ /** Current status of the task */
3571
+ status: A2ATaskStatus;
3572
+ /** Progress percentage (0-100) if available */
3573
+ progress?: number;
3574
+ /** Task result if completed */
3575
+ result?: A2ATaskResult;
3576
+ /** Error information if failed */
3577
+ error?: string;
3578
+ /** Additional metadata */
3579
+ metadata?: Record<string, any>;
3580
+ }
3581
+ /**
3582
+ * Service responsible for delegating A2A tasks to remote agents.
3583
+ * Implements the A2A protocol for task submission, tracking, and completion.
3584
+ *
3585
+ * This service handles:
3586
+ * - Finding suitable agents for specific task types
3587
+ * - Submitting tasks to remote agents via HTTP API
3588
+ * - Tracking task status and handling updates
3589
+ * - Managing task lifecycle according to A2A protocol
3590
+ * - Error handling and retry logic
3591
+ * - Integration with local task repository for persistence
3592
+ */
3593
+ declare class TaskDelegationService {
3594
+ private readonly config;
3595
+ private readonly taskRepository;
3596
+ /**
3597
+ * Creates an instance of TaskDelegationService.
3598
+ * @param {IA2ATaskRepository} taskRepository - The repository for persisting task status.
3599
+ * @param {TaskDelegationConfig} [config={}] - Configuration for the service.
3600
+ */
3601
+ constructor(taskRepository: IA2ATaskRepository, config?: TaskDelegationConfig);
3602
+ /**
3603
+ * Delegates a list of A2A tasks to suitable remote agents.
3604
+ * For each task, finds the best agent and submits the task.
3605
+ *
3606
+ * @param {A2ATask[]} tasks - Array of A2A tasks to delegate
3607
+ * @param {string} [traceId] - Optional trace ID for request tracking
3608
+ * @returns {Promise<A2ATask[]>} Promise resolving to array of successfully delegated tasks
3609
+ */
3610
+ delegateTasks(tasks: A2ATask[], traceId?: string): Promise<A2ATask[]>;
3611
+ /**
3612
+ * Delegates a single A2A task to a suitable remote agent.
3613
+ *
3614
+ * @param {A2ATask} task - The A2A task to delegate
3615
+ * @param {string} [traceId] - Optional trace ID for request tracking
3616
+ * @returns {Promise<A2ATask | null>} Promise resolving to the updated task or null if delegation failed
3617
+ */
3618
+ delegateTask(task: A2ATask, traceId?: string): Promise<A2ATask | null>;
3619
+ /**
3620
+ * Submits a task to a specific remote agent using A2A protocol.
3621
+ *
3622
+ * @private
3623
+ * @param {A2ATask} task - The A2A task to submit
3624
+ * @param {A2AAgentInfo} targetAgent - The target agent to submit the task to
3625
+ * @param {string} [traceId] - Optional trace ID for request tracking
3626
+ * @returns {Promise<TaskSubmissionResponse>} Promise resolving to the submission response
3627
+ */
3628
+ private submitTaskToAgent;
3629
+ /**
3630
+ * Checks the status of a delegated task from the remote agent.
3631
+ *
3632
+ * @param {A2ATask} task - The A2A task to check status for
3633
+ * @param {string} [traceId] - Optional trace ID for request tracking
3634
+ * @returns {Promise<TaskStatusResponse | null>} Promise resolving to the current task status
3635
+ */
3636
+ checkTaskStatus(task: A2ATask, traceId?: string): Promise<TaskStatusResponse | null>;
3637
+ /**
3638
+ * Updates a local A2A task based on remote status information.
3639
+ *
3640
+ * @param {A2ATask} task - The local A2A task to update
3641
+ * @param {TaskStatusResponse} statusResponse - The status response from the remote agent
3642
+ * @param {string} [traceId] - Optional trace ID for request tracking
3643
+ * @returns {Promise<A2ATask>} Promise resolving to the updated task
3644
+ */
3645
+ updateTaskFromRemoteStatus(task: A2ATask, statusResponse: TaskStatusResponse, traceId?: string): Promise<A2ATask>;
3646
+ /**
3647
+ * Generates a callback URL for webhook notifications.
3648
+ * This would typically point to an endpoint in the local system.
3649
+ *
3650
+ * @private
3651
+ * @param {string} taskId - The task ID to generate callback URL for
3652
+ * @returns {string} The callback URL string
3653
+ */
3654
+ private generateCallbackUrl;
3655
+ /**
3656
+ * Cancels a delegated task on the remote agent.
3657
+ *
3658
+ * @param {A2ATask} task - The A2A task to cancel
3659
+ * @param {string} [traceId] - Optional trace ID for request tracking
3660
+ * @returns {Promise<boolean>} Promise resolving to whether cancellation was successful
3661
+ */
3662
+ cancelTask(task: A2ATask, traceId?: string): Promise<boolean>;
3663
+ }
3664
+
1444
3665
  interface PESAgentDependencies {
1445
3666
  /** Manages thread configuration and state. */
1446
3667
  stateManager: StateManager;
@@ -1449,7 +3670,6 @@ interface PESAgentDependencies {
1449
3670
  * This serves as a custom prompt part if no thread-specific or call-specific
1450
3671
  * system prompt is provided. It's appended to the agent's base system prompt.
1451
3672
  */
1452
- instanceDefaultCustomSystemPrompt?: string;
1453
3673
  /** Manages conversation history. */
1454
3674
  conversationManager: ConversationManager;
1455
3675
  /** Registry for available tools. */
@@ -1464,6 +3684,16 @@ interface PESAgentDependencies {
1464
3684
  toolSystem: ToolSystem;
1465
3685
  /** Provides access to UI communication sockets. */
1466
3686
  uiSystem: UISystem;
3687
+ /** Repository for A2A tasks. */
3688
+ a2aTaskRepository: IA2ATaskRepository;
3689
+ /** Service for discovering A2A agents. */
3690
+ agentDiscoveryService?: AgentDiscoveryService | null;
3691
+ /** Service for delegating A2A tasks. */
3692
+ taskDelegationService?: TaskDelegationService | null;
3693
+ /** Resolver for standardized system prompt composition. */
3694
+ systemPromptResolver: SystemPromptResolver;
3695
+ /** Optional: Defines the default identity and high-level guidance for the agent. */
3696
+ persona?: AgentPersona;
1467
3697
  }
1468
3698
  /**
1469
3699
  * Implements the Plan-Execute-Synthesize (PES) agent orchestration logic.
@@ -1475,7 +3705,6 @@ interface PESAgentDependencies {
1475
3705
  * It constructs standardized prompts (`ArtStandardPrompt`) directly as JavaScript objects
1476
3706
  * for the `ReasoningEngine`. It processes the `StreamEvent` output from the reasoning engine for both planning and synthesis.
1477
3707
  *
1478
- * @implements {IAgentCore}
1479
3708
  * // @see {PromptManager} // Removed
1480
3709
  * @see {ReasoningEngine}
1481
3710
  * @see {ArtStandardPrompt}
@@ -1483,50 +3712,75 @@ interface PESAgentDependencies {
1483
3712
  */
1484
3713
  declare class PESAgent implements IAgentCore {
1485
3714
  private readonly deps;
1486
- /** The base system prompt inherent to this agent. */
1487
- private readonly defaultSystemPrompt;
1488
- /**
1489
- * Stores the instance-level default custom system prompt, passed during construction.
1490
- * Used in the system prompt hierarchy if no thread or call-level prompt is specified.
1491
- */
1492
- private readonly instanceDefaultCustomSystemPrompt?;
3715
+ private readonly persona;
1493
3716
  /**
1494
3717
  * Creates an instance of the PESAgent.
1495
- * @param dependencies - An object containing instances of all required subsystems (managers, registries, etc.).
3718
+ * @param {module:core/agents/pes-agent.PESAgentDependencies} dependencies - An object containing instances of all required subsystems (managers, registries, etc.).
1496
3719
  */
1497
3720
  constructor(dependencies: PESAgentDependencies);
1498
3721
  /**
1499
3722
  * Executes the full Plan-Execute-Synthesize cycle for a given user query.
1500
3723
  *
1501
3724
  * **Workflow:**
1502
- * 1. **Initiation & Config:** Loads thread configuration. Resolves the final system prompt based on a hierarchy:
1503
- * Call-level (`AgentProps.options.systemPrompt`) > Thread-level (`ThreadConfig.systemPrompt`) >
1504
- * Instance-level (`ArtInstanceConfig.defaultSystemPrompt` via constructor) > Agent's base prompt.
1505
- * The resolved custom part is appended to the agent's base prompt.
1506
- * 2. **Data Gathering:** Gathers history, available tools, the resolved system prompt, and query.
1507
- * 3. **Planning Prompt Construction:** Directly constructs the `ArtStandardPrompt` object/array for planning.
1508
- * 4. **Planning LLM Call:** Sends the planning prompt object to the `reasoningEngine` (requesting streaming). Consumes the `StreamEvent` stream, buffers the output text, and handles potential errors.
1509
- * 5. **Planning Output Parsing:** Parses the buffered planning output text to extract intent, plan, and tool calls using `outputParser.parsePlanningOutput`.
1510
- * 6. **Tool Execution:** Executes identified tool calls via the `toolSystem`.
1511
- * 7. **Data Gathering (Synthesis):** Gathers the original query, plan, tool results, history, etc.
1512
- * 8. **Synthesis Prompt Construction:** Directly constructs the `ArtStandardPrompt` object/array for synthesis.
1513
- * 9. **Synthesis LLM Call:** Sends the synthesis prompt object to the `reasoningEngine` (requesting streaming). Consumes the `StreamEvent` stream, buffers the final response text, and handles potential errors.
1514
- * 10. **Finalization:** Saves the final AI message, updates state if needed, records observations, and returns the result.
1515
- *
1516
- * **Error Handling:**
1517
- * - Errors during critical phases (planning/synthesis LLM call) will throw an `ARTError`. Prompt construction errors are less likely but possible if data is malformed.
1518
- * - Errors during tool execution or synthesis LLM call might result in a 'partial' success status, potentially using the error message as the final response content.
3725
+ * 1. **Initiation & Config:** Loads thread configuration and resolves system prompt
3726
+ * 2. **Data Gathering:** Gathers history, available tools
3727
+ * 3. **Planning:** LLM call for planning and parsing
3728
+ * 4. **A2A Discovery & Delegation:** Identifies and delegates A2A tasks to remote agents
3729
+ * 5. **Tool Execution:** Executes identified local tool calls
3730
+ * 6. **Synthesis:** LLM call for final response generation including A2A results
3731
+ * 7. **Finalization:** Saves messages and cleanup
1519
3732
  *
1520
3733
  * @param {AgentProps} props - The input properties containing the user query, threadId, userId, traceId, etc.
1521
3734
  * @returns {Promise<AgentFinalResponse>} A promise resolving to the final response, including the AI message and execution metadata.
1522
- * @throws {ARTError} If a critical error occurs that prevents the agent from completing the process (e.g., config loading, planning failure).
1523
- * @see {AgentProps}
1524
- * @see {AgentFinalResponse}
1525
- * // @see {PromptContext} // Removed - context is implicit in object construction
1526
- * @see {ArtStandardPrompt}
1527
- * @see {StreamEvent}
3735
+ * @throws {ARTError} If a critical error occurs that prevents the agent from completing the process.
1528
3736
  */
1529
3737
  process(props: AgentProps): Promise<AgentFinalResponse>;
3738
+ /**
3739
+ * Loads thread configuration and resolves the system prompt hierarchy.
3740
+ * @private
3741
+ */
3742
+ private _loadConfiguration;
3743
+ /**
3744
+ * Gathers conversation history for the current thread.
3745
+ * @private
3746
+ */
3747
+ private _gatherHistory;
3748
+ /**
3749
+ * Gathers available tools for the current thread.
3750
+ * @private
3751
+ */
3752
+ private _gatherTools;
3753
+ /**
3754
+ * Performs the planning phase including LLM call and output parsing.
3755
+ * @private
3756
+ */
3757
+ private _performPlanning;
3758
+ /**
3759
+ * Delegates A2A tasks identified in the planning phase.
3760
+ * @private
3761
+ */
3762
+ private _delegateA2ATasks;
3763
+ /**
3764
+ * Waits for A2A tasks to complete with configurable timeout.
3765
+ * Polls task status periodically and updates local repository with results.
3766
+ * @private
3767
+ */
3768
+ private _waitForA2ACompletion;
3769
+ /**
3770
+ * Executes local tools identified during planning.
3771
+ * @private
3772
+ */
3773
+ private _executeLocalTools;
3774
+ /**
3775
+ * Performs the synthesis phase including LLM call for final response generation.
3776
+ * @private
3777
+ */
3778
+ private _performSynthesis;
3779
+ /**
3780
+ * Finalizes the agent execution by saving the final message and performing cleanup.
3781
+ * @private
3782
+ */
3783
+ private _finalize;
1530
3784
  /**
1531
3785
  * Formats conversation history messages for direct inclusion in ArtStandardPrompt.
1532
3786
  * Converts internal MessageRole to ArtStandardMessageRole.
@@ -1546,12 +3800,21 @@ declare class PESAgent implements IAgentCore {
1546
3800
  * - Simple demos or examples where persistence isn't needed.
1547
3801
  * - Ephemeral agents that don't require long-term memory.
1548
3802
  *
1549
- * @implements {StorageAdapter}
3803
+ * It provides a simple key-value store for various data types used within the
3804
+ * ART framework, such as conversation history, agent state, and observations.
3805
+ *
3806
+ * @see {@link StorageAdapter} for the interface definition.
1550
3807
  */
1551
3808
  declare class InMemoryStorageAdapter implements StorageAdapter {
1552
3809
  private storage;
1553
3810
  /**
1554
- * Initializes the adapter. This is a no-op for the in-memory adapter.
3811
+ * Creates an instance of InMemoryStorageAdapter.
3812
+ * @see StorageAdapter
3813
+ */
3814
+ constructor();
3815
+ /**
3816
+ * Initializes the adapter. This is a no-op for the in-memory adapter
3817
+ * and is provided for interface compatibility.
1555
3818
  * @param _config - Optional configuration (ignored by this adapter).
1556
3819
  * @returns A promise that resolves immediately.
1557
3820
  */
@@ -1629,7 +3892,8 @@ interface IndexedDBConfig {
1629
3892
  * **Important:** The `init()` method *must* be called and awaited before performing
1630
3893
  * any other database operations (get, set, delete, query).
1631
3894
  *
1632
- * @implements {StorageAdapter}
3895
+ * @see {@link StorageAdapter} for the interface it implements.
3896
+ * @see {@link IndexedDBConfig} for configuration options.
1633
3897
  */
1634
3898
  declare class IndexedDBStorageAdapter implements StorageAdapter {
1635
3899
  private db;
@@ -1640,7 +3904,8 @@ declare class IndexedDBStorageAdapter implements StorageAdapter {
1640
3904
  /**
1641
3905
  * Creates an instance of IndexedDBStorageAdapter.
1642
3906
  * Note: The database connection is not opened until `init()` is called.
1643
- * @param config - Configuration options including database name, version, and required object stores.
3907
+ * @param {module:integrations/storage/indexedDB.IndexedDBConfig} config - Configuration options including database name, version, and required object stores.
3908
+ * @see https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
1644
3909
  */
1645
3910
  constructor(config: IndexedDBConfig);
1646
3911
  /**
@@ -1702,6 +3967,8 @@ declare class IndexedDBStorageAdapter implements StorageAdapter {
1702
3967
  * @param filterOptions - Options for filtering, sorting, skipping, and limiting results.
1703
3968
  * @returns A promise resolving to an array of deep copies of the matching items.
1704
3969
  * @throws {Error} If the database is not initialized, the store doesn't exist, or a database error occurs.
3970
+ * @remarks TODO: Implement more advanced querying using IndexedDB indexes and cursors.
3971
+ * This will improve performance for large datasets.
1705
3972
  */
1706
3973
  query<T>(collection: string, filterOptions: FilterOptions): Promise<T[]>;
1707
3974
  /**
@@ -1720,6 +3987,112 @@ declare class IndexedDBStorageAdapter implements StorageAdapter {
1720
3987
  clearAll(): Promise<void>;
1721
3988
  }
1722
3989
 
3990
+ interface SupabaseConfig {
3991
+ /** Supabase project URL, e.g., https://xyzcompany.supabase.co */
3992
+ url: string;
3993
+ /** Supabase anon or service key. Prefer service key on server-side only. */
3994
+ apiKey: string;
3995
+ /** Optional schema name (default 'public'). */
3996
+ schema?: string;
3997
+ /**
3998
+ * Table names to use. These map ART collections to Supabase.
3999
+ * If you customize collection names in repositories, adjust accordingly.
4000
+ */
4001
+ tables?: {
4002
+ conversations?: string;
4003
+ observations?: string;
4004
+ state?: string;
4005
+ a2a_tasks?: string;
4006
+ };
4007
+ /**
4008
+ * Optional: pass a pre-initialized Supabase client (from @supabase/supabase-js)
4009
+ * Useful in environments where you already manage the client and auth.
4010
+ */
4011
+ client?: any;
4012
+ }
4013
+ /**
4014
+ * A Supabase-backed StorageAdapter implementation.
4015
+ *
4016
+ * Expectations/assumptions:
4017
+ * - Each collection maps to a table with a primary key column named 'id' (text/uuid).
4018
+ * - We store JSON columns for flexible data where needed. However, repositories
4019
+ * store fully shaped rows; this adapter just persists and retrieves whole objects.
4020
+ * - For query(), we implement basic equality filters per FilterOptions.filter keys,
4021
+ * plus limit/skip and a single-key sort.
4022
+ */
4023
+ declare class SupabaseStorageAdapter implements StorageAdapter {
4024
+ private client;
4025
+ private config;
4026
+ private schema;
4027
+ private tables;
4028
+ /**
4029
+ * Creates an instance of SupabaseStorageAdapter.
4030
+ * @see SupabaseConfig
4031
+ */
4032
+ constructor(config: SupabaseConfig);
4033
+ /**
4034
+ * Configures the adapter with the provided Supabase settings.
4035
+ * @private
4036
+ * @param {SupabaseConfig} config - The configuration for the adapter.
4037
+ */
4038
+ private configure;
4039
+ /**
4040
+ * Initializes the Supabase client if it hasn't been provided already.
4041
+ * @returns {Promise<void>} A promise that resolves when the client is initialized.
4042
+ */
4043
+ init(): Promise<void>;
4044
+ /**
4045
+ * Maps a collection name to a Supabase table name.
4046
+ * @private
4047
+ * @param {string} collection - The name of the collection.
4048
+ * @returns {string} The name of the Supabase table.
4049
+ */
4050
+ private tableForCollection;
4051
+ /**
4052
+ * Retrieves a single item from a collection by its ID.
4053
+ * @template T
4054
+ * @param {string} collection - The name of the collection.
4055
+ * @param {string} id - The ID of the item to retrieve.
4056
+ * @returns {Promise<T | null>} A promise that resolves with the item, or null if not found.
4057
+ */
4058
+ get<T>(collection: string, id: string): Promise<T | null>;
4059
+ /**
4060
+ * Saves (upserts) an item in a collection.
4061
+ * @template T
4062
+ * @param {string} collection - The name of the collection.
4063
+ * @param {string} id - The ID of the item to save.
4064
+ * @param {T} data - The data to save.
4065
+ * @returns {Promise<void>} A promise that resolves when the item is saved.
4066
+ */
4067
+ set<T>(collection: string, id: string, data: T): Promise<void>;
4068
+ /**
4069
+ * Deletes an item from a collection by its ID.
4070
+ * @param {string} collection - The name of the collection.
4071
+ * @param {string} id - The ID of the item to delete.
4072
+ * @returns {Promise<void>} A promise that resolves when the item is deleted.
4073
+ */
4074
+ delete(collection: string, id: string): Promise<void>;
4075
+ /**
4076
+ * Queries items in a collection.
4077
+ * @template T
4078
+ * @param {string} collection - The name of the collection.
4079
+ * @param {FilterOptions} filterOptions - The options for filtering, sorting, and pagination.
4080
+ * @returns {Promise<T[]>} A promise that resolves with an array of items.
4081
+ */
4082
+ query<T>(collection: string, filterOptions: FilterOptions): Promise<T[]>;
4083
+ /**
4084
+ * Clears all items from a collection.
4085
+ * @param {string} collection - The name of the collection.
4086
+ * @returns {Promise<void>} A promise that resolves when the collection is cleared.
4087
+ */
4088
+ clearCollection(collection: string): Promise<void>;
4089
+ /**
4090
+ * Clears all items from all collections.
4091
+ * @returns {Promise<void>} A promise that resolves when all collections are cleared.
4092
+ */
4093
+ clearAll(): Promise<void>;
4094
+ }
4095
+
1723
4096
  /**
1724
4097
  * Configuration options required for the `GeminiAdapter`.
1725
4098
  */
@@ -1742,6 +4115,7 @@ declare class GeminiAdapter implements ProviderAdapter {
1742
4115
  * Creates an instance of GeminiAdapter.
1743
4116
  * @param {GeminiAdapterOptions} options - Configuration options for the adapter.
1744
4117
  * @throws {Error} If `apiKey` is missing in the options.
4118
+ * @see https://ai.google.dev/api/rest
1745
4119
  */
1746
4120
  constructor(options: GeminiAdapterOptions);
1747
4121
  /**
@@ -1763,6 +4137,7 @@ declare class GeminiAdapter implements ProviderAdapter {
1763
4137
  * @see {CallOptions}
1764
4138
  * @see {StreamEvent}
1765
4139
  * @see {LLMMetadata}
4140
+ * @see https://ai.google.dev/api/rest/v1beta/models/generateContent
1766
4141
  */
1767
4142
  call(prompt: ArtStandardPrompt, options: CallOptions): Promise<AsyncIterable<StreamEvent>>;
1768
4143
  /**
@@ -1804,7 +4179,7 @@ interface OpenAIAdapterOptions {
1804
4179
  * Handles formatting requests and parsing responses for OpenAI.
1805
4180
  * Uses raw `fetch` for now.
1806
4181
  *
1807
- * @implements {ProviderAdapter}
4182
+ * @see {@link ProviderAdapter} for the interface definition.
1808
4183
  */
1809
4184
  declare class OpenAIAdapter implements ProviderAdapter {
1810
4185
  readonly providerName = "openai";
@@ -1813,8 +4188,9 @@ declare class OpenAIAdapter implements ProviderAdapter {
1813
4188
  private apiBaseUrl;
1814
4189
  /**
1815
4190
  * Creates an instance of the OpenAIAdapter.
1816
- * @param options - Configuration options including the API key and optional model/baseURL overrides.
4191
+ * @param {OpenAIAdapterOptions} options - Configuration options including the API key and optional model/baseURL overrides.
1817
4192
  * @throws {Error} If the API key is missing.
4193
+ * @see https://platform.openai.com/docs/api-reference
1818
4194
  */
1819
4195
  constructor(options: OpenAIAdapterOptions);
1820
4196
  /**
@@ -1824,6 +4200,7 @@ declare class OpenAIAdapter implements ProviderAdapter {
1824
4200
  * @param {ArtStandardPrompt} prompt - The standardized prompt messages.
1825
4201
  * @param {CallOptions} options - Call options, including `threadId`, `traceId`, `stream` preference, and any OpenAI-specific parameters (like `temperature`, `max_tokens`) passed through.
1826
4202
  * @returns {Promise<AsyncIterable<StreamEvent>>} A promise resolving to an AsyncIterable of StreamEvent objects.
4203
+ * @see https://platform.openai.com/docs/api-reference/chat/create
1827
4204
  */
1828
4205
  call(prompt: ArtStandardPrompt, options: CallOptions): Promise<AsyncIterable<StreamEvent>>;
1829
4206
  /**
@@ -1865,7 +4242,8 @@ interface AnthropicAdapterOptions {
1865
4242
  *
1866
4243
  * Handles formatting requests, parsing responses, streaming, and tool use.
1867
4244
  *
1868
- * @implements {ProviderAdapter}
4245
+ * @see {@link ProviderAdapter} for the interface definition.
4246
+ * @see {@link AnthropicAdapterOptions} for configuration options.
1869
4247
  */
1870
4248
  declare class AnthropicAdapter implements ProviderAdapter {
1871
4249
  readonly providerName = "anthropic";
@@ -1891,26 +4269,40 @@ declare class AnthropicAdapter implements ProviderAdapter {
1891
4269
  */
1892
4270
  call(prompt: ArtStandardPrompt, options: CallOptions): Promise<AsyncIterable<StreamEvent>>;
1893
4271
  /**
1894
- * Prepares request options. Currently a placeholder for potential future additions
1895
- * like Anthropic beta headers for specific models or features (e.g., prompt caching).
1896
- * The user's example code shows more advanced beta header logic.
4272
+ * Prepares request options, adding Anthropic beta headers if applicable for features like prompt caching.
4273
+ * This allows opting into experimental features on a per-request basis.
4274
+ * @private
4275
+ * @param {string} modelId - The model ID being used for the request, to determine which beta features may apply.
4276
+ * @returns {Anthropic.RequestOptions} The request options object, potentially with custom headers.
1897
4277
  */
1898
4278
  private getRequestOptions;
1899
4279
  /**
1900
4280
  * Translates the provider-agnostic `ArtStandardPrompt` into the Anthropic SDK Messages format.
4281
+ * It handles system prompts, message merging for consecutive roles, and validates message structure.
1901
4282
  *
1902
4283
  * @private
1903
4284
  * @param {ArtStandardPrompt} artPrompt - The input `ArtStandardPrompt` array.
1904
- * @returns {{ systemPrompt?: string; messages: AnthropicSDKMessageParam[] }}
1905
- * @throws {ARTError} If translation encounters an issue.
4285
+ * @returns {{ systemPrompt?: string; messages: Anthropic.Messages.MessageParam[] }} An object containing the extracted system prompt and the array of Anthropic-formatted messages.
4286
+ * @throws {ARTError} If translation encounters an issue, such as multiple system messages or invalid message roles.
1906
4287
  */
1907
4288
  private translateToAnthropicSdk;
1908
4289
  /**
1909
- * Maps a single ArtStandardMessage to Anthropic SDK's content format (string or AnthropicSDKContentBlockParam[]).
4290
+ * Maps a single `ArtStandardMessage` to Anthropic SDK's content format.
4291
+ * This can be a simple string or an array of `ContentBlockParam` for complex content
4292
+ * like tool calls and tool results.
4293
+ *
4294
+ * @private
4295
+ * @param {ArtStandardMessage} artMsg - The ART standard message to map.
4296
+ * @returns {string | AnthropicSDKContentBlockParam[]} The translated content for the Anthropic API.
4297
+ * @throws {ARTError} If tool call arguments are not valid JSON or if a tool result is missing its ID.
1910
4298
  */
1911
4299
  private mapArtMessageToAnthropicContent;
1912
4300
  /**
1913
- * Translates ART ToolSchema array to Anthropic's tool format.
4301
+ * Translates an array of `ToolSchema` from the ART framework format to Anthropic's specific tool format.
4302
+ * @private
4303
+ * @param {ToolSchema[]} artTools - An array of ART tool schemas.
4304
+ * @returns {AnthropicSDKTool[]} An array of tools formatted for the Anthropic API.
4305
+ * @throws {ARTError} If a tool's `inputSchema` is invalid.
1914
4306
  */
1915
4307
  private translateArtToolsToAnthropic;
1916
4308
  }
@@ -1931,14 +4323,11 @@ interface OpenRouterAdapterOptions {
1931
4323
  appName?: string;
1932
4324
  }
1933
4325
  /**
1934
- * Implements the `ProviderAdapter` interface for interacting with the OpenRouter API,
1935
- * which provides access to various LLMs through an OpenAI-compatible interface.
4326
+ * This adapter provides a unified interface for various LLM providers through OpenRouter,
4327
+ * handling prompt conversion and response parsing into the ART `StreamEvent` format.
1936
4328
  *
1937
- * Handles formatting requests and parsing responses for OpenRouter's chat completions endpoint.
1938
- * Handles formatting requests and parsing responses for OpenRouter's chat completions endpoint.
1939
- * Note: Streaming is **not yet implemented** for this adapter. Calls requesting streaming will yield an error and end.
1940
- *
1941
- * @implements {ProviderAdapter}
4329
+ * @see {@link ProviderAdapter} for the interface it implements.
4330
+ * @see {@link OpenRouterAdapterOptions} for configuration options.
1942
4331
  */
1943
4332
  declare class OpenRouterAdapter implements ProviderAdapter {
1944
4333
  readonly providerName = "openrouter";
@@ -1949,8 +4338,9 @@ declare class OpenRouterAdapter implements ProviderAdapter {
1949
4338
  private appName?;
1950
4339
  /**
1951
4340
  * Creates an instance of the OpenRouterAdapter.
1952
- * @param options - Configuration options including the API key, the specific OpenRouter model identifier, and optional headers/baseURL.
4341
+ * @param {OpenRouterAdapterOptions} options - Configuration options including the API key, the specific OpenRouter model identifier, and optional headers/baseURL.
1953
4342
  * @throws {Error} If the API key or model identifier is missing.
4343
+ * @see https://openrouter.ai/docs
1954
4344
  */
1955
4345
  constructor(options: OpenRouterAdapterOptions);
1956
4346
  /**
@@ -1962,6 +4352,7 @@ declare class OpenRouterAdapter implements ProviderAdapter {
1962
4352
  * @param {ArtStandardPrompt} prompt - The standardized prompt messages.
1963
4353
  * @param {CallOptions} options - Call options, including `threadId`, `traceId`, `stream`, and any OpenAI-compatible generation parameters.
1964
4354
  * @returns {Promise<AsyncIterable<StreamEvent>>} A promise resolving to an AsyncIterable of StreamEvent objects. If streaming is requested, it yields an error event and ends.
4355
+ * @see https://openrouter.ai/docs#api-reference-chat-completions
1965
4356
  */
1966
4357
  call(prompt: ArtStandardPrompt, options: CallOptions): Promise<AsyncIterable<StreamEvent>>;
1967
4358
  /**
@@ -1988,13 +4379,11 @@ interface DeepSeekAdapterOptions {
1988
4379
  apiBaseUrl?: string;
1989
4380
  }
1990
4381
  /**
1991
- * Implements the `ProviderAdapter` interface for interacting with the DeepSeek API,
1992
- * which uses an OpenAI-compatible Chat Completions endpoint.
1993
- *
1994
- * Handles formatting requests and parsing responses for DeepSeek models.
1995
- * Note: Streaming is **not yet implemented** for this adapter. Calls requesting streaming will yield an error and end.
4382
+ * This adapter provides a consistent interface for ART agents to use DeepSeek models,
4383
+ * handling the conversion of standard ART prompts to the DeepSeek API format and
4384
+ * parsing the responses into the ART `StreamEvent` format.
1996
4385
  *
1997
- * @implements {ProviderAdapter}
4386
+ * @see {@link ProviderAdapter} for the interface it implements.
1998
4387
  */
1999
4388
  declare class DeepSeekAdapter implements ProviderAdapter {
2000
4389
  readonly providerName = "deepseek";
@@ -2003,8 +4392,9 @@ declare class DeepSeekAdapter implements ProviderAdapter {
2003
4392
  private apiBaseUrl;
2004
4393
  /**
2005
4394
  * Creates an instance of the DeepSeekAdapter.
2006
- * @param options - Configuration options including the API key and optional model/baseURL overrides.
4395
+ * @param {DeepSeekAdapterOptions} options - Configuration options including the API key and optional model/baseURL overrides.
2007
4396
  * @throws {Error} If the API key is missing.
4397
+ * @see https://platform.deepseek.com/api-docs
2008
4398
  */
2009
4399
  constructor(options: DeepSeekAdapterOptions);
2010
4400
  /**
@@ -2016,6 +4406,7 @@ declare class DeepSeekAdapter implements ProviderAdapter {
2016
4406
  * @param {ArtStandardPrompt} prompt - The standardized prompt messages.
2017
4407
  * @param {CallOptions} options - Call options, including `threadId`, `traceId`, `stream`, and any OpenAI-compatible generation parameters.
2018
4408
  * @returns {Promise<AsyncIterable<StreamEvent>>} A promise resolving to an AsyncIterable of StreamEvent objects. If streaming is requested, it yields an error event and ends.
4409
+ * @see https://platform.deepseek.com/api-docs/api/create-chat-completion/index.html
2019
4410
  */
2020
4411
  call(prompt: ArtStandardPrompt, options: CallOptions): Promise<AsyncIterable<StreamEvent>>;
2021
4412
  /**
@@ -2056,7 +4447,8 @@ interface OllamaAdapterOptions {
2056
4447
  *
2057
4448
  * Handles formatting requests, parsing responses, streaming, and tool use.
2058
4449
  *
2059
- * @implements {ProviderAdapter}
4450
+ * @see {@link ProviderAdapter} for the interface definition.
4451
+ * @see {@link OllamaAdapterOptions} for configuration options.
2060
4452
  */
2061
4453
  declare class OllamaAdapter implements ProviderAdapter {
2062
4454
  readonly providerName = "ollama";
@@ -2079,20 +4471,33 @@ declare class OllamaAdapter implements ProviderAdapter {
2079
4471
  call(prompt: ArtStandardPrompt, options: CallOptions): Promise<AsyncIterable<StreamEvent>>;
2080
4472
  /**
2081
4473
  * Translates the provider-agnostic `ArtStandardPrompt` into the OpenAI API's `OpenAIMessage[]` format.
2082
- * This is a common utility function that can be shared or adapted from other OpenAI-compatible adapters.
4474
+ * This method can handle model-specific formatting, such as merging consecutive messages for certain models.
4475
+ * @private
4476
+ * @param {ArtStandardPrompt} artPrompt - The input `ArtStandardPrompt` array.
4477
+ * @param {string} [modelIdForTransform] - The model ID, used to determine if special formatting is needed.
4478
+ * @returns {OpenAIMessage[]} The `OpenAIMessage[]` array formatted for the OpenAI API.
2083
4479
  */
2084
4480
  private translateToOpenAI;
4481
+ /**
4482
+ * Maps a single `ArtStandardMessage` to an `OpenAIMessage`.
4483
+ * @private
4484
+ * @param {ArtStandardMessage} message - The message to map.
4485
+ * @returns {OpenAIMessage} The mapped message.
4486
+ * @throws {ARTError} If an unsupported or invalid message role is encountered.
4487
+ */
2085
4488
  private mapArtMessageToOpenAIMessage;
2086
4489
  /**
2087
- * Translates ART ToolSchema array to OpenAI's tool format.
4490
+ * Translates an array of `ToolSchema` from the ART framework format to OpenAI's specific tool format.
4491
+ * @private
4492
+ * @param {ToolSchema[]} artTools - An array of ART tool schemas.
4493
+ * @returns {OpenAI.Chat.Completions.ChatCompletionTool[]} An array of tools formatted for the OpenAI API.
4494
+ * @throws {ARTError} If a tool's schema is invalid.
2088
4495
  */
2089
4496
  private translateArtToolsToOpenAI;
2090
4497
  /**
2091
- * Optional method for graceful shutdown.
2092
- * For Ollama, which is typically a separate local server, this adapter
2093
- * doesn't manage persistent connections that need explicit closing.
2094
- * The OpenAI client used internally might have its own cleanup, but
2095
- * it's generally handled by garbage collection.
4498
+ * Optional method for graceful shutdown. For Ollama, which is typically a separate
4499
+ * local server, this adapter doesn't manage persistent connections that need explicit closing.
4500
+ * @returns {Promise<void>} A promise that resolves when the shutdown is complete.
2096
4501
  */
2097
4502
  shutdown(): Promise<void>;
2098
4503
  }
@@ -2101,7 +4506,13 @@ declare class OllamaAdapter implements ProviderAdapter {
2101
4506
  * An ART Framework tool that safely evaluates mathematical expressions using the mathjs library.
2102
4507
  * It supports basic arithmetic, variables via a scope, complex numbers, and a predefined list of safe functions.
2103
4508
  *
2104
- * @implements {IToolExecutor}
4509
+ * This tool is designed to be used within the ART framework's `ToolSystem`.
4510
+ * It provides a safe way to perform mathematical calculations by leveraging
4511
+ * the `mathjs` library. The tool validates the input expression to ensure it's a
4512
+ * single, valid mathematical expression before evaluation.
4513
+ *
4514
+ * @see {@link IToolExecutor} for the interface it implements.
4515
+ * @see {@link ToolSystem} for the system that manages and executes tools.
2105
4516
  */
2106
4517
  declare class CalculatorTool implements IToolExecutor {
2107
4518
  /** The unique name identifier for this tool. */
@@ -2128,25 +4539,217 @@ declare class CalculatorTool implements IToolExecutor {
2128
4539
  execute(input: any, context: ExecutionContext): Promise<ToolResult>;
2129
4540
  }
2130
4541
 
4542
+ /**
4543
+ * Configuration for the PKCE OAuth 2.0 authentication strategy.
4544
+ */
4545
+ interface PKCEOAuthConfig {
4546
+ /** The OAuth 2.0 authorization endpoint URL. */
4547
+ authorizationEndpoint: string;
4548
+ /** The OAuth 2.0 token endpoint URL. */
4549
+ tokenEndpoint: string;
4550
+ /** The client ID for the application. */
4551
+ clientId: string;
4552
+ /** The redirect URI for the application. */
4553
+ redirectUri: string;
4554
+ /** The scopes to request (space-separated). */
4555
+ scopes: string;
4556
+ /** Optional: The resource parameter to specify the target audience (for MCP servers). */
4557
+ resource?: string;
4558
+ /** Open login in a new tab (default true for ART MCP flows). */
4559
+ openInNewTab?: boolean;
4560
+ /** BroadcastChannel name used to receive auth codes from callback tab (default 'art-auth'). */
4561
+ channelName?: string;
4562
+ }
4563
+ /**
4564
+ * Implements the OAuth 2.0 Authorization Code Flow with PKCE (Proof Key for Code Exchange).
4565
+ * This is the recommended, most secure method for authenticating users in browser-based applications.
4566
+ */
4567
+ declare class PKCEOAuthStrategy implements IAuthStrategy {
4568
+ private config;
4569
+ private cachedToken;
4570
+ private codeVerifierForPendingLogin;
4571
+ private loginWaiter;
4572
+ private channel?;
4573
+ /**
4574
+ * Creates an instance of PKCEOAuthStrategy.
4575
+ * @param {PKCEOAuthConfig} config - The configuration for the PKCE OAuth 2.0 strategy.
4576
+ */
4577
+ constructor(config: PKCEOAuthConfig);
4578
+ /**
4579
+ * Initiates the PKCE login flow by redirecting the user to the authorization endpoint.
4580
+ * @returns {Promise<void>} A promise that resolves when the login process is complete.
4581
+ */
4582
+ login(): Promise<void>;
4583
+ /**
4584
+ * Handles the redirect from the authorization server.
4585
+ * This method should be called on the redirect URI page.
4586
+ * It exchanges the authorization code for an access token.
4587
+ * @returns {Promise<void>} A promise that resolves when the redirect has been handled.
4588
+ */
4589
+ handleRedirect(): Promise<void>;
4590
+ /**
4591
+ * Gets the authentication headers, automatically handling token refresh if needed.
4592
+ * @returns {Promise<Record<string, string>>} A promise that resolves to the authentication headers.
4593
+ */
4594
+ getAuthHeaders(): Promise<Record<string, string>>;
4595
+ /**
4596
+ * Clears the cached token.
4597
+ */
4598
+ logout(): void;
4599
+ /**
4600
+ * Checks if there is a valid, non-expired token.
4601
+ * @returns {Promise<boolean>} A promise that resolves to true if the token is valid, false otherwise.
4602
+ */
4603
+ isAuthenticated(): Promise<boolean>;
4604
+ /**
4605
+ * Generates a random string for the code verifier.
4606
+ * @returns {string} The generated code verifier.
4607
+ */
4608
+ private generateCodeVerifier;
4609
+ /**
4610
+ * Generates a code challenge from a code verifier.
4611
+ * @param {string} verifier - The code verifier.
4612
+ * @returns {Promise<string>} A promise that resolves to the code challenge.
4613
+ */
4614
+ private generateCodeChallenge;
4615
+ /**
4616
+ * Encodes a byte array into a base64 URL-safe string.
4617
+ * @param {Uint8Array} bytes - The byte array to encode.
4618
+ * @returns {string} The base64 URL-safe encoded string.
4619
+ */
4620
+ private base64UrlEncode;
4621
+ /**
4622
+ * Refreshes the access token using the refresh token.
4623
+ * @returns {Promise<void>} A promise that resolves when the token has been refreshed.
4624
+ */
4625
+ private refreshToken;
4626
+ /**
4627
+ * Exchanges an authorization code for an access token.
4628
+ * @param {string} code - The authorization code.
4629
+ * @returns {Promise<void>} A promise that resolves when the token exchange is complete.
4630
+ */
4631
+ private exchangeCodeForToken;
4632
+ }
4633
+
4634
+ /**
4635
+ * A proxy tool that wraps an MCP server tool and implements the {@link IToolExecutor} interface.
4636
+ *
4637
+ * @remarks
4638
+ * This allows MCP server tools to be used seamlessly within the ART Framework.
4639
+ *
4640
+ * @see {@link McpManager} for the system that manages these proxy tools.
4641
+ * @see {@link IToolExecutor} for the interface it implements.
4642
+ *
4643
+ * @class McpProxyTool
4644
+ */
4645
+ declare class McpProxyTool implements IToolExecutor {
4646
+ readonly schema: ToolSchema;
4647
+ private card;
4648
+ private toolDefinition;
4649
+ private mcpManager;
4650
+ /**
4651
+ * Creates an instance of McpProxyTool.
4652
+ *
4653
+ * @param card Configuration for the MCP server hosting this tool.
4654
+ * @param toolDefinition The tool definition from the MCP server.
4655
+ * @param mcpManager The MCP manager for managing connections.
4656
+ */
4657
+ constructor(card: McpServerConfig, toolDefinition: McpToolDefinition, mcpManager: McpManager);
4658
+ /**
4659
+ * Executes the tool by making a request to the MCP server.
4660
+ *
4661
+ * @param input Validated input arguments for the tool.
4662
+ * @param context Execution context containing threadId, traceId, etc.
4663
+ * @returns A promise resolving to the tool result.
4664
+ */
4665
+ execute(input: any, context: ExecutionContext): Promise<ToolResult>;
4666
+ /**
4667
+ * Gets the original tool name from the MCP server.
4668
+ *
4669
+ * @returns The original tool name.
4670
+ */
4671
+ getOriginalToolName(): string;
4672
+ /**
4673
+ * Gets the MCP server configuration.
4674
+ *
4675
+ * @returns The server configuration.
4676
+ */
4677
+ getServerConfig(): McpServerConfig;
4678
+ /**
4679
+ * Gets the MCP tool definition.
4680
+ *
4681
+ * @returns The tool definition.
4682
+ */
4683
+ getToolDefinition(): McpToolDefinition;
4684
+ }
4685
+
2131
4686
  /**
2132
4687
  * Generates a unique Version 4 UUID (Universally Unique Identifier) string.
4688
+ *
4689
+ * @remarks
2133
4690
  * Uses the underlying 'uuid' library's v4 implementation.
4691
+ *
2134
4692
  * @returns A randomly generated UUID string (e.g., "f47ac10b-58cc-4372-a567-0e02b2c3d479").
4693
+ *
4694
+ * @see {@link https://www.npmjs.com/package/uuid | uuid npm package}
2135
4695
  */
2136
4696
  declare const generateUUID: () => string;
2137
4697
 
2138
4698
  /**
2139
- * Main entry point for the ART Framework library.
2140
- * This file exports the primary factory function (`createArtInstance`),
2141
- * core components, adapters, types, interfaces, and utilities needed
2142
- * to build and run ART agents.
4699
+ * ART (Agentic Reasoning & Tool-use) Framework - Main Entry Point
4700
+ * -----------------------------------------------------------------
4701
+ *
4702
+ * Welcome to the ART framework! This file is the primary public API surface for the library.
4703
+ * It's structured to provide a clear and intuitive experience for developers,
4704
+ * whether you're just getting started or building advanced, custom agentic systems.
4705
+ *
4706
+ * --- Quick Start ---
4707
+ * For most use cases, you'll only need `createArtInstance` and the associated types.
4708
+ *
4709
+ * Example:
4710
+ * ```ts
4711
+ * import { createArtInstance } from 'art-framework';
4712
+ * import type { ArtInstanceConfig } from 'art-framework';
4713
+ *
4714
+ * const config: ArtInstanceConfig = {
4715
+ * storage: { type: 'memory' },
4716
+ * providers: {
4717
+ * openai: { adapter: 'openai', apiKey: '...' }
4718
+ * },
4719
+ * tools: [new CalculatorTool()],
4720
+ * persona: {
4721
+ * name: 'MyAgent',
4722
+ * prompts: {
4723
+ * synthesis: 'You are MyAgent. Always answer in rhyme.'
4724
+ * }
4725
+ * }
4726
+ * };
4727
+ *
4728
+ * const art = await createArtInstance(config);
4729
+ * const response = await art.process({ query: "Hello, world!" });
4730
+ * ```
4731
+ *
4732
+ * --- API Structure ---
4733
+ * 1. **Core Factory**: The main function to create an ART instance.
4734
+ * 2. **Primary Interfaces & Types**: Essential types for configuration and interaction.
4735
+ * 3. **Built-in Components**: Concrete implementations of adapters, tools, and agents.
4736
+ * 4. **Advanced Systems & Managers**: Lower-level components for building custom logic.
4737
+ * 5. **Utilities**: Helper functions and classes.
4738
+ *
4739
+ * @module ART
2143
4740
  */
2144
4741
  /**
2145
- * The main function to create and initialize an ART instance.
2146
- * @see {@link ./core/agent-factory.ts} for implementation details.
4742
+ * The main factory function to create and initialize a complete ART framework instance.
4743
+ * This is the recommended starting point for all users. It simplifies setup by
4744
+ * assembling all necessary components based on the provided configuration.
4745
+ * @param {ArtInstanceConfig} config - The configuration object for the ART instance.
4746
+ * @returns {Promise<ArtInstance>} A promise that resolves to a ready-to-use ART instance.
4747
+ * @see {@link ArtInstanceConfig} for configuration options.
2147
4748
  */
2148
4749
 
2149
- /** The current version of the ART Framework package. */
4750
+ /**
4751
+ * The current version of the ART Framework package.
4752
+ */
2150
4753
  declare const VERSION = "0.2.8";
2151
4754
 
2152
- export { ARTError, AdapterInstantiationError, type AgentFinalResponse, type AgentOptions, type AgentProps, type AgentState, AnthropicAdapter, ApiQueueTimeoutError, type ArtInstance, type ArtInstanceConfig, type ArtStandardMessage, type ArtStandardMessageRole, ArtStandardMessageSchema, type ArtStandardPrompt, ArtStandardPromptSchema, type AvailableProviderEntry, CalculatorTool, type CallOptions, type ConversationManager, type ConversationMessage, type ConversationSocket, DeepSeekAdapter, ErrorCode, type ExecutionContext, type ExecutionMetadata, type FilterOptions, type FormattedPrompt, GeminiAdapter, type IAgentCore, type IConversationRepository, type IObservationRepository, type IProviderManager, type IStateRepository, type IToolExecutor, type ITypedSocket, InMemoryStorageAdapter, IndexedDBStorageAdapter, type JsonObjectSchema, type JsonSchema, type LLMMetadata, LLMStreamSocket, LocalInstanceBusyError, LocalProviderConflictError, LogLevel, Logger, type ManagedAdapterAccessor, type MessageOptions, MessageRole, ModelCapability, type Observation, type ObservationFilter, type ObservationManager, type ObservationSocket, ObservationType, OllamaAdapter, type OllamaAdapterOptions, OpenAIAdapter, OpenRouterAdapter, type OutputParser, PESAgent, type ParsedToolCall, type PromptContext, type PromptManager, type ProviderAdapter, type ProviderManagerConfig, type ReasoningEngine, type RuntimeProviderConfig, type StateManager, type StateSavingStrategy, type StorageAdapter, type StreamEvent, type ThreadConfig, type ThreadContext, type ToolRegistry, type ToolResult, type ToolSchema, type ToolSystem, TypedSocket, type UISystem, UnknownProviderError, type UnsubscribeFunction, VERSION, createArtInstance, generateUUID };
4755
+ export { type A2AAgentInfo, type A2ATask, type A2ATaskEvent, type A2ATaskFilter, type A2ATaskMetadata, A2ATaskPriority, type A2ATaskResult, A2ATaskSocket, A2ATaskStatus, ARTError, AdapterInstantiationError, type AgentDiscoveryConfig, AgentDiscoveryService, type AgentFinalResponse, type AgentOptions, type AgentPersona, type AgentProps, type AgentState, AnthropicAdapter, type AnthropicAdapterOptions, ApiQueueTimeoutError, type ArtInstance, type ArtInstanceConfig, type ArtStandardMessage, type ArtStandardMessageRole, ArtStandardMessageSchema, type ArtStandardPrompt, ArtStandardPromptSchema, AuthManager, type AvailableProviderEntry, CalculatorTool, type CallOptions, type ConversationManager, type ConversationMessage, ConversationSocket, type CreateA2ATaskRequest, DeepSeekAdapter, type DeepSeekAdapterOptions, ErrorCode, type ExecutionContext, type ExecutionMetadata, type FilterOptions, type FormattedPrompt, GeminiAdapter, type GeminiAdapterOptions, type IA2ATaskRepository, type IAgentCore, type IAuthStrategy, type IConversationRepository, type IObservationRepository, type IProviderManager, type IStateRepository, type IToolExecutor, type ITypedSocket, InMemoryStorageAdapter, IndexedDBStorageAdapter, type JsonObjectSchema, type JsonSchema, type LLMMetadata, LLMStreamSocket, LocalInstanceBusyError, LocalProviderConflictError, LogLevel, Logger, type LoggerConfig, type ManagedAdapterAccessor, McpClientController, McpManager, type McpManagerConfig, McpProxyTool, type McpResource, type McpResourceTemplate, type McpServerConfig, type McpServerStatus, type McpToolDefinition, type MessageOptions, MessageRole, ModelCapability, type Observation, type ObservationFilter, type ObservationManager, ObservationSocket, ObservationType, OllamaAdapter, type OllamaAdapterOptions, OpenAIAdapter, type OpenAIAdapterOptions, OpenRouterAdapter, type OpenRouterAdapterOptions, type OutputParser, PESAgent, type PKCEOAuthConfig, PKCEOAuthStrategy, type ParsedToolCall, type PromptBlueprint, type PromptContext, type PromptManager, type ProviderAdapter, type ProviderManagerConfig, type ReasoningEngine, type RuntimeProviderConfig, type StageSpecificPrompts, type StateManager, type StateSavingStrategy, type StorageAdapter, type StreamEvent, type StreamEventTypeFilter, SupabaseStorageAdapter, type SystemPromptMergeStrategy, type SystemPromptOverride, type SystemPromptResolver, type SystemPromptSpec, type SystemPromptsRegistry, type TaskDelegationConfig, TaskDelegationService, type TaskStatusResponse, type ThreadConfig, type ThreadContext, type ToolRegistry, type ToolResult, type ToolSchema, type ToolSystem, TypedSocket, type UISystem, UnknownProviderError, type UnsubscribeFunction, type UpdateA2ATaskRequest, VERSION, createArtInstance, generateUUID };