Download all docs
actions

Python

Serverless Python compute as a first-class element: your handler function runs in an isolated Firecracker VM with full network egress, pip dependencies, and per-invocation memory and timeout limits — the language is the element type, so there is nothing to configure but your code.

Working with it

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

Py
type

Python

Execute Python code in a sandboxed environment

actionsatomdefinition

When to use / not

When to use

  • Running ad-hoc Python logic — data wrangling, API glue, a quick transform — without standing up a server.
  • Reaching the Python ecosystem (requests, pandas, numpy, scipy) via pip dependencies cached into a pre-built layer.
  • Querying an attached sql, document, or vector element, whose connection is injected into the handler as an environment variable.
  • A serverless step inside an app or automation that scales to zero when idle and retries on transient failure.

When not to use

  • Writing the logic in another language — use the javascript, ruby, go-fn, rust-fn, or csharp action instead; the language is the element type.
  • Pausing a run for a human decision or approval — that is what the hitl action is for, not a code function.
  • Branching, looping, or sequencing other elements — express orchestration with automation (condition, loop, wait), not code inside one 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

requirementsobject
Pip dependencies as key-value map (e.g. {"requests": ">=2.31", "numpy": "*"}). Alternative to source.requirements array format.
handlerstring
Entry point function name. Your Python code must define this callable. When set explicitly (BUGS-483), the named function is invoked verbatim — case-sensitive — so `handler: "Handler"` calls `def Handler(...)`. If the named function isn't defined, the runtime errors with the list of actual callables in your code so you can spot the typo / case mismatch. When unset, falls back to the default lookup order: handler() -> main() -> entrypoint().
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
  • applyPOST
  • attachPOST
  • attachmentsGET
  • batch_statsGET
  • buildPOST
  • build_statusGET
  • composePOST
  • contextGET
  • createPOST
  • deleteDELETE
  • detachPOST
  • diagnosticsGET
  • disablePOST
  • enablePOST
  • export_bundleGET
  • getGET
  • get_attached_modifiersGET
  • import_bundlePOST
  • intentionGET
  • invokePOST
  • list_attachmentsGET
  • logsGET
  • measurePOST
  • 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
  • testPOST
  • test_statusGET
  • treeGET
  • updatePATCH
  • update_metaPATCH
  • versionGET

Ports

Inputs

  • payloadrequest
  • resultrequest
  • errorevent

Composition

Errors / when it fails

Inline source requires code in spec.source.code
Fails unless: source.code != null && len(source.code) > 0
File source requires spec.source.path
Fails unless: source.path != null && len(source.path) > 0
Git source requires spec.source.repository
Fails unless: source.repository != null && len(source.repository) > 0

Validation rules

  • High memory allocation (>2GB) may increase costs
  • Long timeout (>5min) — consider async processing patterns
  • Large number of pip dependencies may increase cold start time

Python (python)

Category: actions | Form: | Symbol: Py

Execute Python code in a sandboxed environment

Runs Python 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 function (default entry point is “handler”). Supports pip dependencies via spec.source.requirements. Attach data elements (sql, document, vector) to inject connections as environment variables.

Guide

Execute Python code in a sandboxed environment

What It Does

Python is a serverless compute element that runs Python code inside an isolated Firecracker VM. Unlike the old polyglot function element, the language is the element type — there is no runtime property to configure. Each Python element has a dedicated handler function, optional pip dependencies, and can receive injected connections from attached data elements.

Code runs with full network egress, a configurable memory ceiling, and per-invocation timeout enforcement. Dependencies are pre-built into cached layers to minimize cold start time.

Element Definition

PropertyValue
Typepython
Categoryfunctions
Formatom
Symbolcode / #3776AB

Properties

