@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
193 lines • 8.36 kB
JavaScript
import { GOAL_CONTINUATION_MESSAGE_TYPE } from "../../../messages.js";
import { assistantContentHash } from "./session-commit-boundary.js";
import { sentHashPrefixDigest } from "./session-sync.js";
export const BINDING_ENTRY_TYPE = "claude-sdk-oauth-binding";
export const BINDING_MARKER = { schemaVersion: 2, marker: true };
/**
* The record is derived from the registry entry plus the hashes the branch
* actually carries, never from the process binding map: that map holds the
* previous turn's state while `message_end` runs (and only a prefix digest right
* after a restart), so reading it would anchor this turn's marker to a stale or
* absent sent-stream.
*/
export function storedBindingFromEntry(entry, hashes, anchor) {
return {
schemaVersion: 1,
sessionPath: anchor.sessionPath,
sessionId: anchor.sessionId,
markerEntryId: anchor.markerEntryId,
sdkSessionId: entry.sdkSessionId,
sentCount: hashes.length,
sentPrefixHash: sentHashPrefixDigest(hashes),
assistantContentHash: anchor.assistantContentHash,
lastAssistantUuid: entry.assistantUuidByIndex.get(hashes.length) ?? null,
accountName: entry.accountName,
modelId: entry.modelId,
systemPromptHash: entry.systemPromptHash,
toolsetHash: entry.toolsetHash,
};
}
/** Persist a completed turn whose resident registry entry closed before `message_end`. */
export function storedBindingFromBinding(binding, hashes, anchor) {
if (binding.sdkSessionIdConfirmed === false)
return undefined;
if (binding.sentCount !== hashes.length)
return undefined;
const expectedDigest = sentHashPrefixDigest(hashes);
const bindingDigest = binding.sentPrefixHash ?? (binding.sentHashes.length > 0 ? sentHashPrefixDigest(binding.sentHashes) : undefined);
if (bindingDigest === undefined || bindingDigest !== expectedDigest)
return undefined;
return {
schemaVersion: 1,
sessionPath: anchor.sessionPath,
sessionId: anchor.sessionId,
markerEntryId: anchor.markerEntryId,
sdkSessionId: binding.sdkSessionId,
sentCount: hashes.length,
sentPrefixHash: sentHashPrefixDigest(hashes),
assistantContentHash: anchor.assistantContentHash,
lastAssistantUuid: binding.lastAssistantUuid,
accountName: binding.accountName,
modelId: binding.modelId,
systemPromptHash: binding.systemPromptHash,
toolsetHash: binding.toolsetHash,
};
}
/**
* Reason carried by the newest binding ledger record, when that record is an
* invalidation. A marker appended later retires it: the marker means a turn
* re-established the binding, so no cause is pending any more.
*/
export function invalidationReasonFromBranch(branch) {
const index = newestBindingEntryIndex(branch);
if (index < 0)
return undefined;
const data = branch[index]?.data;
return isBindingInvalidation(data) ? data.reason : undefined;
}
function isBindingInvalidation(value) {
if (typeof value !== "object" || value === null)
return false;
return "invalidated" in value && value.invalidated === true && "reason" in value && typeof value.reason === "string";
}
export function bindingFromStoredBranch(branch, stored) {
const markerIndex = newestBindingEntryIndex(branch);
if (markerIndex < 0)
return undefined;
const marker = branch[markerIndex];
if (marker?.id !== stored.markerEntryId || !isBindingMarker(marker.data))
return undefined;
const assistantIndex = committedAssistantIndex(branch, markerIndex + 1);
if (assistantIndex < 0 || !branch.slice(assistantIndex + 1).every(isAppendOnlyTailEntry))
return undefined;
const committedAssistant = branch[assistantIndex]?.message;
if (!isAssistantMessage(committedAssistant))
return undefined;
if (assistantContentHash(committedAssistant) !== stored.assistantContentHash)
return undefined;
return bindingFromStored(stored);
}
/**
* The marker is appended inside `message_end`, so handlers that run after this
* builtin (and extensions loaded later) can append ledger entries before the
* assistant itself persists. The committed assistant is the first message after
* the marker; anything that reaches the model in between fails closed.
*/
function committedAssistantIndex(branch, from) {
for (let index = from; index < branch.length; index += 1) {
const entry = branch[index];
if (entry?.type === "message")
return index;
if (!entry || !isLedgerOnlyEntry(entry))
return -1;
}
return -1;
}
/**
* Entry types the session-manager never projects into the LLM context. They
* cannot shift the sent-stream digest the binding is verified against, so any
* `custom` ledger record (hook state, rule scans, memory bookkeeping, ...) is
* admitted regardless of who wrote it. Everything the model can see - messages,
* custom messages other than the goal continuation, compaction and branch
* summaries - keeps failing closed (oh-my-openagent#7925).
*/
const LEDGER_ONLY_ENTRY_TYPES = new Set([
"custom",
"label",
"session_info",
"thinking_level_change",
"model_change",
// A refused switch (#1526) is bookkeeping the model never sees; omitting it
// here made recording the refusal destroy the stored binding on resume.
"model_change_rejected",
"configuration_update",
]);
function isLedgerOnlyEntry(entry) {
if (entry.type === "custom_message")
return entry.customType === GOAL_CONTINUATION_MESSAGE_TYPE;
return LEDGER_ONLY_ENTRY_TYPES.has(entry.type);
}
/**
* Entries the anchor may be followed by: they extend the branch without rewriting the committed
* assistant. A `custom_message` never reaches this lane's wire at all (`isTransmittedMessage`
* admits only `user` and `toolResult`), and a later `user` / `toolResult` is an unsent delta whose
* safety `decideNativeContinuity` already proves by comparing `sentPrefixHash` before it resumes.
* Retiring the binding for either duplicated that check and charged a full re-send for it
* (senpi#1964). A later assistant, a compaction, a branch summary and an explicit invalidation
* still fail closed, here or in the checks around this one.
*/
function isAppendOnlyTailEntry(entry) {
if (isLedgerOnlyEntry(entry))
return true;
if (entry.type === "custom_message")
return true;
if (entry.type !== "message")
return false;
const message = entry.message;
if (typeof message !== "object" || message === null || !("role" in message))
return false;
return message.role === "user" || message.role === "toolResult";
}
function newestBindingEntryIndex(branch) {
for (let index = branch.length - 1; index >= 0; index -= 1) {
const entry = branch[index];
if (entry?.type === "custom" && entry.customType === BINDING_ENTRY_TYPE)
return index;
}
return -1;
}
function isBindingMarker(value) {
if (typeof value !== "object" || value === null)
return false;
return "schemaVersion" in value && value.schemaVersion === 2 && "marker" in value && value.marker === true;
}
function isAssistantMessage(value) {
if (typeof value !== "object" || value === null)
return false;
return ("role" in value &&
value.role === "assistant" &&
"api" in value &&
typeof value.api === "string" &&
"provider" in value &&
typeof value.provider === "string" &&
"model" in value &&
typeof value.model === "string" &&
"content" in value &&
Array.isArray(value.content));
}
function bindingFromStored(stored) {
return {
senpiSessionId: stored.sessionId,
sdkSessionId: stored.sdkSessionId,
sentCount: stored.sentCount,
sentHashes: [],
sentPrefixHash: stored.sentPrefixHash,
lastAssistantUuid: stored.lastAssistantUuid,
assistantUuidByIndex: stored.lastAssistantUuid === null ? [] : [[stored.sentCount, stored.lastAssistantUuid]],
accountName: stored.accountName,
modelId: stored.modelId,
systemPromptHash: stored.systemPromptHash,
toolsetHash: stored.toolsetHash,
};
}
//# sourceMappingURL=session-binding.js.map