UNPKG

@code-yeongyu/senpi

Version:

Coding agent CLI with read, bash, edit, write tools and session management

76 lines • 3.25 kB
import { releaseDisconnectAttachment, releaseOwnerAttachment } from "./session-router-attachments.js"; import { code, detail, error } from "./session-router-errors.js"; function afterCommitRefusal(host, command, owner) { if (host.draining || host.drainExitRequested) return error(command.id, command.type, "session_busy_lifecycle", { reason: "host_draining" }); if (!host.writer.hasConnection(owner) || host.releasedConnections.has(owner)) return error(command.id, command.type, "session_not_attached", { reason: "no_connection" }); if (host.registry.peek(command.sessionId)?.state !== "open" || !host.bindings.has(command.sessionId)) return error(command.id, command.type, "unknown_session", {}); return undefined; } function takeOtherHolds(host, sessionId, owner) { const taken = []; for (const [connection, owned] of [...host.sessionsByConnection]) { const holds = connection === owner ? 0 : (owned.get(sessionId) ?? 0); for (let hold = 0; hold < holds; hold++) releaseOwnerAttachment(host, connection, sessionId); if (holds > 0) taken.push([connection, holds]); } return taken; } /** Refuses on any other host; else records the takeover, runs `attach` for the caller, and lets the others go. */ export async function takeOver(host, command, owner, attach) { const ledger = host.defaults.sessionTakeover; if (host.defaults.sessionOwner !== "machine" || ledger === undefined) return error(command.id, command.type, "takeover_unsupported", { reason: "only a headless engine with a takeover ledger takes sessions over", }); if (typeof command.holder !== "string" || command.holder.length === 0) return error(command.id, command.type, "takeover_holder_required", {}); let record; try { record = await ledger.takeOver(command.durableSessionId, command.holder); } catch (cause) { return error(command.id, command.type, "takeover_failed", { reason: cause instanceof Error ? cause.message : String(cause), }); } const refused = afterCommitRefusal(host, command, owner); if (refused !== undefined) return refused; try { attach(); } catch (cause) { return error(command.id, command.type, code(cause), detail(cause) ?? {}); } const taken = takeOtherHolds(host, command.sessionId, owner); const released = { type: "session_released", sessionId: command.sessionId, reason: "taken_over", }; for (const [connection, holds] of taken) { if (host.writer.hasConnection(connection)) await host.writer.enqueueControl(released, connection); for (let hold = 0; hold < holds; hold++) await releaseDisconnectAttachment(host, command.sessionId); } return { id: command.id, type: "response", command: command.type, success: true, data: { sessionId: command.sessionId, attached: true, holder: record.holder, generation: record.generation, released: taken.length, }, }; } //# sourceMappingURL=attach-takeover.js.map