Download all docs
agents

Open Code

The provider-agnostic coding agent: the open-source Open Code CLI running as a real terminal inside a sandboxed Firecracker VM, free to drive Claude, OpenAI, Gemini, or any of 20+ providers — the multi-provider sibling of claude-code, with the same start/stop/snapshot session lifecycle.

Working with it

Opening a Open Code launches a terminal session — its dedicated working surface.

How it appears

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

Oc
type

Open Code

Open-source, provider-agnostic AI coding agent — real CLI terminal in a sandboxed VM

agentsatomdefinition

When to use / not

When to use

  • You want a coding agent but need provider flexibility — Claude today, OpenAI or Gemini tomorrow — by setting one provider-prefixed model string.
  • You prefer open-source agent tooling over a vendor-locked CLI, while keeping Triform's sandboxed-VM execution and snapshot/restore.
  • You want an interactive PTY terminal a collaborator can drive live, or a headless single-prompt run that returns JSON — both from the same element.

When not to use

  • You are Anthropic-only and want the first-party experience — use claude-code instead.
  • You need a composable agent where you control exactly which tools are exposed — use triformer.
  • You just need to run a function or call an API, with no agentic loop — reach for an actions element (python, javascript, …) or http.

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

idle_timeout_secondsinteger
Seconds of inactivity before the VM is snapshotted. Lower = faster resource reclaim, higher = less snapshot/restore churn.
session_ttl_hoursinteger
Maximum session lifetime in hours. After this, the snapshot is discarded and a new session must be started.
auto_resumeboolean
Automatically restore the last session when reopening the terminal. If false, starts a fresh session.
memory_mbinteger
VM memory in MB. Open Code needs ~256MB, rest is for tool execution.
vcpusinteger
Virtual CPUs for the VM
disk_gbinteger
Workspace disk size in GB
network_accessboolean
Allow outbound network access from the VM (needed for provider API calls and package installs)
terminal_colsinteger
Initial terminal width in columns
terminal_rowsinteger
Initial terminal height in rows
shellstring
Login shell before opencode CLI is started
providerstring
Default LLM provider (e.g., anthropic, openai, google, openrouter)
modelstring
Default model in provider/model format. Use triform/ prefix for models from the intelligence layer (e.g., triform/claude-sonnet-4-6, triform/gpt-4.1). Direct provider models also work (e.g., anthropic/claude-sonnet-4-6, openai/gpt-4.1).
opencode_configobject
Optional Open Code settings written to opencode.jsonc in the workspace
workspace_sourcestring
What to mount as /workspace. 'circle' = full circle repo, 'empty' = blank workspace.
mount_readonly_pathsarray
Additional paths mounted read-only into the VM (e.g., shared libraries)

Capabilities

Defined for this element
  • Compute
  • Llm
  • Storage
  • Observe

Operations

  • activityGET
  • attachPOST
  • attachmentsGET
  • batch_statsGET
  • composePOST
  • contextGET
  • createPOST
  • deleteDELETE
  • detachPOST
  • disablePOST
  • discard_sessionPOST
  • enablePOST
  • export_bundleGET
  • getGET
  • get_attached_modifiersGET
  • import_bundlePOST
  • intentionGET
  • invokePOST
  • list_attachmentsGET
  • logsGET
  • promotePOST
  • readmeGET
  • readme_updatePOST
  • remove-modifierPOST
  • resize_terminalPOST
  • restorePOST
  • run_cancelPOST
  • run_getGET
  • runsGET
  • schemaGET
  • session_getGET
  • sessionsGET
  • sourceGET
  • source_branchesGET
  • source_promotePOST
  • source_repairPOST
  • source_statusGET
  • source_validatePOST
  • start_sessionPOST
  • statsGET
  • stop_sessionPOST
  • treeGET
  • updatePATCH
  • update_metaPATCH
  • versionGET
  • write_stdinPOST
  • ws-terminalGET

Ports

Inputs

  • sessionrequest
  • sessionrequest

Composition

Errors / when it fails

network_access must be true — Open Code requires outbound access for provider API calls
Fails unless: false

Validation rules

  • High memory allocation (>4GB) — increases snapshot size and restore time
  • Very short idle timeout (<15s) — may cause excessive snapshot/restore cycles
  • Long session TTL (>72h) — snapshot storage accumulates
  • Large disk (>20GB) — increases VM boot time and snapshot size

Open Code (open-code)

Category: agents | Form: | Symbol: Oc

Open-source, provider-agnostic AI coding agent — real CLI terminal in a sandboxed VM

