@jackchen_me/open-multi-agent 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 (133) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +280 -0
  3. package/dist/agent/agent.d.ts +121 -0
  4. package/dist/agent/agent.d.ts.map +1 -0
  5. package/dist/agent/agent.js +294 -0
  6. package/dist/agent/agent.js.map +1 -0
  7. package/dist/agent/pool.d.ts +128 -0
  8. package/dist/agent/pool.d.ts.map +1 -0
  9. package/dist/agent/pool.js +236 -0
  10. package/dist/agent/pool.js.map +1 -0
  11. package/dist/agent/runner.d.ts +120 -0
  12. package/dist/agent/runner.d.ts.map +1 -0
  13. package/dist/agent/runner.js +274 -0
  14. package/dist/agent/runner.js.map +1 -0
  15. package/dist/index.d.ts +73 -0
  16. package/dist/index.d.ts.map +1 -0
  17. package/dist/index.js +87 -0
  18. package/dist/index.js.map +1 -0
  19. package/dist/llm/adapter.d.ts +38 -0
  20. package/dist/llm/adapter.d.ts.map +1 -0
  21. package/dist/llm/adapter.js +46 -0
  22. package/dist/llm/adapter.js.map +1 -0
  23. package/dist/llm/anthropic.d.ts +56 -0
  24. package/dist/llm/anthropic.d.ts.map +1 -0
  25. package/dist/llm/anthropic.js +307 -0
  26. package/dist/llm/anthropic.js.map +1 -0
  27. package/dist/llm/openai.d.ts +62 -0
  28. package/dist/llm/openai.d.ts.map +1 -0
  29. package/dist/llm/openai.js +424 -0
  30. package/dist/llm/openai.js.map +1 -0
  31. package/dist/memory/shared.d.ts +86 -0
  32. package/dist/memory/shared.d.ts.map +1 -0
  33. package/dist/memory/shared.js +155 -0
  34. package/dist/memory/shared.js.map +1 -0
  35. package/dist/memory/store.d.ts +64 -0
  36. package/dist/memory/store.d.ts.map +1 -0
  37. package/dist/memory/store.js +103 -0
  38. package/dist/memory/store.js.map +1 -0
  39. package/dist/orchestrator/orchestrator.d.ts +173 -0
  40. package/dist/orchestrator/orchestrator.d.ts.map +1 -0
  41. package/dist/orchestrator/orchestrator.js +698 -0
  42. package/dist/orchestrator/orchestrator.js.map +1 -0
  43. package/dist/orchestrator/scheduler.d.ts +112 -0
  44. package/dist/orchestrator/scheduler.d.ts.map +1 -0
  45. package/dist/orchestrator/scheduler.js +282 -0
  46. package/dist/orchestrator/scheduler.js.map +1 -0
  47. package/dist/task/queue.d.ts +160 -0
  48. package/dist/task/queue.d.ts.map +1 -0
  49. package/dist/task/queue.js +337 -0
  50. package/dist/task/queue.js.map +1 -0
  51. package/dist/task/task.d.ts +86 -0
  52. package/dist/task/task.d.ts.map +1 -0
  53. package/dist/task/task.js +201 -0
  54. package/dist/task/task.js.map +1 -0
  55. package/dist/team/messaging.d.ts +106 -0
  56. package/dist/team/messaging.d.ts.map +1 -0
  57. package/dist/team/messaging.js +182 -0
  58. package/dist/team/messaging.js.map +1 -0
  59. package/dist/team/team.d.ts +141 -0
  60. package/dist/team/team.d.ts.map +1 -0
  61. package/dist/team/team.js +282 -0
  62. package/dist/team/team.js.map +1 -0
  63. package/dist/tool/built-in/bash.d.ts +12 -0
  64. package/dist/tool/built-in/bash.d.ts.map +1 -0
  65. package/dist/tool/built-in/bash.js +133 -0
  66. package/dist/tool/built-in/bash.js.map +1 -0
  67. package/dist/tool/built-in/file-edit.d.ts +14 -0
  68. package/dist/tool/built-in/file-edit.d.ts.map +1 -0
  69. package/dist/tool/built-in/file-edit.js +130 -0
  70. package/dist/tool/built-in/file-edit.js.map +1 -0
  71. package/dist/tool/built-in/file-read.d.ts +12 -0
  72. package/dist/tool/built-in/file-read.d.ts.map +1 -0
  73. package/dist/tool/built-in/file-read.js +82 -0
  74. package/dist/tool/built-in/file-read.js.map +1 -0
  75. package/dist/tool/built-in/file-write.d.ts +11 -0
  76. package/dist/tool/built-in/file-write.d.ts.map +1 -0
  77. package/dist/tool/built-in/file-write.js +70 -0
  78. package/dist/tool/built-in/file-write.js.map +1 -0
  79. package/dist/tool/built-in/grep.d.ts +15 -0
  80. package/dist/tool/built-in/grep.d.ts.map +1 -0
  81. package/dist/tool/built-in/grep.js +287 -0
  82. package/dist/tool/built-in/grep.js.map +1 -0
  83. package/dist/tool/built-in/index.d.ts +36 -0
  84. package/dist/tool/built-in/index.d.ts.map +1 -0
  85. package/dist/tool/built-in/index.js +45 -0
  86. package/dist/tool/built-in/index.js.map +1 -0
  87. package/dist/tool/executor.d.ts +71 -0
  88. package/dist/tool/executor.d.ts.map +1 -0
  89. package/dist/tool/executor.js +116 -0
  90. package/dist/tool/executor.js.map +1 -0
  91. package/dist/tool/framework.d.ts +143 -0
  92. package/dist/tool/framework.d.ts.map +1 -0
  93. package/dist/tool/framework.js +371 -0
  94. package/dist/tool/framework.js.map +1 -0
  95. package/dist/types.d.ts +285 -0
  96. package/dist/types.d.ts.map +1 -0
  97. package/dist/types.js +8 -0
  98. package/dist/types.js.map +1 -0
  99. package/dist/utils/semaphore.d.ts +47 -0
  100. package/dist/utils/semaphore.d.ts.map +1 -0
  101. package/dist/utils/semaphore.js +85 -0
  102. package/dist/utils/semaphore.js.map +1 -0
  103. package/examples/01-single-agent.ts +131 -0
  104. package/examples/02-team-collaboration.ts +167 -0
  105. package/examples/03-task-pipeline.ts +201 -0
  106. package/examples/04-multi-model-team.ts +261 -0
  107. package/package.json +49 -0
  108. package/src/agent/agent.ts +364 -0
  109. package/src/agent/pool.ts +278 -0
  110. package/src/agent/runner.ts +413 -0
  111. package/src/index.ts +166 -0
  112. package/src/llm/adapter.ts +74 -0
  113. package/src/llm/anthropic.ts +388 -0
  114. package/src/llm/openai.ts +522 -0
  115. package/src/memory/shared.ts +181 -0
  116. package/src/memory/store.ts +124 -0
  117. package/src/orchestrator/orchestrator.ts +851 -0
  118. package/src/orchestrator/scheduler.ts +352 -0
  119. package/src/task/queue.ts +394 -0
  120. package/src/task/task.ts +232 -0
  121. package/src/team/messaging.ts +230 -0
  122. package/src/team/team.ts +334 -0
  123. package/src/tool/built-in/bash.ts +187 -0
  124. package/src/tool/built-in/file-edit.ts +154 -0
  125. package/src/tool/built-in/file-read.ts +105 -0
  126. package/src/tool/built-in/file-write.ts +81 -0
  127. package/src/tool/built-in/grep.ts +362 -0
  128. package/src/tool/built-in/index.ts +50 -0
  129. package/src/tool/executor.ts +178 -0
  130. package/src/tool/framework.ts +557 -0
  131. package/src/types.ts +362 -0
  132. package/src/utils/semaphore.ts +89 -0
  133. package/tsconfig.json +25 -0
