npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

conscious-agent

v3.0.0

Published

Self-referential structure-learning system — agents that learn by inhabiting worlds

Readme

conscious-agent

An executable model of Donald Hoffman's conscious-agent formalism — in Node.js.

Build self-referential agents that learn by inhabiting worlds. Zero external dependencies.

For AI coding assistants: A SKILL.md file lives in .context/SKILL.md with patterns for complex use cases (multi-agent networks, live data feeding, debugging). opencode and compatible tools load it automatically.

const { ConsciousAgent } = require('conscious-agent');
const { CoinTossWorld } = require('conscious-agent/worlds');

const world = new CoinTossWorld(4);
const agent = new ConsciousAgent({ agentId: 'my_agent', world });
const outputs = agent.run(1000);
console.log(`"I" locked: ${agent.isILocked}`);

Installation

npm install conscious-agent   # once published

or directly From Git

npm install github:ben42-01/hoffman-agents

Or from source:

cd hoffman-agents-node
npm link                     # or copy src/ into your project

Quick Start

Single agent in a coin-toss world

const { ConsciousAgent } = require('conscious-agent');
const { CoinTossWorld } = require('conscious-agent/worlds');

const world = new CoinTossWorld(3);
const agent = new ConsciousAgent({ agentId: 'coin_agent', world });

for (let i = 0; i < 500; i++) {
  const output = agent.step();
  if (output.iLocked) {
    console.log(`I locked at step ${output.step}`);
    break;
  }
}

Custom Markov world

const { ConsciousAgent, WorldBuilder } = require('conscious-agent');

const data = Array.from({ length: 500 }, () => [Math.random(), Math.random(), Math.random()]);
const world = new WorldBuilder()
  .addFeature('temp', 'minmax', 4)
  .addFeature('humidity', 'minmax', 4)
  .addFeature('pressure', 'minmax', 4)
  .build(data);

const agent = new ConsciousAgent({ agentId: 'weather_agent', world });
const outputs = agent.run(1000);

Build world from JSON data (v2.1)

const { buildWorldFromDataFrame } = require('conscious-agent');

const rows = [
  { temperature: 23.5, humidity: 65, pressure: 1013 },
  { temperature: 24.1, humidity: 63, pressure: 1011 },
  // ...
];
const world = buildWorldFromDataFrame(rows);
// Auto-detects numeric columns, or pass explicit feature specs

Predict next state (v2.1)

const prediction = agent.predictNext();
if (prediction) {
  console.log(`Expecting state ${prediction.stateId} (conf: ${prediction.confidence.toFixed(2)})`);
  const top3 = prediction.topK(3);
}

Combine two agents

const { combine } = require('conscious-agent');

const a = new ConsciousAgent({ agentId: 'agent_a', world });
const b = new ConsciousAgent({ agentId: 'agent_b', world });
a.run(500);
b.run(500);

const combined = combine(a, b);
console.log(`Combined agent: ${combined.agentId}, level: ${combined.cycleLevel}`);

Multi-agent network

const { AgentNetwork } = require('conscious-agent');

const network = new AgentNetwork({ nAgents: 10, seed: 42 });
const states = network.run(100);
console.log(`Avg prediction error: ${network.avgPredictionError().toFixed(3)}`);

Save and load

const { saveAgent, loadAgent, cloneAgent } = require('conscious-agent/io');

const path = saveAgent(agent, './souls');
const loaded = loadAgent(path);

const cloned = cloneAgent(agent, 'experiment_clone');

Public API

// Core classes
const { ConsciousAgent, World, WorldBuilder } = require('conscious-agent');
const { SimpleWorld, ExperienceSpace, Prediction } = require('conscious-agent');

// World factories
const { CoinTossWorld, SelfWorld, Normalizer, FeatureSpec } = require('conscious-agent/worlds');
const { buildWorldFromDataFrame } = require('conscious-agent');

// IO
const { saveAgent, loadAgent, cloneAgent, loadLatest, clone } = require('conscious-agent/io');

// Multi-agent
const { AgentNetwork, Topology, InteractionCycle, combine } = require('conscious-agent');

// Core components
const { TraceBuffer, TraceEvent, ExperienceTrie, TrieNode } = require('conscious-agent');
const { MetaTrie, MetaStateSnapshot, SelfTokenState, ExperienceLexicon, LexiconEntry } = require('conscious-agent');

// Utilities
const { strangeLoopScore, computeSelfReferenceScore, populationReferenceScore } = require('conscious-agent');
const { prune, traceDistance, mergeSimilarPaths, inventToken, isInventedToken } = require('conscious-agent');
const { SharedMeaningTracker, EnvironmentState, sequenceToStateId } = require('conscious-agent');

// v2.1 — Predict next state
agent.predictNext();         // → Prediction { stateId, stateLabel, confidence, topK(n) }
prediction.topK(3);          // top 3 alternatives with confidence

// v2.1 — Config-driven construction
ConsciousAgent.fromConfig('id', { agent: { selfToken: { lockThreshold: 0.3 } } });

// v2.1 — Topology introspection
topology.getConnectionStrength(0, 1);   // query connection weight
topology.maybeAddConnection(0, 5);       // add link probabilistically
topology.getAgentObservers(3);           // who observes agent 3?

// v2.0 — Agent mode control
agent.setMode('frozen');     // deterministic projection, no trie/meta updates
agent.thaw();                // back to learning mode
agent.refreeze();            // back to frozen

// v2.0 — Memory & lifecycle
agent.clearMemory();         // reset trace buffer + counters, preserve trie/lexicon
agent.injectObservation(worldState);  // push new data mid-run without reset

