Skip to content

Repository files navigation

VSM — Viable Systems for Ruby Agents

Conforms to README.lint

VSM is a tiny, idiomatic Ruby runtime for building agentic systems with a clear spine: Operations, Coordination, Intelligence, Governance, and Identity.

🌸 Why use VSM?

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.

🌸🌸 Who benefits from VSM?

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.

🌸🌸🌸 What exactly is VSM?

VSM is a Ruby gem that provides:

  1. 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
  2. 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.

  3. Async-first architecture — powered by the async gem, VSM runs streaming, I/O, and multiple tool calls concurrently without blocking.

  4. Clean interfaces — Ports translate external events (CLI, HTTP, MCP) into messages. Tools expose JSON Schema descriptors that work with any LLM provider.

  5. Built-in observability — append-only JSONL ledger of all events, ready to feed into a monitoring UI.

🌸🌸🌸🌸 How do I use VSM?

Install

# Gemfilegem"vsm","~> 0.0.1"
bundle install

Ruby 3.2+ recommended.

Quick Example

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: hello

Project Generator (CLI)

Scaffold 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-agent

Options:

  • --with-llm openai|anthropic|gemini — choose LLM provider (default: openai)
  • --model <name> — default model
  • --git — initialize git and commit
  • --bundle — run bundle 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.

Building a Real Agent

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: WriteFileToolendend

Your MyLLMIntelligence would:

  1. Maintain conversation history
  2. Call your LLM provider with available tools
  3. Emit :tool_call messages when the LLM wants to use tools
  4. Stream :assistant_delta tokens as they arrive
  5. Emit final :assistant message when done

🌸🌸🌸🌸🌸 Extras

Table of Contents

Features

  • 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

Meta Tools

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 tools
  • meta_list_tools — List all tools available in the organism (descriptors and paths)
  • meta_explain_tool — Show code and context for a specific tool
  • meta_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 capsuleendend

Example calls:

  • meta_summarize_self {} → high‑level snapshot and counts
  • meta_list_tools {} → array of tools with descriptors
  • meta_explain_tool { "tool": "some_tool" } → code snippet + descriptor
  • meta_explain_role { "role": "coordination" } → role class, constructor args, source locations, and code blocks

Core Concepts

Capsule

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.

Message

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)

AsyncChannel

A non‑blocking bus built on fibers (async). Emitting a message never blocks the emitter.

Tools as Capsules

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}end

VSM 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.

Async & Parallelism

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.

Ports (Interfaces)

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)endend

Start everything:

VSM::Runtime.start(capsule,ports: [MyPort.new(capsule:)])

Built-in Ports

  • VSM::Ports::ChatTTY — A generic, customizable chat terminal UI. Safe to run alongside MCP stdio; prefers IO.console so it won’t pollute stdout.
  • VSM::Ports::MCP::ServerStdio — Exposes your capsule as an MCP server on stdio implementing tools/list and tools/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)

MCP Client (reflect and wrap tools)

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]endend

See 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.

Customizing ChatTTY

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.

LLM-driven MCP tools

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.

Observability

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 and ChatTTY Coexistence

  • MCP stdio port only reads stdin and writes strict JSON to stdout.
  • ChatTTY prefers IO.console or 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.

Writing an Intelligence

The Intelligence role is where you plan/decide. It might:

  • forward a conversation to an LLM driver (OpenAI/Anthropic/Gemini),
  • emit :tool_call messages when the model asks to use tools,
  • stream :assistant_delta tokens 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})endtrueendend

In your application, you can plug in provider drivers that stream and support native tool calling; Intelligence remains the same.

Testing

VSM is designed for unit tests:

  • Capsules: inject fake systems and assert dispatch.
  • Intelligence: feed :user / :tool_result messages and assert emitted messages.
  • Tools: call #run directly.
  • 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

Design Goals

  • 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)

Roadmap

  • 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-gemini add‑ons for native tool‑calling + streaming
  • MCP ports: stdio server/client to expose/consume MCP tools

FAQ

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.

API Overview

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: [])endend

License

MIT. See LICENSE.txt.

Contributing

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 rspec

Lint with:

bundle exec rubocop

About

No description, website, or topics provided.

Resources

Stars

32 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages