@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
302 lines • 12.5 kB
JavaScript
import { normalizeWaitItems, waitItemSignature } from "./lifecycle-wait-items.js";
import { custodyIsOpen, readWorkCustody } from "./work-custody-record.js";
/** Custody keys the engine opens itself (senpi#3986): queued deliveries and published wake sources. */
export const ENGINE_DELIVERY_KEY_PREFIX = "delivery:";
export const WAKE_SOURCE_KEY_PREFIX = "wake-source:";
export const ENGINE_CUSTODY_KEY_PREFIXES = [ENGINE_DELIVERY_KEY_PREFIX, WAKE_SOURCE_KEY_PREFIX];
/** A send whose delivery ticket was refused before anything was written. */
export class DeliveryTicketRefused extends Error {
constructor(ticketId, reason) {
super(`Delivery ticket ${ticketId} was refused: ${reason}`);
this.name = "DeliveryTicketRefused";
this.ticketId = ticketId;
this.reason = reason;
}
}
export class CustodyViolation extends Error {
constructor(key) {
super(`Work custody is no longer owned: ${key}`);
this.name = "CustodyViolation";
this.key = key;
}
}
/** One session's durable registry. A token never acknowledges its own delivery. */
export class SessionWorkObligations {
constructor(store) {
this.records = new Map();
this.unpersisted = new Map();
this.delivering = new Set();
/** Engine delivery custody a send opened in this process and has not queued yet (senpi#6810). */
this.sending = new Set();
this.publishedSources = new Set();
this.store = store;
for (const entry of store.entries) {
if (entry.type !== "custom" || entry.customType !== "work-custody")
continue;
const record = readWorkCustody(entry.data);
if (record)
this.records.set(record.id, record);
}
}
get active() {
return [...this.records.values()].filter(custodyIsOpen);
}
get activeCount() {
return this.active.reduce((sum, record) => sum + (record.activeCount ?? 1), 0);
}
get persisted() {
return this.unpersisted.size === 0;
}
open(key, kind, detail) {
const existing = this.active.find((record) => record.key === key);
if (existing)
return this.token(existing.id);
const record = {
id: crypto.randomUUID(),
key,
kind,
state: "open",
...(detail === undefined ? {} : { detail }),
};
if (key.startsWith(ENGINE_DELIVERY_KEY_PREFIX))
this.sending.add(record.id);
this.install(record);
this.store.changed();
return this.token(record.id);
}
/**
* An engine delivery's own custody while its send is in flight (senpi#6810): the session is starting or joining a
* turn for that delivery, so this custody is never background work the session waits on.
*/
isDeliveryInFlight(record) {
if (!record.key.startsWith(ENGINE_DELIVERY_KEY_PREFIX))
return false;
return this.sending.has(record.id) || (record.ticketId !== undefined && this.delivering.has(record.ticketId));
}
/**
* An engine delivery's own custody that the given run consumed: that run's own work until `settleRun`, so never a
* background wait, even after its delivery ended (senpi#6814 review).
*/
isConsumedBy(record, runId) {
if (runId === undefined || !record.key.startsWith(ENGINE_DELIVERY_KEY_PREFIX))
return false;
return record.state === "consumed" && record.runId === runId;
}
syncSource(source, kind, activeCount, items) {
const key = `${WAKE_SOURCE_KEY_PREFIX}${source}`;
this.publishedSources.add(key);
const current = this.active.find((record) => record.key === key);
if (activeCount <= 0) {
if (current)
this.close(current.id, "passive");
return;
}
const detail = normalizeWaitItems(items);
if (current?.activeCount === activeCount &&
current.kind === kind &&
waitItemSignature(current) === waitItemSignature(detail))
return;
this.install({
...current,
id: current?.id ?? crypto.randomUUID(),
key,
source,
kind,
activeCount,
items: detail.items,
omittedItems: detail.omittedItems,
state: current?.state ?? "open",
});
this.store.changed();
}
/** After a restart, a restored wake source stays open only if its producer published again. */
retireRestoredSources() {
for (const record of this.active) {
if (record.key.startsWith(WAKE_SOURCE_KEY_PREFIX) && !this.publishedSources.has(record.key))
this.close(record.id, "passive");
}
}
/**
* The single ticket admission check every send branch runs before it writes anything (held notices, a queued
* message, a delivery): an unknown, closed, consumed or in-delivery ticket takes no new delivery.
*/
admission(ticketId) {
const record = [...this.records.values()].find((value) => value.ticketId === ticketId);
if (!record)
return "unknown";
if (!custodyIsOpen(record))
return "closed";
if (record.state === "consumed")
return "consumed";
return this.delivering.has(ticketId) ? "delivering" : "admitted";
}
queue(ticketId, payload) {
const admission = this.admission(ticketId);
if (admission === "unknown")
throw new CustodyViolation(ticketId);
if (admission !== "admitted")
return false;
const record = this.ticketRecord(ticketId);
// A restored queued ticket is re-sent plain; it keeps the item ids its batch was recorded with (senpi#4106).
const itemIds = payload.itemIds ?? (record.state === "queued" ? record.payload?.itemIds : undefined);
this.install({
...record,
state: "queued",
payload: { ...payload, ...(itemIds ? { itemIds } : {}) },
delivery: undefined,
});
this.delivering.add(ticketId);
this.sending.delete(record.id);
this.store.changed();
return true;
}
/** The item ids a queued ticket's batch was recorded with, if any. */
queuedItemIds(ticketId) {
const record = [...this.records.values()].find((value) => value.ticketId === ticketId);
return record?.state === "queued" ? record.payload?.itemIds : undefined;
}
/**
* A delivery whose custody is still open and unconsumed (kept for a later turn) is background work again: recompute.
* A delivery its turn consumed stays that run's own work until `settleRun`, so ending it publishes nothing (senpi#6814).
*/
endDelivery(ticketId) {
if (!this.delivering.delete(ticketId))
return;
const record = [...this.records.values()].find((value) => value.ticketId === ticketId);
if (record && custodyIsOpen(record) && record.state !== "consumed")
this.store.changed();
}
passive(ticketId) {
const record = this.ticketRecord(ticketId);
if (custodyIsOpen(record))
this.close(record.id, "passive");
}
consumed(ticketId, run) {
const record = this.ticketRecord(ticketId);
if (!custodyIsOpen(record) || record.state === "consumed")
return;
this.install({ ...record, state: "consumed", ...run, delivery: undefined });
this.store.changed();
}
failed(ticketId) {
const record = this.ticketRecord(ticketId);
if (!custodyIsOpen(record) || record.state === "consumed")
return;
this.install({ ...record, state: "queued", delivery: "failed" });
this.store.changed();
}
held(ticketId, noticeId) {
const record = this.ticketRecord(ticketId);
if (custodyIsOpen(record))
this.close(record.id, "held", noticeId);
}
retire(ticketId) {
const record = this.ticketRecord(ticketId);
if (!custodyIsOpen(record) || record.state === "consumed")
return;
this.install({ ...record, state: "open", delivery: "retired", payload: undefined });
this.store.changed();
}
cancel(ticketId) {
const record = this.ticketRecord(ticketId);
if (custodyIsOpen(record) && record.state !== "consumed")
this.close(record.id, "cancelled");
}
settleRun(runId) {
for (const record of this.active) {
if (record.state === "consumed" && record.runId === runId)
this.install({ ...record, state: "settled" });
}
this.store.changed();
}
/**
* At restoration, a consumed delivery of any run other than the restored current one belongs to a run that ended:
* its message is already in the conversation, so it settles as `idle()` would have (senpi#4848). The current run's
* consumed custody stays for crash recovery and `startRun`, unless the transcript holds that run's end
* (`currentRunEnded`, senpi#7016). With no recorded run nothing proves the consuming run ended, so crash recovery
* keeps all of it.
*/
settleEndedRuns(currentRunId, currentRunEnded) {
if (currentRunId === undefined)
return;
const ended = this.active.filter((record) => record.state === "consumed" && (record.runId !== currentRunId || currentRunEnded));
for (const record of ended)
this.install({ ...record, state: "settled" });
if (ended.length > 0)
this.store.changed();
}
install(record) {
try {
this.store.append(record);
this.unpersisted.delete(record.id);
}
catch (error) {
if (!(error instanceof Error))
throw error;
this.unpersisted.set(record.id, record);
}
this.records.set(record.id, record);
}
/** A lifecycle publication cannot claim durability before its live custody is durable. */
flush() {
for (const [id, record] of this.unpersisted) {
this.store.append(record);
this.unpersisted.delete(id);
}
}
owned(id) {
const record = this.records.get(id);
if (!record || !custodyIsOpen(record))
throw new CustodyViolation(record?.key ?? id);
return record;
}
ticketRecord(ticketId) {
const record = [...this.records.values()].find((value) => value.ticketId === ticketId);
if (!record)
throw new CustodyViolation(ticketId);
return record;
}
close(id, state, noticeId) {
const record = this.owned(id);
this.sending.delete(id);
this.install({ ...record, state, ...(noticeId === undefined ? {} : { noticeId }) });
this.store.changed();
}
token(id) {
return {
transfer: (nextKey, kind) => {
const current = this.owned(id);
if (nextKey === current.key)
throw new CustodyViolation(nextKey);
const next = this.active.find((record) => record.key === nextKey) ?? {
id: crypto.randomUUID(),
key: nextKey,
kind: kind ?? current.kind,
state: "open",
};
// Both writes are synchronous; publish only after custody has moved.
// If the second append fails, both remain open: work cannot disappear.
try {
this.install(next);
this.install({ ...current, state: "cancelled" });
}
finally {
this.store.changed();
}
return this.token(next.id);
},
ticket: () => {
const record = this.owned(id);
if (record.ticketId)
return record.ticketId;
const ticketId = crypto.randomUUID();
this.install({ ...record, state: "queued", ticketId });
this.store.changed();
return ticketId;
},
heldAsNotice: (noticeId) => this.close(id, "held", noticeId),
close: (reason) => this.close(id, reason === "consumed" ? "settled" : reason),
};
}
}
//# sourceMappingURL=work-obligations.js.map