Simten

Architecture

How circuits go from text to simulation

Why there's a sandbox

User-defined circuit code is arbitrary TypeScript, such as circuit('Foo', { eval: ({ a, b }) => ... }). Running it in the main React frame would let a malicious circuit read auth cookies, hijack the chat session, or escape into the editor's tab. Instead, every circuit you compile or simulate runs inside a cross-origin iframe (sandbox.simtenusercontent.dev). Origin isolation keeps it away from the page's cookies, storage and DOM, and the sandbox's CSP limits its network access to esm.sh, for npm imports. See Security.

This is the same pattern CodePen uses to isolate user-authored snippets from their editor app: preview runs on a separate origin (cdpn.io) inside a sandboxed iframe, talking to the host page via postMessage only. Everything you'll see called "sandbox" in the Simten codebase is one side of that bridge or the other.

Runtime topology

The four layers a circuit flows through in the browser:

LayerFileResponsibility
Public hookpackages/react/src/sandbox/useSimulation.tsWhat the canvas, blog demos and docs call. Compiles, opens a session, and mirrors its state into React: state, and actions such as set, tick, stepBack and run.
Sandbox client (page)packages/sandbox/src/sandbox-client.ts, simulation-client.tsThe hidden iframe, request ids, and SimulationClient, an async mirror of core's Simulation that forwards each call as a message. No React.
Sandbox iframeapps/sandbox/src/main.ts, worker.tsThe other side of the bridge. Runs inside the iframe (cross-origin). The iframe's main thread relays postMessage commands to a Web Worker, which runs user code and every simulation (SessionHost), and restarts the worker if it hangs.
Simulator enginepackages/core/src/simulator/Pure computation, with no iframe and no React. Used by the iframe app for browser sims; used directly by simulate() from @simten/core for Node/CI scripts.

Direction of calls (browser path):

useSimulation → SandboxClient / SimulationClient → [postMessage / iframe boundary] → apps/sandbox/main.ts → worker.ts → SessionHost → core Simulation

If you're writing a vitest property test or a CI fuzzer, you skip the bridge entirely and just import simulate from @simten/core and drive the circuit directly. See "Two ways to run a circuit" below.

From TypeScript to Simulation

When you define a circuit, it goes through six stages before anything appears on screen:

1

Build

circuit() calls → Circuit IR

The TypeScript circuit() builder collects node types, port declarations, and connection calls. The .to() wiring calls produce a declarative connection list. The result is a Circuit, whose .circuit is the CircuitIR: a plain data structure describing the circuit's structure.

2

Validate

Check for errors before running

