> ## 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.

# server-core/socket

> Server WebSocket connection/session runtime primitives.

# server-core/socket

*`packages/server/src/socket`*

## Purpose

Server WebSocket connection/session runtime primitives.

## Public surface

### [`AgentConnection`](https://github.com/chughtapan/moltzap/blob/main/packages/server/src/socket/connection.ts#L50)

*Interface*

```ts theme={null}
class AgentConnection extends Data.TaggedClass("AgentConnection")<
  ConnectionBase & { readonly auth: AgentContext }
> {
  private readonly brandValue!: never;
}
```

Re-exports the public API from `current module`.

### [`AgentContext`](https://github.com/chughtapan/moltzap/blob/main/packages/server/src/socket/context.ts#L16)

*Class*

```ts theme={null}
export class AgentContext extends Data.TaggedClass("AgentContext")<{
  readonly agentId: AgentId;
  readonly agentStatus: AgentStatus;
  readonly ownerUserId: UserId;
}> {}
```

The principal context stored on an authenticated socket connection. Every
gated method's `requires` head selects this arm.

### [`agentContextFrom`](https://github.com/chughtapan/moltzap/blob/main/packages/server/src/socket/context.ts#L32)

*Function*

```ts theme={null}
export function agentContextFrom(parts: {
  readonly agentId: AgentId;
  readonly agentStatus: string;
  readonly ownerUserId: UserId;
}): Effect.Effect<AgentContext>
```

Mint an AgentContext from authenticator fields. The `agent_status`
SQL enum constrains stored values to AgentStatus, but the DB driver
types it as `string`, so any other value is an impossible-state defect.

**Returns:** The agent context from result.

### [`AgentStatus`](https://github.com/chughtapan/moltzap/blob/main/packages/server/src/socket/context.ts#L10)

*TypeAlias*

```ts theme={null}
export type AgentStatus = "active" | "suspended";
```

Closed agent lifecycle states. Mirrors
`core-schema.sql → CREATE TYPE agent_status AS ENUM (...)`. The closed
union makes the active-agent check exhaustive — adding a state forces every
consumer switch to handle it.

### [`Connection`](https://github.com/chughtapan/moltzap/blob/main/packages/server/src/socket/connection.ts#L60)

*TypeAlias*

```ts theme={null}
export type Connection = UnauthenticatedConnection | AgentConnection;
```

The two-arm connection state — the connections map's only entry shape.

### [`ConnectionManager`](https://github.com/chughtapan/moltzap/blob/main/packages/server/src/socket/connection.ts#L137)

*Class*

```ts theme={null}
export class ConnectionManager {
  /**
   * Connections and their per-agent delivery projection share one Ref so
   * authentication, disconnect cleanup, and subscription updates are atomic.
   * This prevents an old last-disconnect cleanup from deleting a newly
   * authenticated socket's freshly hydrated subscriptions.
   */
  private readonly stateRef: Ref.Ref<ConnectionManagerState> = Effect.runSync(
    Ref.make({
      connections: HashMap.empty<ConnectionId, Connection>(),
      agentConversationSubscriptions: HashMap.empty<
        AgentId,
        HashSet.HashSet<ConversationId>
      >(),
    }),
  );

  /**
   * Insert a fresh `UnauthenticatedConnection`. Called by the socket handler
   * at WebSocket open. The Connect handler promotes it to the agent arm.
   * @param connId Value supplied to the operation.
   * @param socket Value supplied to the operation.
   * @param originator Value supplied to the operation.
   * @returns The add unauthenticated result.
   */
  addUnauthenticated(
    connId: ConnectionId,
    socket: WebSocketRef,
    originator: Originator,
  ): Effect.Effect<void> {
    return Ref.update(this.stateRef, (state) => ({
      ...state,
      connections: HashMap.set(
        state.connections,
        connId,
        new UnauthenticatedConnection({ connId, socket, originator }),
      ),
    }));
  }

  /**
   * Non-mutating read. Callers discriminate on the returned arm's `_tag`.
   * @param connId Value supplied to the operation.
   * @returns The current result.
   */
  peek(connId: ConnectionId): Effect.Effect<Option.Option<Connection>> {
    return Ref.get(this.stateRef).pipe(
      Effect.map((state) => HashMap.get(state.connections, connId)),
    );
  }

  /**
   * Snapshot of every connection arm. Callers iterate + discriminate on `_tag`
   * (e.g. The shutdown loop reads `arm.socket.shutdown`).
   * @returns The current result.
   */
  allConnections(): Effect.Effect<readonly Connection[]> {
    return Ref.get(this.stateRef).pipe(
      Effect.map((state) => Array.from(HashMap.values(state.connections))),
    );
  }

  /**
   * Current connection count.
   * @returns The current result.
   */
  currentSize(): Effect.Effect<number> {
    return Ref.get(this.stateRef).pipe(
      Effect.map((state) => HashMap.size(state.connections)),
    );
  }

  /**
   * Atomic per-connection authentication gate. Mints the agent arm from the
   * unauthenticated entry and returns a `TransitionOutcome` whose success arm
   * carries the minted connection, so callers narrow without a cast.
   * @param connId Value supplied to the operation.
   * @param auth Value supplied to the operation.
   * @returns The current result.
   */
  authenticate(
    connId: ConnectionId,
    auth: AgentContext,
  ): Effect.Effect<TransitionOutcome> {
    return Ref.modify(this.stateRef, (state) => {
      const current = HashMap.get(state.connections, connId);
      if (Option.isNone(current)) {
        return [{ kind: "not-connected" } as const, state];
      }
      return Match.value(current.value).pipe(
        Match.tag(
          "AgentConnection",
          (existing): [TransitionOutcome, typeof state] => [
            { kind: "already-connected", existing },
            state,
          ],
        ),
        Match.tag(
          "UnauthenticatedConnection",
          (unauth): [TransitionOutcome, typeof state] => {
            const authed = new AgentConnection({
              connId: unauth.connId,
              socket: unauth.socket,
              originator: unauth.originator,
              auth,
            });
            return [
              { kind: "ok-agent", authed },
              {
                ...state,
                connections: HashMap.set(state.connections, connId, authed),
              },
            ];
          },
        ),
        Match.exhaustive,
      );
    });
  }
```

