agentml

package module
v0.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 17, 2025 License: MIT Imports: 5 Imported by: 5

README ยถ

AgentML

๐Ÿšง Early Alpha - Building in Public

AgentML is in early alpha and being built openly with the community. The vision is ambitious, the foundation is solid, but many features are still in development. Join us in shaping the future of agent standards.

โš ๏ธ Repository Status: Many packages in this repository are proof-of-concept (POC) or work-in-progress (WIP). Code quality, APIs, and implementation approaches are evolving rapidly. Use with caution in production environments.


The Vision: A Universal Language for AI Agents

The AI agent landscape is fragmented and accelerating, with new frameworks appearing weekly. This creates vendor lock-in and forces costly rewrites when a chosen framework becomes limiting or unmaintained.

AgentML is the universal language for agents, inspired by the success of HTML for the web.

AgentML : Agent Frameworks  =  HTML : Web Browsers

Just as HTML lets you write content once and have it render in any browser, AgentML lets you define your agent's behavior once and run it anywhere. This is achieved by building on the battle-tested W3C SCXML standard, a formal model for state machines that has been proven for over 20 years in complex industrial systems.

This provides two primary paths for execution:

  1. Native Execution (Recommended): Run agents with agentmlx, the reference runtime built in Go/WASM. It's designed for high performance and portability.
  2. Transformation (Planned): To integrate with existing ecosystems, we are planning transformers to convert AgentML into other popular frameworks like LangGraph, CrewAI, n8n, and more. This feature is not yet implemented but is a key part of our roadmap.

By separating behavior from runtime, your agents outlive framework trends.


Table of Contents


Installation

Installing agentmlx Runtime

To run AgentML files (.aml), you need the agentmlx runtime. Install it with a single command:

curl -fsSL sh.agentml.dev | sh

This will:

  • Automatically detect your platform (Linux/macOS, amd64/arm64)
  • Download the latest release
  • Verify checksums for security
  • Install to ~/.agentmlx/bin
  • Add to your PATH

Install from different channels:

# Latest stable release
curl -fsSL sh.agentml.dev | sh

# Next (release candidate)
curl -fsSL sh.agentml.dev | sh -s -- --channel next

# Beta releases
curl -fsSL sh.agentml.dev | sh -s -- --channel beta

Install specific version:

curl -fsSL sh.agentml.dev | sh -s -- --version 1.0.0-rc.1

Install to custom directory:

export AGENTMLX_INSTALL_DIR=/usr/local
curl -fsSL sh.agentml.dev | sh

Release Channels:

  • latest - Stable releases (v1.0.0) - Default
  • next - Release candidates (v1.0.0-rc.1)
  • beta - Beta releases (v1.0.0-beta.1)

The installer automatically falls back if a channel is empty: latest โ†’ next โ†’ beta

Verify installation:

agentmlx --version
# or use the shorter alias
amlx --version

Both agentmlx and amlx commands are available after installation.

For more installation options and manual downloads, see the agentmlx documentation.


Core Concepts

AgentML uses SCXML state machines to define deterministic behavior, moving beyond prompt-only approaches where behavior is emergent and unpredictable.

  1. State Machines: Explicitly define valid states, transitions, and the agent's lifecycle. This enables formal verification and testing.

  2. Schema-Guided Events: LLM outputs are constrained to structured JSON events validated against schemas using the event:schema attribute. This ensures reliability and type safety.

    โš ๏ธ Work in Progress: Event schema validation and external schema loading (import directive) are in active development. APIs and features may change as we refine the implementation based on community feedback.

    The event:schema attribute on a transition provides JSON schema validation for an event. It is critical to include description fields at both the schema and property level, as these descriptions are the primary way to guide LLMs in generating correct event data.

    With Descriptions (Good):

