> ## Documentation Index
> Fetch the complete documentation index at: https://docs.moltzap.xyz/llms.txt
> Use this file to discover all available pages before exploring further.

# simulator/src

> Code-first simulator API.

# simulator/src

*`packages/simulator/src`*

## Purpose

Code-first simulator API.

## Public surface

### [`AgentConnection`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/network/router.ts#L119)

*Interface*

```ts theme={null}
export interface AgentConnection<Name extends string = string> {
  readonly agent: AgentHandle<Name>;
  readonly key: AgentKey;
  readonly routerUrl: ServerBaseUrl;
  awaitReady(within: Duration.Duration): Effect.Effect<void, NetworkFailure>;
}
```

Runtime connection issued by every router implementation. A
runtime chooses its own startup deadline and awaits router-visible readiness
before completing acquisition.

### [`AgentHandle`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/network/participant.ts#L56)

*Class*

```ts theme={null}
export class AgentHandle<
  Name extends string = string,
> extends ParticipantHandle<Name> {
  readonly [AgentHandleTypeId] = AgentHandleTypeId;

  private constructor(name: Name, id: AgentId) {
    super(name, id, ParticipantHandleConstruction);
  }

  static [AgentHandleConstruction]<const Name extends string>(
    name: Name,
    id: AgentId,
  ): AgentHandle<Name> {
    return new AgentHandle(name, id);
  }
}
```

A participant whose autonomous runtime is owned by the run scope.

### [`AgentProcessExited`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/events/core.ts#L86)

*Class*

```ts theme={null}
export class AgentProcessExited extends Schema.TaggedClass<AgentProcessExited>()(
  "moltzap.agent-process-exited/v1",
  {
    agentName: AgentName,
    agentId: AgentId,
    runtime: Schema.NonEmptyString,
    code: Schema.NonNegativeInt,
  },
) {}
```

A roster runtime process terminated with an operating-system exit code.

### [`AgentProcessSignaled`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/events/core.ts#L97)

*Class*

```ts theme={null}
export class AgentProcessSignaled extends Schema.TaggedClass<AgentProcessSignaled>()(
  "moltzap.agent-process-signaled/v1",
  {
    agentName: AgentName,
    agentId: AgentId,
    runtime: Schema.NonEmptyString,
    signal: Schema.NonEmptyString,
  },
) {}
```

A roster runtime process terminated because it received a signal.

### [`AgentRoster`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/runtime/roster.ts#L60)

*Interface*

```ts theme={null}
export class AgentRoster<
  Id extends string,
  Definitions extends Readonly<Record<string, AgentRuntimeLike>>,
> {
  readonly [AgentRosterTypeId] = AgentRosterTypeId;

  private constructor(
    readonly definitionId: Id,
    readonly definitions: Definitions,
    readonly validatedDefinitions: ReadonlyArray<ValidatedAgentDefinition>,
    readonly Agents: Context.Tag<
      AgentsService<Id, Definitions>,
      StartedAgentHandles<Definitions>
    >,
  ) {}

  static make<
    const Id extends string,
    const Definitions extends Readonly<Record<string, AgentRuntimeLike>>,
  >(
    definitionId: Id,
    runtimes: Definitions,
  ): AgentRoster<Id, Definitions> {
    const entries = Object.entries(runtimes);
    const validatedDefinitions = Object.freeze(
      entries.map(([name, runtime]) =>
        Object.freeze({
          name,
          agentName: Schema.decodeUnknownSync(AgentName)(name),
          runtime,
        }),
      ),
    );
    nextRosterServiceId += 1;
    const definitions = Object.freeze(
      Object.fromEntries(entries),
    ) as Definitions;
    const Agents = Context.GenericTag<
      AgentsService<Id, Definitions>,
      StartedAgentHandles<Definitions>
    >(`@moltzap/simulator/Agents/${definitionId}/${nextRosterServiceId}`);
    return Object.freeze(
      new AgentRoster(definitionId, definitions, validatedDefinitions, Agents),
    );
  }
}
```

A roster is both the keyed runtime definition and the owner of the exact
handles service used by the experiment Effect.

### [`AgentRosterAcquisitionError`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/runtime/roster.ts#L32)

*TypeAlias*

```ts theme={null}
export type AgentRosterAcquisitionError<
  Definitions extends Readonly<Record<string, AgentRuntimeLike>>,
> = RuntimeAcquisitionErrorOf<Definitions[keyof Definitions]>;
```

### [`AgentRosterRequirements`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/runtime/roster.ts#L37)

*TypeAlias*

```ts theme={null}
export type AgentRosterRequirements<
  Definitions extends Readonly<Record<string, AgentRuntimeLike>>,
> = RuntimeRequirementsOf<Definitions[keyof Definitions]>;
```

The union of every heterogeneous runtime's Effect requirements.

### [`AgentRuntime`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/runtime/runtime.ts#L84)

*Interface*

```ts theme={null}
export interface AgentRuntime<AcquisitionError = never, Requirements = never>
```

A runtime definition accepted by keyed society rosters.

### [`AgentRuntimeCompleted`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/events/core.ts#L65)

*Class*

```ts theme={null}
export class AgentRuntimeCompleted extends Schema.TaggedClass<AgentRuntimeCompleted>()(
  "moltzap.agent-runtime-completed/v1",
  {
    agentName: AgentName,
    agentId: AgentId,
    runtime: Schema.NonEmptyString,
  },
) {}
```