FieldTypeDefaultDescription
handlerstringhandlerEntry point function name in your Python code
source.typestringinlineSource location: inline, file, or git
source.codestringInline Python source (for type: inline)
source.pathstringFile path in workspace (for type: file)
source.repositorystringGit URL (for type: git)
source.refstringBranch, tag, or commit SHA (for type: git)
source.requirementsarray[]pip dependencies (e.g. ["requests==2.31.0"])
memory_mbinteger128Memory allocation in MB (64–4096)
timeout_msinteger30000Execution time limit in milliseconds (100–900000)
environmentobject{}Custom environment variables
layersarray[]Additional runtime layers
concurrency.reservedintegerReserved concurrent execution slots
concurrency.maxintegerMaximum concurrent executions
retry.max_attemptsinteger3Retry attempts on failure
retry.backoff_msinteger1000Initial backoff delay in ms
retry.backoff_multipliernumber2.0Exponential backoff multiplier

Ports

DirectionPortRequiredDescription
InputpayloadYesJSON input passed to the handler function
OutputresultHandler return value as JSON
OutputerrorError details if execution failed

Capabilities

CapabilityDescription
zero-scaleScales to zero when idle
streamingSupports output streaming
env-injectionData resources injected as environment variables
pip-dependenciesSupports pip package dependencies

Input Contract

Your handler receives the caller’s payload as a Python dict. 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}
    return {"greeting": f"Hello, {input['name']}!"}

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": "python",
  "slug": "my-python-fn",
  "name": "My Python Function",
  "spec": {
    "source": {
      "type": "inline",
      "code": "def handler(input):\n    return {\"message\": \"Hello, \" + input.get(\"name\", \"World\") + \"!\"}"
    },
    "memory_mb": 128,
    "timeout_ms": 10000
  }
}

Invoking

POST /api/{circle}/{project}/my-python-fn/ops/invoke
Content-Type: application/json

{
  "payload": { "name": "Triform" }
}

Writing Handler Functions

The handler function receives the input payload as a Python dict and must return a JSON-serializable value:

def handler(input):
    # input is a dict — the JSON payload from the invoke call
    name = input.get("name", "World")
    count = input.get("count", 1)

    results = []
    for i in range(count):
        results.append(f"Hello {name} #{i + 1}")

    return {
        "results": results,
        "total": count
    }

Entry Point Resolution

If spec.handler is not set, the runtime looks for a callable in this order:

  1. handler()
  2. main()
  3. A function matching the element slug (hyphens replaced with underscores)

Async Handlers

The runtime supports async handlers via asyncio:

import asyncio
import aiohttp

async def handler(input):
    url = input.get("url", "https://example.com")
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            return {"status": response.status, "url": str(response.url)}

Using pip Dependencies

List dependencies in spec.source.requirements. They are resolved at build time and cached as a layer:

{
  "spec": {
    "source": {
      "type": "inline",
      "code": "...",
      "requirements": ["requests>=2.31.0", "beautifulsoup4>=4.12.0"]
    }
  }
}

Pre-build the dependency layer to avoid cold start penalty:

POST /api/{circle}/{project}/my-python-fn/ops/build

Attaching Data Resources

Data elements (sql, document, vector) are injected as environment variables:

POST /api/{circle}/{project}/my-database/ops/attach
Content-Type: application/json

{ "target_id": "<python-element-uuid>" }

Inside the handler, access the injected connection strings:

import os

def handler(input):
    db_url = os.environ.get("RESOURCE_SQL_MY_DATABASE")
    # use db_url to connect to the database
    return {"connected": db_url is not None}
ResourceEnvironment variable pattern
sqlRESOURCE_SQL_{SLUG_UPPER}
documentRESOURCE_DOCUMENT_{SLUG_UPPER}
vectorRESOURCE_VECTOR_{SLUG_UPPER}
graphRESOURCE_GRAPH_{SLUG_UPPER}
timeseriesRESOURCE_TIMESERIES_{SLUG_UPPER}

Common Mistakes

