Concepts
Agents (Logic + Lifecycle)
Agents are units of work. You build them with the AgentFactory builder, declaring which events they listen to, which events they emit, and the async logic that runs when triggered.
Basic Usage
import { AgentFactory, AgentNetworkEvent, S } from '@m4trix/core/matrix';
const inputEvent = AgentNetworkEvent.of('user-input', S.Struct({ text: S.String }));
const outputEvent = AgentNetworkEvent.of('agent-output', S.Struct({ reply: S.String }));
const echoAgent = AgentFactory.run()
.listensTo([inputEvent])
.emits([outputEvent])
.logic(async ({ triggerEvent, emit }) => {
emit({
name: 'agent-output',
payload: { reply: `Echo: ${triggerEvent.payload.text}` },
});
})
.produce({});Lifecycle
- Definition —
AgentFactory.run()starts the builder;.listensTo(),.emits(),.logic()configure the agent. - Production —
.produce(params)finalizes and returns anAgentinstance. - Registration — The agent is registered in a network via
registerAgent(agent).subscribe(...).publishTo(...). - Execution — When a matching event arrives on a subscribed channel, the logic runs. The agent can emit events to its publish channels.
Type Safety
The builder provides end-to-end type inference:
- Trigger events —
triggerEventin.logic()is typed as a union of alllistensToevent envelopes - Emit payloads — The
emit()function only accepts payloads matching declaredemitsevents - Parameters —
paramsin.logic()matches the schema from.params()(validated by.produce()) - Runtime emit checks —
emitonly publishes events declared with.emits()(or a tool's.emits()) whose payload passes the event's schema; anything else throwsEmitValidationErrorand fails the invocation. An agent without.emits()may emit nothing
Catch-All Agents
If you omit .listensTo(), the agent receives every event on its subscribed channels, except the runtime's own m4trix:* events. Useful for logging and monitoring.
const loggerAgent = AgentFactory.run()
.logic(async ({ triggerEvent }) => {
console.log('Event received:', triggerEvent);
})
.produce({});See AgentFactory API for the full builder reference.