{
        "type": "object",
      "description": "User intent to perform a flight-related action (search, book, update, cancel)",
        "properties": {
          "action": {
          "type": "string",
            "enum": ["search", "book", "update", "cancel"],
          "description": "The specific action: search for flights, book a new flight, etc."
          },
          "details": {
            "type": "object",
          "description": "Flight-specific information extracted from user message",
            "properties": {
              "from": {
                "type": "string",
              "description": "Departure location: city name or airport code (e.g., 'New York' or 'JFK')"
            }
          }
        }
  }
}
  1. Efficient Token Usage: The runtime provides the LLM with a "snapshot" of the current state, datamodel, and available events. This context allows prompts to be minimal, and the static parts (the agent's SCXML definition) can be cached by the LLM provider, reducing token consumption.

  2. Decomposition: Complex agents can be broken down into smaller, reusable state machines using the <invoke> tag. This is ideal for managing complexity and sharing components like authentication or payment processing.

  3. Compiler-Inspired Validation: To ensure reliability, especially when agents are building other agents, AgentML includes a powerful validation system. Inspired by the Rust compiler (rustc), it provides detailed, actionable error messages that help developers (and other agents) pinpoint issues quickly and achieve a high success rate when generating AgentML documents.

    Here is an example of the validator's output:

    ./agentml/examples/customer_support/customer_support.aml:89:5: WARNING[W340] State 'await_user_input' has only conditional transitions and may deadlock if no events match
          88 |     <!-- Await User Input and Classify Intent (Combined State) -->
          89 |     <state id="await_user_input">
                   ^
          90 |       <onentry>
      hint: Add an unconditional fallback transition (without 'event' or 'cond' attributes)
      hint: Or ensure all possible events are handled
      hint: Example: <transition target="fallback_state" />
    
    summary: 0 error(s), 1 warning(s), 1 total
    
Schema References with import

To keep agent files clean and promote reuse, schemas can be defined in external JSON or YAML files (including OpenAPI specs) and loaded with an import directive. The runtime intelligently detects the file type.

This enables schema reuse via JSON Pointer (RFC 6901) references with namespace prefixes.

schemas/events.json:

{
  "components": {
    "schemas": {
      "FlightRequest": {
  "type": "object",
        "description": "Schema for a flight-related request.",
  "properties": {
            "action": { "$ref": "#/components/schemas/FlightAction" }
        }
      },
      "FlightAction": {
      "type": "string",
          "enum": ["search", "book", "cancel"]
      }
    }
  }
}

agent.aml:

<agent xmlns="github.com/agentflare-ai/agentml/agent"
       import:events="./schemas/events.json">

  <!-- Reference schemas using a namespace and JSON Pointer -->
  <transition event="intent.flight"
              event:schema="events:#/components/schemas/FlightRequest"
              target="handle_flight" />
</agent>

This unified import directive is designed to work for schemas, namespace implementations, and future WASM components.


Key Features

  • ๐ŸŽฏ Deterministic Behavior: Predictable, auditable agent behavior via state machines.
  • ๐Ÿ“ Schema-Guided Events: event:schema attributes validate LLM-generated events. ๐Ÿšง
  • ๐Ÿ”„ Runtime Snapshots: Efficiently provide LLM context, minimizing token usage. โœ…
  • ๐Ÿ“ฆ Modular Design: Decompose complex agents into reusable components with <invoke>. โœ…
  • ๐Ÿ”Œ Extensible Namespaces: Plug in custom functionality (LLMs, memory, I/O). โœ…
  • ๐Ÿ“Š Observable: Foundation for OpenTelemetry tracing and logging. โœ…
  • ๐ŸŒ Universal Standard: Write once, deploy anywhere via native runtime or transformation. ๐Ÿ”ฎ
  • ๐Ÿ”— Remote Communication: Built-in distributed agent communication via IOProcessors. โœ…

Legend: โœ… Working | ๐Ÿšง In Development | ๐Ÿ”ฎ Planned


Architecture

  • Document Structure: AgentML files use an <agent> root element, which is a compatible extension of SCXML's <scxml> element. The datamodel attribute specifies the scripting language used for data manipulation and expressions.
  • Supported Datamodels: AgentML supports ecmascript, starlark, and xpath. Support for using wasm components as a datamodel is planned for the future.
  • Namespace System: Functionality is extended through namespaces (e.g., for Gemini, Ollama, Memory) declared with the import:prefix="uri" directive.
  • Runtime Snapshot: At each step, the runtime creates an XML snapshot containing the active states, datamodel, and available events. This, combined with the SCXML document, gives the LLM complete and current context.

Write Once, Deploy Anywhere ๐Ÿ”ฎ

๐Ÿšง Vision Statement: This section describes our goal for AgentML. Framework transformers are planned and not yet available.

The core promise of AgentML is to end the cycle of constant rewrites caused by framework fragmentation.

        AgentML (.aml)
               |
       โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
       โ–ผ                          โ–ผ
   agentmlx                   Transform to: (Planned)
  (Primary                    - LangGraph
   Runtime)                   - CrewAI
       |                      - n8n
       โ–ผ                      - ...and more
   Go/WASM
   Anywhere
Native Runtime: agentmlx

The agentmlx runtime is the recommended way to execute AgentML files. It is a high-performance, portable Go/WASM binary that is fully compliant with the W3C SCXML specification, passing all 193 official conformance tests. agentmlx will be open-sourced soon.

# Future: Run directly with agentmlx (or amlx)
agentmlx run customer-support.aml
# or shorter
amlx run customer-support.aml
Framework Transformers (Planned)

When you need to integrate with an existing ecosystem, transformers will convert AgentML into framework-specific code.

# PLANNED: Transform AgentML to LangGraph
agentmlx transform customer-support.aml --target langgraph --output customer-support.py

This provides framework insurance, eliminating vendor lock-in and allowing you to choose a runtime based on deployment needs, not sunk costs.


Extensibility with WebAssembly (Planned) ๐Ÿ”ฎ

๐Ÿšง Vision Statement: WASM-based namespaces are a forward-looking goal.

Our vision for true interoperability and extensibility is to load namespaces as WebAssembly (WASM) components that adhere to the agentml.wit interface.

<!-- Future: Load namespace from a WASM module -->
<agent import:gemini="https://cdn.example.com/gemini-namespace.wasm"
       import:custom="./my-namespace.wasm">
  
  <gemini:generate ... />
  <custom:process ... />
</agent>

This means you can:

  • Write extensions in any language (Rust, Go, Python, C++) that compiles to WASM.
  • Run on any runtime that supports the WASM component model.
  • Securely sandbox custom code.

This is the "JavaScript for agents," enabling a dynamic and polyglot ecosystem on top of AgentML's "HTML for agents" structure.


Remote Agent Communication

AgentML supports distributed agent communication using the W3C SCXML IOProcessor interface. Agents can communicate across processes and networks using standard protocols like HTTP and WebSockets.

<state id="notify_remote_agent">
  <onentry>
    <!-- Send an event to a remote agent via HTTP -->
    <send event="task.assigned"
          target="https://agent.example.com/events"
          type="github.com/agentflare-ai/agentml/ioprocessor/http">
      <param name="task_id" expr="task.id" />
    </send>
  </onentry>
  
  <!-- Wait for a response -->
  <transition event="task.acknowledged" target="confirmed" />
</state>

This architecture supports patterns like agent swarms, supervisor-worker delegation, and pub/sub, with built-in support for security, observability, and automatic trace propagation.


Current Status & Roadmap

We are building AgentML in the open. Your feedback is critical.

What's working now:

  • โœ… Core SCXML interpreter (Go implementation)
  • โœ… Gemini & Ollama LLM integration namespaces
  • โœ… Basic event-driven agent workflows
  • โœ… Datamodel and state machine semantics
  • โœ… OpenTelemetry tracing foundation
  • โœ… IOProcessor implementations (HTTP, WebSocket)

What's in active development:

  • ๐Ÿšง agentmlx runtime - Native Go/WASM execution (primary focus)
  • ๐Ÿšง Memory namespace (vector search, graph database)
  • ๐Ÿšง Event schema validation (event:schema) and external schema loading (import)

What's planned:

  • ๐Ÿ”ฎ Framework transformers (LangGraph, CrewAI, n8n, OpenAI, Autogen)
  • ๐Ÿ”ฎ WASM namespace loading via agentml.wit
  • ๐Ÿ”ฎ Visual editor and debugger
  • ๐Ÿ”ฎ Agent marketplace

How to participate:

  • ๐Ÿ—ฃ๏ธ Share your use cases in GitHub Discussions.
  • ๐Ÿ’ก Propose features via GitHub Issues.
  • ๐Ÿ”ง Contribute code through pull requests.

Getting Started

โš ๏ธ Alpha Software: APIs may change, features may be incomplete, and you may encounter bugs.

What You Need

AgentML is a language specification - you write .aml files that define your agent's behavior. The agentmlx runtime (coming soon) executes these files. No installation of AgentML itself is needed.

To use AgentML:

  1. Write your agent in .aml files (see example below)
  2. Run with agentmlx run your-agent.aml or amlx run your-agent.aml (runtime in development)
  3. The runtime handles all namespaces, extensions, and execution
Basic Agent Example
<agent xmlns="github.com/agentflare-ai/agentml/agent"
       datamodel="ecmascript"
       import:gemini="github.com/agentflare-ai/agentml/gemini">

  <datamodel>
    <data id="user_input" expr="''" />
    <data id="response" expr="''" />
  </datamodel>

  <state id="main">
    <state id="awaiting_input">
      <onentry>
        <!-- In a real agent, input comes from an IOProcessor -->
        <assign location="user_input" expr="getUserInput()" />
      </onentry>
      <transition target="processing" />
    </state>

    <state id="processing">
      <onentry>
        <!-- LLM generates a structured event based on the input -->
        <gemini:generate
          model="gemini-2.0-flash-exp"
          location="_event"
          promptexpr="'Process this input: ' + user_input" />
      </onentry>
      
      <!-- Transition only if the LLM output matches the event schema -->
      <transition event="action.response"
                  event:schema='{"type": "object", "properties": {"message": {"type": "string"}}, "required": ["message"]}'
                  target="responding" />
    </state>

    <state id="responding">
      <onentry>
        <assign location="response" expr="_event.data.message" />
        <log expr="'Response: ' + response" />
      </onentry>
      <transition target="awaiting_input" />
    </state>
  </state>
</agent>

For most users: Just write .aml files and run them with agentmlx (or amlx) - no Go code needed!


Namespaces

AgentML's functionality is extended through namespaces. Here are the currently available or planned ones:

  • Agent (.../agentml/agent): Core namespace for <agent> root element and event:schema validation.
  • Gemini (.../agentml/gemini): Google Gemini LLM integration.
  • Ollama (.../agentml/ollama): Local LLM integration via Ollama.
  • Memory (github.com/agentflare-ai/agentml/memory): High-performance memory with vector search and graph database capabilities. This is powered by sqlite-graph, our custom extension that provides a complete, local, filesystem-based memory framework within a single SQLite file.
<agent import:memory="github.com/agentflare-ai/agentml/memory">
  <!-- Vector operations -->
  <memory:embed location="embedding" expr="text_content" />
  <memory:search location="results" expr="query_embedding" limit="10" />
  
  <!-- Graph operations -->
  <memory:graph-query location="results">
    <query>
      MATCH (p:Person)-[:KNOWS]->(friend)
      WHERE p.age > 25
      RETURN p.name, friend.name
    </query>
  </memory:graph-query>
  
  <!-- Key-value storage -->
  <memory:put key="user_preference" expr="preference_value" />
  <memory:get key="user_preference" location="preference" />
</agent>

Features:

  • Vector similarity search
  • Graph database with Cypher queries
  • Embedding generation
  • Persistent key-value storage

See memory/README.md for details.

  • Stdin (.../agentml/stdin): Simple stdin/stdout I/O for console agents.
Creating Custom Namespaces

Custom namespaces can be implemented in Go (currently), or any language that compiles to WASM (future).

Current: Go implementations define types and interfaces in code.

Future: WebAssembly Component Model via agentml.wit ๐Ÿ”ฎ

The agentml.wit file defines standard interfaces for namespaces using WebAssembly Interface Types (WIT). This enables:

  • Language freedom: Implement namespaces in Rust, Go, Python, C++, or any WASM-capable language
  • Portable: Same .wasm module works across all runtimes
  • Standard contract: Defined interfaces ensure interoperability
  • Secure: WASM sandboxing isolates namespace code

๐Ÿšง Migration Note: Current Go-based type definitions (e.g., types.go) will be deprecated in favor of agentml.wit as the canonical type specification. This transition enables true polyglot namespace development.


Best Practices

  • Keep .aml files focused: Decompose large agents into smaller, invoked services.
  • Use meaningful state IDs: handle_flight_request is better than state_5.
  • Validate with schemas: Always use event:schema and provide detailed description fields to guide the LLM.
  • Use external schemas: Define schemas in .json/.yaml files and load them with import: for reuse and maintainability.
  • Prefer external scripts: Use <script src="./utils.js" /> for better linting, IDE support, and maintainability. Only use inline scripts for simple expressions. When you must write inline scripts with comparison operators (<, >) or other special XML characters, wrap your code in <![CDATA[...]]>:
  <!-- Best: External script with full linting support -->
  <script src="./validation.js" />
  
  <!-- Inline without CDATA: XML parser errors -->
    <script>
    if (count < 10 && value > 5) {  <!-- This will break! -->
      return true;
    }
    </script>
  
  <!-- Inline with CDATA: Works but no linting -->
    <script>
      <![CDATA[
    if (count < 10 && value > 5) {
      return true;
    }
      ]]>
    </script>

Documentation ยถ

Index ยถ

Constants ยถ

View Source
const (
	EventSystemVariable        = "_event"
	SessionIDSystemVariable    = "_sessionid"
	NameSystemVariable         = "_name"
	IOProcessorsSystemVariable = "_ioprocessors"
	XSystemVariable            = "_x"
)
View Source
const NamespaceURI = "xsd.agentml.dev/agentml"

Variables ยถ

This section is empty.

Functions ยถ

This section is empty.

Types ยถ

type Assign ยถ

type Assign struct {
	xmldom.Element
	Location    string        // Location expression specifying where to assign the value
	Expr        string        // Optional value expression to evaluate and assign
	AssignType  string        // Optional type attribute for XML handling modes
	InlineNodes []xmldom.Node // Inline XML/text content if no expr
	Content     string        // Text content fallback
}

Assign changes the value of a location in the data model (SCXML 5.4)

type Cancel ยถ

type Cancel struct {
	xmldom.Element
	SendID     string // The ID of the send element to cancel
	SendIDExpr string // Optional expression to compute the send ID
}

Cancel cancels a previously sent event (SCXML 6.3)

type Clock ยถ

type Clock interface {
	// Now returns the current time
	Now() time.Time

	// Since returns the duration since the given time
	Since(t time.Time) time.Duration

	// Sleep pauses the current goroutine for at least the given duration
	Sleep(ctx context.Context, d time.Duration) error

	// After returns a channel that receives the current time after the given duration
	After(d time.Duration) <-chan time.Time

	// NewTimer creates a new timer that will send the current time after the given duration
	NewTimer(d time.Duration) Timer

	// NewTicker creates a new ticker that will send the current time every given duration
	NewTicker(d time.Duration) Ticker

	// TimeScale returns the current time scale (1.0 = real-time, 2.0 = 2x speed, etc.)
	TimeScale() float64

	// SetTimeScale sets the time scale for simulation (only applies to simulation clocks)
	SetTimeScale(scale float64)

	// Advance manually advances time by the given duration (only applies to mock clocks)
	Advance(d time.Duration)

	// Pause pauses time advancement (only applies to mock clocks)
	Pause()

	// Resume resumes time advancement (only applies to mock clocks)
	Resume()

	// IsPaused returns true if the clock is paused
	IsPaused() bool
}

Clock provides an abstraction over time for testing and simulation

type Content ยถ

type Content struct {
	xmldom.Element
	Expr string // Optional value expression to evaluate
	Body any    // Optional inline content body (XML, text, etc.)
}

Content represents content for data operations (SCXML 5.6)

type Data ยถ

type Data struct {
	xmldom.Element
	ID      string // The data element identifier
	Expr    string // Optional initial value expression
	Src     string // Optional external source URI
	Content any    // Optional XML content (for XPath data model)
}

Data represents a data element defined in the SCXML document.

type DataModel ยถ

type DataModel interface {
	// Initialize sets up the data model with initial data elements.
	// This is called when the SCXML document is loaded and should create
	// all data elements defined in <data> elements.
	Initialize(ctx context.Context, dataElements []Data) error

	// EvaluateValue evaluates a value expression and returns the result.
	// Used for <data expr="...">, <assign expr="...">, etc.
	// Returns an error if the expression cannot be evaluated.
	EvaluateValue(ctx context.Context, expression string) (any, error)

	// EvaluateCondition evaluates a conditional expression and returns a boolean.
	// Used for <transition cond="..."> and other conditional logic.
	// Returns an error if the expression cannot be evaluated as a boolean.
	EvaluateCondition(ctx context.Context, expression string) (bool, error)

	// EvaluateLocation evaluates a location expression and returns the value at that location.
	// Used for <param location="..."> and other location-based access.
	// Returns an error if the location is invalid or cannot be accessed.
	EvaluateLocation(ctx context.Context, location string) (any, error)

	// Assign assigns a value to a location in the data model.
	// Used for <assign location="..." expr="..."> operations.
	// Returns an error if the location is invalid or the assignment fails.
	Assign(ctx context.Context, location string, value any) error

	// GetVariable retrieves the value of a data element by ID.
	// Returns an error if the data element doesn't exist.
	GetVariable(ctx context.Context, id string) (any, error)

	// SetVariable sets the value of a data element by ID.
	// Returns an error if the data element doesn't exist or the value is invalid.
	SetVariable(ctx context.Context, id string, value any) error

	// GetSystemVariable retrieves a system variable value.
	// System variables include: _event, _sessionid, _name, _ioprocessors, _x
	// Returns an error if the system variable doesn't exist.
	GetSystemVariable(ctx context.Context, name string) (any, error)

	// SetSystemVariable sets a system variable value.
	// Most system variables are read-only and will return an error if modified.
	// Returns an error if the variable doesn't exist or cannot be modified.
	SetSystemVariable(ctx context.Context, name string, value any) error

	// SetCurrentEvent sets the _event system variable to the current event.
	// This is called by the interpreter when processing events.
	SetCurrentEvent(ctx context.Context, event any) error

	// ExecuteScript executes a script in the data model's context.
	// For ECMAScript data models, this executes JavaScript code with access to all variables.
	// For other data models, this may evaluate the script as an expression.
	// Returns an error if the script cannot be executed.
	ExecuteScript(ctx context.Context, script string) error

	// Clone creates a copy of the data model for use in parallel states.
	// The clone should share system variables but have independent data elements.
	Clone(ctx context.Context) (DataModel, error)

	// ValidateExpression validates that an expression is syntactically correct
	// for this data model. Returns nil if valid, error if invalid.
	ValidateExpression(ctx context.Context, expression string, exprType ExpressionType) error
}

type DataModelLoader ยถ

type DataModelLoader func(ctx context.Context, interpreter Interpreter) (DataModel, error)

type Event ยถ

type Event struct {
	ID         string    `json:"id"`                   // Unique event ID using MUID
	Name       string    `json:"name"`                 // Event name for matching
	Type       EventType `json:"type"`                 // Internal, external, or platform
	Delay      string    `json:"delay,omitempty"`      // Delay for delayed events
	Data       any       `json:"data"`                 // Event data payload
	Metadata   any       `json:"metadata,omitempty"`   // Metadata for the event
	InvokeID   string    `json:"invokeid,omitempty"`   // For invoked sessions
	Timestamp  time.Time `json:"timestamp"`            // When event was created
	Origin     string    `json:"origin,omitempty"`     // Origin of external events
	OriginType string    `json:"origintype,omitempty"` // Type of origin
	SendID     string    `json:"sendid,omitempty"`     // ID from send element
	Raw        string    `json:"raw,omitempty"`        // Raw data for HTTP events
	Target     string    `json:"target,omitempty"`     // Target URI from original send
	TargetType string    `json:"targettype,omitempty"` // I/O processor type URI from send
}

Event represents an SCXML event as defined in the W3C specification

type EventType ยถ

type EventType string

EventType represents the type of SCXML event

const (
	EventTypeInternal EventType = "internal"
	EventTypeExternal EventType = "external"
	EventTypePlatform EventType = "platform"
)

type ExecutionError ยถ

type ExecutionError struct {
	Message string
	Element xmldom.Element
}

ExecutionError represents an error that occurred during agentml execution

func (*ExecutionError) Error ยถ

func (e *ExecutionError) Error() string

type Executor ยถ

type Executor interface {
	xmldom.Element
	// Execute runs the executable content
	Execute(ctx context.Context, interpreter Interpreter) error
}

Executor represents any executable content that can be executed

type ExpressionType ยถ

type ExpressionType string

ExpressionType defines the type of expression being evaluated.

const (
	ValueExpression     ExpressionType = "value"
	ConditionExpression ExpressionType = "condition"
	LocationExpression  ExpressionType = "location"
)

type Finalize ยถ

type Finalize struct {
	xmldom.Element
}

Finalize finalizes the session (SCXML 6.5)

type Foreach ยถ

type Foreach struct {
	xmldom.Element
	Array string // Value expression that evaluates to an iterable collection
	Item  string // Variable name to store each item during iteration
	Index string // Optional variable name to store iteration index
}

Foreach iterates over a collection in the data model (SCXML 4.6)

type IOProcessor ยถ

type IOProcessor interface {
	// Handle processes a fully-formed event using this I/O processor
	// This is the preferred method for I/O processor implementations.
	// The event contains all pre-evaluated data from the interpreter's data model.
	// IOProcessors should focus only on transport/communication logic.
	// ctx: context for tracing and cancellation
	// event: the event to handle (all data model evaluation already completed)
	// Returns error if transport/communication fails (e.g., error.communication)
	Handle(ctx context.Context, event *Event) error

	// Location returns the location/URI that external entities can use
	// to communicate with this SCXML session via this I/O processor
	// This is used to populate the _ioprocessors system variable
	Location(ctx context.Context) (string, error)

	// Type returns the I/O processor type URI (e.g., "github.com/agentflare-ai/agentml/ioprocessor/scxml")
	Type() string

	// Shutdown cleans up resources used by this I/O processor
	Shutdown(ctx context.Context) error
}

IOProcessor defines the interface that all I/O processors must implement according to W3C SCXML specification sections C.1 and C.2

type IOProcessorLoader ยถ

type IOProcessorLoader func(ctx context.Context, interpreter Interpreter) (IOProcessor, error)

type If ยถ

type If struct {
	xmldom.Element
	Cond        string      // Boolean condition expression
	Interpreter Interpreter // Reference to interpreter for recursive execution
}

If provides conditional execution with elseif and else branches (SCXML 4.3)

type Interpreter ยถ

type Interpreter interface {
	IOProcessor
	SessionID() string
	Configuration() []string
	In(ctx context.Context, stateId string) bool
	Raise(ctx context.Context, event *Event)
	Send(ctx context.Context, event *Event) error
	Cancel(ctx context.Context, sendId string) error
	Log(ctx context.Context, label, message string)
	Context() context.Context
	Clock() Clock
	DataModel() DataModel
	ExecuteElement(ctx context.Context, element xmldom.Element) error
	SendMessage(ctx context.Context, data SendData) error
	ScheduleMessage(ctx context.Context, data SendData) (string, error)
	InvokedSessions() map[string]Interpreter
	Tracer() Tracer
	Snapshot(ctx context.Context, maybeConfig ...SnapshotConfig) (xmldom.Document, error)
}

Interpreter interface for SCXML interpretation

type Log ยถ

type Log struct {
	xmldom.Element
	Label string // Optional label for the log message
	Expr  string // Expression to evaluate and log
}

Log generates a logging or debug message (SCXML 5.11)

type Namespace ยถ

type Namespace interface {
	URI() string
	Handle(ctx context.Context, element xmldom.Element) (bool, error)
	Unload(ctx context.Context) error
}

type NamespaceLoader ยถ

type NamespaceLoader func(ctx context.Context, interpreter Interpreter, doc xmldom.Document) (Namespace, error)

type Option ยถ

type Option func(*Trace)

type Param ยถ

type Param struct {
	xmldom.Element
	Name     string // The name of the parameter key
	Expr     string // Optional value expression to evaluate
	Location string // Optional location expression to retrieve value from
}

Param represents a parameter for data operations (SCXML 5.7)

type PlatformError ยถ

type PlatformError struct {
	EventName string         // The error event name (e.g., "error.execution")
	Message   string         // Error message
	Data      map[string]any // Additional error data (element, line, etc.)
	Cause     error          // Wrapped underlying error
}

PlatformError represents an error that should generate a platform error event

func (*PlatformError) Error ยถ

func (e *PlatformError) Error() string

func (*PlatformError) Unwrap ยถ

func (e *PlatformError) Unwrap() error

type Position ยถ

type Position struct {
	File   string `json:"file"`
	Line   int    `json:"line"`
	Column int    `json:"column"`
	Offset int64  `json:"offset"`
}

Position contains source position information for a diagnostic

type Raise ยถ

type Raise struct {
	xmldom.Element
	Event     string // Event name to raise
	EventExpr string // Optional dynamic event name expression
}

Raise raises an internal event (SCXML 6.4)

type Script ยถ

type Script struct {
	xmldom.Element
	Src     string // Optional URI of external script to load
	Content string // Inline script content
}

Script provides scripting capabilities (SCXML 5.8)

type Send ยถ

type Send struct {
	xmldom.Element
	Event      string   // Optional event name to send
	EventExpr  string   // Optional dynamic event name expression
	Target     string   // Optional target URI
	TargetExpr string   // Optional dynamic target expression
	TypeURI    string   // Optional I/O processor type URI
	TypeExpr   string   // Optional dynamic type expression
	SendID     string   // Optional send identifier
	IdLocation string   // Optional location to store generated ID
	Delay      string   // Optional delay duration (CSS2 format)
	DelayExpr  string   // Optional dynamic delay expression
	NameList   []string // Optional list of data model locations to include
	Params     []Param  // Optional parameter key-value pairs
	Content    *Content // Optional content payload
}

Send sends an event to a specified destination (SCXML 6.2)

type SendData ยถ

type SendData struct {
	Event    string   // Event name to send
	Target   string   // Target URI for the message
	Type     string   // I/O processor type URI
	ID       string   // Send identifier
	Delay    string   // Delay duration (CSS2 format)
	NameList []string // List of data model locations to include
	Params   []Param  // Parameter key-value pairs
	Content  *Content // Content payload (nil if not present)
}

SendData encapsulates all data needed for a send operation

type SnapshotConfig ยถ

type SnapshotConfig struct {
	// ExcludeAll acts as a master switch: when true, disables all sections
	ExcludeAll bool
	// Specific sections to exclude (opt-out pattern)
	ExcludeConfiguration bool // exclude state configuration
	ExcludeData          bool // exclude datamodel values
	ExcludeQueue         bool // exclude internal/external queues
	ExcludeServices      bool // exclude invoked child services recursively
	ExcludeRaise         bool // exclude available raise (internal) transitions
	ExcludeSend          bool // exclude available send (external) transitions
	ExcludeCancel        bool // exclude cancelable delayed events
}

SnapshotConfig controls what the snapshot excludes when embedding into the document. By default, all sections are included. Use Exclude fields to opt-out of specific sections.

type Ticker ยถ

type Ticker interface {
	C() <-chan time.Time
	Stop()
	Reset(d time.Duration)
}

Ticker interface abstracts time.Ticker

type Timer ยถ

type Timer interface {
	C() <-chan time.Time
	Stop() bool
	Reset(d time.Duration) bool
}

Timer interface abstracts time.Timer

type Trace ยถ

type Trace struct {
	Level     slog.Level `json:"level"`
	Code      string     `json:"code"`
	Message   string     `json:"message"`
	Position  Position   `json:"position"`
	Tag       string     `json:"tag,omitempty"`
	Attribute string     `json:"attribute,omitempty"`
	Hints     []string   `json:"hints,omitempty"`
}

Trace describes an issue found during validation or runtime execution

type Tracer ยถ

type Tracer interface {
	Error(code, message string, element xmldom.Element, opts ...Option)
	Warn(code, message string, element xmldom.Element, opts ...Option)
	Info(code, message string, element xmldom.Element, opts ...Option)

	Diagnostics() []Trace
	HasErrors() bool
	Clear()
}

Tracer interface for collecting diagnostics

type Variable ยถ

type Variable struct {
	Name string
}

Directories ยถ

Path Synopsis
env module
gemini module
memory module
ollama module
prompt module
stdin module

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL