Download all docs
actions

Ruby

Ruby running as a first-class element: you hand the platform a handler method — inline, from a file, or from a git repo — and every invocation executes it in its own sandboxed Firecracker microVM with Bundler-resolved gems and guaranteed memory and CPU isolation.

Working with it

Opening a Ruby launches a code runner — its dedicated working surface.

How it appears

The same element type rendered as a definition, a circle instance, and a live workspace card.

Rb
type

Ruby

Execute Ruby code in a sandboxed environment

actionsatomdefinition

When to use / not

When to use

  • Reshaping or transforming JSON payloads as they move between elements in an app or automation.
  • Calling an external REST or SOAP service from inside a workflow, leaning on a gem like httparty.
  • Encoding deterministic business logic — scoring functions, rule engines, routing decisions.
  • Text processing with Ruby's string, regex, and templating ergonomics.

When not to use

  • Reaching for a data-science or ML library ecosystem — `python` has the broader runtime for that work.
  • The behavior is a reasoning or generative task rather than deterministic code — use an agent or `lab` element instead of hand-writing logic.
  • You only need to persist or query data — connect a `sql`, `document`, or `vector` element directly rather than wrapping it in a function.

Topology

Created from the library and placed inside an app or circle. It is a top-level building block you compose with other elements.

Properties

handlerstring
Entry point method name. Your Ruby code must define this callable. Default: handler
sourceobject
Source code location. For inline code use type="inline" with code in the "code" field. IMPORTANT: code goes in spec.source.code (NOT spec.code).
memory_mbinteger
Memory allocation in MB

Capabilities

Defined for this element
  • Compute
  • Observe
  • Storage

Operations

  • activityGET
  • attachPOST
  • attachmentsGET
  • batch_statsGET
  • composePOST
  • contextGET
  • createPOST
  • deleteDELETE
  • deployPOST
  • detachPOST
  • diagnosticsGET
  • disablePOST
  • enablePOST
  • export_bundleGET
  • getGET
  • get_attached_modifiersGET
  • import_bundlePOST
  • intentionGET
  • invokePOST
  • list_attachmentsGET
  • logsGET
  • promotePOST
  • readmeGET
  • readme_updatePOST
  • remove-modifierPOST
  • restorePOST
  • run_cancelPOST
  • run_getGET
  • runsGET
  • schemaGET
  • sourceGET
  • source_branchesGET
  • source_promotePOST
  • source_repairPOST
  • source_statusGET
  • source_validatePOST
  • statsGET
  • treeGET
  • updatePATCH
  • update_metaPATCH
  • validate_sourcePOST
  • versionGET

Ports

Inputs

  • inputrequest
  • outputrequest
  • errorevent

Composition

Errors / when it fails

spec.source.code must not be empty when source.type is 'inline'
Fails unless: source.code != null && source.code != ''
spec.source.path must be specified when source.type is 'file'
Fails unless: source.path != null && source.path != ''
spec.source.repository must be specified when source.type is 'git'
Fails unless: source.repository != null && source.repository != ''
Gem entries should follow Bundler format, e.g. 'sinatra~>3.0' or 'json>=2.6,<3.0'

Validation rules

  • Memory over 2048MB may incur higher compute costs
  • Timeout over 5 minutes — consider using an async pattern for long-running work
  • Large number of gem dependencies increases cold start time

Ruby (ruby)

Category: actions | Form: | Symbol: Rb

Execute Ruby code in a sandboxed environment

Runs Ruby code in a sandboxed Firecracker VM. Put your code in spec.source.code with spec.source.type set to “inline”. Your code must define a handler method. Supports gem dependencies via spec.source.requirements.

Guide

Execute Ruby code in a sandboxed Firecracker VM

What It Does

The Ruby element runs Ruby code inside an isolated Firecracker microVM. You supply source code (inline, from a file path, or from a git repository) and the platform resolves gem dependencies, caches the bundle, and executes the handler method on each invocation. Each run gets its own VM with guaranteed memory and CPU isolation — there is no shared state between invocations unless you explicitly connect data elements.

Element Definition

PropertyValue
Typeruby
Categoryfunctions
Formatom
SymbolRb / #CC342D

