UNPKG

@code-yeongyu/senpi

Version:

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

132 lines • 7.24 kB
/** * The engine as a hand (`--hand`, senpi#5840): loopless runtimes per execution scope (`createLooplessHand`) serving the * remote executor, its device file channel and the scopes' loop hooks on one local endpoint, through the reference * transport over {@link serveSocketCarrier}. What a scope's work sends the loop after its call ended travels on the wake * lane from the hand's durable outbox (H3). It never runs a loop and opens no transcript; the process lives until it is * signalled. */ import { createServer } from "node:net"; import { posix, win32 } from "node:path"; import { createHandWakeLink, createReliableTransport, createRemoteExecutor, HAND_WAKE_LANE, serveLoopHooks, } from "@earendil-works/pi-agent-core"; import { closeServer, prepareSocketPath } from "../rpc/host-lifecycle-proxy.js"; import { listen } from "../rpc/host-socket-bind.js"; import { createLooplessHand } from "../rpc/remote-executor-scope.js"; import { shieldSocketDuringClose, unlinkOwnedSocket } from "../rpc/socket-ownership.js"; import { ensureSocketSecret, resolveSocketTransportAddress, socketSecretPath } from "../rpc/socket-transport.js"; import { handWakesOver, openHandWakeOutbox } from "./hand-wakes.js"; import { serveSocketCarrier } from "./socket-carrier.js"; /** The lane the loop hooks of a hand's scopes travel on; every other lane is the remote executor's. */ const HAND_LOOP_HOOK_LANE = "loop-hooks"; export function handSocketPath(agentDir, platform = process.platform) { return (platform === "win32" ? win32 : posix).join(agentDir, "rpc", "hand.sock"); } /** The hand's durable wake outbox, beside its socket: one live hand per agent dir writes it. */ export function handWakeStorePath(agentDir, platform = process.platform) { return (platform === "win32" ? win32 : posix).join(agentDir, "rpc", "hand-wakes.json"); } /** The address a carrier dials: the socket path on POSIX, its named pipe (named with the secret) on Windows. */ function handEndpoint(agentDir, platform, secret) { return resolveSocketTransportAddress(handSocketPath(agentDir, platform), platform, secret); } /** * The hand endpoint's secret: on Windows (a named pipe has no owner-only file mode) the shared RPC host's mechanism, * an owner-only `<hand.sock>.secret` file whose bytes a carrier sends first; on POSIX the 0600 socket in its 0700 * directory is the boundary and there is none. Never read from the host's secret-file override variable. */ export function handEndpointSecret(socketPath, platform = process.platform) { return platform === "win32" ? ensureSocketSecret(socketSecretPath(socketPath)) : Promise.resolve(undefined); } /** One transport seen as several: frames on each named lane go to that lane's view, every other frame to `rest`. */ function splitLanes(transport, lanes) { const handlers = new Map(); const named = new Set(lanes); const REST = ""; transport.onFrame((frame) => handlers.get(named.has(frame.lane) ? frame.lane : REST)?.(frame)); const view = (key) => ({ send: (to, payload) => transport.send(to, payload), onFrame: (handler) => void handlers.set(key, handler), inFlight: (to) => transport.inFlight(to), close: () => transport.close(), }); return { lane: view, rest: view(REST) }; } export async function runHand(options) { const { agentDir } = options.configuration; const report = (message) => void process.stderr.write(`senpi hand: ${message}\n`); const socketPath = handSocketPath(agentDir); // Refuses an entry a live hand still serves; only a dead (stale) entry is removed. The wake outbox it opens next // claims its file's next epoch, so an older hand still shutting down can no longer write it. await prepareSocketPath(socketPath); const outbox = await openHandWakeOutbox(handWakeStorePath(agentDir), { onFault: (error) => report(`wake fault: ${error.message}`), }); const transport = createReliableTransport({ clock: { now: () => Date.now(), setTimer: (callback, ms) => { const timer = setTimeout(callback, ms); return () => clearTimeout(timer); }, }, onHandlerError: (error) => report(`frame handler failed: ${String(error)}`), }); const lanes = splitLanes(transport, [HAND_LOOP_HOOK_LANE, HAND_WAKE_LANE]); const wakeLink = createHandWakeLink({ transport: lanes.lane(HAND_WAKE_LANE), outbox, onFault: (error) => report(`wake fault: ${String(error)}`), }); // The loop runs elsewhere (a hosted loop), so this machine is its extensions' home: their loop hooks run here (S33). const hand = createLooplessHand(options.configuration, { twoSidedHome: "hand", ...(options.extensionFactories === undefined ? {} : { extensionFactories: options.extensionFactories }), wakes: handWakesOver(wakeLink), }); const executor = createRemoteExecutor({ authority: { kind: "self" }, fileChannel: true, transport: lanes.rest, openScope: hand.openScope, onFault: (error) => report(`call fault: ${String(error)}`), }); const loopHooks = serveLoopHooks({ transport: lanes.lane(HAND_LOOP_HOOK_LANE), lane: HAND_LOOP_HOOK_LANE, run: hand.loopHooks, onFault: (error) => report(`loop hook fault: ${String(error)}`), }); const secret = await handEndpointSecret(socketPath); const server = createServer(); serveSocketCarrier(server, transport, secret, report); const boundIdentity = await listen(server, socketPath, secret); report(`listening on ${handEndpoint(agentDir, process.platform, secret)}`); return new Promise(() => { const stop = async () => { let exitCode = 0; const step = async (name, run) => { try { await run(); } catch (error) { exitCode = 1; report(`${name} failed during shutdown: ${String(error)}`); } }; // The transport goes first: closing it destroys the carrier connection, and the listener's close waits for // every open connection, so a carrier still attached would hold the shutdown (and the shielded entry) open. await step("loop hooks", () => loopHooks.close()); await step("wake link", () => wakeLink.close()); await step("transport", () => transport.close()); // libuv unlinks the bound name on close, which would delete a newer hand's entry: shield it for the close, // then remove only the entry this process bound. await step("listener close", () => shieldSocketDuringClose(socketPath, () => closeServer(server))); await step("executor", () => executor.close()); await step("hand runtimes", () => hand.close()); await step("socket removal", () => unlinkOwnedSocket(socketPath, boundIdentity, report)); process.exit(exitCode); }; process.once("SIGTERM", () => void stop()); process.once("SIGINT", () => void stop()); }); } //# sourceMappingURL=hand-entry.js.map