Download all docs
actions

Go

A compiled-Go compute element: write a Handler in Go, and Triform builds it once, caches the binary, and runs it inside an isolated Firecracker microVM — giving you fast cold starts, a tiny footprint, and goroutine concurrency.

Working with it

Opening a Go 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.

Go
type

Go

Execute compiled Go code in a sandboxed environment

actionsatomdefinition

When to use / not

When to use

  • You want a function that starts fast and stays lean — the binary is compiled ahead of time and cached, so invocations skip the warm-up cost.
  • Your workload is concurrent — fanning out parallel calls, pipelines, or worker patterns where goroutines are the natural fit.
  • You already have Go logic — paste it inline, pull in Go modules via requirements, or point at a Git repository.
  • You need a typed, sandboxed compute step wired between other elements — a webhook feeds it, it transforms, and it writes to a database.

When not to use

  • You want to iterate without a compile step — `python` or `javascript` run interpreted, so quick edits skip the build wait.
  • You need maximum throughput or memory-tight numeric work — `rust-fn` is the other compiled peer and trades Go's simplicity for tighter control.
  • The step is a human decision rather than code — use `hitl` to pause for approval instead of executing 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

sourceobjectrequired
Source code configuration
handlerstring
Entry point function. Must be exported (capitalized).
timeout_msinteger
Maximum execution time in milliseconds

Capabilities

Defined for this element
  • Compute
  • Observe
  • Storage

Operations

  • activityGET
  • attachPOST
  • attachmentsGET
  • batch_statsGET
  • buildPOST
  • composePOST
  • contextGET
  • createPOST
  • deleteDELETE
  • 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
  • validatePOST
  • versionGET

Ports

Inputs

  • inputrequest
  • outputrequest
  • errorevent

Composition

Errors / when it fails

source.code is required when source.type is inline
Fails unless: source.code != null && source.code != ''
source.git_url is required when source.type is git
Fails unless: source.git_url != null && source.git_url != ''
handler must be an exported Go function name (start with a capital letter, e.g. Handler)
Fails unless: handler =~ '^[A-Z][a-zA-Z0-9_]*$'

Validation rules

  • memory_mb over 1024MB — consider whether your function truly needs this much memory
  • timeout_ms over 5 minutes — long-running functions may be better suited to an agent element
  • Pinning to 'main' branch means code changes automatically — consider pinning to a commit SHA for stable deployments

Go (go-fn)

Category: actions | Form: | Symbol: Go

Execute compiled Go code in a sandboxed environment

Compiles and runs Go code in a sandboxed Firecracker VM. Code is compiled ahead of time and cached. Go functions offer fast startup and excellent concurrency. Put your code in spec.source.code or point to a git repository. Your code must define a Handler function. Supports Go modules via spec.source.requirements.

Guide

Execute compiled Go code in a sandboxed Firecracker VM.

Overview

The go-fn element compiles your Go source code and runs the resulting binary inside a Firecracker microVM. The compiled binary is cached in object storage — subsequent invocations skip compilation and start immediately. Go functions offer fast startup times, a small binary footprint, and first-class support for concurrent workloads via goroutines.

Input Contract

Your Handler receives a map[string]interface{} containing the caller’s payload. 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-greeter/ops/invoke
{"name": "Alice", "count": 3}
func Handler(input map[string]interface{}) (map[string]interface{}, error) {
    // input = map["name":"Alice" "count":3]
    name, _ := input["name"].(string)
    return map[string]interface{}{"greeting": fmt.Sprintf("Hello, %s!", name)}, nil
}

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

POST /api/{circle}/my-greeter/ops/invoke
{"payload": {"name": "Alice"}}
// Handler still receives map["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

element_type: go-fn
slug: my-greeter

spec:
  source:
    type: inline
    code: |
      package main

      import "fmt"

      func Handler(input map[string]interface{}) (map[string]interface{}, error) {
          name, _ := input["name"].(string)
          if name == "" {
              name = "World"
          }
          return map[string]interface{}{
              "message": fmt.Sprintf("Hello, %s!", name),
          }, nil
      }
  handler: Handler

Source Configuration

Inline Code

Set spec.source.type: inline and provide your code in spec.source.code. The Handler function must be exported (capital first letter) and accept map[string]interface{} as input.

Go Module Dependencies

Add module dependencies in spec.source.requirements. These lines are appended to the require block in go.mod:

spec:
  source:
    type: inline
    code: |
      package main

      import (
        "github.com/tidwall/gjson"
      )

      func Handler(input map[string]interface{}) (map[string]interface{}, error) {
          // ...
          return map[string]interface{}{}, nil
      }
    requirements: |
      github.com/tidwall/gjson v1.18.0