Runs the open-source Open Code CLI as an interactive terminal session. All models from the Triform intelligence layer are auto-available via the triform/ prefix (e.g., triform/claude-sonnet-4-6, triform/gpt-4.1). Also supports direct provider access (anthropic/, openai/, groq/, etc.). Same session lifecycle as claude-code (start_session, stop_session, resize_terminal). Requires CODER_WORKER_URL for interactive mode. Set spec.model (default: triform/claude-sonnet-4-6). Set spec.default_agent (default: build) to select the Open Code agent type. Headless mode via generate/invoke produces JSON output. All sessions run in Firecracker VMs with snapshot/restore. Timeout defaults to 5 minutes. Use this when you need multi-provider flexibility or open-source tooling. For Anthropic-only, use claude-code. For composable tool-based agents, use agent.

Guide

Open-source, provider-agnostic AI coding agent — real CLI terminal in a sandboxed VM

What It Does

Open Code runs the open-source Open Code CLI as an interactive terminal session inside a Firecracker VM. It supports Claude, OpenAI, Gemini, and 20+ other LLM providers, making it the multi-provider alternative to Claude Code. The session lifecycle is identical to Claude Code: PTY-over-WebSocket for interactive use, NDJSON streaming for headless execution, and snapshot/restore for session persistence.

Element Definition

PropertyValue
Typeopen-code
Categoryagents
Formatom
Symbolterminal / #22C55E

Properties

FieldTypeDefaultDescription
modelstringanthropic/claude-sonnet-4-6Model with provider prefix (e.g., openai/gpt-4.1)
default_agentstringbuildOpen Code agent type to use
timeout_msinteger300000Maximum execution time (5 minutes default)

Topology

  • Lives in: agents/open-code/ repository
  • Referenced by: projects
  • Accepts modifiers: rate-limit, auth-policy, protection

Quick Start

Creating via API

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

{
  "element_type": "open-code",
  "slug": "my-opencode",
  "name": "My Open Code",
  "spec": {
    "model": "anthropic/claude-sonnet-4-6",
    "default_agent": "build"
  }
}

Interactive Session

POST /api/{circle}/{project}/my-opencode/ops/start_session

{
  "cols": 120,
  "rows": 40
}

Headless Execution

POST /api/{circle}/{project}/my-opencode/ops/invoke

{
  "prompt": "Refactor the database module to use connection pooling"
}

Operations

OperationMethodDescription
start_sessionPOSTStart interactive terminal session
stop_sessionPOSTStop/suspend a session
resize_terminalPOSTResize terminal dimensions
sessionsGETList all sessions
session_getGETGet session details
discard_sessionPOSTPermanently delete session
generate/invokePOSTHeadless single-prompt execution
generationsGETList generation history
generation_getGETGet generation details

Common Mistakes

Model name missing provider prefix. Unlike Claude Code, Open Code requires provider-prefixed model names: anthropic/claude-sonnet-4-6, not just claude-sonnet-4-6. The prefix routes to the correct backend.

No isolation executor configured. Interactive sessions require CODER_WORKER_URL. Without it, start_session fails.

Choosing between open-code and claude-code. Use open-code when you need multi-provider support or open-source tooling. Use claude-code for Anthropic-only use cases. Use triformer for composable tool-based workflows where you control exactly which tools are available.

Relationships

  • Attaches to: rate-limit, auth-policy, api-token, filter-words, evaluator, prompt, variable
  • Uses: sql, document, vector, graph, timeseries

Capabilities

  • companion: Can serve as an interactive companion in the workspace
  • interactive-terminal: Real PTY terminal with bidirectional I/O over WebSocket
  • snapshot-restore: VM snapshotted on idle, restored in ~22ms on interaction
  • coding: Full coding capabilities via Open Code’s built-in tools
  • multi-provider: Supports 20+ LLM providers — Claude, OpenAI, Gemini, and more
  • persistence: Session state persists across snapshots via VM memory + disk
  • workspace-access: Circle workspace mounted into VM filesystem
  • server-mode: Can run as a headless server for programmatic API access

Properties

PropertyTypeDefaultDescription
idle_timeout_secondsinteger30Seconds of inactivity before the VM is snapshotted. Lower = faster resource reclaim, higher = less snapshot/restore churn.
session_ttl_hoursinteger24Maximum session lifetime in hours. After this, the snapshot is discarded and a new session must be started.
auto_resumebooleantrueAutomatically restore the last session when reopening the terminal. If false, starts a fresh session.
memory_mbinteger1024VM memory in MB. Open Code needs ~256MB, rest is for tool execution.
vcpusinteger2Virtual CPUs for the VM
disk_gbinteger10Workspace disk size in GB
network_accessbooleantrueAllow outbound network access from the VM (needed for provider API calls and package installs)
terminal_colsinteger120Initial terminal width in columns
terminal_rowsinteger40Initial terminal height in rows
shellstring"/bin/bash"Login shell before opencode CLI is started
providerstring"anthropic"Default LLM provider (e.g., anthropic, openai, google, openrouter)
modelstring"triform/claude-sonnet-4-6"Default model in provider/model format. Use triform/ prefix for models from the intelligence layer (e.g., triform/claude-sonnet-4-6, triform/gpt-4.1). Direct provider models also work (e.g., anthropic/claude-sonnet-4-6, openai/gpt-4.1).
opencode_configobjectOptional Open Code settings written to opencode.jsonc in the workspace
workspace_sourcestring"circle"What to mount as /workspace. ‘circle’ = full circle repo, ‘empty’ = blank workspace.
mount_readonly_pathsarray[]Additional paths mounted read-only into the VM (e.g., shared libraries)

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.

