DocumentationReference

HazelJS Organism Package

npm downloads

Agentic Organism Runtime for HazelJS — deploy a mission, not an agent topology.

In conventional multi-agent systems, developers define the organization.
In HazelJS Agentic Organisms, developers define the mission and operating boundaries. The organization emerges dynamically at runtime.

Quick Reference

  • Purpose: Self-organizing ephemeral agent societies that pursue a mission under constitution, resource limits, and environment signals.
  • When to use: Autonomous ops / support departments, signal-driven specialist teams, resource-constrained fleets, strategy evolution, or digital-twin simulation — when you do not want a hardcoded agent graph.
  • Key APIs: createOrganism, createOpsOrganism, createOrganismHost, OrganismHostRegistry, OrganismRepository, toEnvironmentSignal, toIncidentEnvironmentSignal, toAgentOutcomeReport, @Mission, @Organism, @AgentGene, @Environment, @Constitution, @Resource, observe, inspect, simulate, reproduceAgent, placeBid, clearMarket, negotiate, emergencyStop.
  • Dependencies: @hazeljs/​agent (peer), @hazeljs/​core. Optional: @hazeljs/​agent-gatekeeper, observability.
  • Not a second kernel: Composes AgentRuntime / Agent OS — does not replace tools, durable runs, DNA, or Gatekeeper.
  • Common mistakes: Hardcoding ecommerce capability routing in code (use signalNeedMappings); expecting Gene ≈ DNA; treating organism agents as permanent app architecture; skipping maxAgents / spawn-rate limits; assuming InMemoryOrganismRepository is multi-replica safe (inject a durable OrganismRepository and reuse ids).

Why Organism exists

Problem in productionOrganism answer
You know the mission, not the final agent rosterGenes + need detection → spawn / reuse / specialize
Static Supervisor graphs go stale under new signalsEnvironment → perception → decision loop
Agents live forever and burn budgetUtility, reputation, survival termination
Unbounded spawn / generation depthHard limits + constitution + kill switch
Competing strategies need selection pressureConstrained mutation + generation evaluation
Scarce tokens/money across peersWallets, forecasts, bids, market clearing, negotiation

Prefer plain @hazeljs/​agent (or Supervisor / AgentGraph) when the agent set is small and stable and the workflow is a known DAG.

Installation

npm install @hazeljs/​organism @hazeljs/​agent @hazeljs/​core

Mental model

WORLD → PERCEPTION → MISSION → SELF-ORGANIZING AGENT SOCIETY → ACTION → WORLD

Agents are ephemeral runtime entities, not permanent application architecture.

  1. Environment emits signals
  2. Perception filters for mission relevance
  3. Need detector asks: what capability is missing?
  4. Capability registry prefers reuse over birth
  5. Birth allocates scarce resources and records structured reasons
  6. Outcomes update utility / reputation / mission progress
  7. Survival terminates low-value agents after enough evidence
flowchart TD
  ENV[Environment] --> P[PerceptionEngine]
  P --> N[NeedDetector]
  N --> D[DecisionEngine]
  D --> Cap[CapabilityRegistry]
  D --> B[BirthEngine]
  D --> RA[ResourceAllocator]
  B --> A[RuntimeAgents]
  A --> RT[AgentRuntime_Tools_MCP]
  A --> O[OutcomeReporting]
  O --> U[UtilityEngine]
  U --> REP[ReputationEngine]
  REP --> S[SurvivalEngine]
  S --> X[Terminate_or_Continue]
  C[Constitution] --> D
  C --> GK[PolicyEngine_Gatekeeper]
  M[Mission] --> D
  M --> U

Core concepts

TermMeaning
MissionWhat the organism is trying to achieve
OrganismAutonomous runtime pursuing the mission
GeneReusable capability template for spawning agents (≠ DNA)
AgentEphemeral worker created inside the organism
EnvironmentExternal signals the organism observes
ConstitutionRules no agent may override
EconomyFinite token / money / tool budgets

Quick start

import { createOrganism } from '@hazeljs/​organism';

