@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
297 lines • 13 kB
JavaScript
/**
* WHAT the supervisor knows about the host's activity: attached public clients, and the turns its
* always-on observer connection sees start and settle on the internal socket, which also carries the
* host's count of attached connections that hold something there (`host_occupancy`, oh-my-openagent#14272).
* Feeds the idle-exit decision. Split out of `host-lifecycle.ts`, which keeps the supervisor's orchestration (senpi#2566).
*/
import { watch } from "node:fs";
import { createConnection, Socket } from "node:net";
import { ClientOccupancy } from "./host-client-occupancy.js";
import { hostOwnerGone, readHostOwner, sameHostOwner } from "./host-daemon-state.js";
import { IdleExitDecider } from "./host-lifecycle-policy.js";
import { hostOccupancyHolders, WATCH_HOST_OCCUPANCY } from "./host-observe-request.js";
import { holdIdleExitForSettling, SessionRunActivity } from "./host-run-activity.js";
import { startupHandOff } from "./host-startup-beacon.js";
import { supervisorLog } from "./host-supervisor-log.js";
import { connectInternalConnection } from "./internal-channel.js";
import { attachJsonlLineReader, MAX_RPC_LINE_CHARACTERS } from "./jsonl.js";
import { activeTurnsForIdleDecision, createObserverLink } from "./observer-link.js";
import { resolveSocketTransportAddress, sendSocketHandshake } from "./socket-transport.js";
/**
* The observer's internal handshake bound (senpi#3816 review), the same 5 s the raw connect had: a child that accepts
* and never answers fails the open, and the connection is dropped.
*/
export const INTERNAL_OBSERVER_HANDSHAKE_MS = 5_000;
export class SupervisorActivity {
constructor(options) {
this.options = options;
// Everything `current()` reads exists before any client can be accepted: a connection admitted
// during startup asks for the activity snapshot, and a successor's first `open_session` once
// failed on a binding read before its initializer ran.
// A coordinated start's launcher probes once the endpoint is published: the window waits for that first
// client for as long as the launcher may still decide the start (senpi#6001).
this.decider = new IdleExitDecider(options.idleExitMs, Date.now, startupHandOff()?.budgetMs);
// A settled session's agent_settled handlers hold idle exit for at most one idle window (omo#11419).
this.runs = new SessionRunActivity({
settleHoldMs: options.idleExitMs,
onSettleHoldExpired: (sessionId, heldMs) => supervisorLog(`session ${sessionId} settled ${heldMs} ms ago and its agent_settled extension handlers have not finished; idle exit no longer waits for them`),
});
this.clients = new ClientOccupancy(() => this.attached(), options.instanceId);
this.observerLink = createObserverLink({
open: () => this.connectObserver(),
settled: options.settled,
retryDelayMs: 250,
now: Date.now,
setTimer: (run, ms) => {
const timer = setTimeout(run, ms);
timer.unref?.();
return { cancel: () => clearTimeout(timer) };
},
});
}
current() {
return {
// Without a healthy observer the host's count is unknown, and every attached client counts.
connections: this.clients.occupancy(this.observerLink.healthy() ? this.sessionHolders : undefined),
activeTurns: activeTurnsForIdleDecision({
healthy: this.observerLink.healthy(),
unhealthySince: this.observerLink.unhealthySince(),
now: Date.now(),
unknownGraceMs: this.decider.idleExitMs,
observedBusy: this.runs.busySessions,
}),
};
}
refresh() {
const current = this.current();
if (current.connections > 0 || current.activeTurns > 0 || this.clients.unclassifiedCount > 0)
this.options.onActivity?.();
return holdIdleExitForSettling(this.decider.update(current), this.runs);
}
/**
* An attachment restarts the idle window even when the host has not counted the client as a holder yet: its first
* command (an open) is still on its way there.
*/
attached() {
this.decider.restart();
this.options.onActivity?.();
this.refresh();
}
/** Owner death never turns an unknown observer snapshot into permission to stop a turn. */
quiescent() {
return (this.observerLink.healthy() &&
this.runs.busySessions === 0 &&
this.runs.settlingSessions === 0 &&
this.clients.attachedCount === 0 &&
this.clients.unclassifiedCount === 0);
}
openObserver() {
return this.observerLink.open();
}
stopObserver() {
this.observerLink.stop();
this.observerSocket?.destroy();
}
async connectObserver() {
const secret = this.options.internalSecret;
const next = createConnection(resolveSocketTransportAddress(this.options.internalSocket, process.platform, secret));
if (secret)
sendSocketHandshake(next, secret);
let stream;
try {
if (this.options.internalKey)
stream = await connectInternalConnection(next, this.options.internalKey, {
timeoutMs: INTERNAL_OBSERVER_HANDSHAKE_MS,
});
else {
await waitForConnect(next, 5_000);
stream = next;
}
}
catch (cause) {
next.destroy();
throw cause;
}
this.observerSocket = stream;
this.sessionHolders = undefined;
attachJsonlLineReader(stream, (line) => this.observeHostEvent(line), { maxLineLength: MAX_RPC_LINE_CHARACTERS });
stream.write(`${JSON.stringify({ type: WATCH_HOST_OCCUPANCY, observe: true })}\n`);
return {
onLost: (handler) => {
const lost = () => {
this.sessionHolders = undefined;
handler();
this.options.onActivity?.();
};
stream.once("close", lost);
stream.once("error", lost);
},
};
}
observeHostEvent(line) {
const holders = hostOccupancyHolders(line);
if (holders !== undefined) {
this.sessionHolders = holders;
this.refresh();
return;
}
if (this.runs.observe(line))
this.refresh();
}
}
/** Continuous quiet time, in addition to attach holds and confirmed owner death (#3044). */
export const OWNER_EXIT_GRACE_MS = 2_000;
const OWNER_PROBE_MAX_INTERVAL_MS = 5_000;
/**
* Fresh starts inherit an event-loop pipe on POSIX and Windows. An existing supervisor cannot
* receive a newly inherited fd, nor can a foreign handoff caller pass the original owner's fd:
* those bindings use the OS start identity. Failed observations are never death.
*/
export class SupervisorOwner {
constructor(generationDir) {
this.watchFailed = false;
this.nextProbeAt = 0;
this.probeIntervalMs = 1_000;
this.gone = false;
this.revision = 0;
this.stopped = false;
this.idle = new IdleExitDecider(OWNER_EXIT_GRACE_MS, () => performance.now());
this.generationDir = generationDir;
}
async start(fd) {
await this.reload();
if (fd === undefined || this.owner == null)
return;
try {
const pipe = new Socket({ fd, readable: true, writable: false });
this.pipe = pipe;
const bound = this.owner;
let failed = false;
const eof = () => {
if (!failed && !this.stopped && sameHostOwner(this.owner, bound))
this.gone = true;
};
pipe.once("end", eof);
// Windows may report a clean close without an end; an errored pipe remains unknown.
if (process.platform === "win32")
pipe.once("close", eof);
pipe.once("error", () => {
failed = true;
if (this.pipe === pipe)
this.pipe = undefined;
pipe.destroy();
});
pipe.resume();
}
catch {
// Inheritance was unavailable on this launch path: use the recorded OS identity.
this.pipe = undefined;
}
}
async reload() {
const revision = ++this.revision;
const next = await readHostOwner(this.generationDir);
if (this.stopped || revision !== this.revision)
return;
if (!sameHostOwner(this.owner, next)) {
this.pipe?.destroy();
this.pipe = undefined;
this.gone = false;
this.nextProbeAt = 0;
this.probeIntervalMs = 1_000;
this.activity();
}
this.owner = next;
if (next == null) {
this.watcher?.close();
this.watcher = undefined;
}
else if (!this.watcher && !this.watchFailed) {
try {
this.watcher = watch(this.generationDir, (_event, filename) => {
if (filename?.toString() === "owner.json")
void this.reload();
});
this.watcher.once("error", () => {
this.watchFailed = true;
this.watcher?.close();
this.watcher = undefined;
});
}
catch {
// Exhausted or unavailable filesystem watches degrade to record polling, not startup failure.
this.watchFailed = true;
}
}
}
activity() {
this.idle.update({ connections: 1, activeTurns: 0 });
}
async shouldExit(activity) {
// Also discovers a first owner claimed on an initially unowned generation, without an fs watcher.
if (!this.watcher)
await this.reload();
const owner = this.owner;
const revision = this.revision;
// Bun can leave the inherited pipe silent after its writer dies (#4845). Reparenting
// re-enables the OS-identity check; it never bypasses ownership or the quiet-state gate.
if (owner != null &&
(!this.pipe || process.ppid !== owner.pid) &&
!this.gone &&
performance.now() >= this.nextProbeAt) {
const gone = await hostOwnerGone(owner);
if (this.stopped || revision !== this.revision)
return false;
this.gone = gone;
this.nextProbeAt = performance.now() + this.probeIntervalMs;
this.probeIntervalMs = Math.min(OWNER_PROBE_MAX_INTERVAL_MS, this.probeIntervalMs * 2);
}
const quiet = this.gone && owner != null && activity.quiescent();
if (this.idle.update({ connections: quiet ? 0 : 1, activeTurns: 0 }) !== "exit")
return false;
// fs.watch may lag a new owner's atomic write. Its ensure holds a connection until this
// publication, so re-read the record AND occupancy before authorizing synchronous shutdown.
const current = await readHostOwner(this.generationDir);
if (this.stopped || revision !== this.revision)
return false;
// `fs.watch` can also DROP that write entirely (senpi#4629 measured the same loss in a test
// wait on this machine class). Refusing on the mismatch alone left this supervisor bound to a
// dead predecessor forever: it never adopted the replacement, so the replacement's own death
// could not end the generation and the host outlived its owner until the idle window. Adopt
// the record here - the watcher stays the fast path - and decide for the real owner next tick.
if (!sameHostOwner(owner, current)) {
await this.reload();
return false;
}
return activity.quiescent();
}
stop() {
this.stopped = true;
this.watcher?.close();
this.pipe?.destroy();
}
}
function waitForConnect(socket, timeoutMs) {
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
cleanup();
reject(new Error(`observer connection to internal host timed out after ${timeoutMs}ms`));
}, timeoutMs);
const onConnect = () => {
cleanup();
resolve();
};
const onError = (cause) => {
cleanup();
reject(cause);
};
const cleanup = () => {
clearTimeout(timer);
socket.off("connect", onConnect);
socket.off("error", onError);
};
socket.once("connect", onConnect);
socket.once("error", onError);
});
}
//# sourceMappingURL=host-lifecycle-activity.js.map