Pular para o conteúdo principal
R

rotifer-playground (rotifer)

rotifer-protocol/rotifer-playground/plugins/rotifer

Skills do Rotifer Protocol e servidor MCP Rotifer configurados como instâncias do provedor de skills e cliente MCP nativos do DSH: pesquisar Genes, compará-los no ranking Arena, instalar ou reverter Genes no projeto local e criar/executar Agents locais. O servidor MCP tem versão fixada e se limita ao conjunto de ferramentas evolve, sem publicação nem login.

Instalar

dsh plugin --profile web add github:rotifer-protocol/rotifer-playground

Este plugin está no subdiretório plugins/rotifer do repositório.

README

Rotifer Playground

CI npm License: Apache-2.0 Node.js Protocol Discord

Development environment for the Rotifer Protocol — WASM-Native, Polyglot by Design: build genes in TypeScript / Rust / AssemblyScript / Go / C, compete in Arenas, share via Cloud, and simulate agent evolution.

Status: v0.41.x — The experimental P2P node now records when each announcement reached it. On the node's local control API, every record from GET /received has receivedAtMs: the time, by this node's clock, it first received that announcement. That lets you measure how long announcements take to spread. rotifer network received prints the same list as before, and what nodes send each other is unchanged. The Rotifer project now runs two public nodes, each a bootstrap node and a relay, with their addresses on rotifer.dev. The CLI does not connect to them on its own: its default bootstrap list is still empty, so pass them with -b or put them in bootstrap_peers. This repository also has tools for load-testing many nodes at once, in deploy/loadtest/; they are not part of the npm package and do not change the CLI. Still true from v0.40: this repository has a deployment package and runbook for running a public P2P bootstrap and relay node on your own Linux server, in deploy/p2p-server/: systemd units, a firewall with per-IP connection limits and a 1 MB/s outbound cap, a monthly outbound quota, and upgrade and rollback scripts. Its installer installs the pinned release from the npm registry with signatures checked, and refuses a lock file in which any package comes from anywhere else or has no integrity hash. The package is not part of the npm package and the CLI is unchanged: nothing changes for anyone who only uses the CLI. Still true from v0.39: the experimental P2P node now asks before it first connects. rotifer network start shows what the node connects to and what peers can see, and starts only after you answer yes; a no starts nothing and saves nothing, not even a node key. Scripts, CI and --json runs are never prompted: they need --accept-p2p or an earlier yes at a terminal, and otherwise exit 1 without connecting (P2P_CONSENT_REQUIRED). rotifer network consent prints the notice (--show), records or withdraws consent (--accept, --revoke; revoking also stops a running node) and reports it (--status). A node can now act as a Circuit Relay v2 relay for peers behind NAT, but only when started with --relay-server and its public IPv4 address in --announce; the role is off by default, and reservations and circuits have built-in limits. rotifer network start also takes --relay to hold a reservation on a relay, --max-inbound and --max-pending to cap connections, and --foreground to run under a service manager such as systemd. rotifer network status honours --json and only reads: it no longer writes ~/.rotifer/network.json. The default bootstrap list is empty: the node uses the official nodes (see v0.41 above) only when you pass them, and any other relay you use is one you or another operator runs. rotifer wrap --from-clawhub accepts @owner/slug for a slug that more than one publisher uses; given only the slug, it prints one command per publisher, installs nothing and never picks a publisher for you. Still true from v0.38: a gene from outside this workspace (installed from Rotifer Cloud or wrapped from ClawHub) no longer gets credentials from your environment unasked when it runs in the WASM sandbox. Before running one that declares credentials there, rotifer run, rotifer agent run, rotifer test, rotifer arena submit and rotifer hello stop, unless --allow-credentials already covers every credential it declares: at a terminal they ask once, default no, and a yes holds for that run only; otherwise, or with --json, they exit 1 with credentials_not_granted and print the --allow-credentials NAME@host to pass. Only a Hybrid gene with a network block can be given a credential, only the granted names are read, and each is sent only to the exact host it was granted for; a credential declared without an exact host cannot be granted (credentials_not_grantable). Genes from this workspace are unchanged. None of this applies on the Node.js path, which rotifer run and rotifer agent run take for such a gene only with --trust-unsigned: there the gene runs with the host's full privileges, with no question and no host limit. The node-certificate (proof-of-registration) issuing service is now live, so once signed in you can get this node a certificate with rotifer network attest enable; the service's database migration is now part of this repository's regular Supabase migration chain. Still true from v0.37: when the CLI runs a gene's source under Node.js, the global fetch answers to the gene's phenotype.network the way ctx.gatewayFetch does and a WebSocket or EventSource is refused, but this is not a sandbox: only the WASM sandbox confines a gene; T1 waits for an async express and judges the value it resolves to; a gene call whose Promise never settles fails with exit code 1. Still true from v0.36: genes made with rotifer wrap pass the WASM sandbox in rotifer test, rotifer arena submit and rotifer run; wrap --from-clawhub refuses a package with a symbolic link, a .. segment or an absolute path (E0013), and a gene wrapped from ClawHub is refused on the unsandboxed Node.js path unless you pass --trust-unsigned; rotifer login accepts only a PKCE code on its local callback port. Still true from v0.35: rotifer hello --template <id> prints, gene by gene, the rotifer install command for each missing gene or why it can't be installed, never installs anything itself, and no longer reports a run that did nothing as a success; code-security and doc-qa are not available yet; the experimental P2P node keeps up to 8 outbound connections to peers it chose, redials a bootstrap node when none is connected, and keeps the score penalty on more than 10 peers sharing one IP. The P2P node stays off unless you start it. Still true from v0.34: the experimental P2P node can find genes across nodes, not only hear LAN announcements. rotifer network announce writes the gene to the DHT and republishes it every 12 hours; the announce list survives a daemon restart, and rotifer network withdraw stops republishing and serving a gene (copies other nodes already hold expire on their own within 48 hours). rotifer network search <query> matches keywords against announcements this node has heard and runs a Rotifer Cloud search alongside, as two separate lists; a v2 gene ID is looked up in the DHT, and the DHT is never searched by keyword. Records from other nodes are checked before they are stored, with per-publisher and total limits, and a peer that keeps breaking them is blocked for a while. Nodes started with --host 0.0.0.0 find each other on the local network by mDNS without --bootstrap (--no-mdns turns that off); the node is on libp2p 0.57, can connect through a relay or by hole punching, and enforces connection and memory limits. Gossip on topics without a registered validator is ignored. Heartbeats can carry a Cloud-issued proof of registration that peers check and use in GossipSub scoring; the Cloud issuing side is in this repository and is now live (see v0.38 above). Breaking: nodes on 0.27–0.33 still connect and gossip with this version but no longer share its DHT, so upgrade your bootstrap node. Still true from v0.33: agents have memory (spec §38) that survives genome changes, stored in .rotifer/playground.db with every change logged to .rotifer/audit.jsonl; Rotifer Cloud does not store agent memory yet; rotifer run checks input and output against the gene's schema (--no-validate turns that off). Still true from v0.32: Arena F(g) is on a 0–1 scale and scores from earlier versions are not converted; arena submit --cloud uploads the tier that actually ran; Hybrid genes must use https, and every redirect hop is checked against their allowed domains. Still true from v0.30: F(g) is scored against the season median and stays estimated and outside the ranking until coverage and robustness are measured (planned for v1.0); every CLI path runs a gene with exactly the permissions its phenotype declares; publishing enforces spec §47.5 T1. See CHANGELOG.md for full release history. Internet-wide reach and L4 Collective Immunity are later milestones — see Implementation Status below.


