Golem agent reflection moonbit

From golemcloud/golem · View interactive version

Golem agent reflection moonbit is an AI agent skill from the GitHub repository golemcloud/golem. Discovering and calling Golem agents through runtime reflection in MoonBit. Use when agent types or methods are selected dynamically, schemas must be inspected at runtime, caller-authored codecs are needed, or SchemaValue calls must avoid discovery.

How to use this skill

Skill file

Agent Reflection and Client Approaches (MoonBit)

Golem exposes four composable client approaches:

The last three are reflection approaches. They compose: discovery can select

schemas, canonical tool paths, and agent IDs for later fully dynamic

calls, while the @schema.AgentId of an existing durable agent can be rebound

through a method-only, discovered, or fully dynamic client.

Discover and inspect schemas

let available = @reflection.get_all_agent_types()
guard @reflection.get_agent_type("CounterAgent") is Some(counter_type) else {
  raise @reflection.ReflectError::Discovery("CounterAgent is unavailable")
}
guard counter_type.find_method("add") is Some(add) else {
  raise @reflection.ReflectError::Discovery("add is unavailable")
}

Agent type names and agent IDs are environment-scoped.

AgentType exposes its lifecycle mode, constructor SchemaRef, and method

schemas. get_agent_type_by_agent_id(agent_id) returns the deployed agent type

that the type tag of an agent ID names. SchemaRef::pack_json

converts canonical JSON into a schema-native value; unpack_json performs the

awaited conversion back. to_json_schema() projects the canonical JSON carrier

for introspection, including named definitions and representable restrictions;

capabilities, futures, and streams have no JSON value representation and project

to an unsatisfiable reflection JSON Schema. An omitted option record field and

an explicit null both decode as absent; re-encoding may emit null, and the

field is omitted from JSON Schema required. A tool command's input_schema()

also accepts JSON that omits a scalar option, positional with a declared

default, or flag: pack_json fills in the declared default, and

to_json_schema() does not require the argument. A JSON failure raises

ReflectError::Json(message, path~), where path locates the failing value. Canonical JSON encodes s64 and

u64 as decimal strings, duration as { "nanoseconds": "..." }, and quantity

mantissas as decimal strings. These strings reject +, leading zeroes, -0,

and overflow. Discovery returns

an immutable snapshot; explicitly

discover again when a newer deployment must be observed.

Use discovered clients

JSON convenience automatically packs and unpacks:

let counter = counter_type.upsert_json(Json::object({
  "name": Json::string("main"),
}))
let result = counter.invoke_json(
  "add",
  Json::object({ "by": Json::number(5.0) }),
)

For explicit reflected packing, call add.input().pack_json, invoke through

invoke_value, await the result, and call the output SchemaRef::unpack_json.

Reflected schema-native constructor and method inputs are checked locally

against the selected schema graph before opening RPC. Declared native outputs

are checked after invocation.

upsert_json and upsert_value connect to the keyed agent of the constructor

value, which the host creates when it is missing. get_by_id(agent_id) connects

to the existing agent of the type with the ID; an unknown ID, or the ID of an

agent of another type, raises Remote(NotFound(_)). For an ephemeral type, use

ephemeral_json or ephemeral_value: every invocation runs on a new one-shot

instance, whose agent ID the invocation metadata returns. Every client has the

async agent_id().

The async create_json(input, keyed?, config?, env?) and

create_value(input, keyed?, config?, env?) create a new durable agent. Without

keyed=true it has no key and a new agent ID; with it, it is the keyed agent,

and an existing one raises Remote(Conflict(_)). Their config entries are

ReflectedConfigJsonValue or ReflectedConfigValue creation-time overrides,

and env adds environment variables. The reflected type rejects unknown paths,

secret fields, and values that do not match their declarations before creating

transport. Component defaults may satisfy required declarations. The host

validates the effective config when it creates the agent and supplies secrets.

upsert takes no overrides.

