@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
39 lines • 1.59 kB
JavaScript
export class HistoryReductions {
constructor(source) {
this.reductions = new WeakMap();
this.source = source;
}
reduce(reducer) {
const generation = this.source.generation();
const count = this.source.count();
const previous = this.reductions.get(reducer);
if (previous !== undefined && previous.generation === generation && previous.count <= count) {
// The state was produced by this reducer, so it has type S.
const state = previous.state;
if (previous.count === count)
return state;
const appended = this.source.appendedSince(previous.count);
if (appended !== undefined)
return this.store(reducer, generation, count, this.fold(reducer, state, appended));
}
return this.store(reducer, generation, count, this.fold(reducer, reducer.initial(), this.source.readAll()));
}
/** A fold that throws may have updated the memoized state in place, so the memo goes and the next call starts over. */
fold(reducer, initial, entries) {
try {
let state = initial;
for (const entry of entries)
state = reducer.add(state, entry);
return state;
}
catch (error) {
this.reductions.delete(reducer);
throw error;
}
}
store(reducer, generation, count, state) {
this.reductions.set(reducer, { generation, count, state });
return state;
}
}
//# sourceMappingURL=session-history-reduce.js.map