Install

npm install -g @rotifer/playground

Or use directly via npx:

npx -y @rotifer/playground@latest init my-agent

Requirements: Node.js >= 22.18.0 (genes are TypeScript; the CLI relies on Node’s built-in type stripping to run them from source)

rotifer compile (TypeScript → WASM) also needs esbuild and javy-cli on your PATH: npm i -g esbuild javy-cli. init, hello and arena on the bundled genes run without them.


First Agent in Seconds

rotifer init my-agent && cd my-agent
rotifer hello --template quality-advisor

rotifer init bootstraps the local Arena and Genesis genes. rotifer hello --template quality-advisor is the recommended preset-agent entrypoint for a first run.


30-Second Demo

$ rotifer init my-agent

  Rotifer Protocol - Agent Workspace Initialization
  ───────────────────────────────────────────────────
✓ Agent workspace scaffolding created
ℹ Installing Genesis genes...
✓ 5 Genesis genes installed
✓ 1 starter gene installed for the recommended template (quality-advisor)

  Starter Genes
  ───────────────
  Name                        Domain            Fidelity
  ────────────────────────────────────────────────────────
  genesis-file-read           filesystem        Wrapped
  hello-world                 general           Wrapped
  gene-health-scanner         meta.diagnostics  Wrapped
  genesis-l0-constraint       safety            Native
  genesis-web-search          search            Native
  genesis-web-search-lite     search            Native
  genesis-code-format         tooling           Native
