@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
144 lines • 7.43 kB
JavaScript
/**
* What a client can observe about the daemon on one socket, in one record.
*
* Everything that describes the RUNNING host comes from the host's own answers - `get_protocol_info`
* for identity, `list_sessions` for occupancy - because files describe the past and the socket
* describes the present. Everything that describes the DAEMON DIRECTORY (which generations exist,
* which environment scope the last ensure granted) comes from disk, because a generation that no
* longer answers is exactly what an operator is looking for when they ask.
*
* A socket nobody serves is not an error here: `reachable: false` with the same field set is the
* answer, so a caller parses one shape either way and branches on one boolean.
*/
import { isHostCrash, readHostCrashRecords } from "./host-crash-record.js";
import { readDaemonEnvKeys } from "./host-daemon-env.js";
import { createHostDaemonPaths, parseShardSocket } from "./host-daemon-paths.js";
import { readHostRegistration } from "./host-daemon-registration.js";
import { pruneDeadGenerations, readGenerationRows } from "./host-generations.js";
import { withHostUnits } from "./host-unit-placement.js";
import { OBSERVE_REQUEST_FIELD } from "./host-observe-request.js";
import { electPointer } from "./host-pointer-election.js";
import { observeProtocolInfo, requestOnSocket } from "./host-probe.js";
import { readHostProcessMetrics } from "./host-process-metrics.js";
import { parseSessionRows, readClaimRows } from "./host-status-rows.js";
import { rpcKeyRoot, withRpcKeyRoot } from "./rpc-auth-client.js";
const STATUS_PROBE_TIMEOUT_MS = 10_000;
export async function readHostStatus(options, read = {}) {
return (await probeHostStatus(options, read)).report;
}
/**
* The report plus what the socket itself said, which the report blends with the directory: `answered`
* is the raw `get_protocol_info` answer (`undefined` when nothing answered) - the report's `instanceId`
* falls back to the RECORDED generation, so only this says whether the socket named an instance - and
* `listing` is every row `list_sessions` returned, whether or not the report publishes them.
*/
export async function probeHostStatus(options, read = {}) {
// The host's key record lives under its own agent dir; a looker that names it proves the key from there.
return withRpcKeyRoot(rpcKeyRoot({}, options.agentDir), () => probeHostStatusInKeyRoot(options, read));
}
async function probeHostStatusInKeyRoot(options, read) {
const paths = createHostDaemonPaths({
socket: options.socket,
...(options.agentDir ? { agentDir: options.agentDir } : {}),
});
const prune = read.prune !== false;
const includeWorkers = options.includeWorkers === true;
// Both reads observe: looking at a host must never be what keeps it from idling out.
const timeoutMs = read.timeoutMs ?? STATUS_PROBE_TIMEOUT_MS;
const host = await observeProtocolInfo(options.socket, timeoutMs);
// Reading the directory is also when it is cleaned: an operator asking what runs here must not
// be shown generations that ended, and the next reader must get the same answer.
if (prune)
await pruneDeadGenerations(paths);
const pointer = await electPointer(paths, { write: prune });
const generations = await withHostUnits(await readGenerationRows(paths, { includeDead: !prune }));
const current = generations.find((row) => row.current && row.alive);
const registered = await readHostRegistration(paths);
const metrics = current ? await readHostProcessMetrics(current.pid) : UNOBSERVED_METRICS;
// A socket that did not answer who it is will not answer what it holds: asking again would only
// spend a second budget on a hung endpoint.
const listing = host === undefined || host.lifecycle === "stopping"
? []
: await readSessionListing(options.socket, includeWorkers, timeoutMs);
const claims = await readClaimRows(paths, generations);
const report = {
reachable: host !== undefined,
lifecycle: host?.lifecycle ?? null,
socket: options.socket,
pid: current?.pid ?? null,
processStartTime: registered?.instanceId === current?.instanceId && registered?.record.pid === current?.pid
? (registered?.record.processStartTime ?? null)
: null,
instanceId: host?.instanceId ?? current?.instanceId ?? null,
generation: host?.generation ?? current?.generation ?? null,
engineVersion: host?.engineVersion ?? current?.engineVersion ?? null,
capabilities: host?.capabilities ?? [],
launchProfile: host?.launch_profile ?? null,
runtimeBuildId: host?.runtimeBuildId ?? null,
handover: host?.handover ?? null,
sessions: countSessions(listing),
zombies: metrics.zombies,
rss_mb: metrics.rss_mb,
host_rss_mb: metrics.host_rss_mb,
host_footprint_mb: metrics.host_footprint_mb,
open_fds: metrics.open_fds,
memory_pressure: host?.memory_pressure ?? null,
path_identity_resolver: host?.path_identity_resolver ?? null,
env_keys: await readDaemonEnvKeys(paths),
generations,
pointer,
crashes: readHostCrashRecords(paths.dir).filter(isHostCrash).length,
shard: parseShardSocket(options.socket),
session_rows: includeWorkers ? listing : [],
claims_live: claims.filter((claim) => claim.live).length,
claims: includeWorkers ? claims : [],
};
return { report, answered: host, listing };
}
/**
* The occupancy a stop decision is made on. A host that does not answer holds nothing a client can
* see, and an empty count is what lets a stop proceed against a socket nobody serves.
*/
export async function readSessionCounts(socket, includeWorkers) {
return countSessions(await readSessionListing(socket, includeWorkers));
}
async function readSessionListing(socket, includeWorkers, timeoutMs = STATUS_PROBE_TIMEOUT_MS) {
const reply = await requestOnSocket(socket, { type: "list_sessions", [OBSERVE_REQUEST_FIELD]: true, ...(includeWorkers ? { include_workers: true } : {}) }, timeoutMs);
return parseSessionRows(reply);
}
function countSessions(rows) {
const attached = rows.filter((row) => row.attachments > 0).length;
const retained = rows.length - attached;
return {
total: rows.length,
interactive: rows.filter((row) => row.kind !== "worker").length,
worker: rows.filter((row) => row.kind === "worker").length,
retained,
foreign_attached: attached,
foreign_retained: retained,
};
}
/** Identity fields of a probed host, for the `host` field of a refusal. */
export function hostSummary(host) {
if (host === undefined)
return null;
return {
protocolVersion: host.protocolVersion,
serverVersion: host.serverVersion,
lifecycle: host.lifecycle ?? null,
capabilities: host.capabilities,
instanceId: host.instanceId ?? null,
generation: host.generation ?? null,
engineVersion: host.engineVersion ?? null,
launchProfileId: host.launch_profile?.profile_id ?? null,
pathIdentityResolver: host.path_identity_resolver ?? null,
};
}
const UNOBSERVED_METRICS = {
rss_mb: null,
host_rss_mb: null,
host_footprint_mb: null,
open_fds: null,
zombies: null,
};
//# sourceMappingURL=host-status.js.map