@@ -0,0 +1,698 @@
1
+ /**
2
+ * @fileoverview OpenMultiAgent — the top-level multi-agent orchestration class.
3
+ *
4
+ * {@link OpenMultiAgent} is the primary public API of the open-multi-agent framework.
5
+ * It ties together every subsystem:
6
+ *
7
+ * - {@link Team} — Agent roster, shared memory, inter-agent messaging
8
+ * - {@link TaskQueue} — Dependency-aware work queue
9
+ * - {@link Scheduler} — Task-to-agent assignment strategies
10
+ * - {@link AgentPool} — Concurrency-controlled execution pool
11
+ * - {@link Agent} — Conversation + tool-execution loop
12
+ *
13
+ * ## Quick start
14
+ *
15
+ * ```ts
16
+ * const orchestrator = new OpenMultiAgent({ defaultModel: 'claude-opus-4-6' })
17
+ *
18
+ * const team = orchestrator.createTeam('research', {
19
+ * name: 'research',
20
+ * agents: [
21
+ * { name: 'researcher', model: 'claude-opus-4-6', systemPrompt: 'You are a researcher.' },
22
+ * { name: 'writer', model: 'claude-opus-4-6', systemPrompt: 'You are a technical writer.' },
23
+ * ],
24
+ * sharedMemory: true,
25
+ * })
26
+ *
27
+ * const result = await orchestrator.runTeam(team, 'Produce a report on TypeScript 5.5.')
28
+ * console.log(result.agentResults.get('coordinator')?.output)
29
+ * ```
30
+ *
31
+ * ## Key design decisions
32
+ *
33
+ * - **Coordinator pattern** — `runTeam()` spins up a temporary "coordinator" agent
34
+ * that breaks the high-level goal into tasks, assigns them, and synthesises the
35
+ * final answer. This is the framework's killer feature.
36
+ * - **Parallel-by-default** — Independent tasks (no shared dependency) run in
37
+ * parallel up to `maxConcurrency`.
38
+ * - **Graceful failure** — A failed task marks itself `'failed'` and its direct
39
+ * dependents remain `'blocked'` indefinitely; all non-dependent tasks continue.
40
+ * - **Progress callbacks** — Callers can pass `onProgress` in the config to receive
41
+ * structured {@link OrchestratorEvent}s without polling.
42
+ */
43
+ import { Agent } from '../agent/agent.js';
44
+ import { AgentPool } from '../agent/pool.js';
45
+ import { ToolRegistry } from '../tool/framework.js';
46
+ import { ToolExecutor } from '../tool/executor.js';
47
+ import { registerBuiltInTools } from '../tool/built-in/index.js';
48
+ import { Team } from '../team/team.js';
49
+ import { TaskQueue } from '../task/queue.js';
50
+ import { createTask } from '../task/task.js';
51
+ import { Scheduler } from './scheduler.js';
52
+ // ---------------------------------------------------------------------------
53
+ // Internal constants
54
+ // ---------------------------------------------------------------------------
55
+ const ZERO_USAGE = { input_tokens: 0, output_tokens: 0 };
56
+ const DEFAULT_MAX_CONCURRENCY = 5;
57
+ const DEFAULT_MODEL = 'claude-opus-4-6';
58
+ // ---------------------------------------------------------------------------
59
+ // Internal helpers
60
+ // ---------------------------------------------------------------------------
61
+ function addUsage(a, b) {
62
+ return {
63
+ input_tokens: a.input_tokens + b.input_tokens,
64
+ output_tokens: a.output_tokens + b.output_tokens,
65
+ };
66
+ }
67
+ /**
68
+ * Build a minimal {@link Agent} with its own fresh registry/executor.
69
+ * Registers all built-in tools so coordinator/worker agents can use them.
70
+ */
71
+ function buildAgent(config) {
72
+ const registry = new ToolRegistry();
73
+ registerBuiltInTools(registry);
74
+ const executor = new ToolExecutor(registry);
75
+ return new Agent(config, registry, executor);
76
+ }
77
+ /**
78
+ * Attempt to extract a JSON array of task specs from the coordinator's raw
79
+ * output. The coordinator is prompted to emit JSON inside a ```json … ``` fence
80
+ * or as a bare array. Returns `null` when no valid array can be extracted.
81
+ */
82
+ function parseTaskSpecs(raw) {
83
+ // Strategy 1: look for a fenced JSON block
84
+ const fenceMatch = raw.match(/```json\s*([\s\S]*?)```/);
85
+ const candidate = fenceMatch ? fenceMatch[1] : raw;
86
+ // Strategy 2: find the first '[' and last ']'
87
+ const arrayStart = candidate.indexOf('[');
88
+ const arrayEnd = candidate.lastIndexOf(']');
89
+ if (arrayStart === -1 || arrayEnd === -1 || arrayEnd <= arrayStart) {
90
+ return null;
91
+ }
92
+ const jsonSlice = candidate.slice(arrayStart, arrayEnd + 1);
93
+ try {
94
+ const parsed = JSON.parse(jsonSlice);
95
+ if (!Array.isArray(parsed))
96
+ return null;
97
+ const specs = [];
98
+ for (const item of parsed) {
99
+ if (typeof item !== 'object' || item === null)
100
+ continue;
101
+ const obj = item;
102
+ if (typeof obj['title'] !== 'string')
103
+ continue;
104
+ if (typeof obj['description'] !== 'string')
105
+ continue;
106
+ specs.push({
107
+ title: obj['title'],
108
+ description: obj['description'],
109
+ assignee: typeof obj['assignee'] === 'string' ? obj['assignee'] : undefined,
110
+ dependsOn: Array.isArray(obj['dependsOn'])
111
+ ? obj['dependsOn'].filter((x) => typeof x === 'string')
112
+ : undefined,
113
+ });
114
+ }
115
+ return specs.length > 0 ? specs : null;
116
+ }
117
+ catch {
118
+ return null;
119
+ }
120
+ }
121
+ /**
122
+ * Execute all tasks in `queue` using agents in `pool`, respecting dependencies
123
+ * and running independent tasks in parallel.
124
+ *
125
+ * The orchestration loop works in rounds:
126
+ * 1. Find all `'pending'` tasks (dependencies satisfied).
127
+ * 2. Dispatch them in parallel via the pool.
128
+ * 3. On completion, the queue automatically unblocks dependents.
129
+ * 4. Repeat until no more pending tasks exist or all remaining tasks are
130
+ * `'failed'`/`'blocked'` (stuck).
131
+ */
132
+ async function executeQueue(queue, ctx) {
133
+ const { team, pool, scheduler, config } = ctx;
134
+ while (true) {
135
+ // Re-run auto-assignment each iteration so tasks that were unblocked since
136
+ // the last round (and thus have no assignee yet) get assigned before dispatch.
137
+ scheduler.autoAssign(queue, team.getAgents());
138
+ const pending = queue.getByStatus('pending');
139
+ if (pending.length === 0) {
140
+ // Either all done, or everything remaining is blocked/failed.
141
+ break;
142
+ }
143
+ // Dispatch all currently-pending tasks as a parallel batch.
144
+ const dispatchPromises = pending.map(async (task) => {
145
+ // Mark in-progress
146
+ queue.update(task.id, { status: 'in_progress' });
147
+ const assignee = task.assignee;
148
+ if (!assignee) {
149
+ // No assignee — mark failed and continue
150
+ const msg = `Task "${task.title}" has no assignee.`;
151
+ queue.fail(task.id, msg);
152
+ config.onProgress?.({
153
+ type: 'error',
154
+ task: task.id,
155
+ data: msg,
156
+ });
157
+ return;
158
+ }
159
+ const agent = pool.get(assignee);
160
+ if (!agent) {
161
+ const msg = `Agent "${assignee}" not found in pool for task "${task.title}".`;
162
+ queue.fail(task.id, msg);
163
+ config.onProgress?.({
164
+ type: 'error',
165
+ task: task.id,
166
+ agent: assignee,
167
+ data: msg,
168
+ });
169
+ return;
170
+ }
171
+ config.onProgress?.({
172
+ type: 'task_start',
173
+ task: task.id,
174
+ agent: assignee,
175
+ data: task,
176
+ });
177
+ config.onProgress?.({
178
+ type: 'agent_start',
179
+ agent: assignee,
180
+ task: task.id,
181
+ data: task,
182
+ });
183
+ // Build the prompt: inject shared memory context + task description
184
+ const prompt = await buildTaskPrompt(task, team);
185
+ try {
186
+ const result = await pool.run(assignee, prompt);
187
+ ctx.agentResults.set(`${assignee}:${task.id}`, result);
188
+ if (result.success) {
189
+ // Persist result into shared memory so other agents can read it
190
+ const sharedMem = team.getSharedMemoryInstance();
191
+ if (sharedMem) {
192
+ await sharedMem.write(assignee, `task:${task.id}:result`, result.output);
193
+ }
194
+ queue.complete(task.id, result.output);
195
+ config.onProgress?.({
196
+ type: 'task_complete',
197
+ task: task.id,
198
+ agent: assignee,
199
+ data: result,
200
+ });
201
+ config.onProgress?.({
202
+ type: 'agent_complete',
203
+ agent: assignee,
204
+ task: task.id,
205
+ data: result,
206
+ });
207
+ }
208
+ else {
209
+ queue.fail(task.id, result.output);
210
+ config.onProgress?.({
211
+ type: 'error',
212
+ task: task.id,
213
+ agent: assignee,
214
+ data: result,
215
+ });
216
+ }
217
+ }
218
+ catch (err) {
219
+ const message = err instanceof Error ? err.message : String(err);
220
+ queue.fail(task.id, message);
221
+ config.onProgress?.({
222
+ type: 'error',
223
+ task: task.id,
224
+ agent: assignee,
225
+ data: err,
226
+ });
227
+ }
228
+ });
229
+ // Wait for the entire parallel batch before checking for newly-unblocked tasks.
230
+ await Promise.all(dispatchPromises);
231
+ }
232
+ }
233
+ /**
234
+ * Build the agent prompt for a specific task.
235
+ *
236
+ * Injects:
237
+ * - Task title and description
238
+ * - Dependency results from shared memory (if available)
239
+ * - Any messages addressed to this agent from the team bus
240
+ */
241
+ async function buildTaskPrompt(task, team) {
242
+ const lines = [
243
+ `# Task: ${task.title}`,
244
+ '',
245
+ task.description,
246
+ ];
247
+ // Inject shared memory summary so the agent sees its teammates' work
248
+ const sharedMem = team.getSharedMemoryInstance();
249
+ if (sharedMem) {
250
+ const summary = await sharedMem.getSummary();
251
+ if (summary) {
252
+ lines.push('', summary);
253
+ }
254
+ }
255
+ // Inject messages from other agents addressed to this assignee
256
+ if (task.assignee) {
257
+ const messages = team.getMessages(task.assignee);
258
+ if (messages.length > 0) {
259
+ lines.push('', '## Messages from team members');
260
+ for (const msg of messages) {
261
+ lines.push(`- **${msg.from}**: ${msg.content}`);
262
+ }
263
+ }
264
+ }
265
+ return lines.join('\n');
266
+ }
267
+ // ---------------------------------------------------------------------------
268
+ // OpenMultiAgent
269
+ // ---------------------------------------------------------------------------
270
+ /**
271
+ * Top-level orchestrator for the open-multi-agent framework.
272
+ *
273
+ * Manages teams, coordinates task execution, and surfaces progress events.
274
+ * Most users will interact with this class exclusively.
275
+ */
276
+ export class OpenMultiAgent {
277
+ config;
278
+ teams = new Map();
279
+ completedTaskCount = 0;
280
+ /**
281
+ * @param config - Optional top-level configuration.
282
+ *
283
+ * Sensible defaults:
284
+ * - `maxConcurrency`: 5
285
+ * - `defaultModel`: `'claude-opus-4-6'`
286
+ * - `defaultProvider`: `'anthropic'`
287
+ */
288
+ constructor(config = {}) {
289
+ this.config = {
290
+ maxConcurrency: config.maxConcurrency ?? DEFAULT_MAX_CONCURRENCY,
291
+ defaultModel: config.defaultModel ?? DEFAULT_MODEL,
292
+ defaultProvider: config.defaultProvider ?? 'anthropic',
293
+ onProgress: config.onProgress,
294
+ };
295
+ }
296
+ // -------------------------------------------------------------------------
297
+ // Team management
298
+ // -------------------------------------------------------------------------
299
+ /**
300
+ * Create and register a {@link Team} with the orchestrator.
301
+ *
302
+ * The team is stored internally so {@link getStatus} can report aggregate
303
+ * agent counts. Returns the new {@link Team} for further configuration.
304
+ *
305
+ * @param name - Unique team identifier. Throws if already registered.
306
+ * @param config - Team configuration (agents, shared memory, concurrency).
307
+ */
308
+ createTeam(name, config) {
309
+ if (this.teams.has(name)) {
310
+ throw new Error(`OpenMultiAgent: a team named "${name}" already exists. ` +
311
+ `Use a unique name or call shutdown() to clear all teams.`);
312
+ }
313
+ const team = new Team(config);
314
+ this.teams.set(name, team);
315
+ return team;
316
+ }
317
+ // -------------------------------------------------------------------------
318
+ // Single-agent convenience
319
+ // -------------------------------------------------------------------------
320
+ /**
321
+ * Run a single prompt with a one-off agent.
322
+ *
323
+ * Constructs a fresh agent from `config`, runs `prompt` in a single turn,
324
+ * and returns the result. The agent is not registered with any pool or team.
325
+ *
326
+ * Useful for simple one-shot queries that do not need team orchestration.
327
+ *
328
+ * @param config - Agent configuration.
329
+ * @param prompt - The user prompt to send.
330
+ */
331
+ async runAgent(config, prompt) {
332
+ const agent = buildAgent(config);
333
+ this.config.onProgress?.({
334
+ type: 'agent_start',
335
+ agent: config.name,
336
+ data: { prompt },
337
+ });
338
+ const result = await agent.run(prompt);
339
+ this.config.onProgress?.({
340
+ type: 'agent_complete',
341
+ agent: config.name,
342
+ data: result,
343
+ });
344
+ if (result.success) {
345
+ this.completedTaskCount++;
346
+ }
347
+ return result;
348
+ }
349
+ // -------------------------------------------------------------------------
350
+ // Auto-orchestrated team run (KILLER FEATURE)
351
+ // -------------------------------------------------------------------------
352
+ /**
353
+ * Run a team on a high-level goal with full automatic orchestration.
354
+ *
355
+ * This is the flagship method of the framework. It works as follows:
356
+ *
357
+ * 1. A temporary "coordinator" agent receives the goal and the team's agent
358
+ * roster, and is asked to decompose it into an ordered list of tasks with
359
+ * JSON output.
360
+ * 2. The tasks are loaded into a {@link TaskQueue}. Title-based dependency
361
+ * tokens in the coordinator's output are resolved to task IDs.
362
+ * 3. The {@link Scheduler} assigns unassigned tasks to team agents.
363
+ * 4. Tasks are executed in dependency order, with independent tasks running
364
+ * in parallel up to `maxConcurrency`.
365
+ * 5. Results are persisted to shared memory after each task so subsequent
366
+ * agents can read them.
367
+ * 6. The coordinator synthesises a final answer from all task outputs.
368
+ * 7. A {@link TeamRunResult} is returned.
369
+ *
370
+ * @param team - A team created via {@link createTeam} (or `new Team(...)`).
371
+ * @param goal - High-level natural-language goal for the team.
372
+ */
373
+ async runTeam(team, goal) {
374
+ const agentConfigs = team.getAgents();
375
+ // ------------------------------------------------------------------
376
+ // Step 1: Coordinator decomposes goal into tasks
377
+ // ------------------------------------------------------------------
378
+ const coordinatorConfig = {
379
+ name: 'coordinator',
380
+ model: this.config.defaultModel,
381
+ provider: this.config.defaultProvider,
382
+ systemPrompt: this.buildCoordinatorSystemPrompt(agentConfigs),
383
+ maxTurns: 3,
384
+ };
385
+ const decompositionPrompt = this.buildDecompositionPrompt(goal, agentConfigs);
386
+ const coordinatorAgent = buildAgent(coordinatorConfig);
387
+ this.config.onProgress?.({
388
+ type: 'agent_start',
389
+ agent: 'coordinator',
390
+ data: { phase: 'decomposition', goal },
391
+ });
392
+ const decompositionResult = await coordinatorAgent.run(decompositionPrompt);
393
+ const agentResults = new Map();
394
+ agentResults.set('coordinator:decompose', decompositionResult);
395
+ // ------------------------------------------------------------------
396
+ // Step 2: Parse tasks from coordinator output
397
+ // ------------------------------------------------------------------
398
+ const taskSpecs = parseTaskSpecs(decompositionResult.output);
399
+ const queue = new TaskQueue();
400
+ const scheduler = new Scheduler('dependency-first');
401
+ if (taskSpecs && taskSpecs.length > 0) {
402
+ // Map title-based dependsOn references to real task IDs so we can
403
+ // build the dependency graph before adding tasks to the queue.
404
+ this.loadSpecsIntoQueue(taskSpecs, agentConfigs, queue);
405
+ }
406
+ else {
407
+ // Coordinator failed to produce structured output — fall back to
408
+ // one task per agent using the goal as the description.
409
+ for (const agentConfig of agentConfigs) {
410
+ const task = createTask({
411
+ title: `${agentConfig.name}: ${goal.slice(0, 80)}`,
412
+ description: goal,
413
+ assignee: agentConfig.name,
414
+ });
415
+ queue.add(task);
416
+ }
417
+ }
418
+ // ------------------------------------------------------------------
419
+ // Step 3: Auto-assign any unassigned tasks
420
+ // ------------------------------------------------------------------
421
+ scheduler.autoAssign(queue, agentConfigs);
422
+ // ------------------------------------------------------------------
423
+ // Step 4: Build pool and execute
424
+ // ------------------------------------------------------------------
425
+ const pool = this.buildPool(agentConfigs);
426
+ const ctx = {
427
+ team,
428
+ pool,
429
+ scheduler,
430
+ agentResults,
431
+ config: this.config,
432
+ };
433
+ await executeQueue(queue, ctx);
434
+ // ------------------------------------------------------------------
435
+ // Step 5: Coordinator synthesises final result
436
+ // ------------------------------------------------------------------
437
+ const synthesisPrompt = await this.buildSynthesisPrompt(goal, queue.list(), team);
438
+ const synthesisResult = await coordinatorAgent.run(synthesisPrompt);
439
+ agentResults.set('coordinator', synthesisResult);
440
+ this.config.onProgress?.({
441
+ type: 'agent_complete',
442
+ agent: 'coordinator',
443
+ data: synthesisResult,
444
+ });
445
+ // Note: coordinator decompose and synthesis are internal meta-steps.
446
+ // Only actual user tasks (non-coordinator keys) are counted in
447
+ // buildTeamRunResult, so we do not increment completedTaskCount here.
448
+ return this.buildTeamRunResult(agentResults);
449
+ }
450
+ // -------------------------------------------------------------------------
451
+ // Explicit-task team run
452
+ // -------------------------------------------------------------------------
453
+ /**
454
+ * Run a team with an explicitly provided task list.
455
+ *
456
+ * Simpler than {@link runTeam}: no coordinator agent is involved. Tasks are
457
+ * loaded directly into the queue, unassigned tasks are auto-assigned via the
458
+ * {@link Scheduler}, and execution proceeds in dependency order.
459
+ *
460
+ * @param team - A team created via {@link createTeam}.
461
+ * @param tasks - Array of task descriptors.
462
+ */
463
+ async runTasks(team, tasks) {
464
+ const agentConfigs = team.getAgents();
465
+ const queue = new TaskQueue();
466
+ const scheduler = new Scheduler('dependency-first');
467
+ this.loadSpecsIntoQueue(tasks.map((t) => ({
468
+ title: t.title,
469
+ description: t.description,
470
+ assignee: t.assignee,
471
+ dependsOn: t.dependsOn,
472
+ })), agentConfigs, queue);
473
+ scheduler.autoAssign(queue, agentConfigs);
474
+ const pool = this.buildPool(agentConfigs);
475
+ const agentResults = new Map();
476
+ const ctx = {
477
+ team,
478
+ pool,
479
+ scheduler,
480
+ agentResults,
481
+ config: this.config,
482
+ };
483
+ await executeQueue(queue, ctx);
484
+ return this.buildTeamRunResult(agentResults);
485
+ }
486
+ // -------------------------------------------------------------------------
487
+ // Observability
488
+ // -------------------------------------------------------------------------
489
+ /**
490
+ * Returns a lightweight status snapshot.
491
+ *
492
+ * - `teams` — Number of teams registered with this orchestrator.
493
+ * - `activeAgents` — Total agents currently in `running` state.
494
+ * - `completedTasks` — Cumulative count of successfully completed tasks
495
+ * (coordinator meta-steps excluded).
496
+ */
497
+ getStatus() {
498
+ return {
499
+ teams: this.teams.size,
500
+ activeAgents: 0, // Pools are ephemeral per-run; no cross-run state to inspect.
501
+ completedTasks: this.completedTaskCount,
502
+ };
503
+ }
504
+ // -------------------------------------------------------------------------
505
+ // Lifecycle
506
+ // -------------------------------------------------------------------------
507
+ /**
508
+ * Deregister all teams and reset internal counters.
509
+ *
510
+ * Does not cancel in-flight runs. Call this when you want to reuse the
511
+ * orchestrator instance for a fresh set of teams.
512
+ *
513
+ * Async for forward compatibility — shutdown may need to perform async
514
+ * cleanup (e.g. graceful agent drain) in future versions.
515
+ */
516
+ async shutdown() {
517
+ this.teams.clear();
518
+ this.completedTaskCount = 0;
519
+ }
520
+ // -------------------------------------------------------------------------
521
+ // Private helpers
522
+ // -------------------------------------------------------------------------
523
+ /** Build the system prompt given to the coordinator agent. */
524
+ buildCoordinatorSystemPrompt(agents) {
525
+ const roster = agents
526
+ .map((a) => `- **${a.name}** (${a.model}): ${a.systemPrompt?.slice(0, 120) ?? 'general purpose agent'}`)
527
+ .join('\n');
528
+ return [
529
+ 'You are a task coordinator responsible for decomposing high-level goals',
530
+ 'into concrete, actionable tasks and assigning them to the right team members.',
531
+ '',
532
+ '## Team Roster',
533
+ roster,
534
+ '',
535
+ '## Output Format',
536
+ 'When asked to decompose a goal, respond ONLY with a JSON array of task objects.',
537
+ 'Each task must have:',
538
+ ' - "title": Short descriptive title (string)',
539
+ ' - "description": Full task description with context and expected output (string)',
540
+ ' - "assignee": One of the agent names listed in the roster (string)',
541
+ ' - "dependsOn": Array of titles of tasks this task depends on (string[], may be empty)',
542
+ '',
543
+ 'Wrap the JSON in a ```json code fence.',
544
+ 'Do not include any text outside the code fence.',
545
+ '',
546
+ '## When synthesising results',
547
+ 'You will be given completed task outputs and asked to synthesise a final answer.',
548
+ 'Write a clear, comprehensive response that addresses the original goal.',
549
+ ].join('\n');
550
+ }
551
+ /** Build the decomposition prompt for the coordinator. */
552
+ buildDecompositionPrompt(goal, agents) {
553
+ const names = agents.map((a) => a.name).join(', ');
554
+ return [
555
+ `Decompose the following goal into tasks for your team (${names}).`,
556
+ '',
557
+ `## Goal`,
558
+ goal,
559
+ '',
560
+ 'Return ONLY the JSON task array in a ```json code fence.',
561
+ ].join('\n');
562
+ }
563
+ /** Build the synthesis prompt shown to the coordinator after all tasks complete. */
564
+ async buildSynthesisPrompt(goal, tasks, team) {
565
+ const completedTasks = tasks.filter((t) => t.status === 'completed');
566
+ const failedTasks = tasks.filter((t) => t.status === 'failed');
567
+ const resultSections = completedTasks.map((t) => {
568
+ const assignee = t.assignee ?? 'unknown';
569
+ return `### ${t.title} (completed by ${assignee})\n${t.result ?? '(no output)'}`;
570
+ });
571
+ const failureSections = failedTasks.map((t) => `### ${t.title} (FAILED)\nError: ${t.result ?? 'unknown error'}`);
572
+ // Also include shared memory summary for additional context
573
+ let memorySummary = '';
574
+ const sharedMem = team.getSharedMemoryInstance();
575
+ if (sharedMem) {
576
+ memorySummary = await sharedMem.getSummary();
577
+ }
578
+ return [
579
+ `## Original Goal`,
580
+ goal,
581
+ '',
582
+ `## Task Results`,
583
+ ...resultSections,
584
+ ...(failureSections.length > 0 ? ['', '## Failed Tasks', ...failureSections] : []),
585
+ ...(memorySummary ? ['', memorySummary] : []),
586
+ '',
587
+ '## Your Task',
588
+ 'Synthesise the above results into a comprehensive final answer that addresses the original goal.',
589
+ 'If some tasks failed, note any gaps in the result.',
590
+ ].join('\n');
591
+ }
592
+ /**
593
+ * Load a list of task specs into a queue.
594
+ *
595
+ * Handles title-based `dependsOn` references by building a title→id map first,
596
+ * then resolving them to real IDs before adding tasks to the queue.
597
+ */
598
+ loadSpecsIntoQueue(specs, agentConfigs, queue) {
599
+ const agentNames = new Set(agentConfigs.map((a) => a.name));
600
+ // First pass: create tasks (without dependencies) to get stable IDs.
601
+ const titleToId = new Map();
602
+ const createdTasks = [];
603
+ for (const spec of specs) {
604
+ const task = createTask({
605
+ title: spec.title,
606
+ description: spec.description,
607
+ assignee: spec.assignee && agentNames.has(spec.assignee)
608
+ ? spec.assignee
609
+ : undefined,
610
+ });
611
+ titleToId.set(spec.title.toLowerCase().trim(), task.id);
612
+ createdTasks.push(task);
613
+ }
614
+ // Second pass: resolve title-based dependsOn to IDs.
615
+ for (let i = 0; i < createdTasks.length; i++) {
616
+ const spec = specs[i];
617
+ const task = createdTasks[i];
618
+ if (!spec.dependsOn || spec.dependsOn.length === 0) {
619
+ queue.add(task);
620
+ continue;
621
+ }
622
+ const resolvedDeps = [];
623
+ for (const depRef of spec.dependsOn) {
624
+ // Accept both raw IDs and title strings
625
+ const byId = createdTasks.find((t) => t.id === depRef);
626
+ const byTitle = titleToId.get(depRef.toLowerCase().trim());
627
+ const resolvedId = byId?.id ?? byTitle;
628
+ if (resolvedId) {
629
+ resolvedDeps.push(resolvedId);
630
+ }
631
+ }
632
+ const taskWithDeps = {
633
+ ...task,
634
+ dependsOn: resolvedDeps.length > 0 ? resolvedDeps : undefined,
635
+ };
636
+ queue.add(taskWithDeps);
637
+ }
638
+ }
639
+ /** Build an {@link AgentPool} from a list of agent configurations. */
640
+ buildPool(agentConfigs) {
641
+ const pool = new AgentPool(this.config.maxConcurrency);
642
+ for (const config of agentConfigs) {
643
+ const effective = {
644
+ ...config,
645
+ model: config.model,
646
+ provider: config.provider ?? this.config.defaultProvider,
647
+ };
648
+ pool.add(buildAgent(effective));
649
+ }
650
+ return pool;
651
+ }
652
+ /**
653
+ * Aggregate the per-run `agentResults` map into a {@link TeamRunResult}.
654
+ *
655
+ * Merges results keyed as `agentName:taskId` back into a per-agent map
656
+ * by agent name for the public result surface.
657
+ *
658
+ * Only non-coordinator entries are counted toward `completedTaskCount` to
659
+ * avoid double-counting the coordinator's internal decompose/synthesis steps.
660
+ */
661
+ buildTeamRunResult(agentResults) {
662
+ let totalUsage = ZERO_USAGE;
663
+ let overallSuccess = true;
664
+ const collapsed = new Map();
665
+ for (const [key, result] of agentResults) {
666
+ // Strip the `:taskId` suffix to get the agent name
667
+ const agentName = key.includes(':') ? key.split(':')[0] : key;
668
+ totalUsage = addUsage(totalUsage, result.tokenUsage);
669
+ if (!result.success)
670
+ overallSuccess = false;
671
+ const existing = collapsed.get(agentName);
672
+ if (!existing) {
673
+ collapsed.set(agentName, result);
674
+ }
675
+ else {
676
+ // Merge multiple results for the same agent (multi-task case)
677
+ collapsed.set(agentName, {
678
+ success: existing.success && result.success,
679
+ output: [existing.output, result.output].filter(Boolean).join('\n\n---\n\n'),
680
+ messages: [...existing.messages, ...result.messages],
681
+ tokenUsage: addUsage(existing.tokenUsage, result.tokenUsage),
682
+ toolCalls: [...existing.toolCalls, ...result.toolCalls],
683
+ });
684
+ }
685
+ // Only count actual user tasks — skip coordinator meta-entries
686
+ // (keys that start with 'coordinator') to avoid double-counting.
687
+ if (result.success && !key.startsWith('coordinator')) {
688
+ this.completedTaskCount++;
689
+ }
690
+ }
691
+ return {
692
+ success: overallSuccess,
693
+ agentResults: collapsed,
694
+ totalTokenUsage: totalUsage,
695
+ };
696
+ }
697
+ }
698
+ //# sourceMappingURL=orchestrator.js.map