const organism = await createOrganism({
  mission: {
    id: 'support',
    objective: 'Operate customer support while maintaining 90% CSAT',
    successCriteria: [{ name: 'csat', operator: 'gte', target: 90 }],
  },
  genes: [
    {
      id: 'support-gene',
      capabilities: ['customer-support', 'commerce'],
    },
    {
      id: 'analysis-gene',
      capabilities: ['analytics', 'analysis'],
    },
  ],
  constitution: {
    id: 'commerce',
    rules: [
      {
        id: 'privacy',
        rule: 'Never expose customer personally identifiable information',
        severity: 'critical',
      },
      {
        id: 'refund-limit',
        rule: 'Refunds above $200 require human approval',
        severity: 'high',
      },
    ],
  },
  limits: {
    maxAgents: 10,
    maxGenerationDepth: 3,
    maxChildrenPerAgent: 3,
    maxSpawnRatePerMinute: 5,
    maxTotalCostPerHour: 10,
  },
  signalNeedMappings: [
    {
      signalType: 'refunds.increased',
      need: 'refund-analysis',
      requiredCapabilities: ['analytics', 'commerce'],
      urgency: 0.9,
      confidence: 0.9,
    },
  ],
  debug: true,
});

await organism.start();

await organism.observe({
  type: 'refunds.increased',
  source: 'analytics',
  severity: 0.9,
  data: { baseline: 0.04, current: 0.071 },
});

const state = await organism.inspect();
console.log(state.agents);

Domain routing belongs in signalNeedMappings — map signal types to required capabilities. Do not bake product-specific keyword → capability tables into the need detector.

Decorators

import { Mission, Organism, AgentGene, Constitution, Environment } from '@hazeljs/​organism';

@Mission({ id: 'ops', objective: 'Keep the store healthy' })
class OpsMission {}

@AgentGene({ id: 'commerce', capabilities: ['commerce', 'support'] })
class CommerceGene {}

@Organism({ mission: OpsMission, genes: [CommerceGene] })
class StoreOrganism {}

Main use cases

  1. Autonomous operations — long-running goals like “operate support at 90% CSAT within budget.”
  2. Environment-driven response — telemetry, commerce events, ops alerts; not chat-first topology.
  3. Ephemeral specialist teams — spawn RefundAnalysis / SizingResearch only while the need exists.
  4. Governed autonomy under scarcity — budgets, constitution, approval gates, survival.
  5. Strategy competition — mutate safe config fields, promote winners, retire losers.
  6. Simulation / digital twin — accelerated clock + mock tools before production.

Reproduction (Phase 2)

Parents spawn children with inheritance policies, permission subsets (never escalate), genealogy, and generation/child limits.

await organism.reproduceAgent({
  parentAgentId,
  reason: 'Specialize on sizing complaints',
  inheritance: { mode: 'subset', capabilities: ['commerce', 'support'] },
});

/​/​ From agent context:
await context.reproduce({ reason: 'Need deeper analytics' });
await context.spawn({ geneId: 'analysis-gene', reason: 'Burst analysis' });

Inspect genealogy with inspect() / CLI hazel organism genealogy <id>.

Evolution (Phase 3)

Constrained mutation (prompt / capabilities / modelConfig / strategyConfig) plus generation evaluation and strategy promotion.

await organism.evaluateGeneration({ generationId });
await organism.promoteWinner({ generationId });

Mutation is audited and bounded — not free-form prompt rewriting.

Agent economy (Phase 4)

Finite wallets plus forecasting, sealed-bid markets, and peer negotiation.

const forecast = await organism.forecastUtility({
  agentId,
  requested: { tokens: 50_000 },
  expectedValue: 5000,
  confidence: 0.72,
});
/​/​ forecast.netExpectedValue, opportunityCost, scarcityMultiplier

organism.placeBid({
  agentId,
  reason: 'Run pricing simulations',
  requested: { tokens: 100_000, money: 10 },
  expectedValue: 5000,
  confidence: 0.72,
  bidPrice: 5,
});

const cleared = await organism.clearMarket();
/​/​ cleared.awarded /​ cleared.denied

await organism.negotiate({
  fromAgentId: donorId,
  toAgentId: receiverId,
  reason: 'Fund analytics burst',
  transfer: { tokens: 10_000 },
  expectedValue: 2000,
  confidence: 0.85,
});

Embedding in product platforms

Prefer the host / ops APIs instead of wrapping OrganismRuntime yourself. Keep tenancy, incident detectors, policy, and adapters in the product layer; leave need detection, spawn/reuse, survival, and simulation to organism.

import {
  createOpsOrganism,
  OrganismHostRegistry,
  toEnvironmentSignal,
  toIncidentEnvironmentSignal,
  toAgentOutcomeReport,
} from '@hazeljs/​organism';

const registry = new OrganismHostRegistry();

