agents-library 0.1.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.
Files changed (89) hide show
  1. package/dist/base-agent.d.ts +172 -0
  2. package/dist/base-agent.d.ts.map +1 -0
  3. package/dist/base-agent.js +255 -0
  4. package/dist/base-agent.js.map +1 -0
  5. package/dist/base-bot.d.ts +282 -0
  6. package/dist/base-bot.d.ts.map +1 -0
  7. package/dist/base-bot.js +375 -0
  8. package/dist/base-bot.js.map +1 -0
  9. package/dist/common/result.d.ts +51 -0
  10. package/dist/common/result.d.ts.map +1 -0
  11. package/dist/common/result.js +45 -0
  12. package/dist/common/result.js.map +1 -0
  13. package/dist/common/types.d.ts +57 -0
  14. package/dist/common/types.d.ts.map +1 -0
  15. package/dist/common/types.js +42 -0
  16. package/dist/common/types.js.map +1 -0
  17. package/dist/index.d.ts +94 -0
  18. package/dist/index.d.ts.map +1 -0
  19. package/dist/index.js +108 -0
  20. package/dist/index.js.map +1 -0
  21. package/dist/kadi-event-publisher.d.ts +163 -0
  22. package/dist/kadi-event-publisher.d.ts.map +1 -0
  23. package/dist/kadi-event-publisher.js +286 -0
  24. package/dist/kadi-event-publisher.js.map +1 -0
  25. package/dist/memory/arcadedb-adapter.d.ts +159 -0
  26. package/dist/memory/arcadedb-adapter.d.ts.map +1 -0
  27. package/dist/memory/arcadedb-adapter.js +314 -0
  28. package/dist/memory/arcadedb-adapter.js.map +1 -0
  29. package/dist/memory/file-storage-adapter.d.ts +122 -0
  30. package/dist/memory/file-storage-adapter.d.ts.map +1 -0
  31. package/dist/memory/file-storage-adapter.js +352 -0
  32. package/dist/memory/file-storage-adapter.js.map +1 -0
  33. package/dist/memory/memory-service.d.ts +208 -0
  34. package/dist/memory/memory-service.d.ts.map +1 -0
  35. package/dist/memory/memory-service.js +410 -0
  36. package/dist/memory/memory-service.js.map +1 -0
  37. package/dist/memory/types.d.ts +126 -0
  38. package/dist/memory/types.d.ts.map +1 -0
  39. package/dist/memory/types.js +41 -0
  40. package/dist/memory/types.js.map +1 -0
  41. package/dist/producer-tool-utils.d.ts +474 -0
  42. package/dist/producer-tool-utils.d.ts.map +1 -0
  43. package/dist/producer-tool-utils.js +664 -0
  44. package/dist/producer-tool-utils.js.map +1 -0
  45. package/dist/providers/anthropic-provider.d.ts +160 -0
  46. package/dist/providers/anthropic-provider.d.ts.map +1 -0
  47. package/dist/providers/anthropic-provider.js +527 -0
  48. package/dist/providers/anthropic-provider.js.map +1 -0
  49. package/dist/providers/model-manager-provider.d.ts +91 -0
  50. package/dist/providers/model-manager-provider.d.ts.map +1 -0
  51. package/dist/providers/model-manager-provider.js +355 -0
  52. package/dist/providers/model-manager-provider.js.map +1 -0
  53. package/dist/providers/provider-manager.d.ts +111 -0
  54. package/dist/providers/provider-manager.d.ts.map +1 -0
  55. package/dist/providers/provider-manager.js +337 -0
  56. package/dist/providers/provider-manager.js.map +1 -0
  57. package/dist/providers/types.d.ts +145 -0
  58. package/dist/providers/types.d.ts.map +1 -0
  59. package/dist/providers/types.js +23 -0
  60. package/dist/providers/types.js.map +1 -0
  61. package/dist/shadow-agent-factory.d.ts +623 -0
  62. package/dist/shadow-agent-factory.d.ts.map +1 -0
  63. package/dist/shadow-agent-factory.js +1117 -0
  64. package/dist/shadow-agent-factory.js.map +1 -0
  65. package/dist/types/agent-config.d.ts +307 -0
  66. package/dist/types/agent-config.d.ts.map +1 -0
  67. package/dist/types/agent-config.js +15 -0
  68. package/dist/types/agent-config.js.map +1 -0
  69. package/dist/types/event-schemas.d.ts +358 -0
  70. package/dist/types/event-schemas.d.ts.map +1 -0
  71. package/dist/types/event-schemas.js +188 -0
  72. package/dist/types/event-schemas.js.map +1 -0
  73. package/dist/types/tool-schemas.d.ts +498 -0
  74. package/dist/types/tool-schemas.d.ts.map +1 -0
  75. package/dist/types/tool-schemas.js +457 -0
  76. package/dist/types/tool-schemas.js.map +1 -0
  77. package/dist/utils/logger.d.ts +135 -0
  78. package/dist/utils/logger.d.ts.map +1 -0
  79. package/dist/utils/logger.js +205 -0
  80. package/dist/utils/logger.js.map +1 -0
  81. package/dist/utils/timer.d.ts +186 -0
  82. package/dist/utils/timer.d.ts.map +1 -0
  83. package/dist/utils/timer.js +211 -0
  84. package/dist/utils/timer.js.map +1 -0
  85. package/dist/worker-agent-factory.d.ts +688 -0
  86. package/dist/worker-agent-factory.d.ts.map +1 -0
  87. package/dist/worker-agent-factory.js +1517 -0
  88. package/dist/worker-agent-factory.js.map +1 -0
  89. package/package.json +38 -0