An autonomous runtime completed normally.

### [`AgentRuntimeDefinition`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/runtime/runtime.ts#L73)

*Interface*

```ts theme={null}
export interface AgentRuntimeDefinition<
  AcquisitionError = never,
  Requirements = never,
> {
  readonly name: string;
  acquire<Name extends string>(
    input: AgentRuntimeInput<Name>,
  ): Effect.Effect<RunningAgent, AcquisitionError, Scope.Scope | Requirements>;
}
```

Scoped acquisition returns only after the runtime is ready. Implementations
own runtime-specific configuration and startup deadlines in their
constructors and register teardown in the acquisition Scope.

### [`AgentRuntimeDefinitionError`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/runtime/runtime.ts#L11)

*Class*

```ts theme={null}
export class AgentRuntimeDefinitionError extends Schema.TaggedError<AgentRuntimeDefinitionError>()(
  "AgentRuntimeDefinitionError",
  {
    detail: Schema.NonEmptyString,
  },
) {}
```

Invalid runtime metadata rejected before a run acquires resources.

### [`AgentRuntimeFailed`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/events/core.ts#L75)

*Class*

```ts theme={null}
export class AgentRuntimeFailed extends Schema.TaggedClass<AgentRuntimeFailed>()(
  "moltzap.agent-runtime-failed/v1",
  {
    agentName: AgentName,
    agentId: AgentId,
    runtime: Schema.NonEmptyString,
    cause: Schema.NonEmptyString,
  },
) {}
```

An autonomous runtime completed with a recorded failure.

### [`AgentRuntimeInput`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/runtime/runtime.ts#L64)

*Interface*

```ts theme={null}
export interface AgentRuntimeInput<Name extends string> {
  readonly connection: AgentConnection<Name>;
}
```

Router attachment issued to every autonomous runtime implementation.

### [`AgentRuntimeReady`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/events/core.ts#L45)

*Class*

```ts theme={null}
export class AgentRuntimeReady extends Schema.TaggedClass<AgentRuntimeReady>()(
  "moltzap.agent-runtime-ready/v1",
  {
    agentName: AgentName,
    agentId: AgentId,
    runtime: Schema.NonEmptyString,
  },
) {}
```

A roster runtime has acquired its identity and completed readiness.

### [`AgentRuntimeStartFailed`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/events/core.ts#L55)

*Class*

```ts theme={null}
export class AgentRuntimeStartFailed extends Schema.TaggedClass<AgentRuntimeStartFailed>()(
  "moltzap.agent-runtime-start-failed/v1",
  {
    agentName: AgentName,
    runtime: Schema.NonEmptyString,
    cause: Schema.NonEmptyString,
  },
) {}
```

A roster runtime failed before it established readiness.

### [`AgentsService`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/runtime/roster.ts#L48)

*Interface*

```ts theme={null}
export interface AgentsService<
  Id extends string,
  Definitions extends Readonly<Record<string, AgentRuntimeLike>>,
> {
  readonly definitionId: Id;
  readonly definitions: Definitions;
}
```

### [`ConversationAddress`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/network/conversation.ts#L40)

*Class*

```ts theme={null}
export class ConversationAddress {
  readonly [ConversationAddressTypeId] = ConversationAddressTypeId;

  private constructor(
    readonly taskId: TaskId,
    readonly conversationId: ConversationId,
    readonly participants: ConversationParticipants,
  ) {}

  static [ConversationAddressConstruction](
    taskId: TaskId,
    conversationId: ConversationId,
    participants: ConversationParticipants,
  ): ConversationAddress {
    return new ConversationAddress(taskId, conversationId, participants);
  }
}
```

A participant-independent network address. Binding an endpoint produces a
conversation socket; the address itself never implies a sender.

### [`ConversationOpened`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/events/core.ts#L108)

*Class*

```ts theme={null}
export class ConversationOpened extends Schema.TaggedClass<ConversationOpened>()(
  "moltzap.conversation-opened/v1",
  {
    openedBy: AgentId,
    taskId: TaskId,
    conversationId: ConversationId,
    participants: Schema.NonEmptyArray(AgentId),
  },
) {}
```

A participant allocated a conversation address for a nonempty group.

### [`ConversationParticipants`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/network/conversation.ts#L31)

*TypeAlias*

```ts theme={null}
export type ConversationParticipants = readonly [
  ParticipantHandle,
  ...ReadonlyArray<ParticipantHandle>,
];
```

Every conversation has at least one participant of any network role.

### [`ConversationSocket`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/network/conversation.ts#L100)

*Class*