Properties

FieldTypeDefaultDescription
source.typestring (enum)inlineSource location: inline (code in spec), file (path in element workspace), or git (repository URL)
source.codestringInline Ruby source. Must define the handler method.
source.pathstringFile path within the element workspace (for file type)
source.repositorystring (URI)Git repository URL (for git type)
source.refstringGit branch, tag, or commit SHA
source.requirementsarray[]Gem dependencies in Bundler format, e.g. ["sinatra~>3.0", "json~>2.6"]
handlerstringhandlerEntry point method name. Must be defined at the top level of your source.
memory_mbinteger128VM memory in MB (64–4096)
timeout_msinteger30000Maximum execution time in milliseconds (100–900000)
environmentobject{}Custom environment variables injected into the VM
layersarray[]Additional runtime layers
concurrency.reservedintegerReserved execution slots
concurrency.maxintegerMaximum concurrent executions
retry.max_attemptsinteger3Retry attempts on failure
retry.backoff_msinteger1000Initial retry backoff in milliseconds
retry.backoff_multipliernumber2.0Exponential backoff multiplier

Ports

DirectionPortTypeRequiredDescription
InputinputrequestYesArbitrary JSON payload passed to the handler method
OutputoutputrequestYesReturn value from the handler method
OutputerroreventNoEmitted when execution raises an unhandled exception

Topology

  • Lives in: actions/ruby/ repository
  • Accepts modifiers: requirements, auth-policy, variable
  • Uses resources: sql, document, vector, files

Capabilities

CapabilityDescription
sandboxed-executionRuns in an isolated Firecracker microVM
gem-dependenciesBundler gem dependency management via Gemfile
data-sourcesInjected connections to sql, document, vector, and files elements
environment-injectionCustom environment variables available at runtime

Input Contract

Your handler receives the caller’s payload as a Ruby Hash with string keys. The platform automatically unwraps common envelope patterns (payload, data, input keys) and strips internal metadata, so your handler always sees the clean user data.

Direct invoke — the JSON body is passed through:

POST /api/{circle}/my-fn/ops/invoke
{"name": "Alice", "count": 3}
def handler(input)
  # input = {"name" => "Alice", "count" => 3}
  { message: "Hello, #{input['name']}!" }
end

Envelope invoke — the platform unwraps payload/data/input keys automatically:

POST /api/{circle}/my-fn/ops/invoke
{"payload": {"name": "Alice"}}
# handler still receives {"name" => "Alice"} — envelope is stripped

Wired invoke (from automation steps or other elements) — the orchestrator shapes inputs based on port topology. Your handler receives the resolved payload, not raw wire data.

Quick Start

Creating via API

POST /api/{circle}/{project}/
Content-Type: application/json

{
  "element_type": "ruby",
  "slug": "greet",
  "name": "Greeter",
  "spec": {
    "handler": "handler",
    "source": {
      "type": "inline",
      "code": "def handler(input)\n  { message: \"Hello, #{input.fetch('name', 'World')}!\" }\nend"
    }
  }
}

Invoking

POST /api/{circle}/{project}/greet/ops/invoke
Content-Type: application/json

{ "name": "Triform" }

Response:

{ "message": "Hello, Triform!" }

Deploying with Gems

Set gem dependencies in spec.source.requirements and deploy to cache the bundle:

POST /api/{circle}/{project}/
Content-Type: application/json

{
  "element_type": "ruby",
  "slug": "http-fetcher",
  "spec": {
    "handler": "handler",
    "source": {
      "type": "inline",
      "requirements": ["httparty~>0.21"],
      "code": "require 'httparty'\n\ndef handler(input)\n  response = HTTParty.get(input['url'])\n  { status: response.code, body: response.parsed_response }\nend"
    }
  }
}

Then deploy:

POST /api/{circle}/{project}/http-fetcher/ops/deploy
Content-Type: application/json

{}

Writing Handlers

The handler method receives the input payload as a Ruby Hash (with string keys) and must return a value that can be serialized to JSON.

require 'json'

def handler(input)
  # input is a Hash with string keys
  user_id = input['user_id']
  threshold = input.fetch('threshold', 100)

  # Perform computation
  score = compute_score(user_id)

  # Return any JSON-serializable value
  {
    user_id: user_id,
    score: score,
    passed: score >= threshold
  }
