@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
233 lines • 11.2 kB
JavaScript
import { COMPACT_EVENTS_CAPABILITY } from "./custom-capability.js";
import { ConnectionDelegations } from "./delegated-connection.js";
import { serializeJsonLine } from "./jsonl.js";
import { acceptActors, SessionEventWriterLanes, settleActors } from "./session-event-writer-lanes.js";
import { closeSocket } from "./socket-closing.js";
/** Connection registration, capabilities, security presentations and per-session delivery settings. */
export class SessionEventWriterConnections extends SessionEventWriterLanes {
constructor() {
super(...arguments);
/** Which connections act for someone else, and what they were granted (senpi#5632). */
this.delegations = new ConnectionDelegations();
}
delegationDescriptorOf(id) {
return this.delegations.descriptorOf(id);
}
isRemoteConnection(connection) {
return this.delegations.isDelegated(connection) || this.originOf?.(connection) !== undefined;
}
isTargetedRecord(record) {
return (record.type === "response" ||
record.type === "bash_execution_update" ||
// Relocation records belong to the one connection that offers it (session-relocation-channel.ts).
record.type === "host_request" ||
record.type === "relocation_due" ||
(record.type === "extension_ui_request" &&
record.audience !== "session" &&
["select", "confirm", "input", "editor"].includes(String(record.method))));
}
isSessionSealed(sessionId) {
return this.sealedSessions.has(sessionId);
}
registerConnection(id, connection, options = {}) {
this.delegations.admit(id, options.launchProof);
const previousPresenter = this.presenterConnections.get(id);
if (previousPresenter)
this.presenterAuthority?.detach(previousPresenter);
this.fanout.registerConnection(id, connection, options);
if (this.presenterAuthority) {
const sender = this.presenterAuthority.connect(id, (frame) => {
if (!this.fanout.get(id))
return false;
try {
connection.writeRaw(serializeJsonLine(frame));
// A pending drain does not undo an accepted write or drop the next resolution.
void connection.waitForBackpressure().catch(() => this.presenterAuthority?.detach(sender));
return true;
}
catch {
this.presenterAuthority?.detach(sender);
return false;
}
});
this.presenterConnections.set(id, sender);
}
}
unregisterConnection(id) {
this.delegations.close(id);
this.secretPresentations.detach(id);
const sender = this.presenterConnections.get(id);
if (sender)
this.presenterAuthority?.detach(sender);
this.presenterConnections.delete(id);
this.securityPresentations.dropConnection(id);
this.fanout.unregisterConnection(id);
this.status.dropConnection(id);
this.surfaceDedupe.dropConnection(id);
}
attachConnectionToSession(id, sessionId, compact = false) {
this.fanout.attachConnectionToSession(id, sessionId, compact);
if (this.hasConnection(id))
this.securityPresentations.attach(id, sessionId);
const sender = this.presenterConnections.get(id);
const binding = this.presenterBindings.get(sessionId);
if (sender && binding)
this.presenterAuthority?.attach(sender, binding);
}
detachConnectionFromSession(id, sessionId) {
const sender = this.presenterConnections.get(id);
const binding = this.presenterBindings.get(sessionId);
if (sender && binding)
this.presenterAuthority?.detach(sender, binding);
this.fanout.detachConnectionFromSession(id, sessionId);
this.secretPresentations.recheck();
this.securityPresentations.detach(id, sessionId);
}
hasConnection(id) {
return this.fanout.get(id) !== undefined;
}
setConnectionCapabilities(id, capabilities) {
this.fanout.setConnectionCapabilities(id, capabilities);
this.secretPresentations.recheck();
this.securityPresentations.capabilitiesChanged(id);
if (!capabilities.includes("interactive_user") || !capabilities.includes("mcp_form_presenter_v1")) {
const sender = this.presenterConnections.get(id);
if (sender)
this.presenterAuthority?.withdraw(sender);
}
}
clearConnectionCapabilities(id) {
const sender = this.presenterConnections.get(id);
if (sender)
this.presenterAuthority?.withdraw(sender);
this.fanout.clearConnectionCapabilities(id);
this.secretPresentations.recheck();
this.securityPresentations.capabilitiesChanged(id);
}
bindSecurityPresentations(sessionId, durableId, notices, ui) {
if (this.fanout.isEmpty())
return undefined;
return this.securityPresentations.bind(sessionId, durableId, notices, ui.select);
}
acceptWorkerSecuritySnapshot(sessionId, snapshot) {
this.securityPresentations.acceptSnapshot(sessionId, snapshot);
}
routeWorkerGrant(sessionId, requestId, preferred, capabilities, cancel, title) {
return this.securityPresentations.routeWorkerGrant(sessionId, requestId, preferred, capabilities, cancel, title);
}
/** An in-process grant select is presented on the connection in context; the others see its notice. */
noticeGrantDialog(sessionId, id, title) {
this.securityPresentations.noticeGrant(sessionId, id, title, this.currentConnection());
}
acceptWorkerGrantResponse(sessionId, id, connection) {
return this.securityPresentations.acceptWorkerResponse(sessionId, id, connection);
}
settleGrantDialog(sessionId, id) {
this.securityPresentations.settleGrant(sessionId, id);
}
hasRegisteredConnectionCapabilities(id) {
return this.fanout.hasRegisteredConnectionCapabilities(id);
}
compactSelection(id) {
return this.fanout.get(id)?.selection;
}
getConnectionCapabilities(id) {
return this.fanout.getConnectionCapabilities(id);
}
/**
* Records a session's visibility class. A worker session is machine-driven work that
* only its attached connections track, so its lifecycle records are delivered to them
* instead of broadcast; an interactive session keeps the broadcast every client (the
* desktop mirror, the supervisor's idle observer) relies on.
*/
setSessionMedia(sessionId, persister) {
if (persister === undefined)
this.mediaPersisters.delete(sessionId);
else
this.mediaPersisters.set(sessionId, persister);
}
/** A worker isolate frames a canonical-only unit; an in-process host folds block controls in its own lane. */
enqueueCanonical(_sessionId, _control) { }
/** A worker isolate reports a lost canonical record to its host lane; an in-process binding tells its lane directly. */
canonicalUnavailable(_sessionId, _cause) { }
/** The session's records reach `lane` before `enqueue`; sealing or forgetting the session retires it. */
registerAcceptance(sessionId, lane) {
if (!this.sealedSessions.has(sessionId))
this.fanout.acceptance.set(sessionId, lane);
if (this.fanout.events)
lane.beforeAccept = (record) => this.prepareDelivery(sessionId, record);
}
setSessionKind(sessionId, kind) {
if (kind === "worker")
this.workerSessions.add(sessionId);
else
this.workerSessions.delete(sessionId);
}
/**
* RULING-124: the host's own close of connection `id` (shutdown, handoff). A peer that selected compact events receives
* `socket_closing` first and `close(true)` must then flush before it closes; every other peer gets `close(false)` at
* once, exactly as before.
*/
closeConnection(id, code, close) {
const registered = this.fanout.get(id);
const compact = registered !== undefined && this.fanout.connectionHas(id, COMPACT_EVENTS_CAPABILITY);
if (registered === undefined) {
close(false);
return Promise.resolve();
}
return closeSocket({ ...registered.connection, close: () => close(compact) }, registered.actor, compact, code);
}
/** Drain just this connection before closing it after its last handoff park. */
async flushConnection(id) {
const target = this.fanout.get(id);
if (target)
await settleActors([target.actor]);
}
/**
* omo-relay-daemon#307: a socket whose incarnations ran out is ended once its `detach_connection` answer is flushed
* (engine_closed). `sinkOf` is the sink the socket host registered under that connection id; its `close` half-closes,
* so the answer still buffered in the transport reaches a peer that reads late, instead of a destroy discarding it.
*/
endExhaustedConnections(sinkOf) {
this.delegations.endConnection = (id) => {
const sink = sinkOf(id);
if (sink)
void this.flushConnection(id).finally(() => sink.close?.());
};
}
/** Execute a connection's command with its response destination in context. */
withConnection(id, task) {
return this.connectionContext.run(id, task);
}
/** Connection id of the command currently being dispatched, when one owns it. */
currentConnection() {
return this.connectionContext.getStore();
}
/**
* Return worker credit once this session's destinations have ACCEPTED the record
* into their bounded queues - never when the slowest peer's kernel has drained it.
* A client that is merely busy would otherwise pace the producing worker into
* session_worker_credit_timeout and force the dead-peer budget under
* SESSION_WORKER_LIMITS.controlMs (#1774). Delivery stays bounded by each queue's
* maxQueueBytes and its dead-peer cut. A destination that failed (byte overflow or
* stall) was already cut and closed by the fanout's onFailure; it is a cut peer,
* not a writer failure. The shared stdio lane keeps its stdout backpressure wait.
*/
waitForSessionBackpressure(sessionId) {
if (this.fanout.isEmpty())
return this.flush();
return acceptActors(this.sessionActors(sessionId));
}
/** Registered actors this session's records are delivered to, plus the caller's own. */
sessionActors(sessionId) {
const targets = new Set([
...this.fanout.targets(sessionId, this.currentConnection(), false, undefined),
this.currentConnection(),
]);
return [...targets].flatMap((target) => {
const registered = target === undefined ? undefined : this.fanout.get(target);
return registered ? [registered.actor] : [];
});
}
}
//# sourceMappingURL=session-event-writer-connections.js.map