VSM is a tiny, idiomatic Ruby runtime for building agentic systems with a clear spine: Operations, Coordination, Intelligence, Governance, and Identity.
Building agentic systems often leads to tangled callback spaghetti and unclear responsibilities. As you add tools, LLM providers, and coordination logic, the complexity explodes. You end up with:
- Callbacks nested in callbacks with no clear flow
- Tool execution mixed with business logic
- No clear separation between "what the agent does" vs "how it decides" vs "what rules it follows"
- Difficulty testing individual components
- Lock-in to specific LLM providers or frameworks
VSM solves this by providing a composable, testable architecture with named responsibilities (POODR/SOLID style). You get clear separation of concerns from day one, and can start with a single capsule and grow to a swarm—without changing your interface or core loop.
The Viable System Model gives you a proven organizational pattern: every autonomous system needs Operations (doing), Coordination (scheduling), Intelligence (deciding), Governance (rules), and Identity (purpose). VSM makes this concrete in Ruby.
Ruby developers building AI agents who want clean architecture over framework magic. If you've read Sandi Metz's POODR, appreciate small objects with single responsibilities, and want your agent code to be as clean as your Rails models, VSM is for you.
Teams scaling from prototype to production who need to start simple (one tool, one LLM call) but know they'll need multiple tools, streaming, confirmations, and policy enforcement later. VSM's recursive capsule design means your "hello world" agent uses the same architecture as your production swarm.
Developers who want provider independence. VSM doesn't lock you into OpenAI, Anthropic, or any specific provider. Your Intelligence component decides how to plan—whether that's calling an LLM, following a state machine, or using your own logic.
VSM is a Ruby gem that provides:
Five named systems that every agent needs:
- Operations — do the work (tools/skills)
- Coordination — schedule, order, and arbitrate conversations (the "floor")
- Intelligence — plan/decide (e.g., call an LLM driver, or your own logic)
- Governance — enforce policy, safety, and budgets
- Identity — define purpose and invariants
Capsules — recursive building blocks. Every capsule has the five systems above plus a message bus. Capsules can contain child capsules, and "tools" are just capsules that opt-in to a tool interface.
Async-first architecture — powered by the
asyncgem, VSM runs streaming, I/O, and multiple tool calls concurrently without blocking.Clean interfaces — Ports translate external events (CLI, HTTP, MCP) into messages. Tools expose JSON Schema descriptors that work with any LLM provider.
Built-in observability — append-only JSONL ledger of all events, ready to feed into a monitoring UI.
# Gemfilegem"vsm","~> 0.0.1"bundle installRuby 3.2+ recommended.
Here's a minimal agent with one tool:
require"securerandom"require"vsm"# 1) Define a tool as a capsuleclassEchoTool < VSM::ToolCapsuletool_name"echo"tool_description"Echoes a message"tool_schema({type: "object",properties: {text: {type: "string"}},required: ["text"]})defrun(args)"you said: #{args["text"]}"endend# 2) Define your Intelligence (decides what to do)classDemoIntelligence < VSM::Intelligencedefhandle(message,bus:, **)returnfalseunlessmessage.kind == :userifmessage.payload =~ /\Aecho:\s*(.+)\z/# User said "echo: something" - call the toolbus.emitVSM::Message.new(kind: :tool_call,payload: {tool: "echo",args: {"text"=> $1 }},corr_id: SecureRandom.uuid,meta: message.meta)else# Just respondbus.emitVSM::Message.new(kind: :assistant,payload: "Try: echo: hello",meta: message.meta)endtrueendend# 3) Build your agent using the DSLcapsule=VSM::DSL.define(:demo)doidentityklass: VSM::Identity,args: {identity: "demo",invariants: []}governanceklass: VSM::Governancecoordinationklass: VSM::Coordinationintelligenceklass: DemoIntelligenceoperationsdocapsule:echo,klass: EchoToolendend# 4) Add a simple CLI interfaceclassStdinPort < VSM::Portdefloopsession=SecureRandom.uuidprint"You: "while(line= $stdin.gets&.chomp)@capsule.bus.emitVSM::Message.new(kind: :user,payload: line,meta: {session_id: session})@capsule.roles[:coordination].wait_for_turn_end(session)print"You: "endenddefrender_out(msg)casemsg.kindwhen:assistantputs"\nBot: #{msg.payload}"when:tool_resultputs"\nTool> #{msg.payload}"@capsule.bus.emitVSM::Message.new(kind: :assistant,payload: "(done)",meta: msg.meta)endendend# 5) Start the runtimeVSM::Runtime.start(capsule,ports: [StdinPort.new(capsule:)])Run it:
ruby quickstart.rb
# You: echo: hello# Tool> you said: helloScaffold a new VSM app with a ChatTTY interface:
gem install vsm # or build/install locally
vsm new my_agent
cd my_agent
bundle install
bundle exec exe/my-agentOptions:
--with-llm openai|anthropic|gemini— choose LLM provider (default: openai)--model <name>— default model--git— initialize git and commit--bundle— runbundle install--path <dir>— target directory (default:./<name>)--force— overwrite an existing non-empty directory
Generated layout mirrors the airb example: an Organism.build to assemble the capsule, a default ChatTTY port, and a sample echo tool ready to extend.
For a real agent with LLM integration:
capsule=VSM::DSL.define(:my_agent)doidentityklass: VSM::Identity,args: {identity: "my_agent",invariants: ["stay in workspace"]}governanceklass: VSM::Governancecoordinationklass: VSM::Coordinationintelligenceklass: MyLLMIntelligence# Your class that calls OpenAI/Anthropic/etcmonitoringklass: VSM::Monitoring# Optional: writes JSONL event logoperationsdocapsule:list_files,klass: ListFilesToolcapsule:read_file,klass: ReadFileToolcapsule:write_file,klass: WriteFileToolendendYour MyLLMIntelligence would:
- Maintain conversation history
- Call your LLM provider with available tools
- Emit
:tool_callmessages when the LLM wants to use tools - Stream
:assistant_deltatokens as they arrive - Emit final
:assistantmessage when done
- Features
- Core Concepts
- Tools as Capsules
- Async & Parallelism
- Ports (Interfaces)
- Observability
- Writing an Intelligence
- Testing
- Design Goals
- Roadmap
- FAQ
- API Overview
- License
- Contributing
- Named systems: Operations, Coordination, Intelligence, Governance, Identity
- Capsules: recursive building blocks (a capsule can contain more capsules)
- Async bus: non‑blocking message channel with fan‑out subscribers
- Structured concurrency: streaming + multiple tool calls in parallel
- Tools-as-capsules: opt‑in tool interface + JSON Schema descriptors
- Executors: run tools in the current fiber or a thread pool (Ractor/Subprocess future)
- Ports: clean ingress/egress adapters for CLI/TUI/HTTP/MCP/etc.
- Observability: append‑only JSONL ledger you can feed into a UI later
- POODR/SOLID: small objects, high cohesion, low coupling
VSM includes a set of read‑only meta tools you can attach to any capsule to inspect its structure and code:
meta_summarize_self— Summarize the current capsule including roles and toolsmeta_list_tools— List all tools available in the organism (descriptors and paths)meta_explain_tool— Show code and context for a specific toolmeta_explain_role— Explain a role implementation for a capsule, with source snippets
Attach them when building your capsule:
capsule=VSM::DSL.define(:my_agent)doidentityklass: VSM::Identity,args: {identity: "my_agent"}governanceklass: VSM::Governancecoordinationklass: VSM::Coordinationintelligenceklass: VSM::Intelligencemonitoringklass: VSM::Monitoringoperationsdometa_tools# registers the four meta tools above on this capsuleendendExample calls:
meta_summarize_self {}→ high‑level snapshot and countsmeta_list_tools {}→ array of tools with descriptorsmeta_explain_tool { "tool": "some_tool" }→ code snippet + descriptormeta_explain_role { "role": "coordination" }→ role class, constructor args, source locations, and code blocks
A container with five named systems and a message bus:
Capsule(:name)
├─ Identity (purpose & invariants)
├─ Governance (safety & budgets)
├─ Coordination (scheduling & "floor")
├─ Intelligence (planning/deciding)
├─ Operations (tools/skills)
└─ Monitoring (event ledger; optional)
Capsules can contain child capsules. Recursion means a "tool" can itself be a full agent if you want.
VSM::Message.new(kind: :user | :assistant | :assistant_delta | :tool_call | :tool_result | :plan | :policy | :audit | :confirm_request | :confirm_response,payload: "any",path: [:airb,:operations,:fs],# optional addressingcorr_id: "uuid",# correlate tool_call ↔ tool_resultmeta: {session_id: "uuid", ... }# extra context)A non‑blocking bus built on fibers (async). Emitting a message never blocks the emitter.
Any capsule can opt‑in to act as a "tool" by including VSM::ActsAsTool (already included in VSM::ToolCapsule).
classReadFile < VSM::ToolCapsuletool_name"read_file"tool_description"Read the contents of a UTF-8 text file at relative path."tool_schema({type: "object",properties: {path: {type: "string"}},required: ["path"]})defrun(args)path=governance_safe_path(args.fetch("path"))File.read(path,mode: "r:UTF-8")end# Optional: choose how this tool executesdefexecution_mode=:fiber# or :threadprivatedefgovernance_safe_path(rel)=governance.instance_eval{# simple helperfull=File.expand_path(File.join(Dir.pwd,rel))raise"outside workspace"unlessfull.start_with?(Dir.pwd)full}endVSM provides provider‑agnostic descriptors:
tool=instance.tool_descriptortool.to_openai_tool# => {type:"function", function:{ name, description, parameters }}tool.to_anthropic_tool# => {name, description, input_schema}tool.to_gemini_tool# => {name, description, parameters}Why opt‑in? Not every capsule should be callable as a tool. Opt‑in keeps coupling low. Later you can auto‑expose selected capsules as tools or via MCP.
VSM is async by default:
- The bus is fiber‑based and non‑blocking.
- The capsule loop drains messages without blocking emitters.
- Operations runs each tool call in its own task; tools can choose their execution mode:
:fiber(default) — I/O‑bound, non‑blocking:thread— CPU‑ish work or blocking libraries
You can add Ractor/Subprocess executors later without changing the API.
A Port translates external events into messages and renders outgoing messages. Examples: CLI chat, TUI, HTTP, MCP stdio, editor plugin.
classMyPort < VSM::Portdefloopsession=SecureRandom.uuidwhile(line= $stdin.gets&.chomp)@capsule.bus.emitVSM::Message.new(kind: :user,payload: line,meta: {session_id: session})@capsule.roles[:coordination].wait_for_turn_end(session)endenddefrender_out(msg)casemsg.kindwhen:assistant_deltathen $stdout.print(msg.payload)when:assistantthenputs"\nBot: #{msg.payload}"when:confirm_requestthenconfirm(msg)endenddefconfirm(msg)print"\nConfirm? #{msg.payload} [y/N] "ok=($stdin.gets || "").strip.downcase.start_with?("y")@capsule.bus.emitVSM::Message.new(kind: :confirm_response,payload: {accepted: ok},meta: msg.meta)endendStart everything:
VSM::Runtime.start(capsule,ports: [MyPort.new(capsule:)])VSM::Ports::ChatTTY— A generic, customizable chat terminal UI. Safe to run alongside MCP stdio; prefersIO.consoleso it won’t pollute stdout.VSM::Ports::MCP::ServerStdio— Exposes your capsule as an MCP server on stdio implementingtools/listandtools/call.
Enable them:
require"vsm/ports/chat_tty"require"vsm/ports/mcp/server_stdio"ports=[VSM::Ports::MCP::ServerStdio.new(capsule: capsule),# machine IO (stdio)VSM::Ports::ChatTTY.new(capsule: capsule)# human IO (terminal)]VSM::Runtime.start(capsule,ports: ports)Reflect tools from an external MCP server and expose them as local tools using the DSL. This uses a tiny stdio JSON‑RPC client under the hood.
require"vsm/dsl_mcp"cap=VSM::DSL.define(:mcp_client)doidentityklass: VSM::Identity,args: {identity: "mcp_client",invariants: []}governanceklass: VSM::Governancecoordinationklass: VSM::Coordinationintelligenceklass: VSM::Intelligence# or your ownmonitoringklass: VSM::Monitoringoperationsdo# Prefix helps avoid name collisionsmcp_server:smith,cmd: "smith-server --stdio",prefix: "smith_",include: %w[searchread]endendSee examples/06_mcp_mount_reflection.rb and examples/07_connect_claude_mcp.rb.
Note: Many MCP servers speak LSP-style Content-Length framing on stdio. The
current minimal transport uses NDJSON for simplicity. If a server hangs or
doesn't respond, switch the transport to LSP framing in lib/vsm/mcp/jsonrpc.rb.
You can customize ChatTTY via options or by subclassing to override only the banner and rendering methods, while keeping the input loop.
classFancyTTY < VSM::Ports::ChatTTYdefbanner(io)io.puts"\e[95m\n ███ CUSTOM CHAT ███\n\e[0m"enddefrender_out(m)super# or implement your own formattingendendVSM::Runtime.start(capsule,ports: [FancyTTY.new(capsule: capsule,prompt: "Me> ")])See examples/08_custom_chattty.rb.
Use an LLM driver (e.g., OpenAI) to automatically call tools reflected from an MCP server:
driver=VSM::Drivers::OpenAI::AsyncDriver.new(api_key: ENV.fetch("OPENAI_API_KEY"),model: ENV["AIRB_MODEL"] || "gpt-4o-mini")cap=VSM::DSL.define(:mcp_with_llm)doidentityklass: VSM::Identity,args: {identity: "mcp_with_llm",invariants: []}governanceklass: VSM::Governancecoordinationklass: VSM::Coordinationintelligenceklass: VSM::Intelligence,args: {driver: driver,system_prompt: "Use tools when helpful."}monitoringklass: VSM::Monitoringoperationsdomcp_server:server,cmd: ["claude","mcp","serve"]# reflect toolsendendVSM::Runtime.start(cap,ports: [VSM::Ports::ChatTTY.new(capsule: cap)])See examples/09_mcp_with_llm_calls.rb.
VSM ships a tiny Monitoring role that writes an append‑only JSONL ledger:
.vsm.log.jsonl
{"ts":"2025-08-14T12:00:00Z","kind":"user","path":null,"corr_id":null,"meta":{"session_id":"..."}}
{"ts":"...","kind":"tool_call", ...}
{"ts":"...","kind":"tool_result", ...}
{"ts":"...","kind":"assistant", ...}
Use it to power a TUI/HTTP "Lens" later. Because everything flows over the bus, you get consistent events across nested capsules and sub‑agents.
- MCP stdio port only reads stdin and writes strict JSON to stdout.
- ChatTTY prefers
IO.consoleor falls back to stderr and disables input if no TTY. - You can run both in the same process: machine protocol on stdio, human UI on the terminal.
The Intelligence role is where you plan/decide. It might:
- forward a conversation to an LLM driver (OpenAI/Anthropic/Gemini),
- emit
:tool_callmessages when the model asks to use tools, - stream
:assistant_deltatokens and finish with:assistant.
Minimal example (no LLM, just logic):
classMyIntelligence < VSM::Intelligencedefinitialize@history=Hash.new{ |h,k| h[k]=[]}enddefhandle(message,bus:, **)returnfalseunless[:user,:tool_result].include?(message.kind)sid=message.meta&.dig(:session_id)@history[sid] << messageifmessage.kind == :user && message.payload =~ /read (.+)/bus.emitVSM::Message.new(kind: :tool_call,payload: {tool: "read_file",args: {"path"=> $1 }},corr_id: SecureRandom.uuid,meta: {session_id: sid})elsebus.emitVSM::Message.new(kind: :assistant,payload: "ok",meta: {session_id: sid})endtrueendendIn your application, you can plug in provider drivers that stream and support native tool calling; Intelligence remains the same.
VSM is designed for unit tests:
- Capsules: inject fake systems and assert dispatch.
- Intelligence: feed
:user/:tool_resultmessages and assert emitted messages. - Tools: call
#rundirectly. - Ports: treat like adapters; they're thin.
Quick smoke test:
require"vsm"RSpec.describe"tool dispatch"doclassT < VSM::ToolCapsuletool_name"t";tool_description"d";tool_schema({type: "object",properties: {},required: []})defrun(_args)="ok"endit"routes tool_call to tool_result"docap=VSM::DSL.define(:test)doidentityklass: VSM::Identity,args: {identity: "t",invariants: []}governanceklass: VSM::Governancecoordinationklass: VSM::Coordinationintelligenceklass: VSM::Intelligenceoperations{capsule:t,klass: T}endq=Queue.newcap.bus.subscribe{ |m| q << mifm.kind == :tool_result}cap.runcap.bus.emitVSM::Message.new(kind: :tool_call,payload: {tool: "t",args: {}},corr_id: "1")expect(q.pop.payload).toeq("ok")endend- Ergonomic Ruby (small objects, clear names, blocks/DSL where it helps)
- High cohesion, low coupling (roles are tiny; tools are self‑contained)
- Recursion by default (any capsule can contain more capsules)
- Async from day one (non‑blocking bus; concurrent tools)
- Portability (no hard dependency on a specific LLM vendor)
- Observability built‑in (event ledger everywhere)
- Executors: Ractor & Subprocess for heavy/risky tools
- Limiter: per‑tool semaphores and budgets (tokens/time/IO) in Governance
- Lens UI: terminal/HTTP viewer for plans, tools, and audits
- Drivers: optional
vsm-openai,vsm-anthropic,vsm-geminiadd‑ons for native tool‑calling + streaming - MCP ports: stdio server/client to expose/consume MCP tools
Does every capsule have to be a tool?
No. Opt‑in via VSM::ActsAsTool. Many capsules (planner, auditor, coordinator) shouldn't be callable as tools.
Can I run multiple interfaces at once (chat + HTTP + MCP)?
Yes. Start multiple ports; Coordination arbitrates the "floor" per session.
How do I isolate risky or CPU‑heavy tools?
Set execution_mode to :thread today. Ractor/Subprocess executors are planned and will use the same API.
What about streaming tokens?
Handled by your Intelligence implementation (e.g., your LLM driver). Emit :assistant_delta messages as tokens arrive; finish with a single :assistant.
Is VSM tied to any specific LLM?
No. Write a driver that conforms to your Intelligence's expectations (usually "yield deltas" + "yield tool_calls"). Keep the provider in your app gem.
moduleVSM# MessagesMessage(kind:,payload:,path: nil,corr_id: nil,meta: {})# BusclassAsyncChanneldefemit(message);enddefpop;enddefsubscribe(&block);endattr_reader:contextend# Roles (named systems)classOperations;end# routes tool_call -> childrenclassCoordination;end# scheduling, floor, turn-endclassIntelligence;end# your planning/LLM driverclassGovernance;end# policy/safety/budgetsclassIdentity;end# invariants & escalationclassMonitoring;end# JSONL ledger (observe)# Capsules & DSLclassCapsule;endmoduleDSLdefself.define(:name, &block)->Capsuleend# ToolsmoduleToolDescriptor#to_openai_tool / #to_anthropic_tool / #to_gemini_toolendmoduleActsAsTool;endclassToolCapsule# include ActsAsTool# def run(args) ...# def execution_mode = :fiber | :threadend# Ports & runtimeclassPortdefinitialize(capsule:);enddefloop;end# optionaldefrender_out(msg);enddefegress_subscribe;endendmoduleRuntimedefself.start(capsule,ports: [])endendMIT. See LICENSE.txt.
Issues and PRs are welcome! Please include:
- A failing spec (RSpec) for bug reports
- Minimal API additions
- Clear commit messages
Run tests with:
bundle exec rspecLint with:
bundle exec rubocop