@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
73 lines • 2.36 kB
JavaScript
/**
* Single-consumer queue with backpressure: once `capacity` values wait, the producer awaits `writable()` before it
* reads more from its source, so a long streamed tool call never overflows it (senpi#2822).
*/
export const SESSION_STREAM_QUEUE_CAPACITY = 256;
export class BoundedAsyncQueue {
constructor(capacity) {
this.values = [];
this.writers = [];
this.closed = false;
this.failed = false;
this.capacity = capacity;
}
[Symbol.asyncIterator]() {
return this;
}
next() {
if (this.values.length > 0) {
const value = this.values.shift();
if (this.values.length < this.capacity)
this.releaseWriters();
return Promise.resolve({ value, done: false });
}
if (this.failed)
return Promise.reject(this.failure);
if (this.closed)
return Promise.resolve({ value: undefined, done: true });
return new Promise((resolve, reject) => {
this.reader = { resolve, reject };
});
}
push(value) {
if (this.closed || this.failed)
return;
const reader = this.reader;
if (reader) {
this.reader = undefined;
reader.resolve({ value, done: false });
return;
}
this.values.push(value);
}
/** Resolves once there is room for more values, or once the queue has ended. */
writable() {
if (this.closed || this.failed || this.values.length < this.capacity)
return Promise.resolve();
return new Promise((resolve) => this.writers.push(resolve));
}
releaseWriters() {
for (const resolve of this.writers.splice(0))
resolve();
}
close() {
if (this.closed || this.failed)
return;
this.closed = true;
this.releaseWriters();
const reader = this.reader;
this.reader = undefined;
reader?.resolve({ value: undefined, done: true });
}
fail(error) {
if (this.closed || this.failed)
return;
this.failed = true;
this.failure = error;
this.releaseWriters();
const reader = this.reader;
this.reader = undefined;
reader?.reject(error);
}
}
//# sourceMappingURL=bounded-queue.js.map