openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
866 lines (865 loc) โข 29.3 kB
JavaScript
import { o as normalizeLowercaseStringOrEmpty } from "./string-coerce-CCIiB4H7.mjs";
import { t as escapeRegExp } from "./regexp-dj3rRPbj.mjs";
import { n as findMarkdownCodeSpans, t as findMarkdownCodeRegions } from "./markdown-code-regions-CUsfah9M.mjs";
import { a as projectLinesOutsideCode, i as isInsideSettledBlockCode, o as stripLinesOutsideCode, r as isInsideCode } from "./code-ranges-2XaqsF-S.mjs";
import { n as trimTextPreservingCode } from "./trim-code-text-Dr7f3RLr.mjs";
import { a as consumeLineBreak, g as skipWhitespace, m as skipHorizontalWhitespace } from "./grammar-BX_b9bJA.mjs";
import { r as findCodeOwnership } from "./code-regions-CfNY0afj.mjs";
import { i as REASONING_TAG_NAMES, n as findMarkdownCodeRegions$1, o as reduceReasoningText, s as scanReasoningTags } from "./reasoning-tags-DL3sP_9k.mjs";
import { c as stripLeadingEmptyLines, i as createTextProjector, n as createConditionalTextProjector, o as leadingEmptyLinesTextFilter, s as trimTextFilter, t as applyTextFilters } from "./text-projection-DwmQz6_O.mjs";
import { i as parseXmlTagAt, n as stripToolCallXmlTags, r as createQuotedStringScanner, t as toolCallXmlTextFilter } from "./tool-call-xml-DSl4fabj.mjs";
import { a as stripPlainTextToolCallBlocks, r as projectPlainTextToolCallBlocks, t as createPlainTextToolCallBraceProbe } from "./payload-DXepDNU7.mjs";
//#region src/shared/text/assistant-text-transforms.ts
const MEMORY_TAG_RE = /<\s*(\/?)\s*relevant[-_]memories\b[^<>]*>/gi;
const MEMORY_TAG_QUICK_RE = /<\s*\/?\s*relevant[-_]memories\b/i;
const LEGACY_BRACKET_TOOL_BLOCK_QUICK_RE = /\[\s*\/?\s*TOOL_(?:CALL|RESULT)\s*\]/i;
const traceIconHeads = [
"๐",
"๐ ๏ธ",
"๐",
"๐",
"๐",
"๐",
"โ๏ธ"
].flatMap((e) => [[e], ["โ ๏ธ", e]]);
const traceChannelHeads = [
"tool call",
"tool result",
"function call"
].flatMap((e) => [
"",
"-",
"_",
" "
].flatMap((t) => [":", "="].map((n) => [e.replace(" ", t), n])));
const traceLineRules = [
{
heads: traceIconHeads,
body: /\s*(?:Session Status|Exec|Read|Edit|Write|Patch|Search|Open|Click|Find|Screenshot|Update Plan|Tool Call|Tool Result|Function Call|Shell|Command)\s*:/
},
{
heads: [["โ ๏ธ", "๐ ๏ธ"]],
body: /\s+(?:(?:Exec|Bash)\s+failed(?:(?:\s+\(exit\s+-?\d+\))|(?:\s*:[^\r\n]*))?|\S[^\r\n]*\s+\(agent\)`{0,2}\s+failed(?:\s*:[^\r\n]*)?)\s*$/
},
{
heads: [["๐ ๏ธ"]],
body: /\s*(?:(?:(?:elevated|pty)\b\s*(?:ยท|,)\s*)+)?(?:`{1,2}\s*\S|(?:run|check|fetch|pull|push|view|show|list|switch|create|merge|rebase|stage|restore|reset|stash|search|find|print|copy|move|remove|install|start|cd|git|pnpm|npm|yarn|bun|node|python|python3|bash|sh)\b)/
},
{
heads: traceChannelHeads,
body: /(?:)/
}
];
const INTERNAL_TRACE_LINE_RE = new RegExp(`^(?:>\\s*)?(?:${traceLineRules.map(({ heads: e, body: t }) => `(?:${e.map((e) => e.map(escapeRegExp).join("\\s*")).join("|")})${t.source}`).join("|")})`, "i");
const traceLineHeads = traceLineRules.flatMap(({ heads: e }) => e.flatMap((e) => [e, [">", ...e]]));
const INTERNAL_TRACE_HEAD_RE = new RegExp(`^[^\\S\\r\\n]*(?:${traceLineHeads.map((e) => e.map(escapeRegExp).join("\\s*")).join("|")})`, "im");
/**
* Strip malformed Minimax tool invocations that leak into text content.
* Minimax sometimes embeds tool calls as XML in text blocks instead of
* proper structured tool calls.
*/
function stripMinimaxToolCallXml(e, t) {
const n = /\]?<\]minimax\[>\[/g;
const r = /\]?<\]minimax\[>\[<tool_call>/g;
const i = /\]?<\]minimax\[>\[<\/tool_call>/g;
if (!e || !/minimax:tool_call/i.test(e) && !r.test(e)) return e;
r.lastIndex = 0;
const a = findMarkdownCodeRegions(e);
let o = "";
let s = 0;
for (const t of e.matchAll(r)) {
const r = t.index;
if (r < s || isInsideCode(r, a)) continue;
i.lastIndex = r + t[0].length;
let c = i.exec(e);
while (c && isInsideCode(c.index, a)) c = i.exec(e);
if (!c) break;
const l = c.index + c[0].length;
o += e.slice(s, r);
if (a.some((e) => e.start >= r && e.end <= l)) {
s = l;
continue;
}
o += e.slice(r, l).replace(n, "");
s = l;
}
o += e.slice(s);
if (!/minimax:tool_call/i.test(o)) return o;
const c = findMarkdownCodeRegions(o);
const l = /(<invoke\b[^>]*>)|<\/?minimax:tool_call>/gi;
let u = "";
let d = 0;
for (const e of o.matchAll(l)) {
const n = e.index ?? 0;
if (n < d || isInsideCode(n, c)) continue;
let r = n + e[0].length;
if (e[1]) {
const e = parseXmlTagAt(o, n);
if (!e || e.isTruncated) continue;
const i = /^\s*[{[]/.test(o.slice(e.end)) ? createQuotedStringScanner(o, e.end) : void 0;
const a = /<\/invoke>/gi;
a.lastIndex = e.end;
let s = a.exec(o);
const l = s;
while (s && (i ? i(s.index) : isInsideCode(s.index, c))) s = a.exec(o);
if (!s && i && t?.recoverUnclosed !== false) s = l;
if (!s) continue;
r = s.index + s[0].length;
}
u += o.slice(d, n);
d = r;
}
u += o.slice(d);
return u;
}
function stripLegacyBracketToolCallBlocks(e) {
if (!e || !LEGACY_BRACKET_TOOL_BLOCK_QUICK_RE.test(e)) return e;
const t = findMarkdownCodeRegions(e);
let n = "";
let r = 0;
for (const i of e.matchAll(/\[\s*TOOL_(CALL|RESULT)\s*\]/gi)) {
const a = i.index;
if (a < r || isInsideCode(a, t)) continue;
const o = a + i[0].length;
const s = i[1]?.toUpperCase() === "RESULT";
const c = s ? /\[\s*\/\s*TOOL_RESULT\s*\]/gi : /\[\s*\/\s*TOOL_CALL\s*\]/gi;
c.lastIndex = o;
let l = c.exec(e);
while (l && isInsideCode(l.index, t)) l = c.exec(e);
const u = e.slice(o, l?.index);
if (!(s ? /^\s*[{[]/.test(u) || /\b(?:tool|result|output|content)\s*=>/i.test(u) || /\b(?:tool|result|output|content)\s*:/i.test(u) : /\btool\s*=>\s*["'][A-Za-z_][A-Za-z0-9_.:-]{0,119}["']/i.test(u) && /\bargs\s*=>/i.test(u))) continue;
n += e.slice(r, a);
r = l ? l.index + l[0].length : e.length;
if (r === e.length) break;
}
return n + e.slice(r);
}
function stripRelevantMemoriesTags(e) {
if (!e || !MEMORY_TAG_QUICK_RE.test(e)) return e;
MEMORY_TAG_RE.lastIndex = 0;
const t = findMarkdownCodeRegions(e);
let n = "";
let r = 0;
let i = false;
for (const a of e.matchAll(MEMORY_TAG_RE)) {
const o = a.index ?? 0;
if (isInsideCode(o, t)) continue;
const s = a[1] === "/";
if (!i) {
n += e.slice(r, o);
if (!s) i = true;
} else if (s) i = false;
r = o + a[0].length;
}
if (!i) n += e.slice(r);
return n;
}
function stripAssistantInternalTraceLines(e) {
if (!INTERNAL_TRACE_HEAD_RE.test(e)) return e;
return stripLinesOutsideCode(e, (e) => INTERNAL_TRACE_LINE_RE.test(e.trim()));
}
function stripInvisibleAssistantText(e) {
return /^[\p{White_Space}\p{Default_Ignorable_Code_Point}]*$/u.test(e) ? "" : e;
}
const plainToolCallTransform = (e) => stripPlainTextToolCallBlocks(e, { resolveProtectedRanges: findMarkdownCodeRegions });
//#endregion
//#region src/shared/text/downgraded-tool-call-text.ts
function consumeJsonish(e, t) {
let n = t;
while (n < e.length && /[ \t\r\n]/.test(e[n] ?? "")) n += 1;
const r = e[n];
if (r === void 0) return null;
if (r !== "{" && r !== "[" && r !== "\"") {
while (n < e.length && e[n] !== "\n" && e[n] !== "\r") n += 1;
return n;
}
let i = r === "\"" ? 0 : 1;
let a = r === "\"";
let o = false;
for (n += 1; n < e.length; n += 1) {
const t = e[n];
if (a) {
if (o) o = false;
else if (t === "\\") o = true;
else if (t === "\"") a = false;
} else if (t === "\"") a = true;
else if (t === "{" || t === "[") i += 1;
else if (t === "}" || t === "]") i -= 1;
if (!a && i === 0) return n + 1;
}
return null;
}
function stripDowngradedToolCalls(e) {
let t;
let n = "";
let r = 0;
for (const i of e.matchAll(/\[Tool Call:[^\]]*\]/gi)) {
const a = i.index;
if (a < r || isInsideCode(a, t ??= findMarkdownCodeRegions$1(e))) continue;
n += e.slice(r, a);
let o = skipHorizontalWhitespace(e, a + i[0].length);
o = skipHorizontalWhitespace(e, consumeLineBreak(e, o) ?? o);
if (normalizeLowercaseStringOrEmpty(e.slice(o, o + 9)) === "arguments") {
o += 9;
if (e[o] === ":") o += 1;
if (e[o] === " ") o += 1;
o = consumeJsonish(e, o) ?? o;
}
if (!n || n.endsWith("\n") || n.endsWith("\r")) o = consumeLineBreak(e, o) ?? o;
r = o;
}
return n + e.slice(r);
}
/**
* Strip downgraded tool call text representations that leak into user-visible
* text content when replaying history across providers.
*/
function stripDowngradedToolCallText(e, t) {
if (!e || !/\[Tool (?:Call|Result)/i.test(e) && !/\[Historical context/i.test(e)) return e;
let n = stripDowngradedToolCalls(e);
for (const e of [/\[Tool Result for ID[^\]]*\]\n?[\s\S]*?(?=\n*\[Tool |\n*$)/gi, /\[Historical context:[^\]]*\]\n?/gi]) {
const t = n;
let r;
n = t.replace(e, (e, n) => isInsideCode(n, r ??= findMarkdownCodeRegions$1(t)) ? e : "");
}
return trimTextPreservingCode(n, t?.preserveTrailingWhitespace ? "start" : "both");
}
function downgradedToolCallTextFilter(e) {
return {
transform: (t) => stripDowngradedToolCallText(t, e),
activationTokens: [
"[Tool Call",
"[Tool Result",
"[Historical context"
]
};
}
//#endregion
//#region src/shared/text/internal-scaffolding-stages.ts
const names = [
"reasoning",
"modelTokens",
"memories",
"xml",
"trace",
"legacy",
"plain",
"leading",
"invisible"
];
/** The internal-scaffolding profile has one order for batch and streaming callers. */
function orderInternalScaffoldingStages(e) {
return names.map((t) => e[t]);
}
//#endregion
//#region src/shared/text/model-special-token-transform.ts
const MODEL_SPECIAL_TOKEN_RE = /<[|๏ฝ][^|๏ฝ\s]*[|๏ฝ]>/g;
/** Blank-line boundary the canonical ownership parser uses to settle reference definitions. */
function findLastBlankLine(e) {
let t = -1;
for (const n of e.matchAll(/(?:\r\n|\n|\r(?!\n))[ \t]*(?:\r\n|\n|\r(?!\n))/g)) t = n.index;
return t;
}
function projectModelSpecialTokens$1(e, t) {
if (!e) return {
text: e,
codeOwnershipPending: false,
hasRetainedInlineCode: false
};
MODEL_SPECIAL_TOKEN_RE.lastIndex = 0;
if (!MODEL_SPECIAL_TOKEN_RE.test(e)) return {
text: e,
codeOwnershipPending: false,
hasRetainedInlineCode: false
};
MODEL_SPECIAL_TOKEN_RE.lastIndex = 0;
const n = /[`~\t]| {4}/u.test(e) ? t?.(e) : void 0;
const r = n?.regions ?? findMarkdownCodeRegions(e);
const i = n?.definitions.length ? findLastBlankLine(e) : -1;
let a = n?.definitions.some((e) => e.end > i) ?? false;
const o = n?.retainStart ?? e.length;
const s = n?.textSpans.some(([t, n]) => n > o && e.slice(Math.max(t, o), n).includes("["));
const c = /[\r\n]/.test(e.slice(o));
let l = false;
let u = "";
let d = 0;
for (const t of e.matchAll(MODEL_SPECIAL_TOKEN_RE)) {
const n = t[0];
const i = t.index ?? 0;
const f = i + n.length;
u += e.slice(d, i);
const p = r.find((e) => i < e.end && f > e.start);
if (p) {
u += n;
if (!p.block && p.end > o) {
l = true;
a ||= s || c;
}
} else {
a ||= e.lastIndexOf("`", f - 1) >= o && e.includes("`", i);
if (/(?:\p{L}|\p{M}|\p{N})$/u.test(u.slice(-2)) && /^[\p{L}\p{N}]/u.test(e.slice(f, f + 2))) u += " ";
}
d = f;
}
u += e.slice(d);
return {
text: u,
codeOwnershipPending: a,
hasRetainedInlineCode: l
};
}
/**
* Strips leaked model control tokens like `<|assistant|>` or full-width pipe variants.
* Code examples are preserved; remove this when providers stop emitting these tokens.
*
* @see https://github.com/openclaw/openclaw/issues/40020
*/
function stripModelSpecialTokens(e) {
return projectModelSpecialTokens$1(e).text;
}
//#endregion
//#region src/shared/text/model-special-tokens.ts
const TOKEN_START_RE = /<[|๏ฝ]/;
function findLastPipe(e, t) {
return Math.max(e.lastIndexOf("|", t), e.lastIndexOf("๏ฝ", t));
}
function endsWithIncompleteTokenPrefix(e) {
if (e.endsWith("<")) return true;
const t = findLastPipe(e, e.length - 1);
if (t < 1) return false;
if (t === e.length - 1) {
const n = findLastPipe(e, t - 1);
if (n > 0 && e[n - 1] === "<") return true;
return e[t - 1] === "<";
}
if (e[t - 1] !== "<") return false;
return !/[\s|๏ฝ]/.test(e.slice(t + 1));
}
function endsWithCompleteToken(e) {
if (!e.endsWith(">")) return false;
const t = findLastPipe(e, e.length - 2);
if (t < 1) return false;
const n = findLastPipe(e, t - 1);
return n > 0 && e[n - 1] === "<" && !/[\s|๏ฝ]/.test(e.slice(n + 1, t));
}
function endsWithTokenBeforeIncompleteSurrogate(e) {
return /[\uD800-\uDBFF]$/u.test(e) && endsWithCompleteToken(e.slice(0, -1));
}
function projectModelSpecialTokens(e) {
return projectModelSpecialTokens$1(e, (e) => findCodeOwnership(e, { includeText: true }));
}
/**
* Streams the same stripping without re-parsing the settled prefix after a leak. Once a
* token has appeared, deltas that cannot start or complete one append directly; the
* canonical transform only runs for an unstable tail, a token-ending separator, a backtick
* delta, a fence-capable tilde run that can change whether an earlier token is code-owned,
* or Markdown ownership is unsettled according to the canonical parser.
*/
function createModelSpecialTokenProjector() {
let e = 0;
let t = "";
let n = false;
let r = "";
let i = false;
let a = false;
let o = "";
let s = false;
let c = false;
const projectFull = (l, u) => {
e = l.length;
const d = projectModelSpecialTokens(l);
const f = d.text;
s = d.codeOwnershipPending;
c = d.hasRetainedInlineCode;
const p = u === null ? null : f.startsWith(t) ? f.slice(t.length) : null;
t = f;
n ||= TOKEN_START_RE.test(l);
r = l.slice(-1);
i = endsWithIncompleteTokenPrefix(l);
a = endsWithCompleteToken(l) || endsWithTokenBeforeIncompleteSurrogate(l) || a && /[\uD800-\uDBFF]$/u.test(l);
o = l.slice(-2);
return {
text: f,
delta: p
};
};
return (l) => {
if (l.delta === null) return projectFull(l.text, null);
const u = l.delta;
if (l.text.length !== e + u.length) return projectFull(l.text, u);
if (!n) {
const i = r + u;
n = TOKEN_START_RE.test(i);
r = i.slice(-1);
if (!n) {
e = l.text.length;
t = l.text;
return l;
}
return projectFull(l.text, u);
}
const d = u.includes("`") || u.includes("~~~") || (o + u).includes("~~~");
if (s || i || a || TOKEN_START_RE.test(u) || d || c && /[\r\n]/.test(u)) return projectFull(l.text, u);
e = l.text.length;
t += u;
i = u.endsWith("<");
o = l.text.slice(-2);
return {
text: t,
delta: u
};
};
}
/** Delivery filter: batch parity through `transform`, bounded work through `create`. */
const modelSpecialTokensTextFilter = {
transform: stripModelSpecialTokens,
create: createModelSpecialTokenProjector
};
//#endregion
//#region packages/markdown-core/src/reasoning-tags-batch.ts
/** Strips reasoning tags using the same reducer as streamed partitioning. */
function stripReasoningTagsFromMarkdown(e, t) {
return reduceReasoningText(e, findMarkdownCodeSpans(e), {
depth: 0,
visibleEver: false
}, {
final: true,
mode: t.recoverUnclosed === false ? "hide" : t.mode === "preserve" ? "static-preserve" : "static-strict",
scope: t.scope
}).filter((e) => e.kind === "text").map((e) => e.text).join("");
}
//#endregion
//#region src/shared/text/tag-name-probe.ts
/** Proves tag absence; the canonical transform owns attributes and Markdown after activation. */
function createTagNameProbe(e) {
let t;
let n = false;
return ({ text: r, delta: i }) => {
if (n) return true;
for (const a of i ?? r) if (a === "<") t = "";
else if (t !== void 0) {
if ((t === "" || t === "/") && /\s/u.test(a)) continue;
if (t === "" && a === "/") {
t = "/";
continue;
}
const r = t.startsWith("/") ? t.slice(1) : t;
if (e.includes(r) && /[\s/>]/u.test(a)) {
n = true;
return true;
}
t += a.toLowerCase();
const i = t.startsWith("/") ? t.slice(1) : t;
if (!e.some((e) => e.startsWith(i))) t = void 0;
}
return false;
};
}
//#endregion
//#region src/shared/text/final-tags.ts
const FINAL_TAG_NAME = "final";
const FINAL_TAG_CANDIDATE_RE = /<[^<>]*>/g;
function parseAttributeList(e) {
const t = /[^\s=/"'<>]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'<>]+))?/y;
let n = skipWhitespace(e, 0);
while (n < e.length) {
t.lastIndex = n;
if (!t.test(e)) return false;
n = skipWhitespace(e, t.lastIndex);
}
return true;
}
/** Parses a candidate `<final>` tag while rejecting lookalike names and malformed attributes. */
function parseFinalTag(e) {
let t = e.slice(1, -1).trimStart();
let n = false;
if (t.startsWith("/")) {
n = true;
t = t.slice(1).trimStart();
}
if (!t.toLowerCase().startsWith("final")) return null;
const r = t[5] ?? "";
if (r && !/\s/.test(r) && r !== "/") return null;
let i = t.slice(5);
if (n) return i.trim().length === 0 ? {
isClose: true,
isSelfClosing: false
} : null;
const a = i.trimEnd();
const o = a.endsWith("/");
i = o ? a.slice(0, -1) : i;
if (!parseAttributeList(i)) return null;
return {
isClose: false,
isSelfClosing: o
};
}
/** Finds valid `<final>` control tags so callers can strip only actual model markers. */
function findFinalTagMatches(e) {
const t = [];
for (const n of e.matchAll(FINAL_TAG_CANDIDATE_RE)) {
const e = n[0];
const r = parseFinalTag(e);
if (!r) continue;
t.push({
index: n.index ?? 0,
text: e,
...r
});
}
return t;
}
/** Removes final-answer markers outside Markdown code while preserving their enclosed answer. */
function stripFinalTags(e, t) {
const n = findFinalTagMatches(e).filter((e) => e.index >= (t?.contentStart ?? 0));
if (n.length === 0) return e;
const r = t?.codeRegions() ?? findMarkdownCodeRegions(e);
let i = 0;
let a = "";
let o = 0;
for (const t of n) {
let n = r[i];
while (n && n.end <= t.index) {
i += 1;
n = r[i];
}
if (n && n.start <= t.index) continue;
a += e.slice(o, t.index);
o = t.index + t.text.length;
}
a += e.slice(o);
return a;
}
const finalTagTextFilter = {
transform: stripFinalTags,
create: () => createConditionalTextProjector(stripFinalTags, createTagNameProbe([FINAL_TAG_NAME]), (e, t, n) => {
const r = e.lastIndexOf("<") > e.lastIndexOf(">") ? e.lastIndexOf("<") : Infinity;
const i = findFinalTagMatches(e).some((e) => e.index < t && e.index + e.text.length > t);
const a = t > n.contentStart && r >= t && !i;
return {
text: stripFinalTags(e, n),
retainStart: a ? t : n.contentStart,
retainedOutputStart: a ? stripFinalTags(e.slice(0, t), n).length : n.contentStart
};
})
};
//#endregion
//#region src/shared/text/reasoning-tags.ts
const THINKING_TAG_NAMES = [
"think",
"thinking",
"thought",
"antthinking",
"antml:think",
"antml:thinking",
"antml:thought",
"mm:think",
"mm:thinking",
"mm:thought"
];
const REASONING_AND_FINAL_TAG_NAMES = [...REASONING_TAG_NAMES, FINAL_TAG_NAME];
const REASONING_OR_FINAL_TAG_RE = new RegExp(`<\\s*\\/?\\s*(?:${REASONING_AND_FINAL_TAG_NAMES.map(escapeRegExp).join("|")})(?=[\\s/>])`, "i");
/** Detects whether a stray reasoning close tag separates two visible text regions. */
function hasOrphanReasoningCloseBoundary(e) {
return e.before.trim().length > 0 && e.after.trim().length > 0;
}
/** Strips model reasoning/final tags from visible text while preserving literal code examples. */
function stripReasoningTagsFromText(e, t) {
if (!e || !REASONING_OR_FINAL_TAG_RE.test(e)) return e;
const n = t?.mode ?? "strict";
const r = t?.trim ?? "both";
const i = t?.scope ?? "all";
let a = e;
const o = findFinalTagMatches(a);
if (o.length > 0) a = stripFinalTags(a);
const s = scanReasoningTags(a).tags.length > 0;
if (o.length === 0 && !s) return e;
const c = s ? stripReasoningTagsFromMarkdown(a, {
mode: n,
scope: i,
recoverUnclosed: t?.recoverUnclosed
}) : a;
if (r === "none") return c;
return r === "start" ? c.trimStart() : c.trim();
}
/** Final-marker deletion and reasoning reduction own separate Markdown streams. */
function reasoningTagTextFilter(e) {
const transform = (t) => stripReasoningTagsFromText(t, {
...e,
trim: "none"
});
return {
transform,
create() {
const t = {
transform: (t) => stripReasoningTagsFromMarkdown(t, e),
create() {
let n = {
visibleEver: false,
rawBefore: false,
terminalLiteral: false
};
const reduce = (t, r, i, a, o) => {
const s = {
depth: 0,
visibleEver: n.visibleEver
};
const c = {
...n,
boundary: a,
reset: false,
lastReset: -1,
holdStart: Infinity
};
return {
output: n.terminalLiteral ? t.slice(r) : reduceReasoningText(t, i, s, {
start: r,
scope: e.scope,
final: o,
mode: !e.recoverUnclosed ? "hide" : e.mode === "preserve" ? "static-preserve" : "static-strict",
checkpoint: c
}).filter((e) => e.kind === "text").map((e) => e.text).join(""),
state: s,
effect: c
};
};
return createConditionalTextProjector(t.transform, createTagNameProbe(REASONING_TAG_NAMES), (e, t, r) => {
const i = r.contentStart;
const a = r.codeRegions().map((e) => [e.start, e.end]);
const o = reduce(e, i, a, t, true);
const s = scanReasoningTags(e.slice(i), false).pendingStart;
const c = Math.min(o.effect.holdStart, s === void 0 ? Infinity : i + s);
const l = t > i && c >= t && o.effect.lastReset < t ? reduce(e.slice(0, t), i, a, t, false) : void 0;
const u = l !== void 0 && l.effect.holdStart >= t && l.state.depth === 0 && l.effect.reset === o.effect.reset;
return {
text: e.slice(0, i) + o.output,
resetSettled: o.effect.reset,
retainStart: u ? t : i,
retainedOutputStart: i + (l?.output.length ?? 0),
commit: u && l ? () => {
n = {
visibleEver: l.state.visibleEver,
rawBefore: l.effect.rawBefore,
terminalLiteral: l.effect.terminalLiteral
};
} : void 0
};
});
}
};
return createTextProjector([finalTagTextFilter, t]);
}
};
}
//#endregion
//#region src/shared/text/assistant-internal-scaffolding.ts
const transforms = orderInternalScaffoldingStages({
reasoning: (e) => stripReasoningTagsFromText(e, {
mode: "preserve",
scope: "all",
trim: "none",
recoverUnclosed: true
}),
modelTokens: stripModelSpecialTokens,
memories: stripRelevantMemoriesTags,
xml: stripToolCallXmlTags,
trace: stripAssistantInternalTraceLines,
legacy: stripLegacyBracketToolCallBlocks,
plain: plainToolCallTransform,
leading: stripLeadingEmptyLines,
invisible: stripInvisibleAssistantText
});
function stripAssistantInternalScaffolding(e) {
let t = e;
for (const e of transforms) t = e(t);
return t;
}
//#endregion
//#region src/shared/text/assistant-visible-text.ts
const invisibleTextFilter = {
transform: stripInvisibleAssistantText,
create: () => {
let e = false;
let t = 0;
let n = "";
const r = createConditionalTextProjector(() => "", (r) => {
if (!e) {
const i = n + (r.delta ?? r.text);
n = /[\uD800-\uDBFF]$/.test(i) ? i.slice(-1) : "";
e = Boolean(stripInvisibleAssistantText(n ? i.slice(0, -1) : i));
if (e) t = r.text.length;
}
return !e;
});
r.canReplaceFrom = (n) => e && n >= t;
return r;
}
};
const profileFilters = /* @__PURE__ */ new Map();
function assistantVisibleTextFilters(e, t = false, n) {
const r = `${e}:${t}:${Boolean(n?.preserveTrailingWhitespace)}`;
const i = profileFilters.get(r);
if (i) return i;
const a = e === "internal-scaffolding";
const o = e === "delivery" || e === "final-answer-delivery";
const s = a || e === "history" ? "none" : n?.preserveTrailingWhitespace ? "start" : "both";
const c = reasoningTagTextFilter({
mode: a ? "preserve" : "strict",
scope: e === "final-answer-delivery" ? "leading" : "all",
recoverUnclosed: !t
});
if (a) {
const e = orderInternalScaffoldingStages({
reasoning: c,
modelTokens: modelSpecialTokensTextFilter,
memories: {
transform: stripRelevantMemoriesTags,
activationTokens: ["relevant-memories", "relevant_memories"]
},
xml: toolCallXmlTextFilter({}, t),
trace: assistantTraceTextFilter,
legacy: legacyBracketToolCallTextFilter,
plain: plainToolCallTextFilter,
leading: leadingEmptyLinesTextFilter,
invisible: invisibleTextFilter
});
profileFilters.set(r, e);
return e;
}
const l = [
minimaxToolCallTextFilter(t),
modelSpecialTokensTextFilter,
{
transform: stripRelevantMemoriesTags,
activationTokens: ["relevant-memories", "relevant_memories"]
},
toolCallXmlTextFilter({
stripFunctionCallsXmlPayloads: e === "tool-progress",
stripFunctionResponseAfterPluralToolCalls: e === "delivery" || e === "final-answer-delivery"
}, t),
...e === "tool-progress" ? [] : [assistantTraceTextFilter],
legacyBracketToolCallTextFilter,
plainToolCallTextFilter,
downgradedToolCallTextFilter(n)
];
l.push(c);
l.push(trimTextFilter(s, { preserveCodeIndentation: o }), invisibleTextFilter);
profileFilters.set(r, l);
return l;
}
function minimaxToolCallTextFilter(e = false) {
return {
transform: (t) => stripMinimaxToolCallXml(t, { recoverUnclosed: !e }),
activationTokens: ["minimax:tool_call", "<]minimax[>[<tool_call>"]
};
}
const legacyBracketToolCallTextFilter = {
transform: stripLegacyBracketToolCallBlocks,
activationTokens: ["TOOL_CALL", "TOOL_RESULT"]
};
const assistantTraceTextFilter = {
transform: stripAssistantInternalTraceLines,
create() {
let e = false;
const resetLine = () => traceLineHeads.map((e) => ({
parts: e,
part: 0,
offset: 0
}));
let t = resetLine();
return createConditionalTextProjector(stripAssistantInternalTraceLines, (n) => {
if (e) return true;
const r = n.delta ?? n.text;
for (let n = 0; n < r.length; n++) {
const i = r.charAt(n).toLowerCase();
if (i === "\n") {
t = resetLine();
continue;
}
const a = /\s/.test(i);
t = t.filter((t) => {
if (t.offset === 0 && a) return true;
if (t.parts[t.part]?.charAt(t.offset) !== i) return false;
t.offset++;
if (t.offset === t.parts[t.part]?.length) {
t.part++;
t.offset = 0;
e ||= t.part === t.parts.length;
}
return true;
});
if (e) return true;
if (t.length === 0) {
const e = r.indexOf("\n", n + 1);
if (e === -1) break;
n = e - 1;
}
}
return false;
}, (e, t) => projectLinesOutsideCode(e, (e) => INTERNAL_TRACE_LINE_RE.test(e.trim()), t));
}
};
const plainToolCallActivationTokens = [
"<parameter=",
"<function=",
"to="
];
function createPlainToolCallTextProjector(e = false) {
const checkpoint = (t, n, r) => projectPlainTextToolCallBlocks(t, {
resolveProtectedRanges: r.codeRegions,
settleBefore: n,
preview: e,
isProtectionSettled: (e) => e < n || isInsideSettledBlockCode(e, t, r.codeRegions())
});
const t = new RegExp(plainToolCallActivationTokens.map(escapeRegExp).join("|"), "i");
const n = Math.max(...plainToolCallActivationTokens.map((e) => e.length - 1));
const r = createPlainTextToolCallBraceProbe(e);
let i = false;
let a = "";
return createConditionalTextProjector(plainToolCallTransform, (e) => {
if (!i) {
const o = a + (e.delta ?? e.text);
i = t.test(o) || r(e.delta ?? e.text);
a = !i && n ? o.slice(-n) : "";
}
return i;
}, checkpoint);
}
const plainToolCallTextFilter = {
transform: plainToolCallTransform,
create: createPlainToolCallTextProjector
};
/** Channel previews share the call grammar, but cannot expose its provisional tail. */
const plainToolCallPreviewTextFilter = {
transform: plainToolCallTransform,
create: () => createPlainToolCallTextProjector(true)
};
/**
* Settlement of a plain-text tool-call candidate at the end of visible text. Streaming may
* publish that tail and retract it later through a replacement, but block replies
* (already-delivered chat messages) cannot be retracted, so their drain waits until the
* candidate settles.
*/
function hasUnsettledPlainTextToolCall(e) {
if (!e) return false;
return projectPlainTextToolCallBlocks(e, { resolveProtectedRanges: findMarkdownCodeRegions$1 }).unsettled;
}
function sanitizeAssistantVisibleTextWithProfile(e, t = "delivery", n = false) {
return applyTextFilters(e, assistantVisibleTextFilters(t, n));
}
/**
* Canonical user-visible assistant text sanitizer for delivery and history
* extraction paths. Keeps prose, removes internal scaffolding.
*/
function sanitizeAssistantVisibleText(e) {
return sanitizeAssistantVisibleTextWithProfile(e, "delivery");
}
/**
* Backwards-compatible trim wrapper.
* Prefer sanitizeAssistantVisibleTextWithProfile for new call sites.
*/
function sanitizeAssistantVisibleTextWithOptions(e, t) {
return sanitizeAssistantVisibleTextWithProfile(e, t?.trim === "none" ? "history" : "delivery");
}
//#endregion
export { downgradedToolCallTextFilter as _, minimaxToolCallTextFilter as a, sanitizeAssistantVisibleText as c, stripAssistantInternalScaffolding as d, THINKING_TAG_NAMES as f, findFinalTagMatches as g, finalTagTextFilter as h, legacyBracketToolCallTextFilter as i, sanitizeAssistantVisibleTextWithOptions as l, stripReasoningTagsFromText as m, assistantVisibleTextFilters as n, plainToolCallPreviewTextFilter as o, hasOrphanReasoningCloseBoundary as p, hasUnsettledPlainTextToolCall as r, plainToolCallTextFilter as s, assistantTraceTextFilter as t, sanitizeAssistantVisibleTextWithProfile as u, stripDowngradedToolCallText as v };