For fully dynamic values, manually construct the positional record and use a dynamic

client:

let result = dynamic.invoke_value(
  "add",
  @model.SchemaValue::Record([@model.SchemaValue::U32(5U)]),
)

Fully dynamic clients never discover or validate schemas. Constructor and method

record fields must be packed in declaration order; the runtime authoritatively

accepts or rejects the attempt.

Discover a tool, then invoke it dynamically

This bridge packs and validates with a discovered snapshot, invokes through a

fully dynamic client, handles the raw tool result, and then explicitly validates

and decodes the output:

fn describe_dynamic_tool_error(
  error : @tool.ToolError[@reflection.ReflectedToolCustomError],
) -> String {
  match error {
    Rpc(error) => "rpc:\{Repr(error)}"
    RemoteTool(error) => "remote:\{Repr(error)}"
    Tool(custom) => {
      let message = "tool:\{Repr(custom)}"
      @model.drop_owned_capabilities(custom.payload.value)
      message
    }
    UnknownToolError(name, payload) => {
      @model.drop_owned_capabilities(payload.value)
      "unknown:\{name}"
    }
    InvalidInput(message) => "input:\{message}"
    MalformedRemoteOutput(message) => "output:\{message}"
  }
}

async fn invoke_discovered_tool_dynamically() -> String {
  let tool = @reflection.get_tool_type("moonbit-reflection-test")
  let command = tool.command(["echo"])
  let packed = match command.pack_json(
    Json::object({ "label": Json::string("moonbit") }),
  ) {
    Ok(value) => value
    Err(error) => return "input:\{describe_dynamic_tool_error(error)}"
  }
  let typed_input = command.input_schema().typed_value(packed) catch {
    error => return "input:\{Repr(error)}"
  }

  let dynamic = @reflection.DynamicToolClient::new(tool.lookup_name())
  let raw = match dynamic.invoke_value(
    command.path(),
    typed_input,
  ) {
    Ok(raw) => raw
    Err(error) => {
      return "invoke:\{describe_dynamic_tool_error(error)}"
    }
  }

  match (command.result(), raw.result) {
    (None, None) => "ok"
    (Some(schema), Some(output)) => {
      schema.validate_value(output.value) catch {
        error => {
          @model.drop_owned_capabilities(output.value)
          return "output:\{Repr(error)}"
        }
      }
      let json = schema.unpack_json(output.value) catch {
        error => {
          @model.drop_owned_capabilities(output.value)
          return "decode:\{Repr(error)}"
        }
      }
      @model.drop_owned_capabilities(output.value)
      json.stringify()
    }
    (_, Some(output)) => {
      @model.drop_owned_capabilities(output.value)
      "output:unexpected"
    }
    _ => "output:missing"
  }
}

Moving the discovered name, path, and graphs into DynamicToolClient does not

transfer automatic validation policy. The recipe explicitly releases custom

error payloads and returned values after decoding. For dynamic streaming calls,

drain or close transferred streams and cancel a started invocation when it is

abandoned.

Both reflected and direct clients support awaited, trigger, and scheduled

calls through invoke_value, trigger_value, and schedule_value. Awaited

calls use the asynchronous host invocation path and can carry live streams.

Reflected trigger and scheduled calls reject methods whose input or output

schema contains a stream.

Define caller-defined static clients

Method-only and full clients do not discover payload schemas. The caller's

IntoSchema and FromSchema implementations are the schema authority. They have

two forms.

For tools, wrap any caller-owned typed client factory in a named or reusable

definition. Binding is optimistic and performs no discovery or compatibility

preflight:

let named = @reflection.ToolClientDefinition::named(
  "reports",
  fn(name) { ReportsClient::new_for(name) },
)
let reports = named.client()

let reusable = @reflection.ToolClientDefinition::unnamed(
  fn(name) { ReportsClient::new_for(name) },
)
let staging_reports = reusable.client_for("reports-staging")