detach

Post /ops/detach | Auth: Read

Detach this actor from a target element

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.

discard_session

Post /ops/session/discard | Auth: Execute

Permanently delete a suspended session’s snapshot

Permanently delete a session and its snapshot. Cannot be undone.

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 actor

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

Invoke the actor with input

Always include data:{} even for no-input actors. Use ?stream=true for streaming output (agents support this). Use ?async=true to get a run_id immediately and poll via run_get. Input must match the actor’s port schema (check via schema operation). Creates a run record in execution history.

list_attachments

Get /ops/targets | Auth: Read

List all elements this agent is attached to

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

logs

Get /ops/logs | Auth: Read

Get execution logs

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.

resize_terminal

Post /ops/session/resize | Auth: Execute

Resize the terminal (sent when the portal window changes size)

Resize an active terminal session. Pass terminal_id, cols, rows.

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

runs

Get /ops/runs | Auth: Read

List execution runs

Filter with ?status=completed|failed|running, paginate with ?limit=N&offset=N. Default limit is 50. Returns total count for pagination.

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.

session_get

Get /ops/sessions/{session_id} | Auth: Read

Get details of a specific session

Get details of a specific session by session_id.

sessions

Get /ops/sessions | Auth: Read

List all sessions for this element (active, suspended, terminated)

List all terminal sessions for this element.

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.

start_session

Post /ops/session/start | Auth: Execute

Start or resume an interactive Open Code terminal session

Start an interactive Open Code terminal session. Same lifecycle as claude-code but runs the opencode binary. Set cols/rows for terminal size (defaults: 120x40). Returns ws_path for WebSocket connection. Requires CODER_WORKER_URL.

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.

stop_session

Post /ops/session/stop | Auth: Execute

Stop an active session. Snapshots automatically unless force_terminate=true.

Stop a running terminal session. Pass terminal_id. Set force_terminate: true to kill immediately, otherwise session is suspended for later restore.

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.

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.

write_stdin

Post /ops/session/stdin | Auth: Execute

Write a line of text to a running terminal session’s stdin PTY.

Sends text + newline to the PTY of a running session. Does not await output — use ws-terminal WebSocket for streaming output. Requires a running session_id. Returns {written: true} on success.

ws-terminal

Get /ops/ws/terminal | Auth: Write

Interactive Open Code PTY terminal over WebSocket. Binary frames carry raw PTY I/O; text frames carry JSON control messages (resize, lifecycle, ping).

Error Codes

CodeClassRetryableDescription
OPEN_CODE_VM_FAILEDinternalyesFirecracker VM failed to start or crashed
OPEN_CODE_SNAPSHOT_FAILEDinternalyesVM snapshot failed — session continues but won’t survive disconnect
OPEN_CODE_RESTORE_FAILEDinternalyesFailed to restore from snapshot — falls back to new session
OPEN_CODE_SESSION_EXPIREDtimeoutnoSession TTL exceeded — snapshot discarded
OPEN_CODE_RESOURCE_LIMITlimitnoVM resource limits exceeded (memory, disk, CPU)
OPEN_CODE_PROVIDER_ERRORinternalyesLLM provider API returned an error (auth, rate limit, etc.)

Lifecycle / runtime

Defined for this element

Before invoke

  • validate_input
  • resolve_brain
  • resolve_tool_elements
  • check_rate_limit

After invoke

  • record_metrics
  • emit_traces

On error

  • log_error
  • record_error_metric

Observability

Defined for this element

Metrics

  • session_count
  • session_active_duration_ms
  • session_wall_duration_ms
  • snapshot_count
  • restore_count
  • restore_latency_ms
  • snapshot_size_bytes
  • files_modified
  • error_rate
  • concurrent_active_sessions
  • provider_request_count
  • provider_error_count

Events

  • open_code.session.started
  • open_code.session.suspended
  • open_code.session.resumed
  • open_code.session.terminated
  • open_code.session.expired

Pricing / cost

Inherited from agents

Operation costs

  • invoke: 10000 micro-AU

Set it up

Providerstring
LLM provider for the coding session
Modelstring
Model identifier (e.g., claude-sonnet-4-6)