@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
143 lines • 5.82 kB
JavaScript
import { execFile } from "node:child_process";
import { readProcessStartMs } from "../../core/extensions/builtin/terminal/process-start-probe.js";
import { foreignSessionHolders } from "../../core/foreign-session-holders.js";
import { processStartTimeMs } from "../../utils/process-identity.js";
import { holderGenerationEnded } from "./host-stalled-evidence.js";
import { RPC_ERROR_SESSION_HELD } from "./rpc-types.js";
import { RpcSessionRegistryError } from "./session-registry-types.js";
// Admission is conservative: a new command must pass the guard unless it is explicitly
// a read or a control needed to finish/cancel an already-admitted turn.
const READ_ONLY_OR_CONTROL = new Set([
"get_state",
"get_snapshot",
"get_effect_status",
"get_pending_inputs",
"get_steering_messages",
"get_follow_up_messages",
"get_available_models",
"get_available_thinking_levels",
"get_model_thinking_level",
"get_fast_mode",
"get_session_stats",
"resolve_path",
"get_fork_messages",
"get_entries",
"get_tree",
"get_last_assistant_text",
"get_messages",
"get_media",
"get_commands",
"get_loaded_surfaces",
"get_auth_providers",
"get_provider_accounts",
"memory_report",
"eval_cells.list",
"eval_cells.peek",
"eval_cells.stop",
"export_html",
"export_jsonl",
"abort",
"interrupt",
"abort_compaction",
"abort_branch_summary",
"abort_retry",
"abort_bash",
"clear_queue",
"check_reload_veto",
"cleanup_bash_output",
"set_client_info",
"extension_ui_response",
"extension_ui_progress",
"host_response",
]);
/** One bounded identity snapshot for all foreign PIDs, never one subprocess per lease. */
function readProcessStarts() {
const windows = process.platform === "win32";
const command = windows ? "powershell.exe" : "ps";
const args = windows
? [
"-NoProfile",
"-NonInteractive",
"-Command",
'Get-CimInstance Win32_Process -ErrorAction Stop | ForEach-Object { if ($null -ne $_.CreationDate) { "{0} {1}" -f $_.ProcessId, $_.CreationDate.ToUniversalTime().ToString("o") } }',
]
: ["-axo", "pid=,lstart="];
return new Promise((resolve) => {
execFile(command, args, {
timeout: windows ? 5_000 : 1_000,
maxBuffer: 4 * 1024 * 1024,
windowsHide: true,
...(windows ? {} : { env: { ...process.env, LC_ALL: "C", LANG: "C" } }),
}, (error, stdout) => {
if (error)
return resolve(undefined);
const starts = new Map();
for (const line of stdout.split("\n")) {
const row = /^\s*(\d+)\s+(.+)$/.exec(line);
if (!row)
continue;
const start = processStartTimeMs(row[2]);
if (start !== undefined)
starts.set(Number(row[1]), start);
}
resolve(starts);
});
});
}
/** Fresh leases at each boundary; daemon identity resolution is lazy and scoped to one command. */
export function sessionHeldCheck(resolveDaemonPids) {
let daemonPids;
let processStarts;
const pidStarts = new Map();
const observedStarts = new Map();
return async (sessionFile, sessionId) => {
const holders = await foreignSessionHolders(sessionFile, sessionId, {
holderEnded: (generation) => holderGenerationEnded(generation),
readProcessStartMs: (pid) => {
let probe = pidStarts.get(pid);
if (!probe) {
probe = (async () => {
if (process.platform !== "linux")
processStarts ??= readProcessStarts();
const starts = await processStarts;
const start = starts?.get(pid) ?? (await readProcessStartMs(pid));
observedStarts.set(pid, start);
return start;
})();
pidStarts.set(pid, probe);
}
return probe;
},
});
if (holders.length === 0)
return;
daemonPids ??= resolveDaemonPids?.(observedStarts) ?? Promise.resolve([]);
const family = await daemonPids;
const foreign = holders.filter((holder) => !family.includes(holder.pid));
if (foreign.length > 0)
throw new RpcSessionRegistryError(RPC_ERROR_SESSION_HELD, undefined, {
holders: foreign.map(({ pid, cwd, host_socket, host_instance }) => ({
pid,
...(cwd === undefined ? {} : { cwd }),
...(host_socket === undefined ? {} : { host_socket }),
...(host_instance === undefined ? {} : { host_instance }),
})),
});
};
}
/** The session-command admission boundary shared by in-process and worker hosts. */
export async function dispatchSessionBinding(command, entry, binding, acknowledgePrompt, daemonPids) {
if (!binding)
throw new RpcSessionRegistryError("unknown_session");
if (!READ_ONLY_OR_CONTROL.has(command.type)) {
const assertSessionNotHeld = sessionHeldCheck(daemonPids);
const state = entry.worker?.snapshot?.state;
await assertSessionNotHeld(entry.runtime?.session.sessionFile ?? state?.sessionFile ?? entry.sessionPath, entry.runtime?.session.sessionId ?? state?.sessionId ?? entry.durableSessionId);
if ("sessionPath" in command)
await assertSessionNotHeld(command.sessionPath);
}
if (command.type === "prompt")
acknowledgePrompt();
await binding.handle(command);
}
//# sourceMappingURL=session-held.js.map