// v2.0 — Metrics & introspection
agent.metrics;               // { predictionError, iLocked, loopDepth, outputTokens }
network.getMetrics();        // { agentCount, meanPredictionError, iLockRate, ... }
network.getAgentMetrics(id); // individual agent's metrics snapshot
trie.getStats();             // { nodeCount, maxDepth, meanVisitCount, depthDistribution }
trie.exportNodes(3);         // all paths with visitCount >= 3
trie.getDominantPaths(5);    // top 5 most-visited paths

// v2.0 — Batch stepping
network.stepAll(worldState); // step all agents with same world state
network.agentList;           // agents as an ordered array

// v2.0 — Action space
output.actionDistribution;   // { token: probability, ... } — full distribution
new ConsciousAgent({ allowableTokens: ['I', 'notice'] });  // constrain output
agent.setAllowableTokens(['I', 'notice', 'familiar']);

// v2.0 — Composition
combine(a, b, c);            // n-ary combination (3+ agents)
fuse(combined);              // decompose back into constituents

// v2.0 — TraceBuffer
traceBuffer.resize(100);     // dynamic window resizing

// v2.0 — Trie compression
prune(trie, 5);              // remove nodes with < 5 visits
traceDistance(pathA, pathB); // edit distance with transition-aware cost
mergeSimilarPaths(trie, matrix, 0.15);  // merge paths within threshold

Self-Modelling

Agents contain four self-modelling mechanisms. They are mechanisms; whether any of them amounts to self-awareness is not something the code can establish.

| Mechanism | Type | What it does | |-----------|------|-------------| | MetaTrie | Built-in | A Markov chain over the agent's own coarse self-observations | | SelfTokenState ("I") | Built-in | Locks when that chain has a stable attractor; unlocks when it dissolves | | strangeLoopScore | Built-in | Counts self-reference in output tokens (mostly reflects time in the core output mode) | | SelfWorld | Optional wrapper | Feeds the agent's internal metrics back into its perception |

SelfWorld

SelfWorld is a world wrapper that lets the agent perceive its own internal state alongside external data. The agent's trie learns transitions over composite states of (world + self).

const inner = new SimpleWorld({ nStates: 10 });
const agent = new ConsciousAgent({
  agentId: 'self_aware',
  world: new SelfWorld(inner, (self) => ({
    sp: self.experience.selfToken.stationaryProb,
    pe: self.meanPredictionError,
  })),
});
agent.run(1000);

Each step, the agent's WorldState contains both 'world' and 'self' sequences. The agent discovers patterns like "when my prediction error is high and the world shows pattern X, the next state tends to be Y."

→ What these mechanisms do and do not show: docs/SELF_AWARENESS.md

How It Works

Every ConsciousAgent has an experience space — four interconnected structures:

  1. TraceBuffer — short-term memory: the last N state transitions
  2. ExperienceTrie — long-term world model: compressed prefix tree over observed state sequences
  3. MetaTrie — self-model: a Markov chain over the agent's own coarse self-observations
  4. SelfTokenState ("I") — identity: locks onto a stable attractor of the self-model

The agent cycles through perception → meta-observation → decision (generate output tokens via the decision kernel D).

The "I" locks when the agent's self-observation chain has a clear, stable attractor: enough data, aperiodic, one state well above the uniform baseline, currently occupied. It unlocks with hysteresis when the attractor dissolves. It fires in worlds with structure and not in noise. agent.ergodicStats() reports the criteria, and agent.toFormal() exports the learned kernels as a (X, G, P, D, A, N) tuple. The mathematics is in docs/MATHEMATICAL_MODEL.md.

Version 3 changed the math (see RELEASE_NOTES_v3.0.0.md). Pass { mathVersion: 'legacy' } to reproduce 2.x behaviour exactly, and seed: 1 for reproducible runs, identical across Node and Python.

Experiments

The examples/ directory holds experiments, each with controls. Highlights:

  • 13 Bell test through the headset: correlations produced by a conscious-agent network behind spacetime; best CHSH = 2 + 2·δ(Qᵏ) (npm run examples:bellThroughTheHeadset)
  • 14 Spacetime in the headset: an observer recovers dimension from experience; ⊗ adds dimensions and interaction binds them (npm run examples:spacetimeInTheHeadset)
  • 15 Time in the traces: Hoffman's trace chains; per-observer clocks and an observer-dependent arrow of time (npm run examples:timeInTheTraces)
  • 16 Trace logic and decorated permutations: Hoffman's map to the positive Grassmannian's combinatorics, checked against the paper; trace logic's structure; mass and speed proposals stress-tested (npm run examples:traceLogic)
  • 17 Quantum agents: kernels as quantum channels; combined agents reach exactly 2√2; Markov agents as the decohered limit (npm run examples:quantumAgents)
  • 18 Relativity at infinity: as n → ∞ an agent's clock converges to Einstein's proper time; a light cone needs memory (npm run examples:relativityAtInfinity)
  • 02 Quantum signature?: why an earlier "quantum-like" signature was an artifact
  • 05 Self-reference ablation and 12 ergodic diagnostics: the "I" lock tracks structure

Documentation

MATHEMATICAL_MODEL.md · Q_AND_A.md (results, limitations, corrections) · COMPONENT_DEFINITIONS.md · CONSCIOUS_AGENTS_VISUAL_GUIDE.md · SELF_AWARENESS.md · GLOSSARY.md · CONSCIOUS_AGENTS_THEORY.md (design document)

Requirements

  • Node.js >= 18
  • No external dependencies

License

MIT