Git Repository

Point to a Git repository containing your Go module:

spec:
  source:
    type: git
    git_url: "https://github.com/example/my-fn.git"
    git_ref: "v1.0.0"
  handler: Handler

Handler Signature

Your Handler must be a public (exported) function. Supported signatures:

// Standard: input map + error return
func Handler(input map[string]interface{}) (map[string]interface{}, error)

// With context (for cancellation / timeout propagation)
func Handler(ctx context.Context, input map[string]interface{}) (map[string]interface{}, error)

The function name must match spec.handler (default: Handler).

Resource Limits

FieldDefaultRange
timeout_ms30000100 – 900000
memory_mb12864 – 4096

Operations

OperationDescription
invokeCall the Handler with input data
buildCompile ahead of time (pre-warm cache)
validateRun go vet without building
runsList recent invocation history
run_getFetch details for a specific run
logsFetch stdout/stderr from runs

Wiring

Connect this function to other elements via wires:

wires:
  - source: my-webhook
    target: my-greeter
  - source: my-greeter
    target: my-database

Error Codes

CodeDescription
GO_FN_COMPILATION_FAILEDgo build error
GO_FN_EXECUTION_FAILEDRuntime panic or returned error
GO_FN_TIMEOUTExceeded timeout_ms
GO_FN_MEMORY_EXCEEDEDExceeded memory_mb
GO_FN_INVALID_OUTPUTHandler returned non-serializable value
GO_FN_HANDLER_NOT_EXPORTEDHandler name does not start with a capital letter

Relationships

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

Capabilities

  • compiled: Code is compiled ahead-of-time; binary is cached between invocations
  • go-modules: Supports Go module dependencies via spec.source.requirements
  • sandboxed: Runs inside a Firecracker microVM with strict resource limits
  • binary-cache: Compiled binary is cached and reused on subsequent invocations
  • concurrency: Go goroutines and channels available for concurrent workloads

Properties

PropertyTypeDefaultDescription
sourceobjectSource code configuration
handlerstring"Handler"Entry point function. Must be exported (capitalized).
envobjectEnvironment variables injected at runtime
timeout_msinteger30000Maximum execution time in milliseconds
memory_mbinteger128Memory limit for the sandbox VM in megabytes
data_sourcesarrayData elements this function can access

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.

build

Post /ops/build | Auth: Write

Compile the Go function ahead of time

Trigger a go build without invoking the Handler. Useful to pre-warm the binary cache or validate that compilation succeeds before deployment. Returns build status and any compiler diagnostics.

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

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

Invoke the Go function with input data

Call the compiled Go Handler with a JSON payload. The function is compiled on first invoke (or after source changes) and the binary is cached. Returns the Handler’s return value as JSON. Input contract: your Handler receives the caller’s data as map[string]interface{}. The platform auto-unwraps envelope keys (payload, data, input) so you always get the clean payload.

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 or fetch logs from recent function invocations

Fetch stdout/stderr logs from function runs. Filter by run_id to see logs from a specific invocation. Supports tail (last N lines) or since (timestamp). Returns log lines with timestamps.

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 for a specific invocation run

Fetch full details for a run including input, output, error (if any), and execution metadata. run_id is required.

runs

Get /ops/runs | Auth: Read

List recent invocation runs

Returns recent runs for this function with status, duration, and timestamps. Supports pagination via cursor. Each run includes run_id you can use with run_get to fetch full 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

Post /ops/validate | Auth: Read

Validate Go source code and module dependencies

Run go vet and syntax checking against the source code without building a binary. Faster than a full build — catches compilation errors and type mismatches. Returns valid (boolean), errors, and warnings.

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
GO_FN_COMPILATION_FAILEDvalidationnoGo compilation error — check your source code and go.mod dependencies
GO_FN_EXECUTION_FAILEDinternalyesRuntime panic or returned error from the Handler function
GO_FN_TIMEOUTtimeoutyesFunction execution exceeded timeout_ms limit
GO_FN_MEMORY_EXCEEDEDinternalnoFunction exceeded its memory_mb allocation
GO_FN_INVALID_OUTPUTvalidationnoHandler returned a value that could not be serialized to JSON
GO_FN_HANDLER_NOT_EXPORTEDvalidationnoHandler function must be exported (start with a capital letter)

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

  • go_fn_invocation_count
  • go_fn_duration_ms
  • go_fn_error_rate
  • go_fn_build_duration_ms
  • go_fn_cache_hit_rate

Events

  • go_fn.invoked
  • go_fn.completed
  • go_fn.failed
  • go_fn.build_completed

Pricing / cost

Inherited from actions

Operation costs

  • invoke: 10000 micro-AU