end

def compute_score(user_id)
  # Your logic here
  42
end

Accessing Environment Variables

Environment variables set in spec.environment (or injected by attached data elements) are available via ENV:

def handler(input)
  api_key = ENV['MY_API_KEY']
  base_url = ENV['SERVICE_URL']
  # ...
end

Using Gems

Declare gems in spec.source.requirements and require them in your code:

require 'httparty'
require 'json'

def handler(input)
  result = HTTParty.post(
    'https://api.example.com/process',
    body: input.to_json,
    headers: { 'Content-Type' => 'application/json' }
  )
  result.parsed_response
end

Gem format follows Bundler constraints: "gem_name~>major.minor", "gem_name>=x.y,<z.0", or just "gem_name" for any version.

Project Patterns

Ruby is best suited for:

  • Data transformation — reshaping JSON payloads between elements
  • API integration — calling external REST or SOAP services with gem support
  • Business logic — rule engines, scoring functions, routing decisions
  • Text processing — string manipulation, regex, templating

Example Project Spec

elements:
  - element_type: ruby
    slug: transform-order
    spec:
      handler: handler
      source:
        type: inline
        requirements: ["activesupport~>7.1"]
        code: |
          require 'active_support/all'

          def handler(input)
            order = input.with_indifferent_access
            {
              order_id: order[:id],
              total_cents: (order[:amount].to_f * 100).round,
              currency: order[:currency]&.upcase || 'USD',
              processed_at: Time.current.iso8601
            }
          end

Applying Modifiers

ModifierUse case
requirementsRequire that specific variable or data resources are present before execution
auth-policyRestrict who can invoke the function
variableInject environment-level configuration into the function

Common Mistakes

Using symbol keys for input access. The input Hash always uses string keys. Use input['key'] or input.fetch('key', default), not input[:key], unless you convert with with_indifferent_access.

Defining the handler inside a class without top-level reference. The handler must be accessible at the top level. A plain def handler(input) works. If you use a class, expose the entry point as a top-level method or module function.

Putting gem names without constraints. Pinned or constrained gems (~>, >=) are strongly preferred. Unconstrained gems (gem_name only) may resolve to incompatible versions across deploys.

Forgetting to call deploy after changing requirements. Gem dependencies are bundled at deploy time, not at invocation time. After changing spec.source.requirements, call the deploy operation to rebuild the bundle before invoking.

Returning non-serializable Ruby objects. The return value must be JSON-serializable. Avoid returning Ruby Symbols (:foo), Time objects, or custom class instances without implementing to_json. Hashes with symbol keys are automatically converted.

Relationships

  • Attaches to: auth-policy, variable, rate-limit, validation, alert
  • Uses: sql, document, vector, files

Capabilities

  • sandboxed-execution: Runs in an isolated Firecracker microVM
  • gem-dependencies: Bundler gem dependency management via Gemfile
  • data-sources: Injected connections to sql, document, vector, and files elements
  • environment-injection: Custom environment variables available at runtime

Properties

PropertyTypeDefaultDescription
handlerstringEntry point method name. Your Ruby code must define this callable.
Default: handler
sourceobjectSource code location. For inline code use type=“inline” with code in the “code” field.
IMPORTANT: code goes in spec.source.code (NOT spec.code).
memory_mbinteger128Memory allocation in MB
timeout_msinteger30000Maximum execution time in milliseconds
environmentobjectCustom environment variables injected at runtime
layersarray[]Additional runtime layers
concurrencyobjectControls how many copies can run simultaneously
retryobjectAutomatic retry on failure

Operations

activity

Get /ops/activity | Auth: Read

Get activity events for this element

Scope depends on element capabilities: individual elements query by element_id, project-form elements with activity-scope-members include member activities, circle-level elements with activity-scope-all query the entire circle. Gracefully returns empty list if activities table is missing (old circles).

attach

Post /ops/attach | Auth: Read

Attach this actor to a target element

Call this ON the modifier/resource element, passing target_id of the actor. The target’s contract.yaml must declare the modifier kind in attaches: or uses:. Priority controls evaluation order for modifiers (lower = first).

