@wundr.io/autogen-orchestrator 1.0.3

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/src/types.ts ADDED
@@ -0,0 +1,876 @@
1
+ /**
2
+ * Type definitions for AutoGen-style multi-agent orchestration
3
+ *
4
+ * Implements conversational patterns for agent coordination including
5
+ * group chat, speaker selection, and termination handling.
6
+ */
7
+
8
+ import { z } from 'zod';
9
+
10
+ // ============================================================================
11
+ // Message Types
12
+ // ============================================================================
13
+
14
+ /**
15
+ * Role of the message sender in the conversation
16
+ */
17
+ export type MessageRole = 'system' | 'user' | 'assistant' | 'function';
18
+
19
+ /**
20
+ * Status of a message in the conversation flow
21
+ */
22
+ export type MessageStatus = 'pending' | 'delivered' | 'processed' | 'failed';
23
+
24
+ /**
25
+ * Content type within a message
26
+ */
27
+ export type ContentType =
28
+ | 'text'
29
+ | 'code'
30
+ | 'image'
31
+ | 'function_call'
32
+ | 'function_result';
33
+
34
+ /**
35
+ * Represents a single message in the conversation
36
+ */
37
+ export interface Message {
38
+ /** Unique identifier for the message */
39
+ id: string;
40
+ /** Role of the message sender */
41
+ role: MessageRole;
42
+ /** Content of the message */
43
+ content: string;
44
+ /** Name of the sender (participant name) */
45
+ name: string;
46
+ /** Timestamp when message was created */
47
+ timestamp: Date;
48
+ /** Optional metadata attached to the message */
49
+ metadata?: MessageMetadata;
50
+ /** Content type */
51
+ contentType?: ContentType;
52
+ /** Function call details if applicable */
53
+ functionCall?: FunctionCall;
54
+ /** Status of the message */
55
+ status?: MessageStatus;
56
+ }
57
+
58
+ /**
59
+ * Metadata attached to a message
60
+ */
61
+ export interface MessageMetadata {
62
+ /** Token count for the message */
63
+ tokenCount?: number;
64
+ /** Processing latency in milliseconds */
65
+ latencyMs?: number;
66
+ /** Model used to generate the message */
67
+ model?: string;
68
+ /** Associated task ID */
69
+ taskId?: string;
70
+ /** Parent message ID for threading */
71
+ parentId?: string;
72
+ /** Custom properties */
73
+ properties?: Record<string, unknown>;
74
+ }
75
+
76
+ /**
77
+ * Function call embedded in a message
78
+ */
79
+ export interface FunctionCall {
80
+ /** Name of the function to call */
81
+ name: string;
82
+ /** Arguments for the function */
83
+ arguments: Record<string, unknown>;
84
+ /** Result of the function call */
85
+ result?: unknown;
86
+ }
87
+
88
+ // ============================================================================
89
+ // Chat Participant Types
90
+ // ============================================================================
91
+
92
+ /**
93
+ * Type of chat participant
94
+ */
95
+ export type ParticipantType = 'human' | 'assistant' | 'agent' | 'tool';
96
+
97
+ /**
98
+ * Status of a chat participant
99
+ */
100
+ export type ParticipantStatus =
101
+ | 'active'
102
+ | 'idle'
103
+ | 'busy'
104
+ | 'offline'
105
+ | 'error';
106
+
107
+ /**
108
+ * Represents a participant in the group chat
109
+ */
110
+ export interface ChatParticipant {
111
+ /** Unique identifier for the participant */
112
+ id: string;
113
+ /** Display name of the participant */
114
+ name: string;
115
+ /** Type of participant */
116
+ type: ParticipantType;
117
+ /** System prompt defining participant's behavior */
118
+ systemPrompt: string;
119
+ /** Current status of the participant */
120
+ status: ParticipantStatus;
121
+ /** Capabilities of this participant */
122
+ capabilities: string[];
123
+ /** Model configuration for AI participants */
124
+ modelConfig?: ModelConfig;
125
+ /** Function definitions available to this participant */
126
+ functions?: FunctionDefinition[];
127
+ /** Maximum number of consecutive replies allowed */
128
+ maxConsecutiveReplies?: number;
129
+ /** Description of the participant's role */
130
+ description?: string;
131
+ /** Metadata for the participant */
132
+ metadata?: ParticipantMetadata;
133
+ }
134
+
135
+ /**
136
+ * Model configuration for AI participants
137
+ */
138
+ export interface ModelConfig {
139
+ /** Model identifier */
140
+ model: string;
141
+ /** Temperature for generation */
142
+ temperature?: number;
143
+ /** Maximum tokens to generate */
144
+ maxTokens?: number;
145
+ /** Top-p sampling parameter */
146
+ topP?: number;
147
+ /** Frequency penalty */
148
+ frequencyPenalty?: number;
149
+ /** Presence penalty */
150
+ presencePenalty?: number;
151
+ /** Stop sequences */
152
+ stopSequences?: string[];
153
+ }
154
+
155
+ /**
156
+ * Function definition for participants
157
+ */
158
+ export interface FunctionDefinition {
159
+ /** Function name */
160
+ name: string;
161
+ /** Function description */
162
+ description: string;
163
+ /** Parameter schema */
164
+ parameters: Record<string, unknown>;
165
+ /** Whether function is required */
166
+ required?: boolean;
167
+ }
168
+
169
+ /**
170
+ * Metadata for participants
171
+ */
172
+ export interface ParticipantMetadata {
173
+ /** Creation timestamp */
174
+ createdAt: Date;
175
+ /** Last activity timestamp */
176
+ lastActiveAt?: Date;
177
+ /** Total messages sent */
178
+ messageCount?: number;
179
+ /** Success rate */
180
+ successRate?: number;
181
+ /** Custom properties */
182
+ properties?: Record<string, unknown>;
183
+ }
184
+
185
+ // ============================================================================
186
+ // Group Chat Configuration Types
187
+ // ============================================================================
188
+
189
+ /**
190
+ * Speaker selection method for group chat
191
+ */
192
+ export type SpeakerSelectionMethod =
193
+ | 'round_robin'
194
+ | 'random'
195
+ | 'llm_selected'
196
+ | 'priority'
197
+ | 'manual'
198
+ | 'auto';
199
+
200
+ /**
201
+ * Configuration for the group chat
202
+ */
203
+ export interface GroupChatConfig {
204
+ /** Unique identifier for the chat */
205
+ id?: string;
206
+ /** Name of the group chat */
207
+ name: string;
208
+ /** Description of the chat's purpose */
209
+ description?: string;
210
+ /** Participants in the chat */
211
+ participants: ChatParticipant[];
212
+ /** Speaker selection method */
213
+ speakerSelectionMethod: SpeakerSelectionMethod;
214
+ /** Configuration for speaker selection */
215
+ speakerSelectionConfig?: SpeakerSelectionConfig;
216
+ /** Maximum number of conversation rounds */
217
+ maxRounds?: number;
218
+ /** Maximum total messages allowed */
219
+ maxMessages?: number;
220
+ /** Termination conditions */
221
+ terminationConditions?: TerminationCondition[];
222
+ /** Whether to allow nested chats */
223
+ allowNestedChats?: boolean;
224
+ /** Nested chat configurations */
225
+ nestedChatConfigs?: NestedChatConfig[];
226
+ /** Admin participant name */
227
+ adminName?: string;
228
+ /** Enable message history */
229
+ enableHistory?: boolean;
230
+ /** Maximum history length to maintain */
231
+ maxHistoryLength?: number;
232
+ /** Timeout for the entire chat in milliseconds */
233
+ timeoutMs?: number;
234
+ /** Custom metadata */
235
+ metadata?: Record<string, unknown>;
236
+ }
237
+
238
+ /**
239
+ * Configuration for speaker selection
240
+ */
241
+ export interface SpeakerSelectionConfig {
242
+ /** Model for LLM-based selection */
243
+ selectorModel?: string;
244
+ /** Prompt template for LLM selection */
245
+ selectorPrompt?: string;
246
+ /** Priority order for priority-based selection */
247
+ priorityOrder?: string[];
248
+ /** Weights for weighted selection */
249
+ weights?: Record<string, number>;
250
+ /** Maximum retries for selection */
251
+ maxRetries?: number;
252
+ /** Transition rules between speakers */
253
+ transitionRules?: TransitionRule[];
254
+ /** Allowed speaker transitions */
255
+ allowedTransitions?: Record<string, string[]>;
256
+ }
257
+
258
+ /**
259
+ * Rule for speaker transitions
260
+ */
261
+ export interface TransitionRule {
262
+ /** From participant name */
263
+ from: string;
264
+ /** To participant names */
265
+ to: string[];
266
+ /** Condition for the transition */
267
+ condition?: string;
268
+ /** Weight for this transition */
269
+ weight?: number;
270
+ }
271
+
272
+ // ============================================================================
273
+ // Termination Types
274
+ // ============================================================================
275
+
276
+ /**
277
+ * Type of termination condition
278
+ */
279
+ export type TerminationConditionType =
280
+ | 'max_rounds'
281
+ | 'max_messages'
282
+ | 'keyword'
283
+ | 'timeout'
284
+ | 'function'
285
+ | 'consensus'
286
+ | 'custom';
287
+
288
+ /**
289
+ * Configuration for consensus-based termination
290
+ */
291
+ export interface ConsensusConfigType {
292
+ /** Minimum agreement threshold (0-1) */
293
+ threshold: number;
294
+ /** Keywords indicating agreement */
295
+ agreementKeywords: string[];
296
+ /** Keywords indicating disagreement */
297
+ disagreementKeywords: string[];
298
+ /** Minimum participants required for consensus */
299
+ minParticipants?: number;
300
+ /** Number of recent messages to consider */
301
+ windowSize?: number;
302
+ }
303
+
304
+ /**
305
+ * Union type for termination condition values based on type
306
+ * - max_rounds: number
307
+ * - max_messages: number
308
+ * - keyword: string | string[]
309
+ * - timeout: number (milliseconds)
310
+ * - function: TerminationEvaluator
311
+ * - consensus: ConsensusConfigType
312
+ * - custom: TerminationEvaluator | unknown
313
+ */
314
+ export type TerminationConditionValue =
315
+ | number
316
+ | string
317
+ | string[]
318
+ | ConsensusConfigType
319
+ | TerminationEvaluator;
320
+
321
+ /**
322
+ * Configuration for termination conditions
323
+ */
324
+ export interface TerminationCondition {
325
+ /** Type of termination condition */
326
+ type: TerminationConditionType;
327
+ /** Value for the condition - type depends on condition type */
328
+ value: TerminationConditionValue;
329
+ /** Description of the condition */
330
+ description?: string;
331
+ /** Custom function for evaluation (for 'function' type) */
332
+ evaluator?: TerminationEvaluator;
333
+ }
334
+
335
+ /**
336
+ * Function type for custom termination evaluation
337
+ */
338
+ export type TerminationEvaluator = (
339
+ messages: Message[],
340
+ participants: ChatParticipant[],
341
+ context: ChatContext
342
+ ) => Promise<TerminationResult>;
343
+
344
+ /**
345
+ * Result of termination evaluation
346
+ */
347
+ export interface TerminationResult {
348
+ /** Whether to terminate */
349
+ shouldTerminate: boolean;
350
+ /** Reason for termination */
351
+ reason?: string;
352
+ /** Final summary */
353
+ summary?: string;
354
+ /** Additional data */
355
+ data?: Record<string, unknown>;
356
+ }
357
+
358
+ // ============================================================================
359
+ // Nested Chat Types
360
+ // ============================================================================
361
+
362
+ /**
363
+ * Configuration for nested chat sessions
364
+ */
365
+ export interface NestedChatConfig {
366
+ /** Unique identifier for nested chat config */
367
+ id: string;
368
+ /** Name of the nested chat */
369
+ name: string;
370
+ /** Trigger condition for starting nested chat */
371
+ trigger: NestedChatTrigger;
372
+ /** Participants in the nested chat */
373
+ participants: string[];
374
+ /** Maximum rounds for nested chat */
375
+ maxRounds?: number;
376
+ /** Summary method after nested chat completes */
377
+ summaryMethod?: SummaryMethod;
378
+ /** Custom prompt for the nested chat */
379
+ prompt?: string;
380
+ /** Whether to share context with parent chat */
381
+ shareContext?: boolean;
382
+ }
383
+
384
+ /**
385
+ * Condition function type for nested chat triggers
386
+ */
387
+ export type NestedChatConditionFn = (
388
+ message: Message,
389
+ context: ChatContext
390
+ ) => boolean;
391
+
392
+ /**
393
+ * Union type for nested chat trigger values based on trigger type
394
+ * - keyword: string | string[] (keywords to match)
395
+ * - participant: string | string[] (participant names)
396
+ * - condition: string | NestedChatConditionFn (condition expression or function)
397
+ * - manual: string (state key to check)
398
+ */
399
+ export type NestedChatTriggerValue = string | string[] | NestedChatConditionFn;
400
+
401
+ /**
402
+ * Trigger for starting a nested chat
403
+ */
404
+ export interface NestedChatTrigger {
405
+ /** Type of trigger */
406
+ type: 'keyword' | 'participant' | 'condition' | 'manual';
407
+ /** Value for the trigger - type depends on trigger type */
408
+ value: NestedChatTriggerValue;
409
+ /** Description of the trigger */
410
+ description?: string;
411
+ }
412
+
413
+ /**
414
+ * Method for summarizing nested chat results
415
+ */
416
+ export type SummaryMethod = 'last' | 'llm' | 'reflection' | 'custom';
417
+
418
+ // ============================================================================
419
+ // Chat Result Types
420
+ // ============================================================================
421
+
422
+ /**
423
+ * Status of the chat session
424
+ */
425
+ export type ChatStatus =
426
+ | 'initializing'
427
+ | 'active'
428
+ | 'paused'
429
+ | 'completed'
430
+ | 'terminated'
431
+ | 'error';
432
+
433
+ /**
434
+ * Result of a group chat session
435
+ */
436
+ export interface ChatResult {
437
+ /** Chat session ID */
438
+ chatId: string;
439
+ /** Final status of the chat */
440
+ status: ChatStatus;
441
+ /** All messages in the conversation */
442
+ messages: Message[];
443
+ /** Summary of the conversation */
444
+ summary?: string;
445
+ /** Termination reason */
446
+ terminationReason?: string;
447
+ /** Total rounds completed */
448
+ totalRounds: number;
449
+ /** Total messages exchanged */
450
+ totalMessages: number;
451
+ /** Participants involved */
452
+ participants: string[];
453
+ /** Duration in milliseconds */
454
+ durationMs: number;
455
+ /** Metrics for the chat session */
456
+ metrics?: ChatMetrics;
457
+ /** Nested chat results if any */
458
+ nestedResults?: NestedChatResult[];
459
+ /** Error information if failed */
460
+ error?: ChatError;
461
+ /** Timestamp when chat started */
462
+ startedAt: Date;
463
+ /** Timestamp when chat ended */
464
+ endedAt: Date;
465
+ }
466
+
467
+ /**
468
+ * Metrics for a chat session
469
+ */
470
+ export interface ChatMetrics {
471
+ /** Total tokens used */
472
+ totalTokens: number;
473
+ /** Average response time in milliseconds */
474
+ avgResponseTimeMs: number;
475
+ /** Messages per participant */
476
+ messagesPerParticipant: Record<string, number>;
477
+ /** Token usage per participant */
478
+ tokensPerParticipant: Record<string, number>;
479
+ /** Successful responses count */
480
+ successfulResponses: number;
481
+ /** Failed responses count */
482
+ failedResponses: number;
483
+ }
484
+
485
+ /**
486
+ * Result from a nested chat session
487
+ */
488
+ export interface NestedChatResult {
489
+ /** Nested chat ID */
490
+ nestedChatId: string;
491
+ /** Config ID that triggered this nested chat */
492
+ configId: string;
493
+ /** Result of the nested chat */
494
+ result: ChatResult;
495
+ /** Summary from the nested chat */
496
+ summary?: string;
497
+ /** Parent message ID that triggered the nested chat */
498
+ parentMessageId: string;
499
+ }
500
+
501
+ /**
502
+ * Error information for chat failures
503
+ */
504
+ export interface ChatError {
505
+ /** Error code */
506
+ code: string;
507
+ /** Error message */
508
+ message: string;
509
+ /** Stack trace if available */
510
+ stack?: string;
511
+ /** Context of the error */
512
+ context?: Record<string, unknown>;
513
+ /** Whether the error is recoverable */
514
+ recoverable: boolean;
515
+ }
516
+
517
+ // ============================================================================
518
+ // Chat Context Types
519
+ // ============================================================================
520
+
521
+ /**
522
+ * Context available during chat execution
523
+ */
524
+ export interface ChatContext {
525
+ /** Current chat ID */
526
+ chatId: string;
527
+ /** Current round number */
528
+ currentRound: number;
529
+ /** Total messages so far */
530
+ messageCount: number;
531
+ /** Active participants */
532
+ activeParticipants: string[];
533
+ /** Current speaker */
534
+ currentSpeaker?: string;
535
+ /** Previous speaker */
536
+ previousSpeaker?: string;
537
+ /** Start time */
538
+ startTime: Date;
539
+ /** Shared state */
540
+ state: Record<string, unknown>;
541
+ /** Parent context if nested */
542
+ parentContext?: ChatContext;
543
+ }
544
+
545
+ // ============================================================================
546
+ // Speaker Selection Types
547
+ // ============================================================================
548
+
549
+ /**
550
+ * Result of speaker selection
551
+ */
552
+ export interface SpeakerSelectionResult {
553
+ /** Selected speaker name */
554
+ speaker: string;
555
+ /** Reason for selection */
556
+ reason?: string;
557
+ /** Confidence score (0-1) */
558
+ confidence?: number;
559
+ /** Alternative speakers considered */
560
+ alternatives?: string[];
561
+ }
562
+
563
+ /**
564
+ * Interface for speaker selection strategies
565
+ */
566
+ export interface SpeakerSelectionStrategy {
567
+ /** Select the next speaker */
568
+ selectSpeaker(
569
+ participants: ChatParticipant[],
570
+ messages: Message[],
571
+ context: ChatContext,
572
+ config?: SpeakerSelectionConfig
573
+ ): Promise<SpeakerSelectionResult>;
574
+ }
575
+
576
+ // ============================================================================
577
+ // Event Types
578
+ // ============================================================================
579
+
580
+ /**
581
+ * Types of events emitted during chat
582
+ */
583
+ export type ChatEventType =
584
+ | 'chat_started'
585
+ | 'chat_ended'
586
+ | 'message_sent'
587
+ | 'message_received'
588
+ | 'speaker_selected'
589
+ | 'round_started'
590
+ | 'round_ended'
591
+ | 'nested_chat_started'
592
+ | 'nested_chat_ended'
593
+ | 'termination_triggered'
594
+ | 'error';
595
+
596
+ /**
597
+ * Data payloads for different chat event types
598
+ */
599
+ export interface ChatEventDataMap {
600
+ chat_started: { config: GroupChatConfig };
601
+ chat_ended: { result: ChatResult };
602
+ message_sent: { message: Message };
603
+ message_received: { message: Message };
604
+ speaker_selected: { speaker: string; reason?: string };
605
+ round_started: { round: number };
606
+ round_ended: { round: number };
607
+ nested_chat_started: { nestedChatId: string; configId: string };
608
+ nested_chat_ended: { nestedChatId: string; result: NestedChatResult };
609
+ termination_triggered: { reason: string };
610
+ error: { error: ChatError };
611
+ }
612
+
613
+ /**
614
+ * Event emitted during chat execution
615
+ */
616
+ export interface ChatEvent<T extends ChatEventType = ChatEventType> {
617
+ /** Event type */
618
+ type: T;
619
+ /** Event timestamp */
620
+ timestamp: Date;
621
+ /** Chat ID */
622
+ chatId: string;
623
+ /** Event data - typed based on event type */
624
+ data: T extends keyof ChatEventDataMap
625
+ ? ChatEventDataMap[T]
626
+ : Record<string, unknown>;
627
+ }
628
+
629
+ // ============================================================================
630
+ // Zod Schemas for Validation
631
+ // ============================================================================
632
+
633
+ /**
634
+ * Zod schema for Message validation
635
+ */
636
+ export const MessageSchema = z.object({
637
+ id: z.string().min(1),
638
+ role: z.enum(['system', 'user', 'assistant', 'function']),
639
+ content: z.string(),
640
+ name: z.string().min(1),
641
+ timestamp: z.date(),
642
+ metadata: z
643
+ .object({
644
+ tokenCount: z.number().optional(),
645
+ latencyMs: z.number().optional(),
646
+ model: z.string().optional(),
647
+ taskId: z.string().optional(),
648
+ parentId: z.string().optional(),
649
+ properties: z.record(z.unknown()).optional(),
650
+ })
651
+ .optional(),
652
+ contentType: z
653
+ .enum(['text', 'code', 'image', 'function_call', 'function_result'])
654
+ .optional(),
655
+ functionCall: z
656
+ .object({
657
+ name: z.string(),
658
+ arguments: z.record(z.unknown()),
659
+ result: z.unknown().optional(),
660
+ })
661
+ .optional(),
662
+ status: z.enum(['pending', 'delivered', 'processed', 'failed']).optional(),
663
+ });
664
+
665
+ /**
666
+ * Zod schema for ChatParticipant validation
667
+ */
668
+ export const ChatParticipantSchema = z.object({
669
+ id: z.string().min(1),
670
+ name: z.string().min(1),
671
+ type: z.enum(['human', 'assistant', 'agent', 'tool']),
672
+ systemPrompt: z.string(),
673
+ status: z.enum(['active', 'idle', 'busy', 'offline', 'error']),
674
+ capabilities: z.array(z.string()),
675
+ modelConfig: z
676
+ .object({
677
+ model: z.string(),
678
+ temperature: z.number().min(0).max(2).optional(),
679
+ maxTokens: z.number().positive().optional(),
680
+ topP: z.number().min(0).max(1).optional(),
681
+ frequencyPenalty: z.number().min(-2).max(2).optional(),
682
+ presencePenalty: z.number().min(-2).max(2).optional(),
683
+ stopSequences: z.array(z.string()).optional(),
684
+ })
685
+ .optional(),
686
+ functions: z
687
+ .array(
688
+ z.object({
689
+ name: z.string(),
690
+ description: z.string(),
691
+ parameters: z.record(z.unknown()),
692
+ required: z.boolean().optional(),
693
+ }),
694
+ )
695
+ .optional(),
696
+ maxConsecutiveReplies: z.number().positive().optional(),
697
+ description: z.string().optional(),
698
+ });
699
+
700
+ /**
701
+ * Zod schema for GroupChatConfig validation
702
+ */
703
+ export const GroupChatConfigSchema = z.object({
704
+ id: z.string().optional(),
705
+ name: z.string().min(1),
706
+ description: z.string().optional(),
707
+ participants: z.array(ChatParticipantSchema).min(2),
708
+ speakerSelectionMethod: z.enum([
709
+ 'round_robin',
710
+ 'random',
711
+ 'llm_selected',
712
+ 'priority',
713
+ 'manual',
714
+ 'auto',
715
+ ]),
716
+ speakerSelectionConfig: z
717
+ .object({
718
+ selectorModel: z.string().optional(),
719
+ selectorPrompt: z.string().optional(),
720
+ priorityOrder: z.array(z.string()).optional(),
721
+ weights: z.record(z.number()).optional(),
722
+ maxRetries: z.number().positive().optional(),
723
+ transitionRules: z
724
+ .array(
725
+ z.object({
726
+ from: z.string(),
727
+ to: z.array(z.string()),
728
+ condition: z.string().optional(),
729
+ weight: z.number().optional(),
730
+ }),
731
+ )
732
+ .optional(),
733
+ allowedTransitions: z.record(z.array(z.string())).optional(),
734
+ })
735
+ .optional(),
736
+ maxRounds: z.number().positive().optional(),
737
+ maxMessages: z.number().positive().optional(),
738
+ terminationConditions: z
739
+ .array(
740
+ z.object({
741
+ type: z.enum([
742
+ 'max_rounds',
743
+ 'max_messages',
744
+ 'keyword',
745
+ 'timeout',
746
+ 'function',
747
+ 'consensus',
748
+ 'custom',
749
+ ]),
750
+ value: z.union([
751
+ z.number(),
752
+ z.string(),
753
+ z.array(z.string()),
754
+ z.object({
755
+ threshold: z.number(),
756
+ agreementKeywords: z.array(z.string()),
757
+ disagreementKeywords: z.array(z.string()),
758
+ minParticipants: z.number().optional(),
759
+ windowSize: z.number().optional(),
760
+ }),
761
+ z.function(),
762
+ ]),
763
+ description: z.string().optional(),
764
+ }),
765
+ )
766
+ .optional(),
767
+ allowNestedChats: z.boolean().optional(),
768
+ nestedChatConfigs: z
769
+ .array(
770
+ z.object({
771
+ id: z.string(),
772
+ name: z.string(),
773
+ trigger: z.object({
774
+ type: z.enum(['keyword', 'participant', 'condition', 'manual']),
775
+ value: z.union([z.string(), z.array(z.string()), z.function()]),
776
+ description: z.string().optional(),
777
+ }),
778
+ participants: z.array(z.string()),
779
+ maxRounds: z.number().positive().optional(),
780
+ summaryMethod: z
781
+ .enum(['last', 'llm', 'reflection', 'custom'])
782
+ .optional(),
783
+ prompt: z.string().optional(),
784
+ shareContext: z.boolean().optional(),
785
+ }),
786
+ )
787
+ .optional(),
788
+ adminName: z.string().optional(),
789
+ enableHistory: z.boolean().optional(),
790
+ maxHistoryLength: z.number().positive().optional(),
791
+ timeoutMs: z.number().positive().optional(),
792
+ metadata: z.record(z.unknown()).optional(),
793
+ });
794
+
795
+ /**
796
+ * Zod schema for ConsensusConfig validation
797
+ */
798
+ export const ConsensusConfigSchema = z.object({
799
+ threshold: z.number().min(0).max(1),
800
+ agreementKeywords: z.array(z.string()),
801
+ disagreementKeywords: z.array(z.string()),
802
+ minParticipants: z.number().positive().optional(),
803
+ windowSize: z.number().positive().optional(),
804
+ });
805
+
806
+ /**
807
+ * Zod schema for TerminationConditionValue validation
808
+ */
809
+ export const TerminationConditionValueSchema = z.union([
810
+ z.number(),
811
+ z.string(),
812
+ z.array(z.string()),
813
+ ConsensusConfigSchema,
814
+ z.function(),
815
+ ]);
816
+
817
+ /**
818
+ * Zod schema for TerminationCondition validation
819
+ */
820
+ export const TerminationConditionSchema = z.object({
821
+ type: z.enum([
822
+ 'max_rounds',
823
+ 'max_messages',
824
+ 'keyword',
825
+ 'timeout',
826
+ 'function',
827
+ 'consensus',
828
+ 'custom',
829
+ ]),
830
+ value: TerminationConditionValueSchema,
831
+ description: z.string().optional(),
832
+ });
833
+
834
+ // ============================================================================
835
+ // Utility Types
836
+ // ============================================================================
837
+
838
+ /**
839
+ * Options for creating a new message
840
+ */
841
+ export interface CreateMessageOptions {
842
+ role: MessageRole;
843
+ content: string;
844
+ name: string;
845
+ contentType?: ContentType;
846
+ functionCall?: FunctionCall;
847
+ metadata?: Partial<MessageMetadata>;
848
+ }
849
+
850
+ /**
851
+ * Options for adding a participant
852
+ */
853
+ export interface AddParticipantOptions {
854
+ name: string;
855
+ type: ParticipantType;
856
+ systemPrompt: string;
857
+ capabilities?: string[];
858
+ modelConfig?: ModelConfig;
859
+ functions?: FunctionDefinition[];
860
+ maxConsecutiveReplies?: number;
861
+ description?: string;
862
+ }
863
+
864
+ /**
865
+ * Options for starting a chat
866
+ */
867
+ export interface StartChatOptions {
868
+ /** Initial message to start the chat */
869
+ initialMessage?: string;
870
+ /** Initial sender name */
871
+ initialSender?: string;
872
+ /** Initial context state */
873
+ initialState?: Record<string, unknown>;
874
+ /** Skip first speaker selection */
875
+ skipInitialSelection?: boolean;
876
+ }