UNPKG

@code-yeongyu/senpi

Version:

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

79 lines • 3.02 kB
export const isBarrier = (item) => "kind" in item; /** One socket's FIFO: records charged by their bytes, barriers weighing nothing. */ export class SocketEventQueue { constructor() { this.items = []; this.charged = 0; } get bytes() { return this.charged; } get length() { return this.items.length; } push(item) { this.items.push(item); if (!isBarrier(item)) this.charged += item.bytes; } shift() { const item = this.items.shift(); if (item !== undefined && !isBarrier(item)) this.charged -= item.bytes; return item; } /** A record takes its place ahead of `before` while that is still queued, else the tail. */ insertBefore(before, entry) { const at = this.items.indexOf(before); if (at < 0) this.items.push(entry); else this.items.splice(at, 0, entry); this.charged += entry.bytes; } /** * Lossless supersession of the queued record with `key`. The old behaviour replaced the queued line * outright, which threw away every delta a stalled reader had not yet received (a desktop client * assembles text from deltas). Keep the superseded record - demoted to its delta-only form when the * producer supplied one - and let only the newest record carry the snapshot. */ supersede(key) { const existing = this.items.find((item) => !isBarrier(item) && item.key === key); if (existing === undefined || isBarrier(existing)) return; if (existing.demotedLine !== undefined) { this.charged -= existing.bytes; existing.line = existing.demotedLine; existing.bytes = Buffer.byteLength(existing.line); this.charged += existing.bytes; existing.demotedLine = undefined; // The enqueued line never reaches the peer (an event lease it named is released, S13a review). existing.onWritten?.(false); existing.onWritten = undefined; } existing.key = undefined; } /** Keeps the items `keep` accepts; every other record is released (`onWritten(false)`) and every other barrier ended. */ retain(keep) { const kept = []; for (const item of this.items) { if (keep(item)) kept.push(item); else if (isBarrier(item)) item.barrier.cancel(); else item.onWritten?.(false); } this.items = kept; this.charged = kept.reduce((bytes, item) => (isBarrier(item) ? bytes : bytes + item.bytes), 0); } /** Ends every barrier and empties the queue; the dropped records' callbacks never run. */ clear() { for (const item of this.items) if (isBarrier(item)) item.barrier.cancel(); this.items.length = 0; this.charged = 0; } } //# sourceMappingURL=socket-event-queue.js.map