UNPKG

@code-yeongyu/senpi

Version:

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

133 lines • 6.71 kB
import { replayHistoryImages } from "./cold-seed-images.js"; import { appendSdkContentBlocks, neutralizeToolResultText } from "./content-blocks.js"; import { mapPiToolNameToSdk } from "./tools.js"; export { mapPiToolNameToSdk } from "./tools.js"; export function contentToText(content, customToolNameToSdk) { return content .map((block) => { if (block.type === "text") return block.text; if (block.type === "thinking") return block.thinking; if (block.type === "toolCall") { return `Historical tool call (non-executable): ${mapPiToolNameToSdk(block.name, customToolNameToSdk)} args=${JSON.stringify(block.arguments)}`; } return `[${block.type}]`; }) .join("\n"); } function appendContentBlocks(blocks, content) { return appendSdkContentBlocks(blocks, content); } /** * Text that closes the replayed history. Everything after it (recovered tool results, the * response instruction, the final user message) changes every turn, so it stays after the * cache breakpoint. */ export const CONVERSATION_HISTORY_CLOSER = "\n</conversation_history>"; /** * The current turn's tool images go after the history closer, past the cache breakpoint, so the history bytes stay the * same when the turn ends and these images are no longer sent (senpi#5275). */ const CURRENT_TURN_IMAGES_OPENER = "\n<current_turn_tool_images>\n"; const CURRENT_TURN_IMAGES_CLOSER = "\n</current_turn_tool_images>"; export const RESPOND_TO_USER_INSTRUCTION = 'The above is the conversation history so far, provided as context. Respond as the assistant to the user message below only. Never emit "USER:" or "ASSISTANT:" labels or continue the transcript.'; /** * A replay that ends with tool results (a model switch or fallback mid-turn) has no new user message. Saying "the * user message below" there made the model read the last tool output, often images it generated itself, as something * the user had just sent (senpi#2768). */ export const CONTINUE_TURN_INSTRUCTION = 'The above is the conversation history so far, provided as context. There is no new user message: the last entries are results of tool calls you made in your current turn, not anything the user sent. Continue that turn as the assistant. Never emit "USER:" or "ASSISTANT:" labels or continue the transcript.'; /** Claude Code drops a breakpoint set on an image, so the last text block of the history carries it. */ function markCacheBreakpoint(blocks, historyStart, ttl) { for (let index = blocks.length - 1; index >= historyStart; index--) { const block = blocks[index]; if (block?.type !== "text") continue; blocks[index] = { ...block, cache_control: { type: "ephemeral", ttl } }; return; } } export function buildPromptBlocks(context, customToolNameToSdk, toolWatchNote, options = {}) { const blocks = []; const pushText = (text) => { blocks.push({ type: "text", text }); }; const finalMessage = context.messages.at(-1); const finalUserMessage = finalMessage?.role === "user" ? finalMessage : undefined; const history = finalUserMessage ? context.messages.slice(0, -1) : context.messages; // No new user message and the history ends with tool results: a model switch or fallback inside a turn. const continuesTurn = !finalUserMessage && history.at(-1)?.role === "toolResult"; if (history.length > 0) { const historyStart = blocks.length; pushText("<conversation_history>\n"); let hasPreviousTurn = false; const pushPrefix = (label) => { pushText(`${hasPreviousTurn ? "\n\n" : ""}${label}\n`); hasPreviousTurn = true; }; const replayedImages = replayHistoryImages(history, (name) => mapPiToolNameToSdk(name, customToolNameToSdk), { inProgressTurn: continuesTurn, }); for (const [index, message] of history.entries()) { if (message.role === "user") { pushPrefix("USER:"); if (!appendContentBlocks(blocks, replayedImages.history.get(index) ?? message.content)) pushText("(see attached image)"); continue; } if (message.role === "assistant") { pushPrefix("ASSISTANT:"); const text = contentToText(message.content, customToolNameToSdk); if (text.length > 0) pushText(text); continue; } if (message.role === "configurationUpdate" || message.role === "system") continue; pushPrefix(`TOOL RESULT (historical ${mapPiToolNameToSdk(message.toolName, customToolNameToSdk)}, id=${message.toolCallId}):`); const toolResultStart = blocks.length; if (!appendContentBlocks(blocks, replayedImages.history.get(index) ?? message.content)) pushText("(see attached image)"); neutralizeToolResultText(blocks, toolResultStart); } if (options.cacheBreakpoint !== undefined) markCacheBreakpoint(blocks, historyStart, options.cacheBreakpoint); pushText(CONVERSATION_HISTORY_CLOSER); if (replayedImages.currentTurn.length > 0) { pushText(CURRENT_TURN_IMAGES_OPENER); appendContentBlocks(blocks, replayedImages.currentTurn); pushText(CURRENT_TURN_IMAGES_CLOSER); } } if (toolWatchNote?.trim()) { pushText("<recovered_tool_results>\n"); pushText(toolWatchNote.trim()); pushText("\n</recovered_tool_results>"); } pushText(history.at(-1)?.role === "toolResult" && !finalUserMessage ? CONTINUE_TURN_INSTRUCTION : RESPOND_TO_USER_INSTRUCTION); if (finalUserMessage && !appendContentBlocks(blocks, finalUserMessage.content)) pushText("(see attached image)"); return blocks; } /** * A prompt that builds its blocks each time it is iterated. A failover retry hands the same prompt to a fresh query, * and an async generator would be exhausted by then; building late also lets the blocks follow the auth lane the * attempt resolved (its pinned cache lifetime). */ export function buildDeferredPromptStream(build) { return { [Symbol.asyncIterator]: () => buildPromptStream(build())[Symbol.asyncIterator]() }; } export function buildPromptStream(promptBlocks) { return (async function* () { yield { type: "user", message: { role: "user", content: promptBlocks }, parent_tool_use_id: null, session_id: "prompt", }; })(); } //# sourceMappingURL=prompt-bridge.js.map