Putting code at the wrong path. Code must be in spec.source.code, not spec.code. The source object wraps all source-related fields.

Forgetting to define a handler. The VM looks for a callable named handler by default. If your function uses a different name, set spec.handler to match.

Not pre-building dependencies. Without a cached layer, every cold start installs pip packages from scratch. For functions with heavy dependencies (numpy, pandas, scipy), call the build operation first.

Expecting fast cold starts with large dependency trees. Each pip dependency adds to cold start time. For latency-sensitive paths, keep requirements minimal or pre-warm instances via concurrency.reserved.

Workflows

getting-started

Build and deploy a Python function from scratch

  1. Write handler code - Define a handler(event, context) function — it’s your entry point triform_workspace(action: "open", slug: "{slug}")
  2. Add dependencies - List pip packages in spec.source.requirements (one per line) triform_ops(action: "call", slug: "{slug}", operation: "update", input: { spec: { source: { requirements: "requests\npandas" } } })
  3. Test locally - Runs in a sandboxed VM — check output and logs triform_ops(action: "call", slug: "{slug}", operation: "execute")
  4. Deploy to an app - Create an app, then add this function to it triform_element(action: "create", element_type: "app", name: "my-app", intention: "...")

State Guidance

StateGuidanceNext actions
deployedElement is deployed and running in an app.Invoke: triform_ops(action: "call", slug: "{slug}", operation: "invoke")
draftElement is in draft — write your handler code and scaffold before transitioning to ready.Scaffold code: triform_ops(action: "call", slug: "{slug}", operation: "scaffold")
Open to write code: triform_workspace(action: "open", slug: "{slug}")
errorElement is in error state. Check logs, fix the issue, then transition back to draft.View logs: triform_ops(action: "call", slug: "{slug}", operation: "logs")
Reset to draft: triform_ops(action: "call", slug: "{slug}", operation: "lifecycle", input: { target_state: "draft" })
readyCode is ready. Execute directly or deploy to an app.Execute: triform_ops(action: "call", slug: "{slug}", operation: "execute")
Add to an app: triform_element(action: "create", element_type: "app", name: "my-app", intention: "...")

Authoring Hints

FieldHelpExample
environmentEnvironment variables. Key-value pairs injected at runtime. Data source connections are auto-injected as RESOURCE_SQL_{NAME}.``
handlerEntry point. Function name to call. Lookup order: handler() → main() → {slug}().handler
memory_mbMemory (MB). VM memory allocation. Range 64–4096 MB. Default 128.``
source.codeHandler code. Inline Python source. Must define the handler entry point (default name: handler).def handler(event, context):<br> name = event.get("name", "world")<br> return {"message": f"Hello, {name}!"}
source.requirementspip dependencies. List of pip packages, one per line. Resolved at compile time.requests==2.31.0<br>numpy>=1.26
source.typeSource type. Where the code lives: inline (spec.source.code), file (workspace path), or git (remote repo).``
timeout_msTimeout (ms). Max execution time. Default 30000 (30 seconds).``

Error Recovery

ErrorRecovery guidanceNext actions
executionRuntime error during execution. Check logs for the stack trace.View logs: triform_ops(action: "call", slug: "{slug}", operation: "logs")
Open to debug: triform_workspace(action: "open", slug: "{slug}")
resource_not_foundA referenced resource (data source, dependency) was not found.Check data sources: triform_ops(action: "call", slug: "{slug}", operation: "get")
timeoutExecution timed out. The function exceeded spec.timeout_ms.Increase timeout: triform_ops(action: "call", slug: "{slug}", operation: "update", input: { spec: { timeout_ms: 60000 } })
View logs: triform_ops(action: "call", slug: "{slug}", operation: "logs")
validationCode validation failed. Check that your handler function is defined correctly.Open to fix: triform_workspace(action: "open", slug: "{slug}")

Relationships

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