Implements connection manager.

### [`connectionManagerLive`](https://github.com/chughtapan/moltzap/blob/main/packages/server/src/socket/layer.ts#L19)

*Variable*

```ts theme={null}
export const connectionManagerLive = Layer.sync(
  ConnectionManagerTag,
  () => new ConnectionManager(),
)
```

Provides the connection manager live runtime value.

### [`ConnectionManagerTag`](https://github.com/chughtapan/moltzap/blob/main/packages/server/src/socket/layer.ts#L14)

*Class*

```ts theme={null}
export class ConnectionManagerTag extends Context.Tag(
  "moltzap/ConnectionManager",
)<ConnectionManagerTag, ConnectionManager>() {}
```

Implements connection manager tag.

### [`ConnectionTag`](https://github.com/chughtapan/moltzap/blob/main/packages/server/src/socket/layer.ts#L8)

*Class*

```ts theme={null}
export class ConnectionTag extends Context.Tag("moltzap/Connection")<
  ConnectionTag,
  Connection
>() {}
```

Implements connection tag.

### [`Originator`](https://github.com/chughtapan/moltzap/blob/main/packages/server/src/socket/connection.ts#L15)

*TypeAlias*

```ts theme={null}
export type Originator = ReverseClient;
```

The per-connection reverse `RpcClient&lt;ReverseRpcGroup>` the server fires
callbacks/notifications through. Constructed by protocol `MoltZapServer`
during socket accept and passed to
`ConnectionManager.addUnauthenticated` as a primitive-equivalent parameter.

### [`PrincipalBoundaryCanaries`](https://github.com/chughtapan/moltzap/blob/main/packages/server/src/socket/principal.types-check.ts#L87)

*TypeAlias*

```ts theme={null}
export type PrincipalBoundaryCanaries = [
  UnauthenticatedHasNoAuth,
  ForgedAgentRejected,
  InvalidBootPhaseRejected,
];
```

Compile-time assertions for the principal and boot-failure boundaries.

### [`principalCanaryRefs`](https://github.com/chughtapan/moltzap/blob/main/packages/server/src/socket/principal.types-check.ts#L96)

*Variable*

```ts theme={null}
export const principalCanaryRefs: readonly unknown[] = [
  agentIdValue,
  principalTag,
  narrowOutcome,
  bootFail,
] as const
```

Provides the principal canary refs runtime value.

### [`TransitionOutcome`](https://github.com/chughtapan/moltzap/blob/main/packages/server/src/socket/connection.ts#L68)

*TypeAlias*

```ts theme={null}
export type TransitionOutcome =
  | { readonly kind: "not-connected" }
```

Outcome of `ConnectionManager.authenticate`'s atomic transition. The success
arm carries the minted connection so the Connect handler's
`Match.value(outcome).pipe(Match.when({ kind: "ok-agent" }, ...))` narrows
`authed` structurally — no `as AgentConnection` cast.

### [`UnauthenticatedConnection`](https://github.com/chughtapan/moltzap/blob/main/packages/server/src/socket/connection.ts#L44)

*Interface*

```ts theme={null}
class UnauthenticatedConnection extends Data.TaggedClass(
  "UnauthenticatedConnection",
)<ConnectionBase> {
  private readonly brand!: never;
}
```

Re-exports the public API from `current module`.

### [`WebSocketRef`](https://github.com/chughtapan/moltzap/blob/main/packages/server/src/socket/connection.ts#L20)

*Interface*

```ts theme={null}
export interface WebSocketRef {
  /**
   * Write a raw frame to this connection. Fails with SocketError on send
   * failure or if the socket is already closed.
   */
  readonly write: (raw: string) => Effect.Effect<void, SocketError>;
  /** Close this connection's scope, tearing down the underlying socket. */
  readonly shutdown: Effect.Effect<void>;
}
```

The per-connection socket handle registered with `ConnectionManager`.

## Files

* `connection.ts`
* `context.ts`
* `layer.ts`
* `principal.types-check.ts`