const host = await registry.getOrCreate(existingId, () =>
  createOpsOrganism({
    id: existingId,
    mission: { id: 'commerce-ops', objective: 'Keep commerce healthy within policy' },
    genes: [
      { id: 'commerce-generalist', capabilities: ['commerce', 'operations'] },
      { id: 'refund-analysis', capabilities: ['analytics', 'commerce'] },
    ],
    incidentTypes: ['refund_spike', 'product_issue'],
    repository, /​/​ durable OrganismRepository in production
    limits: { maxAgents: 15, maxTotalCostPerHour: 10 },
  })
);

await host.start();

await host.observe(
  toEnvironmentSignal({
    type: 'refund.created',
    source: 'woocommerce',
    severity: 0.7,
    data: { orderId: '123' },
  })
);

await host.observe(
  toIncidentEnvironmentSignal({
    incidentType: 'product_issue',
    severity: 0.85,
    data: { incidentId: 'inc_1' },
  })
);

const state = await host.inspect();
Belongs in @hazeljs/​organismBelongs in the product layer
Mission, genes, need detectionVertical incident detectors
Spawn / reuse / specializeSemantic action catalogs
Constitution enforcementBusiness policy / approvals
Utility, reputation, survivalTenancy (tenantId, businessId)
simulate()Integration adapters
OrganismRepositoryProduct DB for incidents / approvals

Persistence and multi-replica hydrate

Inject OrganismRepository via createOrganism / createOpsOrganism({ repository }).

  • InMemoryOrganismRepository — tests and single-process demos.
  • Production — implement OrganismRepository against your database (e.g. Postgres).

Repository is durable truth; OrganismHostRegistry is a warm cache. When createOpsOrganism({ id, repository }) runs and the repository already has that organism, the runtime restores the persisted record and agents (pool, status, capability index) instead of creating a greenfield society. A registry miss on a new process replica hydrates from the repository when the id exists — no sticky load balancer required for organism state.

LayerShared across replicas?
Durable OrganismRepositoryYes (your DB)
OrganismHostRegistryNo (process-local warm cache)
Restored agents / pool / statusYes, via repository hydrate

Pass a stable id and the same repository instance (or shared DB backend) on every replica.

Safety defaults

  • maxAgents, maxGenerationDepth, maxChildrenPerAgent, maxSpawnRatePerMinute, maxTotalCostPerHour
  • Capability reuse before birth
  • Constitution enforcement on spawn / sensitive actions
  • Minimum age / sample count before survival kill
  • pause() / resume() / terminate() / emergencyStop()

Constitution rules compile into PolicyEngine / Gatekeeper — not a parallel auth stack. Pair with @hazeljs/​agent-gatekeeper for per-tool authorization.

Simulation

await organism.simulate({
  duration: '30d',
  clockSpeed: 1000, /​/​ accelerated
  signals: [/​* EnvironmentSignal[] */​],
});

Use simulation to rehearse ops twins before wiring live environment adapters.

CLI

hazel organism list
hazel organism inspect <id>
hazel organism agents <id>
hazel organism genealogy <id>
hazel organism resources <id>
hazel organism events <id>
hazel organism pause <id>
hazel organism resume <id>
hazel organism stop <id>

Package boundary

@hazeljs/​organism → @hazeljs/​agent → @hazeljs/​core
                 ↘ optional: agent-gatekeeper, observability
  • Gene ≠ DNA — genes are spawn templates; DNA is Agent OS packaging for identity/prompt/policies.
  • Organism ≠ Supervisor / AgentGraph — those are developer-defined topologies; organism emerges from mission + signals.
  • Deterministic control plane — resource accounting, reputation, limits, genealogy, mutation audits, and market clearing are code-first. Models may later interpret ambiguous signals; Phases 1–4 core loops do not require an LLM for spawn decisions.

Scope (Phases 1–4)

PhaseShips
1Mission, genes, environment signals, need detection, spawn/reuse, resources, utility, reputation, survival, constitution, simulation, inspect/graph, events
2Reproduction, inheritance policies, genealogy, generation/child limits, context.reproduce() / context.spawn()
3Constrained mutation, generation evaluation, strategy promotion
4Utility forecasting, opportunity cost, resource bidding, market clearing, peer negotiation

Product embedding (current): createOpsOrganism, OrganismHostRegistry, signal bridges, and restore-from-repository for multi-replica hydrate.

Source

For full source, examples, and changelog, see the organism package on GitHub.

Ecommerce demo: packages/​organism/​examples/​ecommerce-organism.