societyai 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. package/CHANGELOG.md +111 -0
  2. package/LICENSE +21 -0
  3. package/README.md +879 -0
  4. package/dist/builder.d.ts +181 -0
  5. package/dist/builder.d.ts.map +1 -0
  6. package/dist/builder.js +667 -0
  7. package/dist/builder.js.map +1 -0
  8. package/dist/config.d.ts +43 -0
  9. package/dist/config.d.ts.map +1 -0
  10. package/dist/config.js +11 -0
  11. package/dist/config.js.map +1 -0
  12. package/dist/context.d.ts +107 -0
  13. package/dist/context.d.ts.map +1 -0
  14. package/dist/context.js +319 -0
  15. package/dist/context.js.map +1 -0
  16. package/dist/errors.d.ts +31 -0
  17. package/dist/errors.d.ts.map +1 -0
  18. package/dist/errors.js +85 -0
  19. package/dist/errors.js.map +1 -0
  20. package/dist/events.d.ts +219 -0
  21. package/dist/events.d.ts.map +1 -0
  22. package/dist/events.js +395 -0
  23. package/dist/events.js.map +1 -0
  24. package/dist/graph.d.ts +104 -0
  25. package/dist/graph.d.ts.map +1 -0
  26. package/dist/graph.js +366 -0
  27. package/dist/graph.js.map +1 -0
  28. package/dist/index.d.ts +28 -0
  29. package/dist/index.d.ts.map +1 -0
  30. package/dist/index.js +113 -0
  31. package/dist/index.js.map +1 -0
  32. package/dist/logger.d.ts +13 -0
  33. package/dist/logger.d.ts.map +1 -0
  34. package/dist/logger.js +78 -0
  35. package/dist/logger.js.map +1 -0
  36. package/dist/memory.d.ts +146 -0
  37. package/dist/memory.d.ts.map +1 -0
  38. package/dist/memory.js +353 -0
  39. package/dist/memory.js.map +1 -0
  40. package/dist/metrics.d.ts +143 -0
  41. package/dist/metrics.d.ts.map +1 -0
  42. package/dist/metrics.js +271 -0
  43. package/dist/metrics.js.map +1 -0
  44. package/dist/middleware.d.ts +147 -0
  45. package/dist/middleware.d.ts.map +1 -0
  46. package/dist/middleware.js +484 -0
  47. package/dist/middleware.js.map +1 -0
  48. package/dist/models.d.ts +32 -0
  49. package/dist/models.d.ts.map +1 -0
  50. package/dist/models.js +211 -0
  51. package/dist/models.js.map +1 -0
  52. package/dist/patterns.d.ts +6 -0
  53. package/dist/patterns.d.ts.map +1 -0
  54. package/dist/patterns.js +68 -0
  55. package/dist/patterns.js.map +1 -0
  56. package/dist/pipeline.d.ts +84 -0
  57. package/dist/pipeline.d.ts.map +1 -0
  58. package/dist/pipeline.js +569 -0
  59. package/dist/pipeline.js.map +1 -0
  60. package/dist/retry.d.ts +5 -0
  61. package/dist/retry.d.ts.map +1 -0
  62. package/dist/retry.js +70 -0
  63. package/dist/retry.js.map +1 -0
  64. package/dist/society.d.ts +94 -0
  65. package/dist/society.d.ts.map +1 -0
  66. package/dist/society.js +721 -0
  67. package/dist/society.js.map +1 -0
  68. package/dist/strategies.d.ts +55 -0
  69. package/dist/strategies.d.ts.map +1 -0
  70. package/dist/strategies.js +678 -0
  71. package/dist/strategies.js.map +1 -0
  72. package/dist/tools.d.ts +88 -0
  73. package/dist/tools.d.ts.map +1 -0
  74. package/dist/tools.js +366 -0
  75. package/dist/tools.js.map +1 -0
  76. package/dist/types.d.ts +213 -0
  77. package/dist/types.d.ts.map +1 -0
  78. package/dist/types.js +19 -0
  79. package/dist/types.js.map +1 -0
  80. package/dist/validation.d.ts +64 -0
  81. package/dist/validation.d.ts.map +1 -0
  82. package/dist/validation.js +334 -0
  83. package/dist/validation.js.map +1 -0
  84. package/dist/worker-pool.d.ts +17 -0
  85. package/dist/worker-pool.d.ts.map +1 -0
  86. package/dist/worker-pool.js +80 -0
  87. package/dist/worker-pool.js.map +1 -0
  88. package/docs/README.md +468 -0
  89. package/docs/advanced.md +616 -0
  90. package/docs/aggregation-strategies.md +926 -0
  91. package/docs/api-reference.md +771 -0
  92. package/docs/architecture.md +648 -0
  93. package/docs/context-system.md +642 -0
  94. package/docs/event-system.md +1047 -0
  95. package/docs/examples.md +576 -0
  96. package/docs/getting-started.md +564 -0
  97. package/docs/graph-execution.md +389 -0
  98. package/docs/memory-system.md +497 -0
  99. package/docs/metrics-observability.md +560 -0
  100. package/docs/middleware-system.md +1038 -0
  101. package/docs/migration.md +296 -0
  102. package/docs/pipeline-patterns.md +761 -0
  103. package/docs/structured-output.md +612 -0
  104. package/docs/tool-calling.md +491 -0
  105. package/docs/workflows.md +740 -0
  106. package/examples/README.md +234 -0
  107. package/examples/advanced-patterns.ts +115 -0
  108. package/examples/complete-integration.ts +327 -0
  109. package/examples/graph-workflow.ts +161 -0
  110. package/examples/memory-system.ts +155 -0
  111. package/examples/metrics-tracking.ts +243 -0
  112. package/examples/structured-output.ts +231 -0
  113. package/examples/tool-calling.ts +163 -0
  114. package/package.json +94 -0
