Golem agent reflection ts

From golemcloud/golem · View interactive version

Golem agent reflection ts is an AI agent skill from the GitHub repository golemcloud/golem. Composing caller-defined static, discovered, and fully dynamic Golem clients in TypeScript. Use when schemas are caller-owned or discovered at runtime, or an existing AgentId must be bound to a client.

How to use this skill

Skill file

Calling Agents with Runtime Reflection (TypeScript)

Normal RPC is the non-reflective baseline: when producer and caller share a

source definition, use the SDK's ordinary Target.client surface. Reflection

adds caller-defined static clients, discovered clients, and fully dynamic

clients. These surfaces compose through immutable schema snapshots and typed

AgentId values: opaque UUIDs that Golem issues.

Discover Agent Types

The reflection API exposes agent types visible in the current environment:

import {
  getAllAgentTypes,
  getReflectedAgentType,
} from '@golemcloud/golem-ts-sdk';

const available = getAllAgentTypes();
const counterType = getReflectedAgentType('CounterAgent');

if (!counterType) {
  throw new Error('CounterAgent is not visible in this environment');
}

console.log(counterType.name, counterType.mode, counterType.sourceLanguage);
console.log(counterType.methods.map((method) => method.name));

An AgentType contains its constructor schema, method schemas, descriptions,

implementation identity, and lifecycle mode. Use method(name) when selecting

a method dynamically; it returns undefined for an unknown method.

Inspect and Validate Schemas

Constructor and method schemas are exposed as SchemaRef values. They accept

canonical JSON, report structured validation issues, and can render JSON

Schema:

const method = counterType.method('add');
if (!method) throw new Error('CounterAgent.add is not registered');

const validation = method.input.validateJson({ by: 5 });
if (!validation.success) {
  throw new Error(JSON.stringify(validation.issues));
}

const jsonSchema = method.input.toJsonSchema();

Use packJson and unpackJson only when integrating with APIs that explicitly

exchange schema-native values. Normal reflected calls accept and return JSON.

Invoke a Durable Agent

Use the reflected type's client factory just like a typed definition factory,

then select the method by name:

const counter = counterType.client.upsert({ name: 'main' });
const invocation = await counter.method('add').invoke({ by: 5 });

console.log(invocation.value);
console.log(invocation.metadata.agentId);
console.log(invocation.metadata.invocationId.toString()); // <agent-id>.<uuid>

upsert addresses the keyed agent of the constructor input and creates it when it is missing; it takes no overrides. To set configuration, create the agent with create, with one canonical JSON value per declared path:

const configured = await counterType.client.create(
  { name: 'other' },
  { keyed: true, config: [{ path: ['threshold'], value: 10 }], env: { MODE: 'test' } },
);

With keyed: true, create creates the keyed agent and rejects with a conflict RemoteCallError when it exists; without it, every create makes a new agent without a key, with a new agent ID. The reflected factory rejects unknown paths, secret fields, and invalid values locally. Required local fields may already have component defaults. The host validates the effective configuration when it creates the agent and supplies secrets. An existing agent keeps its original configuration.

invoke and invokeJson return { value, metadata }. trigger and schedule

also return identity metadata. Client creation and invocation failures are

reported as structured RemoteCallError values; use isRemoteCallError to

inspect their cause without parsing messages.

Choose Between Method-Only and Full Clients

defineAgentClient({ methods }) creates a caller-defined static method-only client. Use it only with an existing durable agent, through getById(agentId). It performs no discovery, creates no agents, and has no lifecycle mode or declaration-aware config validation.

defineAgentClient({ name, id, methods, mode?, config? }) creates a caller-defined static full client. Use it when the caller owns the complete local definition and needs the lifecycle factories: upsert, create, and getById for a durable mode, only upsert for an ephemeral mode. It still performs no deployment discovery.

Bind with a Method-Only Client

Use a method-only client when the ID of an existing durable agent is known.

getById takes the agent type from the type tag of the AgentId:

import { AgentId, defineAgentClient, method } from '@golemcloud/golem-ts-sdk';
import { z } from 'zod';

const existingAgentId = AgentId.parse(savedAgentIdText);
const PingClient = defineAgentClient({
  methods: {
    ping: method({ input: {}, returns: z.string() }),
  },
});

