@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
190 lines • 9.2 kB
JavaScript
import { convertToLlm } from "../../../messages.js";
import { ANTHROPIC_SUBSCRIPTION_PROVIDER_ID } from "./account-management.js";
import { restoreColdSeedCalibration } from "./cold-seed-budget.js";
import { sdkModelId } from "./context-window.js";
import { BINDING_ENTRY_TYPE, BINDING_MARKER, bindingFromStoredBranch, invalidationReasonFromBranch, storedBindingFromBinding, storedBindingFromEntry, } from "./session-binding.js";
import { deleteStoredBinding, readStoredBinding, writeStoredBinding } from "./session-binding-store.js";
import { AssistantCommitBoundary, assistantContentHash, isResidentAssistant, isTerminalFailure, } from "./session-commit-boundary.js";
import { forgetBinding, getBinding, keepBindingThenClose, rememberBinding, rememberBindingInvalidation, } from "./session-reattach.js";
import { closeSession, getSession, recordBranchInfo, recordPendingFork, switchSessionModel, } from "./session-registry.js";
import { sentMessageHashes, sentMessages } from "./session-sync.js";
const commitBoundary = new AssistantCommitBoundary();
function persistBindingInvalidation(pi, sessionId, reason, divergedPath) {
pi.appendEntry?.(BINDING_ENTRY_TYPE, {
schemaVersion: 1,
invalidated: true,
reason,
...(divergedPath === undefined ? {} : { divergedPath }),
});
rememberBindingInvalidation(sessionId, reason);
}
async function invalidateBinding(pi, ctx, reason, divergedPath) {
const sessionId = ctx.sessionManager.getSessionId();
forgetBinding(sessionId);
const sessionFile = ctx.sessionManager.getSessionFile?.();
if (sessionFile)
await deleteStoredBinding(sessionFile);
persistBindingInvalidation(pi, sessionId, reason, divergedPath);
}
function residentEntryFor(sessionId, message) {
const entry = getSession(sessionId);
if (!entry || !isResidentAssistant(message, entry.modelId))
return undefined;
return entry;
}
export function registerSessionRegistry(pi) {
pi.on("session_start", async (event, ctx) => {
if (event.reason === "reload")
return;
const sessionId = ctx.sessionManager.getSessionId();
forgetBinding(sessionId);
rememberBindingInvalidation(sessionId, undefined);
const sessionFile = ctx.sessionManager.getSessionFile?.();
if (event.reason === "new")
return;
if (event.reason === "fork") {
if (sessionFile)
await deleteStoredBinding(sessionFile);
persistBindingInvalidation(pi, sessionId, "fork");
return;
}
if (!sessionFile)
return;
// A restart carries the ledger, not the process maps: the newest binding record
// says whether a cause is still pending (invalidation) or was retired (marker).
const branch = ctx.sessionManager.getBranch();
rememberBindingInvalidation(sessionId, invalidationReasonFromBranch(branch));
restoreColdSeedCalibration(sessionId, branch);
const stored = await readStoredBinding(sessionFile);
if (!stored)
return;
if (stored.sessionId !== sessionId) {
await deleteStoredBinding(sessionFile);
return;
}
const binding = bindingFromStoredBranch(branch, stored);
if (!binding) {
await deleteStoredBinding(sessionFile);
return;
}
rememberBinding(binding);
});
pi.on("session_compact", async (event, ctx) => {
if (!event.accepted)
return;
recordPendingFork(ctx.sessionManager.getSessionId(), "compaction");
await invalidateBinding(pi, ctx, "compaction");
});
pi.on("session_tree", async (event, ctx) => {
if (event.oldLeafId === null || event.newLeafId === null)
return;
recordBranchInfo(ctx.sessionManager.getSessionId(), {
oldLeafId: event.oldLeafId,
newLeafId: event.newLeafId,
});
await invalidateBinding(pi, ctx, "tree_changed");
});
pi.on("model_select", (event, ctx) => {
const sessionId = ctx.sessionManager.getSessionId();
// Leaving this provider is an excursion, not an invalidation: the live SDK
// session closes but the binding stays, so coming back to the same model
// reattaches at the recorded prefix instead of re-sending the whole
// conversation (senpi#1747). Identity drift still flattens on the way back.
if (event.model?.provider !== ANTHROPIC_SUBSCRIPTION_PROVIDER_ID) {
keepBindingThenClose(sessionId, "model_selected");
return;
}
// Started, not awaited: the next turn admission waits for it (senpi#6411).
if (!switchSessionModel(sessionId, event.model.id, sdkModelId(event.model))) {
keepBindingThenClose(sessionId, "model_selected");
}
});
pi.on("thinking_level_select", (_event, ctx) => {
const sessionId = ctx.sessionManager.getSessionId();
// Closing a streaming query kills the in-flight turn (oh-my-openagent#8759). Reasoning
// options are part of the toolset fingerprint, so the next admission sees the drift and
// reattaches with the new level once this turn has settled.
if (getSession(sessionId)?.activeTurn)
return;
keepBindingThenClose(sessionId, "thinking_level_selected");
});
pi.on("message_update", (event, ctx) => {
if (event.message.role !== "assistant")
return;
const sessionId = ctx.sessionManager.getSessionId();
if (residentEntryFor(sessionId, event.message)) {
commitBoundary.captureProviderFinal(sessionId, event.message);
}
});
pi.on("message_end", async (event, ctx) => {
if (event.message.role !== "assistant")
return;
const sessionId = ctx.sessionManager.getSessionId();
const entry = getSession(sessionId);
const binding = getBinding(sessionId);
const modelId = entry?.modelId ?? binding?.modelId;
if (!modelId)
return;
if (isTerminalFailure(event.message)) {
commitBoundary.forget(sessionId);
return;
}
const { outcome, divergedPath } = commitBoundary.commit(sessionId, event.message, modelId);
if (outcome === "rewritten") {
recordPendingFork(sessionId, "assistant_rewritten", divergedPath);
await invalidateBinding(pi, ctx, "assistant_rewritten", divergedPath);
return;
}
// Only an assistant this provider actually produced may anchor a record.
if (outcome !== "clean")
return;
const sessionFile = ctx.sessionManager.getSessionFile?.();
if (!sessionFile || !pi.appendEntry)
return;
const context = ctx.sessionManager.buildSessionContext();
const hashes = sentMessageHashes(sentMessages({ ...context, messages: convertToLlm(context.messages) }));
const committedAssistantHash = assistantContentHash(event.message);
const recordFor = (markerEntryId) => {
const anchor = {
sessionPath: sessionFile,
sessionId,
markerEntryId,
assistantContentHash: committedAssistantHash,
};
return entry
? storedBindingFromEntry(entry, hashes, anchor)
: binding
? storedBindingFromBinding(binding, hashes, anchor)
: undefined;
};
// Validate before touching the branch: a rejected closed-entry fallback must
// not leave a marker-only entry that retires the still-valid older sidecar.
if (!recordFor("pending"))
return;
pi.appendEntry(BINDING_ENTRY_TYPE, BINDING_MARKER);
// The marker is now the newest ledger record, so any earlier cause is retired.
rememberBindingInvalidation(sessionId, undefined);
const markerEntryId = ctx.sessionManager.getLeafId();
if (!markerEntryId)
return;
const stored = recordFor(markerEntryId);
if (!stored)
return;
await writeStoredBinding(sessionFile, stored);
});
pi.on("session_shutdown", (event, ctx) => {
// A config hot-reload keeps the session and this module's registry (session_start skips
// "reload" above), and the resident query captures no per-load state: its hooks and tool
// handlers are module constants. The next turn's fingerprint check restarts the process
// only when the reload changed the prompt, tools or options. Closing here re-spawned Claude
// Code on every reload, and on a real account re-attached the claude.ai connectors.
if (event.reason === "reload")
return;
closeSession(ctx.sessionManager.getSessionId(), event.reason);
});
pi.on("session_extensions_removed", async (_event, ctx) => {
closeSession(ctx.sessionManager.getSessionId(), "extensions_removed");
await invalidateBinding(pi, ctx, "extensions_removed");
});
}
//# sourceMappingURL=session-registry-wiring.js.map