UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

146 lines (145 loc) • 6.93 kB
import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs"; import { n as estimateStringChars } from "./cjk-chars-CgnWl5qA.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-MSizso-z.mjs"; import { t as IMAGE_BLOCK_TOKENS } from "./compaction-cut-point-CEj7MSFJ.mjs"; //#region src/agents/sessions/context-token-pressure.ts /** Shared fresh-request estimates for admission and compaction replacement. */ /** Buffer for token-estimation inaccuracy, shared by admission and compaction. */ const SAFETY_MARGIN = 1.2; const ESTIMATED_CHARS_PER_TOKEN = 4; const TOOL_RESULT_CHARS_PER_TOKEN = 2; const JSON_PAYLOAD_CHARS_PER_TOKEN = 3; const MESSAGE_BOUNDARY_OVERHEAD_TOKENS = 12; const CONTENT_BLOCK_OVERHEAD_TOKENS = 6; function estimateStringTokenPressure(e, t = 4, n = "general") { const r = Math.ceil(estimateStringChars(e) / t); return n === "tool-result" ? Math.max(Math.ceil(e.length / TOOL_RESULT_CHARS_PER_TOKEN), r) : r; } function estimateJsonPayloadTokenPressure(e, t = JSON_PAYLOAD_CHARS_PER_TOKEN, n = "general") { try { const r = JSON.stringify(e); return typeof r === "string" ? estimateStringTokenPressure(r, t, n) : 1; } catch { return 256; } } /** Count model-facing definitions; runtime output schemas and metadata never reach the provider. */ function estimateToolSchemaTokens(e) { return e?.length ? estimateJsonPayloadTokenPressure(e.map(({ name: e, description: t, parameters: n }) => ({ name: e, description: t, parameters: n }))) : 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, t = "general") { if (typeof e === "string") return estimateStringTokenPressure(e, 4, t); if (!isRecord(e)) return estimateJsonPayloadTokenPressure(e, 4, t); const n = e.type; const r = n === "text" ? e.text : n === "thinking" ? e.thinking : void 0; if (typeof r === "string") return CONTENT_BLOCK_OVERHEAD_TOKENS + estimateStringTokenPressure(r, 4, t); if (n === "image") return IMAGE_BLOCK_TOKENS; return CONTENT_BLOCK_OVERHEAD_TOKENS + estimateJsonPayloadTokenPressure(e, 4, t); } 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); } function estimateContentTokenPressure(e, t = "general") { if (typeof e === "string") return estimateStringTokenPressure(e, 4, t); if (Array.isArray(e)) return e.reduce((e, n) => e + estimateContentBlockTokenPressure(n, t), 0); if (e !== void 0) return estimateJsonPayloadTokenPressure(e, t === "tool-result" ? 4 : JSON_PAYLOAD_CHARS_PER_TOKEN, t); return 0; } function estimateMessageTokenPressure(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, "tool-result"); 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)) for (const t of e.content) { if (isRecord(t)) { const e = t.type; if (e === "toolCall" || e === "tool_use") { n += estimateAssistantToolCallTokenPressure(t); continue; } } n += estimateContentBlockTokenPressure(t); } 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); } /** Prepare fixed request costs before estimating its pending input or replacement history. */ function createFreshLlmBoundaryTokenEstimator(e) { const t = estimateToolSchemaTokens(e.tools); const n = estimateRenderedPromptTokens({ systemPrompt: e.systemPrompt, prompt: "" }); return (r) => { let i = 0; const a = /* @__PURE__ */ new Map(); for (const t of r.messages) { const n = estimateMessageTokenPressure(t); i += n; if (!e.retainCompletionUsage || t.role !== "assistant" || n === 0) continue; const r = t.usage?.contextUsage; const o = r?.state === "available" ? r.totalTokens - r.promptTokens : 0; const s = Number.isFinite(o) ? Math.max(0, o) / SAFETY_MARGIN : 0; const c = t.turnId?.trim() || t.responseId?.trim(); if (c) { const e = a.get(c); a.set(c, { estimated: (e?.estimated ?? 0) + n, measured: Math.max(e?.measured ?? 0, s) }); } else i += Math.max(0, s - n); } for (const { estimated: e, measured: t } of a.values()) i += Math.max(0, t - e); return Math.ceil((n + estimateStringTokenPressure(r.prompt) + t + (r.imageCount ?? 0) * IMAGE_BLOCK_TOKENS + i) * SAFETY_MARGIN); }; } function estimateVariableRequestTokens(e, t) { const n = createFreshLlmBoundaryTokenEstimator({}); return n({ messages: e, prompt: t }) - n({ messages: [], prompt: "" }); } function estimateCompactionHistoryTokens(e, t) { const n = t?.pendingTokens && t.pendingUserIdempotencyKey ? e.findLast((e) => e.role === "user" && "idempotencyKey" in e && e.idempotencyKey === t.pendingUserIdempotencyKey) : void 0; const r = n ? Math.min(estimateCompactionHistoryTokens([n]), t?.pendingUserTokens ?? t?.pendingTokens ?? 0) : 0; return estimateVariableRequestTokens(e, "") - r; } //#endregion export { estimateMessageTokenPressure as a, estimateToolSchemaTokens as c, estimateJsonPayloadTokenPressure as i, estimateVariableRequestTokens as l, createFreshLlmBoundaryTokenEstimator as n, estimateRenderedPromptTokens as o, estimateCompactionHistoryTokens as r, estimateStringTokenPressure as s, SAFETY_MARGIN as t };