```ts theme={null}
export class ConversationSocket {
  readonly [ConversationSocketTypeId] = ConversationSocketTypeId;

  /**
   * The ordered receive cursor for this endpoint and conversation. Repeated
   * consumption advances the cursor instead of replaying old delivery.
   */
  readonly messages: Stream.Stream<ReceivedMessage, NetworkFailure>;

  private constructor(
    readonly endpoint: ParticipantHandle,
    readonly address: ConversationAddress,
    messages: Stream.Stream<ReceivedMessage, NetworkFailure>,
    private readonly sendMessage: (
      content: MessageParts,
    ) => Effect.Effect<Message, NetworkFailure>,
  ) {
    this.messages = messages;
  }

  static [ConversationSocketConstruction](
    endpoint: ParticipantHandle,
    address: ConversationAddress,
    messages: Stream.Stream<ReceivedMessage, NetworkFailure>,
    sendMessage: (
      content: MessageParts,
    ) => Effect.Effect<Message, NetworkFailure>,
  ): ConversationSocket {
    return new ConversationSocket(endpoint, address, messages, sendMessage);
  }

  /** Commit one message through the bound endpoint. */
  send(content: string | MessageParts): Effect.Effect<Message, NetworkFailure> {
    return validateParts(parts(content)).pipe(Effect.flatMap(this.sendMessage));
  }

  /**
   * Receive the next ordered delivery. Selection policy belongs in the
   * consuming Effect, so the socket never skips an earlier message.
   */
  receive(): Effect.Effect<ReceivedMessage, NetworkFailure> {
    return this.messages.pipe(
      Stream.runHead,
      Effect.flatMap(
        Option.match({
          onNone: () =>
            Effect.fail(
              networkFailure(
                "receive",
                `conversation ${this.address.conversationId} ended before another message arrived`,
              ),
            ),
          onSome: Effect.succeed,
        }),
      ),
    );
  }
}
```

A conversation address bound to exactly one controlled endpoint.

### [`CoreEvents`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/events/core.ts#L228)

*Variable*

```ts theme={null}
export const CoreEvents = EventCatalog.merge(
  RunEvents,
  RouterEvents,
  RuntimeEvents,
  EndpointEvents,
  LinkEvents,
)
```

The exact event classes readable from every simulator run ledger.

### [`CustomerEvents`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/kernel/event-services.ts#L38)

*Interface*

```ts theme={null}
export interface CustomerEvents<Catalog extends AnyEventCatalog> {
  readonly emit: (
    event: EventOf<Catalog>,
    metadata?: EventMetadata,
  ) => Effect.Effect<LedgerRecord<Catalog>, LedgerFailure>;
}
```

Definition-bound emission of customer-owned event classes only.

### [`defineRuntime`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/runtime/runtime.ts#L99)

*Function*

```ts theme={null}
export function defineRuntime<AcquisitionError, Requirements>(
  runtime: AgentRuntimeDefinition<AcquisitionError, Requirements>,
): AgentRuntime<AcquisitionError, Requirements>
```

Preserve inferred attachment, error, and requirement types.

### [`EffectMessageContext`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/runtime/effect.ts#L49)

*Interface*

```ts theme={null}
export interface EffectMessageContext {
  readonly agent: AgentHandle;
  readonly taskId: TaskId;
  readonly message: Message;
}
```

Message delivery context passed to ordinary Effect agent code.

### [`EffectMessageReply`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/runtime/effect.ts#L56)

*TypeAlias*

```ts theme={null}
export type EffectMessageReply = string | MessageParts | undefined;
```

A message handler may decline to reply, reply with text, or provide parts.

### [`effectRuntime`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/runtime/effect.ts#L250)

*Function*

```ts theme={null}
export function effectRuntime<E = never, R = never>(
  options: EffectRuntimeOptions<E, R> = {},
): AgentRuntime<EffectRuntimeStartFailed, R>
```

Create a scoped in-process agent that communicates exclusively through the
production MoltZap protocol.

**Returns:** Autonomous runtime backed by in-process Effect behavior.

### [`EffectRuntimeOptions`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/runtime/effect.ts#L59)

*Interface*

```ts theme={null}
export interface EffectRuntimeOptions<E = never, R = never> {
  readonly startupTimeout?: Duration.Duration;
  readonly onMessage?: (
    context: EffectMessageContext,
  ) => Effect.Effect<EffectMessageReply, E, R>;
}
```

Construction options owned by one in-process runtime implementation.

### [`EffectRuntimeStartFailed`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/runtime/effect.ts#L36)

*Class*

```ts theme={null}
export class EffectRuntimeStartFailed extends Schema.TaggedError<EffectRuntimeStartFailed>()(
  "EffectRuntimeStartFailed",
  {
    agent: Schema.String,
    detail: Schema.String,
  },
) {
  override get message(): string {
    return `Effect runtime for "${this.agent}" failed to start: ${this.detail}`;
  }
}
```

Acquisition failed before an in-process agent became router-visible.

### [`EncodedEventOf`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/events/catalog.ts#L48)

*TypeAlias*

```ts theme={null}
export type EncodedEventOf<Catalog> = Schema.Schema.Encoded<
  CatalogSchemaOf<Catalog>
>;
```

The closed encoded union persisted for a catalog.

### [`Endpoint`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/network/endpoint.ts#L56)

*Class*