Method-only clients contain method codecs only. Bind the existing agent with an

@schema.AgentId; the type tag of the ID selects the agent type. Do not add a

standalone name to this form. An unknown ID raises Remote(NotFound(_)):

let counter = @reflection.MethodOnlyAgentClient::bind(existing_id)
let result : @reflection.Invocation[AddOutput] = counter.invoke(
  "add",
  AddInput::{ by: 5U },
)

Full clients add a declared type name, typed constructor/ID shape,

lifecycle mode, and an optional typed config carrier:

#derive.golem_schema
struct CounterId { name : String }
#derive.golem_schema
struct AddInput { by : UInt }
#derive.golem_schema
struct AddOutput { value : UInt }

// The keyed agent; the host creates it when it is missing
let counter = @reflection.FullAgentClient::upsert(
  "CounterAgent",
  CounterId::{ name: "main" },
)
// A new agent without a key (async); `keyed=true` creates the keyed agent instead
let fresh = @reflection.FullAgentClient::create(
  "CounterAgent",
  CounterId::{ name: "main" },
)
let fresh_id : @schema.AgentId = fresh.agent_id()
// The existing agent with the ID
let bound = @reflection.FullAgentClient::get_by_id("CounterAgent", fresh_id)

get_by_id never creates the agent; an unknown ID, or the ID of an agent of

another type, raises Remote(NotFound(_)). create also takes config?, a

typed carrier of @rpc.AgentConfigOverrides, and env?.

For ephemeral full clients, use ephemeral: every invocation runs on a new

one-shot instance, whose agent ID the invocation metadata returns. There is no

ephemeral create or get_by_id:

let logical = @reflection.FullAgentClient::ephemeral(
  "ResearchRequest",
  ResearchRequestId::{ route: "live" },
)

Ordinary RPC *Override records implement @rpc.AgentConfigOverrides, so the

same typed carrier accepted by a normal RPC client's create can be passed to

FullAgentClient::create. Secret config fields are deliberately absent from

generated override records. Custom callers may implement

AgentConfigOverrides using @rpc.typed_config_value.

Normal RPC #derive.agent clients expose the same upsert, create and

get_by_id construction for durable agents, and only upsert for ephemeral

agents. Caller codecs remain authoritative for payload encoding and decoding.

For trigger or scheduled caller-codec calls, pass an output type tag so the

SDK can reject live streams in either direction:

counter.trigger(
  "reset",
  ResetInput::{},
  (@schema.type_tag() : @schema.TypeTag[Unit]),
)

Identity and lifecycle boundaries

@schema.AgentId::parse reads its text form. It does not hold the agent type

or the constructor parameters, so it cannot be computed offline: ask a client

with agent_id(), or read it from agent metadata.

agent of a manually packed constructor value; for an ephemeral type, every

invocation runs on a new one-shot instance.

config?, env?)` to create a new durable agent.

Fully dynamic address helpers perform no discovery, schema validation, lifecycle-mode

verification, or local factory checks. The runtime is authoritative.

A bound method-only client exposes no lifecycle factories. The dynamic

helpers above construct raw addresses rather than validated lifecycle

factories. Packed streams and owned handles still follow

the MoonBit SDK's transfer and cleanup rules.

An ephemeral address has no guaranteed reusable pre-invocation identity. The

final identity comes from invocation metadata and must not be treated as a

resumable durable identity or rebound. Durable identities from invocation

metadata may be discovered later and rebound through a reflected client.

Choose an invocation path

| Situation | Use |

|---|---|

| Shared source definition available | Normal RPC agent client |

| Typed client owned by the caller | MethodOnlyAgentClient or FullAgentClient resolved by environment type name |

| Runtime-selected method with automatic JSON conversion | invoke_json |

| Explicit runtime-schema packing and inspection | SchemaRef::pack_json, invoke_value, unpack_json, to_json_schema |

| Fully dynamic infrastructure with Golem values | DynamicAgentClient |

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.