UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

3 lines • 7.28 kB
import{i as estimateStringTokenPressure,t as CHARS_PER_TOKEN_ESTIMATE}from"./cjk-chars-BGxcPZMF.mjs";import{l as isRecord}from"./record-coerce-BTbqdJ3-.mjs";import{a as memoizeFrozenPlainDataProjection,r as isDeeplyFrozenPlainData}from"./immutable-data-CyaF4H_G.mjs";import{a as bashExecutionToText,i as COMPACTION_SUMMARY_SUFFIX,n as BRANCH_SUMMARY_SUFFIX,r as COMPACTION_SUMMARY_PREFIX,t as BRANCH_SUMMARY_PREFIX}from"./messages-CH6T1pxQ.mjs";import{t as IMAGE_BLOCK_TOKENS}from"./compaction-cut-point-CwzAZ7By.mjs"; //!src/agents/sessions/context-token-pressure.ts const SAFETY_MARGIN=1.2;const JSON_PAYLOAD_CHARS_PER_TOKEN=3;const MESSAGE_BOUNDARY_OVERHEAD_TOKENS=12;const CONTENT_BLOCK_OVERHEAD_TOKENS=6;function createFixedRequestTokenEstimator(){let e;let t=0;let n;let r=0;return i=>{if(e!==i.systemPrompt){e=i.systemPrompt;t=e?.trim()?MESSAGE_BOUNDARY_OVERHEAD_TOKENS+estimateStringTokenPressure(e):0}const a=i.tools??[];if(!n||n.length!==a.length||!a.every((e,t)=>{const r=n[t];return e.name===r.name&&e.description===r.description&&e.parameters===r.parameters})){r=estimateToolSchemaTokens(a);n=a.every(({parameters:e})=>isDeeplyFrozenPlainData(e))?a.map(({name:e,description:t,parameters:n})=>({name:e,description:t,parameters:n})):void 0}return{systemTokens:t,toolTokens:r}}}function estimateJsonPayloadTokenPressure(e,t=JSON_PAYLOAD_CHARS_PER_TOKEN){try{const n=JSON.stringify(e);return typeof n===`string`?estimateStringTokenPressure(n,t):1}catch{return 256}}function estimateToolSchemaTokens(e){return e?.length?estimateJsonPayloadTokenPressure(e.map(({name:e,description:t,parameters:n})=>({name:e,description:t,parameters:n})),4):0}function estimateIdentifierTokenPressure(e){if(e==null)return 0;if(typeof e===`string`||typeof e===`number`||typeof e===`boolean`||typeof e===`bigint`)return estimateStringTokenPressure(String(e),JSON_PAYLOAD_CHARS_PER_TOKEN);return estimateJsonPayloadTokenPressure(e)}function estimateContentBlockTokenPressure(e){if(typeof e===`string`)return estimateStringTokenPressure(e);if(!isRecord(e))return estimateJsonPayloadTokenPressure(e,4);const t=e.type;const n=t===`text`?e.text:t===`thinking`?e.thinking:void 0;if(typeof n===`string`)return CONTENT_BLOCK_OVERHEAD_TOKENS+estimateStringTokenPressure(n);if(t===`image`)return IMAGE_BLOCK_TOKENS;return CONTENT_BLOCK_OVERHEAD_TOKENS+estimateJsonPayloadTokenPressure(e,4)}function estimateAssistantToolCallTokenPressure(e){const t=e.arguments??e.input??e.args??{};return CONTENT_BLOCK_OVERHEAD_TOKENS+estimateIdentifierTokenPressure(e.name)+estimateJsonPayloadTokenPressure(t,JSON_PAYLOAD_CHARS_PER_TOKEN)}const estimateContentArrayTokenPressure=memoizeFrozenPlainDataProjection(e=>e.reduce((e,t)=>e+estimateContentBlockTokenPressure(t),0));const estimateAssistantContentTokenPressure=memoizeFrozenPlainDataProjection(e=>e.reduce((e,t)=>e+(isRecord(t)&&(t.type===`toolCall`||t.type===`tool_use`)?estimateAssistantToolCallTokenPressure(t):estimateContentBlockTokenPressure(t)),0));function estimateContentTokenPressure(e){if(typeof e===`string`)return estimateStringTokenPressure(e);if(Array.isArray(e))return estimateContentArrayTokenPressure(e);if(e!==void 0)return estimateJsonPayloadTokenPressure(e);return 0}const estimateMessageTokenPressure=memoizeFrozenPlainDataProjection(e=>{if(`excludeFromContext`in e&&e.excludeFromContext===true)return 0;const t=isRecord(e)?e:{};let n=MESSAGE_BOUNDARY_OVERHEAD_TOKENS;if(e.role===`toolResult`||t.role===`tool`||t.type===`toolResult`){const r=e.role===`toolResult`?e.content:t.content;const i=e.role===`toolResult`?e.toolName:t.toolName;n+=estimateContentTokenPressure(r);n+=estimateIdentifierTokenPressure(i??t.tool_name);return n}if(e.role===`bashExecution`){n+=estimateStringTokenPressure(bashExecutionToText(e));return n}if(e.role===`branchSummary`||e.role===`compactionSummary`){const[t,r]=e.role===`branchSummary`?[BRANCH_SUMMARY_PREFIX,BRANCH_SUMMARY_SUFFIX]:[COMPACTION_SUMMARY_PREFIX,COMPACTION_SUMMARY_SUFFIX];return n+estimateStringTokenPressure(t+e.summary+r)}if(e.role===`assistant`){if(Array.isArray(e.content))n+=estimateAssistantContentTokenPressure(e.content);else n+=estimateContentTokenPressure(e.content);const r=t.toolCalls??t.tool_calls;if(Array.isArray(r))for(const e of r)n+=isRecord(e)?estimateAssistantToolCallTokenPressure(e):estimateJsonPayloadTokenPressure(e);return n}n+=estimateContentTokenPressure(t.content);return n});function estimateRenderedPromptTokens(e){return(e.systemPrompt?.trim()?MESSAGE_BOUNDARY_OVERHEAD_TOKENS+estimateStringTokenPressure(e.systemPrompt):0)+MESSAGE_BOUNDARY_OVERHEAD_TOKENS+estimateStringTokenPressure(e.prompt)}function collectMessageTokenPressureFact(e,t=false){const n=estimateMessageTokenPressure(e);const r={tokens:n};if(e.role===`user`&&`idempotencyKey`in e&&typeof e.idempotencyKey===`string`)r.userIdempotencyKey=e.idempotencyKey;if(t&&e.role===`assistant`&&n!==0){const t=e.usage?.contextUsage;const n=t?.state===`available`?t.totalTokens-t.promptTokens:0;r.completionTokens=Number.isFinite(n)?Math.max(0,n):0;r.completionId=e.turnId?.trim()||e.responseId?.trim()}return r}function*collectMessageTokenPressureFacts(e,t=false){for(const n of e)yield collectMessageTokenPressureFact(n,t)}function createFreshLlmBoundaryTokenEstimator(e){const t=createLlmBoundaryTokenEstimatorFromFacts(e);return n=>t({...n,messages:collectMessageTokenPressureFacts(n.messages,e.retainCompletionUsage)})}function createLlmBoundaryTokenEstimatorFromFacts(e){const t=e.safetyMargin??1.2;const n=e.fixedTokenPressure?.toolTokens??estimateToolSchemaTokens(e.tools);const r=e.fixedTokenPressure?e.fixedTokenPressure.systemTokens+MESSAGE_BOUNDARY_OVERHEAD_TOKENS:estimateRenderedPromptTokens({systemPrompt:e.systemPrompt,prompt:``});return i=>{let a=0;const o=/* @__PURE__ */ new Map;for(const n of i.messages){const r=n.tokens;a+=r;if(!e.retainCompletionUsage||n.completionTokens===void 0||r===0)continue;const i=n.completionTokens/t;const s=n.completionId;if(s){const e=o.get(s);o.set(s,{estimated:(e?.estimated??0)+r,measured:Math.max(e?.measured??0,i)})}else a+=Math.max(0,i-r)}for(const{estimated:e,measured:t}of o.values())a+=Math.max(0,t-e);return Math.ceil((r+estimateStringTokenPressure(i.prompt)+n+(i.imageCount??0)*IMAGE_BLOCK_TOKENS+a)*t)}}function estimateVariableRequestTokens(e,t){const n=createFreshLlmBoundaryTokenEstimator({});return n({messages:e,prompt:t})-n({messages:[],prompt:``})}function estimateCompactionHistoryTokens(e,t){return estimateCompactionHistoryTokensFromFacts(collectMessageTokenPressureFacts(e),t)}function estimateCompactionHistoryTokensFromFacts(e,t){const n=createLlmBoundaryTokenEstimatorFromFacts({});const r=n({messages:[],prompt:``});let i;function*selectPending(){for(const n of e){if(t?.pendingTokens&&t.pendingUserIdempotencyKey&&n.userIdempotencyKey===t.pendingUserIdempotencyKey)i=n;yield n}}return n({messages:selectPending(),prompt:``})-r-(i?Math.min(n({messages:[i],prompt:``})-r,t?.pendingUserTokens??t?.pendingTokens??0):0)}export{estimateJsonPayloadTokenPressure as a,estimateToolSchemaTokens as c,estimateCompactionHistoryTokens as i,estimateVariableRequestTokens as l,createFixedRequestTokenEstimator as n,estimateMessageTokenPressure as o,createFreshLlmBoundaryTokenEstimator as r,estimateRenderedPromptTokens as s,SAFETY_MARGIN as t};