```ts theme={null}
export class Endpoint<Name extends string = string> {
  readonly [EndpointTypeId] = EndpointTypeId;

  private constructor(
    readonly participant: ParticipantHandle<Name>,
    private readonly transport: EndpointTransport,
    private readonly inbox: EndpointInbox,
  ) {}

  static [EndpointConstruction]<const Name extends string>(
    attachment: AttachedEndpoint<Name>,
    inbox: EndpointInbox,
  ): Endpoint<Name> {
    return new Endpoint(attachment.participant, attachment.transport, inbox);
  }

  /**
   * Observe messages delivered after this stream is subscribed. Conversation
   * sockets retain their own ordered delivery queues independently.
   * @returns Live endpoint delivery stream.
   */
  messages(): Stream.Stream<ReceivedMessage, NetworkFailure> {
    return this.inbox.messages;
  }

  /**
   * Open a conversation through this endpoint's ordinary protocol attachment.
   * The opener is included in the resulting address automatically.
   * @param participants Nonempty addressed participant set.
   * @returns A conversation socket bound to this endpoint.
   */
  open(
    ...participants: ConversationParticipants
  ): Effect.Effect<ConversationSocket, NetworkFailure> {
    const [first, ...rest] = participants;
    const ids: ParticipantIds = [
      first.id,
      ...rest.map((participant) => participant.id),
    ];
    const addressed = addressedParticipants(this.participant, participants);
    return this.transport.openConversation(ids).pipe(
      Effect.flatMap((opened) =>
        this.inbox.conversation(opened.taskId, opened.conversationId).pipe(
          Effect.map((messages) => ({
            messages,
            opened,
          })),
        ),
      ),
      Effect.map(({ messages, opened }) => {
        const address = makeConversationAddress(
          opened.taskId,
          opened.conversationId,
          addressed,
        );
        return makeConversationSocket(
          this.participant,
          address,
          messages,
          (content) =>
            this.transport.send(
              address.taskId,
              address.conversationId,
              content,
            ),
        );
      }),
    );
  }

  /**
   * Bind this endpoint as the sender for an existing address.
   * @param address Participant-independent conversation address.
   * @returns Endpoint-bound socket when this endpoint is addressed.
   */
  socket(
    address: ConversationAddress,
  ): Effect.Effect<ConversationSocket, NetworkFailure> {
    const isParticipant = address.participants.some(
      (participant) => participant.id === this.participant.id,
    );
    return isParticipant
      ? this.inbox
          .conversation(address.taskId, address.conversationId)
          .pipe(
            Effect.map((messages) =>
              makeConversationSocket(
                this.participant,
                address,
                messages,
                (content) =>
                  this.transport.send(
                    address.taskId,
                    address.conversationId,
                    content,
                  ),
              ),
            ),
          )
      : Effect.fail(
          networkFailure(
            "socket",
            `participant ${this.participant.name} is not addressed by the conversation`,
          ),
        );
  }
}
```

A run-scoped participant controlled directly by the experiment program.

### [`EndpointMessageReceived`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/events/core.ts#L131)

*Class*

```ts theme={null}
export class EndpointMessageReceived extends Schema.TaggedClass<EndpointMessageReceived>()(
  "moltzap.endpoint-message-received/v1",
  {
    endpointId: AgentId,
    taskId: TaskId,
    conversationId: ConversationId,
    messageId: MessageId,
    senderId: AgentId,
    parts: MessageParts,
  },
) {}
```

A controlled endpoint received a message through the data plane.

### [`EndpointMessageSent`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/events/core.ts#L119)

*Class*

```ts theme={null}
export class EndpointMessageSent extends Schema.TaggedClass<EndpointMessageSent>()(
  "moltzap.endpoint-message-sent/v1",
  {
    endpointId: AgentId,
    taskId: TaskId,
    conversationId: ConversationId,
    messageId: MessageId,
    parts: MessageParts,
  },
) {}
```

A controlled endpoint committed a message through the data plane.

### [`EventCatalog`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/events/catalog.ts#L156)

*Class*

```ts theme={null}
export class EventCatalog<
  SchemaType extends CatalogSchema,
  Classes extends EventClass = EventClass,
> {
  readonly schema: Schema.Schema<
    Schema.Schema.Type<SchemaType>,
    Schema.Schema.Encoded<SchemaType>,
    never
  >;
  readonly eventClasses: ReadonlyArray<EventClass>;
  readonly tags: ReadonlyArray<VersionedEventTag>;
  private readonly [EventCatalogTypeId] = EventCatalogTypeId;

  private constructor(
    schema: SchemaType,
    eventClasses: ReadonlyArray<EventClass>,
  ) {
    this.schema = Schema.make<
      Schema.Schema.Type<SchemaType>,
      Schema.Schema.Encoded<SchemaType>,
      never
    >(schema.ast);
    this.eventClasses = Object.freeze([...eventClasses]);
    this.tags = Object.freeze(
      this.eventClasses.map((eventClass) => eventClass._tag),
    );
    Object.freeze(this);
  }

  static make<
    const EventClasses extends readonly [
      EventClass,
      ...ReadonlyArray<EventClass>,
    ],
  >(
    ...eventClasses: EventClasses
  ): EventCatalog<EventClassesSchema<EventClasses>, EventClasses[number]> {
    validateEventClasses(eventClasses);
    return new EventCatalog(makeEventClassesSchema(eventClasses), eventClasses);
  }

  static empty(): EventCatalog<Schema.Schema<never>, never> {
    const eventClasses: ReadonlyArray<never> = [];
    return new EventCatalog(Schema.make<never>(Schema.Never.ast), eventClasses);
  }

  static merge<
    const Catalogs extends readonly [
      EventCatalog<CatalogSchema, EventClass>,
      ...ReadonlyArray<EventCatalog<CatalogSchema, EventClass>>,
    ],
  >(
    ...catalogs: Catalogs
  ): EventCatalog<
    MergedCatalogSchema<Catalogs>,
    CatalogClassesOf<Catalogs[number]>
  > {
    const eventClasses = catalogs.flatMap((catalog) => catalog.eventClasses);
    validateEventClasses(eventClasses);
    return new EventCatalog(mergeCatalogSchemas(catalogs), eventClasses);
  }

  has(eventClass: EventClass): eventClass is Classes {
    return this.eventClasses.some(
      (catalogEventClass) => catalogEventClass === eventClass,
    );
  }

  hasEvent(event: unknown): event is Schema.Schema.Type<SchemaType> {
    if (typeof event !== "object" || event === null) {
      return false;
    }
    const constructor: unknown = Reflect.get(event, "constructor");
    return this.eventClasses.some((eventClass) => eventClass === constructor);
  }

  decode(input: unknown) {
    return Schema.decodeUnknown(Schema.asSchema(this.schema))(input, {
      onExcessProperty: "error",
    });
  }

  encode(event: Schema.Schema.Type<SchemaType>) {
    return Schema.encode(Schema.asSchema(this.schema))(event, {
      onExcessProperty: "error",
    });
  }
}
```

