UNPKG

@code-yeongyu/senpi

Version:

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

296 lines • 13.4 kB
/** * The manifest write side: `createTerminalManifestStore` plus `TerminalManifestWriter`, * persisting ONLY lifecycle transitions and debounced checkpoints of the record shaped in * `terminal-manifest-model.ts` — never per-line output and never a runtime handle. */ import { unlink } from "node:fs/promises"; import { join } from "node:path"; import { createSidecarStore } from "../../../session-sidecar-store.js"; import { DURABLE_MONITOR_EXPIRY_MS } from "./shared.js"; import { TERMINAL_MANIFEST_CHECKPOINT_DEBOUNCE_MS, TERMINAL_MANIFEST_VERSION, } from "./terminal-manifest-model.js"; import { parseTerminalManifest } from "./terminal-manifest-parse.js"; // The data model is re-exported so every importer keeps this module as the manifest's single // entry point; nothing outside had to learn the model module's path. export { DURABLE_MONITOR_EXPIRY_MS, TERMINAL_MANIFEST_CHECKPOINT_DEBOUNCE_MS, TERMINAL_MANIFEST_VERSION, } from "./terminal-manifest-model.js"; export function createTerminalManifestStore(session) { return createSidecarStore({ baseDir: join(session.getSessionDir(), "extensions", "terminal"), sessionId: session.getSessionId(), version: TERMINAL_MANIFEST_VERSION, tempPrefix: "terminal", parse: parseTerminalManifest, }); } export class TerminalManifestWriter { #sessionId; #debounceMs; #now; #entries = new Map(); #backgrounds = new Map(); #pending = new Map(); #pendingRpc = new Map(); #timer; #tail = Promise.resolve(); constructor(options) { this.store = createTerminalManifestStore(options.session); this.#sessionId = options.session.getSessionId(); this.#debounceMs = options.debounceMs ?? TERMINAL_MANIFEST_CHECKPOINT_DEBOUNCE_MS; this.#now = options.now ?? Date.now; } recordRegister(registration) { this.#entries.set(registration.monitorId, this.#entryFor(registration)); return this.#persist(); } /** * Re-adopt an entry a restore handler just brought back to life, so THIS generation's * in-memory map owns it again. Without this, the writer starts every generation empty and * the next persist (a register, a background start, a checkpoint flush, recordShutdown) * rewrites the manifest WITHOUT the restored monitors — the monitor survives one restart * and is erased on the second. * * Every persisted field is preserved verbatim, notably `createdAt` and `expiresAt`: the * durability deadline is set once at registration and a restore NEVER extends it. Only * `suspended` is cleared, because the monitor is live again in this process. * * Deliberately does NOT write: re-adoption is not a state transition, it is recovery of * state already on disk. The entry reaches the file again on the restore's own next * persist (the file class's checkpoint, any later transition, or recordShutdown), so a * restart costs zero extra writes and the write-on-transition invariant holds. */ adoptRestored(entry) { this.#entries.set(entry.monitorId, { ...entry, suspended: false }); } /** * Write the post-restore truth once: re-spawned watches carry their new runtime identity (so * the NEXT crash stops them instead of starting copies), and entries that did not come back * are gone (so they are never re-run). With nothing left, the manifest file is removed. */ persistRestored() { return this.#persist(); } /** * Reload seam (SF-2): a reload generation starts with an empty writer, and its first * transition would rewrite the manifest without the entries the previous generation * recorded. Seed the live (non-suspended) entries and background sessions from disk * without writing; a corrupt or absent manifest seeds nothing. */ async seedFromDisk() { let state; try { state = await this.store.read(); } catch { return; } if (state === null) return; for (const entry of state.monitors) if (!entry.suspended) this.#entries.set(entry.monitorId, entry); for (const background of state.backgroundSessions) this.#backgrounds.set(background.id, background); } /** * Live durable-monitor count for admission control: entries that survive a restart. * Ephemeral entries are never counted, so any number of one-shot watches can coexist * with the durable ones. */ durableCount() { let count = 0; for (const entry of this.#entries.values()) if (entry.durabilityClass !== "ephemeral") count += 1; return count; } /** * Reconcile a registry transition snapshot (the bundle's single onChange consumer * forwards it here): settle removes entries, pause/resume/rearm flips deliveryPaused. * An entry missing its stable monitorId throws — never silently skipped; entries not * registered through the tool call site are left alone (durability spec unknown). */ observeMonitorState(snapshot) { const live = new Map(); for (const entry of snapshot) { if (typeof entry.monitorId !== "string" || entry.monitorId.length === 0) { throw new Error(`terminal manifest writer saw a monitor snapshot entry without a stable monitorId (runtime id ${entry.id}); surfacing instead of silently skipping it`); } live.set(entry.monitorId, { paused: entry.paused, fireWindow: entry.fireWindow }); } let changed = false; for (const [monitorId, known] of this.#entries) { const current = live.get(monitorId); if (current === undefined) { if (known.suspended) continue; // shutdown-suspended entries are expected to be absent this.#entries.delete(monitorId); // settle: the registry transitioned it out changed = true; continue; } // The live fire window rides every state transition — notably the auto-mute pause — // so a restart re-binds the burned budget instead of a fresh one. const fireWindow = current.fireWindow ?? known.fireWindow; if (known.deliveryPaused !== current.paused || known.fireWindow.count !== fireWindow.count) { this.#entries.set(monitorId, { ...known, deliveryPaused: current.paused, fireWindow }); changed = true; } } return changed ? this.#persist() : Promise.resolve(); } /** Debounced checkpoint persist: a burst inside the window collapses into one write. */ scheduleCheckpoint(monitorId, checkpoint) { this.#pending.set(monitorId, checkpoint); this.#debounce(); } /** An rpc watch's view (hosts, statuses), debounced like a file checkpoint. */ scheduleRpcCheckpoint(monitorId, checkpoint) { this.#pendingRpc.set(monitorId, checkpoint); this.#debounce(); } #debounce() { if (this.#timer !== undefined) clearTimeout(this.#timer); this.#timer = setTimeout(() => { this.#timer = undefined; this.#absorbPending(); void this.#persist(); }, this.#debounceMs); } /** Drain: apply any pending checkpoints and await every in-flight write. */ async flush() { if (this.#timer !== undefined) { clearTimeout(this.#timer); this.#timer = undefined; } if (this.#pending.size === 0 && this.#pendingRpc.size === 0) await this.#tail; else { this.#absorbPending(); await this.#persist(); } } /** Shutdown transition: flush checkpoints and mark every live monitor suspended in one write. */ async recordShutdown() { if (this.#timer !== undefined) { clearTimeout(this.#timer); this.#timer = undefined; } this.#absorbPending(); for (const [monitorId, entry] of this.#entries) this.#entries.set(monitorId, { ...entry, suspended: true }); await this.#persist(); } /** * A graceful close (oh-my-openagent#14313): the session ended on request, so its monitors and background jobs stop * for good. Nothing is left to re-run on a reopen, and the manifest file goes away with the last entry. */ async recordClosed() { if (this.#timer !== undefined) { clearTimeout(this.#timer); this.#timer = undefined; } this.#pending.clear(); this.#pendingRpc.clear(); this.#entries.clear(); this.#backgrounds.clear(); await this.#persist(); } recordBackgroundStart(id, command, startedAtMs, runtime) { this.#backgrounds.set(id, { id, command, startedAtMs: startedAtMs ?? this.#now(), ...(runtime === undefined ? {} : { runtime }), }); return this.#persist(); } recordBackgroundExit(id) { return this.#backgrounds.delete(id) ? this.#persist() : Promise.resolve(); } #absorbPending() { for (const [monitorId, checkpoint] of this.#pending) { const entry = this.#entries.get(monitorId); if (entry) this.#entries.set(monitorId, { ...entry, lastCheckpoint: checkpoint }); } this.#pending.clear(); for (const [monitorId, rpcCheckpoint] of this.#pendingRpc) { const entry = this.#entries.get(monitorId); if (entry) this.#entries.set(monitorId, { ...entry, rpcCheckpoint }); } this.#pendingRpc.clear(); } #entryFor({ monitorId, spec, runtime, deadlineMs }) { const createdAt = this.#now(); // A spec that omits `persistent` is ephemeral: the persisted field is a boolean the // strict parse rejects as undefined, so coerce here rather than trusting the caller. const persistent = spec.persistent === true; return { monitorId, sessionId: this.#sessionId, description: spec.description, runtimeKind: spec.kind, durabilityClass: !persistent ? "ephemeral" : spec.kind === "file" ? "checkpointed-file" : spec.kind === "rpc" ? "checkpointed-rpc" : "restartable-command", command: spec.kind === "command" ? spec.command : undefined, path: spec.kind === "file" ? spec.path : undefined, event: spec.kind === "file" ? spec.event : undefined, filter: spec.kind === "file" ? undefined : spec.filter, humanInput: spec.kind === "command" && spec.humanInput === true ? true : undefined, ...(spec.kind === "command" && spec.wakesPerHour !== undefined ? { wakesPerHour: spec.wakesPerHour } : {}), cwd: spec.kind === "rpc" ? undefined : spec.cwd, ...(spec.kind === "rpc" ? { target: spec.target, ...(spec.events === undefined ? {} : { events: spec.events }), ...(spec.exclude === undefined ? {} : { exclude: spec.exclude }), } : {}), approvedParent: spec.kind === "file" ? spec.approvedParent : undefined, createdAt, // Absolute durability deadline for every restart-surviving entry, set once here and // never extended by a restore or a rearm. An ephemeral entry dies with the process, // so its runtime deadline stays the registry's business, not the manifest's. expiresAt: persistent ? createdAt + DURABLE_MONITOR_EXPIRY_MS : null, persistent, suspended: false, lastCheckpoint: null, deliveryPaused: false, fireWindow: { startMs: createdAt, count: 0 }, ...(runtime === undefined ? {} : { runtime }), ...(deadlineMs === undefined || persistent ? {} : { deadlineMs }), }; } /** An empty manifest carries no state worth a file: unlink instead of writing `{[],[]}`. */ async #removeFile() { try { await unlink(this.store.filePath); } catch (error) { if (!(typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT")) throw error; } this.store.clear(); } #persist() { const run = this.#tail.then(() => this.#entries.size === 0 && this.#backgrounds.size === 0 ? this.#removeFile() : this.store.write({ version: TERMINAL_MANIFEST_VERSION, sessionId: this.#sessionId, monitors: [...this.#entries.values()], backgroundSessions: [...this.#backgrounds.values()], updatedAt: this.#now(), })); this.#tail = run.then(() => undefined, (error) => { this.persistFailure = error; }); return this.#tail; } } //# sourceMappingURL=terminal-manifest.js.map