const client = PingClient.getById(existingAgentId);
const result = await client.ping();

A method-only client contains only methods; it cannot declare name,

id, config, or mode. It performs no discovery and uses durable result

semantics. An ID whose type tag names no deployed agent type, an ephemeral agent

type, or an unknown agent throws a not-found RemoteCallError.

AgentId.parse checks only the text form and throws a TypeError for text that

is not a UUID.

Address Agents with Caller-Owned Schemas

A fully defined client is the caller-defined static option when the target name,

constructor shape, and methods are known locally but the target implementation

is not imported. Its factories accept constructor values described by any

supported Standard Schema library:

import { z } from 'zod';
import { defineAgentClient, method } from '@golemcloud/golem-ts-sdk';

const CounterClient = defineAgentClient({
  name: 'CounterAgent',
  id: { name: z.string() },
  methods: {
    echo: method({ input: { message: z.string() }, returns: z.string() }),
  },
});

const counter = CounterClient.client.upsert({ name: 'main' });
const first = await counter.echo({ message: 'from Zod' });

const agentId = await counter.agentId();
const same = CounterClient.client.getById(agentId);
const second = await same.echo({ message: 'by ID' });

The factories validate and pack constructor fields through the caller's

schema library before opening RPC. getById connects only to an agent of the

declared agent type; an unknown ID, or the ID of an agent of another type,

throws a not-found RemoteCallError. For infrastructure that already

owns a Golem SchemaValue for the constructor, use the reflected factory's

upsertValue(value) or createValue(value, options); record fields must be in

the target constructor's declared order. When runtime metadata is available,

pack JSON with agentType.constructorInput.packJson(json).

Bind a Concrete Agent ID

After an agent exists, resolve the schema registered for the agent type of its

ID and bind it:

import { AgentId, getAgentTypeByAgentId } from '@golemcloud/golem-ts-sdk';

function bindExisting(agentId: AgentId) {
  const reflected = getAgentTypeByAgentId(agentId);
  if (!reflected || reflected.mode !== 'durable') {
    throw new Error('No deployed durable agent type has the type tag of this ID');
  }
  return reflected.client.getById(agentId);
}

getAgentTypeByAgentId reads the agent type from the type tag of the ID. It

does not check that the agent exists, and returns undefined when no deployed

agent type has that tag. getById never creates the agent: an unknown ID throws

a not-found RemoteCallError. AgentId.parse(text) is the strict local

operation when malformed ID text must be reported. Use

DynamicAgentClient.getById(agentId) only for lifecycle-free

infrastructure that already holds schema-native values and intentionally

invokes arbitrary method names without discovery.

Agents Without a Key and Ephemeral Agents

Reflected durable types expose the same factories as definition clients:

upsert, create, and getById. Without keyed, create makes a new agent

without a key; only its ID reaches it again:

const created = await counterType.client.create({ name: 'main' });
const createdId = await created.agentId();
const again = counterType.client.getById(createdId);

For an ephemeral reflected type, only upsert and upsertValue are available;

create rejects with a TypeError, and getById and the client's agentId()

throw one. Each invocation returns its allocated one-shot identity in metadata:

const requestType = getReflectedAgentType('RequestAgent');
if (!requestType || requestType.mode !== 'ephemeral') {
  throw new Error('RequestAgent must be ephemeral');
}

const request = requestType.client.upsert({ route: 'summarize' });

const result = await request.method('run').invoke({ text: 'hello' });
console.log(result.metadata.agentId, result.metadata.invocationId.toString());

Do not treat an ephemeral client as having a reusable agent ID. A one-shot

ephemeral instance cannot accept another invocation or be resumed.

Validation, Optional Values, and Wide Integers

Validation happens at several boundaries:

In Normal RPC and caller-defined static inputs, declare optional fields with the schema library, for example z.string().optional(), and omit them normally. Reflected JSON accepts either an omitted option record field or an explicit null as absent; re-encoding may include the field with null. Reflection JSON Schema omits that field from required:

import { getReflectedAgentType } from '@golemcloud/golem-ts-sdk';