ℹ 7 starter gene(s) across 6 domain(s)

  Agent workspace "my-agent" is ready!

One command scaffolds the workspace and ships the starter genes, including the one the recommended template needs. rotifer hello --template quality-advisor then turns them into your first preset agent.


Three-Act Experience (ADR-11)

Act 1 — Wow (30 seconds)

rotifer init my-agent && cd my-agent

Your workspace already holds the starter genes. rotifer arena list shows them in the local Arena, unscored until you evaluate one with rotifer arena submit <gene>. No configuration needed.

Act 2 — Aha (5 minutes)

rotifer hello --template quality-advisor # Run the recommended preset Agent
rotifer agent list                 # Inspect the generated hello-* agent

Bundled genes become a working preset agent in seconds.

Act 3 — Hooked (30 minutes)

Turn your own code into a gene, then build a custom agent:

# Wrap existing code as a gene
rotifer scan genes/                    # Discover candidate functions
rotifer wrap hello-world               # Wrap as a gene (generates Phenotype)
rotifer test hello-world               # Run sandbox tests (WASM sandbox for compiled genes)
rotifer test hello-world --compliance  # Run structural compliance checks
rotifer arena submit hello-world       # Submit to Arena (admission gate)
rotifer arena list                     # See your gene's ranking

# Write a gene in TypeScript — same language, zero learning curve
mkdir genes/my-search && cat > genes/my-search/index.ts << 'EOF'
export function express(input: { query: string }) {
  return { results: [`Found: ${input.query}`], total: 1 };
}
EOF

rotifer wrap my-search --domain search
rotifer compile my-search           # TS → JS → WASM → Rotifer IR
rotifer arena submit my-search      # Watch it climb the rankings
rotifer arena list --domain search # Compare against Genesis genes

# Create an Agent with a gene genome (supports Seq, Par, Cond, Try)
rotifer agent create search-bot --genes genesis-web-search my-search
rotifer agent create parallel-bot --genes web-search doc-search --composition Par
rotifer agent list

# Run the Agent — WASM sandbox execution preferred
rotifer agent run search-bot --input '{"query":"rotifer protocol"}'
rotifer agent run search-bot --no-sandbox  # Force Node.js fallback

rotifer compile auto-detects TypeScript genes and compiles them to Native WASM. No separate toolchain required.


Architecture

playground/
├── crates/
│   ├── rotifer-core/        Rust: types, sandbox, arena, algebra, fitness, storage
│   └── rotifer-napi/        Native bridge: Rust ↔ Node.js FFI
├── src/                     TypeScript CLI and supporting modules
│   ├── commands/            CLI command modules
│   ├── cloud/               Cloud Binding client (auth, API, types)
│   └── utils/               Config, display, native binding, IR compiler
├── genes/                   Bundled gene directories
├── supabase/                Cloud Binding self-hosting guide
├── templates/               Gene + composition scaffolds
└── tests/                   Unit + E2E test suites

Layers

LayerTechnologyResponsibility
CLITypeScript + commander.jsUser interface, command routing, display
BridgeNative bridge (cdylib)Rust-to-Node.js FFI binding
CoreRust + WASM runtimeWASM sandbox (Direct + WASI), Arena engine, Algebra executor, Fitness computation, SQLite storage

CLI Commands

Run rotifer --help for the grouped command list. The commands below cover the main local, cloud, arena, and agent workflows.