The exact immutable event universe for one definition.

The private type identifier makes catalog arguments nominal: a structural
object cannot claim a schema, constructor list, and tag list that disagree.

### [`EventCatalogDefinitionError`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/events/catalog.ts#L58)

*Class*

```ts theme={null}
export class EventCatalogDefinitionError extends Schema.TaggedError<EventCatalogDefinitionError>()(
  "EventCatalogDefinitionError",
  {
    failure: Schema.Literal(
      "duplicate-tag",
      "invalid-event-class",
      "invalid-tag",
    ),
    tag: Schema.String,
  },
) {
  override get message(): string {
    switch (this.failure) {
      case "duplicate-tag":
        return `Duplicate event tag "${this.tag}"`;
      case "invalid-event-class":
        return `Event catalog member "${this.tag}" is not a schema-backed class`;
      case "invalid-tag":
        return `Event tag "${this.tag}" must be namespaced and versioned, for example "acme.consensus-reached/v1"`;
    }
  }
}
```

Invalid catalogs fail during definition construction, before a run starts.

### [`EventCatalogDefinitionFailure`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/events/catalog.ts#L52)

*TypeAlias*

```ts theme={null}
export type EventCatalogDefinitionFailure =
  | "duplicate-tag"
  | "invalid-event-class"
  | "invalid-tag";
```

### [`EventClass`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/events/catalog.ts#L10)

*TypeAlias*

```ts theme={null}
export type EventClass = Schema.Schema.AnyNoContext & {
  readonly _tag: VersionedEventTag;
};
```

A schema-backed event constructor. The catalog retains both the schema and
constructor faces so persisted values decode back into their exact class.

### [`EventClassOf`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/events/catalog.ts#L45)

*TypeAlias*

```ts theme={null}
export type EventClassOf<Catalog> = CatalogClassesOf<Catalog>;
```

The closed constructor union declared by a catalog.

### [`EventMetadata`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/kernel/event-services.ts#L22)

*Interface*

```ts theme={null}
export interface EventMetadata {
  readonly causationId?: string;
  readonly correlationId?: string;
}
```

Causality metadata accepted from a customer event producer.

### [`EventOf`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/events/catalog.ts#L42)

*TypeAlias*

```ts theme={null}
export type EventOf<Catalog> = Schema.Schema.Type<CatalogSchemaOf<Catalog>>;
```

The closed instance union declared by a catalog.

### [`InstallMode`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/runtime/packages.ts#L505)

*TypeAlias*

```ts theme={null}
export type InstallMode = "published" | "workspace";
```

### [`LedgerFailure`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/ledger/live.ts#L54)

*TypeAlias*

```ts theme={null}
export type LedgerFailure =
  | LedgerStorageError
  | ParseResult.ParseError
  | LedgerSerializationError;
```

### [`LinkController`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/network/link.ts#L49)

*Class*

```ts theme={null}
export class LinkController extends Context.Tag(
  "@moltzap/simulator/LinkController",
)<LinkController, LinkControllerService>() {}
```

Experiment-facing directed-link control installed by the run kernel.

### [`LinkControllerService`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/network/link.ts#L37)

*Interface*

```ts theme={null}
export interface LinkControllerService {
  /**
   * Keep one directed link disabled for the lifetime of the current Scope.
   * Overlapping acquisitions share a single physical down/up transition.
   */
  readonly disable: (
    from: ParticipantHandle,
    to: ParticipantHandle,
  ) => Effect.Effect<void, NetworkFailure, LinkDriver | Scope.Scope>;
}
```

Run-scoped, evidence-producing directed-link control.

### [`LinkDown`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/events/core.ts#L155)

*Class*

```ts theme={null}
export class LinkDown extends Schema.TaggedClass<LinkDown>()(
  "moltzap.link-down/v1",
  {
    from: AgentId,
    to: AgentId,
  },
) {}
```

A directed participant link transitioned from available to unavailable.

### [`LinkUp`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/events/core.ts#L164)

*Class*

```ts theme={null}
export class LinkUp extends Schema.TaggedClass<LinkUp>()("moltzap.link-up/v1", {
  from: AgentId,
  to: AgentId,
}) {}
```

A directed participant link transitioned from unavailable to available.