const type = getReflectedAgentType('SearchAgent');
const search = type?.method('search');
if (!type || !search || type.mode !== 'durable') throw new Error('SearchAgent.search unavailable');

const checked = search.input.validateJson({ query: 'golem' });
if (!checked.success) throw new Error(JSON.stringify(checked.issues));
const result = await type.client.upsert({ tenant: 'docs' }).method('search').invoke({
  query: 'golem',
});
console.log(result.value);

Canonical JSON represents s64 and u64 as decimal strings. Duration is { nanoseconds: "..." }, and quantity uses a decimal-string mantissa. Smaller integers remain numbers. The generated JSON Schema uses matching patterns and exact range metadata.

Capabilities, futures, and streams cannot be packed or unpacked as reflected JSON. Their reflection JSON Schema projection is unsatisfiable; use schema-native value APIs for those leaves.

Cancellation, Streams, and Cleanup

Cancel an awaited agent call with AbortSignal; cancel a scheduled durable call with its token. A triggered call has no result observer:

import { getReflectedAgentType, isRemoteCallError } from '@golemcloud/golem-ts-sdk';

const type = getReflectedAgentType('CounterAgent');
if (!type || type.mode !== 'durable') throw new Error('CounterAgent unavailable');
const client = type.client.upsert({ name: 'main' });
const add = client.method('add');
const abort = new AbortController();

try {
  const pending = add.invoke({ by: 1 }, abort.signal);
  // abort.abort(); // cancels observation; remote side effects may already have happened
  console.log((await pending).value);
} catch (error) {
  if (isRemoteCallError(error)) console.error(error.cause);
  else throw error;
}

const scheduled = add.schedule({ seconds: 1n, nanoseconds: 0 }, { by: 2 });
scheduled.cancellationToken.cancel();

Schema-native streams and opaque capabilities cannot be packed as JSON. Use invokeValue, transfer an owned input stream once, consume returned streams to EOF or call return() when abandoning them, and do not reuse transferred handles. For reflected tools, startJson/startValue return independent stdout, stderr, result, collect(), and cancel() handles. collect() concurrently settles both outputs and the result, reporting a result failure before output failures; always consume or cancel a started operation.

Discovery to a Fully Dynamic Agent

Keep the discovered method snapshot beside the dynamic client. The dynamic

client does not inherit validation merely because its values came from

discovery:

import {
  DynamicAgentClient,
  getReflectedAgentType,
  isRemoteCallError,
} from '@golemcloud/golem-ts-sdk';

async function callDynamically() {
  const type = getReflectedAgentType('SearchAgent');
  const method = type?.method('search');
  if (!type || type.mode !== 'durable' || !method) {
    throw new Error('SearchAgent.search is unavailable');
  }

  const input = method.input.packJson({ query: 'golem', cursor: null });
  const inputCheck = method.input.validateValue(input);
  if (!inputCheck.success) throw new Error(JSON.stringify(inputCheck.issues));

  try {
    const id = await type.client.upsert({ tenant: 'docs' }).agentId();
    const dynamic = DynamicAgentClient.getById(id);
    const result = await dynamic.method(method.name).invokeValue(input);
    if (!method.output || result.value === undefined) {
      throw new Error('search returned an unexpected unit result');
    }
    const outputCheck = method.output.validateValue(result.value);
    if (!outputCheck.success) throw new Error(JSON.stringify(outputCheck.issues));
    return method.output.unpackJson(result.value);
  } catch (error) {
    if (isRemoteCallError(error)) {
      console.error('dynamic search failed', error.cause);
    }
    throw error;
  }
}

This awaited example owns no stream or cancellation handle. If a packed input

or output contains owned streams, transfer each input once and consume or close

every returned stream according to the cleanup rules above.

Choosing the Client Surface

| Situation | Use |

|---|---|

| Target definition and method known in source | Target.client |

| Type or method selected at runtime | getReflectedAgentType / getAllAgentTypes |

| Existing agent ID needs its current schema | getAgentTypeByAgentId(agentId), then client.getById(agentId) |

| Existing agent ID plus a caller-owned method-only or full client | clientDefinition.getById(agentId) or clientDefinition.client.getById(agentId) |

| Lifecycle-free invocation with schema-native values | DynamicAgentClient.getById(agentId) |

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.