attachments

Get /ops/attachments | Auth: Read

List all modifiers and resources attached to this element

Returns both modifiers (policy enforcement) and resources (data injection) with is_modifier flag to distinguish. Items in the generated MODIFIER_TYPES list are modifiers; everything else is a resource. Includes cascade_policy and version pin info.

batch_stats

Get /ops/batch_stats | Auth: Read

Get per-element statistics for all children of this element

Returns per-child stats plus an aggregate. Most meaningful on compound or manifest form elements (repositories, circles, projects); atoms have no children so the result is an empty children array with a zeroed aggregate. Uses efficient GROUP BY SQL. Weighted averages for eval scores.

compose

Post /ops/compose | Auth: Execute

Batch add and remove modifiers on this element in a single call

Declarative composition: add modifiers by ref path (slug or path@version) and remove by attachment ID, all in one atomic call on the target element. Each ‘add’ entry resolves the source element, validates topology, attaches with optional priority and cascade policy. Each ‘remove’ entry deletes the attachment row. Returns a summary of what was added and removed. Example: compose({ add: [{ref: “my-prompt”}, {ref: “rate-limit/api@v2”, priority: 50}], remove: [{attachment_id: “uuid”}] })

context

Get /ops/context | Auth: Read

Get connected elements (graph traversal)

Graph traversal showing all connected elements with their relationship type (contains, contained_by, references, referenced_by, attaches, etc.). Use ?depth=N to control traversal depth (default 1) and ?types=actor,data to filter by element types.

create

Post /ops/create | Auth: Write

Create child element

POST to the parent path — element_type goes in the request body, NOT the URL. Both element_type and slug are required and must be non-empty. Name is derived from slug if omitted. Writes to both Git and PostgreSQL. All elements are stored flat under the circle — no intermediate library wrapper rows.

delete

Delete /ops/delete | Auth: Admin

Delete element (soft delete)

Soft delete — sets state to ‘deleted’ but retains the record. Cannot delete elements that have children (has_no_bond precondition) or active runs. Requires admin auth and confirmation.

deploy

Post /ops/deploy | Auth: Write

Compile dependencies and prepare the function for execution

Bundle gem dependencies, validate handler existence, and promote the element from ready to deployed state. No input required. Returns deploy_id and status. Must be in ready state. After deploy, invoke will use the cached bundle.

detach

Post /ops/detach | Auth: Read

Detach this actor from a target element

diagnostics

Get /ops/diagnostics | Auth: Read

Check isolation service connectivity and health

Returns the status of the isolation executor that this element depends on for code execution. Use this to distinguish between user code errors and infrastructure issues when invoke returns 500. Returns isolation_reachable (bool), worker_available (bool), and last_error if any.

disable

Post /ops/disable | Auth: Admin

Disable element (hides and prevents use)

Idempotent — safe to call on already-disabled elements. Optionally pass a reason string. Disabled elements cannot be invoked or executed. Inverse of enable.

enable

Post /ops/enable | Auth: Admin

Enable element (makes usable and visible)

Idempotent — safe to call on already-enabled elements. Transitions element to ready/enabled state. Cannot enable deleted elements. Inverse of disable.

export_bundle

Get /ops/export/bundle | Auth: Read

Export element as downloadable git bundle

On non-root-namespace elements, returns a binary git bundle. On root-namespace (circle) elements, dispatch hands off to the circle’s own export_bundle op, which returns a multi-element JSON envelope with one base64 bundle per child element — this is intentional, not an error.

get

Get /ops/get | Auth: Read

Get element details

Element is already resolved by the routing layer — this returns the cached element, not a fresh DB query. Use the path /api/{circle}/{slug} to address elements.

get_attached_modifiers

Get /ops/attached | Auth: Read

Get elements that are attached to this action

import_bundle

Post /ops/import/bundle | Auth: Write

Import git bundle into element

Accepts a base64-encoded git bundle in the JSON bundle_base64 field. Use overwrite=true to replace existing elements with same slug (default skips duplicates). Imported elements get new UUIDs. Returns counts of imported/skipped elements and any errors.

intention

