logic.code component executes custom Python code safely within the workflow execution environment. It provides a
sandboxed space equipped with helpers for input/output data handling and flow control.
Runtime Environment
The execution occurs inside a hardened Python 3 environment.Available Modules
You can leverage several standard libraries and helpful built-ins: Standard Libraries:json,uuid,time,datetime,zoneinfofunctools,traceback,copy,decimaltextwrap,math,re,abctyping,Union,Literal
ExceptionValueErrorExit: A special exception intentionally designed to exit the active code block immediately.
InvalidSessionObjectAlias: An alias violates the namespace grammar.InvalidThreadEnvelope/InvalidGraphEnvelope: The target object is not a thread / graph, or, for a graph or when a thread’s items are listed or fetched, is missing. A post to a missing thread creates it, andthread_messageson one reads an empty history.ThreadItemConflict: A post’s id already names an item of another session, revision or thread (alias).GraphMutationConflict: Anif_revoptimistic-lock check failed — the element changed since it was read.GraphTraversalLimitExceeded: Aquery_session_graphtraversal exceeded a hard bound.InvalidGraphQuery: A malformed traversal query.LimitExceeded: A write would create a new session object past the execution’sworkflow.session_objects_per_session. It carries thelimitobject. See Limits.
Input & Output
Reading Inputs
You can access data arriving at the component’s input ports. Inputs are received as explicitly typed Value Objects.data_inputs: A list of all received input port data.get_data_input(route): A helper function to grab the Value Object of a specific input port by its exact route name.
Writing Outputs
You can emit data out of the component by pushing Value Objects to output routes.set_data_output(route, value, persist=False): Assigns a value to a targeted output port.route: Output port name (e.g., “result”).value: The Value Object payload.persist: IfTrue, stores the output specifically to component data tracking logic for external visibility.
Flow Control
You determine which logic route the workflow should navigate following code execution.set_result(route, terminal=False): Declares the destination route.route: Connection edge to traverse ("success","failure", etc).terminal: Set toTrueif this intentionally ends the entire workflow execution.
exit(): Aborts the execution of the remainder of the active code script.
Helper Functions
Data Helpers
create_message(role, text=None, attribute_id=None): Generates a standardized “message” Value Object dynamically.create_value(data_type, data): Quickly wrap arbitrary matching data into a recognized Value structure.
Session Management
Every function below is bound to the execution’s own session — none of them takes asession_id, so your code
can only ever reach its own session’s objects. Names and behavior mirror the platform’s REST session commands
one-to-one, and the same validation applies here as on the REST API (alias grammar, thread/graph envelope checks,
size limits, graph mutation/traversal caps, and if_rev optimistic concurrency). Writes are attributed to the user
the execution runs as.
The request/response shapes for each function are documented in full on the linked operations reference pages
below — this section covers the signature, behavior, and return shape only.
Objects
A session object is a typed document addressed by analias — a path such as missions/a1/graph.
download_session_object(alias): Reads the value of a session object. Returns the typed payload, orNoneif it doesn’t exist. See Download Session Object.upload_session_object(alias, value, client=None): Writes/creates a session object, validating the alias. See Upload Session Object.delete_session_object(alias, client=None): Deletes a session object. If the object is athreadorgraphenvelope, this also cascades — deleting all of its child thread items / graph elements. See Session Objects for the envelope model (there’s no dedicated delete reference page).list_session_objects(prefix="", delimiter=None, cursor=None, limit=None): Lists session objects under an optional aliasprefix, with optionaldelimiter-based folder rollup and cursor pagination. Returns{"objects": [...], "cursor": ..., "common_prefixes": [...]}(the last key only whendelimiteris given). See List Session Objects.
Tools
Two pure helpers for a flow that runs a model’s tool calls. The loop and an example are on Tool Calling.tool_calls(message): Lists the calls in a message.messageis a value envelope ({"type": "message", "message": {...}}) or message data. Returns[{"id", "name", "arguments"}]in block order, and[]for a message with none.tool_result_message(results): Builds the reply.resultsis a list of{"id", "content", "is_error"?};contentis a string (one text block), a list of blocks (as given), or any other JSON (onejsonblock). Returns a message value: roleuser, onetool_resultblock per result, in order. A result without anidraisesValueError("tool result <n> has no id").
Threads
Athread object holds an append-only list of items. A post to an alias that holds nothing creates the thread, so
there is no envelope to create first; an alias that holds another kind of object is refused with
InvalidThreadEnvelope. Upload an envelope with upload_session_object(alias, {"type": "thread", ...}) only to give
the thread a name or a description of its own.
post_session_thread_item(alias, content, parent_id=None, metadata=None, client=None): Appends an item.contentis a list of typed parts (e.g.[{"type": "text", "text": "..."}]);metadatais a free-form tag dict. Returns{"item": <item>}. See Post Session Thread Item.thread_messages(alias, roles=None, skip_roles=None, anchor=None, from_=None, to=None, keep=None): Reads the thread as messages, selected as a history is. Returns amessagesvalue of the items this execution can see: those posted before it started, and its own.post_message(alias, message): Posts amessageor amessagesvalue, as adata.threaddoes: one item per message, a message over the item limit in parts, the item’ssourcestamped by the platform. Returns{"items": [...]}, the items posted. A program run again from the start by a retried run posts under the same ids, so it posts nothing twice: a message with a part still stored is not posted again, unless the retry splits it into fewer parts after the stored one lost its first two parts and every part those name (parts).list_session_thread_items(alias, ascending=False, created_since=None, created_before=None, cursor=None, limit=None): Reads items, newest-first by default;created_since/created_beforebound the range (usecreated_sinceas a delta cursor). Returns{"items": [...], "cursor": ...}. See List Session Thread Items.get_session_thread_item(alias, item_id): Fetches a single item. Returns{"item": <item>}. See Get Session Thread Item.
logic.code wired to a data.thread reads it on an input as
thread_messages(alias) would: the visible thread, notes left out. An output wired to a thread is posted when the
program ends. set_data_output(route, value, persist=True) on a thread output warns that persist does nothing; call
post_message to post at once.
set_result needs a connection for each route it can name, so a gate like this wires both
due and skip.
Graphs
Agraph object holds vertices and edges. Create the envelope first with
upload_session_object(alias, {"type": "graph", ...}) — vertices and edges are then changed only via mutations.
apply_session_graph_mutations(alias, operations, client=None): Applies a batch of mutations (add_vertex,add_edge,set_vertex_props,set_edge_props,remove_*_props,delete_vertex,delete_edge), each optionally carryingif_revfor optimistic concurrency. Returns{"elements": [...], "changes": [...]}. See Apply Session Graph Mutations.query_session_graph(alias, query): Runs a bounded traversal against a query AST. Returns{"result": ...}. See Query Session Graph.list_session_graph_elements(alias, type=None, ascending=False, updated_since=None, ids_only=False, cursor=None, limit=None): Pages elements, optionally filtered totype"vertex"/"edge". Returns{"elements": [...], "cursor": ...}, or{"element_ids": [...], "cursor": ...}whenids_only=True. See List Session Graph Elements.get_session_graph_element(alias, element_id): Fetches one element. Returns{"element": ...}. See Get Session Graph Element.get_session_graph_elements(alias, element_ids): Batch-fetches elements. Returns{"elements": [...]}. See Get Session Graph Elements.list_session_graph_neighbors(alias, from_ids, direction, label=None, neighbor_label=None, cursor=None, limit=None): Expands adjacency fromfrom_ids(directionis"out"/"in"/"both", optionally filtered by edgelabel/neighbor_label). Returns{"edges": [...], "vertices": [...], "cursor": ...}. See List Session Graph Neighbors.
Events and listeners
list_session_events(filter=None, after=None, before=None, ascending=False, limit=None, cursor=None): Reads the session’s event stream. The arguments are the REST command’s, withoutsessionandinclude_session. Returns{"events": [...], "cursor": ...}. See List Session Events.list_session_listeners(): Lists the session’s declared and connection listeners. Returns{"listeners": [...]}. See List Session Listeners.set_session_listener(listener, enabled): Switches a declared listener, by alias or id, on or off in the session. Returns{"listener": {...}}. It takes noclient, and aclientargument is refused. See Set Session Listener.
upload_session_object, delete_session_object, post_session_thread_item and
apply_session_graph_mutations, take an optional client: a string of 1-64 characters, echoed as source.client of
the event the write raises. A write by an execution carries source.kind workflow with the execution’s id. See
Source.
Advanced: optimistic concurrency
Mutations can carryif_rev to guard against a concurrent write. If another writer already advanced the element
since it was read, the call raises GraphMutationConflict instead of silently overwriting it — catch the
exception and reconcile on a later run:
Logging & Events
Produce informational, warning, or failure events logged to the execution stream:post_output_event(message)post_warning_event(message)post_error_event(message)
System Metadata
current_time_utc_iso(): Gets UTC time dynamically.result: The immediate runtime representation of the result dictionary.
Limits
Four limits shape alogic.code run. All four come from the session’s blob, and each is fixed
when the execution is created.
workflow.code_run_seconds— 870 seconds by default, and at most. A run still going at that point is stopped; the node takes itsfailureroute, and the error message names the limit.workflow.code_imports— the third-party modules the code may import beyond the standard libraries above, empty by default. A module on the list is imported when the program names it, and is bound under its own name. The entry"*"makes every listed module import before the code runs, whether the program names it or not; it adds no module the list does not name.workflow.component_runs_per_execution— eachlogic.coderun is one node run, so a loop through a code node counts every pass.workflow.session_objects_per_session— a write that would create a new session object past it raisesLimitExceeded, carrying thelimitobject. The check uses the value the execution started with, where a REST write uses the value in force when it arrives.

