@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
125 lines • 5.41 kB
JavaScript
import { randomUUID } from "node:crypto";
import { attachJsonlLineReader, MAX_RPC_LINE_CHARACTERS, serializeJsonLine } from "./jsonl.js";
import { connectAuthenticatedRpcSocket } from "./rpc-auth-client.js";
import { DEFAULT_LOOP_LAG_ERROR_MS } from "./loop-lag-threshold.js";
import { authRecord } from "./rpc-auth-proof.js";
export class RouteDisconnected extends Error {
constructor(sent) {
super(sent ? "predecessor_delivery_outcome_unknown" : "predecessor_not_sent");
this.sent = sent;
}
}
/**
* How long a predecessor may leave a request unanswered before it has to show it is alive: the host's own stall
* threshold. A late answer is followed by a liveness probe, and a predecessor that answers neither is stalled.
*/
export const PREDECESSOR_REQUEST_TIMEOUT_MS = DEFAULT_LOOP_LAG_ERROR_MS;
/** A request the predecessor did not answer in time (`predecessor_request_timeout`); the connection is cut. */
export class RouteTimedOut extends Error {
constructor() {
super("predecessor_request_timeout");
}
}
/** One authenticated attachment per downstream connection and session. IDs and requester-only records never mix. */
export class PredecessorPeer {
constructor(socket, generation, onRecord, onEnd) {
this.pending = new Map();
this.socket = socket;
this.generation = generation;
const detach = attachJsonlLineReader(socket, (line) => {
let value;
try {
value = authRecord(JSON.parse(line));
}
catch {
socket.destroy();
return;
}
if (!value)
return;
const pending = typeof value.id === "string" && value.type === "response" ? this.pending.get(value.id) : undefined;
if (pending)
pending.resolve(value);
else
onRecord(value);
}, { maxLineLength: MAX_RPC_LINE_CHARACTERS, onOversizedLine: () => socket.destroy() });
socket.on("error", () => socket.destroy());
socket.once("close", () => {
detach();
for (const pending of this.pending.values())
pending.reject(new RouteDisconnected(true));
onEnd();
});
}
static async connect(endpoint, onRecord, onEnd) {
const { socket, protocol } = await connectAuthenticatedRpcSocket(endpoint.socket, undefined, {
keyRoot: endpoint.keyRoot,
expectedLaunchId: endpoint.launchId,
});
const data = authRecord(protocol.data);
if (data?.instanceId !== endpoint.instanceId || typeof data.generation !== "number") {
socket.destroy();
throw new Error("predecessor_identity_mismatch");
}
return new PredecessorPeer(socket, data.generation, onRecord, onEnd);
}
/**
* Every request is bounded. `deadlineMs` is a fixed limit; without it the request waits while the predecessor stays
* alive, so a long command (`bash`, `compact` answer when their work is done) is never cut.
*/
async request(command, deadlineMs) {
if (this.socket.destroyed)
throw new RouteDisconnected(false);
const id = typeof command.id === "string" ? command.id : randomUUID();
if (this.pending.has(id))
throw new Error("duplicate_request_id");
const pending = Promise.withResolvers();
this.pending.set(id, pending);
try {
this.socket.write(serializeJsonLine({ ...command, id }));
return await (deadlineMs === undefined
? this.answerWhileAlive(pending.promise)
: within(pending.promise, deadlineMs));
}
catch (cause) {
// Nothing a stalled predecessor sends later may still be read as an answer to a caller that gave up.
if (cause instanceof RouteTimedOut)
this.socket.destroy();
// This command was written, so its outcome is unknown even when a liveness probe found the connection already
// cut by another request's deadline (destroyed before `close`): reporting it as not sent would let the caller
// replay a mutation the predecessor may have committed.
if (cause instanceof RouteDisconnected && !cause.sent)
throw new RouteDisconnected(true);
throw cause;
}
finally {
this.pending.delete(id);
}
}
async answerWhileAlive(answer) {
for (;;) {
const answered = await within(answer, PREDECESSOR_REQUEST_TIMEOUT_MS).catch((cause) => {
if (cause instanceof RouteTimedOut)
return undefined;
throw cause;
});
if (answered !== undefined)
return answered;
await this.request({ type: "get_protocol_info", observe: true }, PREDECESSOR_REQUEST_TIMEOUT_MS);
}
}
send(record) {
this.socket.write(serializeJsonLine(record));
}
close() {
this.socket.destroy();
}
}
function within(answer, ms) {
let timer;
const late = new Promise((_, reject) => {
timer = setTimeout(() => reject(new RouteTimedOut()), ms);
});
return Promise.race([answer, late]).finally(() => clearTimeout(timer));
}
//# sourceMappingURL=predecessor-peer.js.map