Get /ops/intention | Auth: Read

Get element intention with full inheritance chain

Returns three levels: direct (this element’s intention), inherited (from category and root), and resolved (final merged intention). Useful for understanding an element’s purpose in context of its hierarchy.

invoke

Post /ops/invoke | Auth: Execute

Execute the Ruby handler with the provided input

Run the element’s Ruby handler method. Pass any JSON-serializable object as input. Returns the handler’s return value as output. Input contract: your handler receives the caller’s data as a Ruby Hash with string keys. The platform auto-unwraps envelope keys (payload, data, input) so you always get the clean payload. Execution runs in a Firecracker microVM with the configured memory_mb and timeout_ms limits.

list_attachments

Get /ops/targets | Auth: Read

List all elements this action is attached to

Returns all target elements where this action is currently attached. Shows target_id, target_type, priority, and cascade_policy.

logs

Get /ops/logs | Auth: Read

Stream recent execution logs

Returns log lines from the most recent executions. Use since_run_id to fetch only logs after a specific run. Logs include stdout/stderr output from the Ruby process.

promote

Post /ops/promote | Auth: Admin

Promote element configuration to a target environment

Only for manifest-form elements (projects). Environments advance: dev → demo → live. dev→demo requires member+ role, demo→live requires admin. Freezes member versions at promotion time (creates snapshot). Persists environment config to spec.environments.

readme

Get /ops/readme | Auth: Read

Get element README.md content

Reads README.md from the element’s git repository. Returns empty content (not an error) if no README exists. Always returns markdown format.

readme_update

Post /ops/readme_update | Auth: Write

Update element README.md content

Creates or overwrites README.md in the element’s git repo. Commits to the draft branch. Content must be provided as a markdown string.

remove-modifier

Post /ops/remove-modifier | Auth: Execute

Remove an attached modifier from this element by attachment ID

Removes a modifier/resource attachment by its row ID. The ID comes from the attachments or context API. This is the reverse of attach — called on the target element, not the source.

restore

Post /ops/restore | Auth: Admin

Restore element to a specific version

Automatically snapshots the current state before restoring (creates a ‘Before restore to vN’ version entry). Writes restored spec to git as .triform/spec.yaml. Git failures warn but don’t fail the operation — DB state is authoritative. Cannot restore deleted elements.

run_cancel

Post /ops/runs/{run_id}/cancel | Auth: Execute

Cancel a running execution

Only works on runs with status pending or running. Already-completed or failed runs cannot be cancelled. The run transitions to cancelled state and triggers run.cancelled event.

run_get

Get /ops/runs/{run_id} | Auth: Read

Get details of a specific run

Retrieve full details for a single run including input, output, logs, and resource usage. Pass run_id as a path parameter.

runs

Get /ops/runs | Auth: Read

List recent execution runs

Returns a paginated list of recent invocations ordered by started_at descending. Use limit and offset for pagination. Each run includes run_id, status, duration_ms, started_at, and a summary of input/output.

schema

Get /ops/schema | Auth: Read

Get input/output port schemas (MCP tools/list compatible)

Call this before invoking an actor to discover its expected input/output format. Returns MCP-compatible tool definitions — useful for building dynamic tool UIs or A2A integration.

source

Get /ops/source | Auth: Read

Get any file’s content from the element’s git repository

Reads an arbitrary file from the element’s CAS-backed git tree by its relative path. Same store as readme, just generalized. Path safety: rejects .. traversal, leading /, and null bytes. Use this to view main.py for action elements, asset files for SPAs, etc. Returns empty content (not an error) if the file doesn’t exist.

source_branches

Get /ops/source/branches | Auth: Read

List Source branches for this element

Returns the standard draft/demo/live Source branches, their current commits, and promotion relationships. Use GET /api/{element_path}/ops/source/branches.

source_promote

Post /ops/source/promote | Auth: Write

Promote Source branch forward

Promotes draft to demo or demo to live through the generated element op path. Direct Git pushes to demo/live are blocked by Source policy.

source_repair

Post /ops/source/repair | Auth: Write

Inspect or repair the element Source index

Runs Source repair through the element operation path. Defaults to dry_run=true; set dry_run=false only after reviewing a dry-run report.

