@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
117 lines • 4.77 kB
JavaScript
import { attachJsonlLineReader, MAX_RPC_LINE_CHARACTERS } from "../rpc/jsonl.js";
import { authenticateSocket } from "../rpc/socket-transport.js";
const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
/** A reference packet as one carrier line; anything else is not carried. */
function encodeCarrierLine(message) {
if (!isRecord(message) || typeof message.lane !== "string" || typeof message.seq !== "number")
return undefined;
if (message.kind === "ack")
return `${JSON.stringify({ kind: "ack", lane: message.lane, seq: message.seq })}\n`;
if (message.kind !== "data" || !(message.payload instanceof Uint8Array))
return undefined;
const payload = Buffer.from(message.payload).toString("base64");
return `${JSON.stringify({ kind: "data", lane: message.lane, seq: message.seq, payload })}\n`;
}
/** One carrier line back as the packet the reference transport reads; a malformed line is dropped as a lost message. */
function decodeCarrierLine(line) {
let parsed;
try {
parsed = JSON.parse(line);
}
catch {
return undefined;
}
if (!isRecord(parsed) || typeof parsed.lane !== "string" || typeof parsed.seq !== "number")
return undefined;
if (parsed.kind === "ack")
return { kind: "ack", lane: parsed.lane, seq: parsed.seq };
if (parsed.kind !== "data" || typeof parsed.payload !== "string")
return undefined;
return {
kind: "data",
lane: parsed.lane,
seq: parsed.seq,
payload: new Uint8Array(Buffer.from(parsed.payload, "base64")),
};
}
/**
* Makes `socket` the current connection of `side` until it closes. Returns `detach`, which ends this connection's
* hold on the side (the socket's own close does the same) without signalling it twice.
*/
export function attachSocketCarrier(socket, side, report) {
let live = true;
let reportedError = false;
const stopReading = attachJsonlLineReader(socket, (line) => {
if (live)
side.message(decodeCarrierLine(line));
}, { maxLineLength: MAX_RPC_LINE_CHARACTERS });
const onDrain = () => {
if (live)
side.writable();
};
/**
* A failing carrier leaves one line per connection - the code and the message, never a packet payload - and then
* the socket is destroyed as before, so the transport resumes on a fresh connection and the failure is visible
* in the hand's stderr instead of only as a stalled lane (senpi#5993).
*/
const onError = (error) => {
if (live && !reportedError) {
reportedError = true;
const code = error.code;
report(`carrier socket error${code === undefined ? "" : ` ${code}`}: ${error.message}`);
}
socket.destroy();
};
const detach = () => {
if (!live)
return;
live = false;
stopReading();
socket.off("drain", onDrain);
side.detached();
};
socket.on("drain", onDrain);
socket.once("close", detach);
socket.on("error", onError);
side.attached({
// `false` means "not taken": the side resends after `writable()`. So refuse while the socket is over its
// high-water mark instead of queueing a line the side will send again.
send: (message) => {
if (!live || socket.destroyed || socket.writableNeedDrain)
return false;
const line = encodeCarrierLine(message);
if (line !== undefined)
socket.write(line);
return true;
},
close: () => socket.destroy(),
});
return detach;
}
/**
* Serves `side` on `server`: the newest connection is the carrier, and an older one is dropped when a new one arrives.
* With a `secret` (the Windows named pipe; the same handshake the shared RPC host uses), a connection becomes the
* carrier only after it sent the secret's bytes first (`authenticateSocket`), so a connection without it never
* displaces the current carrier.
*/
export function serveSocketCarrier(server, side, secret, report) {
let current;
const take = (socket) => {
const previous = current;
previous?.detach();
previous?.socket.destroy();
const detach = attachSocketCarrier(socket, side, report);
current = { socket, detach };
socket.once("close", () => {
if (current?.socket === socket)
current = undefined;
});
};
server.on("connection", (socket) => {
if (secret === undefined)
take(socket);
else
authenticateSocket(socket, secret, () => take(socket));
});
}
//# sourceMappingURL=socket-carrier.js.map