UNPKG

@code-yeongyu/senpi

Version:

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

160 lines • 7.28 kB
import { createHash } from "node:crypto"; import { appendSdkContentBlocks, neutralizeToolResultText } from "./content-blocks.js"; import { longContextAvailable } from "./long-context.js"; import { imageNeutralContent } from "./sent-image-slots.js"; import { HOST_TOOL_POLICY_FINGERPRINT, mapPiToolNameToSdk } from "./tools.js"; const sentHashesByEntry = new WeakMap(); function stableValue(value, seen = new WeakSet()) { if (typeof value === "function") return `[function:${value.name}:${value.toString()}]`; if (typeof value === "bigint") return value.toString(); if (value === null || typeof value !== "object") return value; if (seen.has(value)) return "[circular]"; seen.add(value); const normalized = Array.isArray(value) ? value.map((item) => stableValue(item, seen)) : Object.fromEntries(Object.entries(value) .filter(([, item]) => item !== undefined) .sort(([left], [right]) => left.localeCompare(right)) .map(([key, item]) => [key, stableValue(item, seen)])); seen.delete(value); return normalized; } function digest(value) { return createHash("sha256") .update(JSON.stringify(stableValue(value))) .digest("hex"); } export function sessionSyncDigest(value) { return digest(value); } /** * A user message with no content blocks carries nothing to transmit and is * transient: it is present for a single provider call and gone by the next. * Hashing one shifts every later index, so the following turn reports * `sent_stream_diverged` and re-sends the whole history even though the * conversation never changed. Tool results are never filtered - an empty tool * result is a real observation, and its id and name stay hash-significant. */ function isContentlessUserMessage(message) { if (message.role !== "user") return false; // Only a literal zero-block array is content-less. Whitespace-only text and // explicit empty-text blocks still emit transport blocks, so they must stay // hash-significant to keep divergence detection fail-closed. return Array.isArray(message.content) && message.content.length === 0; } export function sentMessages(context) { return context.messages.filter(isTransmittedMessage); } /** * The one selection rule for "message the provider was sent". Branch-derived and * context-derived hashes MUST share it: a content-less user message that only one * side skips shifts every later index and reports a false divergence. */ export function isTransmittedMessage(message) { if (message.role !== "user" && message.role !== "toolResult") return false; return !isContentlessUserMessage(message); } /** * Applies the transmitted-message rule itself, so no caller can produce a hash * list that disagrees with another caller's by forgetting the filter. */ export function sentMessageHashes(messages) { const hashes = messages.filter(isTransmittedMessage).map((message) => digest(message.role === "user" ? { role: message.role, content: imageNeutralContent(message.content) } : { role: message.role, toolCallId: message.toolCallId, toolName: message.toolName, content: imageNeutralContent(message.content), })); return hashes; } export function sentHashPrefixDigest(hashes, count = hashes.length) { return digest(hashes.slice(0, count)); } /** Pure divergence guard: every non-proven continuation resolves to cold-seed. */ export function sentHashesForEntry(entry) { return sentHashesByEntry.get(entry); } export function recordSyncedStream(entry, hashes) { const copy = [...hashes]; sentHashesByEntry.set(entry, copy); entry.sentCount = copy.length; entry.syncedPrefixHash = sentHashPrefixDigest(copy); entry.branchInfo = null; } export function configFingerprint(options, context, authLane, accountName) { return { systemPromptHash: digest(options.systemPrompt ?? null), toolsetHash: digest({ tools: options.tools ?? [], reasoning: { thinking: options.thinking, effort: options.effort, maxThinkingTokens: options.maxThinkingTokens, }, contextTools: (context.tools ?? []).map((tool) => ({ name: tool.name, description: tool.description, parameters: tool.parameters, })), cwd: options.cwd, authLane, accountName, permissionMode: options.permissionMode, // The compaction owner (`autoCompactEnabled`) is fixed at spawn: a changed owner must // restart the resident process, or the old owner keeps compacting next to the new one. settings: options.settings, // Bump HOST_TOOL_POLICY_FINGERPRINT in tools.ts when denial copy or hooks change. hostToolPolicy: HOST_TOOL_POLICY_FINGERPRINT, settingSources: options.settingSources, // A refused 1M window must restart the resident process at the standard one (senpi#3408). Only // the refusal state is hashed: a live model switch reaches the process through setModel. longContextRefused: !longContextAvailable(), // Claude Code reads its window once at spawn, so a switch to a model planned at another window // restarts the resident process at that window instead of keeping the old one (senpi#3801). contextWindow: options.env?.CLAUDE_CODE_MAX_CONTEXT_TOKENS, // Claude Code reads its endpoint once at spawn, so a changed models.json baseUrl restarts the resident // process; unset (no override) drops out of the digest and leaves existing fingerprints unchanged. baseUrl: options.env?.ANTHROPIC_BASE_URL, extraArgs: options.extraArgs, pathToClaudeCodeExecutable: options.pathToClaudeCodeExecutable, includePartialMessages: options.includePartialMessages, }), }; } function appendContent(blocks, content) { // The delta path has always transmitted a whole-content empty string as an // empty text block; keep that wire shape so resident sessions see the same // payload as before the shared mapper (prompt-bridge intentionally skips it). if (content === "") { blocks.push({ type: "text", text: "" }); return; } appendSdkContentBlocks(blocks, content); } export function buildDeltaPromptBlocks(messages, customToolNameToSdk) { const blocks = []; for (const [index, message] of messages.entries()) { if (index > 0) blocks.push({ type: "text", text: "\n\n" }); if (message.role === "toolResult") { blocks.push({ type: "text", text: `Tool result (${mapPiToolNameToSdk(message.toolName, customToolNameToSdk)}, id=${message.toolCallId}):\n`, }); } const contentStart = blocks.length; appendContent(blocks, message.content); if (message.role === "toolResult") neutralizeToolResultText(blocks, contentStart); } return blocks; } //# sourceMappingURL=session-sync.js.map