PARACOSM AGENTOS | API Reference v0.9.1202
Home Simulation API Docs GitHub npm
Home Simulation API Docs GitHub npm AgentOS Discord
paracosm - v0.9.1202
    Preparing search index...

    paracosm - v0.9.1202

    Paracosm

    PARACOSM

    Paracosm simulates any what-if as divergent timelines using LLM agent swarms for structured world modeling. Turn a prompt into a runnable multi-agent world and fork its future.

    npm License Docs AgentOS NVIDIA Inception Member

    paracosm.agentos.sh · Live Demo · API Docs · npm · Discord

    Paracosm end-to-end: paragraph in, multiple leaders running side by side, fork-and-replay out

    Type a what-if. Compile a typed world. Run it as timelines side by side and change one thing between them: who leads or an event at any turn. Watch the trajectories diverge.

    ▶ 34-second demo  ·  ▶ Digital twin


    Paracosm simulates any what-if as divergent timelines from the same seed, roster and dice. It compiles a JSON scenario draft (or a prompt, or an extracted document) into a runnable multi-agent world. The kernel reproduces byte-for-byte. The LLM Event Director writes each timeline’s unscripted crises from what happens in it. Snapshot any turn, fork with a different actor, seed, or custom event, and the branch streams alongside the trunk: the contrast is visible in the artifact, not promised in copy.

    Paracosm system flow: world source through Scenario Compiler, ScenarioPackage, Deterministic Kernel, Runtime Orchestrator turn loop (Director → Departments → Commander → Reactions, with Tool Forge + LLM Judge + HEXACO Drift + AgentMemory side modules), Agent Swarm of personality-typed cells, and a Zod-validated RunArtifact that can be replayed byte-for-byte or forked at any past turn into divergent branches.


    "In all fictions, each time a man meets diverse alternatives, he chooses one and eliminates the others. In the work of Ts'ui Pên, he chooses, simultaneously, all of them."

    Jorge Luis Borges, The Garden of Forking Paths, 1941

    A world model that can be forked needs three things: a deterministic substrate that can be rewound, an LLM reasoner that can be replayed against the same state, and a contract for what state actually means. Paracosm carries all three. Snapshots are JSON, the kernel round-trips through JSON.stringify, and every fork resumes from the captured state without recomputing the prefix.

    import { WorldModel } from 'paracosm';
    import worldJson from './my-world.json' with { type: 'json' };

    const wm = await WorldModel.fromJson(worldJson);

    // Trunk run, snapshots captured at every turn
    const trunk = await wm.simulate(visionaryActor, {
    maxTurns: 6, seed: 42, captureSnapshots: true,
    });

    // Fork at turn 3 with a different actor; turns 1 to 3 are reused, not rerun
    const branch = await (await wm.forkFromArtifact(trunk, 3)).simulate(
    pragmatistActor,
    { maxTurns: 6, seed: 42 },
    );

    console.log(trunk.metadata.runId); // parent run id
    console.log(branch.metadata.forkedFrom); // { parentRunId, atTurn: 3 }
    console.log(trunk.fingerprint, branch.fingerprint);

    captureSnapshots defaults to false so that ordinary runs stay lean. The dashboard flips it on for every UI run; the Reports tab shows a fork button on each completed turn but the last, posts to /setup with the parent artifact (a fork runs in its parent's scenario, so a run loaded from another scenario's file shows a note to switch to that scenario instead of the buttons), and routes the new run into a Branches tab where forks accumulate as cards with per-metric deltas as they stream. Those buttons fork the session's trunk run: opening a branch card shows the Reports tab without moving them to that branch.

    const replay = await wm.replay(storedArtifact);
    console.log(replay.matches); // true when each between-turn step reproduces the state the run saved after it
    console.log(replay.divergence); // first path that differs, from the artifact's root, when matches=false

    With captureSnapshots: true the turn loop saves, beside each turn's end-of-turn snapshot, the state its first between-turn step starts from and the state right after each turn's step, before the turn's decisions move it. Replay restores the kernel from the state each step started from, re-runs the step (ageing, dose, deaths, births, food and morale), and compares the result with the state the run saved after it. It calls no model, so it is fast and free. It does not re-apply a turn's decisions. A run saved before the turn loop kept those snapshots gets a WorldModelReplayError saying replay cannot verify it, never a match or a mismatch (#235). What replay checks, what the seed fixes and what the model decides: FAQ.


    "We don't want to conquer the cosmos, we only want to extend the boundaries of Earth to the frontiers of the cosmos. We don't want other worlds; we want mirrors."

    Stanislaw Lem, Solaris, 1961

    By default a comparison in paracosm holds the scenario, the seed and the dice fixed and changes one thing. The commonest is the actor’s personality. A fork can also change the seed.

    Two simulation runs against an identical compiled scenario, starting from the same kernel state, produce divergent trajectories when the only thing that changes is the actor's personality. The kernel is reproducible. The divergence comes from the LLM stages reading a HEXACO profile and deciding accordingly. Both runs roll the same dice for the same person, so the people who die on one side and not the other are the ones whose world that run changed: a habitat that shields more of the dose, supplies held above what the colony landed with, morale that holds, a department that keeps them off the airlock. On Mars Genesis, which keeps one death die for each person and cause for a life, a person both sides lose dies no earlier on the side that gave them better chances in every year.

    Actors do not need to be people. The same authoring contract handles colony commanders, ship captains, AI release directors, governing councils, faction leaders, autonomous coordinators, or any entity whose decisions shape the world after a chain of inputs. Paracosm does not care what an actor represents. It cares how the actor decides.

    import { compileScenario, WorldModel } from 'paracosm';
    import worldJson from './my-world.json' with { type: 'json' };

    const scenario = await compileScenario(worldJson, {
    provider: 'anthropic',
    model: 'claude-sonnet-4-6',
    });
    const wm = WorldModel.fromScenario(scenario);

    const reyes = {
    name: 'Captain Reyes', archetype: 'The Pragmatist', unit: 'Station Alpha',
    hexaco: { openness: 0.4, conscientiousness: 0.9, extraversion: 0.3,
    agreeableness: 0.6, emotionality: 0.5, honestyHumility: 0.8 },
    instructions: 'You lead by protocol. Safety margins first.',
    };

    const okafor = {
    name: 'Captain Okafor', archetype: 'The Innovator', unit: 'Station Beta',
    hexaco: { openness: 0.9, conscientiousness: 0.4, extraversion: 0.8,
    agreeableness: 0.5, emotionality: 0.3, honestyHumility: 0.6 },
    description: 'Test one small change before expanding it.',
    };

    const [a, b] = await Promise.all(
    [reyes, okafor].map((actor) =>
    wm.simulate({ actor, maxTurns: 6, seed: 42 }),
    ),
    );
    console.log(a.fingerprint, b.fingerprint); // diverges visibly within two turns

    The library uses written leader orders as provided. Omit instructions or leave it blank to have Paracosm fill it from the leader's name, archetype, optional description and trait scores. The same inputs produce the same orders without a model call. All ten built-in leader presets include their own written orders.

    Each run carries a swarm of ~100 personality-typed agents (cells with departments, roles, mood, family edges, and persistent memory) on RunArtifact.finalSwarm. The dedicated paracosm/swarm subpath ships pure-projection helpers for the common shapes:

    import { getSwarm, swarmByDepartment, moodHistogram, departmentHeadcount } from 'paracosm/swarm';

    const swarm = getSwarm(a);
    if (swarm) {
    console.log(`T${swarm.turn} · ${swarm.population} alive · ${Math.round((swarm.morale ?? 0) * 100)}% morale`);
    console.log(moodHistogram(swarm)); // { focused: 12, anxious: 5, ... }
    console.log(departmentHeadcount(swarm)); // { engineering: 18, agriculture: 22, ... }
    console.log(swarmByDepartment(a)); // org chart with full roster per dept
    }

    Same data is on WorldModel.swarm(artifact) if you already have the WorldModel façade imported, and at GET /api/v1/runs/:runId/swarm for HTTP consumers. The dashboard's living-swarm grid streams the same shape per-turn via SSE.

    Six turns is enough to surface the contrast. The fingerprint is a stable hash over the trajectory, decisions, and final metrics, so two runs are easy to diff.


    WorldModel.fromPrompt compiles a scenario from seed source material (paste, URL, or extracted PDF text), and wm.quickstart then generates N contextual HEXACO actors and runs them in parallel. Both paths validate against DraftScenarioSchema and route into compileScenario. The canonical ScenarioPackage contract is never bypassed. The compiled scenario declares each score's start and range and the category tables its events use, so a run holds every score the scenario declares.

    import { WorldModel } from 'paracosm';

    const wm = await WorldModel.fromPrompt({
    seedText: 'Q3 board brief: the company must decide between...',
    domainHint: 'corporate strategic decision',
    });

    const { actors, artifacts } = await wm.quickstart({ actorCount: 3 });
    artifacts.forEach((a, i) => console.log(actors[i].name, a.fingerprint));

    Run is the default dashboard tab. It shows the loaded scenario, two leaders and their HEXACO scores and written orders, the colony's living grid at turn 0, and one Start button. Under it, Other scenarios loads another scenario, and Write your own scenario takes a pasted brief, a URL or a PDF, compiles it through the same path and runs it. A curated library of HEXACO archetypes ships at paracosm.ACTOR_PRESETS for programmatic wm.batch sweeps.


    npm install paracosm   # also: pnpm add paracosm · bun add paracosm
    

    Paracosm ships as pure ESM. The root export covers most use cases (run, runMany, WorldModel, compileScenario, marsScenario, lunarScenario, ACTOR_PRESETS, all public types). Subpath escape hatches are kept for power users: paracosm/compiler, paracosm/schema, paracosm/swarm, paracosm/digital-twin, paracosm/core. Node 22+, Bun 1.x, and any TypeScript runner with ESM and import-attributes support resolve them out of the box.


    The authoring contract is JSON because JSON validates, diffs, caches, and snapshots. A draft can be hand-written, generated from a prompt, or grounded with seedText / seedUrl.

    {
    "id": "submarine-habitat",
    "labels": {
    "name": "Deep Ocean Habitat",
    "populationNoun": "crew",
    "settlementNoun": "habitat",
    "timeUnitNoun": "day",
    "currency": "credits"
    },
    "setup": {
    "defaultTurns": 8,
    "defaultPopulation": 50,
    "defaultStartTime": 2040,
    "defaultSeed": 42
    },
    "departments": [
    {
    "id": "life-support",
    "label": "Life Support",
    "role": "Chief Life Support Officer",
    "instructions": "Analyze O2 levels, CO2 scrubbing capacity, water recycling."
    },
    {
    "id": "engineering",
    "label": "Engineering",
    "role": "Chief Engineer",
    "instructions": "Analyze hull integrity, pressure systems, power generation."
    }
    ],
    "metrics": [
    { "id": "population", "format": "number" },
    { "id": "morale", "format": "percent" }
    ]
    }

    Every scenario declares its own vocabulary via labels.populationNoun (plural), labels.settlementNoun (singular), and labels.timeUnitNoun. The dashboard, kernel, and progression hooks pick those up everywhere user-facing copy renders. Without overrides, paracosm falls back to colonists / colony / tick. labels.actorNoun names the leader (release director, CEO); the run's prompts say leader without it. A run carries only the metrics and politics its scenario declares in world, plus population and morale, so the kernel's Mars-heritage values (power, food, water, earthDependencyPct) stay out of the state, stream, outcome effects, prompts and saved runs of a scenario that does not declare them.

    Time is unit-agnostic. setup.defaultTimePerTurn and setup.defaultStartTime are plain numbers; whether they represent years, quarters, hours, or ticks is decided by timeUnitNoun. The dashboard turn header reads Quarter 5, Day 22, or Year 2043 straight from the label.

    Ages, experience and the kernel's yearly rates (births, deaths, partnerships, recovery, promotions) are in years. Between turns the kernel converts the elapsed units to years with setup.yearsPerTimeUnit, or, when the scenario declares none, with the length of the unit timeUnitNoun names: year 1, quarter 1/4, month 1/12, week 1/52, day 1/365, hour 1/8760, and 1 for any other word (tick, turn). A month of Atlas Lab ages its people a twelfth of a year and rolls a twelfth of a year's births and deaths; an eight-year Mars turn runs as eight one-year steps, so it ages its colonists eight years, gives the chances eight one-year turns give and settles the colony's morale once a year. Progression hooks get the step as timeDelta (the scenario's unit) and as yearsDelta, with yearsSinceStart and yearsPerUnit beside them.


    import { compileScenario, WorldModel } from 'paracosm';
    import worldJson from './my-world.json' with { type: 'json' };

    // First compile is roughly $0.10 and caches to disk; reruns are free
    const scenario = await compileScenario(worldJson, {
    provider: 'anthropic',
    model: 'claude-sonnet-4-6',
    });
    const wm = WorldModel.fromScenario(scenario);

    const result = await wm.simulate({
    actor,
    maxTurns: 6,
    seed: 42,
    // costPreset: 'economy', // ~5-10× cheaper iteration on OpenAI
    onEvent(e) { console.log(actor.name, e.type, e.data.summary); },
    });

    console.log(result.metadata.scenario.name, '→', result.fingerprint);
    console.log('cost $', result.cost?.totalUSD.toFixed(2));
    console.log('final ', result.finalState?.metrics);
    console.log('forged tools ', result.forgedTools?.length ?? 0);
    console.log('citations ', result.citations?.length ?? 0);

    Each call to wm.simulate takes one actor. The dashboard fans cohorts out side-by-side and auto-switches to a constellation view past 50; the API has no limit.

    git clone https://github.com/framerslab/paracosm
    cd paracosm && npm install
    (cd src/dashboard && npm install) && npm run dashboard:build
    cp .env.example .env # add OPENAI_API_KEY or ANTHROPIC_API_KEY
    npm run dashboard # opens http://localhost:3456

    The dashboard ships a scenario editor for writing, importing, compiling, and running custom worlds from the browser, plus the live Branches view for forks.

    Choose a scenario and two leaders on Run, then press Start. Watch shows the current crisis, both recorded decisions and figures from each colony's own grid. Use the colony switch to compare the two sides on a phone.

    Press Pause to hold the turn and its grids while the simulation continues. Use the run line or step keys to read turns that have arrived. Speed sets the reading pace, and Latest takes you back to the newest turn. Watch and Visualization share the chosen turn. At the verdict, use Play from turn 1 to review the run or open Reports to read the run log.

    Stop asks for confirmation and leaves the turns that already arrived playable on that page. On a phone using the free run, find Stop the run in the run actions menu. A saved replay plays recorded events without calling a model. Use Leave the replay to return to Watch.

    npm install -g paracosm

    paracosm run # actors.json + default scenario
    paracosm run --name "Reyes" --openness 0.85 --turns 6
    paracosm dashboard 6 # auto-launch with 6 turns
    paracosm compile scenarios/lunar.json --seed-url <url> --max-searches 5
    paracosm init my-app --domain "Submarine crew of 8" --actors 3

    The CLI looks for actors.json via --actors, then ./actors.json, then ./config/actors.json, then a bundled example. --name renames the chosen actor, and its written orders take the new name wherever they name the old one. A back-compat paracosm-dashboard alias is shipped for existing scripts and Docker invocations.

    The dashboard ships two ways to produce a shareable run link, both landing the viewer on the Visualization tab with no upload step.

    From the dashboard UI — four places copy paracosm.agentos.sh/sim?replay=<sessionId>&tab=viz to the clipboard:

    • Share viz link in the header's run actions menu, while a run is open and has a saved replay.
    • Share viz link in a run's detail drawer. Open Library from More, then open the run.
    • Copy viz share link on a leader's results card in Run.
    • Share on a Library row whose replay was linked when the run was saved.

    All four routes hit the public /sessions/:id/replay SSE endpoint so the viewer streams the stored run directly. Anyone who has the link and can reach the dashboard that made it can watch the run; a link made on a dashboard served at localhost opens only on that computer. Every one of these keys shows the link in a field after the press, with whether it was copied and who can open it; when the browser refuses the clipboard or does not answer within three seconds, the note says so and the link stays in the field to copy by hand.

    By URL construction — any remote .json save can be turned into a deep link that fetches, parses, and lands on the tab you choose. No upload step, no preview modal. A file on another site than the dashboard's is fetched after the viewer answers one question that names that site.

    https://paracosm.agentos.sh/sim?load=<remote-json-url>&tab=viz&autoload=1
    
    Param Required Behaviour
    load yes URL of the remote .json save. Must be http: or https: and CORS-readable. Pastebins, gists, S3, GitHub raw all work.
    tab no Tab to open after the run loads. sim (default), viz, reports, chat, library, settings, studio. Invalid values fall back to sim.
    autoload no 1 or true skips the F9 preview modal and confirms the load automatically. Omit to show the preview confirm step. A file on another site still asks the question naming that site first.

    Concrete share links:

    # r/dataisbeautiful drop — opens straight on the swarm viz
    paracosm.agentos.sh/sim?load=https://gist.githubusercontent.com/<user>/<id>/raw/mars-run.json&tab=viz&autoload=1

    # Linked from a bug report — opens the reports tab with preview shown
    paracosm.agentos.sh/sim?load=https://example.com/runs/diverged-run.json&tab=reports

    The ?load= and ?autoload= params are stripped after the fetch resolves, so refreshing the page won't re-download. ?tab= is kept so the URL survives copy/paste. Cross-origin fetches require the host to send permissive CORS headers (Access-Control-Allow-Origin: * on Gists, S3 with the right bucket policy, etc.).


    Every simulation returns a RunArtifact: one Zod-validated shape exported from paracosm/schema. The same shape covers civilization sims (turn-loop), digital-twin runs (batch-trajectory), and one-shot forecasts (batch-point). New results expose artifact.provenance with aiGenerated, generator, and models by role.

    import { RunArtifactSchema, type RunArtifact } from 'paracosm/schema';

    const wm = WorldModel.fromScenario(scenario);
    const artifact: RunArtifact = await wm.simulate({ actor, maxTurns: 6 });
    const parsed = RunArtifactSchema.parse(artifact); // optional dev-mode validation

    switch (artifact.metadata.mode) {
    case 'turn-loop': // civ sims: per-turn trajectory + decisions
    case 'batch-trajectory': // digital twin: labeled timepoints over a horizon
    case 'batch-point': // one-shot forecast: overview + risk flags
    }

    Run JSON, the first replay event, and HTML, PDF and PNG run exports carry provenance. Older files can be read without the field. In the dashboard and HTML reports, each model-written block carries data-ai-generated="true". A page with model-written content has one ai-generated-content meta tag. Human-written text stays unmarked.

    The dashboard shows a disclosure before Start and one at the top of each chat. HTML and PDF reports show one disclosure under the title when a passage is model-written.

    For non-TypeScript consumers, npm run export:json-schema emits schema/run-artifact.schema.json and schema/stream-event.schema.json. Python projects generate Pydantic types via datamodel-codegen; any ecosystem with a JSON-Schema generator adopts cleanly.


    For simulations that revolve around a single subject under an intervention, paracosm exposes a DigitalTwin subpath plus SubjectConfig and InterventionConfig as first-class input primitives. The subject can be a persona: a person with a HEXACO personality, a profile and conditions, with a product change as the intervention.

    import { DigitalTwin } from 'paracosm/digital-twin';
    import { SubjectConfigSchema, InterventionConfigSchema } from 'paracosm/schema';

    const twin = await DigitalTwin.fromJson(scenarioJson);

    const subject = SubjectConfigSchema.parse({
    id: 'persona-dana',
    name: 'Dana Okafor',
    profile: { age: 31, job: 'shift nurse', device: 'phone', sessionMinutes: 10 },
    personality: {
    openness: 0.72, conscientiousness: 0.4, extraversion: 0.3,
    agreeableness: 0.66, emotionality: 0.58, honestyHumility: 0.61,
    },
    conditions: ['uses the product in short breaks', 'new to tools of this kind'],
    });

    const intervention = InterventionConfigSchema.parse({
    id: 'three-step-setup',
    name: 'Three-step setup',
    description: 'First use asks three questions in place of twelve and offers a worked example.',
    category: 'product change',
    mechanism: 'A shorter first session lets a new person reach a first result before a break ends.',
    targetBehaviors: ['finishes setup', 'returns the next day'],
    duration: { value: 7, unit: 'days' },
    adherenceProfile: { expected: 0.9, risks: ['skips the worked example'] },
    });

    const treated = await twin.intervene({ subject, intervention, actor, maxTurns: 4, seed: 11 });
    // The control arm: the same subject, actor and seed, with no intervention.
    const baseline = await twin.simulate({ subject, actor, maxTurns: 4, seed: 11 });

    DigitalTwin is an alias of WorldModel. The subpath names the use case in the import path. The run's departments read the subject and the intervention in their system text, the actor in each decision request (its session keeps the block once, and a later decision prompt names them in one line) and the Event Director in each prompt it is sent; the run's start (the actor's system text, its opening message and the promotions) reads neither, so both arms start alike. RunArtifact.subject and RunArtifact.intervention record them, and scenarioExtensions.paracosmInternal.twinContext holds the block the models were sent. A fork applies only the subject and intervention its own call passes.


    Actors are not always human. Paracosm ships a TraitModel registry with two built-ins, and registering more is one call.

    Model Axes For
    hexaco openness, conscientiousness, extraversion, agreeableness, emotionality, honesty-humility CEOs, captains, governors, councils, military commanders
    ai-agent exploration, verification-rigor, deference, risk-tolerance, transparency, instruction-following Frontier-lab release directors, autonomous coordinators, eval subs
    import { WorldModel } from 'paracosm';

    const releaseDirector = {
    name: 'Atlas-Bot Release Director',
    archetype: 'Aggressive AI Release Optimizer',
    unit: 'Frontier Lab',
    // hexaco is optional when traitProfile is set; a representative
    // snapshot is also accepted.
    traitProfile: {
    modelId: 'ai-agent',
    traits: {
    exploration: 0.85,
    'verification-rigor': 0.2,
    deference: 0.2,
    'risk-tolerance': 0.85,
    transparency: 0.4,
    'instruction-following': 0.4,
    },
    },
    instructions: 'You weight time-to-market. Verification is overhead.',
    };

    const wmAi = WorldModel.fromScenario(scenario);
    await wmAi.simulate({ actor: releaseDirector, maxTurns: 6, seed: 42 });

    The orchestrator's normalizeActorConfig accepts either shape. End-to-end captures and full surface live in docs/COOKBOOK.md.


    Running a simulation calls real LLM APIs against the user's key. Paracosm assigns a different model tier per role so flagship cost only lands where it earns its keep (forge-code correctness).

    Preset Departments Commander · Director · Judge Reactions OpenAI / run Anthropic / run
    quality (default) gpt-5.4 · claude-sonnet-4-6 gpt-4o (commander), gpt-5.4-mini (director, judge) · claude-haiku-4-5-20251001 gpt-5.4-nano · claude-haiku-4-5-20251001 ~$1 to $3 ~$3 to $7
    economy gpt-4o · claude-sonnet-4-6 gpt-5.4-nano · claude-haiku-4-5-20251001 gpt-5.4-nano · claude-haiku-4-5-20251001 ~$0.20 to $0.60 ~$3 to $5

    Numbers assume 6 turns, 5 departments, 100 agents, up to 3 events per turn. Forge approval rate drops 10 to 20 points on economy because the mid-tier department model occasionally violates structured-output schemas the judge rejects. Use economy for iteration and CI; use quality for publishable runs. Explicit models entries always win over the preset, so per-role overrides combine cleanly with global defaults.

    WorldModel.simulate returns a cost field with the run's USD spend and its LLM call count; it leaves the token counts empty. Stable system prefixes (the director's instructions, the department prompts) route through a cacheBreakpoint: true block, so on Anthropic the shared prefix serves from prompt cache at one-tenth input cost from turn 2 onward once it reaches the model's minimum (4,096 tokens on Claude Haiku 4.5, prompt caching); OpenAI caches a prefix on its own once it reaches the model's minimum (1,024 tokens on GPT-5.6 and later, set by the request on earlier models, prompt caching). The cost payload on each streamed event (_cost) carries the tokens, the prompt-cache reads and writes, and the USD the cache saved, per stage.


    Director event → Kernel advance (deterministic, seeded) → Department analysis in parallel (with optional runtime tool forging, each call in a QuickJS WebAssembly instance of its own; an LLM judge approves each forge) → Commander decision (HEXACO-weighted) → Outcome classification → Kernel effects → Agent reactions → Memory consolidation → Personality drift.

    Every structured LLM call (director, departments, commander, reactions, verdict) is Zod-validated with retry-with-feedback. Schemas under src/runtime/validators/. Full per-stage breakdown in docs/ARCHITECTURE.md.


    paracosm compile <scenario.json> --seed-text "..." or --seed-url <url> extracts topics, searches across Firecrawl + Tavily + Serper + Brave in parallel, reranks with Cohere rerank-v3.5 when COHERE_API_KEY is set (Cohere picks the best three of every result the providers return for a query), ingests the result into an AgentOS AgentMemory.sqlite() store, and threads citations into department prompts. Bundle cached per-seed. Surface citations land in the dashboard's Reports tab.


    marsScenario (100 colonists, 6 turns over 48 years; 5 departments) and lunarScenario (50-person south-pole crew; regolith + 1/6g) ship from the paracosm root as references for custom scenarios.

    Programmatic surfaces: paracosm root (run, runMany, WorldModel, compileScenario, createParacosmClient), plus paracosm/{compiler,schema,swarm,digital-twin,core} for deeper paths. Provider / preset / model defaults can be pinned per client or via PARACOSM_* env vars. Full reference + every method signature: docs/COOKBOOK.md.

    For non-SSE consumers there's POST /simulate (gated on PARACOSM_ENABLE_SIMULATE_ENDPOINT=true) and nine read-and-replay routes under /api/v1/*. Wire-level details: docs/HTTP_API.md.

    Storage: SQLite through @framers/sql-storage-adapter (better-sqlite3, or sql.js when the native module cannot load). Run history (Library) lives in data/runs.db under APP_DIR, the working directory when unset (PARACOSM_RUN_HISTORY_DB_PATH moves it), and saved sessions (Load menu) in data/sessions.db; STORAGE_ADAPTER and DATABASE_URL have no effect on either. Admin write routes (/admin/sessions/save, /admin/data/wipe, DELETE /admin/scenarios/:id, POST /scenarios/:id/rename) and the disk write of POST /scenario/store (saveToDisk: true) require both ADMIN_WRITE=true and an ADMIN_TOKEN bearer in the X-Admin-Token header; off by default. With ADMIN_WRITE=true the dashboard's Settings tab shows an Admin Token field, where an operator enters the token once for that browser. The dashboard sends it on Save to Disk, Delete server data, and a scenario's Rename and Delete; Clear local data clears the browser's cached data and lets go of that browser's own run on the server, stopping it when it is running; run history, saved sessions and output files are kept.


    src/
    index.ts the package root: run, runMany, WorldModel, compileScenario,
    the built-in scenarios, trait models, presets and types
    api/ run() and runMany()
    engine/ scenario contract, compiler and deterministic kernel
    core/ kernel: seeded RNG, state, snapshots, progression (paracosm/core)
    compiler/ scenario draft + source grounding to ScenarioPackage (paracosm/compiler)
    schema/ RunArtifact types and Zod schemas (paracosm/schema)
    digital-twin/ WorldModel as DigitalTwin (paracosm/digital-twin)
    scenarios/ loads Mars Genesis and Lunar Outpost from scenarios/*.json
    data-driven-hooks/ turns a scenario's JSON hooks into runtime hooks
    physics/ per-agent progression physics a scenario names in its JSON
    traits/ trait models: HEXACO and the AI-agent model
    registries/ effects, events and metrics
    presets/ actor presets
    provider/ provider key resolution

    runtime/ simulation execution
    orchestrator/ turn pipeline: event director, departments, commander, reactions
    agents/ agent reactions, memory and post-run chat
    world-model/ the WorldModel facade: simulate, replay, fork, intervene, batch
    swarm/ views over a run's agent swarm (paracosm/swarm)
    research/ citation and research memory
    validators/ Zod validators for LLM responses
    economics/ cost tracking and pricing
    io/ output writer, artifact assembly, SSE envelopes
    util/ parsers and shared helpers

    llm/ validated LLM calls shared by the runtime and the compiler
    cli/ the paracosm command
    server/ the dashboard's HTTP and SSE server
    dashboard/ the React + Vite dashboard at /sim, and the landing page

    docs/architecture/INTERNAL_LAYOUT.md describes each folder.

    The engine owns the chassis. The scenario owns the domain. The kernel handles state, time, randomness, and invariants. The scenario handles event categories, department instructions, progression hooks, and research citations. The orchestrator connects them.


    "You are not the kind of dead that can be brought back."

    SOMA, Frictional Games, 2015

    Paracosm uses AgentOS for agent orchestration, LLM dispatch, tool forging, and memory. The composition is what makes the runs feel inhabited rather than scripted: department heads remember, specialists invent tools mid-decision, and the LLM judge holds the line on safety before any forge enters the pipeline.

    AgentOS API Used for
    agent() Commander, department, and Event Director agents
    generateText() LLM calls for event generation and tool evaluation
    EmergentCapabilityEngine Runtime tool forging; forged code runs in AgentOS's QuickJSExecutor
    EmergentJudge LLM-as-judge safety review of forged tools
    WebSearchService Multi-provider seed enrichment with Firecrawl, Tavily, Serper, Brave
    AgentMemory Per-run citation memory with full-text recall

    Hosted demo Your own install (Apache-2.0)
    Where paracosm.agentos.sh/sim, in the browser, without an account. Your machine or server: npm install paracosm for the SDK and the CLI, paracosm dashboard for the same dashboard at http://localhost:3456. To reach it by another name (a LAN name, a server behind a proxy), list the name in PARACOSM_ALLOWED_HOSTS, and from another machine also set HOST=0.0.0.0.
    Model keys The host's keys, or your own OpenAI or Anthropic key entered in Settings. Your own keys, from the environment or a .env file.
    Limits Runs on the host's keys are capped in turns, population, departments and leaders (two), and each IP address has a daily run limit, which a Digital Twin run also counts against. Quickstart compiles count against a daily compile limit, and its grounding, actor and URL requests against a daily limit of their own. Your own key lifts the run caps and the run limit for a run you start (a Digital Twin run takes no key, so it always counts); live search there runs only on search keys you bring. No hosted quotas: the SDK and paracosm run cap no turns, population, departments or daily runs. The API has its own bounds: runMany() and WorldModel.quickstart() take 2 to 6 actors and throw outside that range, run() runs two and returns the first, and a dashboard run takes 2 to 300 actors (a fork takes 1). The dashboard server limits runs on its own keys to RATE_LIMIT per IP address per day (1 when unset); RATE_LIMIT=0 turns the limit off.
    Cost Free to try. Free. You pay your model provider for the runs you make.
    Support Community via Discord and GitHub. Community via Discord and GitHub.

    Commercial, partnership and sponsorship inquiries go to [email protected].


    Live demo paracosm.agentos.sh/sim
    Landing page paracosm.agentos.sh
    API docs paracosm.agentos.sh/docs
    HTTP API docs/HTTP_API.md
    Cookbook docs/COOKBOOK.md
    FAQ docs/FAQ.md: dice, models, seeds, replay and forks
    npm npmjs.com/package/paracosm
    AgentOS agentos.sh
    Discord wilds.ai/discord
    Guide What
    Contributing Development setup, commit and pull request rules, review threads, contribution licensing
    Releasing and deploying What a merge to master deploys and when npm publishes
    Agent instructions Commands and conventions for coding agents
    Code of Conduct Community standards
    Security Policy Reporting vulnerabilities privately
    Support Where to get help

    Apache-2.0

    The landing page, the dashboard and the API docs load their fonts from the site itself: Inter and JetBrains Mono, in assets/fonts/, from the @fontsource-variable/inter and @fontsource-variable/jetbrains-mono packages. Both fonts are under the SIL Open Font License 1.1; the licence texts are assets/fonts/LICENSE-Inter.txt and assets/fonts/LICENSE-JetBrains-Mono.txt.


    Built by Frame.dev
    [email protected]