1 agents

unified-orchestrator

unified-orchestrator

Overview

The Unified Orchestrator is an L1 Supreme Authority agent operating in the medium-predator organism classification of the Prismatic Platform. This agent serves as the supreme coordination hub for intelligent task routing and multi-agent orchestration, decomposing complex objectives into coordinated task sequences and dispatching them to the most capable specialist agents. When users invoke the /orchestrate command, it is the Unified Orchestrator that analyzes the request, formulates an execution plan, allocates agent resources, and monitors the mission to completion.

The "medium-predator" classification reflects the Unified Orchestrator's position in the platform's ecological hierarchy -- it actively coordinates and directs lower-tier agents (herbivores and small predators) while operating under the strategic direction of the Strategic Command and Supreme Commander agents. This intermediate position gives the Unified Orchestrator both the tactical flexibility to adapt to changing conditions and the strategic awareness to align task execution with platform-wide objectives.

This agent operates under the NO MERCY doctrine, executing orchestration decisions with absolute confidence after Trinity Gate verification and demanding complete execution from all subordinate agents.

Orchestration Architecture

The Unified Orchestrator implements a multi-phase orchestration pipeline that transforms high-level objectives into coordinated multi-agent operations.

User Request -> Task Analysis -> Decomposition -> Agent Selection -> Execution -> Synthesis -> Delivery
PhaseDurationActivityOutput
Task AnalysisSecondsParse request, identify domain, assess complexityTask specification
DecompositionSecondsBreak into subtasks with dependency graphTask DAG
Agent SelectionSecondsMatch subtasks to capable agentsAgent assignment map
ExecutionMinutes-HoursDispatch tasks, monitor progress, handle failuresTask results
SynthesisSeconds-MinutesMerge results, verify completeness, format outputUnified result
DeliverySecondsPresent results to user with provenanceFinal deliverable

Technical Implementation

defmodule PrismaticAgents.UnifiedOrchestrator do
  @moduledoc """
  L1 Unified Orchestrator agent.
  Supreme coordination for intelligent task routing and multi-agent orchestration.
  """

  use GenServer
  require Logger

  @max_parallel_agents 12
  @mission_timeout_ms :timer.minutes(30)

  defstruct [
    :active_missions,
    :agent_pool,
    :task_queue,
    :completion_rate,
    :last_orchestration_at,
    status: :ready
  ]

  @spec start_link(keyword()) :: GenServer.on_start()
  def start_link(opts \\ []) do
    GenServer.start_link(__MODULE__, opts, name: __MODULE__)
  end

  @impl true
  def init(_opts) do
    {:ok, %__MODULE__{active_missions: [], agent_pool: discover_available_agents()}}
  end

  @spec orchestrate(String.t(), keyword()) :: {:ok, map()} | {:error, term()}
  def orchestrate(objective, opts \\ []) do
    GenServer.call(__MODULE__, {:orchestrate, objective, opts}, @mission_timeout_ms)
  end

  @impl true
  def handle_call({:orchestrate, objective, opts}, _from, state) do
    max_agents = Keyword.get(opts, :max_agents, @max_parallel_agents)

    with {:ok, spec} <- analyze_task(objective),
         {:ok, dag} <- decompose_task(spec),
         {:ok, assignments} <- select_agents(dag, state.agent_pool, max_agents),
         {:ok, results} <- execute_mission(assignments, dag),
         {:ok, synthesis} <- synthesize_results(results) do

      :telemetry.execute(
        [:prismatic, :agents, :orchestrator, :mission_complete],
        %{
          subtask_count: length(Map.keys(dag)),
          agents_used: length(Map.keys(assignments)),
          duration_ms: synthesis.duration_ms
        },
        %{objective: objective, success: true}
      )

      {:reply, {:ok, synthesis}, update_state(state, synthesis)}
    else
      {:error, reason} ->
        :telemetry.execute(
          [:prismatic, :agents, :orchestrator, :mission_failed],
          %{},
          %{objective: objective, reason: reason}
        )
        {:reply, {:error, reason}, state}
    end
  end

  defp execute_mission(assignments, dag) do
    execution_order = topological_sort(dag)

    results =
      execution_order
      |> Enum.reduce(%{}, fn task_batch, accumulated_results ->
        batch_results =
          task_batch
          |> Task.async_stream(
            fn task ->
              agent = Map.fetch!(assignments, task.id)
              context = extract_dependencies(task, accumulated_results)
              execute_subtask(agent, task, context)
            end,
            max_concurrency: @max_parallel_agents,
            timeout: :timer.minutes(10)
          )
          |> Enum.map(fn {:ok, result} -> result end)
          |> Map.new(fn r -> {r.task_id, r} end)

        Map.merge(accumulated_results, batch_results)
      end)

    {:ok, results}
  end
end

Agent Selection Algorithm

The Unified Orchestrator selects agents for subtasks based on a multi-factor scoring algorithm.

FactorWeightMeasurement
Domain Match40%Agent domain matches task domain
Capability Score25%Agent's demonstrated capability for task type
Current Load15%Agent's current task queue depth
Historical Performance15%Past success rate for similar tasks
Authority Level5%Agent has sufficient authority for task

