@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
276 lines • 10.4 kB
JavaScript
import { EngineTurnHoldNotices } from "./engine-turn-hold-notices.js";
/** Scan only ledger entries without materializing a compacted session's transcript. */
export const engineTurnHoldHistory = {
initial: () => [],
add: (entries, entry) => {
if (entry.type === "custom" &&
["session-hold", "session-notice", "session-notices-consumed"].includes(entry.customType))
entries.push(entry);
return entries;
},
};
export function engineWakeSource(customType) {
if (customType === "goal-continuation")
return "goal";
if (customType.startsWith("senpi-monitor:"))
return "monitor";
if (customType.startsWith("senpi-codemode:"))
return "codemode";
return customType;
}
/** One session-scoped hold ledger, independent of the transcript leaf. */
export class EngineTurnHold {
constructor(entries, unattended, append, notify, emit) {
this.records = new Map();
this.pauseSeq = 0;
/** The seq of the newest hold that pauses the session, which `session_paused` announced (senpi#6900). */
this.announcedSeq = 0;
this.released = [];
this.releaseBarrier = false;
this.goalDeferred = false;
this.generationValue = 0;
this.attended = !unattended;
this.append = append;
this.notify = notify;
this.emit = emit;
this.notices = new EngineTurnHoldNotices(entries, append, (error) => this.writeFailed(error));
for (const entry of entries) {
if (entry.type !== "custom" || entry.customType !== "session-hold")
continue;
const data = entry.data;
if (data.op === "add") {
this.pauseSeq = Math.max(this.pauseSeq, data.pauseSeq);
if (data.kind !== "run_fence")
this.announcedSeq = Math.max(this.announcedSeq, data.pauseSeq);
this.records.set(data.key, {
kind: data.kind,
key: data.key,
since: data.at,
data: data.data,
sourceCounts: {},
});
}
else if (data.op === "release") {
for (const key of data.keys)
this.records.delete(key);
}
}
this.pauseOpen = this.isHeld();
}
/** A run fence alone holds only wakes tagged with its run (senpi#3811), so it does not hold the session. */
isHeld() {
for (const hold of this.records.values())
if (hold.kind !== "run_fence")
return true;
return false;
}
get fences() {
return [...this.records.values()].filter((hold) => hold.kind === "run_fence");
}
get held() {
return this.isHeld();
}
get awaitingInput() {
return this.isHeld() || this.releaseBarrier;
}
get generation() {
return this.generationValue;
}
get releasing() {
return this.releaseBarrier;
}
invalidate() {
this.generationValue++;
}
attend() {
this.attended = true;
}
get holds() {
return [...this.records.values()].map((hold) => ({ ...hold, sourceCounts: this.sources }));
}
/** The seq of the newest hold added on this session; a hold's own seq is the value read right after it was added. */
get currentPauseSeq() {
return this.pauseSeq;
}
/**
* Whether a Resume quoting `expectedSeq` has seen every hold that pauses the session. Run fences raise the seq
* without pausing anything, so a seq from before a fence, up to the current one, is still current (senpi#6900).
*/
isCurrentPauseSeq(expectedSeq) {
return expectedSeq >= this.announcedSeq && expectedSeq <= this.pauseSeq;
}
getHold(key) {
const hold = this.records.get(key);
return hold ? { ...hold, sourceCounts: this.sources } : undefined;
}
get sources() {
return this.notices.sources;
}
get noticeCount() {
return this.notices.noticeCount;
}
start() {
if (!this.attended)
this.addHold("unattended");
if (this.isHeld() && this.noticeCount > 0)
this.showNotice();
}
addHold(kind, opts) {
const key = opts?.key ?? kind;
if (this.records.has(key))
return;
const at = new Date().toISOString();
this.pauseSeq++;
this.records.set(key, { kind, key, since: at, data: opts?.data, sourceCounts: {} });
let persisted = false;
try {
this.append("session-hold", {
op: "add",
kind,
key,
data: opts?.data,
pauseSeq: this.pauseSeq,
at,
});
persisted = true;
}
catch (error) {
this.writeFailed(error);
}
finally {
// A run fence alone does not pause the session, so it emits no `session_paused` (senpi#3811). Any other hold
// announces its seq, even while already paused: Resume quotes that seq, so an unannounced one could never
// be released (senpi#6900).
if (kind !== "run_fence" && this.isHeld()) {
this.announcedSeq = this.pauseSeq;
this.pauseOpen = true;
this.emit({
type: "session_paused",
pauseSeq: this.pauseSeq,
kind,
at,
noticeCount: this.noticeCount,
persisted,
});
}
if (!persisted)
this.notify("Pause could not be saved; it will not survive a restart.");
}
}
release(keys, cause) {
const present = [...new Set(keys)].filter((key) => this.records.has(key));
if (present.length === 0)
return;
const at = new Date().toISOString();
this.append("session-hold", {
op: "release",
keys: present,
observedSeq: this.pauseSeq,
cause,
at,
});
for (const key of present)
this.records.delete(key);
// A pause emits one `session_resumed` when it ends, however many `session_paused` it announced (senpi#6900); a
// fence that outlives the pause resumes nothing (senpi#3811).
if (this.pauseOpen && !this.isHeld()) {
this.pauseOpen = false;
this.emit({ type: "session_resumed", pauseSeq: this.pauseSeq, cause, at });
}
}
holdsSource(source) {
return this.isHeld() || (!this.attended && this.releaseBarrier) || (source === "goal" && this.goalDeferred);
}
note(source, message) {
const noticeId = this.notices.note(source, this.pauseSeq, message, this.stopped);
this.emit({
type: "session_notice",
noticeIds: [noticeId],
noticeCount: this.noticeCount,
disposition: "notice_persisted",
});
if (!this.attended)
this.showNotice();
}
/**
* A held itemized batch, written all-or-nothing: each item becomes its own notice with its own `session_notice`
* event, and a failed write throws with no item kept (senpi#3811 design 4.5).
*/
noteItems(items) {
const notices = this.notices.noteItems(this.pauseSeq, items, this.stopped);
for (const notice of notices)
this.emit({
type: "session_notice",
noticeIds: [notice.noticeId],
noticeCount: this.noticeCount,
disposition: "notice_persisted",
});
if (!this.attended)
this.showNotice();
return notices;
}
messages() {
return this.notices.messages();
}
releaseAll(cause) {
const sources = this.sources;
if (this.releaseBarrier || !this.isHeld())
return {};
this.generationValue++;
if (this.isHeld())
this.released = this.holds;
this.releaseBarrier = true;
this.goalDeferred = (sources.goal ?? 0) > 0;
// Neither human input nor resume_session releases a run-owned hold: only the parent's run Resume does (senpi#3811).
const keys = [...this.records.values()].filter((hold) => hold.kind !== "inherited_hold");
this.release(keys.map((hold) => hold.key), cause);
return sources;
}
/** Undo a release whose input never reached admission: lower the barrier and keep every held wake held. */
abandonRelease() {
this.releaseBarrier = false;
this.goalDeferred = false;
for (const { kind, key, data } of this.released)
this.addHold(kind, { key, data });
this.released = [];
}
rejectInput() {
this.releaseBarrier = false;
this.goalDeferred = false;
if (!this.attended)
for (const { kind, key, data } of this.released)
this.addHold(kind, { key, data });
}
consume(source, deliveredIds) {
const noticeIds = this.notices.consume(source, this.pauseSeq, deliveredIds);
if (noticeIds.length === 0)
return false;
this.emit({ type: "session_notice", noticeIds, noticeCount: this.noticeCount, disposition: "model_consumed" });
return true;
}
finish() {
const sources = this.sources;
this.notices.consumeNotices(this.pauseSeq);
// Wakes arriving after the delivery snapshot still belong to the ledger.
// Re-arm the hold rather than draining an unbounded stream in this release.
if (this.messages().length > 0) {
this.rejectInput();
return sources;
}
this.consume("goal");
this.goalDeferred = false;
this.releaseBarrier = false;
this.released = [];
return sources;
}
get stopped() {
return [...this.records.values()].some((hold) => hold.kind === "session_hold");
}
showNotice() {
this.notify(this.notices.noticeText(this.noticeCount, undefined, this.stopped));
}
writeFailed(error) {
console.warn("session_hold_write_failed", error instanceof Error ? error.message : String(error));
}
}
//# sourceMappingURL=engine-turn-hold.js.map