@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
292 lines • 17.2 kB
JavaScript
import { detachConnection } from "./connection-detach.js";
import { compactUpdatesEnabled } from "../../core/engine-socket-flag.js";
import { compactAdmissionGate, declareSocketClient } from "./compact-socket-commands.js";
import { invalidCompactAdmission, unknownCompactAdmission } from "./compact-admission-validation.js";
import { compactSubscribe } from "./compact-subscribe-admission.js";
import { withAdmissionRequest } from "./compact-admission-reply.js";
import { resetStream } from "./compact-reset-stream.js";
import { answerEffectFromTranscript } from "./effect-commands.js";
import { answerWarm } from "./host-warm.js";
import { answerRecoveryPage, answerReleaseRecovery } from "./recovery-page-command.js";
import { compactTransportDisabled } from "./compact-transport-refusal.js";
import { RPC_ERROR_MISSING_SESSION_ID } from "./rpc-types.js";
import { answerListHands, answerSelectHand } from "./hand-selection-commands.js";
import { attachSession, reclaimSession, releaseAttachment } from "./session-attachment-commands.js";
import { attachmentGate } from "./session-attachment-gate.js";
import { runWithSessionAttribution } from "./session-attribution.js";
import { dispatchSessionBinding } from "./session-held.js";
import { findSession } from "./find-session.js";
import { routeMoveSession } from "./session-move-router.js";
import { releaseSession } from "./session-release.js";
import { releaseConnection } from "./session-router-attachments.js";
import { close, tearDownUnloaded } from "./session-router-close.js";
import { code, detail, error } from "./session-router-errors.js";
import { answerListSessions, answerProtocolInfo, answerSubscriptionLimits } from "./session-router-host-reads.js";
import { acknowledgePrompt, otherRequestsSettled } from "./session-router-observation.js";
import { sweepDrain } from "./session-router-occupancy.js";
import { openWithBarrier } from "./session-router-open.js";
import { claimSession, parkSession } from "./session-router-park.js";
import { syncRetainedRecord } from "./session-router-residency.js";
import { answerSetSessionContext, answerSubscribeSessions, answerUnsubscribeSessions, notAttachedRefusal, } from "./session-status-commands.js";
import { unloadSession } from "./session-unload.js";
/**
* Every routed command runs inside its session's attribution scope, so a stall the
* loop-lag watchdog observes right after this dispatch can name the session that
* caused it - and anything the command starts inherits the attribution.
*/
export function handle(host, command) {
const malformed = invalidCompactAdmission(command);
if (malformed)
return Promise.resolve(malformed);
const ownership = unknownCompactAdmission(host, command);
if (ownership instanceof Promise)
return ownership.then((refusal) => refusal ?? admitted(host, command));
return ownership ? Promise.resolve(ownership) : admitted(host, command);
}
function admitted(host, command) {
const routed = host.routes.command(command, () => admitted(host, command));
if (routed)
return routed;
if ("sessionId" in command && command.sessionId !== undefined && host.registry.peek(command.sessionId)?.speculative)
return Promise.resolve(error(command.id, command.type, "unknown_session"));
if (command.type === "park_session")
return parkSession(host, command);
const refusal = attachmentGate(host, command) ?? compactAdmissionGate(host, command);
if (refusal)
return Promise.resolve(refusal);
// RULING-111 (LEAK-B/C): the host-side pre-declaration belongs to the compact negotiation; with the flag off a
// session-scoped declaration reaches its session exactly as on main.
if (command.type === "set_client_info" && compactUpdatesEnabled()) {
const reply = declareSocketClient(host, command);
if (!reply.success)
return Promise.resolve(reply);
const peer = host.writer.currentConnection();
if (command.capabilities !== undefined && peer !== undefined)
command = { ...command, capabilities: [...(host.pendingCapabilities.get(peer) ?? [])] };
if (command.id === undefined && command.capabilities === undefined)
return Promise.resolve(undefined);
}
const sessionId = "sessionId" in command ? command.sessionId : undefined;
// A parked handle is answered by its terminal record and connection close, never unknown_session.
if (host.draining && sessionId !== undefined && host.handoffClosed.has(sessionId))
return Promise.resolve(host.writer.currentConnection()?.startsWith("generation-route-")
? error(command.id, command.type, "generation_session_parked")
: undefined);
if (host.draining &&
command.type === "open_session" &&
!(host.writer.currentConnection()?.startsWith("generation-route-") && command.expectedHostInstance !== undefined))
return Promise.resolve(error(command.id, command.type, "host_draining"));
// A warm holds no session and no path, so it stays out of the accounting a drain waits on (senpi#2314).
if (command.type === "warm")
return answerWarm(command, {
draining: host.draining,
warm: host.registry.warm,
cwd: host.defaults.cwd,
hostContext: host.defaults.hostContext,
});
host.activeRequests.set(sessionId, (host.activeRequests.get(sessionId) ?? 0) + 1);
return withAdmissionRequest(command, host.writer.currentConnection(), () => runWithSessionAttribution({ sessionId }, () => dispatch(host, command)).finally(() => {
const remaining = (host.activeRequests.get(sessionId) ?? 1) - 1;
if (remaining > 0)
host.activeRequests.set(sessionId, remaining);
else
host.activeRequests.delete(sessionId);
if (sessionId !== undefined)
for (const listener of host.requestSettledListeners.get(sessionId) ?? [])
listener();
if (host.draining)
sweepDrain(host);
}));
}
/** Attachments held by connections other than the caller: every one of the caller's own holds is excluded. */
function otherAttachments(host, caller, sessionId) {
const own = caller === undefined ? 0 : (host.sessionsByConnection.get(caller)?.get(sessionId) ?? 0);
return Math.max(0, (host.registry.peek(sessionId)?.attachments ?? 0) - own);
}
export async function dispatch(host, command) {
if (command.type === "reset_stream" && host.admissions)
return resetStream(host, command);
if (command.type === "cancel_attempt" && host.admissions !== undefined) {
const peer = host.writer.currentConnection();
const epoch = peer === undefined ? undefined : host.writer.socketEpochOf(peer);
if (epoch === undefined)
return error(command.id, command.type, "unsupported_transport");
const outcome = await host.admissions.cancel(epoch, command.admissionId);
return { id: command.id, type: "response", command: "cancel_attempt", success: true, data: { outcome } };
}
if ((command.type === "reset_stream" || command.type === "cancel_attempt") && host.admissions === undefined)
return compactTransportDisabled(command);
if (command.type === "get_protocol_info")
return answerProtocolInfo(host, command);
if (command.type === "get_subscription_limits")
return answerSubscriptionLimits(command);
if (command.type === "list_sessions") {
if (!host.writer.currentConnection()?.startsWith("generation-route-")) {
try {
await host.routes.discover();
}
catch (cause) {
return error(command.id, command.type, code(cause));
}
}
return answerListSessions(host, command);
}
if (command.type === "list_hands")
return answerListHands(host, command);
if (command.type === "select_hand")
return answerSelectHand(host, command);
if (command.type === "detach_connection")
return detachConnection(command, host.writer.currentConnection(), (id) => releaseConnection(host, id));
if (command.type === "open_session")
return openWithBarrier(host, command);
if (command.type === "claim_session")
return claimSession(host, command);
if (command.type === "attach_session") {
const reply = await attachSession(host, command);
if (reply?.success === false &&
(reply.error === "unknown_session" || reply.error === "session_identity_mismatch"))
try {
return await host.routes.attachByIdentity(command, reply);
}
catch (cause) {
return error(command.id, command.type, code(cause));
}
return reply;
}
if (command.type === "release_attachment")
return releaseAttachment(host, command);
if (command.type === "reclaim_session")
return reclaimSession(host, command);
if (command.type === "find_session")
return findSession(
// The host's own directory when the registry carries none: a worker-runtime host runs its sessions in workers and
// still keeps the session files. Only this lookup reads it; `move_session` reads the registry's and stays refused.
{ agentDir: host.registry.agentDir ?? host.defaults.agentDir, hosted: () => host.registry.list() }, command);
if (command.type === "close_session")
return close(host, command);
if (command.type === "release_session")
return releaseSession({
draining: () => host.draining,
hostInstance: host.defaults.hostContext?.host_instance,
otherAttachments: (sessionId) => otherAttachments(host, host.writer.currentConnection(), sessionId),
lookup: (sessionId) => host.registry.getForCommand(sessionId, "release_session"),
code: (cause) => code(cause),
// The release is itself one of the session's in-flight requests.
otherRequests: (sessionId) => Math.max(0, (host.activeRequests.get(sessionId) ?? 1) - 1),
otherRequestsSettled: (sessionId) => otherRequestsSettled(host, sessionId),
pendingPrompts: (sessionId) => host.bindings.get(sessionId)?.pendingPrompts?.() ?? [],
tearDown: (sessionId, sessionPath) => host.releaseTeardown(sessionId, sessionPath),
}, command);
if (command.type === "move_session")
return routeMoveSession(host, command);
if (command.type === "unload_session") {
const caller = host.writer.currentConnection();
return unloadSession({
draining: () => host.draining,
by: { connectionId: caller ?? "host" },
lookup: (sessionId) => host.registry.getForCommand(sessionId, "unload_session"),
code: (cause) => code(cause),
// The unload is itself one of the session's in-flight requests.
otherRequests: (sessionId) => Math.max(0, (host.activeRequests.get(sessionId) ?? 1) - 1),
otherRequestsSettled: (sessionId) => otherRequestsSettled(host, sessionId),
pendingPrompts: (sessionId) => host.bindings.get(sessionId)?.pendingPrompts?.() ?? [],
otherAttachments: (sessionId) => otherAttachments(host, caller, sessionId),
openChildSessions: (durableSessionId) => host.registry
.list()
.filter((row) => row.durableSessionId !== durableSessionId &&
(row.context?.parent_session_id === durableSessionId ||
row.context?.root_session_id === durableSessionId)).length,
tearDown: (sessionId, sessionPath) => tearDownUnloaded(host, sessionId, sessionPath),
}, command);
}
if (command.type === "set_client_info" && !command.sessionId)
return command.id === undefined && compactUpdatesEnabled() ? undefined : declareSocketClient(host, command);
if (command.type === "subscribe_sessions") {
if (host.admissions && command.admissionId !== undefined)
return compactSubscribe(host, command);
const connection = host.writer.currentConnection();
const { answer, activate } = answerSubscribeSessions(command, connection, host.writer.status);
// On a socket host the response is enqueued HERE, ahead of activation: a delta published
// while this dispatch awaited the route queues behind the snapshot it belongs after.
if (activate !== undefined && connection !== undefined) {
const enqueue = async () => {
// Two hops: the response must be enqueued onto the actor's FIFO before the
// subscription goes live, so a delta published between registration and here
// always lands behind the snapshot answer it follows.
await host.writer.enqueueControl(answer, connection);
await new Promise((resolve) => queueMicrotask(resolve));
try {
// A connection that closed while this subscribe awaited dispatch already ran dropConnection,
// before this pending entry existed; drop it here or it holds deltas for the life of the host.
if (host.writer.hasConnection(connection))
host.writer.status.activate(activate);
else
host.writer.status.unsubscribe(connection, activate);
}
catch (cause) {
process.stderr.write(`senpi rpc subscription activation failed: ${String(cause)}\n`);
}
};
void enqueue().catch((cause) => {
host.writer.status.unsubscribe(connection, activate);
process.stderr.write(`senpi rpc subscribe answer could not be delivered: ${String(cause)}\n`);
});
return undefined;
}
return answer;
}
if (command.type === "unsubscribe_sessions") {
const peer = host.writer.currentConnection();
const answer = answerUnsubscribeSessions(command, peer, host.writer.status);
if (answer.success && peer !== undefined)
host.writer.unregisterSubscription(peer, command.subscriptionId);
return answer;
}
// A receipt of a session this host has not loaded is read from its transcript, never by loading it.
if (command.type === "get_effect_status" && !command.sessionId && command.sessionPath !== undefined)
return answerEffectFromTranscript(command.id, command.sessionPath, command.effectId);
// The token owner's page route (S11b): host-level, before any session or worker forwarding; absent with the flag off.
if (command.type === "get_recovery_page" && host.writer.recoveryPages !== undefined)
return answerRecoveryPage(host.writer.recoveryPages, host.writer, command);
if (command.type === "release_recovery" && host.writer.recoveryEvents !== undefined)
return answerReleaseRecovery(host.writer.recoveryEvents, host.writer, command);
if (command.type === "get_recovery_page" || command.type === "release_recovery")
return compactTransportDisabled(command);
if (!command.sessionId)
return error(command.id, command.type, RPC_ERROR_MISSING_SESSION_ID);
const sessionId = command.sessionId;
if (host.writer.isSessionSealed(sessionId) && host.registry.peek(sessionId)?.state === "open")
return error(command.id, command.type, "session_output_overflow", {
sessionId,
action: "unload_and_reopen",
});
if (command.type === "set_session_context")
return setSessionContext(host, command);
try {
const entry = host.registry.getForCommand(sessionId, command.type);
await dispatchSessionBinding(command, entry, host.bindings.get(sessionId), () => acknowledgePrompt(host, command.id, sessionId), (observedStarts) => host.registry.holderPids?.(observedStarts) ?? Promise.resolve([]));
return undefined;
}
catch (cause) {
return error(command.id, command.type, code(cause), detail(cause));
}
}
/** Any attached connection may patch; a host with no per-connection identity (stdio) owns every session. */
export function setSessionContext(host, command) {
const owner = host.writer.currentConnection();
if (owner !== undefined && host.sessionsByConnection.get(owner)?.has(command.sessionId) !== true)
return notAttachedRefusal(command);
try {
const entry = host.registry.getForCommand(command.sessionId, command.type);
const answered = answerSetSessionContext(command, entry, host.writer.status);
// The record carries the overlay a restart reopens the session with (a terminal task_status
// is not reopened at all), so it follows each accepted patch.
if (answered.success)
void syncRetainedRecord(host, command.sessionId, undefined);
return answered;
}
catch (cause) {
return error(command.id, command.type, code(cause), detail(cause));
}
}
//# sourceMappingURL=session-router-routing.js.map