Four validation phases run in order: syntax checks, semantic checks (duplicate names, unknown references), type checks (bus width matching), and structural checks (cycle detection via Tarjan's SCC, floating ports).

3

Compile to IR

AST → Circuit objects

The AST is compiled into Circuit objects, the system's universal representation. Both primitives and composites share the same interface: ports, connections, nodes, parameters.

4

Elaborate

Flatten composites to primitives

Composite circuits are recursively expanded. A FullAdder becomes two Xor, two And, and one Or. Connections are stitched through composite boundaries. The result is a FlatCircuit: only primitives, no hierarchy.

5

Compile to numeric

Typed arrays for fast simulation

Node IDs become array indices. Port connections become index lookups. Each primitive gets mapped to an evaluator function via a dispatch table. The result is a NumericCircuit, with zero string operations in the hot path.

6

Simulate

Event-driven propagation

An event queue drives evaluation. When a node's output changes, its dependents are enqueued. Propagation continues until no more changes occur. For sequential circuits, a 5-phase tick cycle handles clock edges and state updates.

See the Simulator Engine page for deep details on the numeric compilation and tick cycle.

Circuit IR

Everything in the system (primitives, user circuits, elaborated results) uses the same CircuitIR interface. It's internal: the Circuit that circuit() returns shows only its name, inputs and outputs, and carries its IR alongside.

interface CircuitIR {
  name: string;
  inputs: PortDescriptor[];
  outputs: PortDescriptor[];
  clocks: ClockDescriptor[];
  state: StateBlock[];
  nodes: Node[];
  connections: Connection[];
  implementation: { kind: 'primitive' } | { kind: 'composite' };
}

Primitives have evaluator functions registered against them. Composites are purely structural: they define what to connect, not how to compute. The elaboration step removes all composites, leaving only primitives.

Simulation Model

Combinational circuits

No clock, no state. Inputs change → outputs update immediately.

  1. Seed the event queue with source nodes (constants, switches, inputs)
  2. Evaluate each node, detect output changes, enqueue dependents
  3. Repeat until the queue is empty (the circuit has stabilized)

Sequential circuits

Each clock tick executes five phases:

Phase 1
Propagate

Evaluate all combinational logic with current state. Capture port values; this is what the API returns.

Phase 2
Clock

Set all clocks to rising edge.

Phase 3
Compute next state

For each sequential node, compute what the next state should be based on current inputs and clock edges.

Phase 4
Commit

Atomically copy next state → current state for all nodes. Increment cycle count. All updates appear simultaneous.

Phase 5
Re-propagate

Propagate the committed state through combinational logic. Prepares internal values for the next tick.

The atomic commit in Phase 4 is what makes this match real hardware: all flip-flops and registers update at the same instant, just like a physical clock edge.

Simulation

simulate(top) returns a Simulation: the engine plus the typed port interface, the clock and, when asked for, history. It is synchronous, has no timers and holds nothing that needs releasing.

┌──────────────────────┐
│  test, verify file,  │
│  MCP, sandbox worker │
└─────────┬────────────┘
          │ set / get / tick / stepBack
          ▼
┌──────────────────────┐
│     Simulation       │  ports, cycle, history
└─────────┬────────────┘
          │ tick / restore / setNode
          ▼
┌──────────────────────┐
│   SimulatorEngine    │  pure computation (no React, no UI)
└──────────────────────┘

A set marks the logic dirty and the next read settles it, so get after set returns the settled value and a set followed by tick costs nothing extra.

Time-travel

simulate(top, { history: n }) keeps the last n steps; the default is 0, no history. Each tick call records one snapshot, so tick(100) is one step back. Navigation is index-based:

  • stepBack() / stepForward(): move one step
  • seek(index): jump to any recorded step
  • Ticking while viewing the past truncates forward history (linear, no branching)

Each returns false, and changes nothing, when there is nothing to step to. Snapshots carry the top-level inputs and Switch/Input values, so a rewind puts the switches back too.

sim.set takes the circuit's inputs as a person at the board sees them: input ports by name and Switch and Input nodes by path (d, cpu.kbd), all written before the circuit settles. A key that names anything else, or both a port and a Switch, throws. simulate(top, { memory }) loads memory contents by node path before cycle 0.

Simten's own code reaches other internal nodes through nodesOf(sim) in @simten/core/internal: set(path, value) writes any node by dotted path, ports() reads every port value, peripherals() reads the state of screens, consoles and the memories wired to them, and advance(n) followed by record() ticks in slices and records the whole run as one step.

Auto-run

In the browser, auto-run runs in the sandbox worker. actions.run(speed) starts a loop next to the engine, which ticks in slices of about 80% of a frame and pushes the latest state to the page 30 times a second without waiting for a reply. The RISC-V CPU can run at ~20,000 ticks/sec while the UI updates at 30fps, so the engine does ~667 ticks per frame. Each frame is one history step. simulate() has no auto-run; in Node, call tick in a loop.

setInput and setNode

The engine takes top-level inputs and nodes separately. engine.setInput(name, value) drives a top-level input by its name. engine.setNode(path, value) writes a node by its exact path (cpu.imem, not imem) and dispatches on the node's type:

  • Switch/Input/Button → sets arguments.value (combinational)
  • ROM/RAM/Register → sets sequential state directly

A name that isn't one of the two throws, and an input name isn't a node path. Simulation.set resolves each key to one or the other; nodesOf(sim).set writes nodes. ROM data written with setNode persists across reset (like real hardware, where flash survives a power cycle).

In the browser, the page can only set input ports and Switch and Input nodes (SimulationClient.set, the same rules as Simulation.set). A program goes into memory when its session opens (memory in open's options).

Packages

@simten/core       ← headless: circuit builder, compiler, simulator
       ↑
@simten/sandbox    ← the sandbox from any page, no framework
       ↑
@simten/react      ← React: useSimulation, canvas, clock controls, code editor
PackageDescription
@simten/coreTypeScript builder, compiler, validator, simulator engine, Simulation, environmental state, Verilog export. No UI dependencies.
@simten/sandboxThe sandbox without React: SandboxClient and SimulationClient for pages, and the worker's session host, the iframe's relay and inProcessSandbox() for tests. Depends on core.
@simten/reactReact: useSimulation, SandboxProvider, CircuitCanvas, ClockControls, and the code editor. Depends on core and sandbox.
@simten/mcpMCP server for Claude Code integration

The library gives you data, input and output, and the apps arrange them (decision 0010). The cards around circuits on simten.dev, the embed page's view and the game's dialogs are app code; what the apps share (UI primitives, share links, the Fork button, the theme) is in @simten/shared, a private workspace package that isn't published.

The split follows Sandpack's sandpack-client and sandpack-react: everything that isn't React lives in core and sandbox, so a Vue or Svelte layer would sit on @simten/sandbox the same way. A page that isn't an app embeds the iframe from Share → Embed and needs no package. See Using Simten without React.

Hooks

One hook, useSimulation, compiles and simulates. Give it a circuit built on the page (blog posts, docs) or source text (the editor, the embed page). It compiles in the sandbox, opens a session on the chosen circuit, and subscribes to it. The session's history, ticking and auto-run all run in the sandbox worker; the hook keeps no timers.

CallInputUsed by
useSimulation(circuit, options)Circuit built on the page, sent as IR plus behavior as text (compile-ir)the site's circuit cards, landing page, blog demos, docs demos, the RV32I debugger
useSimulation({ source, circuit? }, options)source textthe editor, the game's level page and map drilldown, the embed page
useSandboxClient()source textcode that compiles without simulating: the game's grader, the docs pipeline visualizer

options takes initialInputs, history (200 steps by default) and memory (contents by node path, loaded before cycle 0; a new object opens a new session, as loading a program does on real hardware). The page can write only input ports and Switch and Input nodes, by name or path (actions.set).

The session runs the circuit itself, so state.portValues has the circuit's own ports by name (sum) and its nodes' by path (ha1.x.out). The canvas draws a circuit with ports with a Switch or Input on each input port and a lamp or display on each output, named after the ports, around the circuit as one box that shows the circuit's name (ports-view.ts). A layout places the box by the key circuit. Only the drawing has those nodes: their values come from the circuit's ports, a click on a is set({ a }), and the drill-down into the box reads the circuit's insides.

Every useSimulation on a page shares one sandbox, created by the first, and each opens its own session in it, so circuits don't share state. The nearest SandboxProvider above a hook overrides that: with a client, it uses that client; without one, its subtree gets a sandbox of its own.

The drill-down inspector is a view of the simulation the canvas is showing. It draws a composite from its definition and reads its values from the same session's port map by dotted path (ha1.x.out), so it shows the same cycle as the canvas and moves with it while auto-run is on. It writes nothing: a composite's input ports are drawn as indicators, not switches. A primitive's gate-level reference build (MADE_OF, an Adder drawn as full adders) isn't in the running circuit, so while its frame is open it runs as a second session in the same sandbox, fed the primitive's input values from the first.

The editor's Verilog export runs in the sandbox too (actions.exportVerilog()), with the compile's own behavior, so a design exports the same in the browser as headless.

Data flows one direction, from the compiled circuit to the sandbox to the UI:

circuit() or source text
          ↓
   useSimulation → sandbox iframe → worker (SessionHost, Simulation)
          ↓
   { state, actions }
          ↓
   CircuitCanvas (rendering)

Editor state

The editor holds the source text and passes it to useSimulation. The canvas draws the session's own circuit (state.circuit). Its top-level node ids are the names set takes (a port's switch is named after the port, and a circuit without ports isn't wrapped), so a click, a program upload and the keyboard all address nodes by those ids. A program loaded on an instruction memory goes in through the memory option, so loading or clearing one starts a new session at cycle 0.

Import paths

ImportContents
@simten/corecircuit, bit, bus, simulate, Circuit: the public API. Components come from @simten/core/std
@simten/core/internalelaborate, createEngine, createSimulation, nodesOf, SimulatorEngine, the IR types (CircuitIR), a built circuit's internals (internalsOf), libraries of definitions and behavior (libraryOf), executeCircuitCode, captureEnvironmentalState, restoreEnvironmentalState: for Simten's own packages, no stability promise
@simten/sandboxSandboxClient, SimulationClient: the sandbox from any page, no framework
@simten/sandbox/hostThe worker side (SessionHost, createRelay) and inProcessSandbox() for tests
@simten/reactuseSimulation, SandboxProvider, useSandboxClient, CircuitCanvas, ClockControls
@simten/react/code-editorCodeEditor, setupSimtenIntellisense, useTypeAcquisition, registerSimtenThemes: Monaco with circuit IntelliSense. See Code Editor
@simten/react/styles.cssThe stylesheet, with the theme as CSS variables

The node components, layout and drill-down are how CircuitCanvas works, and aren't exported.

Two ways to run a circuit

The same engine powers two distinct consumption paths. The split is interactive vs programmatic, not "prototyping vs production":

PathWhere it runsHas a canvas?Drives the canvas?Typical use
SandboxBrowser worker (editor, CircuitCanvas, embed pages)yesonly via human clickslive editing, interactive embeds, viewing what an assistant built
ScriptNode (tsx, vitest, CI)non/a, there is noneproperty tests, fuzzers, batch sweeps, CI verification

Sandbox path

When user code runs inside the editor or an embed, it goes through the sandbox iframe + worker (see Security). Code in this path defines circuits; a person at the canvas drives them, by flipping a switch or pressing run. The MCP's show_circuit only pushes a circuit to the canvas, with the inputs and memory its run starts from; nothing reads the canvas back. User code itself currently has no API to drive the canvas simulator. The canvas sim and user code share the sandbox worker, but a user-code simulate(...) call would still create a separate instance instead of moving the canvas; wiring it to the canvas slot is what self-animating embeds would need.

Script path

Outside the browser there's no sandbox, no canvas, and no boundary to route through. Import @simten/core directly:

import { circuit, bit, simulate } from '@simten/core';

const Counter = circuit('Counter', { ... });
const sim = simulate(Counter);
sim.set({ reset: 1 });
sim.tick();
// run property tests, fuzzers, sweeps at full engine speed

This is the path for any code that needs to drive simulation programmatically, whether that's a vitest property test you're writing during prototyping or a CI fuzzer comparing the TS sim to iverilog. There's nothing for it to be out of sync with, so the constraints that apply in the browser don't apply here.

A blog-post circuit card is "production" but uses the sandbox path. A throwaway vitest exploration is "prototyping" but uses the script path. The axis that matters is whether there's a canvas and whether human/LLM input drives it, not how finished the code is.

MCP Integration

The MCP server drives a viewer in the browser: Claude Code calls MCP tools, and the server pushes the results over a WebSocket for display and in-browser simulation. The browser is display-only: it sends back nothing but a render acknowledgment.

Claude Code (terminal)
↕ MCP tools (stdio)
MCP Server (localhost)
↓ WebSocket push
Browser App
DirectionMechanismExamples
Claude → BrowserWebSocket pushThe circuit, with the inputs and memory its run starts from
Browser → ClaudeRender acknowledgmentBoolean ack that a pushed circuit rendered

The browser viewer is intentionally one-way: it accepts nothing actionable back, so a rendered page can't drive Claude or read its state. The MCP server provides tools, not inference; users bring their own Claude subscription. Zero AI API cost for the app developer.

See the MCP Integration guide for setup and available tools.

On this page