source_status

Get /ops/source/status | Auth: Read

Get Source control status for this element

Returns the branch-aware clone URL, checkout commands, current draft commit, child source-link count, portable export summary, Source health, warnings, and auth hints for the addressed element. Use the element-first path: GET /api/{element_path}/ops/source/status.

source_validate

Post /ops/source/validate | Auth: Read

Validate Source branch contents

Validates a Source branch before accepting local Git workflow changes or promotion. Defaults to branch=draft and rejects runtime data, generated output, secret material, and unreadable CAS refs.

stats

Get /ops/stats | Auth: Read

Get aggregate statistics for this element

Health status is computed: error if errors_per_day > 5 or success_rate < 0.8, warning if errors_per_day > 0 or success_rate < 0.95. Firing alerts escalate health to error/warning. Default period is ‘day’. Returns runs_per_day, success_rate, avg_duration_ms, and more.

tree

Get /ops/tree | Auth: Read

Get the element’s position in the graph — ancestors, children, references, and subtree statistics

Uses per-circle ElementGraph cache for O(1) lookups. Returns ancestors (containment chain), children (direct), members (references), referenced_by (reverse refs), attachments, and subtree stats. Default depth is 3, max is 10. Pass ?include_metadata=true for name/state on each node.

update

Patch /ops/update | Auth: Write

Update element

Partial update — send only the fields you want to change. spec, name, and intention are all independently optional. spec MUST be a JSON object when present; deep-merged into the existing spec by default. Empty {"spec":{}} preserves existing spec content but still records a new version (no-op for content, not for version state). To clear/replace the entire spec wholesale send {"spec":{...},"deep":false}. List-typed spec fields use replace semantics (the patch list replaces the existing list, no array merging). Coordinates Git + DB writes. Slug cannot be changed after creation.

update_meta

Patch /ops/update_meta | Auth: Write

Update element metadata (lightweight merge — does NOT bump version or snapshot spec)

Shallow JSONB merge into element.meta. Top-level keys in the provided value replace existing meta values; other keys are preserved. Used for UI metadata like canvas positions, panel state, viewer preferences. Wire-shape op_name is update_meta (distinct from update) so SSE subscribers + the cache auto-invalidator can distinguish lightweight metadata changes from spec edits without inspecting the payload. The MutatingElementStore wrapper stamps this op_name on the lifecycle event emitted by update_element_meta storage calls.

validate_source

Post /ops/validate_source | Auth: Write

Parse and validate Ruby source code without executing it

Syntax-check the Ruby source and verify the handler method exists. Pass source object with code field. Returns valid (boolean) and errors array with line/column/message entries. Use this before saving spec to catch issues early.

version

Get /ops/version | Auth: Read

Get current version or full history

Returns current version by default. Pass ?history=true for full version history (up to ?limit=N, default 50). Versions are backed by the element_versions table. Every spec update creates a new version entry.

Error Codes

CodeClassRetryableDescription
RUBY_EXECUTION_FAILEDinternalnoRuby code raised an unhandled exception
RUBY_TIMEOUTtimeoutyesExecution exceeded the configured timeout_ms
RUBY_SYNTAX_ERRORvalidationnoRuby source code has a syntax error
RUBY_HANDLER_NOT_FOUNDvalidationnoThe specified handler method was not defined in the source
RUBY_GEM_INSTALL_FAILEDvalidationyesOne or more gem dependencies could not be resolved
RUBY_MEMORY_EXCEEDEDinternalnoExecution exceeded the configured memory_mb limit

Lifecycle / runtime

Defined for this element

Before invoke

  • validate_source
  • resolve_data_sources
  • check_rate_limit

After invoke

  • record_metrics
  • emit_traces

On error

  • log_error
  • record_error_metric

Observability

Defined for this element

Metrics

  • ruby_invocation_count
  • ruby_duration_ms
  • ruby_error_rate
  • ruby_memory_used_mb
  • ruby_cold_start_ms

Events

  • ruby.invoked
  • ruby.completed
  • ruby.failed
  • ruby.cold_start

Pricing / cost

Inherited from actions

Operation costs

  • invoke: 10000 micro-AU