Skip to main content
The orchestrator factory creates and wires together all components of the Longshot system, including the planner, worker pool, merge queue, reconciler, and monitor.

createOrchestrator()

Creates a fully wired orchestrator instance ready to execute a build request.
async function createOrchestrator(
  request: string,
  callbacks?: OrchestratorCallbacks
): Promise<Orchestrator>
request
string
required
The natural-language build request to execute
callbacks
OrchestratorCallbacks
Optional callbacks for lifecycle events and monitoring

OrchestratorCallbacks

Callbacks for all major orchestrator events:
interface OrchestratorCallbacks {
  onTaskCreated?: (task: Task) => void;
  onTaskCompleted?: (task: Task, handoff: Handoff) => void;
  onIterationComplete?: (iteration: number, tasks: Task[], handoffs: Handoff[]) => void;
  onError?: (error: Error) => void;
  onSweepComplete?: (result: SweepResult) => void;
  onReconcilerError?: (error: Error) => void;
  onWorkerTimeout?: (workerId: string, taskId: string) => void;
  onEmptyDiff?: (workerId: string, taskId: string) => void;
  onMetricsUpdate?: (snapshot: MetricsSnapshot) => void;
  onTaskStatusChange?: (task: Task, oldStatus: string, newStatus: string) => void;
  onFinalizationStart?: () => void;
  onFinalizationAttempt?: (attempt: number, sweepResult: SweepResult) => void;
  onFinalizationComplete?: (attempts: number, passed: boolean) => void;
}

Orchestrator Interface

The created orchestrator exposes:
interface Orchestrator {
  planner: Planner;
  subplanner: Subplanner;
  reconciler: Reconciler;
  workerPool: WorkerPool;
  mergeQueue: MergeQueue;
  taskQueue: TaskQueue;
  monitor: Monitor;
  
  start(): Promise<void>;
  stop(): Promise<void>;
  waitForCompletion(): Promise<void>;
}

Methods

start()

Starts the orchestrator execution loop.
await orchestrator.start();

stop()

Gracefully stops the orchestrator and all components.
await orchestrator.stop();

waitForCompletion()

Waits until all tasks are complete and the merge queue is drained.
await orchestrator.waitForCompletion();

Component Wiring

The factory automatically wires:
  1. Configuration — Loads from environment and validates
  2. Tracer — Sets up distributed tracing
  3. Git mutex — Serializes git operations
  4. Task queue — Priority-based task queue with lifecycle tracking
  5. Worker pool — Ephemeral sandbox manager
  6. Merge queue — Serial merge pipeline with conflict handling
  7. Monitor — Metrics collection and health checks
  8. Reconciler — Periodic build/test sweeps
  9. Subplanner — Recursive task decomposition
  10. Root planner — Top-level planning loop

Finalization Phase

After all tasks complete, the orchestrator runs a finalization phase:
  1. Drain merge queue — Wait for all pending merges
  2. Retry unmerged branches — Attempt to merge any blocked branches
  3. Final sweep — Run reconciler one last time
  4. Report — Emit finalization metrics
The finalization phase runs up to FINALIZATION_MAX_ATTEMPTS times (default: 3) until the build passes or attempts are exhausted.

Usage Example

import { createOrchestrator } from "@longshot/orchestrator";

const orchestrator = await createOrchestrator(
  "Build a REST API according to SPEC.md",
  {
    onTaskCreated: (task) => {
      console.log(`Created task: ${task.description}`);
    },
    onTaskCompleted: (task, handoff) => {
      console.log(`Completed: ${task.description}`);
      console.log(`Files changed: ${handoff.filesChanged.length}`);
    },
    onMetricsUpdate: (metrics) => {
      console.log(`Active: ${metrics.activeWorkers}, Pending: ${metrics.pendingTasks}`);
    },
    onFinalizationComplete: (attempts, passed) => {
      console.log(`Finalization ${passed ? 'passed' : 'failed'} after ${attempts} attempts`);
    },
  }
);

await orchestrator.start();
await orchestrator.waitForCompletion();
await orchestrator.stop();

console.log("Build complete!");

Environment Configuration

The orchestrator reads configuration from environment variables:
  • LLM_BASE_URL, LLM_API_KEY — LLM provider
  • GIT_REPO_URL, GIT_TOKEN — Target repository
  • MAX_WORKERS — Concurrency limit
  • WORKER_TIMEOUT — Worker timeout in seconds
  • MERGE_STRATEGYfast-forward, rebase, or merge-commit
  • FINALIZATION_ENABLED — Enable/disable finalization phase
  • FINALIZATION_MAX_ATTEMPTS — Max finalization retries
See Configuration for all options.

Build docs developers (and LLMs) love