@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
101 lines • 4.35 kB
JavaScript
/**
* The terminal's control listener. Every connection must present the 32-byte secret first
* (`authenticateSocket`, the handshake every RPC transport shares); a wrong secret is disconnected
* before a single JSONL line is read. After that it is the RPC framing: one LF-terminated JSON
* object per request, one response per request carrying its `id`, plus pushed feed events.
*
* The socket path is the endpoint's logical address on every platform (its secret lives beside it); on win32 the
* listener binds the named pipe the host transport derives from that path and the secret (senpi#4267), which is
* the address every client already connects to.
*/
import { chmod } from "node:fs/promises";
import { createServer } from "node:net";
import { attachJsonlLineReader, MAX_RPC_LINE_CHARACTERS, serializeJsonLine } from "../rpc/jsonl.js";
import { rpcCommandShapeError } from "../rpc/rpc-input-validation.js";
import { socketSink } from "../rpc/socket-sink.js";
import { authenticateSocket, resolveSocketTransportAddress } from "../rpc/socket-transport.js";
export async function listenControlSocket(socketPath, secret, handlers) {
const clients = new Set();
let nextConnection = 0;
const server = createServer((socket) => {
clients.add(socket);
socket.once("close", () => clients.delete(socket));
socket.on("error", () => socket.destroy());
authenticateSocket(socket, secret, () => acceptConnection(socket, ++nextConnection, handlers));
});
await new Promise((resolve, reject) => {
server.once("error", reject);
server.listen(resolveSocketTransportAddress(socketPath, process.platform, secret), () => {
server.off("error", reject);
resolve();
});
});
server.on("error", (error) => handlers.listenerError(error));
// A named pipe has no file to restrict: the secret, 0600 beside the logical path, is its gate.
if (process.platform !== "win32")
await chmod(socketPath, 0o600);
return { close: () => closeServer(server, clients) };
}
function acceptConnection(socket, id, handlers) {
const connection = {
id,
// Every record, answers and feed events alike, leaves through the endpoint's writer when it has one,
// so this connection's output keeps one order.
send: (record) => {
if (handlers.respond !== undefined)
handlers.respond(connection, record);
else if (!socket.destroyed)
socket.write(serializeJsonLine(record));
},
transport: socketSink(socket),
};
handlers.opened?.(connection);
const detach = attachJsonlLineReader(socket, (line) => void answer(connection, line, handlers), {
maxLineLength: MAX_RPC_LINE_CHARACTERS,
onOversizedLine: () => connection.send(failure(undefined, "parse", "RPC line exceeds the size limit.")),
});
socket.once("close", () => {
detach();
handlers.closed(connection);
});
}
async function answer(connection, line, handlers) {
let parsed;
try {
parsed = JSON.parse(line);
}
catch {
connection.send(failure(undefined, "parse", "Invalid JSON."));
return;
}
const shapeError = rpcCommandShapeError(parsed);
if (shapeError !== undefined || !isCommand(parsed)) {
connection.send(failure(undefined, "parse", shapeError ?? "RPC command needs a string `type`."));
return;
}
const answer = await handlers.command(connection, parsed);
if (answer === null)
return;
connection.send(answer);
}
function isCommand(value) {
return typeof value === "object" && value !== null && "type" in value && typeof value.type === "string";
}
export function failure(id, command, error) {
return { ...(id === undefined ? {} : { id }), type: "response", command, success: false, error };
}
export function success(id, command, data) {
return {
...(id === undefined ? {} : { id }),
type: "response",
command,
success: true,
...(data === undefined ? {} : { data }),
};
}
function closeServer(server, clients) {
for (const client of clients)
client.destroy();
return new Promise((resolve) => server.close(() => resolve()));
}
//# sourceMappingURL=session-control-server.js.map