@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
144 lines • 6.15 kB
JavaScript
/**
* The spec requests of one session's jobs: decides when a job is due (`request-policy.ts`), sends
* the redacted request to the injected author, validates the answer with a dry run, retries once
* with the errors, and enforces the session's in-flight and hourly caps. No I/O of its own: the
* clock, the author and the line matcher are injected.
* Ported from oh-my-pi 9df0457b31 `job-widgets/registry.ts` (MIT, Copyright Can Boluk et al.).
*/
import { createWidgetRedactor, redactAuthorRequest, } from "./author-redact.js";
import { JOB_WIDGET_REQUEST_LIMITS, newAuthoringState, planRequest, REQUEST_WINDOW_MS, } from "./request-policy.js";
import { sampleLines } from "./source-stats.js";
import { jobWidgetSkip, validateJobWidgetSpec } from "./spec-validate.js";
const ROUNDS = 2;
/** Where a spec's constant totals and targets may come from, besides the samples. */
function statedText(brief) {
return [brief.command, brief.task, brief.intent, brief.watch, brief.stage].filter(Boolean).join("\n");
}
export class JobWidgetRequestController {
#author;
#matcher;
#now;
#limits;
#redact;
#states = new Map();
#aborts = new Map();
/** Start times of author calls in the last {@link REQUEST_WINDOW_MS}, oldest first. */
#sent = [];
#inFlight = 0;
/** Until when no request starts, after the author last found no model. */
#noModelUntil = Number.NEGATIVE_INFINITY;
constructor(options) {
this.#author = options.author;
this.#matcher = options.matcher;
this.#now = options.now ?? Date.now;
this.#limits = { ...JOB_WIDGET_REQUEST_LIMITS, ...options.limits };
this.#redact = createWidgetRedactor(options.obfuscate);
}
/** Settings re-read on a re-bind: they apply from the next request on; caps already spent stay spent. */
configure(options) {
this.#limits = { ...JOB_WIDGET_REQUEST_LIMITS, ...options.limits };
this.#redact = createWidgetRedactor(options.obfuscate);
}
get inFlight() {
return this.#inFlight;
}
/** Starts the request `job` is due, or returns `undefined` when none is (or a session cap holds it back). */
maybeRequest(job) {
const now = this.#now();
if (now < this.#noModelUntil)
return undefined;
if (this.#inFlight >= this.#limits.maxInFlight || !this.#windowHasRoom(now))
return undefined;
let state = this.#states.get(job.id);
if (!state) {
state = newAuthoringState();
this.#states.set(job.id, state);
}
const plan = planRequest(job, state, now, this.#limits);
return plan ? this.#run(job, state, plan) : undefined;
}
forget(jobId) {
this.#aborts.get(jobId)?.abort();
this.#aborts.delete(jobId);
this.#states.delete(jobId);
}
dispose() {
for (const controller of this.#aborts.values())
controller.abort();
this.#aborts.clear();
this.#states.clear();
}
#windowHasRoom(now) {
while (this.#sent.length > 0 && now - (this.#sent[0] ?? now) >= REQUEST_WINDOW_MS)
this.#sent.shift();
return this.#sent.length < this.#limits.maxPerHour;
}
#canSend(state) {
return state.requests < this.#limits.maxRequestsPerJob && this.#windowHasRoom(this.#now());
}
async #run(job, state, plan) {
const controller = new AbortController();
this.#aborts.set(job.id, controller);
state.inFlight = true;
this.#inFlight += 1;
try {
return await this.#rounds(job, state, plan, controller.signal);
}
catch (error) {
return controller.signal.aborted ? { kind: "aborted" } : { kind: "failed", error };
}
finally {
this.#inFlight -= 1;
state.inFlight = false;
if (this.#aborts.get(job.id) === controller)
this.#aborts.delete(job.id);
}
}
/** One request and at most one retry carrying the validation errors. */
async #rounds(job, state, plan, signal) {
const raw = {
jobId: job.id,
brief: job.brief,
sources: job.runtime.samples(),
previous: plan.previous,
};
const base = redactAuthorRequest(raw, this.#redact);
const validation = { matcher: this.#matcher, samples: sampleLines(base.sources), brief: statedText(base.brief) };
let rejected;
let errors = [];
for (let round = 0; round < ROUNDS && this.#canSend(state); round++) {
state.requests += 1;
const sentAt = this.#now();
this.#sent.push(sentAt);
const request = rejected ? redactAuthorRequest({ ...raw, rejected }, this.#redact) : base;
const answer = await this.#author(request, signal);
if (signal.aborted)
return { kind: "aborted" };
if (answer === undefined) {
// No call was made: give back the job's request and the hourly slot reserved for it.
state.requests -= 1;
const slot = this.#sent.indexOf(sentAt);
if (slot !== -1)
this.#sent.splice(slot, 1);
this.#noModelUntil = this.#now() + this.#limits.noModelRetryMs;
return { kind: "unavailable" };
}
const skip = jobWidgetSkip(answer);
if (skip !== undefined) {
state.skippedWatch = job.brief.watch ?? "";
return { kind: "skipped", reason: skip };
}
const checked = validateJobWidgetSpec(answer, validation);
if (checked.ok) {
state.specHadWatch = Boolean(job.brief.watch);
return { kind: "installed", spec: checked.spec };
}
errors = checked.errors;
rejected = { answer: JSON.stringify(answer), errors };
}
if (!job.runtime.spec)
state.stopped = true;
return { kind: "rejected", errors };
}
}
//# sourceMappingURL=request-controller.js.map