CommandDescription
rotifer init [workspace-name]Initialize a new Agent workspace with Genesis genes
rotifer hello [--template <id>]Create and run a preset agent from curated templates inside a Rotifer Agent workspace. --list-templates shows which can run here; a template missing genes exits 1 and says what can be installed
rotifer scan [path]Scan for candidate genes and local skills
rotifer wrap <gene-name>Wrap a function or SKILL.md as a gene (offers to publish, default yes — see Publishing by default)
rotifer wrap <gene-name> --from-clawhub <slug>Wrap a ClawHub skill as a gene. When more than one publisher uses the slug, name one as ClawHub writes it, --from-clawhub @owner/slug; otherwise the command stops, lists each publisher's command, and installs nothing
rotifer test [gene-name]Test a gene (WASM sandbox preferred, --compliance for structural checks)
rotifer compile [gene-name]Compile gene to Rotifer IR (auto TS→WASM)
rotifer run <gene-name>Execute a single local gene directly; input and output are checked against the gene's schema (--no-validate skips that)
rotifer listList local genes in the current Agent workspace
rotifer loginLog in to Rotifer Cloud (OAuth)
rotifer logoutLog out from Rotifer Cloud
rotifer publish [gene-name]Publish gene(s) to Rotifer Cloud
rotifer search [query]Search genes on Rotifer Cloud
rotifer install <gene-ref>Install a gene from Cloud (UUID, name, or content hash)
rotifer info <gene-ref>View gene details (local or Cloud)
rotifer stats <gene-ref>View download statistics for a gene
rotifer compare [gene-refs...]Compare 2–5 genes by reputation and downloads
rotifer reputation [gene-ref]View gene and creator reputation scores
rotifer versions <owner> <gene-name>View version history chain for a gene
rotifer arena submit <gene-name>Submit a gene to the Arena (--cloud for Cloud Arena)
rotifer arena listList Arena rankings (--cloud for Cloud Arena)
rotifer arena watch <domain>Watch Arena rankings live (--cloud for Cloud Arena)
rotifer agent create <agent-name>Create an Agent (--composition Seq|Par|Cond|Try|TryPool)
rotifer agent listList all agents
rotifer agent run <agent-name>Execute genome pipeline (WASM sandbox, --no-sandbox for Node.js)
rotifer genome export <agent>Export an agent's genome as a shareable Blueprint (.rgenome); aborts if the file would carry a credential or fail import's format checks
rotifer genome import <file>Rebuild an agent from a Blueprint: installs Native/Hybrid genes by exact version (--pinned) or picks Arena-verified substitutes that clear the F(g) and V(g) thresholds; --dry-run shows the plan
rotifer vg [path]V(g) security scan for gene/skill code
rotifer networkP2P gene network commands (see rotifer network --help)
rotifer self-updateCheck for updates and upgrade Rotifer packages
rotifer configManage global Rotifer configuration
rotifer whoamiShow current authentication status

External genes and your credentials

A gene you installed or wrapped can declare that it needs a credential from your environment and which hosts it may send it to. rotifer run, agent run, test and hello ask you before such a gene runs in the sandbox:

These external genes want to use credentials from your environment:
  some-gene: SEARCH_API_KEY → api.search.example
Allow this for this run? [y/N]

The answer holds for that one run, and a gene can use a credential only at the host you allowed it for. Genes from your own workspace are not asked about.

Without a terminal, or with --json, nothing is asked: the command stops with exit code 1 and credentials_not_granted. To allow it there, pass exact pairs:

rotifer run some-gene --allow-credentials SEARCH_API_KEY@api.search.example

arena submit takes the same flag, but it scores Hybrid genes without running them, so it has nothing to ask today. --trust-unsigned runs a gene outside the sandbox with your whole environment, so none of this applies to it.


Publishing by default

rotifer wrap asks whether to publish the gene it just created, and the answer defaults to yes — pressing Enter uploads it to Rotifer Cloud:

Publishing is on by default — turn it off with 'rotifer config set default-publish false'
Publish 'my-search' to Rotifer Cloud? [Y/n]

Answering n keeps the gene local; rotifer publish my-search uploads it later. The default exists because a registry only helps people find genes that reached it, and the step most often skipped is the upload.

It asks rather than uploads, and it only asks when there is someone to answer:

SituationWhat happens
rotifer config set default-publish false (or ROTIFER_AUTO_PUBLISH=0)Never asks. rotifer publish still works.
No terminal — CI, a pipe, a scriptNever asks and never publishes, so a build that wraps genes does not upload them.
Signed outNever asks; points at rotifer login.
Native gene with no gene.ir.wasmNever asks; points at rotifer compile, which publishing would require anyway.

Publishing this way runs the same gates as rotifer publish: V(g) security scan, IR integrity, phenotype schema, secret scan, and dependency audit. A gene that fails them is not uploaded, and wrap still reports the gene as created.


