@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
73 lines • 2.39 kB
JavaScript
import { decodeUtf8, encodeUtf8, utf8ByteLength as byteLength } from "./encoding.js";
const MAX_PENDING_TAIL_CHUNKS = 10;
export class TailWindow {
constructor(maxBytes) {
this.chunks = [];
this.bytes = 0;
this.startsAtBoundary = true;
this.maxBytes = maxBytes;
}
append(text, bytes, startsAtLineBoundary) {
if (bytes === 0) {
return;
}
if (bytes >= this.maxBytes) {
this.replaceWithTail(text, startsAtLineBoundary);
return;
}
this.chunks.push(text);
this.bytes += bytes;
if (this.chunks.length > MAX_PENDING_TAIL_CHUNKS) {
this.compact();
}
if (this.bytes > this.maxBytes * 2) {
this.trimToMax();
}
}
text() {
this.trimToMax();
return this.joined();
}
get startsAtLineBoundary() {
return this.startsAtBoundary;
}
replaceWithTail(text, startsAtLineBoundary) {
const buffer = encodeUtf8(text);
let start = Math.max(0, buffer.length - this.maxBytes);
while (start < buffer.length && (buffer[start] & 0xc0) === 0x80) {
start++;
}
this.startsAtBoundary = start === 0 ? startsAtLineBoundary : buffer[start - 1] === 0x0a;
const tail = decodeUtf8(buffer.subarray(start));
this.chunks = tail.length > 0 ? [tail] : [];
this.bytes = byteLength(tail);
}
joined() {
if (this.chunks.length === 0) {
return "";
}
if (this.chunks.length > 1) {
this.compact();
}
return this.chunks[0] ?? "";
}
compact() {
const joined = this.chunks.join("");
this.chunks = joined.length > 0 ? [joined] : [];
}
trimToMax() {
if (this.bytes <= this.maxBytes) {
return;
}
const buffer = encodeUtf8(this.joined());
let start = Math.max(0, buffer.length - this.maxBytes);
while (start < buffer.length && (buffer[start] & 0xc0) === 0x80) {
start++;
}
this.startsAtBoundary = start === 0 ? this.startsAtBoundary : buffer[start - 1] === 0x0a;
const tail = decodeUtf8(buffer.subarray(start));
this.chunks = tail.length > 0 ? [tail] : [];
this.bytes = byteLength(tail);
}
}
//# sourceMappingURL=tail-window.js.map