@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
61 lines • 2.27 kB
JavaScript
import { packPayload } from "./payload-wire.js";
import { TOOL_CHILD_LIMITS } from "./protocol.js";
export class JobUpdates {
#jobId;
#channel;
#writer;
#window;
#nextSeq = 0;
#acked = 0;
#waiters = [];
#ended = false;
/** The previous update's send: updates go out in call order, each packed before it takes its seq. */
#tail = Promise.resolve();
constructor(options) {
this.#jobId = options.jobId;
this.#channel = options.channel;
this.#writer = options.writer;
this.#window = options.window ?? TOOL_CHILD_LIMITS.updatesInFlight;
}
/** Sends the next update once a credit is free, after every earlier one; rejects after the job ended. */
update(value) {
const sent = this.#tail.then(() => this.#send(value));
this.#tail = sent.catch(() => undefined);
return sent;
}
async #send(value) {
while (!this.#ended && this.#nextSeq - this.#acked >= this.#window)
await new Promise((resolve) => this.#waiters.push(resolve));
if (this.#ended)
throw new Error(`update after job ${this.#jobId} ended`);
const packed = this.#writer === undefined ? { inline: true, value } : await packPayload(value, this.#writer);
if (this.#ended)
throw new Error(`update after job ${this.#jobId} ended`);
const seq = ++this.#nextSeq;
this.#channel.send(packed.inline
? {
type: "update",
jobId: this.#jobId,
seq,
...(packed.value === undefined ? {} : { value: packed.value }),
}
: { type: "update", jobId: this.#jobId, seq, valueRef: packed.ref });
}
/** The server delivered update `seq`: every update up to it holds no credit any more. */
acked(seq) {
if (seq <= this.#acked)
return;
this.#acked = Math.min(seq, this.#nextSeq);
this.#wake();
}
/** The job ended: waiting producers are released and further updates refused. */
end() {
this.#ended = true;
this.#wake();
}
#wake() {
for (const resolve of this.#waiters.splice(0))
resolve();
}
}
//# sourceMappingURL=job-updates.js.map