UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

293 lines (292 loc) • 10.8 kB
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs"; import { n as sliceUtf16Safe, r as truncateUtf16Safe } from "./utf16-slice-CuDyEXgS.mjs"; import { t as pruneMapToMaxSize } from "./map-size-BBr20tbc.mjs"; import "./utils-C8YECn2Q.mjs"; import { r as resolveAgentConfig } from "./agent-scope-config-DmXgFGKP.mjs"; import { n as sha256Hex } from "./node-crypto-B6yuTjmm.mjs"; import "./agent-scope-BwB8YH6y.mjs"; //#region src/agents/embedded-agent-helpers/bootstrap-limits.ts const DEFAULT_BOOTSTRAP_MAX_CHARS = 2e4; //#endregion //#region src/agents/embedded-agent-helpers/bootstrap.ts /** * Builds and sanitizes bootstrap context inserted into embedded-agent sessions. */ function isBase64Signature(e) { const t = e.trim(); if (!t) return false; const n = t.replace(/\s+/g, ""); if (!/^[A-Za-z0-9+/=_-]+$/.test(n)) return false; const r = n.includes("-") || n.includes("_"); try { const e = Buffer.from(n, r ? "base64url" : "base64"); if (e.length === 0) return false; const t = e.toString(r ? "base64url" : "base64"); const normalize = (e) => e.replace(/=+$/g, ""); return normalize(t) === normalize(n); } catch { return false; } } /** * Strips Claude-style thought_signature fields from content blocks. * * Gemini expects thought signatures as base64-encoded bytes, but Claude stores message ids * like "msg_abc123...". We only strip "msg_*" to preserve any provider-valid signatures. */ function stripThoughtSignatures(e, t) { if (!Array.isArray(e)) return e; const n = t?.allowBase64Only ?? false; const r = ["thought_signature", ...t?.includeCamelCase ?? false ? ["thoughtSignature"] : []]; const shouldStripSignature = (e) => { if (!n) return typeof e === "string" && e.startsWith("msg_"); return typeof e !== "string" || !isBase64Signature(e); }; return e.map((e) => { if (!e || typeof e !== "object") return e; const t = e; const n = r.filter((e) => shouldStripSignature(t[e])); if (n.length === 0) return e; const i = { ...t }; for (const e of n) delete i[e]; return i; }); } const DEFAULT_BOOTSTRAP_TOTAL_MAX_CHARS = 6e4; const USER_BOOTSTRAP_MAX_CHARS = 4e3; const MIN_BOOTSTRAP_FILE_BUDGET_CHARS = 64; const BOOTSTRAP_HEAD_RATIO = .75; const BOOTSTRAP_TAIL_RATIO = .25; const MIN_BOOTSTRAP_TRIMMED_CONTENT_CHARS = 16; const AGENTS_BOOTSTRAP_FILENAME = "AGENTS.md"; const USER_BOOTSTRAP_FILENAME = "USER.md"; const AGENTS_POLICY_DIGEST_RATIO = .35; const AGENTS_POLICY_HEAD_RATIO = .45; const AGENTS_POLICY_TAIL_RATIO = .15; const AGENTS_POLICY_DIGEST_MAX_LINE_CHARS = 240; const AGENTS_POLICY_DIGEST_CANDIDATE_PATTERN = /\b(?:AGENTS\.md|scoped|required|must|never|do not|before subtree|read scoped|owner|security|secret|credential|test|validation|command|commit|push|github|pr)\b|(?:🔴|禁止|嚴禁|不得|絕不|絕對不|切勿|必須|務必|一律|紅線)/iu; const AGENTS_POLICY_DIGEST_HIGH_PRIORITY_PATTERN = /\b(?:AGENTS\.md|scoped|required|must|never|do not|before subtree|read scoped|security|secret|credential)\b|(?:🔴|禁止|嚴禁|不得|絕不|絕對不|切勿)/iu; const trimmedBootstrapCache = /* @__PURE__ */ new Map(); const MAX_TRIMMED_BOOTSTRAP_ENTRIES = 256; const warnedBootstrapTruncations = /* @__PURE__ */ new Set(); function resolveBootstrapCharLimit(e, t, n, r) { const i = e && t ? resolveAgentConfig(e, t)?.[n] ?? e.agents?.defaults?.[n] : e?.agents?.defaults?.[n]; if (typeof i === "number" && Number.isFinite(i) && i > 0) return Math.floor(i); return r; } function resolveBootstrapMaxChars(e, t) { return resolveBootstrapCharLimit(e, t, "bootstrapMaxChars", DEFAULT_BOOTSTRAP_MAX_CHARS); } function resolveBootstrapTotalMaxChars(e, t) { return resolveBootstrapCharLimit(e, t, "bootstrapTotalMaxChars", DEFAULT_BOOTSTRAP_TOTAL_MAX_CHARS); } function isPolicyDigestCandidate(e) { return /^(?:#{1,6}|\s*[-*+]|\s*\d+[.)])\s+\S/u.test(e) || AGENTS_POLICY_DIGEST_CANDIDATE_PATTERN.test(e); } function normalizePolicyDigestLine(e) { const t = e.trim().replace(/\s+/gu, " "); if (t.length <= AGENTS_POLICY_DIGEST_MAX_LINE_CHARS) return t; return `${truncateUtf16Safe(t, 239)}…`; } function buildAgentsPolicyDigest(e, t) { if (t <= 0) return { text: "", omittedLines: 0 }; const n = /* @__PURE__ */ new Set(); let r = 0; const trySelect = (e) => { const i = n.size > 0 ? 1 : 0; if (r + i + e.text.length > t) return; n.add(e); r += i + e.text.length; }; for (const t of e) if (t.highPriority) trySelect(t); for (const t of e) if (!n.has(t)) trySelect(t); return { text: e.filter((e) => n.has(e)).map((e) => e.text).join("\n"), omittedLines: Math.max(0, e.length - n.size) }; } function trimAgentsBootstrapContent(e, t) { let n = Math.floor(t * AGENTS_POLICY_HEAD_RATIO); let r = Math.floor(t * AGENTS_POLICY_TAIL_RATIO); let i = Math.floor(t * AGENTS_POLICY_DIGEST_RATIO); const a = []; if (!(i <= 0)) { let t = null; for (const n of e.split(/\r?\n/u)) { const e = normalizePolicyDigestLine(n); if (e.length === 0) { t = null; continue; } if (/^\s*(?:`{3,}|~{3,})/u.test(e)) t = null; else if (isPolicyDigestCandidate(e)) { a.push({ text: t === null ? e : `${t}\n${e}`, highPriority: AGENTS_POLICY_DIGEST_HIGH_PRIORITY_PATTERN.test(e) }); t = null; } else t = e; } } let o = buildAgentsPolicyDigest(a, i); const render = () => [ sliceUtf16Safe(e, 0, n), `[...truncated, read ${AGENTS_BOOTSTRAP_FILENAME} for full content...]`, o.text ? "[Policy digest from AGENTS.md]" : "", o.text, o.omittedLines > 0 ? `[...${o.omittedLines} more policy lines omitted...]` : "", `…(truncated ${AGENTS_BOOTSTRAP_FILENAME}: kept ${n}+policy ${o.text.length}+${r} chars of ${e.length})…`, r > 0 ? sliceUtf16Safe(e, -r) : "" ].filter((e) => e.length > 0).join("\n"); let s = render(); while (s.length > t && (r > 0 || n > 1 || i > 0)) { const e = s.length - t; if (r > 0) r = Math.max(0, r - e); else if (n > 1) n = Math.max(1, n - e); else { i = Math.max(0, i - e); o = buildAgentsPolicyDigest(a, i); } s = render(); } return s.length > t ? truncateUtf16Safe(s, t) : s; } function trimBootstrapContent(e, t, n) { const r = e.trimEnd(); const finish = (e, t = true) => ({ content: e, truncated: t, maxChars: n, originalLength: r.length }); if (r.length <= n) return finish(r, false); if (t?.toLowerCase() === AGENTS_BOOTSTRAP_FILENAME.toLowerCase()) return finish(trimAgentsBootstrapContent(r, n)); const markerTemplate = (e, n) => [ "", `[...truncated, read ${t} for full content...]`, `…(truncated ${t}: kept ${e}+${n} chars of ${r.length})…`, "" ].join("\n"); const compactMarkerTemplate = (e, t) => `[…truncated ${e}+${t}/${r.length}]`; const separatorCharsFor = (e, t, n) => n.includes("\n") ? Number(e > 0) + Number(t > 0) : 0; const renderTruncatedContent = (e, t, n) => [ e, t, n ].filter((e) => e.length > 0).join(t.includes("\n") ? "\n" : ""); const i = markerTemplate(0, 0); const a = n - i.length - separatorCharsFor(1, 1, i) >= MIN_BOOTSTRAP_TRIMMED_CONTENT_CHARS ? markerTemplate : compactMarkerTemplate; let o = 0; let s = 0; let c = a(o, s); for (let e = 0; e < 3; e += 1) { const e = Math.max(0, n - c.length - separatorCharsFor(o, s, c)); const t = Math.floor(e * BOOTSTRAP_HEAD_RATIO); const r = Math.floor(e * BOOTSTRAP_TAIL_RATIO); const i = a(t, r); if (t === o && r === s && i.length === c.length) break; o = t; s = r; c = i; } let l = o + s + c.length + separatorCharsFor(o, s, c); while (l > n && (s > 0 || o > 0)) { const e = l - n; if (s > 0) s = Math.max(0, s - e); else o = Math.max(0, o - e); c = a(o, s); l = o + s + c.length + separatorCharsFor(o, s, c); } if (o === 0 && s === 0 && r.length > 0) { const e = a(1, 0); if (1 + e.length + separatorCharsFor(1, 0, e) <= n) { o = 1; c = e; } } const u = sliceUtf16Safe(r, 0, o); const d = s > 0 ? sliceUtf16Safe(r, -s) : ""; const f = renderTruncatedContent(u, c, d); return finish(f.length > n ? truncateUtf16Safe(f, n) : f); } function clampToBudget(e, t) { if (e.length <= t) return e; return t <= 3 ? truncateUtf16Safe(e, t) : `${truncateUtf16Safe(e, t - 1)}…`; } function buildBootstrapContextFiles(e, t) { const n = t?.maxChars ?? 2e4; let r = Math.max(1, Math.floor(t?.totalMaxChars ?? Math.max(n, DEFAULT_BOOTSTRAP_TOTAL_MAX_CHARS))); const i = []; for (const a of e) { if (r <= 0) break; const e = normalizeOptionalString(a.path) ?? ""; if (!e) { t?.warn?.(`skipping bootstrap file "${a.name}" — missing or invalid "path" field (hook may have used "filePath" instead)`); continue; } const appendContext = (t, n = false) => { r = Math.max(0, r - t.length); i.push({ path: e, content: t, ...n && a.personalUser ? { personalUser: a.personalUser } : {} }); }; if (a.missing) { const t = clampToBudget(`[MISSING] Expected at: ${e}`, r); if (!t) break; appendContext(t); continue; } if (r < MIN_BOOTSTRAP_FILE_BUDGET_CHARS) { t?.warn?.(`remaining bootstrap budget is ${r} chars (<${MIN_BOOTSTRAP_FILE_BUDGET_CHARS}); skipping additional bootstrap files`); break; } const o = a.name?.toLowerCase() === USER_BOOTSTRAP_FILENAME.toLowerCase() ? Math.min(n, USER_BOOTSTRAP_MAX_CHARS) : n; const s = Math.max(1, Math.min(o, r)); if (a.personalUser && (a.content ?? "").trimEnd().length > s) { t?.warn?.("Personal USER.md exceeds the bootstrap budget; using shared defaults."); continue; } const c = a.content ?? ""; const l = c.length > s ? sha256Hex(c) : void 0; const u = l && JSON.stringify([ a.name, l, s ]); const d = (u ? trimmedBootstrapCache.get(u) : void 0) ?? trimBootstrapContent(c, a.name, s); if (u) { trimmedBootstrapCache.delete(u); trimmedBootstrapCache.set(u, d); pruneMapToMaxSize(trimmedBootstrapCache, MAX_TRIMMED_BOOTSTRAP_ENTRIES); } if (!d.content) continue; if (d.truncated && t?.warn) { const n = sha256Hex(JSON.stringify([ e, l, s ])); if (!warnedBootstrapTruncations.has(n)) { warnedBootstrapTruncations.add(n); t.warn(`workspace bootstrap file ${a.name} is ${d.originalLength} chars (limit ${d.maxChars}); truncating in injected context`, n); } } appendContext(d.content, true); } return i; } /** Builds bounded context files from already-resolved bootstrap file metadata. */ function buildBootstrapContextForFiles(e, t) { return buildBootstrapContextFiles(e, { maxChars: resolveBootstrapMaxChars(t.config, t.agentId), totalMaxChars: resolveBootstrapTotalMaxChars(t.config, t.agentId), warn: t.warn }); } //#endregion export { resolveBootstrapTotalMaxChars as a, resolveBootstrapMaxChars as i, buildBootstrapContextFiles as n, stripThoughtSignatures as o, buildBootstrapContextForFiles as r, USER_BOOTSTRAP_MAX_CHARS as t };