### [`MessageParts`](https://github.com/chughtapan/moltzap/blob/main/packages/protocol/dist/message/parts.d.ts#L40)

*TypeAlias*

```ts theme={null}
export type MessageParts = Schema.Schema.Type<typeof MessagePartsSchema>;
```

Nonempty protocol message content.

### [`nanoclawRuntime`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/runtime/nanoclaw/runtime.ts#L352)

*Function*

```ts theme={null}
export function nanoclawRuntime(
  options: NanoclawRuntimeOptions = {},
): AgentRuntime<NanoclawRuntimeAcquisitionError, NanoclawHostServices>
```

Construct a NanoClaw runtime that binds each roster identity to one
scoped container-backed process and waits for router-visible readiness.

### [`NanoclawRuntimeAcquisitionError`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/runtime/nanoclaw/runtime.ts#L119)

*TypeAlias*

```ts theme={null}
export type NanoclawRuntimeAcquisitionError = RuntimeAcquisitionFailed;
```

Failure returned when NanoClaw cannot become router-visible.

### [`NanoclawRuntimeOptions`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/runtime/nanoclaw/runtime.ts#L51)

*Interface*

```ts theme={null}
export interface NanoclawRuntimeOptions {
  readonly startupTimeout?: Duration.Duration;
  readonly workspaceFiles?: ReadonlyArray<NanoclawWorkspaceFile>;
  readonly modelId?: string;
  readonly installMode?: InstallMode;

  /**
   * Register conversations on first delivery in disposable evaluations.
   * Ordinary societies leave registration to their endpoint code.
   */
  readonly autoRegisterConversations?: boolean;

  /** Stdio MCP servers mounted into the NanoClaw container workspace. */
  readonly mcpServers?: ReadonlyArray<NanoclawMcpServer>;
}
```

Configuration captured by one reusable NanoClaw runtime value.

### [`Network`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/network/endpoint.ts#L189)

*Class*

```ts theme={null}
export class Network extends Context.Tag("@moltzap/simulator/Network")<
  Network,
  NetworkService
>() {}
```

Network operations available to the customer program.

### [`NetworkFailure`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/network/router.ts#L46)

*Class*

```ts theme={null}
export class NetworkFailure extends Schema.TaggedError<NetworkFailure>()(
  "NetworkFailure",
  {
    operation: NetworkOperation,
    detail: Schema.String,
  },
) {
  override get message(): string {
    return `Network ${this.operation} failed: ${this.detail}`;
  }
}
```

An operational failure at a network boundary.

### [`NetworkService`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/network/endpoint.ts#L182)

*Interface*

```ts theme={null}
export interface NetworkService {
  endpoint<const Name extends string>(
    name: Name,
  ): Effect.Effect<Endpoint<Name>, NetworkFailure>;
}
```

Controlled endpoint operations installed for one run scope.

### [`openClawRuntime`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/runtime/openclaw/runtime.ts#L318)

*Function*

```ts theme={null}
export function openClawRuntime(
  options: OpenClawRuntimeOptions = {},
): AgentRuntime<OpenClawRuntimeAcquisitionError, OpenClawHostServices>
```

Construct an OpenClaw runtime that binds each roster identity to one
scoped gateway process and waits for router-visible readiness.

### [`OpenClawRuntimeAcquisitionError`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/runtime/openclaw/runtime.ts#L94)

*TypeAlias*

```ts theme={null}
export type OpenClawRuntimeAcquisitionError = RuntimeAcquisitionFailed;
```

Failure returned when OpenClaw cannot become router-visible.

### [`OpenClawRuntimeOptions`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/runtime/openclaw/runtime.ts#L48)

*Interface*

```ts theme={null}
export interface OpenClawRuntimeOptions {
  readonly startupTimeout?: Duration.Duration;
  readonly workspaceFiles?: ReadonlyArray<OpenClawWorkspaceFile>;
  readonly modelId?: string;
  readonly installMode?: InstallMode;
  readonly openclawBin?: string;
  readonly channelDistDir?: string;
  readonly mcpServers?: ReadonlyArray<OpenClawMcpServer>;
}
```

Configuration captured by one reusable OpenClaw runtime value.

### [`ParticipantHandle`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/network/participant.ts#L22)

*Class*

```ts theme={null}
export class ParticipantHandle<Name extends string = string> {
  readonly [ParticipantHandleTypeId] = ParticipantHandleTypeId;

  protected constructor(
    readonly name: Name,
    readonly id: AgentId,
    _construction: typeof ParticipantHandleConstruction,
  ) {}

  static [ParticipantHandleConstruction]<const Name extends string>(
    name: Name,
    id: AgentId,
  ): ParticipantHandle<Name> {
    return new ParticipantHandle(name, id, ParticipantHandleConstruction);
  }
}
```

A router-issued network identity. The hidden symbol prevents structurally
similar protocol data from being used as an identity handle.

### [`ProgramFailed`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/events/core.ts#L176)

*Class*

```ts theme={null}
export class ProgramFailed extends Schema.TaggedClass<ProgramFailed>()(
  "moltzap.program-failed/v1",
  {
    cause: Schema.NonEmptyString,
  },
) {}
```

The customer program failed with a typed failure or defect.

### [`ProgramInterrupted`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/events/core.ts#L184)

*Class*