@@ -0,0 +1,721 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DefaultWorkflowExecutor = exports.WorkflowConfigBuilder = exports.StepBuilder = exports.AgentBuilder = exports.RoleBuilder = exports.MessageBus = void 0;
4
+ const logger_1 = require("./logger");
5
+ const worker_pool_1 = require("./worker-pool");
6
+ class MessageBus {
7
+ constructor() {
8
+ this.handlers = new Map();
9
+ this.history = [];
10
+ }
11
+ async send(message) {
12
+ this.history.push(message);
13
+ if (message.to === 'broadcast') {
14
+ for (const [agentId, handler] of this.handlers) {
15
+ if (agentId !== message.from) {
16
+ handler(message);
17
+ }
18
+ }
19
+ }
20
+ else {
21
+ const handler = this.handlers.get(message.to);
22
+ if (handler) {
23
+ handler(message);
24
+ }
25
+ }
26
+ }
27
+ subscribe(agentId, handler) {
28
+ this.handlers.set(agentId, handler);
29
+ }
30
+ unsubscribe(agentId) {
31
+ this.handlers.delete(agentId);
32
+ }
33
+ getHistory(filter) {
34
+ if (!filter)
35
+ return [...this.history];
36
+ return this.history.filter((msg) => {
37
+ if (filter.from && msg.from !== filter.from)
38
+ return false;
39
+ if (filter.to && msg.to !== filter.to && msg.to !== 'broadcast')
40
+ return false;
41
+ if (filter.type && msg.type !== filter.type)
42
+ return false;
43
+ return true;
44
+ });
45
+ }
46
+ clearHistory() {
47
+ this.history = [];
48
+ }
49
+ }
50
+ exports.MessageBus = MessageBus;
51
+ class RoleBuilder {
52
+ constructor(idOrName) {
53
+ this.role = {};
54
+ if (idOrName) {
55
+ this.role.id = idOrName;
56
+ this.role.name = idOrName;
57
+ }
58
+ }
59
+ static create() {
60
+ return new RoleBuilder();
61
+ }
62
+ withId(id) {
63
+ this.role.id = id;
64
+ return this;
65
+ }
66
+ withName(name) {
67
+ this.role.name = name;
68
+ return this;
69
+ }
70
+ withDescription(description) {
71
+ this.role.description = description;
72
+ return this;
73
+ }
74
+ withSystemPrompt(prompt) {
75
+ this.role.systemPrompt = prompt;
76
+ return this;
77
+ }
78
+ withCapabilities(capabilities) {
79
+ this.role.capabilities = capabilities;
80
+ return this;
81
+ }
82
+ withConstraints(constraints) {
83
+ this.role.constraints = constraints;
84
+ return this;
85
+ }
86
+ withPromptTemplate(template) {
87
+ this.role.promptTemplate = template;
88
+ return this;
89
+ }
90
+ build() {
91
+ if (!this.role.id)
92
+ throw new Error('Role id is required');
93
+ if (!this.role.name)
94
+ throw new Error('Role name is required');
95
+ if (!this.role.systemPrompt)
96
+ throw new Error('Role systemPrompt is required');
97
+ return {
98
+ id: this.role.id,
99
+ name: this.role.name,
100
+ systemPrompt: this.role.systemPrompt,
101
+ description: this.role.description,
102
+ capabilities: this.role.capabilities,
103
+ constraints: this.role.constraints,
104
+ promptTemplate: this.role.promptTemplate,
105
+ };
106
+ }
107
+ }
108
+ exports.RoleBuilder = RoleBuilder;
109
+ class AgentBuilder {
110
+ constructor(id) {
111
+ this.config = {};
112
+ if (id) {
113
+ this.config.id = id;
114
+ this.config.name = id;
115
+ }
116
+ }
117
+ static create() {
118
+ return new AgentBuilder();
119
+ }
120
+ withId(id) {
121
+ this.config.id = id;
122
+ return this;
123
+ }
124
+ withName(name) {
125
+ this.config.name = name;
126
+ return this;
127
+ }
128
+ withRole(role) {
129
+ this.config.role = role;
130
+ return this;
131
+ }
132
+ withModel(model) {
133
+ this.config.model = model;
134
+ return this;
135
+ }
136
+ canCommunicateWith(agentIds) {
137
+ this.config.canCommunicateWith = agentIds;
138
+ return this;
139
+ }
140
+ withPriority(priority) {
141
+ this.config.priority = priority;
142
+ return this;
143
+ }
144
+ withInitialContext(context) {
145
+ this.config.initialContext = context;
146
+ return this;
147
+ }
148
+ build() {
149
+ if (!this.config.id)
150
+ throw new Error('Agent id is required');
151
+ if (!this.config.role)
152
+ throw new Error('Agent role is required');
153
+ if (!this.config.model)
154
+ throw new Error('Agent model is required');
155
+ return {
156
+ id: this.config.id,
157
+ name: this.config.name,
158
+ role: this.config.role,
159
+ model: this.config.model,
160
+ canCommunicateWith: this.config.canCommunicateWith,
161
+ priority: this.config.priority ?? 0,
162
+ initialContext: this.config.initialContext,
163
+ };
164
+ }
165
+ }
166
+ exports.AgentBuilder = AgentBuilder;
167
+ class StepBuilder {
168
+ constructor(id) {
169
+ this.step = {};
170
+ if (id) {
171
+ this.step.id = id;
172
+ this.step.name = id;
173
+ }
174
+ }
175
+ static create() {
176
+ return new StepBuilder();
177
+ }
178
+ withId(id) {
179
+ this.step.id = id;
180
+ return this;
181
+ }
182
+ withName(name) {
183
+ this.step.name = name;
184
+ return this;
185
+ }
186
+ withDescription(description) {
187
+ this.step.description = description;
188
+ return this;
189
+ }
190
+ withAgents(agentIds) {
191
+ this.step.agentIds = agentIds;
192
+ return this;
193
+ }
194
+ withExecutionType(type) {
195
+ this.step.executionType = type;
196
+ return this;
197
+ }
198
+ withInstructions(instructions) {
199
+ this.step.instructions = instructions;
200
+ return this;
201
+ }
202
+ withPromptTemplate(template) {
203
+ this.step.promptTemplate = template;
204
+ return this;
205
+ }
206
+ withMaxIterations(max) {
207
+ this.step.maxIterations = max;
208
+ return this;
209
+ }
210
+ withCompletionCondition(condition) {
211
+ this.step.completionCondition = condition;
212
+ return this;
213
+ }
214
+ withResultTransformer(transformer) {
215
+ this.step.resultTransformer = transformer;
216
+ return this;
217
+ }
218
+ withCondition(condition) {
219
+ this.step.condition = condition;
220
+ return this;
221
+ }
222
+ withNextSteps(stepIds) {
223
+ this.step.nextSteps = stepIds;
224
+ return this;
225
+ }
226
+ withNextStepResolver(resolver) {
227
+ this.step.nextStepResolver = resolver;
228
+ return this;
229
+ }
230
+ build() {
231
+ if (!this.step.id)
232
+ throw new Error('Step id is required');
233
+ if (!this.step.name)
234
+ throw new Error('Step name is required');
235
+ if (!this.step.agentIds || this.step.agentIds.length === 0) {
236
+ throw new Error('Step must have at least one agent');
237
+ }
238
+ return {
239
+ id: this.step.id,
240
+ name: this.step.name,
241
+ description: this.step.description,
242
+ agentIds: this.step.agentIds,
243
+ executionType: this.step.executionType ?? 'sequential',
244
+ instructions: this.step.instructions,
245
+ promptTemplate: this.step.promptTemplate,
246
+ maxIterations: this.step.maxIterations,
247
+ completionCondition: this.step.completionCondition,
248
+ resultTransformer: this.step.resultTransformer,
249
+ condition: this.step.condition,
250
+ nextSteps: this.step.nextSteps,
251
+ nextStepResolver: this.step.nextStepResolver,
252
+ };
253
+ }
254
+ }
255
+ exports.StepBuilder = StepBuilder;
256
+ class WorkflowConfigBuilder {
257
+ constructor(id) {
258
+ this.config = {
259
+ agents: [],
260
+ steps: [],
261
+ };
262
+ if (id) {
263
+ this.config.id = id;
264
+ this.config.name = id;
265
+ }
266
+ }
267
+ static create() {
268
+ return new WorkflowConfigBuilder();
269
+ }
270
+ withId(id) {
271
+ this.config.id = id;
272
+ return this;
273
+ }
274
+ withName(name) {
275
+ this.config.name = name;
276
+ return this;
277
+ }
278
+ withDescription(description) {
279
+ this.config.description = description;
280
+ return this;
281
+ }
282
+ addAgent(agent) {
283
+ this.config.agents.push(agent);
284
+ return this;
285
+ }
286
+ addAgents(agents) {
287
+ this.config.agents.push(...agents);
288
+ return this;
289
+ }
290
+ addStep(step) {
291
+ this.config.steps.push(step);
292
+ return this;
293
+ }
294
+ addSteps(steps) {
295
+ this.config.steps.push(...steps);
296
+ return this;
297
+ }
298
+ withEntryStep(stepId) {
299
+ this.config.entryStepId = stepId;
300
+ return this;
301
+ }
302
+ withGlobalContext(context) {
303
+ this.config.globalContext = context;
304
+ return this;
305
+ }
306
+ onBeforeStep(handler) {
307
+ this.config.onBeforeStep = handler;
308
+ return this;
309
+ }
310
+ onAfterStep(handler) {
311
+ this.config.onAfterStep = handler;
312
+ return this;
313
+ }
314
+ withFinalResultGenerator(generator) {
315
+ this.config.finalResultGenerator = generator;
316
+ return this;
317
+ }
318
+ build() {
319
+ if (!this.config.id)
320
+ throw new Error('Workflow id is required');
321
+ if (!this.config.name)
322
+ throw new Error('Workflow name is required');
323
+ if (this.config.agents.length === 0)
324
+ throw new Error('Workflow must have at least one agent');
325
+ if (this.config.steps.length === 0)
326
+ throw new Error('Workflow must have at least one step');
327
+ return {
328
+ id: this.config.id,
329
+ name: this.config.name,
330
+ description: this.config.description,
331
+ agents: this.config.agents,
332
+ steps: this.config.steps,
333
+ entryStepId: this.config.entryStepId ?? this.config.steps[0].id,
334
+ globalContext: this.config.globalContext,
335
+ onBeforeStep: this.config.onBeforeStep,
336
+ onAfterStep: this.config.onAfterStep,
337
+ finalResultGenerator: this.config.finalResultGenerator,
338
+ };
339
+ }
340
+ }
341
+ exports.WorkflowConfigBuilder = WorkflowConfigBuilder;
342
+ class DefaultWorkflowExecutor {
343
+ constructor(observer) {
344
+ this.logger = (0, logger_1.getLogger)();
345
+ this.messageBus = new MessageBus();
346
+ this.observer = observer;
347
+ }
348
+ buildAgentPrompt(agent, step, context) {
349
+ const defaultTemplate = '{systemPrompt}\n\n{instructions}\n\nInput: {input}\n\nContext: {context}';
350
+ const template = step.promptTemplate ?? agent.role.promptTemplate ?? defaultTemplate;
351
+ const contextData = {
352
+ systemPrompt: agent.role.systemPrompt,
353
+ instructions: step.instructions ?? '',
354
+ input: context.input,
355
+ context: this.formatSharedData(context.sharedData),
356
+ history: this.formatMessageHistory(context.messageHistory, agent.id),
357
+ previousResults: this.formatPreviousResults(context.stepResults),
358
+ };
359
+ if (agent.role.capabilities?.length) {
360
+ contextData.capabilities = `Capabilities: ${agent.role.capabilities.join(', ')}`;
361
+ }
362
+ if (agent.role.constraints?.length) {
363
+ contextData.constraints = `Constraints: ${agent.role.constraints.join(', ')}`;
364
+ }
365
+ let prompt = template;
366
+ for (const [key, value] of Object.entries(contextData)) {
367
+ prompt = prompt.replace(new RegExp(`\\{${key}\\}`, 'g'), value);
368
+ }
369
+ return prompt;
370
+ }
371
+ formatSharedData(data) {
372
+ if (data.size === 0)
373
+ return '';
374
+ const entries = [];
375
+ for (const [key, value] of data) {
376
+ entries.push(`${key}: ${JSON.stringify(value)}`);
377
+ }
378
+ return entries.join('\n');
379
+ }
380
+ formatMessageHistory(messages, agentId) {
381
+ const relevant = messages.filter((m) => m.from === agentId || m.to === agentId || m.to === 'broadcast');
382
+ if (relevant.length === 0)
383
+ return '';
384
+ return relevant.map((m) => `[${m.from} → ${m.to}]: ${m.content}`).join('\n');
385
+ }
386
+ formatPreviousResults(results) {
387
+ if (results.size === 0)
388
+ return '';
389
+ const formatted = [];
390
+ for (const [stepId, stepResults] of results) {
391
+ formatted.push(`--- Step: ${stepId} ---`);
392
+ for (const result of stepResults) {
393
+ if (result.success) {
394
+ formatted.push(`[${result.agentId}]: ${result.content}`);
395
+ }
396
+ }
397
+ }
398
+ return formatted.join('\n');
399
+ }
400
+ async executeSequential(step, agents, context, signal) {
401
+ const results = [];
402
+ for (const agentId of step.agentIds) {
403
+ if (signal?.aborted)
404
+ throw new Error('Operation cancelled');
405
+ const agent = agents.get(agentId);
406
+ if (!agent) {
407
+ this.logger.error(`Agent ${agentId} not found`);
408
+ continue;
409
+ }
410
+ const prompt = this.buildAgentPrompt(agent, step, context);
411
+ this.logger.debug(`Agent ${agentId} processing step ${step.id}`);
412
+ if (this.observer) {
413
+ this.observer.onAgentStart(parseInt(agentId) || 0, agent.model.name(), prompt);
414
+ }
415
+ try {
416
+ const content = await agent.model.process(prompt, signal);
417
+ const result = {
418
+ agentId,
419
+ stepId: step.id,
420
+ content,
421
+ timestamp: Date.now(),
422
+ success: true,
423
+ };
424
+ results.push(result);
425
+ context.sharedData.set(`${step.id}_${agentId}_result`, content);
426
+ if (this.observer) {
427
+ this.observer.onAgentComplete(parseInt(agentId) || 0, agent.model.name(), content);
428
+ }
429
+ }
430
+ catch (error) {
431
+ if (signal?.aborted) {
432
+ throw error;
433
+ }
434
+ const result = {
435
+ agentId,
436
+ stepId: step.id,
437
+ content: '',
438
+ timestamp: Date.now(),
439
+ success: false,
440
+ error: error,
441
+ };
442
+ results.push(result);
443
+ if (this.observer) {
444
+ this.observer.onAgentError(parseInt(agentId) || 0, agent.model.name(), error);
445
+ }
446
+ }
447
+ }
448
+ return results;
449
+ }
450
+ async executeParallel(step, agents, context, signal) {
451
+ const pool = new worker_pool_1.WorkerPool(step.agentIds.length, signal);
452
+ const results = [];
453
+ const tasks = step.agentIds.map((agentId) => async () => {
454
+ const agent = agents.get(agentId);
455
+ if (!agent) {
456
+ this.logger.error(`Agent ${agentId} not found`);
457
+ return null;
458
+ }
459
+ const prompt = this.buildAgentPrompt(agent, step, context);
460
+ this.logger.debug(`Agent ${agentId} processing step ${step.id} (parallel)`);
461
+ if (this.observer) {
462
+ this.observer.onAgentStart(parseInt(agentId) || 0, agent.model.name(), prompt);
463
+ }
464
+ try {
465
+ const content = await agent.model.process(prompt, signal);
466
+ const result = {
467
+ agentId,
468
+ stepId: step.id,
469
+ content,
470
+ timestamp: Date.now(),
471
+ success: true,
472
+ };
473
+ if (this.observer) {
474
+ this.observer.onAgentComplete(parseInt(agentId) || 0, agent.model.name(), content);
475
+ }
476
+ return result;
477
+ }
478
+ catch (error) {
479
+ if (signal?.aborted) {
480
+ throw error;
481
+ }
482
+ if (this.observer) {
483
+ this.observer.onAgentError(parseInt(agentId) || 0, agent.model.name(), error);
484
+ }
485
+ return {
486
+ agentId,
487
+ stepId: step.id,
488
+ content: '',
489
+ timestamp: Date.now(),
490
+ success: false,
491
+ error: error,
492
+ };
493
+ }
494
+ });
495
+ const taskResults = await Promise.all(tasks.map((task) => pool.submit(task)));
496
+ await pool.waitAll();
497
+ for (const result of taskResults) {
498
+ if (result) {
499
+ results.push(result);
500
+ if (result.success) {
501
+ context.sharedData.set(`${step.id}_${result.agentId}_result`, result.content);
502
+ }
503
+ }
504
+ }
505
+ return results;
506
+ }
507
+ async executeCollaborative(step, agents, context, signal) {
508
+ const maxIterations = step.maxIterations ?? 3;
509
+ let allResults = [];
510
+ for (let iteration = 0; iteration < maxIterations; iteration++) {
511
+ if (signal?.aborted)
512
+ throw new Error('Operation cancelled');
513
+ this.logger.info(`Collaborative step ${step.id} - iteration ${iteration + 1}/${maxIterations}`);
514
+ const iterationResults = [];
515
+ for (const agentId of step.agentIds) {
516
+ const agent = agents.get(agentId);
517
+ if (!agent)
518
+ continue;
519
+ const enrichedContext = { ...context };
520
+ enrichedContext.sharedData = new Map(context.sharedData);
521
+ enrichedContext.sharedData.set('currentIteration', iteration);
522
+ enrichedContext.sharedData.set('previousIterationResults', allResults);
523
+ const prompt = this.buildAgentPrompt(agent, step, enrichedContext);
524
+ try {
525
+ const content = await agent.model.process(prompt, signal);
526
+ const result = {
527
+ agentId,
528
+ stepId: step.id,
529
+ content,
530
+ timestamp: Date.now(),
531
+ success: true,
532
+ iteration,
533
+ };
534
+ iterationResults.push(result);
535
+ const message = {
536
+ from: agentId,
537
+ to: 'broadcast',
538
+ type: 'data',
539
+ content: content,
540
+ timestamp: Date.now(),
541
+ messageId: `${agentId}-${step.id}-${iteration}-${Date.now()}`,
542
+ };
543
+ await this.messageBus.send(message);
544
+ context.messageHistory.push(message);
545
+ }
546
+ catch (error) {
547
+ if (signal?.aborted) {
548
+ throw error;
549
+ }
550
+ iterationResults.push({
551
+ agentId,
552
+ stepId: step.id,
553
+ content: '',
554
+ timestamp: Date.now(),
555
+ success: false,
556
+ error: error,
557
+ iteration,
558
+ });
559
+ }
560
+ }
561
+ allResults = [...allResults, ...iterationResults];
562
+ if (step.completionCondition && step.completionCondition(allResults, iteration)) {
563
+ this.logger.info(`Collaborative step ${step.id} completed at iteration ${iteration + 1}`);
564
+ break;
565
+ }
566
+ }
567
+ return allResults;
568
+ }
569
+ async executeStep(step, agents, context, signal) {
570
+ this.logger.info(`Executing step: ${step.name} (${step.executionType})`);
571
+ if (this.observer) {
572
+ this.observer.onPhaseStart(step.name);
573
+ }
574
+ if (step.executionType === 'conditional' && step.condition) {
575
+ if (!step.condition(context.stepResults)) {
576
+ this.logger.info(`Step ${step.id} skipped (condition not met)`);
577
+ if (this.observer) {
578
+ this.observer.onPhaseComplete(step.name);
579
+ }
580
+ return [];
581
+ }
582
+ }
583
+ let results;
584
+ switch (step.executionType) {
585
+ case 'parallel':
586
+ results = await this.executeParallel(step, agents, context, signal);
587
+ break;
588
+ case 'collaborative':
589
+ results = await this.executeCollaborative(step, agents, context, signal);
590
+ break;
591
+ case 'sequential':
592
+ case 'conditional':
593
+ default:
594
+ results = await this.executeSequential(step, agents, context, signal);
595
+ break;
596
+ }
597
+ if (step.resultTransformer && results.length > 0) {
598
+ const transformedContent = step.resultTransformer(results);
599
+ context.sharedData.set(`${step.id}_transformed`, transformedContent);
600
+ }
601
+ if (this.observer) {
602
+ this.observer.onPhaseComplete(step.name);
603
+ }
604
+ return results;
605
+ }
606
+ async execute(workflow, input, signal) {
607
+ const startTime = Date.now();
608
+ const errors = [];
609
+ if (signal?.aborted) {
610
+ throw new Error('Operation cancelled');
611
+ }
612
+ this.logger.info(`Starting workflow: ${workflow.name}`);
613
+ if (this.observer) {
614
+ this.observer.onSocietyStart(input, workflow.agents.length);
615
+ }
616
+ const agentsMap = new Map();
617
+ for (const agent of workflow.agents) {
618
+ agentsMap.set(agent.id, agent);
619
+ this.messageBus.subscribe(agent.id, (message) => {
620
+ this.logger.debug(`Agent ${agent.id} received message from ${message.from}`);
621
+ });
622
+ }
623
+ const context = {
624
+ input,
625
+ sharedData: new Map(Object.entries(workflow.globalContext ?? {})),
626
+ stepResults: new Map(),
627
+ messageHistory: [],
628
+ metadata: {},
629
+ };
630
+ const stepsMap = new Map();
631
+ for (const step of workflow.steps) {
632
+ stepsMap.set(step.id, step);
633
+ }
634
+ let currentStepId = workflow.entryStepId ?? workflow.steps[0].id;
635
+ while (currentStepId) {
636
+ if (signal?.aborted) {
637
+ throw new Error('Operation cancelled');
638
+ }
639
+ const step = stepsMap.get(currentStepId);
640
+ if (!step) {
641
+ errors.push(new Error(`Step ${currentStepId} not found`));
642
+ break;
643
+ }
644
+ if (workflow.onBeforeStep) {
645
+ await workflow.onBeforeStep(step, context);
646
+ }
647
+ try {
648
+ const stepResults = await this.executeStep(step, agentsMap, context, signal);
649
+ context.stepResults.set(step.id, stepResults);
650
+ for (const stepResult of stepResults) {
651
+ if (!stepResult.success && stepResult.error) {
652
+ errors.push(stepResult.error);
653
+ }
654
+ }
655
+ if (workflow.onAfterStep) {
656
+ await workflow.onAfterStep(step, stepResults, context);
657
+ }
658
+ }
659
+ catch (error) {
660
+ if (signal?.aborted) {
661
+ throw error;
662
+ }
663
+ errors.push(error);
664
+ this.logger.error(`Step ${step.id} failed: ${error.message}`);
665
+ }
666
+ if (step.nextStepResolver) {
667
+ currentStepId = step.nextStepResolver(context.stepResults.get(step.id) ?? []);
668
+ }
669
+ else if (step.nextSteps && step.nextSteps.length > 0) {
670
+ currentStepId = step.nextSteps[0];
671
+ }
672
+ else {
673
+ const currentIndex = workflow.steps.findIndex((s) => s.id === currentStepId);
674
+ if (currentIndex >= 0 && currentIndex < workflow.steps.length - 1) {
675
+ currentStepId = workflow.steps[currentIndex + 1].id;
676
+ }
677
+ else {
678
+ currentStepId = null;
679
+ }
680
+ }
681
+ }
682
+ let output;
683
+ if (workflow.finalResultGenerator) {
684
+ output = await workflow.finalResultGenerator(context.stepResults, context);
685
+ }
686
+ else {
687
+ output = this.generateDefaultOutput(context.stepResults);
688
+ }
689
+ for (const agent of workflow.agents) {
690
+ this.messageBus.unsubscribe(agent.id);
691
+ }
692
+ const result = {
693
+ success: errors.length === 0,
694
+ output,
695
+ stepResults: context.stepResults,
696
+ messages: context.messageHistory,
697
+ duration: Date.now() - startTime,
698
+ errors: errors.length > 0 ? errors : undefined,
699
+ };
700
+ if (this.observer) {
701
+ this.observer.onSocietyComplete(output);
702
+ }
703
+ this.logger.info(`Workflow completed in ${result.duration}ms`);
704
+ return result;
705
+ }
706
+ generateDefaultOutput(stepResults) {
707
+ const parts = [];
708
+ for (const [stepId, results] of stepResults) {
709
+ parts.push(`=== ${stepId} ===`);
710
+ for (const result of results) {
711
+ if (result.success) {
712
+ parts.push(`[${result.agentId}]: ${result.content}`);
713
+ }
714
+ }
715
+ parts.push('');
716
+ }
717
+ return parts.join('\n');
718
+ }
719
+ }
720
+ exports.DefaultWorkflowExecutor = DefaultWorkflowExecutor;
721
+ //# sourceMappingURL=society.js.map