@@ -0,0 +1,688 @@
1
+ /**
2
+ * Worker Agent Factory
3
+ * =====================
4
+ *
5
+ * Factory for creating worker agents (artist, designer, programmer) with
6
+ * configuration-driven instantiation and shared infrastructure.
7
+ *
8
+ * Architecture Pattern: **Composition over Inheritance**
9
+ * - BaseWorkerAgent COMPOSES with BaseBot (does NOT extend)
10
+ * - Uses delegation pattern to access BaseBot's circuit breaker and retry logic
11
+ * - This avoids tight coupling and allows flexible behavior customization
12
+ *
13
+ * Design Principles:
14
+ * - Factory pattern for consistent agent creation
15
+ * - Composition over inheritance for flexibility
16
+ * - Strategy pattern for role-specific customization via WorkerBehaviors
17
+ * - Template method pattern for lifecycle management (start/stop)
18
+ *
19
+ * Tool-Calling Agent Loop (Task 3.15):
20
+ * - executeTask sends task + available tools to LLM via ProviderManager
21
+ * - LLM calls tools iteratively (file ops, git ops via MCP)
22
+ * - Loop continues until LLM returns final text response
23
+ * - Git operations use client.invokeRemote() MCP tools, NOT child_process
24
+ *
25
+ * @module worker-agent-factory
26
+ */
27
+ import { KadiClient } from '@kadi.build/core';
28
+ import type { WorkerAgentConfig, AgentRole } from './types/agent-config.js';
29
+ import type { ProviderManager } from './providers/provider-manager.js';
30
+ import type { ToolDefinition } from './providers/types.js';
31
+ import { TaskAssignedEvent } from './types/event-schemas.js';
32
+ /**
33
+ * Base class for worker agents (artist, designer, programmer)
34
+ *
35
+ * **COMPOSITION PATTERN**: This class COMPOSES with BaseBot instead of extending it.
36
+ * - Maintains a private `baseBot` instance for circuit breaker and retry logic
37
+ * - Delegates tool invocation to `baseBot.invokeToolWithRetry()`
38
+ * - Keeps agent-specific logic separate from bot resilience patterns
39
+ *
40
+ * Why Composition over Inheritance?
41
+ * 1. **Flexibility**: Can compose multiple utilities (BaseBot, etc.)
42
+ * 2. **Decoupling**: Changes to BaseBot don't force changes to worker agent interface
43
+ * 3. **Single Responsibility**: BaseBot handles resilience, BaseWorkerAgent handles workflow
44
+ * 4. **Testability**: Can mock BaseBot behavior independently
45
+ *
46
+ * Lifecycle:
47
+ * 1. Constructor: Initialize configuration and compose utilities
48
+ * 2. start(): Connect to broker, subscribe to task events, initialize protocol
49
+ * 3. [Task execution happens asynchronously via event handlers]
50
+ * 4. stop(): Cleanup subscriptions, disconnect from broker
51
+ *
52
+ * @example
53
+ * ```typescript
54
+ * const config: WorkerAgentConfig = {
55
+ * role: 'artist',
56
+ * worktreePath: 'C:/p4/Personal/SD/agent-playground-artist',
57
+ * brokerUrl: 'ws://localhost:8080/kadi',
58
+ * networks: ['kadi'],
59
+ * anthropicApiKey: process.env.ANTHROPIC_API_KEY!,
60
+ * claudeModel: 'claude-sonnet-4-20250514'
61
+ * };
62
+ *
63
+ * const agent = new BaseWorkerAgent(config);
64
+ * await agent.start();
65
+ * // Agent now listens for {role}.task.assigned events and executes tasks
66
+ * ```
67
+ */
68
+ export declare class BaseWorkerAgent {
69
+ /**
70
+ * KĀDI client for broker communication
71
+ *
72
+ * Used for:
73
+ * - Subscribing to events
74
+ * - Publishing completion/failure events
75
+ * - Invoking remote MCP tools (git, file management)
76
+ */
77
+ protected client: KadiClient;
78
+ /**
79
+ * LLM provider manager for model selection and chat
80
+ *
81
+ * Replaces direct Anthropic SDK usage. Provides:
82
+ * - Model-based routing (claude→Anthropic, gpt→Model Manager)
83
+ * - Automatic fallback on provider failure
84
+ * - Tool-calling via ChatOptions.tools
85
+ *
86
+ * Optional — if null, agent cannot execute tasks requiring LLM.
87
+ */
88
+ protected providerManager: ProviderManager | null;
89
+ /**
90
+ * Agent role (artist, designer, programmer)
91
+ *
92
+ * Used for:
93
+ * - Event topic filtering (generic task.assigned, role in payload)
94
+ * - Default file extensions
95
+ * - Commit message prefixes
96
+ */
97
+ protected role: AgentRole;
98
+ /**
99
+ * Absolute path to git worktree for this agent
100
+ *
101
+ * Agent creates files and commits in this directory.
102
+ * Must be a valid git worktree with initialized repository.
103
+ *
104
+ * @example 'C:/GitHub/agent-playground-artist'
105
+ */
106
+ protected worktreePath: string;
107
+ /**
108
+ * Network(s) this agent belongs to
109
+ *
110
+ * Used for network-based event routing in KĀDI broker.
111
+ * Agent only receives events published to these networks.
112
+ *
113
+ * @example ['kadi']
114
+ * @example ['production', 'team-alpha']
115
+ */
116
+ protected networks: string[];
117
+ /**
118
+ * Claude model to use for task execution (from role config or WorkerAgentConfig)
119
+ *
120
+ * @default 'claude-sonnet-4-20250514'
121
+ */
122
+ protected claudeModel: string;
123
+ /**
124
+ * Temperature for LLM requests (from role config)
125
+ *
126
+ * @default undefined (uses provider default)
127
+ */
128
+ protected temperature?: number;
129
+ /**
130
+ * Max tokens for LLM responses (from role config)
131
+ *
132
+ * @default undefined (uses provider default)
133
+ */
134
+ protected maxTokens?: number;
135
+ /**
136
+ * Commit message format template from role config
137
+ *
138
+ * Supports `{taskId}` placeholder. Used in the system prompt to guide
139
+ * the LLM on commit message formatting.
140
+ *
141
+ * @default 'feat({role}): <description> [{taskId}]'
142
+ */
143
+ protected commitFormat?: string;
144
+ /**
145
+ * Agent capabilities for task validation
146
+ *
147
+ * Used to validate incoming tasks before execution.
148
+ * If a task description doesn't match any capabilities, the agent rejects the task.
149
+ */
150
+ protected capabilities: string[];
151
+ /**
152
+ * MCP tool prefixes this agent is allowed to invoke (from role config)
153
+ *
154
+ * Controls which remote tools the agent can call via client.invokeRemote().
155
+ * Examples: ['git_git_', 'ability_file_']
156
+ *
157
+ * If empty, no remote tools are available to the agent.
158
+ */
159
+ protected toolPrefixes: string[];
160
+ /**
161
+ * Maximum iterations for the tool-calling loop.
162
+ * Prevents infinite loops if Claude keeps calling tools.
163
+ */
164
+ protected static readonly MAX_TOOL_LOOP_ITERATIONS = 25;
165
+ /**
166
+ * BaseBot instance for circuit breaker and retry logic (COMPOSITION)
167
+ *
168
+ * Used for resilient tool invocation with exponential backoff.
169
+ * Created lazily when anthropicApiKey is available.
170
+ */
171
+ private baseBot;
172
+ /**
173
+ * Full agent configuration
174
+ *
175
+ * Stored for reference and potential reconfiguration.
176
+ */
177
+ private config;
178
+ /**
179
+ * Set of task IDs that have been processed or are currently in-flight.
180
+ * Prevents duplicate execution when the same task.assigned event arrives
181
+ * multiple times (e.g., retry re-publish while first execution is still running).
182
+ */
183
+ private processedTaskIds;
184
+ /**
185
+ * Create a new BaseWorkerAgent instance
186
+ *
187
+ * Initializes all configuration properties and composes utility classes
188
+ * (BaseBot). Does NOT connect to broker yet - call start()
189
+ * to establish connection.
190
+ *
191
+ * @param config - Worker agent configuration with all required fields
192
+ *
193
+ * @example
194
+ * ```typescript
195
+ * const agent = new BaseWorkerAgent({
196
+ * role: 'artist',
197
+ * worktreePath: 'C:/p4/Personal/SD/agent-playground-artist',
198
+ * brokerUrl: 'ws://localhost:8080/kadi',
199
+ * networks: ['kadi'],
200
+ * anthropicApiKey: process.env.ANTHROPIC_API_KEY!,
201
+ * claudeModel: 'claude-sonnet-4-20250514',
202
+ * customBehaviors: {
203
+ * determineFilename: (taskId) => `artwork-${taskId}.png`
204
+ * }
205
+ * });
206
+ * ```
207
+ */
208
+ constructor(config: WorkerAgentConfig);
209
+ /**
210
+ * Initialize KĀDI client and connect to broker
211
+ *
212
+ * Performs connection sequence with retry logic:
213
+ * 1. Connect KĀDI client to broker (client.serve blocks, so we use setTimeout)
214
+ * 2. Wait for connection to establish (1 second delay)
215
+ * 3. Initialize broker protocol for tool invocation
216
+ * 4. Connect event publisher with retry logic
217
+ *
218
+ * Connection is performed with exponential backoff retry logic inherited from
219
+ * Uses client.publish() for event publishing. If broker is unavailable, events will be queued.
220
+ *
221
+ * @throws {Error} If broker connection fails after all retries
222
+ *
223
+ * @example
224
+ * ```typescript
225
+ * await this.initializeClient();
226
+ * // Client is now connected, protocol is initialized, publisher is ready
227
+ * ```
228
+ */
229
+ protected initializeClient(): Promise<void>;
230
+ /**
231
+ * Subscribe to task assignment events
232
+ *
233
+ * Subscribes to {role}.task.assigned topic pattern to receive task assignments
234
+ * from agent-producer. Topic is constructed dynamically from config.role to avoid
235
+ * hardcoding and ensure flexibility.
236
+ *
237
+ * Event Flow:
238
+ * 1. agent-producer publishes {role}.task.assigned event
239
+ * 2. Broker routes event to this agent based on network membership
240
+ * 3. handleTaskAssignment callback is invoked with event data
241
+ * 4. Event is validated with Zod schema
242
+ * 5. If valid, task execution begins
243
+ * 6. If invalid, error is logged and event is rejected
244
+ *
245
+ * @throws {Error} If subscription fails (e.g., client not connected)
246
+ *
247
+ * @example
248
+ * ```typescript
249
+ * await this.subscribeToTaskAssignments();
250
+ * // Agent now listens for task assignments on {role}.task.assigned
251
+ * ```
252
+ */
253
+ protected subscribeToTaskAssignments(): Promise<void>;
254
+ /**
255
+ * Handle task assignment event
256
+ *
257
+ * Callback invoked when {role}.task.assigned event is received.
258
+ * Performs validation and delegates to task execution.
259
+ *
260
+ * Validation Strategy:
261
+ * - Uses Zod schema for runtime validation (TaskAssignedEventSchema)
262
+ * - Rejects invalid events gracefully without crashing
263
+ * - Logs detailed validation errors for debugging
264
+ * - Maintains backward compatibility with existing event format
265
+ *
266
+ * Error Handling:
267
+ * - Invalid events: Log error, reject event, continue processing
268
+ * - Execution errors: Logged by executeTask method (implemented in next task)
269
+ *
270
+ * @param event - Raw event data from KĀDI broker (may include envelope wrapper)
271
+ *
272
+ * @example
273
+ * ```typescript
274
+ * // Event structure from broker:
275
+ * {
276
+ * data: {
277
+ * taskId: 'task-123',
278
+ * role: 'artist',
279
+ * description: 'Create hero banner',
280
+ * requirements: 'Size: 1920x1080',
281
+ * timestamp: '2025-12-04T10:30:00.000Z'
282
+ * }
283
+ * }
284
+ * ```
285
+ */
286
+ protected handleTaskAssignment(event: unknown): Promise<void>;
287
+ /**
288
+ * Execute task using tool-calling agent loop
289
+ *
290
+ * Replaces the old linear pipeline (generate content → write file → git commit)
291
+ * with an iterative tool-calling loop where the LLM decides what tools to use.
292
+ *
293
+ * Flow:
294
+ * 1. Fetch full task details from quest (if questId provided)
295
+ * 2. Set git working directory to worktree via MCP
296
+ * 3. Build system prompt with task context and available tools
297
+ * 4. Enter tool-calling loop:
298
+ * a. Send messages + tools to ProviderManager.chat()
299
+ * b. If response contains __TOOL_CALLS__, execute each tool via invokeRemote
300
+ * c. Feed tool results back as messages
301
+ * d. Repeat until LLM returns plain text (done) or max iterations reached
302
+ * 5. Extract files created/modified and commit SHA from tool call history
303
+ * 6. Publish task.completed event
304
+ *
305
+ * @param task - Validated task assignment event
306
+ */
307
+ protected executeTask(task: TaskAssignedEvent): Promise<void>;
308
+ /**
309
+ * Build the system prompt for the tool-calling agent loop
310
+ *
311
+ * Includes task context, role identity, worktree path, and instructions
312
+ * for using available tools (git, file operations).
313
+ */
314
+ protected buildTaskSystemPrompt(task: TaskAssignedEvent, implementationGuide: string, verificationCriteria: string): string;
315
+ /**
316
+ * Build tool definitions: local tools + dynamic discovery from KĀDI broker
317
+ *
318
+ * 1. Always includes local tools (write_file, read_file)
319
+ * 2. Discovers network tools from broker via kadi.ability.list
320
+ * 3. Filters network tools by toolPrefixes from role config
321
+ * 4. Converts to OpenAI-compatible ToolDefinition format
322
+ */
323
+ protected buildToolDefinitionsAsync(): Promise<ToolDefinition[]>;
324
+ /**
325
+ * Fallback: append hardcoded git tool definitions when broker discovery fails
326
+ */
327
+ private appendHardcodedGitTools;
328
+ /**
329
+ * @deprecated Use buildToolDefinitionsAsync() instead. Kept for backward compatibility.
330
+ */
331
+ protected buildToolDefinitions(): ToolDefinition[];
332
+ /**
333
+ * Execute a remote MCP tool or local file operation via KĀDI broker
334
+ *
335
+ * Routes tool calls to either local file operations (write_file, read_file)
336
+ * or remote MCP tools via client.invokeRemote().
337
+ *
338
+ * @param toolName - Tool name (e.g., 'git_git_add', 'write_file')
339
+ * @param toolArgs - Tool arguments object
340
+ * @returns Tool execution result
341
+ */
342
+ protected executeRemoteTool(toolName: string, toolArgs: Record<string, any>): Promise<any>;
343
+ /**
344
+ * Track file operations from tool call results
345
+ *
346
+ * Inspects tool name and arguments to determine which files were
347
+ * created or modified during the agent loop.
348
+ */
349
+ private trackFileOperations;
350
+ /**
351
+ * Extract commit SHA from git_commit tool result
352
+ */
353
+ private extractCommitSha;
354
+ /**
355
+ * Sanitize filename to remove unsafe characters
356
+ *
357
+ * Utility method kept for subclass use and backward compatibility.
358
+ *
359
+ * @param filename - Raw filename
360
+ * @returns Sanitized filename safe for filesystem
361
+ */
362
+ protected sanitizeFilename(filename: string): string;
363
+ /**
364
+ * Format commit message for git commit
365
+ *
366
+ * Utility method kept for subclass use. The tool-calling loop
367
+ * instructs the LLM to use this format in the system prompt.
368
+ *
369
+ * @param taskId - Task ID to include in commit message
370
+ * @param files - Array of file paths that were modified/created
371
+ * @param taskDescription - Optional task description for context
372
+ * @returns Formatted commit message
373
+ */
374
+ protected formatCommitMessage(taskId: string, files: string[], taskDescription?: string): string;
375
+ /**
376
+ * Publish task completion event
377
+ *
378
+ * Publishes TaskCompletedEvent to KĀDI broker with topic pattern: {role}.task.completed
379
+ * Event payload matches TaskCompletedEvent schema exactly for backward compatibility.
380
+ *
381
+ * Publishing failures are handled gracefully - errors are logged but do not throw.
382
+ * This ensures task execution completes even if event publishing fails.
383
+ *
384
+ * @param taskId - Task ID that completed
385
+ * @param filesCreated - Array of file paths created during task execution
386
+ * @param filesModified - Array of file paths modified during task execution
387
+ * @param commitSha - Git commit SHA of the commit containing task output
388
+ *
389
+ * @example
390
+ * ```typescript
391
+ * await this.publishCompletion(
392
+ * 'task-123',
393
+ * ['artwork.png'],
394
+ * [],
395
+ * 'a1b2c3d4e5f6g7h8i9j0'
396
+ * );
397
+ * // Publishes to: task.completed
398
+ * ```
399
+ */
400
+ protected publishCompletion(taskId: string, questId: string | undefined, filesCreated: string[], filesModified: string[], commitSha: string, contentSummary?: string): Promise<void>;
401
+ /**
402
+ * Publish task failure event
403
+ *
404
+ * Publishes TaskFailedEvent to KĀDI broker with topic pattern: {role}.task.failed
405
+ * Event payload matches TaskFailedEvent schema exactly for backward compatibility.
406
+ *
407
+ * Publishing failures are handled gracefully - errors are logged but do not throw.
408
+ * This prevents cascading failures when event publishing is unavailable.
409
+ *
410
+ * @param taskId - Task ID that failed
411
+ * @param error - Error that caused task failure
412
+ *
413
+ * @example
414
+ * ```typescript
415
+ * try {
416
+ * await this.executeTask(task);
417
+ * } catch (error) {
418
+ * await this.publishFailure('task-123', error as Error);
419
+ * // Publishes to: task.failed
420
+ * }
421
+ * ```
422
+ */
423
+ protected publishFailure(taskId: string, error: Error, questId?: string): Promise<void>;
424
+ /**
425
+ * Validate whether a task matches this agent's capabilities
426
+ *
427
+ * Performs keyword matching between the task description and the agent's
428
+ * capability list. If no overlap is found, returns a rejection reason.
429
+ *
430
+ * @param task - Task assignment event to validate
431
+ * @returns Rejection reason string if task doesn't match, null if it does
432
+ */
433
+ protected validateTaskCapability(task: TaskAssignedEvent): string | null;
434
+ /**
435
+ * Validate that task targets paths within this agent's worktree.
436
+ *
437
+ * Extracts absolute file paths from task description and requirements,
438
+ * then checks if any fall outside the agent's worktree directory.
439
+ *
440
+ * @param task - Task assignment event to validate
441
+ * @returns Rejection reason string if task targets out-of-scope paths, null if OK
442
+ */
443
+ protected validateTaskScope(task: TaskAssignedEvent): string | null;
444
+ /**
445
+ * Publish task rejection event
446
+ *
447
+ * Publishes TaskRejectedEvent to KĀDI broker with topic: task.rejected
448
+ * This notifies agent-producer that the task was rejected due to capability mismatch,
449
+ * allowing it to reassign or escalate to the human.
450
+ *
451
+ * @param taskId - Task ID that was rejected
452
+ * @param questId - Quest ID (optional)
453
+ * @param reason - Reason for rejection
454
+ */
455
+ protected publishRejection(taskId: string, questId: string | undefined, reason: string): Promise<void>;
456
+ /**
457
+ * Start the worker agent
458
+ *
459
+ * Performs initialization sequence:
460
+ * 1. Connect to KĀDI broker
461
+ * 2. Initialize broker protocol
462
+ * 3. Connect event publisher
463
+ * 4. Subscribe to {role}.task.assigned events
464
+ * 5. Enter event loop (non-blocking)
465
+ *
466
+ * After start() completes, the agent is ready to receive task assignments.
467
+ *
468
+ * @throws {Error} If broker connection fails after all retries
469
+ *
470
+ * @example
471
+ * ```typescript
472
+ * const agent = new BaseWorkerAgent(config);
473
+ * await agent.start();
474
+ * console.log('Agent is now listening for task assignments');
475
+ * ```
476
+ */
477
+ start(): Promise<void>;
478
+ /**
479
+ * Stop the worker agent
480
+ *
481
+ * Performs cleanup sequence:
482
+ * 1. Unsubscribe from all events (TODO: next task)
483
+ * 2. Disconnect event publisher
484
+ * 3. Disconnect KĀDI client
485
+ * 4. Clear protocol reference
486
+ *
487
+ * After stop() completes, the agent is fully shut down and can be safely destroyed.
488
+ *
489
+ * @example
490
+ * ```typescript
491
+ * await agent.stop();
492
+ * console.log('Agent has been stopped');
493
+ * ```
494
+ */
495
+ stop(): Promise<void>;
496
+ /**
497
+ * Invoke tool with retry logic using composed BaseBot
498
+ *
499
+ * Delegates to BaseBot's invokeToolWithRetry() method for resilient tool invocation.
500
+ * This demonstrates the composition pattern - we use BaseBot's functionality
501
+ * without inheriting from it.
502
+ *
503
+ * @param params - Tool invocation parameters
504
+ * @returns Tool invocation result
505
+ *
506
+ * @example
507
+ * ```typescript
508
+ * const result = await this.invokeToolWithRetry({
509
+ * targetAgent: 'mcp-server-git',
510
+ * toolName: 'git_commit',
511
+ * toolInput: { message: 'feat: create artwork', files: ['artwork.png'] },
512
+ * timeout: 30000
513
+ * });
514
+ * ```
515
+ */
516
+ protected invokeToolWithRetry(params: {
517
+ targetAgent: string;
518
+ toolName: string;
519
+ toolInput: any;
520
+ timeout: number;
521
+ }): Promise<any>;
522
+ /**
523
+ * Check circuit breaker state using composed BaseBot
524
+ *
525
+ * @returns True if circuit is open, false if closed (or no BaseBot)
526
+ */
527
+ protected checkCircuitBreaker(): boolean;
528
+ /**
529
+ * Set the ProviderManager for LLM chat
530
+ *
531
+ * Called by the agent entry point after constructing BaseAgent
532
+ * (which creates the ProviderManager).
533
+ *
534
+ * @param pm - ProviderManager instance from BaseAgent
535
+ */
536
+ setProviderManager(pm: ProviderManager): void;
537
+ /**
538
+ * Configure role-specific settings from a loaded RoleConfig
539
+ *
540
+ * @param roleConfig - Parsed role configuration
541
+ */
542
+ applyRoleConfig(roleConfig: {
543
+ capabilities?: string[];
544
+ tools?: string[];
545
+ provider?: {
546
+ model?: string;
547
+ temperature?: number;
548
+ maxTokens?: number;
549
+ };
550
+ commitFormat?: string;
551
+ }): void;
552
+ }
553
+ /**
554
+ * Factory class for creating worker agents with validated configuration
555
+ *
556
+ * Provides static factory method for instantiating worker agents with:
557
+ * - Runtime configuration validation using Zod schemas
558
+ * - Descriptive error messages for invalid configurations
559
+ * - Type-safe agent creation with compile-time checks
560
+ * - Clean separation between validation and instantiation
561
+ *
562
+ * The factory validates all required configuration fields before creating
563
+ * the agent instance, ensuring early failure with clear error messages
564
+ * rather than runtime errors during agent execution.
565
+ *
566
+ * @example
567
+ * ```typescript
568
+ * // Minimal agent creation (10-15 lines)
569
+ * import { WorkerAgentFactory } from 'agents-library';
570
+ *
571
+ * const agent = WorkerAgentFactory.createAgent({
572
+ * role: 'artist',
573
+ * worktreePath: 'C:/p4/Personal/SD/agent-playground-artist',
574
+ * brokerUrl: 'ws://localhost:8080/kadi',
575
+ * networks: ['kadi'],
576
+ * anthropicApiKey: process.env.ANTHROPIC_API_KEY!
577
+ * });
578
+ *
579
+ * await agent.start();
580
+ * // Agent now listens for artist.task.assigned events
581
+ * ```
582
+ *
583
+ * @example
584
+ * ```typescript
585
+ * // With custom behaviors (under 50 lines)
586
+ * import { WorkerAgentFactory } from 'agents-library';
587
+ *
588
+ * const agent = WorkerAgentFactory.createAgent({
589
+ * role: 'artist',
590
+ * worktreePath: 'C:/p4/Personal/SD/agent-playground-artist',
591
+ * brokerUrl: 'ws://localhost:8080/kadi',
592
+ * networks: ['kadi'],
593
+ * anthropicApiKey: process.env.ANTHROPIC_API_KEY!,
594
+ * claudeModel: 'claude-sonnet-4-20250514',
595
+ * customBehaviors: {
596
+ * determineFilename: (taskId, description) => {
597
+ * // Custom filename logic
598
+ * return `artwork-${taskId}.png`;
599
+ * },
600
+ * formatCommitMessage: (taskId, files) => {
601
+ * // Custom commit message format
602
+ * return `feat: create artwork for ${taskId}`;
603
+ * }
604
+ * }
605
+ * });
606
+ *
607
+ * await agent.start();
608
+ * console.log('Agent started successfully');
609
+ * ```
610
+ */
611
+ export declare class WorkerAgentFactory {
612
+ /**
613
+ * Create a worker agent with validated configuration
614
+ *
615
+ * Static factory method that validates configuration and creates a
616
+ * BaseWorkerAgent instance ready for start().
617
+ *
618
+ * Validation performed:
619
+ * - Role must be 'artist', 'designer', or 'programmer'
620
+ * - Worktree path must be non-empty string
621
+ * - Broker URL must start with ws:// or wss://
622
+ * - Networks array must contain at least one network name
623
+ * - Anthropic API key must be provided
624
+ * - Custom behaviors (if provided) must match expected signatures
625
+ *
626
+ * @param config - Worker agent configuration object
627
+ * @returns Configured BaseWorkerAgent instance (not started)
628
+ *
629
+ * @throws {z.ZodError} If configuration validation fails with detailed error messages
630
+ *
631
+ * @example
632
+ * ```typescript
633
+ * // Basic usage
634
+ * const agent = WorkerAgentFactory.createAgent({
635
+ * role: 'artist',
636
+ * worktreePath: 'C:/p4/Personal/SD/agent-playground-artist',
637
+ * brokerUrl: 'ws://localhost:8080/kadi',
638
+ * networks: ['kadi'],
639
+ * anthropicApiKey: process.env.ANTHROPIC_API_KEY!
640
+ * });
641
+ *
642
+ * // Agent is created but not started - caller must call start()
643
+ * await agent.start();
644
+ * ```
645
+ *
646
+ * @example
647
+ * ```typescript
648
+ * // Error handling
649
+ * try {
650
+ * const agent = WorkerAgentFactory.createAgent(config);
651
+ * await agent.start();
652
+ * } catch (error) {
653
+ * if (error instanceof z.ZodError) {
654
+ * console.error('Configuration validation failed:');
655
+ * error.issues.forEach(issue => {
656
+ * console.error(` - ${issue.path.join('.')}: ${issue.message}`);
657
+ * });
658
+ * } else {
659
+ * console.error('Agent startup failed:', error);
660
+ * }
661
+ * }
662
+ * ```
663
+ */
664
+ static createAgent(config: WorkerAgentConfig): BaseWorkerAgent;
665
+ }
666
+ /**
667
+ * Create a worker agent with configuration
668
+ *
669
+ * Convenience function that delegates to WorkerAgentFactory.createAgent().
670
+ * Provides backward compatibility with existing code.
671
+ *
672
+ * @param config - Worker agent configuration
673
+ * @returns Configured BaseWorkerAgent instance
674
+ *
675
+ * @example
676
+ * ```typescript
677
+ * const agent = createWorkerAgent({
678
+ * role: 'artist',
679
+ * worktreePath: 'C:/p4/Personal/SD/agent-playground-artist',
680
+ * brokerUrl: 'ws://localhost:8080/kadi',
681
+ * networks: ['kadi'],
682
+ * anthropicApiKey: process.env.ANTHROPIC_API_KEY!
683
+ * });
684
+ * await agent.start();
685
+ * ```
686
+ */
687
+ export declare function createWorkerAgent(config: WorkerAgentConfig): BaseWorkerAgent;
688
+ //# sourceMappingURL=worker-agent-factory.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"worker-agent-factory.d.ts","sourceRoot":"","sources":["../src/worker-agent-factory.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAEH,OAAO,EAAE,UAAU,EAAK,MAAM,kBAAkB,CAAC;AACjD,OAAO,KAAK,EAAE,iBAAiB,EAAE,SAAS,EAAE,MAAM,yBAAyB,CAAC;AAE5E,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,iCAAiC,CAAC;AACvE,OAAO,KAAK,EAAW,cAAc,EAAe,MAAM,sBAAsB,CAAC;AACjF,OAAO,EACL,iBAAiB,EAKlB,MAAM,0BAA0B,CAAC;AAiDlC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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