Genesis Genes

Five pre-installed genes ship with every Agent workspace:

GeneDomainFidelityDescription
genesis-web-searchsearchNativeDemo: simulated multi-result search (example.com results, not a live search)
genesis-web-search-litesearchNativeDemo: simulated single-answer search (not a live search)
genesis-file-readfilesystemWrappedRead local files (L0 sandbox restricted)
genesis-code-formattoolingNativeFormat source code (JSON, TS, etc.)
genesis-l0-constraintsafetyNativeL0 sandbox constraint checker

Gene Composition (Algebra)

Genes can be composed using the Rotifer Algebra:

OperatorDescriptionExample
SeqSequential pipelineSearch → Format
ParParallel with mergeSearch + Search-Lite, take first
CondConditional branchIf query.length > 100 → Lite, else → Full
TryFault tolerancePrimary with fallback
TransformMap/transformInner gene → mapper gene

See templates/composition/ for JSON examples.


Examples

The examples/ directory contains reference implementations and experiments:

DirectoryDescription
examples/mcp-migration/How to migrate MCP Tools into Rotifer Genes
examples/api-apocalypse/API fault-tolerance experiment — baseline vs Rotifer agent with domain failover

Development

git clone https://github.com/rotifer-protocol/rotifer-playground.git
cd rotifer-playground

# TypeScript CLI
npm install
npm run build          # Build to dist/
npm test               # Run the TypeScript test suite (Vitest)
npm run lint           # Type-check and lint src/

# Rust Core (requires Rust toolchain)
cargo check -p rotifer-core
cargo test -p rotifer-core

# Full demo
bash demo.sh

Implementation Status

This project is in alpha. The table below shows the honest implementation status of each URAA layer.

URAA LayerSpec NameStatusWhat WorksWhat's Planned
L0Kernel~40%L0Gate pre-execution checks (domain, resource limits, filesystem) on every execution path, including genome steps and the Node.js fallback; audit logPer-gene permission policy, network check, EthicalBoundary, State Anchoring, Trust Anchor
L1Synthesis~70%WASM sandbox, IR compiler, TS→WASM compilation, native bridgeSynthesizer interface, full WASI capability negotiation
L2Calibration~40%Schema validation, sandbox testing, --compliance checksStatic analysis, controlled field trial
L3Competition~85%Arena ranking, F(g) multiplicative model, R(g) reputation, Cloud Registry, experimental P2P node (off by default: mDNS LAN discovery, gene announcements, DHT search)Public bootstrap and relay nodes, internet-wide P2P, hot-loading, retirement
L4Collective Immunity0%—Threat broadcasting, emergency rollback, cross-node consensus
AlgebraComposition~90%All 5 operators in Rust; CLI supports Seq/Par/Cond/TryDataFlowGraph

Key limitation: L4 depends on a mature L3 P2P layer. P2P is runnable today but experimental and off by default, and still lacks automatic peer discovery and internet-wide reach. Full L4 is targeted for v1.x.


Protocol Compliance

Targets Rotifer Protocol Specification (Frozen). See Implementation Status for detailed layer-by-layer coverage.

DepthComponentsNotes
FullPhenotype, AlgebraExpr, Fitness F(g), ArenaCore gene lifecycle
FunctionalWASM Sandbox, L0 Gate, Reputation R(g), P2P HLT (LAN, experimental)L0 at ~40%, expanding
SimplifiedAgent Lifecycle, Gene Lifecycle, RotiferBindingMVP subset
PlannedInternet-wide P2P HLT, Formal Verification, Cross-Binding Consistency, ZK Proofs, L4 ImmunityRoadmap items

Changes driven by implementation feedback are proposed through the ADR process.


Roadmap

See CHANGELOG.md for detailed release history. Upcoming milestones:

  • Next — automatic peer discovery and internet-wide P2P reach
  • v1.0 — Stable release: L0-L3 complete, economic system, security audit
  • v1.x — L4 Collective Immunity

Community

Contributing

See CONTRIBUTING.md for development setup and guidelines.

License

Apache-2.0 with Rotifer Safety Clause

This project uses the Apache License 2.0 with an additional Rotifer Safety Clause that requires any deployment to either preserve the L0 Constraint Layer or clearly disclose modifications to it.


The Rotifer Protocol is alive.

Plugins relacionados