UNPKG

@code-yeongyu/senpi

Version:

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

91 lines • 2.99 kB
const MINUTE_MS = 60_000; const BACKGROUND_AGE_FIRST_MS = 10 * MINUTE_MS; const BACKGROUND_AGE_REPEAT_MS = 30 * MINUTE_MS; const MAX_TIMER_MS = 2_147_483_647; /** The first age milestone strictly after `ageMs`. */ function nextAgeMilestoneMs(ageMs) { if (ageMs < BACKGROUND_AGE_FIRST_MS) return BACKGROUND_AGE_FIRST_MS; const repeats = Math.floor((ageMs - BACKGROUND_AGE_FIRST_MS) / BACKGROUND_AGE_REPEAT_MS) + 1; return BACKGROUND_AGE_FIRST_MS + repeats * BACKGROUND_AGE_REPEAT_MS; } export function backgroundAgeEvent(kind, subject, nowMs) { const ageMs = Math.max(0, nowMs - subject.startedAtMs); return { kind, id: subject.id, description: subject.description, ...(subject.command === undefined ? {} : { command: subject.command }), startedAtMs: subject.startedAtMs, ageMs, ageMinutes: Math.floor(ageMs / MINUTE_MS), autoReapMinutes: subject.autoReapMinutes ?? null, stop: { tool: "kill_bash", args: { bash_id: subject.id } }, }; } export class BackgroundAgeSchedule { #entries = new Map(); #onDue; #timer; constructor(onDue) { this.#onDue = onDue; } add(subject) { const now = Date.now(); this.#entries.set(subject.id, { subject, dueAtMs: subject.startedAtMs + nextAgeMilestoneMs(now - subject.startedAtMs), }); this.#arm(now); } get(id) { return this.#entries.get(id)?.subject; } remove(id) { const entry = this.#entries.get(id); if (!entry) return undefined; this.#entries.delete(id); this.#arm(Date.now()); return entry.subject; } dispose() { this.#entries.clear(); this.#clearTimer(); } #fire() { this.#timer = undefined; const now = Date.now(); const due = []; for (const entry of this.#entries.values()) { if (entry.dueAtMs > now) continue; const ageMs = now - entry.subject.startedAtMs; due.push(backgroundAgeEvent("running", entry.subject, now)); entry.dueAtMs = entry.subject.startedAtMs + nextAgeMilestoneMs(ageMs); } this.#arm(now); for (const event of due) this.#onDue(event); } #arm(now) { this.#clearTimer(); let earliest; for (const entry of this.#entries.values()) { if (earliest === undefined || entry.dueAtMs < earliest) earliest = entry.dueAtMs; } if (earliest === undefined) return; const timer = setTimeout(() => this.#fire(), Math.min(Math.max(0, earliest - now), MAX_TIMER_MS)); timer.unref?.(); this.#timer = timer; } #clearTimer() { if (this.#timer === undefined) return; clearTimeout(this.#timer); this.#timer = undefined; } } //# sourceMappingURL=background-age.js.map