Capabilities

  • zero-scale: Scales to zero when idle
  • streaming: Supports output streaming
  • env-injection: Data resources injected as environment variables
  • pip-dependencies: Supports pip package dependencies

Properties

PropertyTypeDefaultDescription
runtimestringLanguage runtime (informational only — always python for this element type)
requirementsobjectPip dependencies as key-value map (e.g. {“requests”: “>=2.31”, “numpy”: “*”}). Alternative to source.requirements array format.
handlerstringEntry point function name. Your Python code must define this callable.
When set explicitly (BUGS-483), the named function is invoked verbatim —
case-sensitive — so handler: "Handler" calls def Handler(...). If
the named function isn’t defined, the runtime errors with the list of
actual callables in your code so you can spot the typo / case mismatch.
When unset, falls back to the default lookup order: handler() ->
main() -> entrypoint().
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).

apply

Post /ops/apply | Auth: Execute

Run the Layer-3 apply-evidence-rules engine synchronously and return findings + traces inline

Phase C.2 Layer-3 contract. Used today only by the apply-evidence-rules element on ridango-fi: consumes measurements[] from the Layer-2 measure-* fan-out plus the active rules_profile and per-detector context, and returns findings[] + rule_traces[] inline. Distinct from invoke (async + run-id polling) for the same reason as measure: the SPA awaits the envelope directly. Canonical consumer at processing.svelte.ts:1719.

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

Compile dependencies and create a cached layer

Pre-builds pip dependencies and caches them as a layer. Subsequent invocations skip dependency installation. Use force=true to rebuild even if a cached layer exists.

build_status

Get /ops/build/{build_id} | Auth: Read

Check the status of a build

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

Execute the Python function with an input payload

Main entry point for Python function execution. Requires a JSON payload. Returns invocation_id for async tracking. Input contract: your handler receives the caller’s data as a Python dict. The platform auto-unwraps envelope keys (payload, data, input) so you always get the clean payload. Example: def handler(input): return {“greeting”: f“Hello, {input[‘name’]}!“}

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

Get execution logs

measure

Post /ops/measure | Auth: Execute

Run a Layer-2 detector measurement synchronously and return the envelope inline

Phase C.2 Layer-2 contract used by Ridango’s evidence-rules pipeline. The element’s main.py handler runs with the caller’s payload and produces a measurement envelope; the platform returns that envelope directly with no run_id polling. Used by runDirectReviewScan (processing.svelte.ts:1633) to fan out ~23 measure-* detectors at concurrency 4. The element’s main.py must produce the MeasureEnvelope shape — see processing.svelte.ts L1595-L1615 for the consumer’s type definition.

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/{invocation_id} | Auth: Read

Get details of a specific invocation

runs

Get /ops/runs | Auth: Read

List invocation history

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.

test

Post /ops/test | Auth: Execute

Run the function’s test suite

Executes tests defined alongside the function source. Uses pytest by default. Filter with test_filter to run a subset of tests. Returns test_run_id for async status tracking.

test_status

Get /ops/test/{test_run_id} | Auth: Read

Check the status of a test run

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.

Error Codes

CodeClassRetryableDescription
PYTHON_TIMEOUTtimeoutyesExecution exceeded timeout_ms
PYTHON_OOMinternalnoOut of memory (exceeded memory_mb)
PYTHON_SYNTAX_ERRORvalidationnoPython syntax error in source code
PYTHON_IMPORT_ERRORinternalnoFailed to import required dependency
PYTHON_RUNTIME_ERRORinternalnoUnhandled Python exception during execution

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

  • python_invocation_count
  • python_duration_ms
  • python_cold_start_count
  • python_cold_start_duration_ms
  • python_memory_used_mb
  • python_error_rate

Events

  • python.invoked
  • python.completed
  • python.failed
  • python.cold_start
  • python.build.*

Pricing / cost

Inherited from actions

Operation costs

  • invoke: 10000 micro-AU