UNPKG

@code-yeongyu/senpi

Version:

Coding agent CLI with read, bash, edit, write tools and session management

177 lines • 7.61 kB
import { getSdkBoundary, loadClaudeAgentSdk } from "./sdk-boundary.js"; import { logContinuityEvent } from "./session-observability.js"; import { closeSession, getOrCreateSession, getSession, } from "./session-registry.js"; import { recordSyncedStream, sentHashesForEntry } from "./session-sync.js"; const bindings = new Map(); function cloneBinding(binding) { return { ...binding, sentHashes: [...binding.sentHashes], assistantUuidByIndex: binding.assistantUuidByIndex?.map(([index, uuid]) => [index, uuid]), }; } export function evaluateAbortOutcome(receipt) { if (!receipt || typeof receipt !== "object") return "reattach"; const queued = receipt.still_queued; return Array.isArray(queued) && queued.length === 0 ? "keep" : "reattach"; } export function rememberBinding(binding) { bindings.set(binding.senpiSessionId, cloneBinding(binding)); } export function getBinding(senpiSessionId) { const binding = bindings.get(senpiSessionId); return binding ? cloneBinding(binding) : undefined; } export function forgetBinding(senpiSessionId) { bindings.delete(senpiSessionId); } /** * Reason the newest ledger record invalidated this session's binding. Held next * to the binding it replaced so the next continuity decision can name the real * cause instead of the no-record default: a restart re-reads it from the branch * (session-registry-wiring), and a committed turn retires it with the marker. */ const bindingInvalidations = new Map(); export function rememberBindingInvalidation(senpiSessionId, reason) { if (reason === undefined) bindingInvalidations.delete(senpiSessionId); else bindingInvalidations.set(senpiSessionId, reason); } export function bindingInvalidationReason(senpiSessionId) { return bindingInvalidations.get(senpiSessionId); } export function bindingFromEntry(entry, sentHashes) { return { senpiSessionId: entry.senpiSessionId, sdkSessionId: entry.sdkSessionId, sdkSessionIdConfirmed: entry.sdkSessionIdConfirmed, sentCount: entry.sentCount, sentHashes: [...sentHashes], lastAssistantUuid: entry.assistantUuidByIndex.get(entry.sentCount) ?? null, assistantUuidByIndex: [...entry.assistantUuidByIndex.entries()], accountName: entry.accountName, modelId: entry.modelId, systemPromptHash: entry.systemPromptHash, toolsetHash: entry.toolsetHash, }; } /** * Closes the live process but keeps its lineage resumable. A switch still waiting for Claude Code's confirmation is * recorded on the model it selects, so the next turn on that model resumes instead of re-sending (senpi#6411). */ export function keepBindingThenClose(senpiSessionId, reason) { const entry = getSession(senpiSessionId); if (entry) { const binding = bindingFromEntry(entry, sentHashesForEntry(entry) ?? []); rememberBinding({ ...binding, modelId: entry.pendingModelSwitch?.modelId ?? binding.modelId }); } closeSession(senpiSessionId, reason); } export async function verifyRestoredTranscript(binding, cwd, authLane) { // Only config-dir roots are private; claude-cli account dirs link `projects` to the shared root read here. if (authLane === "config-dir") return false; let messages; try { messages = await getSdkBoundary().getSessionMessages(binding.sdkSessionId, { dir: cwd }); } catch (error) { if (error instanceof Error) return false; throw error; } if (messages.length === 0 || messages.some((message) => message.session_id !== binding.sdkSessionId)) { return false; } // A restored binding with no recorded assistant turn has nothing the transcript can prove: the // store keeps only the newest boundary (`bindingFromStored` maps none when it is null), so the // binding is never resumed unchecked. It is rejected, and the session is rebuilt (senpi#2858). if (binding.lastAssistantUuid === null) return false; const anchorIndex = messages.findIndex((message) => message.type === "assistant" && message.uuid === binding.lastAssistantUuid && message.parent_tool_use_id === null); if (anchorIndex < 0) return false; // A top-level user frame after the anchored assistant is a turn the SDK transcript already // holds but the ledger never committed: the process died between pushing the message and // the assistant's commit. A plain resume from the anchor would append that user message a // second time (the in-memory retry checkpoint that forks past such an orphan is never // persisted), so the restored binding fails closed until a fork at the anchor exists // (senpi#1973). Only the count is logged, never the content. const orphanUserMessages = messages .slice(anchorIndex + 1) .filter((message) => message.type === "user" && message.parent_tool_use_id === null).length; if (orphanUserMessages > 0) { logContinuityEvent("claude_sdk_oauth_restored_transcript_orphan_tail", { orphanUserMessages }); return false; } return true; } async function awaitInitialization(entry, signal) { const initialize = entry.query.initializationResult; if (!initialize) return; if (!signal) { await initialize.call(entry.query); return; } let rejectAborted = () => { }; const aborted = new Promise((_, reject) => { rejectAborted = reject; }); const onAbort = () => { closeSession(entry.senpiSessionId, "resume_initialization_aborted"); rejectAborted(new Error("Anthropic Subscription reattach aborted")); }; if (signal.aborted) { onAbort(); } else { signal.addEventListener("abort", onAbort, { once: true }); } try { await Promise.race([initialize.call(entry.query), aborted]); } finally { signal.removeEventListener("abort", onAbort); } } /** * A new query is not a new session: `resume` re-attaches to the existing lineage. * `sessionId` must stay absent unless forking, because the SDK rejects the pair * (sdk.d.ts:1805-1808) and would otherwise silently start an unrelated session. */ export async function reattachSession(input) { // getOrCreateSession() reaches the synchronous SDK `query` through the // session-registry boundary - see sdk-boundary.lazy.ts. await loadClaudeAgentSdk(); const { binding, atUuid } = input; closeSession(binding.senpiSessionId, "reattach"); const entry = getOrCreateSession({ senpiSessionId: binding.senpiSessionId, accountName: binding.accountName, modelId: binding.modelId, systemPromptHash: binding.systemPromptHash, toolsetHash: binding.toolsetHash, options: input.options, resume: atUuid ? { sdkSessionId: binding.sdkSessionId, atUuid } : { sdkSessionId: binding.sdkSessionId }, }); try { await awaitInitialization(entry, input.signal); } catch (error) { closeSession(binding.senpiSessionId, "resume_initialization_failed"); throw error; } recordSyncedStream(entry, binding.sentHashes); for (const [index, uuid] of binding.assistantUuidByIndex ?? []) entry.assistantUuidByIndex.set(index, uuid); if (binding.lastAssistantUuid) entry.assistantUuidByIndex.set(binding.sentCount, binding.lastAssistantUuid); rememberBinding({ ...binding, sdkSessionId: entry.sdkSessionId }); return entry; } //# sourceMappingURL=session-reattach.js.map