```ts theme={null}
export class ProgramInterrupted extends Schema.TaggedClass<ProgramInterrupted>()(
  "moltzap.program-interrupted/v1",
  {
    cause: Schema.NonEmptyString,
  },
) {}
```

The customer program was interrupted.

### [`ProgramSucceeded`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/events/core.ts#L170)

*Class*

```ts theme={null}
export class ProgramSucceeded extends Schema.TaggedClass<ProgramSucceeded>()(
  "moltzap.program-succeeded/v1",
  {},
) {}
```

The customer program returned successfully.

### [`ReadableRunLedger`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/kernel/event-services.ts#L28)

*Interface*

```ts theme={null}
export interface ReadableRunLedger<Catalog extends AnyEventCatalog> {
  readonly ref: LedgerRef;
  readonly manifest: LedgerManifest;
  readonly records: Stream.Stream<LedgerRecord<Catalog>, LedgerFailure>;
  readonly events: <Event extends EventClassOf<Catalog>>(
    eventClass: Event,
  ) => Stream.Stream<Schema.Schema.Type<Event>, LedgerFailure>;
}
```

Definition-bound read access to every committed core and customer event.

### [`ReceivedMessage`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/network/router.ts#L72)

*Interface*

```ts theme={null}
export interface ReceivedMessage {
  readonly taskId: TaskId;
  readonly message: Message;
}
```

A message delivered to one attached endpoint.

### [`RouterMessageCommitted`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/events/core.ts#L147)

*Class*

```ts theme={null}
export class RouterMessageCommitted extends Schema.TaggedClass<RouterMessageCommitted>()(
  "moltzap.router-message-committed/v1",
  {
    ...CommittedRouterMessage.fields,
  },
) {}
```

The router durably committed one message. Payload content remains an
endpoint concern so this evidence also works with content-blind routers.

### [`RouterStarted`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/events/core.ts#L21)

*Class*

```ts theme={null}
export class RouterStarted extends Schema.TaggedClass<RouterStarted>()(
  "moltzap.router-started/v1",
  {
    routerUrl: ServerBaseUrl,
  },
) {}
```

The run-scoped router is accepting participant connections.

### [`RouterStartFailed`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/events/core.ts#L29)

*Class*

```ts theme={null}
export class RouterStartFailed extends Schema.TaggedClass<RouterStartFailed>()(
  "moltzap.router-start-failed/v1",
  {
    cause: Schema.NonEmptyString,
  },
) {}
```

Router acquisition failed before the data plane became available.

### [`RouterStopFailed`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/events/core.ts#L37)

*Class*

```ts theme={null}
export class RouterStopFailed extends Schema.TaggedClass<RouterStopFailed>()(
  "moltzap.router-stop-failed/v1",
  {
    cause: Schema.NonEmptyString,
  },
) {}
```

Router release or stopped-router evidence collection failed.

### [`RunningAgent`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/runtime/runtime.ts#L59)

*Interface*

```ts theme={null}
export interface RunningAgent {
  readonly termination: Effect.Effect<RuntimeTermination>;
}
```

The only post-acquisition lifecycle observation. Completion of this Effect
records a fact; customer policy decides whether that fact ends the run.

### [`RunStarted`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/events/core.ts#L13)

*Class*

```ts theme={null}
export class RunStarted extends Schema.TaggedClass<RunStarted>()(
  "moltzap.run-started/v1",
  {
    definitionId: Schema.NonEmptyString,
  },
) {}
```

The run ledger is allocated and run-scoped acquisition has begun.

### [`RuntimeAcquisitionFailed`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/runtime/process.ts#L36)

*Class*

```ts theme={null}
export class RuntimeAcquisitionFailed extends Schema.TaggedError<RuntimeAcquisitionFailed>()(
  "RuntimeAcquisitionFailed",
  {
    runtime: Schema.NonEmptyString,
    agent: Schema.NonEmptyString,
    detail: Schema.String,
  },
) {
  override get message(): string {
    return `${this.runtime} runtime for "${this.agent}" failed to start: ${this.detail}`;
  }
}
```

An external runtime did not become a ready participant.

### [`RuntimeCompleted`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/runtime/runtime.ts#L19)

*Class*

```ts theme={null}
export class RuntimeCompleted extends Schema.TaggedClass<RuntimeCompleted>()(
  "RuntimeCompleted",
  {},
) {}
```

An autonomous runtime completed normally.

### [`RuntimeExited`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/runtime/runtime.ts#L33)

*Class*

```ts theme={null}
export class RuntimeExited extends Schema.TaggedClass<RuntimeExited>()(
  "RuntimeExited",
  {
    code: Schema.NonNegativeInt,
  },
) {}
```

A runtime process exited with an operating-system exit code.

### [`RuntimeFailed`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/runtime/runtime.ts#L25)

*Class*

```ts theme={null}
export class RuntimeFailed extends Schema.TaggedClass<RuntimeFailed>()(
  "RuntimeFailed",
  {
    detail: Schema.String,
  },
) {}
```

An autonomous runtime completed with a recorded failure.

### [`RuntimeSignaled`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/runtime/runtime.ts#L41)

*Class*

```ts theme={null}
export class RuntimeSignaled extends Schema.TaggedClass<RuntimeSignaled>()(
  "RuntimeSignaled",
  {
    signal: Schema.NonEmptyString,
  },
) {}
```

