Download the PHP package builtbyberry/laravel-swarm without Composer
On this page you can find all versions of the php package builtbyberry/laravel-swarm. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download builtbyberry/laravel-swarm
More information about builtbyberry/laravel-swarm
Files in builtbyberry/laravel-swarm
Package laravel-swarm
Short Description Multi-agent swarm orchestration for Laravel, built on Laravel AI.
License MIT
Homepage https://swarm.builtbyberry.com
Informations about the package laravel-swarm
Laravel Swarm
π Full documentation: swarm.builtbyberry.com
Laravel Swarm brings reusable multi-agent orchestration to Laravel on top of the official Laravel AI package.
Define a swarm once, return the Laravel AI agents that participate in it, and run the workflow synchronously, on a queue, as a stream, or as a checkpointed durable run.
- Documentation: swarm.builtbyberry.com
- Packagist:
builtbyberry/laravel-swarm - Namespace:
BuiltByBerry\LaravelSwarm - Repository: https://github.com/builtbyberry/laravel-swarm
- In-repo docs: docs/README.md
- Examples: examples/README.md
- Upgrading: UPGRADING.md
- Contributing: CONTRIBUTING.md
Quick Start
For background execution, streaming, and durable workflows, see Choosing An Execution Mode.
Requirements
- PHP ^8.5
- Laravel 13 (
illuminate/*^13.0) laravel/ai^0.8
The PHP ^8.5 floor is a deliberate requirement β the package builds on 8.5 language features. As of v0.13.0 the laravel/ai floor is ^0.8; support for 0.6 / 0.7 was dropped. Consumers pinned below laravel/ai 0.8 must upgrade. See the changelog for what the 0.8 adoption changes.
This package declares "minimum-stability": "dev" with "prefer-stable": true because laravel/ai is still pre-1.0 and ships dev-tagged releases. Composer will not resolve a pre-stable transitive dependency from a stable consuming project, so your application's composer.json must also set:
prefer-stable keeps Composer biased toward tagged releases β only dependencies without a stable release (today, laravel/ai) resolve to a dev- constraint. This requirement will be dropped when laravel/ai reaches 1.0; the package will then move to "minimum-stability": "stable" and consuming applications will be free to do the same.
Laravel Swarm orchestrates the same Laravel AI agents, providers, and streams as your application. Treat Composer updates to Laravel or laravel/ai as integration-test events: run your test suite and any queued, streamed, or durable swarm smoke paths after dependency changes. This package's changelog covers Swarm-owned changes; it does not replace verification against upstream Laravel or Laravel AI releases.
Installation
Require the package with Composer, then run the interactive installer:
Tagged releases are available on Packagist. Pin a tagged release for production applications.
swarm:install walks you through the full setup in one shot β it publishes config/swarm.php, seeds the canonical Swarm .env keys with safe defaults, runs the package migrations (or scaffolds LaravelSwarm::ignoreMigrations() for a cache-only deployment), warns when QUEUE_CONNECTION=sync, and offers to dispatch the targeted sub-installers in the same pass:
swarm:install:durableβ scheduler entries (swarm:relay,swarm:recover,swarm:prune), persistence/queue checks, copy-paste worker snippets.swarm:install:auditβ bind aSwarmAuditSink(and optionalSwarmAuditSigner/ActorResolver/CapturePolicy) insideAppServiceProvider.swarm:install:pulseβ register the Swarm recorders and dashboard cards (only offered whenlaravel/pulseis installed).swarm:install:examplesβ copy the runnable starter example pack intoapp/Ai/.
For CI and scripted setups, every prompt has a flag override:
Pass --without-<name> to skip a sub-installer in non-interactive mode, --persistence=cache for cache-only deployments, --skip-migrate to defer migrations, or --force to overwrite an existing config/swarm.php.
After the install, confirm everything wired up cleanly:
--durable also verifies the database tables required by dispatchDurable() and coordinated multi-worker hierarchical queueing.
Read Getting Started for the full new-user walkthrough β installer flow, post-install verification, and running your first starter swarm in under five minutes.
Advanced setup (manual)
Prefer to wire things by hand? Every step swarm:install performs has a stable manual equivalent. See Advanced Setup for the full manual flow β config publish, migrations vs. ignoreMigrations(), scheduler entries, audit sink binding, Pulse recorder + dashboard registration, and copying the starter examples by hand.
Your First Swarm
Generate a swarm class:
See Generators for the full generator surface, including make:swarm:agent and the --topology flag.
Swarms live in App\Ai\Swarms, implement BuiltByBerry\LaravelSwarm\Contracts\Swarm, use the Runnable trait, and return their participating Laravel AI agents from agents():
In a sequential swarm, the first agent receives the original task. Each later agent receives the previous agent's output.
Running A Swarm
Use prompt() when the caller can wait for the full workflow result:
Structured task input is supported:
run() remains available as a compatibility alias for prompt().
SwarmResponse casts to a string for simple use cases and implements toArray() / JsonSerializable for JSON responses:
toArray() intentionally omits the live RunContext so an API response does not accidentally re-emit prompt or input data. Read $response->context directly when your application needs the in-process context.
Choosing An Execution Mode
| Method | Returns | Use when |
|---|---|---|
prompt() |
SwarmResponse |
The request can wait for the full result. |
run() |
SwarmResponse |
Existing code still calls the compatibility alias. |
queue() |
QueuedSwarmResponse |
One background job can own the workflow. |
stream() |
StreamableSwarmResponse |
A sequential workflow should emit live progress or token events. |
broadcast() / broadcastNow() |
StreamableSwarmResponse |
A sequential workflow should stream and broadcast typed events immediately. |
broadcastOnQueue() |
QueuedSwarmResponse |
A worker should stream and broadcast typed events. |
dispatchDurable() |
DurableSwarmResponse |
The workflow needs checkpointing, recovery, operator controls, or branch jobs. |
Guardrails (input, per-step, final output policy checks) run across these modes at fixed orchestration boundaries; see docs/guardrails.md.
queue() and dispatchDurable() return dispatch handles with a runId. Listen for lifecycle events or inspect persisted history for eventual results.
stream() and the broadcast helpers support sequential swarms only. Use lifecycle events and application-owned broadcasts for queued, durable, parallel, or hierarchical operations feeds.
Queueing A Swarm
Use queue() when the workflow should run in the background:
Queued swarms are re-resolved from Laravel's container on the worker. Keep swarm definitions stateless across the queue boundary, and pass per-run data in the task payload:
Queued and durable task payloads should use plain data: strings, integers, floats, booleans, null, and arrays containing only those values. Do not pass models, closures, resources, or runtime service objects.
With the shipped conservative defaults, queued and durable swarms require active context capture:
You may still leave input, output, and artifact capture disabled for redacted history.
Streaming A Swarm
Use stream() when a browser, CLI, or custom consumer needs live typed events from a sequential swarm:
Return the response directly from a route for Laravel AI-style SSE output:
Broadcast the same typed stream events through Laravel broadcasting:
Persisted stream replay is opt in:
Replay later with SwarmHistory::replay($runId). See Streaming for event schemas, replay behavior, capture, limits, and failure handling.
Crash-replay resume (v0.12.0)
A streamed run that is abandoned mid-stream β a worker crash, a dropped connection, an early break β can be resumed by re-running the same swarm with the same run id:
On resume, already-completed non-final steps are skipped (their providers are not re-invoked and tool side effects do not re-fire β their output is rehydrated from a per-step checkpoint), and the terminal streamed step replays byte-identically from its frozen memory snapshot. Governed by the memory replay mode (frozen_view default; fresh_execution opts out) and the database persistence driver. See Streaming β Crash-Replay Durability.
Tool calls (including MCP tools) (v0.13.0)
Swarm carries laravel/ai ToolCall / ToolResult objects through the stream and the durable snapshot as opaque passthrough, so the MCP client/server tools added in laravel/ai 0.8 flow through with no MCP-specific configuration β including structured (non-scalar) MCP results, preserved intact. A tool value JSON cannot represent degrades to a typed placeholder at the tool boundary rather than crashing the run. See Streaming β Tool calls (including MCP tools).
Streaming dynamic swarms & the causal-log substrate (v0.15.0)
stream() now streams dynamic Hierarchical swarms β the coordinator runs synchronously, then its workers stream as the plan is walked. Underneath, the streamed event log is an append-only causal log: nothing is mutated or deleted in place, course-corrections are typed void-edges, and any shape a reader wants (clean vs. forensic, causal vs. presentation order) is a read-time fold via CausalLogView. A background compactor graduates sealed history to a cold tier so the hot log stays bounded, and authors can bound their own context with 'type' => 'rollup' plan nodes and a declarative #[ContextGrowthPolicy].
- Authors: Streaming Substrate Author Guide β dynamic streaming, the causal-log fold, rollup nodes, the context-growth policy.
- Operators: Streaming Substrate Operator Runbook β hot/cold tiering, scheduling
swarm:compact, retention, recovery and quarantine.
Durable Execution
Use dispatchDurable() when the workflow is too important or too long-lived for one queue job:
Durable execution requires database-backed swarm persistence and advances the workflow through checkpointed jobs. Sequential durable swarms run one agent per job. Parallel durable swarms and hierarchical parallel groups use independent branch jobs and join before continuing.
Durable responses also expose operator helpers:
Schedule the relay, recovery, and pruning for durable execution:
Start with webhooks.
Durable per-node streaming (v0.15.0)
A durable run can stream each node's events into the causal log as it executes, instead of producing one blocking prompt() response per node β so operators get a live, replay-safe signal from a durable run. Opt a swarm in with the #[DurableStreaming] attribute (off by default); the decision is pinned onto the run row at start, so a redeploy never changes an in-flight run.
It streams on every durable topology β sequential, hierarchical, static_hierarchical, and parallel (including fan-out branches) β with each node's attempt voided-and-retried cleanly on crash-resume (the same append-only causal-log fold the live substrate uses). The hierarchical coordinator streams structural events; token-streaming the coordinator is a follow-up. Declaring the attribute on a topology not yet wired for streaming fails loud at dispatch. An operator kill-switch (SWARM_DURABLE_STREAMING_ENABLED=false) pauses emission fleet-wide without a redeploy, safely mid-run. See Durable Execution β per-node streaming.
Memory (v0.9.0+)
Swarm Memory is a first-class, scoped, snapshot-replayable memory subsystem. It gives agents and application code a place to read and write structured values that persist across steps, survive queue boundaries, and can be replayed deterministically from a frozen snapshot on a crash-resume.
RunContext writes through to MemoryScope::Run automatically via its ArrayAccess interface β $context['key'] = $value mirrors to memory without any code change.
Propagation, redaction, and an operator surface (v0.10.0+). Memory now ships the controls a regulated workload needs:
MemoryPropagationPolicydecides which memory entries a worker agent sees at invocation (default: the Run-scoped view, byte-identical to v0.9).MemoryCapturePolicyredacts or drops entries at the write boundary, so PII never reaches a snapshot (default: a no-op).- Operator CLI β
swarm:memory:inspect(view a run's frozen snapshots),swarm:memory:dump(export the full memory + snapshot trail for an audit packet / DSAR), andswarm:memory:purge(enforce per-scope retention windows).
See laravel-swarm-memory-vector companion package.
Agent memory tools (v0.11.0+). Agents can now read and write memory mid-prompt as ordinary laravel/ai tools β drop the shipped Recall and Remember tools into any agent's tools() array (or expose them via the HasSwarmMemoryTools trait). Scope ids resolve from the active run, never the model; reads honour the propagation policy and writes honour the capture policy, so the tools can never surface or persist anything the policies forbid. They are disabled by default (swarm.memory.tools.enabled) β granting an LLM access to shared memory is an explicit decision. Scaffold custom variants with php artisan make:memory-tool. See the memory recipes for worked patterns: per-user and tenant-scoped recall, policy-enforced custom tools, recall + redact, and sub-agent memory continuity.
Topologies
Laravel Swarm supports four topologies.
Sequential
Agents run in order. Each agent receives the previous agent's output.
Parallel
Agents run concurrently and each receives the original task.
Parallel agents must be stateless and container-resolvable by class because Laravel concurrency resolves them inside worker processes.
Hierarchical
The first agent is the coordinator. It returns a Laravel AI structured output route plan. Laravel Swarm validates the plan as a DAG and executes selected worker, parallel, and finish nodes.
Read Hierarchical Routing for the route plan schema, validation rules, queue behavior, and durable branch coordination.
Static Hierarchical
The route plan is defined in PHP β no coordinator LLM call runs at runtime. Use it when the graph of agents is always the same and only the content changes.
Read Static Hierarchical Topology for the plan schema, streaming modes, step budgets, and execution mode support.
Testing
Use fake() to intercept swarm execution in application tests:
Fakes cover prompt, queue, stream, broadcast, and durable dispatch intent:
Use database-backed feature tests when you need to prove durable leases, checkpoints, retries, branch joins, wait release, recovery, or webhook idempotency. SwarmFake records intent; it does not execute the durable runtime.
To assert that swarm lifecycle events (started, step, completed, failed, β¦) fired during a real run, add the InteractsWithSwarmEvents trait to your test case and call assertEventFired() (v0.15.1+):
See Testing Swarms.
Configuration
Laravel Swarm stores defaults in config/swarm.php.
Common settings include:
swarm.topologyswarm.timeoutswarm.max_agent_stepsswarm.persistence.driverswarm.capture.*swarm.queue.*swarm.durable.*swarm.streaming.replay.*swarm.observability.*swarm.audit.*swarm.limits.*
Capture defaults are conservative. Prompts, outputs, automatic step artifacts, and rich active-context snapshots are not persisted unless you opt in. When the global persistence driver or a per-store override uses database, swarm.persistence.encrypt_at_rest defaults to true and seals designated sensitive string columns with Laravel's encrypter.
Use Audit Evidence Contract before enabling production capture, audit, or retention policies.
Production Checklist
- Choose
prompt(),queue(),stream(), ordispatchDurable()intentionally. - Use database persistence for durable execution, long-lived history, active-run pruning protection, or operational dashboards.
- Set
SWARM_CAPTURE_ACTIVE_CONTEXT=truefor queued and durable swarms. - Size queue worker timeouts and queue
retry_afterabove the longest expected provider call. - Schedule
swarm:relayevery minute for durable execution AND for the v0.5 audit outbox. The relay drains the durable outbox after each checkpoint and replays failed audit records through the bound sink β a single schedule covers both lanes. Without it, durable runs stall after the first step and queued audit failures accumulate without retry. Useswarm:relay --type=auditto drain only the audit lane during focused recovery. See Audit Evidence Contract for the full relay reference. - Run
php artisan migrateon database persistence to createswarm_audit_outboxβ required for the v0.5 defaultSWARM_AUDIT_FAILURE_POLICY=queue(sink failures persist for retry instead of being silently dropped). Cache persistence detects the missing outbox and falls back to log-and-swallow automatically. - Schedule
swarm:recoverevery five minutes for durable execution and coordinated multi-worker hierarchical queueing. Recovery redispatches runs whose workers died between checkpoint and dispatch. See Maintenance. - Schedule
swarm:prunedaily for database retention cleanup, or setSWARM_PREVENT_PRUNE=truewhen retention is managed outside the package. - Streaming crash-replay (v0.12.0):
php artisan migratecreatesswarm_stream_step_checkpoints, which records each completed non-final streamed step's raw output + usage so an abandonedstream()run resumes idempotently (no provider re-invoke, no side-effect re-fire). It is operational resume state, encrypted at rest by default under the database driver (swarm.persistence.encrypt_at_rest), and pruned with the run β early-pruned alongside snapshots byswarm:memory:purge(--keep-snapshotsretains both) and cascade-deleted via theswarm_run_historiesforeign key as theswarm:prunebackstop. See Streaming β Crash-Replay Durability. - Rotate
APP_KEYcarefully (v0.12.1): whenencrypt_at_restis on, durable operational resume state is sealed with the activeAPP_KEY. Rotating the key without re-keying the stored rows now makes durable resume fail loud with a clearSwarmException("β¦verify APP_KEYβ¦") instead of silently resuming from a wrong/empty prompt β re-pointAPP_KEYto the key that sealed the rows and re-dispatch the affected runs. See Upgrading to v0.12.1. - Treat operational swarm tables as TTL-based runtime storage, not immutable compliance archives.
- Bind
SwarmAuditSinkfor regulated evidence export. - Bind
SwarmTelemetrySinkfor logs, metrics, or tracing correlation. - Avoid secrets in metadata. Capture redaction does not sanitize arbitrary developer-supplied metadata. Set
SWARM_MAX_METADATA_BYTESto enforce a hard size cap. - Build run inspection around
run_id, lifecycle events,SwarmHistory, and durable runtime state. - Bookmark the Operator Runbook: Audit Outbox Triage before going live. It is the 3 a.m. decision tree for dead-letter rows, stale pending rows, and sink outages β and it assumes the reader has not just re-read the reference docs.
- Use
php artisan swarm:trace <run_id>(v0.7+) to reconstruct a single run's audit chain across run history, the audit outbox, and the bound sink. Read-only, on-demand, with--jsonfor monitoring and--include-payloadsfor full envelopes. See Audit Evidence Contract, including the Security and retention subsection covering how the command unseals encrypted-at-rest data on output.
Audit Extension Points
Regulated deployments can replace four audit contracts in the container:
ActorResolverβ resolves the human or system actor recorded on each evidence envelope.CapturePolicyβ decides which run fields are captured, redacted, or omitted before evidence is emitted.SinkFailureHandlerβ handlesSwarmAuditSinkwrite failures (log, retry, halt, or escalate).SwarmAuditSignerβ produces the cryptographic signature attached to each envelope for tamper-evident export.
One optional extension contract (v0.7+):
ReadableSwarmAuditSinkβ extendsSwarmAuditSinkwithforRun(string $runId): iterable<array>so the sink can participate inswarm:trace. Opt-in; the shippedNoOpSwarmAuditSinkdoes not implement it and existing custom sinks remain valid.
Two environment knobs control strict-mode behavior:
SWARM_AUDIT_ACTOR_REQUIRED=trueβ fail closed when no actor can be resolved for a run.SWARM_AUDIT_FAILURE_POLICY=haltβ halt run progression when the audit sink rejects an envelope.
The full SWARM_AUDIT_FAILURE_POLICY matrix (since v0.5): swallow (drop silently β v0.4 default), log (log and continue), queue (persist to swarm_audit_outbox for retry β v0.5 default), dead_letter (persist directly to dead-letter status, no retry), halt (fail the run). The audit outbox is monitored by default via swarm:health (or swarm:health --audit for focused investigation).
Audit-path exception messages are redacted to [redacted] by default since v0.14.0 (SWARM_AUDIT_REDACT_EXCEPTION_MESSAGES=true) unless capture already permits failure free-text; the exception class/type is always logged, so failures stay diagnosable.
See Operator Runbook: Audit Outbox Triage.
Documentation
The full documentation site is at swarm.builtbyberry.com β searchable, versioned, and the recommended starting point.
The same content is mirrored in this repository; start with the in-repo documentation index when working offline.
- Structured Input
- Streaming
- Hierarchical Routing
- Persistence And History
- Durable Execution
- Durable Runtime Architecture
- Durable Waits And Signals
- Durable Retries And Progress
- Durable Child Swarms
- Durable Webhooks
- Observability: Logging And Tracing
- Observability Correlation Contract
- Audit Evidence Contract
- Testing
- Pulse
- Maintenance
- Public Surface Coverage
- Examples
Local Development
From the package root:
If you run PHPStan directly, use:
composer format rewrites files with Pint. Use composer lint when you need a non-mutating formatting check.
License
MIT
All versions of laravel-swarm with dependencies
illuminate/bus Version ^13.0
illuminate/cache Version ^13.0
illuminate/concurrency Version ^13.0
illuminate/console Version ^13.0
illuminate/container Version ^13.0
illuminate/contracts Version ^13.0
illuminate/database Version ^13.0
illuminate/events Version ^13.0
illuminate/filesystem Version ^13.0
illuminate/queue Version ^13.0
illuminate/support Version ^13.0
illuminate/view Version ^13.0
laravel/ai Version ^0.8