@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
207 lines • 9.21 kB
JavaScript
import { reducePendingInput } from "./pending-input.js";
import { projectPendingInput } from "./pending-input-projection.js";
export const PENDING_INPUT_TRANSITION = "pending_input_transition";
/** The one owner of every pending input in a session: reduce, commit, then publish and dispatch (senpi#3549). */
export class PendingInputStore {
constructor(options) {
this.inputs = new Map();
this.listeners = new Set();
this.gate = Promise.resolve();
this.cursor = 0;
this.options = options;
}
/** Rebuilds from the complete journal, then gives every still-pending input a handle of this lifetime. */
static async open(options) {
const store = new PendingInputStore(options);
for (const record of await options.journal.read()) {
for (const input of [record.input, ...(record.batch ?? [])])
store.inputs.set(input.clientMessageId, input);
store.cursor = Math.max(store.cursor, record.cursor);
}
for (const input of [...store.inputs.values()]) {
if (input.phase === "delivered" || input.phase === "removed")
continue;
const handle = { lifetimeId: options.lifetimeId, queuedId: options.nextQueuedId() };
await store.commit(input.clientMessageId, {
type: "rebind",
handle,
attemptsUnsent: options.uncommittedAttemptsAreUnsent === true,
});
}
return store;
}
submit(event) {
return this.serialize(() => this.admit(event));
}
apply(clientMessageId, event) {
return this.serialize(() => this.commit(clientMessageId, event));
}
/** Explicit Stop over the inputs the caller saw: each named revision is removed or reported, never guessed. */
stop(items, consumerFenced) {
return this.serialize(async () => {
const removed = [];
const retained = [];
const conflicts = [];
const stale = [];
for (const item of items) {
const current = this.inputs.get(item.clientMessageId);
if (current === undefined)
continue;
// Revisions restart at 1 on every reopen, so the handle decides which version the caller saw.
if (!sameHandle(current.handle, item.handle)) {
stale.push(item.clientMessageId);
continue;
}
if (current.phase === "queued" && current.revision !== item.expectedRevision) {
conflicts.push({ clientMessageId: item.clientMessageId, currentRevision: current.revision });
continue;
}
await this.commit(item.clientMessageId, { type: "cancel", cause: "stop", consumerFenced });
const after = this.inputs.get(item.clientMessageId);
if (after?.phase === "removed" && current.phase !== "removed")
removed.push(item.clientMessageId);
else
retained.push(item.clientMessageId);
}
return { removed, conflicts, retained, stale };
});
}
/**
* Runs `work` under the gate every command shares, so a consumer can change its native buffer and the
* journal in one step that no edit, removal or other consumer can interleave with.
*/
transaction(work) {
return this.serialize(() => work({
submit: (event) => this.admit(event),
apply: (clientMessageId, event) => this.commit(clientMessageId, event),
applyAll: (changes) => this.commitMany(changes),
current: (clientMessageId) => this.inputs.get(clientMessageId),
}));
}
/** The full record of one input, for the session that owns this store. */
current(clientMessageId) {
return this.inputs.get(clientMessageId);
}
read(clientMessageId) {
const input = this.inputs.get(clientMessageId);
return input === undefined
? { status: "not_admitted", clientMessageId }
: { status: "admitted", projection: projectPendingInput(input) };
}
/** The cursor of the newest committed transition; a snapshot taken now covers everything through it. */
get throughCursor() {
return this.cursor;
}
snapshot() {
return [...this.inputs.values()].map(projectPendingInput);
}
subscribe(listener) {
this.listeners.add(listener);
return () => this.listeners.delete(listener);
}
serialize(operation) {
const guarded = () => {
if (this.unavailable !== undefined)
return Promise.reject(new PendingInputStoreUnavailableError(this.unavailable));
return operation();
};
const run = this.gate.then(guarded, guarded);
this.gate = run.catch(() => undefined);
return run;
}
admit(event) {
const handle = this.inputs.get(event.clientMessageId)?.handle ?? {
lifetimeId: this.options.lifetimeId,
queuedId: this.options.nextQueuedId(),
};
return this.commit(event.clientMessageId, { ...event, type: "submit", handle });
}
async commit(clientMessageId, event) {
return (await this.commitMany([{ clientMessageId, event }]))[0];
}
/**
* Reduces every change, then records all that changed in ONE journal record, so a crash or a failed write
* keeps either all of them or none (a consumer committing a batch never sees half of it delivered).
*/
async commitMany(changes) {
const results = [];
const committed = [];
const staged = new Map();
for (const { clientMessageId, event } of changes) {
const current = staged.get(clientMessageId) ?? this.inputs.get(clientMessageId);
const decision = reducePendingInput(current, event);
const result = decision.result?.clientMessageId === "" ? { ...decision.result, clientMessageId } : decision.result;
results.push(result);
if (decision.next === undefined || decision.effects.length === 0)
continue;
staged.set(clientMessageId, decision.next);
committed.push({ next: decision.next, decision: { ...decision, result } });
}
const [first, ...rest] = committed;
if (first === undefined)
return results;
const record = {
type: PENDING_INPUT_TRANSITION,
cursor: this.cursor + 1,
input: first.next,
...(first.decision.result === undefined ? {} : { result: first.decision.result }),
...(rest.length === 0 ? {} : { batch: rest.map((entry) => entry.next) }),
};
try {
await this.options.journal.append(record);
}
catch (error) {
// A write that may have landed cannot be retried at the same cursor, or the next reopen would see a gap:
// stop accepting commands until a reopen rebuilds the store from what the file actually holds.
if (isUncertainAppend(error))
this.unavailable = error;
throw error;
}
this.cursor = record.cursor;
for (const { next } of committed)
this.inputs.set(next.clientMessageId, next);
// One notification per record: every input it changed, under its one cursor.
const projections = committed.map(({ next }) => projectPendingInput(next));
for (const listener of this.listeners) {
try {
listener(projections, record.cursor);
}
catch (error) {
this.reportListenerError(error);
}
}
for (const { next, decision } of committed) {
for (const effect of decision.effects) {
if (effect.type === "dispatch")
this.options.dispatch?.(effect.token, next);
if (effect.type === "restore_to_draft")
this.options.restoreToDraft?.(effect.text);
}
}
return results;
}
reportListenerError(error) {
const report = this.options.onListenerError;
if (report !== undefined)
report(error);
else
queueMicrotask(() => {
throw error;
});
}
}
function isUncertainAppend(error) {
return error instanceof Error && "code" in error && error.code === "pending_input_append_uncertain";
}
/** A previous write may have landed without being synced; only a reopen can say what the journal holds. */
export class PendingInputStoreUnavailableError extends Error {
constructor(cause) {
super("Pending inputs are unavailable after a failed save; reopen the session to recover them.", { cause });
this.code = "pending_input_store_unavailable";
this.name = "PendingInputStoreUnavailableError";
}
}
function sameHandle(left, right) {
return left.lifetimeId === right.lifetimeId && left.queuedId === right.queuedId;
}
//# sourceMappingURL=pending-input-store.js.map