A runtime process terminated in response to an operating-system signal.

### [`RuntimeTermination`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/runtime/runtime.ts#L49)

*TypeAlias*

```ts theme={null}
export type RuntimeTermination =
  | RuntimeCompleted
  | RuntimeFailed
  | RuntimeExited
  | RuntimeSignaled;
```

Exact terminal observation produced by an acquired runtime.

### [`Simulator`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/definition.ts#L233)

*Variable*

```ts theme={null}
export const Simulator: Readonly<{ define: typeof defineSimulator }> =
  Object.freeze({
    define: defineSimulator,
  })
```

Discoverable entry point for code-first society definitions.

### [`SimulatorDefinition`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/definition.ts#L171)

*Interface*

```ts theme={null}
export interface SimulatorDefinition<
  Id extends SimulatorDefinitionId,
  CustomerCatalogs extends ReadonlyArray<AnyEventCatalog>,
> {
  readonly id: Id;
  readonly catalog: DefinitionEventServices<Id, CustomerCatalogs>["catalog"];
  readonly customerCatalog: CustomerEventCatalog<CustomerCatalogs>;
  readonly Ledger: DefinitionEventServices<Id, CustomerCatalogs>["Ledger"];
  readonly Events: DefinitionEventServices<Id, CustomerCatalogs>["Events"];
  readonly agents: ReturnType<typeof makeAgentRosterBuilder<Id>>;
  readonly run: ReturnType<
    typeof makeRunner<
      Id,
      CatalogSchemaOf<CustomerEventCatalog<CustomerCatalogs>>,
      CatalogClassesOf<CustomerEventCatalog<CustomerCatalogs>>
    >
  >;
  readonly openLedger: ReturnType<
    typeof makeLedgerReader<
      Id,
      CatalogSchemaOf<CustomerEventCatalog<CustomerCatalogs>>,
      CatalogClassesOf<CustomerEventCatalog<CustomerCatalogs>>
    >
  >;
}
```

Definition-bound capabilities for one versioned family of simulator runs.

### [`SimulatorDefinitionError`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/definition.ts#L26)

*Class*

```ts theme={null}
export class SimulatorDefinitionError extends Schema.TaggedError<SimulatorDefinitionError>()(
  "SimulatorDefinitionError",
  {
    definitionId: Schema.String,
    detail: Schema.NonEmptyString,
  },
) {
  override get message(): string {
    return `Simulator definition "${this.definitionId}" is invalid: ${this.detail}`;
  }
}
```

### [`SimulatorDefinitionId`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/definition.ts#L22)

*TypeAlias*

```ts theme={null}
export type SimulatorDefinitionId = `${string}.${string}/v${number}`;
```

Stable code identity persisted in every ledger manifest.

### [`simulatorLayer`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/layer.ts#L21)

*Function*

```ts theme={null}
export function simulatorLayer(options: SimulatorLayerOptions)
```

Provide the production router, filesystem ledger, and Effect Platform host
services once at the application boundary.

### [`SimulatorLayerOptions`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/layer.ts#L12)

*Interface*

```ts theme={null}
export interface SimulatorLayerOptions {
  readonly ledgerDirectory: string;
  readonly router: MoltZapRouterOptions;
}
```

Host configuration shared by every run provided with this Layer.

### [`SimulatorRunFailure`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/kernel/run.ts#L69)

*TypeAlias*

```ts theme={null}
export type SimulatorRunFailure<
  Definitions extends Readonly<Record<string, AgentRuntimeLike>>,
> = AgentRosterAcquisitionError<Definitions> | LedgerFailure | NetworkFailure;
```

### [`SimulatorRunOptions`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/kernel/run.ts#L57)

*Interface*

```ts theme={null}
export interface SimulatorRunOptions {
  readonly provenance?: JsonObject;
  readonly metadata?: JsonObject;
}
```

Optional run metadata; platform and runtime policy belong in Layers.

### [`SimulatorRunResult`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/kernel/run.ts#L63)

*Interface*

```ts theme={null}
export interface SimulatorRunResult<A, E> {
  readonly exit: Exit.Exit<A, E>;
  readonly ledger: LedgerRef;
  readonly completion: LedgerCompletion;
}
```

The program Exit plus the durable ledger that proves the run.

### [`StartedAgentHandles`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/runtime/roster.ts#L42)

*TypeAlias*

```ts theme={null}
export type StartedAgentHandles<
  Definitions extends Readonly<Record<string, AgentRuntimeLike>>,
> = Readonly<{
  [Name in Extract<keyof Definitions, string>]: AgentHandle<Name>;
}>;
```

Exact keyed handles installed only after every runtime is ready.

### [`VersionedEventTag`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/events/catalog.ts#L4)

*TypeAlias*

```ts theme={null}
export type VersionedEventTag = `${string}.${string}/v${number}`;
```

Stable persisted identity for an event class.

## Files

* `definition.ts`
* `catalog.ts`
* `core.ts`
* `event-services.ts`
* `run.ts`
* `layer.ts`
* `live.ts`
* `conversation.ts`
* `endpoint.ts`
* `link.ts`
* `participant.ts`
* `router.ts`
* `effect.ts`
* `runtime.ts`
* `runtime.ts`
* `packages.ts`
* `process.ts`
* `roster.ts`
* `runtime.ts`
