moving
Some checks failed
Installer Smoke / installer-smoke (push) Has been cancelled

This commit is contained in:
Oleg Maslov
2026-09-02 10:10:29 +02:00
commit 0c3e2ead3b
3841 changed files with 970576 additions and 0 deletions

View File

@@ -0,0 +1,150 @@
import type { AgentMemberConfig, AgentResult, ExecutionDeps } from './parallel.js';
/**
* Coordinator execution strategy: a lead agent plans and delegates,
* worker agents execute subtasks, then the lead synthesizes results.
* Best for complex tasks requiring decomposition and integration.
*/
export async function executeCoordinator(
members: AgentMemberConfig[],
taskInput: Record<string, unknown>,
deps?: ExecutionDeps,
): Promise<Record<string, unknown>> {
const lead = members.find(m => m.member.roleInGroup === 'lead');
const workers = members.filter(m => m.member.roleInGroup === 'worker');
if (!lead) {
throw new Error('Coordinator strategy requires a lead agent');
}
const task = (taskInput.task as string) ?? JSON.stringify(taskInput);
// ── Stub mode (backward compat) ──────────────────────────────────
if (!deps) {
const plan = {
agentId: lead.agent.id,
agentName: lead.agent.name,
phase: 'planning',
output: `[Stub] ${lead.agent.name} delegated to ${workers.length} workers`,
subtasks: workers.map(w => ({
assignedTo: w.agent.name,
description: `[Stub] Subtask for ${w.agent.name}`,
})),
};
const workerResults = await Promise.all(
workers.map(async ({ agent }) => ({
agentId: agent.id,
agentName: agent.name,
phase: 'execution',
model: agent.model,
output: `[Stub] ${agent.name} completed delegated work`,
})),
);
const synthesis = {
agentId: lead.agent.id,
agentName: lead.agent.name,
phase: 'synthesis',
output: `[Stub] ${lead.agent.name} synthesized ${workerResults.length} worker outputs`,
};
return {
strategy: 'coordinator',
leadAgent: lead.agent.name,
workerCount: workers.length,
plan,
workerResults,
synthesis,
finalOutput: synthesis.output,
};
}
// ── Real execution: 3-phase pattern ──────────────────────────────
// Phase 1: Lead agent creates plan
const leadPrompt = lead.agent.systemPrompt ?? `You are ${lead.agent.name}, a lead coordinator.`;
const planResult = await deps.runAgent({
model: lead.agent.model,
systemPrompt: `${leadPrompt}\n\nYou are the lead coordinator. Analyze the task and create a clear plan for ${workers.length} worker agent(s). Output a structured plan with one subtask per worker.`,
tools: deps.resolveTools(lead.agent.tools),
messages: [{ role: 'user', content: task }],
});
const plan = {
agentId: lead.agent.id,
agentName: lead.agent.name,
phase: 'planning',
output: planResult.content,
usage: planResult.usage,
};
// Phase 2: Workers execute in parallel, receiving the plan as context
const workerResults: AgentResult[] = await Promise.all(
workers.map(async ({ agent, member }) => {
try {
const workerPrompt = agent.systemPrompt ?? `You are ${agent.name}. Execute your assigned subtask.`;
const result = await deps.runAgent({
model: agent.model,
systemPrompt: `${workerPrompt}\n\n## Coordinator's Plan\n${planResult.content}`,
tools: deps.resolveTools(agent.tools),
messages: [{ role: 'user', content: task }],
});
return {
agentId: agent.id,
agentName: agent.name,
role: member.roleInGroup,
model: agent.model,
output: result.content,
toolsUsed: result.toolsUsed,
usage: result.usage,
};
} catch (err: unknown) {
return {
agentId: agent.id,
agentName: agent.name,
role: member.roleInGroup,
model: agent.model,
output: '',
error: err instanceof Error ? err.message : String(err),
};
}
}),
);
// Phase 3: Lead synthesizes worker results (include failure notices)
const successOutputs = workerResults
.filter(r => !r.error)
.map(r => `## ${r.agentName}\n${r.output}`);
const failureNotices = workerResults
.filter(r => r.error)
.map(r => `## ${r.agentName} (FAILED)\nError: ${r.error}`);
const workerOutputs = [...successOutputs, ...failureNotices].join('\n\n');
const synthesisResult = await deps.runAgent({
model: lead.agent.model,
systemPrompt: `${leadPrompt}\n\nSynthesize the following worker outputs into a comprehensive final result.`,
tools: deps.resolveTools(lead.agent.tools),
messages: [{ role: 'user', content: workerOutputs || 'No worker outputs available.' }],
});
const synthesis = {
agentId: lead.agent.id,
agentName: lead.agent.name,
phase: 'synthesis',
output: synthesisResult.content,
usage: synthesisResult.usage,
};
return {
strategy: 'coordinator',
leadAgent: lead.agent.name,
workerCount: workers.length,
plan,
workerResults,
synthesis,
finalOutput: synthesis.output,
errors: workerResults.filter(r => r.error).map(r => ({ agent: r.agentName, error: r.error })),
};
}

View File

