@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
260 lines • 14 kB
JavaScript
import { compactUpdatesEnabled } from "../../core/engine-socket-flag.js";
import { CompactSelection } from "./compact-negotiation.js";
import { AdmissionRoutingActor } from "./compact-admission-routing.js";
import { tmpdir } from "node:os";
import { startRecoveryCleanup } from "./compact-recovery-cleanup.js";
import { EventLeases } from "./compact-event-leases.js";
import { legacyAttachView } from "./compact-legacy-view.js";
import { RecoveryPageRequests } from "./compact-recovery-requests.js";
import { RecoveryCheckpoints } from "./compact-recovery-state.js";
import { COMPACT_EVENTS_CAPABILITY, MEDIA_PLACEHOLDERS_CAPABILITY } from "./custom-capability.js";
import { ExtensionTransportOwner } from "./extension-owner.js";
import { LegacyReplayStore } from "./legacy-replay-store.js";
import { transportOf, } from "./session-event-connection.js";
import { admissionOf, SessionRecoveryPins } from "./session-recovery-pins.js";
import { closeSocket, queueFailureDetail } from "./socket-closing.js";
import { SocketEventSinkActor } from "./socket-event-fanout.js";
import { EVENT_RESYNC_CAPABILITY } from "./socket-peer-recovery.js";
const BROADCAST_LIFECYCLE_RECORDS = new Set([
"agent_start",
"agent_settled",
"agent_idle",
"session_opened",
"session_closed",
"session_lifecycle",
]);
export class SessionEventFanout {
constructor() {
this.startupCleanup = compactUpdatesEnabled() ? startRecoveryCleanup(tmpdir()) : undefined;
/** Each routing session's acceptance lane; retired when the session is sealed or forgotten. */
this.acceptance = new Map();
/** Today's retention for a session without a lane (RULING-25 Q5), and the open-view count of both sources. */
this.replay = new LegacyReplayStore();
/** The checkpoint tokens this host froze for its peers' baselines and recoveries (S08a). */
this.checkpoints = new RecoveryCheckpoints();
/** The ordinary-event leases of peers that selected compact events (S13); absent with the flag off. */
this.events = compactUpdatesEnabled() ? new EventLeases() : undefined;
/** The page route over those tokens and leases (S11b, S13); absent with the flag off, so it answers as before. */
this.pages = compactUpdatesEnabled()
? new RecoveryPageRequests(this.checkpoints, undefined, this.events)
: undefined;
this.socketEpochs = 0;
/** Today's shed path with the compact-updates flag off; the cut frozen at the shed with it on. */
this.shedMode = compactUpdatesEnabled() ? "capture" : "drop";
this.connections = new Map();
this.connectionCapabilities = new Map();
/** Per connection, each attached session with the ordinal of the attach that holds it. */
this.connectionSessions = new Map();
this.attachOrdinal = 0;
/** Roots an attach baseline still reads; a seal keeps them readable until that view ends (RULING-51 Q2=A). */
this.attachViews = new Set();
this.registeredCapabilityConnections = new Set();
this.pins = new SessionRecoveryPins(this.acceptance, this.checkpoints, this.replay, {
socketEpoch: (id) => this.connections.get(id)?.socketEpoch,
ordinals: (id) => this.connectionSessions.get(id),
required: (id) => this.requiredSessions?.(id) ?? [],
has: (id, capability) => this.connectionHas(id, capability),
}, this.shedMode);
}
registerConnection(id, connection, options = {}) {
this.unregisterConnection(id);
const owner = new ExtensionTransportOwner();
const socketEpoch = `socket-${++this.socketEpochs}`;
const Actor = this.pages ? AdmissionRoutingActor : SocketEventSinkActor;
const actor = new Actor(connection, (cause) => {
const current = this.connections.get(id)?.actor === actor;
const compact = current && this.connectionHas(id, COMPACT_EVENTS_CAPABILITY);
if (current) {
owner.retire();
this.connections.delete(id);
this.connectionCapabilities.delete(id);
this.connectionSessions.delete(id);
this.registeredCapabilityConnections.delete(id);
this.pages?.forgetPeer(socketEpoch);
this.checkpoints.forgetPeer(socketEpoch);
this.events?.forgetPeer(socketEpoch);
this.onConnectionClosed?.(id);
}
process.stderr.write(`senpi rpc connection ${id} event queue failed; closing: ${cause instanceof Error ? cause.message : String(cause)}\n`);
void closeSocket(connection, actor, compact, "event_queue_failed", queueFailureDetail(cause));
}, options.maxQueueBytes, options.stallMs, this.shedMode);
if (actor instanceof AdmissionRoutingActor)
actor.bind(this.checkpoints, socketEpoch, id);
const close = (code, detail) => void closeSocket(connection, actor, this.connectionHas(id, COMPACT_EVENTS_CAPABILITY), code, detail);
const selection = new CompactSelection();
this.connections.set(id, { connection: transportOf(connection), actor, socketEpoch, owner, selection, close });
this.connectionCapabilities.set(id, new Set());
this.connectionSessions.set(id, new Map());
}
unregisterConnection(id) {
const registered = this.connections.get(id);
if (!registered)
return;
registered.owner.retire();
registered.actor.close();
this.pages?.forgetPeer(registered.socketEpoch);
this.checkpoints.forgetPeer(registered.socketEpoch);
this.events?.forgetPeer(registered.socketEpoch);
this.connections.delete(id);
this.connectionCapabilities.delete(id);
this.connectionSessions.delete(id);
this.registeredCapabilityConnections.delete(id);
}
/**
* A first attach is one admission: it freezes the cut C synchronously as that admission's checkpoint (the lane
* root, read later for the baseline; today's replay view for a session without a lane) and installs that peer's
* baseline barrier before the session is live for it; a repeated hold adds nothing. The attempt dies with a
* detach, the peer, or a replacement (new lane epoch), and releases its checkpoint in every case.
*/
attachConnectionToSession(id, sessionId, compact = false) {
const registered = this.connections.get(id);
if (!registered)
return;
const sessions = this.connectionSessions.get(id) ?? new Map();
if (sessions.has(sessionId))
return;
const ordinal = ++this.attachOrdinal;
sessions.set(sessionId, ordinal);
this.connectionSessions.set(id, sessions);
if (compact)
return;
const pinned = this.pins.pin(id, [sessionId]);
const first = pinned[0];
const source = first?.outcome.ok ? first.outcome.value : undefined;
if (source)
this.attachViews.add(source.root);
const release = () => {
if (source)
this.attachViews.delete(source.root);
this.pins.unpin(pinned);
};
const view = { placeholders: this.connectionHas(id, MEDIA_PLACEHOLDERS_CAPABILITY), now: Date.now() };
const cursor = this.acceptance.has(sessionId)
? legacyAttachView(sessionId, source, view, this.replay.track(release))
: this.replay.freezeAttach(sessionId, { ...view, onRelease: release });
// Live while the same attach holds the session and every pinned lane is still the incarnation it was pinned at.
registered.actor.installBaseline(cursor, () => this.connections.get(id)?.actor === registered.actor &&
this.connectionSessions.get(id)?.get(sessionId) === ordinal &&
pinned.every(({ lane, sessionEpoch }) => lane.sessionEpoch === sessionEpoch));
}
detachConnectionFromSession(id, sessionId) {
this.pins.retire(id, sessionId);
this.connectionSessions.get(id)?.delete(sessionId);
}
setConnectionCapabilities(id, capabilities) {
const registered = this.connections.get(id);
if (!registered)
return;
// RULING-81 Q-B: the compact-events opt-in is accepted only behind the engine-socket flag.
const accepted = registered.selection.wireCapabilities(capabilities, this.events !== undefined);
this.connectionCapabilities.set(id, new Set(accepted));
this.registeredCapabilityConnections.add(id);
if (capabilities.includes(EVENT_RESYNC_CAPABILITY))
registered.actor.enableRecovery((reason, carried) => this.pins.resync(id, reason, carried));
else
registered.actor.disableRecovery();
}
clearConnectionCapabilities(id) {
if (this.connections.has(id)) {
this.connectionCapabilities.set(id, new Set());
this.registeredCapabilityConnections.delete(id);
}
}
hasRegisteredConnectionCapabilities(id) {
return this.registeredCapabilityConnections.has(id);
}
getConnectionCapabilities(id) {
if (!this.registeredCapabilityConnections.has(id))
return undefined;
return [...(this.connectionCapabilities.get(id) ?? [])];
}
/** Whether a connection advertised a capability. The only capability lookup in this file. */
connectionHas(id, capability) {
return id === undefined ? false : (this.connectionCapabilities.get(id)?.has(capability) ?? false);
}
targets(sessionId, targetId, isTargeted, recordType) {
if (isTargeted)
return [targetId];
if (typeof recordType === "string" && BROADCAST_LIFECYCLE_RECORDS.has(recordType))
return this.connections.size > 0 ? [...this.connections.keys()] : [undefined];
return this.connections.size > 0
? [...this.connections.keys()].filter((id) => this.connectionSessions.get(id)?.has(sessionId))
: [undefined];
}
/** For a record that reaches `id` because it holds `sessionId`: whether that attachment still does; undefined for every other audience. */
attachmentOf(id, sessionId, isTargeted, recordType) {
if (isTargeted || (typeof recordType === "string" && BROADCAST_LIFECYCLE_RECORDS.has(recordType)))
return undefined;
return this.attachment(id, sessionId);
}
/** The admission (the attach ordinal) through which `id` holds `sessionId` now; undefined when it does not. */
admissionOf(id, sessionId) {
const ordinal = this.connectionSessions.get(id)?.get(sessionId);
return ordinal === undefined ? undefined : admissionOf(ordinal);
}
get(id) {
return this.connections.get(id);
}
values() {
return this.connections.values();
}
/** True when no socket connection is registered, i.e. records must fall back to the stdio lane. */
isEmpty() {
return this.connections.size === 0;
}
broadcast(line) {
for (const { actor } of this.connections.values())
actor.enqueue(line);
}
connectionIds() {
return [...this.connections.keys()];
}
attachedConnections(sessionId) {
return [...this.connections.keys()].filter((id) => this.connectionSessions.get(id)?.has(sessionId));
}
/**
* Pending `question` frames a session has asked and nobody answered yet: the lane's hot count, today's count for a
* session without a lane, and undefined (unknown) for a lane whose compact state is unavailable. The unknown count
* is output-equivalent to the old 0: `liveStatus` reads it as `?? 0`, so the runtime's own count decides.
*/
pendingQuestionCount(sessionId) {
const lane = this.acceptance.get(sessionId);
return lane ? lane.openBroadcastDialogs : this.replay.pendingQuestionCount(sessionId);
}
/** Deliver one line to the connections attached to a session, never to the rest of the fanout. */
deliverToSession(sessionId, line) {
for (const [id, { actor }] of this.connections) {
const held = this.attachment(id, sessionId);
if (held || this.requiredSessions?.(id).includes(sessionId))
actor.enqueue(line, undefined, undefined, undefined, false, held);
}
}
/** Retention only for a session without a lane; a lane-owned session's late peers read its frozen view. */
rememberSnapshot(sessionId, value, line, placeholderLine) {
if (!this.acceptance.has(sessionId))
this.replay.remember(sessionId, value, line, placeholderLine);
}
/**
* A seal or forget ends the routing session for good (its handle is never reissued or re-attached): the lane retires
* (a queued attach view keeps its root) and the session's stream records go on every peer (RULING-56 (2)).
*/
forgetSession(sessionId) {
this.onSessionForgotten?.(sessionId);
for (const { actor, socketEpoch } of this.connections.values())
if (actor instanceof AdmissionRoutingActor)
actor.remember(sessionId, this.checkpoints, socketEpoch);
this.checkpoints.forgetSession(sessionId);
this.acceptance.get(sessionId)?.retire("close", this.attachViews);
this.acceptance.delete(sessionId);
this.replay.forget(sessionId);
}
/**
* The attach holding `sessionId` for `id` now, as a liveness check: true only while that same attach (its ordinal,
* the rule an attach baseline's liveness uses) still holds it, so a detach and re-attach ends it.
*/
attachment(id, sessionId) {
const ordinal = this.connectionSessions.get(id)?.get(sessionId);
return ordinal === undefined ? undefined : () => this.connectionSessions.get(id)?.get(sessionId) === ordinal;
}
}
//# sourceMappingURL=session-event-fanout.js.map