@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
263 lines • 15.2 kB
JavaScript
import { stat } from "node:fs/promises";
import { RETRY_ROUTED_OPEN } from "./predecessor-routes.js";
import { compactUpdatesEnabled } from "../../core/engine-socket-flag.js";
import { startOpenTimer } from "../../core/open-timing.js";
import { compactOpen } from "./compact-open-admission.js";
import { CompactAdmissionError } from "./compact-admission-error.js";
import { runAdmissionProducer } from "./compact-admission-producer.js";
import { parkedOpenCommand } from "./host-handover-parked-open.js";
import { sessionHeldCheck } from "./session-held.js";
import { forgetSessionOwnership, releaseOwnedSession, releaseOwnerAttachment } from "./session-router-attachments.js";
import { close } from "./session-router-close.js";
import { code, detail, error } from "./session-router-errors.js";
import { sweepDrain } from "./session-router-occupancy.js";
import { openSessionFolder } from "./open-session-folder.js";
import { invalidSpawnedBy, validatedOpenProfile } from "./session-router-open-profile.js";
import { holdOpenConnection, ownOpen, publishOpen, replyOpen } from "./session-router-open-result.js";
import { closePark } from "./session-router-park.js";
import { relocationConnection } from "./session-router-relocation.js";
import { syncRetainedRecord } from "./session-router-residency.js";
import { liveToolMediaScope, toolMediaPersister } from "./tool-media-store.js";
export function openWithBarrier(host, command, replyAs) {
if (compactUpdatesEnabled() && command.admissionId !== undefined)
return compactOpen(host, command, (accept, signal) => openPhysicalWithBarrier(host, command, accept, signal));
return openPhysicalWithBarrier(host, command, undefined, undefined, replyAs);
}
function openPhysicalWithBarrier(host, command, accept, signal, replyAs) {
const owner = host.writer.currentConnection();
if (owner === undefined)
return open(host, command, undefined, { replyAs });
// Every open already accepted anywhere on this host, not just on this connection: the
// in-process runtime serves them on ONE loop, so the wait this caller faces is the total.
let inFlight = 0;
for (const pending of host.opensByConnection.values())
inFlight += pending.size;
const releaseBarrier = holdOpenConnection(host, owner);
// Before the open reaches the loop: a client that later hits its deadline can then say
// where it was queued instead of reporting a bare timeout (senpi#1844).
if (command.id !== undefined)
host.writer.sendOpenQueued(owner, {
type: "queued",
for_request: command.id,
position: inFlight + 1,
in_flight: inFlight,
});
const start = () => open(host, command, owner, accept === undefined ? { replyAs } : { accept, signal });
// A late open's physical session is released by its admission (the accept/rollback path, 4272-admission-
// abandonment), so the late response itself owns nothing to release here.
const opened = signal === undefined ? start() : runAdmissionProducer(signal, start, async () => { });
return opened.finally(releaseBarrier);
}
/**
* The successor's reopen of a handoff-parked session: the same open as an `open_session`, with no
* requesting connection and nothing to reply to (senpi#3368). Resolves `undefined` on success and
* the failure response otherwise, exactly as an open does. A session that was live when its host ended
* continues as that host left it (senpi#7020); any other park reopens unattended, holding automatic turns.
*/
export function reopenParked(host, entry) {
const command = parkedOpenCommand(entry);
return open(host, entry.live === true ? command : { ...command, attended: false }, undefined, {
reply: false,
defaults: false,
contextOverlay: entry.contextOverlay,
unattached: true,
...(entry.live === true ? { continued: true } : {}),
});
}
export async function open(host, command, owner, options) {
const validated = validatedOpenProfile(host, command, options);
if ("type" in validated)
return validated;
let opened;
const timer = startOpenTimer(`host-open:${command.id ?? "-"}`);
const assertSessionNotHeld = sessionHeldCheck((observedStarts) => host.registry.holderPids?.(observedStarts) ?? Promise.resolve([]));
try {
// An open that names no folder resumes a session file where its header says, not where this host runs
// (senpi#6427). Inside the try: a file it cannot read refuses the open, and that refusal is this open's answer.
const profile = {
...validated,
cwd: await openSessionFolder(command, validated.cwd),
...(options?.continued === true ? { continued: true } : {}),
};
// A folder that exists but is a file (or a socket) is refused, typed, before anything is opened or created. A missing
// folder, or one this host cannot stat, keeps today's answer from the registry.
if ((await stat(profile.cwd).catch(() => undefined))?.isDirectory() === false)
return error(command.id, "open_session", "session_cwd_not_directory", { cwd: profile.cwd });
await assertSessionNotHeld(command.sessionPath);
timer.mark("held_check");
options?.signal?.throwIfAborted();
if (invalidSpawnedBy(command))
return error(command.id, "open_session", "invalid_spawned_by");
const ancestry = command.spawnedBy;
opened = await host.registry.openSession(ancestry ? { ...profile, spawnedBy: ancestry } : profile,
// Host lifecycle policy, deliberately outside the immutable launch profile.
{
routedHandle: host.routes.handleFor(command.sessionPath),
retainOnDisconnect: command.retain_on_disconnect === true,
attachOnly: command.expectedHostInstance !== undefined,
...(options?.park ? { speculative: true } : {}),
// The successor's restore has no requesting connection to own an attachment (senpi#7020).
...(options?.unattached === true ? { unattached: true } : {}),
});
timer.mark("registry_open");
options?.signal?.throwIfAborted();
const openedSession = opened;
if (host.writer.isSessionSealed(openedSession.sessionId)) {
// Lost output cannot be replayed. Undo only this attachment; keep the runtime and
// seal intact until an explicit unload safely parks it for a fresh open by path.
await releaseOwnedSession(host, openedSession.sessionId);
opened = undefined;
return error(command.id, "open_session", "session_output_overflow", {
sessionId: openedSession.sessionId,
sessionPath: openedSession.sessionPath,
action: "unload_and_reopen",
});
}
const entry = host.registry.getForCommand(openedSession.sessionId, "open_session");
if (!opened.attached && options?.contextOverlay !== undefined)
entry.contextOverlay = options.contextOverlay;
const state = entry.worker?.snapshot?.state;
// The runtime has now published its own lease. Recheck before attaching or replying,
// so an opener racing the initial lookup is rolled back rather than admitted.
await assertSessionNotHeld(entry.runtime?.session.sessionFile ?? state?.sessionFile ?? entry.sessionPath, entry.runtime?.session.sessionId ?? state?.sessionId ?? entry.durableSessionId);
timer.mark("held_recheck");
host.writer.setSessionKind(openedSession.sessionId, entry.kind);
host.writer.setSessionMedia(openedSession.sessionId, toolMediaPersister(() => liveToolMediaScope(entry)));
// The lane is bootstrapped before admission (R3.C1.1); the fanout knows it before the opener's attach freezes a cut,
// so a lane-owned session's baseline is never read from the replay store (RULING-52).
const lane = entry.acceptance ?? entry.worker?.acceptance;
if (lane)
host.writer.registerAcceptance(openedSession.sessionId, lane);
if (options?.accept)
await options.accept(openedSession);
ownOpen(host, openedSession, owner, options?.accept !== undefined);
if (!host.bindings.has(openedSession.sessionId)) {
host.bindings.set(openedSession.sessionId, await host.createBinding(openedSession.sessionId, entry, host.writer, () => void (entry.speculative
? closePark(host, openedSession)
: close(host, { type: "close_session", sessionId: openedSession.sessionId })), {
...host.connectionOptions,
capabilities: owner !== undefined
? (host.pendingCapabilities.get(owner) ?? host.connectionOptions?.capabilities ?? [])
: host.connectionOptions?.capabilities,
connectionRoles: host.connectionRoles,
clientInfo: {
setCapabilities: (connectionId, capabilities) => {
if (connectionId !== undefined) {
host.writer.setConnectionCapabilities(connectionId, capabilities);
host.pendingCapabilities.set(connectionId, [...capabilities]);
}
},
connectionId: () => host.writer.currentConnection(),
relocationConnection: () => relocationConnection(host, openedSession.sessionId),
deliverTo: (connection, deliver) => host.writer.withConnection(connection, deliver),
},
}));
timer.mark("binding");
if (entry.worker)
entry.worker.bindingReady = true;
// Wake the drain sweep the moment a session settles, so a handoff parks it
// without waiting for the next timer tick. Both hooks are OPTIONAL: an
// embedder's runtime and the suite's fakes implement the session surface
// they need and nothing more, and an open must never fail because a
// settle notification is unavailable - the periodic sweep still parks it.
const settled = () => {
if (host.draining)
queueMicrotask(() => sweepDrain(host));
};
if (typeof entry.worker?.subscribeSettled === "function")
entry.worker.subscribeSettled(settled);
else if (typeof entry.runtime?.session.subscribe === "function")
entry.runtime.session.subscribe((event) => {
// agent_idle, not agent_settled: settle-time extension handlers may still be writing (omo#11419).
if (event.type === "agent_idle")
settled();
});
if (entry.worker)
void entry.worker.exited.then(async () => {
await host.finalizations.get(openedSession.sessionId)?.promise;
host.bindings.delete(openedSession.sessionId);
forgetSessionOwnership(host, openedSession.sessionId);
host.writer.forgetSession(openedSession.sessionId);
});
}
options?.signal?.throwIfAborted();
if (options?.park) {
options.park(openedSession);
return undefined;
}
publishOpen(host, openedSession, entry);
host.routes.adopt(openedSession.sessionId);
if (!options?.accept && !host.draining && owner !== undefined && host.releasedConnections.has(owner)) {
releaseOwnerAttachment(host, owner, openedSession.sessionId);
await releaseOwnedSession(host, openedSession.sessionId);
}
// After the open SUCCEEDS (MEDIUM-A): a failed open keeps any record entry, so a later start
// still reopens that session.
await syncRetainedRecord(host, openedSession.sessionId, command.sessionPath);
if (options?.accept) {
return undefined;
}
timer.mark("reply");
replyOpen(host, opened, entry, options?.replyAs?.command ?? command, options?.reply !== false, options?.replyAs?.data);
return undefined;
}
catch (cause) {
if (opened) {
// Only a non-attached open published session_opened and an open status before this
// rollback, and only while the registry still holds the live entry, so only that
// rollback owes its subscribers the terminal record; an attach rollback, or one whose
// entry is already gone, never announced the session in the first place (#3198 review, L1).
if (!options?.park && !opened.attached && !options?.signal?.aborted) {
const entry = host.registry.peek(opened.sessionId);
if (entry?.runtime !== undefined || entry?.worker !== undefined)
host.writer.sealRolledBackOpen(opened.sessionId, entry.sessionPath);
}
try {
if (opened.attached)
await releaseOwnedSession(host, opened.sessionId);
else
await host.registry.close(opened.sessionId);
}
catch {
/* The open rollback has already removed the entry. */
}
if (!opened.attached || !compactUpdatesEnabled())
host.writer.forgetSession(opened.sessionId);
}
if (cause instanceof CompactAdmissionError)
throw cause;
if (!opened &&
owner &&
command.expectedHostInstance &&
!host.draining &&
!options?.accept &&
code(cause) === "session_not_held" &&
!owner.startsWith("generation-route-")) {
const attached = await host.routes.attachPath(command, owner);
if (attached)
return attached;
}
if (!opened &&
owner &&
!host.draining &&
!options?.park &&
!options?.accept &&
code(cause) === "session_path_in_use") {
const routed = await host.routes.open(command, owner, detail(cause));
if (routed === RETRY_ROUTED_OPEN && host.writer.hasConnection(owner) && !host.draining) {
// The handover between generations is bounded like a close: past the grace window the caller gets the
// retryable refusal instead of an open that never answers.
const routedSince = options?.routedSince ?? Date.now();
if (Date.now() - routedSince <= host.registry.closeGraceMs)
return open(host, command, owner, { ...options, routedSince });
return error(command.id, "open_session", code(cause), detail(cause));
}
if (routed === RETRY_ROUTED_OPEN)
return error(command.id, command.type, "host_draining");
if (routed)
return routed;
}
return error(command.id, "open_session", code(cause), detail(cause));
}
}
//# sourceMappingURL=session-router-open.js.map