UNPKG

@code-yeongyu/senpi

Version:

Coding agent CLI with read, bash, edit, write tools and session management

152 lines • 6.97 kB
/** * `warm`: load what the next `open_session` needs without opening a session (senpi#2314). * * A fresh host pays a one-time cost on its first session: the extension module graph compiles and * the extensions' factories load their runtimes (a task engine, for a `child` role). With one host * per session every session paid it. `warm` builds the cwd-bound services an open would build for * the same cwd, kind and context - which compiles that graph and runs those factories - and drops * them. No `AgentSession` exists, no `session_start` fires, nothing is registered or listed, and * the connection that asked stays an observer (`host-observe-request.ts`), so a host that only * received `warm` still idles out on its normal deadline. * * A profile is warmed once per host: a repeat answers `already_warm` without running factories * again, and concurrent warms of one profile share a single load. */ import { access } from "node:fs/promises"; import { isAbsolute } from "node:path"; import { ProviderScope, runWithProviderScope } from "@earendil-works/pi-ai/node/provider-scope"; import { sessionContextError, sessionKindError } from "./rpc-input-validation.js"; import { RPC_ERROR_INVALID_PATH, RPC_ERROR_INVALID_SESSION_CONTEXT, RPC_ERROR_INVALID_SESSION_KIND, RPC_ERROR_WARM_FAILED, } from "./rpc-types.js"; /** Distinct profiles a host remembers as warm; the oldest is forgotten past this. */ const MAX_WARM_PROFILES = 64; function profileKey(profile) { const context = Object.entries(profile.sessionContext ?? {}).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)); return JSON.stringify([profile.cwd, profile.sessionKind ?? "interactive", context]); } /** Coalesces concurrent warms of one profile and answers repeats without loading again. */ export class HostWarmer { constructor(load) { this.warm = new Set(); this.loading = new Map(); this.load = load; } async run(profile) { const key = profileKey(profile); if (this.warm.has(key)) return "already_warm"; let load = this.loading.get(key); if (load === undefined) { load = { cwd: profile.cwd, pending: this.loadOnce(key, profile) }; this.loading.set(key, load); } await load.pending; return "warmed"; } /** * Settles once every load of `cwd` in flight NOW has settled; `undefined` when none is. A snapshot: a warm * that starts later, or one of another cwd, is not part of it. */ inFlight(cwd) { const pending = [...this.loading.values()].filter((load) => load.cwd === cwd).map((load) => load.pending); if (pending.length === 0) return undefined; return Promise.allSettled(pending).then(() => undefined); } async loadOnce(key, profile) { try { await this.load(profile); this.warm.add(key); if (this.warm.size > MAX_WARM_PROFILES) { const oldest = this.warm.values().next().value; if (oldest !== undefined) this.warm.delete(oldest); } } finally { this.loading.delete(key); } } } /** * The in-process registry's `warm`. The services are built inside their own provider scope, exactly * like an open's, and the scope closes when they are dropped, so nothing an extension registered * while loading outlives the warm. */ export function createRegistryWarm(prepare, host) { const warmer = new HostWarmer(async (profile) => { await access(profile.cwd); const launchProfile = { cwd: profile.cwd, ...(profile.sessionKind !== undefined ? { sessionKind: profile.sessionKind } : {}), ...(profile.sessionContext !== undefined ? { sessionContext: Object.freeze({ ...profile.sessionContext }) } : {}), }; const scope = new ProviderScope(); try { await runWithProviderScope(scope, () => prepare({ cwd: profile.cwd, agentDir: host.agentDir, launchProfile: Object.freeze(launchProfile), ...(host.mcpRegistry !== undefined ? { mcpRegistry: host.mcpRegistry } : {}), })); } finally { scope.close(); } }); return { warm: (profile) => warmer.run(profile), inFlight: (cwd) => warmer.inFlight(cwd) }; } /** * Waits for `warming` at most `boundMs`. A warm whose extension factory never settles (there is no factory * timeout) must not stall an open, so past the bound the open proceeds and the reason is reported. */ export async function waitForWarms(warming, boundMs, cwd) { let deadline; const outcome = await Promise.race([ warming.then(() => "settled"), new Promise((resolve) => { deadline = setTimeout(() => resolve("warm_wait_deadline"), boundMs); }), ]); clearTimeout(deadline); if (outcome === "warm_wait_deadline") process.stderr.write(`senpi rpc open: warm_wait_deadline: a warm of ${cwd} still loading after ${boundMs} ms; opening anyway\n`); return outcome; } function refusal(command, code) { return { id: command.id, type: "response", command: "warm", success: false, error: code }; } /** * Answers one `warm`. The router calls this OUTSIDE its request accounting: a warm holds no session * and no path, so neither a drain nor an idle window waits for it. */ export async function answerWarm(command, host) { if (host.draining) return refusal(command, "host_draining"); const kindError = sessionKindError(command.kind); if (kindError) return refusal(command, `${RPC_ERROR_INVALID_SESSION_KIND}: ${kindError}`); const contextError = sessionContextError(command.context); if (contextError) return refusal(command, `${RPC_ERROR_INVALID_SESSION_CONTEXT}: ${contextError}`); if (host.warm === undefined) return { id: command.id, type: "response", command: "warm", success: true, data: { state: "unsupported" } }; // The same context an open on this host would hand its extensions: the host's identity wins. const sessionContext = host.hostContext ? { ...command.context, ...host.hostContext } : command.context; const cwd = command.cwd ?? host.cwd; if (!isAbsolute(cwd)) return refusal(command, RPC_ERROR_INVALID_PATH); try { const state = await host.warm({ cwd, ...(command.kind !== undefined ? { sessionKind: command.kind } : {}), ...(sessionContext !== undefined ? { sessionContext } : {}), }); return { id: command.id, type: "response", command: "warm", success: true, data: { state } }; } catch (cause) { return refusal(command, `${RPC_ERROR_WARM_FAILED}: ${cause instanceof Error ? cause.message : String(cause)}`); } } //# sourceMappingURL=host-warm.js.map