@@ -0,0 +1,99 @@
import type { ToolDefinition } from '@waggle/agent';
export interface AgentMemberConfig {
member: { roleInGroup: string; executionOrder: number };
agent: { id: string; name: string; model: string; systemPrompt: string | null; tools: string[] };
}
/** Dependencies injected for real execution (omit for stub mode) */
export interface ExecutionDeps {
runAgent: (config: {
model: string;
systemPrompt: string;
tools: ToolDefinition[];
messages: Array<{ role: string; content: string }>;
maxTurns?: number;
}) => Promise<{ content: string; toolsUsed: string[]; usage: { inputTokens: number; outputTokens: number } }>;
/** Resolve tool names to ToolDefinition[] from available tools */
resolveTools: (toolNames: string[]) => ToolDefinition[];
}
export interface AgentResult {
agentId: string;
agentName: string;
role: string;
model: string;
output: string;
toolsUsed?: string[];
usage?: { inputTokens: number; outputTokens: number };
error?: string;
}
/**
* Parallel execution strategy: all agents run concurrently, results are merged.
* Best for independent subtasks that don't depend on each other.
*/
export async function executeParallel(
members: AgentMemberConfig[],
taskInput: Record<string, unknown>,
deps?: ExecutionDeps,
): Promise<Record<string, unknown>> {
const task = (taskInput.task as string) ?? JSON.stringify(taskInput);
const results: AgentResult[] = await Promise.all(
members.map(async ({ agent, member }) => {
if (!deps) {
// Stub mode (backward compat for existing tests without deps)
return {
agentId: agent.id,
agentName: agent.name,
role: member.roleInGroup,
model: agent.model,
output: `[Stub] ${agent.name} processed task with model ${agent.model}`,
};
}
try {
const tools = deps.resolveTools(agent.tools);
const systemPrompt = agent.systemPrompt ?? `You are ${agent.name}. Complete the assigned task thoroughly.`;
const result = await deps.runAgent({
model: agent.model,
systemPrompt,
tools,
messages: [{ role: 'user', content: task }],
});
return {
agentId: agent.id,
agentName: agent.name,
role: member.roleInGroup,
model: agent.model,
output: result.content,
toolsUsed: result.toolsUsed,
usage: result.usage,
};
} catch (err: unknown) {
return {
agentId: agent.id,
agentName: agent.name,
role: member.roleInGroup,
model: agent.model,
output: '',
error: err instanceof Error ? err.message : String(err),
};
}
}),
);
return {
strategy: 'parallel',
agentCount: results.length,
results,
mergedOutput: results
.filter(r => !r.error)
.map(r => r.output)
.join('\n\n---\n\n'),
errors: results.filter(r => r.error).map(r => ({ agent: r.agentName, error: r.error })),
};
}

View File

@@ -0,0 +1,85 @@
import type { AgentMemberConfig, AgentResult, ExecutionDeps } from './parallel.js';
/** Stub-mode result carries an extra `inputFrom` marker for backward-compat tests. */
type StubAgentResult = AgentResult & { inputFrom: string };
/**
* Sequential execution strategy: agents run one after another,
* each receiving the previous agent's output as context.
* Best for pipeline-style workflows (research -> draft -> review).
*/
export async function executeSequential(
members: AgentMemberConfig[],
taskInput: Record<string, unknown>,
deps?: ExecutionDeps,
): Promise<Record<string, unknown>> {
const task = (taskInput.task as string) ?? JSON.stringify(taskInput);
const results: AgentResult[] = [];
let previousOutput: string | null = null;
for (const { agent, member } of members) {
if (!deps) {
// Stub mode (backward compat)
const output: StubAgentResult = {
agentId: agent.id,
agentName: agent.name,
role: member.roleInGroup,
model: agent.model,
output: `[Stub] ${agent.name} processed with input from previous step`,
// Preserve inputFrom for backward compat with existing tests
inputFrom: previousOutput === null ? 'taskInput' : (results[results.length - 1]?.agentName ?? 'taskInput'),
};
results.push(output);
previousOutput = output.output;
continue;
}
try {
const tools = deps.resolveTools(agent.tools);
const basePrompt = agent.systemPrompt ?? `You are ${agent.name}. Complete the assigned task.`;
// Chain: inject previous agent's output as context
const systemPrompt = previousOutput
? `${basePrompt}\n\n## Previous Agent's Output\n${previousOutput}`
: basePrompt;
const result = await deps.runAgent({
model: agent.model,
systemPrompt,
tools,
messages: [{ role: 'user', content: task }],
});
const agentResult: AgentResult = {
agentId: agent.id,
agentName: agent.name,
role: member.roleInGroup,
model: agent.model,
output: result.content,
toolsUsed: result.toolsUsed,
usage: result.usage,
};
results.push(agentResult);
previousOutput = result.content;
} catch (err: unknown) {
// Error in chain stops execution — subsequent agents depend on this output
results.push({
agentId: agent.id,
agentName: agent.name,
role: member.roleInGroup,
model: agent.model,
output: '',
error: err instanceof Error ? err.message : String(err),
});
break; // Stop chain on failure
}
}
return {
strategy: 'sequential',
agentCount: results.length,
results,
finalOutput: results.filter(r => !r.error).at(-1)?.output ?? null,
chainBroken: results.some(r => r.error),
};
}