Something went wrong. Try again.
[READ-ONLY] Mirror of https://github.com/Aquaticat/Monochromatic. TypeScript and Rust monorepo: Claude Code and Pi coding-agent plugins, a m
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455/** Builds serialized conversation context for Advisor calls. @module */
import type { Api, AssistantMessage, Model,} from '@earendil-works/pi-ai';import { convertToLlm, serializeConversation, type SessionEntry,} from '@earendil-works/pi-coding-agent';import type { ForeignBorrowed, } from '@monochromatic-dev/ownership-marker-foreign-borrowed/ts';import { ADVISOR_MESSAGE_TYPE, ADVISOR_TOOL_NAME, CONTEXT_TRUNCATION_MARKER, DEFAULT_CONTEXT_OVERHEAD_TOKENS, TOKEN_ESTIMATE_CHARS_PER_TOKEN,} from './constants.ts';import { latestUserPromptExcerpt, NO_USER_PROMPT,} from './context-user.ts';import { buildAdvisorUserMessageText, } from './advisor-request.ts';import { estimateAdvisorInputTokens, } from '@monochromatic-dev/pi-shared-model-selection/ts';import type { AdvisorConfig, AdvisorContext, AdvisorReadonlyModel,} from './types.ts';
//region Public API
/** Agent message type accepted by {@link convertToLlm}, pi's LLM conversion helper. */type AdvisorAgentMessage = Parameters<typeof convertToLlm>[0][number];
/** Sentinel returned by {@link entryToMessage} / {@link filterMessage} when a session entry contributes no message to Advisor context (filtered Advisor artifact, current tool call, or empty content). A `unique symbol`; callers narrow with `=== MESSAGE_EXCLUDED`. */const MESSAGE_EXCLUDED: unique symbol = Symbol('advisor/current message excluded from context',);
/** Options for building Advisor context. */export type BuildAdvisorContextOptions = { /** Session branch entries from pi. */ readonly branch: readonly ForeignBorrowed<SessionEntry>[]; /** Runtime Advisor configuration. */ readonly config: AdvisorConfig; /** Advisor-model system prompt used for token estimate. */ readonly advisorSystemPrompt: string; /** Focused question supplied by the primary agent. */ readonly question?: string; /** Effective serialized-context character budget. */ readonly maxContextChars?: number; /** Current tool call id to omit from serialized context. */ readonly toolCallId?: string;};
/** Options for deriving context budget from selected Advisor model. */export type MaxContextCharsForAdvisorModelOptions = { /** Runtime Advisor configuration. */ readonly config: AdvisorConfig; /** Selected Advisor model. */ readonly model: AdvisorReadonlyModel; /** Advisor-model system prompt used for token reserve estimate. */ readonly advisorSystemPrompt: string; /** Focused question supplied by the primary agent. */ readonly question?: string;};
/** Build deterministic serialized context for an Advisor call. @param options - branch, config, and current tool call metadata @returns serialized context and metadata @example ```typescript const context = buildAdvisorContext({ branch, config, advisorSystemPrompt }); ``` */export function buildAdvisorContext( options: BuildAdvisorContextOptions,): AdvisorContext { /** Agent messages included in the secondary Advisor request. */ const messages: ForeignBorrowed<AdvisorAgentMessage>[] = []; for (const entry of options.branch) { /** Advisor-visible message converted from current session entry. */ const message = entryToMessage({ entry, includePriorAdvisorResults: options.config .includePriorAdvisorResults, ...(options.toolCallId === undefined ? {} : { currentToolCallId: options.toolCallId, }), },); if (message !== MESSAGE_EXCLUDED) messages[messages.length] = message; }
/** Serialized conversation produced by pi's compaction utility. */ const serialized = serializeConversation(convertToLlm(messages,),); /** Effective truncation budget supplied by model-aware caller or config cap. */ const maxContextChars = options.maxContextChars ?? options .config .maxContextChars ?? Number .MAX_SAFE_INTEGER; /** Truncated serialized conversation and metadata. */ const truncation = truncateContext({ text: serialized, maxChars: maxContextChars, },); /** User-message text sent to Advisor after context truncation. */ const advisorUserMessageText = buildAdvisorUserMessageText({ contextText: truncation.text, ...(options.question === undefined ? {} : { question: options.question, }), },); /** Estimated request input tokens. */ const estimatedInputTokens = estimateAdvisorInputTokens({ systemPrompt: options.advisorSystemPrompt, contextText: advisorUserMessageText, },);
/** Latest user prompt excerpt, omitted when no user prompt exists. */ const latestExcerpt = latestUserPromptExcerpt(options.branch,);
return { text: truncation.text, maxContextChars, originalChars: serialized.length, finalChars: truncation.text .length, truncated: truncation.truncated, includedMessageCount: messages.length, estimatedInputTokens, ...(latestExcerpt === NO_USER_PROMPT ? {} : { latestUserPromptExcerpt: latestExcerpt, }), };}
/** Derive serialized-context character budget for selected Advisor model. @param options - config, selected model, and system prompt @returns effective context character budget after output and overhead reserves @example ```typescript maxContextCharsForAdvisorModel({ config, model, advisorSystemPrompt }); ``` */export function maxContextCharsForAdvisorModel( options: MaxContextCharsForAdvisorModelOptions,): number { /** Non-context user-message text reserved before serialized conversation content. */ const reservedUserMessageText = buildAdvisorUserMessageText({ contextText: '', ...(options.question === undefined ? {} : { question: options.question, }), },); /** Input tokens consumed before serialized conversation content. */ const reservedInputTokens = estimateAdvisorInputTokens({ systemPrompt: options.advisorSystemPrompt, contextText: reservedUserMessageText, },) + DEFAULT_CONTEXT_OVERHEAD_TOKENS; /** Input tokens left for serialized conversation content. */ const availableContextTokens = Math.max( 1, options.model .contextWindow - options .config .maxAdvisorOutputTokens - reservedInputTokens, ); /** Model-derived serialized conversation character budget. */ const modelContextChars = Math.max( 1, availableContextTokens * TOKEN_ESTIMATE_CHARS_PER_TOKEN, );
return Math.min( options.config .maxContextChars ?? modelContextChars, modelContextChars, );}
/** Truncate context with stable head and tail preservation. @param text - text to truncate @param maxChars - maximum character budget @returns possibly truncated text and flag @example ```typescript truncateContext({ text: 'abcdef', maxChars: 5 }); ``` */export function truncateContext( { text, maxChars, }: { readonly text: string; readonly maxChars: number; },): { readonly text: string; readonly truncated: boolean;} { if (text.length <= maxChars) { return { text, truncated: false, }; }
/** Character budget left after the omission marker. */ const remainingChars = Math.max( 0, maxChars - CONTEXT_TRUNCATION_MARKER .length, ); /** Head segment length. */ const headChars = Math.ceil(remainingChars / 2,); /** Tail segment length. */ const tailChars = remainingChars - headChars;
/** Tail text, empty when no tail budget remains. */ const tailText = tailChars === 0 ? '' : text.slice(-tailChars,);
return { text: `${ text.slice( 0, headChars, ) }${CONTEXT_TRUNCATION_MARKER}${tailText}`, truncated: true, };}
//endregion Public API
//region Entry conversion
/** Convert one session entry to an Advisor-visible agent message. @param entry - session entry to convert @param includePriorAdvisorResults - whether prior Advisor results should remain visible @param currentToolCallId - current Advisor tool call id to omit @returns Advisor-visible agent message, if entry should be included */function entryToMessage( { entry, includePriorAdvisorResults, currentToolCallId, }: { readonly entry: ForeignBorrowed<SessionEntry>; readonly includePriorAdvisorResults: boolean; readonly currentToolCallId?: string; },): ForeignBorrowed<AdvisorAgentMessage> | typeof MESSAGE_EXCLUDED { if (entry.type === 'message') { return filterMessage({ message: entry.message, includePriorAdvisorResults, ...(currentToolCallId === undefined ? {} : { currentToolCallId, }), },); }
if (entry.type === 'compaction') { return { role: 'compactionSummary', summary: entry.summary, tokensBefore: entry.tokensBefore, timestamp: new Date(entry.timestamp,).getTime(), }; }
if (entry.type === 'branch_summary') { return { role: 'branchSummary', summary: entry.summary, fromId: entry.fromId, timestamp: new Date(entry.timestamp,).getTime(), }; }
if (entry.type === 'custom_message') { if ((!includePriorAdvisorResults) && (entry.customType === ADVISOR_MESSAGE_TYPE)) return MESSAGE_EXCLUDED; return { role: 'custom', customType: entry.customType, content: entry.content, display: entry.display, details: entry.details, timestamp: new Date(entry.timestamp,).getTime(), }; }
return MESSAGE_EXCLUDED;}
/** Filter current or prior Advisor artifacts from one message when needed. @param message - agent message to filter @param includePriorAdvisorResults - whether prior Advisor results should remain visible @param currentToolCallId - current Advisor tool call id to omit @returns filtered message, if message should be included */function filterMessage( { message, includePriorAdvisorResults, currentToolCallId, }: ForeignBorrowed<Readonly<{ message: AdvisorAgentMessage; includePriorAdvisorResults: boolean; currentToolCallId?: string; }>>,): ForeignBorrowed<AdvisorAgentMessage> | typeof MESSAGE_EXCLUDED { if (message.role === 'toolResult') { if ((currentToolCallId !== undefined) && (message.toolCallId === currentToolCallId)) return MESSAGE_EXCLUDED; if ((!includePriorAdvisorResults) && (message.toolName === ADVISOR_TOOL_NAME)) return MESSAGE_EXCLUDED; return message; }
if (message.role !== 'assistant') return message;
/** Assistant content with current Advisor placeholder tool call omitted. */ const content: (typeof message.content)[number][] = []; for (const block of message.content) { /** Whether current block is active Advisor placeholder omitted from context. */ const isCurrentAdvisorCall = (block.type === 'toolCall') && (block.name === ADVISOR_TOOL_NAME) && (block.id === currentToolCallId); if (!isCurrentAdvisorCall) content[content.length] = block; } if (content.length === 0) return MESSAGE_EXCLUDED; return { ...message, content, };}
//endregion Entry conversion