UNPKG

@code-yeongyu/senpi

Version:

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

262 lines • 11.1 kB
import { randomBytes } from "node:crypto"; import { getSdkBoundary } from "./sdk-boundary.js"; import { annotateBranchInfo, annotatePendingFork, annotateTainted, switchEntryModel, } from "./session-entry-annotations.js"; import { recordPendingCloseCause } from "./session-observability.js"; import { SessionReapScheduler } from "./session-reaper.js"; import { transitionToClosed, transitionToClosing, } from "./session-registry-state.js"; export const SESSION_REGISTRY_IDLE_TTL_MS = 30 * 60_000; export const SESSION_REGISTRY_MAX_ENTRIES = 32; class StreamingInputController { constructor() { this.closed = false; this.pending = []; this.readers = []; } [Symbol.asyncIterator]() { return this; } next() { const message = this.pending.shift(); if (message) return Promise.resolve({ value: message, done: false }); if (this.closed) return Promise.resolve({ value: undefined, done: true }); return new Promise((resolve) => this.readers.push(resolve)); } push(message) { if (this.closed) throw new Error("Cannot push to a closed session input controller"); const reader = this.readers.shift(); if (reader) reader({ value: message, done: false }); else this.pending.push(message); } close() { if (this.closed) return; this.closed = true; for (const reader of this.readers.splice(0)) reader({ value: undefined, done: true }); } } const defaultSessionRegistryBoundary = { now: () => Date.now(), queryFactory: (input) => getSdkBoundary().query(input), scheduleReap: (callback, delayMs) => { const timer = setTimeout(callback, delayMs); return { cancel: () => clearTimeout(timer), unref: () => timer.unref() }; }, }; let activeSessionRegistryBoundary = defaultSessionRegistryBoundary; export function overrideSessionRegistryBoundary(override) { activeSessionRegistryBoundary = { ...defaultSessionRegistryBoundary, ...override }; } export function resetSessionRegistryBoundary() { activeSessionRegistryBoundary = defaultSessionRegistryBoundary; } export class SessionRegistryResourceLimitError extends Error { constructor() { super(`Anthropic Subscription session registry is at its ${SESSION_REGISTRY_MAX_ENTRIES}-entry limit with no idle session to evict`); this.code = "session_registry_capacity"; this.name = "SessionRegistryResourceLimitError"; } } export function createSessionUuid(now = Date.now()) { const ts = BigInt(Math.trunc(now)); const bytes = randomBytes(10); const hex = [ ((ts >> 40n) & 0xffn).toString(16).padStart(2, "0"), ((ts >> 32n) & 0xffn).toString(16).padStart(2, "0"), ((ts >> 24n) & 0xffn).toString(16).padStart(2, "0"), ((ts >> 16n) & 0xffn).toString(16).padStart(2, "0"), ((ts >> 8n) & 0xffn).toString(16).padStart(2, "0"), (ts & 0xffn).toString(16).padStart(2, "0"), (0x70 | (bytes[0] & 0x0f)).toString(16).padStart(2, "0"), bytes[1].toString(16).padStart(2, "0"), (0x80 | (bytes[2] & 0x3f)).toString(16).padStart(2, "0"), bytes[3].toString(16).padStart(2, "0"), ...Array.from(bytes.slice(4), (byte) => byte.toString(16).padStart(2, "0")), ].join(""); return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`; } function evictable(entry) { return (entry.state === "IDLE_SYNCED" || entry.state === "TAINTED") && entry.activeTurn === null; } export class AnthropicSubscriptionSessionRegistry { constructor() { this.entries = new Map(); /** * Monotonic per-registry generation counter. Numbers are never reused for * a session id, so stale async work gated on `isCurrentGeneration` cannot be * mistaken for current after a close/reopen cycle. A per-id map of last-used * numbers would grow once per distinct session id for process lifetime; * this counter provides the same (stronger, process-wide) uniqueness with no * residue at all. */ this.generationCounter = 0; this.reaper = new SessionReapScheduler({ now: () => activeSessionRegistryBoundary.now(), scheduleTimer: (callback, delayMs) => activeSessionRegistryBoundary.scheduleReap(callback, delayMs), idleTtlMs: SESSION_REGISTRY_IDLE_TTL_MS, candidate: (senpiSessionId, generation) => { const entry = this.entries.get(senpiSessionId); if (!entry || entry.generation !== generation || !evictable(entry)) return undefined; return { generation: entry.generation, lastUsedAt: entry.lastUsedAt }; }, expire: (senpiSessionId) => this.closeSession(senpiSessionId, "idle_ttl"), }); } get size() { return this.entries.size; } get(senpiSessionId) { return this.entries.get(senpiSessionId); } getOrCreate(input) { const existing = this.entries.get(input.senpiSessionId); if (existing) { const now = activeSessionRegistryBoundary.now(); if (!evictable(existing) || now - existing.lastUsedAt < SESSION_REGISTRY_IDLE_TTL_MS) { this.touch(existing); return existing; } this.closeSession(existing.senpiSessionId, "idle_ttl"); } this.evictExpired(); this.ensureCapacity(); const now = activeSessionRegistryBoundary.now(); const generation = ++this.generationCounter; const sdkSessionId = input.resume?.sdkSessionId ?? createSessionUuid(now); const inputController = new StreamingInputController(); const lineageOptions = input.resume ? { resume: input.resume.sdkSessionId, ...(input.resume.atUuid ? { resumeSessionAt: input.resume.atUuid, forkSession: true } : {}), } : { sessionId: sdkSessionId }; const query = activeSessionRegistryBoundary.queryFactory({ prompt: inputController, options: { ...input.options, ...lineageOptions, extraArgs: { ...input.options.extraArgs, "replay-user-messages": "" }, }, }); const { resume: _resume, ...entryInput } = input; const target = { ...entryInput, sdkSessionId, sdkSessionIdConfirmed: input.resume !== undefined, generation, query, inputController, pumpTask: null, state: "STARTING", activeTurn: null, syncedPrefixHash: null, sentCount: 0, assistantUuidByIndex: new Map(), branchInfo: null, taintedReason: null, pendingForkReason: null, pendingForkDivergedPath: null, lastUsedAt: now, }; // oxlint-disable-next-line eslint/prefer-const -- a closure reads it; const would throw in the TDZ if that closure ran before the assignment, so the rewrite is reviewed separately let entry; entry = new Proxy(target, { set: (current, property, value) => { if (this.entries.get(current.senpiSessionId) !== entry) return true; const previousTurn = current.activeTurn; Reflect.set(current, property, value); if (property === "activeTurn" && previousTurn !== value) { this.recordUse(entry, value === null); } return true; }, }); this.entries.set(input.senpiSessionId, entry); return entry; } touch(entry) { this.recordUse(entry, entry.activeTurn === null && evictable(entry)); } closeSession(senpiSessionId, reason) { const entry = this.entries.get(senpiSessionId); if (!entry) return; recordPendingCloseCause(senpiSessionId, reason); this.reaper.cancel(senpiSessionId, entry.generation); transitionToClosing(entry); entry.inputController.close(); try { entry.query.close(); } finally { transitionToClosed(entry); this.reaper.cancel(senpiSessionId, entry.generation); this.entries.delete(senpiSessionId); } } isCurrentGeneration(senpiSessionId, generation) { return this.entries.get(senpiSessionId)?.generation === generation; } evictExpired() { const now = activeSessionRegistryBoundary.now(); for (const entry of [...this.entries.values()]) { if (evictable(entry) && now - entry.lastUsedAt >= SESSION_REGISTRY_IDLE_TTL_MS) { this.closeSession(entry.senpiSessionId, "idle_ttl"); } } } recordUse(entry, scheduleReap) { if (this.entries.get(entry.senpiSessionId) !== entry) return; entry.lastUsedAt = activeSessionRegistryBoundary.now(); this.reaper.cancel(entry.senpiSessionId, entry.generation); if (scheduleReap) this.reaper.arm(entry.senpiSessionId, entry.generation); } ensureCapacity() { if (this.entries.size < SESSION_REGISTRY_MAX_ENTRIES) return; const oldest = [...this.entries.values()] .filter(evictable) .sort((left, right) => left.lastUsedAt - right.lastUsedAt)[0]; if (!oldest) throw new SessionRegistryResourceLimitError(); this.closeSession(oldest.senpiSessionId, "capacity"); } } export const sessionRegistry = new AnthropicSubscriptionSessionRegistry(); export function getOrCreateSession(input) { return sessionRegistry.getOrCreate(input); } export function getSession(senpiSessionId) { return sessionRegistry.get(senpiSessionId); } export function closeSession(senpiSessionId, reason) { sessionRegistry.closeSession(senpiSessionId, reason); } export function isIdleExpired(entry) { return activeSessionRegistryBoundary.now() - entry.lastUsedAt >= SESSION_REGISTRY_IDLE_TTL_MS; } export function markTainted(senpiSessionId, reason) { annotateTainted(sessionRegistry, senpiSessionId, reason); } export function switchSessionModel(senpiSessionId, modelId, sdkModel) { return switchEntryModel(sessionRegistry, senpiSessionId, modelId, sdkModel); } export function recordPendingFork(senpiSessionId, reason, divergedPath) { annotatePendingFork(sessionRegistry, senpiSessionId, reason, divergedPath); } export function recordBranchInfo(senpiSessionId, info) { annotateBranchInfo(sessionRegistry, senpiSessionId, info); } export function isCurrentGeneration(senpiSessionId, generation) { return sessionRegistry.isCurrentGeneration(senpiSessionId, generation); } //# sourceMappingURL=session-registry.js.map