@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
229 lines • 10.7 kB
JavaScript
/** Short-lived, attach-before-act clients for `senpi host session`. */
import { daemonEnvKeys, daemonEnvOverrides, writeDaemonEnvKeys } from "./host-daemon-env.js";
import { createHostDaemonPaths } from "./host-daemon-paths.js";
import { HostEnsureRefusedError } from "./host-decision.js";
import { endpointKindOfSocket } from "./host-endpoints.js";
import { ensureHost } from "./host-ensure.js";
import { STOP_WAIT_BUDGET_MS } from "./host-ensure-stop.js";
import { HOST_EXIT_OK, HOST_EXIT_REFUSED, refusal } from "./host-outcome.js";
import { detachBeforeClose } from "./host-session-detach.js";
import { mapError } from "./host-session-errors.js";
import { openHostSession } from "./host-session-open.js";
import { resolveSessionRef } from "./host-session-ref.js";
import { waitForHostSession } from "./host-session-wait.js";
import { isTransportGoneError, RpcClient, RpcCommandError, } from "./rpc-client.js";
import { RpcRequestTimeoutError } from "./rpc-request-deadline.js";
export async function runHostSessionRequest(request) {
const deadline = Date.now() + STOP_WAIT_BUDGET_MS;
for (;;) {
try {
return await runHostSessionRequestOnce(request, Math.max(0, deadline - Date.now()));
}
catch (error) {
if (request.action === "open" &&
error instanceof RpcCommandError &&
error.errorCode === "host_stopping" &&
Date.now() < deadline)
continue;
return mapError(error, request.target.socket);
}
}
}
async function runHostSessionRequestOnce(request, stoppingTimeoutMs) {
const { socket, agentDir } = request.target;
let client;
let ensured;
let disconnected;
// A host that stopped answering or a lost transport cannot confirm a detach; the socket close releases.
let connectionUnusable = false;
try {
if ((await endpointKindOfSocket(socket, agentDir)) === "tui") {
return refusal("refuse", undefined, { reason: "unsupported_endpoint_kind", socket, endpoint_kind: "tui" });
}
if (request.action === "open") {
ensured = await ensureHost({
socket,
agentDir,
hostArgs: request.spec.hostArgs,
env: daemonEnvOverrides(process.env, request.spec.env),
policy: request.spec.policy,
upgrade: "never",
stoppingTimeoutMs,
});
if (!ensured.reused) {
await writeDaemonEnvKeys(createHostDaemonPaths({ socket, agentDir }), daemonEnvKeys(process.env, request.spec.env));
}
}
client = new RpcClient({
socketPath: socket,
onDisconnect: (error) => {
connectionUnusable = true;
disconnected?.(error);
},
});
try {
await client.start();
}
catch (error) {
if (error instanceof Error && "code" in error && (error.code === "ENOENT" || error.code === "ECONNREFUSED")) {
return refusal("refuse", undefined, { reason: "host_unavailable", socket, detail: error.message });
}
throw error;
}
let sessionId;
let durableSessionId;
if ("ref" in request) {
const found = await resolveSessionRef(client, request.ref, agentDir);
if (found.kind === "unknown") {
return refusal("refuse", undefined, { reason: "unknown_session", ref: request.ref, socket });
}
if (found.kind === "ambiguous") {
const detail = { reason: "ambiguous_session", ref: request.ref, candidates: found.candidates, socket };
return refusal("refuse", undefined, detail);
}
// A parked session resumes from its transcript and stays retained past this short-lived client.
const reopen = found.kind === "parked"
? {
sessionPath: found.sessionPath,
cwd: found.cwd,
retain_on_disconnect: true,
attended: false,
}
: { sessionPath: found.row.sessionPath, cwd: found.row.cwd };
durableSessionId = found.kind === "parked" ? found.durableSessionId : found.row.durableSessionId;
sessionId = (await client.openSession(reopen)).sessionId;
}
switch (request.action) {
case "open":
return await openHostSession(client, request, socket, ensured);
case "prompt":
return {
exitCode: HOST_EXIT_OK,
payload: { action: "prompt", sessionId, disposition: await client.prompt(request.text) },
};
case "steer": {
// An idle steer is parked until the next prompt; it does not start a run.
const streaming = (await client.getState()).isStreaming;
const disposition = await client.steer(request.text);
return { exitCode: HOST_EXIT_OK, payload: { action: "steer", sessionId, disposition, streaming } };
}
case "abort": {
const aborted = (await client.getState()).isStreaming;
await client.abortStrict();
return { exitCode: HOST_EXIT_OK, payload: { action: "abort", sessionId, acknowledged: true, aborted } };
}
case "model": {
// set_model also persists the GLOBAL default. Smaller contexts may defer the switch.
await client.setModel(request.model.provider, request.model.id);
const state = await client.getState();
return {
exitCode: HOST_EXIT_OK,
payload: {
action: "model",
sessionId,
requested: request.model,
model: state.model ? { provider: state.model.provider, id: state.model.id } : null,
pendingModelSwitch: state.pendingModelSwitch ?? null,
},
};
}
case "list":
return {
exitCode: HOST_EXIT_OK,
payload: { action: "list", socket, sessions: await client.listSessions({ observe: true }) },
};
case "state":
return {
exitCode: HOST_EXIT_OK,
payload: { action: "state", sessionId, durableSessionId, state: await client.getState() },
};
case "read": {
if (request.messages) {
const all = await client.getMessages();
const messages = request.tail === undefined ? all : all.slice(-request.tail);
return {
exitCode: HOST_EXIT_OK,
payload: { action: "read", sessionId, messages, count: messages.length },
};
}
const { entries, leafId } = await client.getEntries(request.since);
const slice = request.tail === undefined ? entries : entries.slice(-request.tail);
return {
exitCode: HOST_EXIT_OK,
payload: {
action: "read",
sessionId,
entries: slice,
count: slice.length,
total: entries.length,
leafId,
nextSince: slice.at(-1)?.id ?? request.since ?? null,
...(request.since !== undefined && { since: request.since }),
},
};
}
case "wait":
return await waitForHostSession(client, sessionId, request, (handler) => {
disconnected = handler;
});
case "unload": {
const answer = await client.unloadSession({
sessionId,
interrupt: request.interrupt,
force: request.force,
clearQueue: request.clearQueue,
children: request.children,
});
return {
exitCode: answer.outcome === "unloaded" ? HOST_EXIT_OK : HOST_EXIT_REFUSED,
payload: { action: "unload", sessionId, ...answer },
};
}
case "close": {
let reason;
const unsubscribe = client.onEvent((record) => {
const event = record;
if (event.type === "session_closed")
reason = event.reason;
});
try {
await client.closeSession(sessionId);
// closeSession tolerates disconnect; this checked read must still succeed.
const remaining = (await client.listSessions()).find((row) => row.sessionId === sessionId);
return {
exitCode: HOST_EXIT_OK,
payload: remaining
? { action: "close", sessionId, closed: false, attachments: remaining.attachments }
: { action: "close", sessionId, closed: true, reason: reason ?? "client_close" },
};
}
finally {
unsubscribe();
}
}
default:
return assertNever(request);
}
}
catch (error) {
if (error instanceof RpcRequestTimeoutError || isTransportGoneError(error))
connectionUnusable = true;
// Only an explicit open owns a launch spec. No other operation may invent one.
if (request.action === "open" && error instanceof RpcCommandError && error.errorCode === "host_stopping")
throw error;
if (error instanceof HostEnsureRefusedError) {
return refusal("refuse", undefined, { reason: error.reason, socket, detail: error.detail });
}
return mapError(error, socket);
}
finally {
ensured?.release();
if (client && !connectionUnusable)
await detachBeforeClose(client, (line) => process.stderr.write(`senpi host session: ${line}\n`));
await client?.stop();
}
}
function assertNever(value) {
throw new Error(`unreachable host session request: ${JSON.stringify(value)}`);
}
//# sourceMappingURL=host-session-runner.js.map