Task Decomposition Strategies

StrategyUse CaseExample
SequentialTasks with strict dependenciesBuild then deploy
ParallelIndependent tasksAnalyze multiple data sources
Fan-Out/Fan-InOne task generates many, results mergedMulti-agent investigation
PipelineEach task feeds the nextData collection, processing, analysis
ConditionalBranching based on intermediate resultsEscalate if threshold exceeded

Mission Monitoring

The Unified Orchestrator provides real-time mission monitoring through structured telemetry events. These events feed into the platform's LiveView monitoring dashboards, providing real-time visibility into mission progress for both automated systems and human operators.

EventDataFrequency
Mission StartedObjective, agent count, estimated durationPer mission
Subtask DispatchedTask ID, assigned agent, expected durationPer subtask
Subtask CompletedTask ID, result, actual durationPer subtask
Mission ProgressCompletion percentage, remaining tasksEvery 30 seconds
Mission CompleteFull results, total duration, agent utilizationPer mission
Agent StalledAgent ID, task ID, elapsed timeWhen timeout approaches
Mission FailureObjective, failure point, error detailsPer failure

Error Handling and Recovery

The Unified Orchestrator implements sophisticated error handling that distinguishes between transient failures (which can be retried), permanent failures (which require alternative approaches), and cascading failures (which require mission restructuring).

defmodule PrismaticAgents.UnifiedOrchestrator.ErrorHandler do
  @moduledoc """
  Error handling and recovery strategies for orchestrated missions.
  Implements retry, fallback, and mission restructuring patterns.
  """

  @max_retries 3
  @retry_backoff_ms 1_000

  @spec handle_subtask_failure(map(), map(), map()) :: {:retry, map()} | {:fallback, map()} | {:abort, map()}
  def handle_subtask_failure(task, error, mission_context) do
    cond do
      transient_error?(error) and task.retry_count < @max_retries ->
        delay = @retry_backoff_ms * :math.pow(2, task.retry_count) |> round()
        {:retry, %{task | retry_count: task.retry_count + 1, retry_after_ms: delay}}

      fallback_agent_available?(task, mission_context) ->
        fallback = select_fallback_agent(task, mission_context)
        {:fallback, %{task | assigned_agent: fallback, retry_count: 0}}

      critical_path_task?(task, mission_context) ->
        {:abort, %{reason: :critical_path_failure, task: task, error: error}}

      true ->
        {:skip, %{task: task, reason: :non_critical_failure, error: error}}
    end
  end

  defp transient_error?(%{type: :timeout}), do: true
  defp transient_error?(%{type: :resource_unavailable}), do: true
  defp transient_error?(%{type: :rate_limited}), do: true
  defp transient_error?(_), do: false
end
Error CategoryDetectionRecovery StrategySLA
Transient FailureTimeout, resource unavailableExponential backoff retry (max 3)< 30 seconds
Agent FailureAgent crash or unresponsiveFallback to alternative agent< 2 minutes
Critical Path FailureUnrecoverable task on critical pathMission abort with partial resultsImmediate
Non-Critical FailureTask failure on optional pathSkip task, continue missionNo delay
Cascading FailureMultiple simultaneous failuresMission restructure or abort< 5 minutes

Operational Metrics

MetricTargetDescription
Mission success rate> 95%Completed missions vs total
Average orchestration latency< 5 secondsTask analysis to first dispatch
Agent utilization60-80%Optimal agent workload balance
Max parallel agents12Simultaneous agent coordination
Task decomposition accuracy> 90%Subtasks correctly identified

Mycelial Network Integration

The Unified Orchestrator communicates with agents through the platform's mycelial network, enabling rapid signal propagation and distributed coordination.

Network OperationMechanismLatency
Task DispatchTargeted message to specific agent< 5 ms
Progress QueryPubSub subscription to agent telemetry< 10 ms
Result CollectionGenServer call with timeout< 100 ms
Emergency RecallBroadcast cancellation signal< 5 ms

Integration Points

AIAD Specification Compliance

AIAD ComponentStatus
Agent specification fileCompliant
Behavioral rules20 rules defined
Telemetry integrationFull coverage
NM/ND doctrine enforcementActive
SEADF integrationRegistered

Mission Types and Templates

The Unified Orchestrator maintains a library of mission templates for common orchestration patterns. These templates accelerate mission planning by providing pre-configured task decomposition strategies, agent selection criteria, and success metrics for frequently executed operation types.

Mission TemplateTypical AgentsDurationUse Case
Quality Sweep6-8 quality agents30-60 minPlatform-wide quality assessment
Intelligence Collection4-6 intelligence agents1-4 hoursMulti-source OSINT operation
Security Audit5-7 security agents2-6 hoursComprehensive security review
Migration Step3-5 architecture agents1-2 hoursStrangler pattern advancement
Content Enhancement2-4 content agents1-3 hoursDocumentation or promo content
Incident Response8-12 mixed agentsVariableEmergency response coordination

Authority Level

L1 - Supreme Authority - Platform-wide strategic and tactical control with authority to coordinate up to 12 parallel agents and direct any L2-L4 agent.


Connect & Contribute

Created by Tomáš Korcak (korczis) | Open Source under GHL