Agent Reflection and Client Approaches (Scala)
Golem exposes four composable client approaches:
- Normal RPC uses a shared source definition through the Scala SDK's ordinary typed RPC mechanism. It is not reflection.
- Caller-defined static clients use caller-owned compile-time codecs through
AgentClientDefinition, without deployment discovery. Definitions may be method-only or full. - Discovered clients read the current environment and produce immutable, snapshot-backed
ReflectedAgentClientandReflectedToolClientvalues with automatic input and output validation. - Fully dynamic clients use
DynamicAgentClientorDynamicToolClientto transport caller-packed schema-native values without retaining a schema authority.
The last three are reflection approaches. They are composable: discovery can
select schemas and agent IDs for a later fully dynamic call, and the
golem.AgentId of an existing durable agent can be rebound through a
method-only, discovered, or fully dynamic client with getById.
Discover and inspect schemas
import golem.reflection.Reflection
val target = Reflection.getAgentType("CounterAgent").flatMap(
_.toRight(golem.reflection.GolemReflectError.Discovery("CounterAgent is unavailable"))
)
val method = target.flatMap(
_.method("add").toRight(golem.reflection.GolemReflectError.Discovery("add is unavailable"))
)
Agent type names are unique in an environment. An AgentType exposes its
lifecycle mode, constructor
SchemaRef, and method SchemaRefs. SchemaRef validates SchemaValue, packs
and unpacks canonical zio.blocks.schema.json.Json, and renders JSON Schema.
An omitted option record field and an explicit null both decode as None;
re-encoding may emit null, and the field is omitted from JSON Schema
required. A tool command's inputSchema also accepts JSON that omits a
scalar option, positional with a declared default, or flag: packing fills in the
declared default, and toJsonSchema does not require the argument. Issues carry
the JSON path of 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. Capabilities, futures,
and streams cannot be packed or unpacked as reflected JSON and project to an
unsatisfiable reflection JSON Schema.
getAgentType returns Right(None) for a missing type and reserves Left for
discovery or decoding failures. The returned schemas are an immutable snapshot;
call discovery again when a newer deployment must be observed.
Use discovered clients
JSON convenience automatically packs and unpacks:
val invocation = client.method("add").flatMap { add =>
// The returned Future contains either a reflection error or JSON invocation.
Right(add.invokeJson(Json.Object("by" -> Json.Number(BigDecimal(5)))))
}
For explicit reflected packing, call method.definition.input.packJson, then
invokeValue; after awaiting, call the output SchemaRef.unpackJson.
For fully dynamic values, get a DynamicAgentClient with
DynamicAgentClient.getById(agentId) (the host resolves the agent type from the
ID) or DynamicAgentClient.upsert(typeName, constructorValue) (the keyed agent),
and manually construct the positional record:
import golem.reflection.DynamicAgentClient
import golem.schema.SchemaValue
val call = DynamicAgentClient.getById(agentId) match {
case Left(error) => Future.successful(Left(error))
case Right(client) =>
client.method("add").invokeValue(
SchemaValue.RecordValue(List(SchemaValue.U32Value(5)))
)
}
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 deliberately carries selected discovery values into a fully
dynamic client. It packs and validates before the call, handles transport and
tool errors, then explicitly validates and decodes the raw result:
import golem.reflection.{DynamicToolClient, Reflection}
import golem.schema.TypedSchemaValue
import zio.blocks.schema.json.Json
import scala.concurrent.{ExecutionContext, Future}
def invokeDiscoveredToolDynamically(
toolName: String,
path: List[String],
json: Json
)(using ExecutionContext): Future[Either[String, Option[Json]]] = {
val prepared = for {
tool <- Reflection.getToolType(toolName).left.map(_.toString)
command <- tool.command(path).left.map(_.toString)
input <- command.packJson(json).left.map(_.toString)
} yield (tool, command, TypedSchemaValue(command.inputSchema.graph, input))
prepared match {
case Left(error) => Future.successful(Left(error))
case Right((tool, command, input)) =>
new DynamicToolClient(tool.lookupName).invoke(command.path, input).map {
case Left(error) => Left(error.toString)
case Right(raw) =>
(command.result, raw.result) match {
case (None, None) => Right(None)
case (Some(schema), Some(output)) =>
schema
.validateValue(output.value)
.left
.map(_.map(_.message).mkString("; "))
.flatMap(_ => schema.unpackJson(output.value).left.map(_.message))
.map(Some(_))
case _ => Left("missing or unexpected tool result")
}
}
}
}
Moving tool.lookupName, command.path, and schema values into
DynamicToolClient does not transfer the reflected client's validation policy.
This non-streaming recipe owns no stream handles. For dynamic streaming calls,
drain or close transferred streams and cancel a started invocation when it is
abandoned.
The reflected factory is agentType.client. upsert(json) and upsertValue(value) return a client of the keyed agent of the constructor parameters, which the host creates when it is missing. create(json, keyed, config, env) and createValue(value, keyed, overrides, env) create a durable agent and return a Future: without keyed the new agent has no key and a new agent ID; with keyed = true it is the keyed agent, and an existing one gives GolemReflectError.Remote(AgentRpcError.Conflict(...)). Their creation-time overrides are canonical JSON entries (ReflectedConfigJson(path, value)) or schema-native ConfigOverride entries, respectively; the reflected type checks declared paths, secret fields, and values before constructing RPC. getById(agentId) (also on AgentType) returns an Either with a client of the existing agent at once; an unknown ID, or the ID of an agent of another type, gives AgentRpcError.NotFound. Every client has agentId(): Future[Either[GolemReflectError, AgentId]].
All reflected and direct methods support awaited, trigger, and scheduled calls
through invokeValue, triggerValue, and scheduleValue. Reflected live
streams are supported by awaited value calls. Trigger and scheduled discovered
or caller-defined calls reject methods whose input or output schema contains a
stream.
Define a caller-defined static client
AgentClientDefinition has two capability-typed construction forms and does
not discover remote schemas. InputRecordCodec and OutputCodec are the
caller's schema authority.
A method-only client definition contains methods only. It binds the existing durable
agent with a golem.AgentId, of the agent type that the ID names:
import golem.reflection._
import golem.runtime.{InputRecordCodec, OutputCodec}
val methods: AgentClientDefinition[MethodOnly, Unit, NoConfig] =
AgentClientDefinition.methodOnly
val add = methods.method(
"add",
InputRecordCodec.single[Int]("by"),
OutputCodec.single[Int]
)
val counter = methods.getById(existingId) // Either[GolemReflectError, CallerCodecAgentClient]
val result = counter match {
case Left(error) => Future.successful(Left(error))
case Right(client) => client.method(add).invoke(5)
}
A full client adds the declared name, lifecycle mode, constructor codec,
and an optional typed config codec. Construction infers DurableFull or
EphemeralFull; both extend Full, which gates identity helpers and
lifecycle factories:
val counter = AgentClientDefinition.full(
name = "CounterAgent",
mode = AgentMode.Durable,
constructor = InputRecordCodec.single[String]("name")
)
val keyed = counter.client.upsert("main") // the keyed agent
val fresh = counter.client.create("main") // Future: a new agent without a key
val keyedNew = counter.client.create("main", keyed = true) // Future: fails with a conflict when it exists
val bound = counter.client.getById(existingId) // Either: the existing agent
val id = fresh.flatMap {
case Left(error) => Future.successful(Left(error))
case Right(client) => client.agentId()
}
When the definition declares an AgentConfigCodec, create(input, config, keyed, env) also takes a typed config value. upsert and getById take no overrides.
Overrides are optional: component defaults can satisfy required local declarations. The host checks the effective config when it creates the agent and supplies secrets.
A full definition's getById binds the declared agent type; an ID of an agent of
another type gives AgentRpcError.NotFound. Fully defined ephemeral definitions
support only upsert, where every invocation runs on a new one-shot instance;
create and getById fail with GolemReflectError.Identity, and they have no
CanBindAgentClient capability, so AgentClientDefinition.getById is rejected at
compile time. AgentConfigCodec[C] maps a typed config carrier to
the existing typed ConfigOverride values; secret fields should not be exposed
by that codec.
Identity and lifecycle boundaries
- A
golem.AgentIdis an opaque UUID that Golem issues;AgentId.parse(text)
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 agentId(),
or read it from agent metadata.
Reflection.getAgentTypeFor(agentId)returns the deployed agent type that the
type tag of an agent ID names.
- Discovered, normal RPC, and full caller-defined factories provide
upsert,
and for durable types also create and getById.
- Use
DynamicAgentClient.upsert(typeName, constructorValue)for a raw keyed
address; for an ephemeral type every invocation runs on a new one-shot instance.
Method-only and fully dynamic agent clients do not expose lifecycle factories.
Packed streams and owned handles still follow the Scala SDK's transfer and
cleanup rules.
An ephemeral address has no reusable agent ID. The agent ID of the one-shot
instance that ran an invocation comes from invocation metadata and must not be
treated as a resumable durable agent or rebound. Durable agent IDs from
invocation metadata may be rebound later with getById.