UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

25 lines (20 loc) • 20.7 kB
import{n as estimateStringChars,t as CHARS_PER_TOKEN_ESTIMATE}from"./cjk-chars-BGxcPZMF.mjs";import{a as asOptionalRecord}from"./record-coerce-BTbqdJ3-.mjs";import{n as sliceUtf16Safe,r as truncateUtf16Safe}from"./utf16-slice-DA3Mllbx.mjs";import{m as hasRuntimeContextMarker}from"./types-B7P9E9_J.mjs";import{a as collectToolPairingMessageFact,f as classifyToolPairingFacts,p as createToolCallOccurrenceQueue}from"./tool-result-pairing-CcYwsQg9.mjs";import{u as isRuntimeContextCarrier}from"./messages-CH6T1pxQ.mjs";import{a as projectSessionEntryMessage}from"./session-Bn9SSeOu.mjs";import"./src-BHImOHU3.mjs";import{r as copyString}from"./truncate-By3uAj89.mjs"; //!packages/agent-core/src/harness/compaction/conversation-serialization.ts const ENTRY_SEPARATOR=` `;const MAX_SUMMARY_INPUT_CHARS=16e4;const MAX_SAMPLED_ENTRY_CHARS=6e3;const MIN_TRIMMED_ENTRY_CHARS=200;const TRIMMED_ENTRY_HEAD_SHARE=.7;const ELISION_MARKER_RESERVE_CHARS=64;const SUMMARY_INPUT_TAIL_SHARE=.5;const SUMMARY_INPUT_USER_SHARE=.25;const SUMMARY_INPUT_HEAD_SHARE=.1;const SUMMARY_INPUT_MIDDLE_SLICES=8;const MAX_USER_ENTRY_CHARS=2e3;const MIN_USER_ENTRY_CHARS=400;const OMISSION_MARKER_CHARS=40;function elideMiddleWithinWeight(e,t){const n=t-64;if(n<MIN_TRIMMED_ENTRY_CHARS)return;const r=Math.floor(n*TRIMMED_ENTRY_HEAD_SHARE);let i=0;let a=Math.min(e.length,r);while(i<a){const t=Math.ceil((i+a)/2);if(estimateStringChars(truncateUtf16Safe(e,t))<=r)i=t;else a=t-1}const o=truncateUtf16Safe(e,i);const s=n-estimateStringChars(o);i=Math.max(o.length,e.length-s);a=e.length;while(i<a){const t=Math.floor((i+a)/2);if(estimateStringChars(sliceUtf16Safe(e,t))<=s)a=t;else i=t+1}const c=sliceUtf16Safe(e,i);return`${o}\n\n[... ${e.length-o.length-c.length} characters omitted ...]\n\n${c}`}function renderConversationEntriesWithinBudget(e,t,n){const r=2;if(e.reduce((e,t)=>e+t.fullChars,0)+r*Math.max(0,e.length-1)<=t)return{text:e.map(e=>copyString(n(e,`full`))).join(` `),omittedEntries:0,trimmedEntries:0};let i=false;let a=e.length;const weight=t=>(i&&t<a?e[t]?.shortChars:e[t]?.labeledChars)??0;const o=/* @__PURE__ */ new Map;let s=0;let c=OMISSION_MARKER_CHARS;const take=(l,u,d=u)=>{if(o.has(l))return true;const f=e[l];if(!f)return false;const p=l>0&&!o.has(l-1);const m=l<e.length-1&&!o.has(l+1);const h=(p&&m?1:!p&&!m?-1:0)*OMISSION_MARKER_CHARS;const g=Math.min(u-h,d+r);let _=weight(l)+r;if(_>g&&g-r-64<MIN_TRIMMED_ENTRY_CHARS)return false;if(_<=g&&c+_+h>t)return false;const v=n(f,i&&l<a?`short`:`labeled`);let y=v;if(_>g){const e=elideMiddleWithinWeight(v,g-r);if(e===void 0)return false;y=e;_=estimateStringChars(e)+r}if(c+_+h>t)return false;if(y!==v)s+=1;o.set(l,copyString(y));c+=_+h;return true};const l=Math.floor(t*SUMMARY_INPUT_TAIL_SHARE);for(let t=e.length-1;t>=0;t-=1){const n=l-c;if(!(weight(t)+r<=n)&&a!==e.length||!take(t,n))break;a=t}i=true;const u=[];for(let t=0;t<a;t++)if(e[t]?.user)u.push(t);if(u.length>0){const e=Math.floor(t*SUMMARY_INPUT_USER_SHARE);const n=c+e;const i=Math.min(MAX_USER_ENTRY_CHARS,Math.max(MIN_USER_ENTRY_CHARS,Math.floor(e/u.length-OMISSION_MARKER_CHARS)));const a=u.reduce((e,t)=>e+Math.min(weight(t)+r,i+r)+OMISSION_MARKER_CHARS,0);const o=Math.max(1,a/e);for(let e=u.length-1;e>=0;e-=o){const t=u[Math.round(e)];if(t===void 0||!take(t,n-c,i))break}}let d=0;const f=c+Math.floor(t*SUMMARY_INPUT_HEAD_SHARE);while(d<a&&take(d,f-c,MAX_SAMPLED_ENTRY_CHARS))d+=1;const p=a-d;if(p>0){const e=Math.floor((t-c)/SUMMARY_INPUT_MIDDLE_SLICES);let n=d;for(let t=0;t<SUMMARY_INPUT_MIDDLE_SLICES;t+=1){let r=Math.max(n,d+Math.floor(t*p/SUMMARY_INPUT_MIDDLE_SLICES));const i=c+e;while(r<a&&take(r,i-c,MAX_SAMPLED_ENTRY_CHARS))r+=1;n=r}}const m=[];let h=0;let g=0;for(let t=0;t<=e.length;t+=1){const n=o.get(t);if(n===void 0&&t<e.length){g+=1;continue}if(g>0){m.push(`[... ${g} ${g===1?`entry`:`entries`} omitted ...]`);h+=g;g=0}if(n!==void 0)m.push(n)}return{text:m.join(` `),omittedEntries:h,trimmedEntries:s}} //!packages/agent-core/src/harness/compaction/file-operations.ts function normalizeFileToolName(e){const t=e.toLowerCase();const n=t.indexOf(`__`,t.startsWith(`mcp__`)?5:0);return n<0?t:t.slice(n+2)}function addFilePaths(e,t){for(const n of Array.isArray(t)?t:[])if(typeof n===`string`)e.add(copyString(n))}function createFileOps(){return{read:/* @__PURE__ */ new Set,written:/* @__PURE__ */ new Set,edited:/* @__PURE__ */ new Set}}function mergeSummaryFileOperations(e,t){addFilePaths(e.read,t.readFiles);addFilePaths(e.edited,t.modifiedFiles)}function collectFileOperationMessageFact(e,t){if(e.role===`assistant`){const n=[];for(const r of e.content){if(r.type!==`toolCall`)continue;let e=t?.get(r);if(!e){const n=asOptionalRecord(r.arguments);const i=[n?.path,n?.file_path,n?.filePath].find(e=>typeof e===`string`);e={id:copyString(r.id),name:copyString(normalizeFileToolName(r.name)),path:i===void 0?void 0:copyString(i)};t?.set(r,e)}n.push(e)}return{role:`assistant`,calls:n}}if(e.role!==`toolResult`)return{role:`other`};const n=normalizeFileToolName(e.toolName);const r=/* @__PURE__ */ new Set;const i=/* @__PURE__ */ new Set;if(n===`apply_patch`)for(const t of[e,...Array.isArray(e.content)?e.content:[]]){const e=asOptionalRecord(asOptionalRecord(asOptionalRecord(t)?.details)?.summary);addFilePaths(r,e?.added);addFilePaths(i,e?.modified)}return{role:`toolResult`,id:copyString(e.toolCallId),name:copyString(n),unchanged:asOptionalRecord(e.details)?.changed===false,written:r,edited:i}}function extractFileOpsFromFacts(e,t){const n=createToolCallOccurrenceQueue();const r=/* @__PURE__ */ new Set;for(const t of e)if(t.role===`assistant`){n.clear();for(const e of t.calls)n.add(e.id,e)}else if(t.role===`toolResult`){const e=n.claim(t.id);if(e?.name===t.name&&(t.name===`edit`||t.name===`write`)&&t.unchanged)r.add(e)}else n.clear();for(const n of e)if(n.role===`toolResult`){for(const e of n.written)t.written.add(e);for(const e of n.edited)t.edited.add(e)}else if(n.role===`assistant`)for(const e of n.calls){if(!e.path||r.has(e))continue;switch(e.name){case`read`:t.read.add(e.path);break;case`write`:t.written.add(e.path);break;case`edit`:t.edited.add(e.path)}}}function extractFileOpsFromMessages(e,t){const n=/* @__PURE__ */ new WeakMap;extractFileOpsFromFacts(e.map(e=>collectFileOperationMessageFact(e,n)),t)}function computeFileLists(e){const t=/* @__PURE__ */ new Set([...e.edited,...e.written]);return{readFiles:[...e.read].filter(e=>!t.has(e)).toSorted(),modifiedFiles:[...t].toSorted()}}const MAX_FILE_OPS_LIST_CHARS=900;function formatBoundedFileList(e,t,n){if(t.length===0||n<=0)return``;const r=`<${e}>\n`;const i=`\n</${e}>`;const a=[];let o=r.length+i.length;for(let e=0;e<t.length;e++){const r=`${t[e]}\n`;const i=t.length-e-1;const s=i>0?`...and ${i} more\n`:``;if(o+r.length+s.length>n){const r=`...and ${t.length-e} more\n`;if(o+r.length<=n)a.push(r);break}a.push(r);o+=r.length}return a.length>0?`${r}${a.join(``).trimEnd()}${i}`:``}function formatFileOperations(e,t){const n=[formatBoundedFileList(`read-files`,e,MAX_FILE_OPS_LIST_CHARS),formatBoundedFileList(`modified-files`,t,MAX_FILE_OPS_LIST_CHARS)].filter(Boolean);return n.length>0?`\n\n${n.join(` `)}`:``} //!packages/agent-core/src/harness/compaction/utils.ts function extractSummaryText(e){const t=e.content.filter(e=>e.type===`text`).map(e=>e.text).join(` `);return t.trim()?t:void 0}const TOOL_RESULT_MAX_CHARS=2e3;const SAMPLED_TOOL_RESULT_MAX_CHARS=500;const IMPORTANT_TOOL_RESULT_TAIL=/(error|exception|failed|fatal|traceback|panic|stack trace|errno|exit code)/i;function stringifyCompactionValue(e){try{return JSON.stringify(e)??`undefined`}catch{return`[unserializable]`}}function truncateForSummary(e,t){if(e.length<=t)return e;const n=Math.min(Math.floor(t*.3),600);const r=sliceUtf16Safe(e,-t);const i=[...r.matchAll(new RegExp(IMPORTANT_TOOL_RESULT_TAIL.source,`gi`))];const a=i.findLast(e=>/^(error|exception|fatal|panic|errno)$/i.test(e[0]))??i.at(-1);if(a){const i=truncateUtf16Safe(e,t-n);const o=sliceUtf16Safe(e,Math.max(0,i.length-32),t);if(!IMPORTANT_TOOL_RESULT_TAIL.test(o)){const t=e.length-r.length+(a.index??0);const o=Math.min(t,e.length-n);if(o>=i.length){const t=sliceUtf16Safe(e,o,o+n);return`${i}\n\n[... ${e.length-i.length-t.length} ${o+t.length<e.length?`middle/trailing`:`more`} characters truncated]\n\n${t}`}}}const o=t-n-64;const s=truncateUtf16Safe(e,t);const c=IMPORTANT_TOOL_RESULT_TAIL.test(s)?``:sliceUtf16Safe(e,-n);const l=c?truncateUtf16Safe(s,o):s;return`${l}\n\n[... ${e.length-l.length-c.length} more characters truncated]${c?`\n\n${c}`:``}`}function projectCompactionContentBlock(e){let t=``;if((e.type===`text`||e.type===`toolResult`||e.type===`tool_result`)&&e.text)t=e.text;else if((e.type===`toolResult`||e.type===`tool_result`)&&typeof e.content===`string`)t=e.content;return{text:t,...e.type!==`text`&&!t?{omission:e.type===`image`?`[image data omitted from summary input]`:`[non-text data omitted from summary input]`}:{}}}function getCompactionContent(e){if(typeof e===`string`)return{text:e,omissionText:``};const t=/* @__PURE__ */ new Set;return{text:e.map(e=>{const n=projectCompactionContentBlock(e);if(n.omission)t.add(n.omission);return n.text}).filter(Boolean).join(` `),omissionText:[...t].join(` `)}}const MAX_OMISSION_MESSAGES=8;const OMISSION_OVERFLOW=`[More image/non-text data omitted from summary input]`;function formatPersistedSenderSuffix(e){if(e.role!==`user`)return``;const t=asOptionalRecord(Reflect.get(e,`__openclaw`));if(!t)return``;const normalize=e=>{if(typeof e!==`string`)return;return e.replaceAll(`\0`,``).trim()||void 0};const n={id:normalize(t.senderId),name:normalize(t.senderName),username:normalize(t.senderUsername)};return n.id?` sender=${JSON.stringify(n)}`:``}function compactionUserRole(e){if(hasRuntimeContextMarker(e))return`Runtime context`;if(Reflect.get(e,`synthetic`)===true)return`Synthetic input`;if(Reflect.get(e,`operatorMessage`)!==void 0)return`Operator input`;if(asOptionalRecord(Reflect.get(e,`__openclaw`))?.beforeAgentRunBlocked!==void 0)return`Internal system input`;const t=Reflect.get(e,`provenance`);if(t===void 0)return`User`;const n=asOptionalRecord(t);switch(n?.kind){case`external_user`:return`User`;case`realtime_voice`:return n.sourceChannel===`talk`?`User`:`Unknown-origin input`;case`inter_session`:return`Inter-session input`;case`internal_system`:return`Internal system input`;default:return`Unknown-origin input`}}function isCompactionUserRequest(e){return e.role===`user`&&compactionUserRole(e)===`User`}function findLatestCompactionUserMessage(e,t){return e.findLast(e=>e.role===`user`&&isCompactionUserRequest(e)&&Boolean(t(e).trim()))}const CREDENTIAL_PATTERNS=[/\b(?:sk|pk|rk|ghp|gho|ghu|ghs|github_pat|xox[abprs]|glpat|AKIA|AIza)[-_A-Za-z0-9]{16,}/g,/\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{5,}/g,/\b(?:api[_-]?key|token|secret|password|passwd|authorization|bearer)\b\s*[:=]\s*["']?[^\s"']{8,}/gi,/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g];function extractCompactionMessageText(e){const t=Reflect.get(e,`content`);const n=typeof t===`string`?t.trim():Array.isArray(t)?t.flatMap(e=>{const t=e&&typeof e===`object`?Reflect.get(e,`text`):void 0;return typeof t===`string`&&t.trim()?[t.trim()]:[]}).join(` `):``;return CREDENTIAL_PATTERNS.reduce((e,t)=>e.replace(t,`[redacted]`),n)}function extractCurrentCompactionUserRequest(e,t){const n=e.findLast(e=>e.role===`user`);return n&&isCompactionUserRequest(n)?t(n):null}function formatCompactionUserLabel(e){return`${compactionUserRole(e)}${formatPersistedSenderSuffix(e)}`}function removeGeneratedCompactionSection(e,t){if(!e)return e;if(e.startsWith(t))return e.slice(t.length);const n=`\n\n${t}`;const r=e.indexOf(n);return r<0?e:`${e.slice(0,r)}\n\n${e.slice(r+n.length)}`}function clearCompactionPendingAskSection(e){const t=/^## Pending user asks[ \t]*$/mu.exec(e);if(!t)return e;const n=t.index+t[0].length;const r=e.slice(n+1);const i=/^##[ \t]+\S.*$/mu.exec(r);return`${e.slice(0,n)}\nNone.${i?`\n${r.slice(i.index)}`:``}`}function serializeConversation(e){const t=createConversationProjector();const n=[];for(const r of e)for(const e of t(r).parts)n.push(e.full);return n.join(` `)}const MAX_CALL_LABEL_ARGUMENT_CHARS=120;const MAX_CALL_LABEL_CHARS=300;function formatCallLabel(e,t){const n=`${e}(${t.map(([e,t])=>`${e}=${t.length>MAX_CALL_LABEL_ARGUMENT_CHARS?`${truncateUtf16Safe(t,MAX_CALL_LABEL_ARGUMENT_CHARS)}...`:t}`).join(`, `)})`;const r=n.length>MAX_CALL_LABEL_CHARS?`${truncateUtf16Safe(n,MAX_CALL_LABEL_CHARS)}...)`:n;return copyString(r)}function omissionPhase(e){return e<MAX_OMISSION_MESSAGES?0:e===MAX_OMISSION_MESSAGES?1:2}function projectConversationMessage(e,t,n){const r=[];const add=(e,t=e,n=t,i=false,a)=>{r.push({full:e,labeled:t,short:n,user:i,toolResult:a})};if(hasRuntimeContextMarker(e))return r;if(e.role===`user`||e.role===`toolResult`){const{text:n,omissionText:r}=getCompactionContent(e.content);const i=omissionPhase(t.omissionMessages);if(r)t.omissionMessages+=1;if(r&&i===1)add(OMISSION_OVERFLOW);const a=i===0?r:``;const project=t=>[a,e.role===`toolResult`?truncateForSummary(n,t):n].filter(Boolean).join(` `);const o=project(TOOL_RESULT_MAX_CHARS);if(o){if(e.role===`toolResult`){const n=t.callLabel??`${e.toolName}(...)`;add(`[Tool result]: ${o}`,`[Tool result of ${n}]: ${o}`,`[Tool result of ${n}]: ${project(SAMPLED_TOOL_RESULT_MAX_CHARS)}`,false,true)}else{const t=`[${formatCompactionUserLabel(e)}]: ${o}`;add(t,t,t,isCompactionUserRequest(e))}}}else if(e.role===`assistant`){const t=[];const r=[];for(const i of e.content)if(i.type===`text`)t.push(i.text);else if(i.type===`toolCall`){const e=Object.entries(i.arguments).map(([e,t])=>[e,stringifyCompactionValue(t)]);const t=e.map(([e,t])=>`${e}=${t}`).join(`, `);r.push(`${i.name}(${t})`);n?.(i.id,formatCallLabel(i.name,e))}if(t.length>0)add(`[Assistant]: ${t.join(` `)}`);if(r.length>0)add(`[Assistant tool calls]: ${r.join(`; `)}`)}return r}function createConversationSequenceState(){const e=createToolCallOccurrenceQueue();let t=0;return{begin(n,r){if(n===`assistant`)e.clear();return{omissionMessages:t,callLabel:n===`toolResult`&&r!==void 0?e.claim(r):void 0}},finish(e){t=e.omissionMessages},add:e.add}}function createConversationProjector(){const e=createConversationSequenceState();return t=>{if(hasRuntimeContextMarker(t))return{parts:[],omissionMessages:0,callLabel:void 0};const n=e.begin(t.role,t.role===`toolResult`?t.toolCallId:void 0);const r=n.omissionMessages;const i=projectConversationMessage(t,n,e.add);e.finish(n);return{parts:i,omissionMessages:r,callLabel:n.callLabel}}}function describeConversationParts(e,t,n){return e.map((e,r)=>{const i=estimateStringChars(e.full);const a=e.labeled===e.full?i:estimateStringChars(e.labeled);return{descriptor:{source:t,partIndex:r,fullChars:i,labeledChars:a,shortChars:e.short===e.labeled?a:estimateStringChars(e.short),fullLength:e.full.length,labeledLength:e.labeled.length,shortLength:e.short.length,user:e.user===true,toolResult:e.toolResult,...n},text:e}})}function createConversationEntryCollector(){const e=createConversationProjector();return(t,n)=>{const{parts:r,omissionMessages:i,callLabel:a}=e(t);return describeConversationParts(r,n,{omissionMessages:i,callLabel:a})}}function collectConversationEntries(e){const t=createConversationEntryCollector();const n=[];for(const[r,i]of e.entries())n.push(...t(i,r));return n}function serializeConversationWithinBudget(e,t){const n=collectConversationEntries(e).map(({descriptor:e,text:t})=>Object.assign(e,{text:t}));return renderConversationEntriesWithinBudget(n,t,(e,t)=>e.text[t])} //!packages/agent-core/src/harness/compaction/compaction-cut-point.ts function getMessageFromEntryForCompaction(e){if(e.type===`compaction`)return;return projectSessionEntryMessage(e)}const IMAGE_BLOCK_TOKENS=2e3;const IMAGE_BLOCK_CHARS=IMAGE_BLOCK_TOKENS*4;function countCompactionContentChars(e){const{text:t,omissionText:n}=getCompactionContent(e);const r=typeof e===`string`?0:e.filter(e=>e.type===`image`).length;return countCompactionContentCharsFromParts(estimateStringChars(t),r,n)}function countCompactionContentCharsFromParts(e,t,n){const r=n?n.length+17:0;return e+t*IMAGE_BLOCK_CHARS+r}function estimateCompactionChars(e){if(`excludeFromContext`in e&&e.excludeFromContext===true)return 0;let t=0;switch(e.role){case`assistant`:for(const n of e.content)if(n.type===`text`)t+=estimateStringChars(n.text);else if(n.type===`thinking`)t+=estimateStringChars(n.thinking);else if(n.type===`toolCall`)t+=estimateStringChars(n.name)+estimateStringChars(stringifyCompactionValue(n.arguments));break;case`user`:t=countCompactionContentChars(e.content);t+=estimateStringChars(formatCompactionUserLabel(e))-4;break;case`custom`:case`toolResult`:t=countCompactionContentChars(e.content);break;case`bashExecution`:t=estimateStringChars(e.command)+estimateStringChars(e.output);break;case`branchSummary`:case`compactionSummary`:t=estimateStringChars(e.summary)}return t}function estimateTokens(e){return Math.ceil(estimateCompactionChars(e)/4)}function isCutPointMessage(e){return e.role===`assistant`||isTurnStartMessage(e)}function isTurnStartMessage(e){const t=e.role;return t===`custom`?!isRuntimeContextCarrier(e):t===`user`||t===`bashExecution`||t===`branchSummary`||t===`compactionSummary`}function isTurnStartEntry(e){const t=getMessageFromEntryForCompaction(e);return t?isTurnStartMessage(t):false}function findTurnStartIndex(e,t,n){return findPreviousTurnStart(t,n,t=>{const n=e[t];return n?isTurnStartEntry(n):false})}function findPreviousTurnStart(e,t,n){for(let r=e;r>=t;r--)if(n(r))return r;return-1}function collectCompactionCutEntryFact(e,t=getMessageFromEntryForCompaction(e)){return{id:e.id,type:e.type,hasMessage:t!==void 0,isCutPoint:t?isCutPointMessage(t):false,isTurnStart:t?isTurnStartMessage(t):false,pairing:t?collectToolPairingMessageFact(t):void 0}}function createToolPairCutResolver(e,t){const n=[];const entryIndexAt=e=>{const n=t[e];if(n===void 0)throw new Error(`Tool pairing references a message outside the compaction entries`);return n};for(const t of classifyToolPairingFacts(e)){const e=entryIndexAt(t.startIndex);let r=e;for(const e of t.occurrences)if(e.result)r=Math.max(r,entryIndexAt(e.result.index));if(r===e)continue;const i=n.at(-1);if(i&&e<=i.end)i.end=Math.max(i.end,r);else n.push({start:e,end:r})}return e=>{let t=0;let r=n.length;while(t<r){const i=Math.floor((t+r)/2);const a=n[i];if(!a)throw new Error(`Compaction tool range is missing from the selected search interval`);if(a.start<e)t=i+1;else r=i}const i=n[t-1];return i&&e<=i.end?i.start:e}}function findCutPoint(e,t,n,r,i){const a=[];for(let r=t;r<n;r++){const t=e[r];if(t)a[r]=collectCompactionCutEntryFact(t)}return findCutPointFromFacts(a,t,n,r,i,t=>{const n=e[t];const r=n?getMessageFromEntryForCompaction(n):void 0;return r?i?.budget?.estimateTokens(r)??estimateTokens(r):0})}function findCutPointFromFacts(e,t,n,r,i,a){const o=i?.budget;let s;let c=n-1;const l=[];const u=[];for(let r=t;r<n;r++){const t=e[r];if(t&&i?.requestBoundary?.preserve&&t.id===i.requestBoundary.entryId)c=r;if(t?.isCutPoint)s=r;const n=t?.pairing;if(n?.role===`toolResult`||n?.role===`assistant`&&n.calls.length>0){l.push(n);u.push(r)}}if(s===void 0)return{firstKeptEntryIndex:t,turnStartIndex:-1,isSplitTurn:false};const d=createToolPairCutResolver(l,u);s=d(s);c=d(c);let f=0;for(let i=n-1;i>=t;i--){const t=e[i];if(!t?.hasMessage)continue;if(t.isCutPoint)s=d(i);f+=a(i);if(f>=r)break}s=Math.min(s,c);if(o){let t=0;let r=n;let i=o.maxTokens;for(let l=n-1;l>=s;l--){const s=e[l];t+=s?.hasMessage?a(l):0;if(t>i)break;if(l<=c&&s?.isCutPoint&&d(l)===l){if(r===n)i=Math.max(t,o.maxTokens-o.reserveTokens);r=l}}if(r===n)return{firstKeptEntryIndex:n,turnStartIndex:-1,isSplitTurn:false};s=r}const p=e[s];if(!p)throw new Error(`compaction cut point does not reference a session entry`);const m=p.isTurnStart;while(s>t){const t=e[s-1];if(!t)break;if(t.type===`compaction`||t.type===`reset`)break;if(t.type===`message`||t.hasMessage)break;s--}const h=m?-1:findPreviousTurnStart(s,t,t=>e[t]?.isTurnStart===true);return{firstKeptEntryIndex:s,turnStartIndex:h,isSplitTurn:!m&&h!==-1}}export{extractFileOpsFromMessages as _,getMessageFromEntryForCompaction as a,MAX_SUMMARY_INPUT_CHARS as b,extractCurrentCompactionUserRequest as c,formatCompactionUserLabel as d,removeGeneratedCompactionSection as f,createFileOps as g,computeFileLists as h,findTurnStartIndex as i,extractSummaryText as l,serializeConversationWithinBudget as m,estimateTokens as n,clearCompactionPendingAskSection as o,serializeConversation as p,findCutPoint as r,extractCompactionMessageText as s,IMAGE_BLOCK_TOKENS as t,findLatestCompactionUserMessage as u,formatFileOperations as v,mergeSummaryFileOperations as y};