openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
309 lines (308 loc) • 10.9 kB
JavaScript
import { n as extractTextFromChatContent } from "./chat-content-Dkam4EQe.mjs";
import { a as isAssistantTextContentBlockType, c as parseAssistantTextSignature, s as normalizeAssistantPhase } from "./chat-message-content-DNUdbbJ8.mjs";
import { n as trimTextPreservingCode } from "./trim-code-text-Dr7f3RLr.mjs";
import { r as createTextProjection, s as trimTextFilter, t as applyTextFilters } from "./text-projection-DwmQz6_O.mjs";
import { t as findNativeToolMarkerTextBlocks } from "./native-tool-marker-B7dSiPNn.mjs";
import { n as assistantVisibleTextFilters } from "./assistant-visible-text-fPqh5m9O.mjs";
import { a as userFacingTextFilters, i as sanitizeUserFacingText, n as renderUserFacingText } from "./user-facing-text-Dqp3fcZx.mjs";
import { n as createInlineCodeState } from "./code-spans-axVMwnI-.mjs";
import { readAssistantThinkingAppend } from "@openclaw/ai/internal/shared";
import { stripCompactionReplayCheckpointInPlace } from "@openclaw/ai/transports";
//#region src/agents/embedded-agent-utils.ts
function isAssistantMessage(e) {
return e?.role === "assistant";
}
function sanitizeAssistantText(e, t, n = false, r) {
return applyTextFilters(e, assistantVisibleTextFilters(t === "final_answer" ? "final-answer-delivery" : "delivery", n, r));
}
function sanitizeAssistantVisibleStreamText(e, t, n) {
return sanitizeUserFacingText(sanitizeAssistantText(e, t, true, n), {
errorContext: false,
streaming: true
});
}
function createAssistantVisibleStreamText(e, t) {
return createTextProjection([
...assistantVisibleTextFilters(e === "final_answer" ? "final-answer-delivery" : "delivery", true, t),
...userFacingTextFilters(false, true),
trimTextFilter(t?.preserveTrailingWhitespace ? "start" : "both", { preserveCodeIndentation: true })
]);
}
function finalizeAssistantExtraction(e, t) {
return e ? renderUserFacingText(t, { errorContext: true }) : sanitizeUserFacingText(t);
}
function prepareEmbeddedAssistantTextForPhase(e, t, n) {
const r = t === "final_answer" && !n ? findNativeToolMarkerTextBlocks(e) : void 0;
const prepareRender = (t, n) => {
const r = e.stopReason === "error";
return () => {
const e = finalizeAssistantExtraction(r, n());
return t === "final_answer" && !e.trim() ? "" : e;
};
};
const i = normalizeAssistantPhase(e.phase);
if (typeof e.content === "string") {
const r = t === "final_answer" && i !== "final_answer" ? void 0 : t;
if (i !== r) return () => "";
const a = n ? n(e.content, true, i) : e.content;
return prepareRender(r, () => sanitizeAssistantText(a, i));
}
if (!Array.isArray(e.content)) return () => "";
let a = false;
let o = false;
for (const n of e.content) {
if (!n || typeof n !== "object") continue;
const e = n;
if (!isAssistantTextContentBlockType(e.type)) continue;
const r = parseAssistantTextSignature(e)?.phase;
a ||= Boolean(r);
o ||= r === "final_answer" && typeof e.text === "string";
if (a && (t === "commentary" || o)) break;
}
const s = t === "final_answer" && !o && (a || i !== "final_answer") ? void 0 : t;
const c = [];
for (const [n, r] of e.content.entries()) {
if (!r || typeof r !== "object") continue;
const e = r;
if (!isAssistantTextContentBlockType(e.type) || typeof e.text !== "string") continue;
const o = parseAssistantTextSignature(e);
const l = o?.phase ?? (a ? void 0 : i);
if (l !== s) continue;
const u = l ?? (t === "final_answer" && o?.id ? "final_answer" : void 0);
c.push({
text: e.text,
phase: u,
contentIndex: n
});
}
if (n) for (const [e, t] of c.entries()) t.text = n(t.text, e === c.length - 1, t.phase, t.contentIndex);
const l = [];
for (const e of c) {
const t = trimTextPreservingCode(e.text);
const n = l.at(-1);
if (n && n.phase === e.phase && n.contentIndex + 1 === e.contentIndex) {
n.contentIndex = e.contentIndex;
if (t) n.text += `\n${t}`;
} else if (t) l.push({
text: t,
phase: e.phase,
contentIndex: e.contentIndex
});
}
return prepareRender(s, () => l.map(({ text: e, phase: t, contentIndex: n }) => r?.has(n) ? "" : sanitizeAssistantText(e, t)).filter((e) => e.trim()).join("\n").trimEnd());
}
/** Prepare selected source parts now; render their visible text only when requested. */
function prepareAssistantVisibleText(e, t) {
return prepareEmbeddedAssistantTextForPhase(e, "final_answer", t);
}
/** Extract text intended for users, preferring explicit final-answer phase blocks. */
function extractAssistantVisibleText(e, t) {
return prepareAssistantVisibleText(e, t)();
}
function extractAssistantCommentaryText(e, t) {
return prepareEmbeddedAssistantTextForPhase(e, "commentary", t)();
}
function extractEmbeddedAssistantText(e) {
const t = extractTextFromChatContent(e.content, {
sanitizeText: (e) => sanitizeAssistantText(e),
joinWith: "\n",
normalizeText: (e) => e.trimEnd()
}) ?? "";
return finalizeAssistantExtraction(e.stopReason === "error", t);
}
/** Extract native thinking block text; signature-only blocks (no summary) surface nothing. */
function extractAssistantThinking(e) {
if (!Array.isArray(e.content)) return "";
const t = [];
for (const n of e.content) {
if (!n || typeof n !== "object") continue;
const e = Reflect.get(n, "type");
const r = Reflect.get(n, "thinking");
if (e === "thinking" && typeof r === "string") {
const e = r.trim();
if (e) t.push(e);
}
}
return t.join("\n");
}
/** Project native summaries incrementally while retaining snapshot replacement semantics. */
function createAssistantThinkingStream() {
let e = createTextProjection([trimTextFilter("both")]);
let t;
const n = [];
let r = "";
let i = "";
return {
get text() {
return i;
},
update(a, o) {
let s;
let c = 0;
let l = typeof a !== "string" && t !== void 0;
if (Array.isArray(a)) for (const e of a) {
if (e?.type !== "thinking" || typeof e.thinking !== "string") continue;
if (s) {
if (n[c] !== s.thinking) {
l = false;
n[c] = s.thinking;
}
c++;
}
s = e;
}
if (!l || n.length !== c) {
l = false;
n.length = c;
r = c === 0 ? "" : n.map((e) => e.trim()).filter(Boolean).join("\n");
}
const u = typeof a === "string" ? a : s?.thinking ?? "";
const d = s && t !== void 0 ? readAssistantThinkingAppend(s, t) : void 0;
const f = e.text;
const p = u === t ? {
text: f,
delta: ""
} : d !== void 0 ? e.append(d) : e.replace(u);
t = typeof a === "string" ? void 0 : u;
let m = l ? p.delta : null;
if (m !== null && !f && p.text && r) m = "\n" + m;
i = !r ? p.text : m !== null ? i + m : r + (p.text ? "\n" : "") + p.text;
if (!i && o?.trim()) {
i = o.trim();
m = null;
t = void 0;
e = createTextProjection([trimTextFilter("both")]);
}
p.text = i;
p.delta = m;
return p;
}
};
}
function formatReasoningMessage(e) {
const t = e.trim();
if (!t) return "";
return `Thinking\n\n${t.split("\n").map((e) => e ? `_${e}_` : e).join("\n")}`;
}
const THINKING_TAG_NAME_PATTERN = String.raw`(?:(?:antml:|mm:)?(?:think(?:ing)?|thought)|antthinking)`;
const THINKING_TAG_OPEN_RE = new RegExp(String.raw`<\s*${THINKING_TAG_NAME_PATTERN}\s*>`, "i");
const THINKING_TAG_CLOSE_RE = new RegExp(String.raw`<\s*\/\s*${THINKING_TAG_NAME_PATTERN}\s*>`, "i");
const THINKING_TAG_SCAN_RE = new RegExp(String.raw`<\s*(\/?)\s*${THINKING_TAG_NAME_PATTERN}\s*>`, "gi");
const THINKING_TAG_EXACT_RE = new RegExp(String.raw`^<\s*(\/?)\s*${THINKING_TAG_NAME_PATTERN}\s*>$`, "i");
function createAssistantStreamBlockState() {
return {
reasoningDepth: 0,
final: false,
inlineCode: createInlineCodeState()
};
}
function createThinkingTagStreamState() {
return {
scannedOffset: 0,
inThinking: false,
extracted: "",
lastMatchEnd: 0
};
}
function splitThinkingTaggedText(e) {
const t = e.trimStart();
if (!t.startsWith("<") || !THINKING_TAG_OPEN_RE.test(t) || !THINKING_TAG_CLOSE_RE.test(e)) return null;
let n = false;
let r = 0;
const i = [];
const pushBlock = (e, t) => {
const n = e === "thinking" ? t.trim() : t;
if (n) i.push(e === "thinking" ? {
type: e,
thinking: n
} : {
type: e,
text: n
});
};
for (const t of e.matchAll(THINKING_TAG_SCAN_RE)) {
const i = t.index ?? 0;
const a = t[1]?.includes("/") ?? false;
if (a !== n) continue;
pushBlock(n ? "thinking" : "text", e.slice(r, i));
r = i + t[0].length;
n = !a;
}
if (n) return null;
pushBlock("text", e.slice(r));
return i.some((e) => e.type === "thinking") ? i : null;
}
function promoteThinkingTagsToBlocks(e) {
if (!Array.isArray(e.content) || e.content.some((e) => e && typeof e === "object" && e.type === "thinking")) return;
const t = [];
let n = false;
for (const r of e.content) {
if (!r || typeof r !== "object" || !("type" in r) || r.type !== "text") {
t.push(r);
continue;
}
const e = splitThinkingTaggedText(r.text);
if (!e) {
t.push(r);
continue;
}
n = true;
for (const n of e) if (n.type === "thinking") t.push({
type: "thinking",
thinking: n.thinking
});
else if (n.type === "text") {
const e = trimTextPreservingCode(n.text, "start");
if (e) t.push({
type: "text",
text: e
});
}
}
if (!n) return;
e.content = t;
stripCompactionReplayCheckpointInPlace(e);
}
function extractThinkingFromTaggedText(e) {
if (!e) return "";
let t = "";
let n = 0;
let r = false;
for (const i of e.matchAll(THINKING_TAG_SCAN_RE)) {
const a = i.index ?? 0;
if (r) t += e.slice(n, a);
r = !(i[1] === "/");
n = a + i[0].length;
}
return t.trim();
}
function extractThinkingFromTaggedStream(e, t, n) {
const r = e.length - t.scannedOffset === n.length ? n : e.slice(t.scannedOffset);
for (let n = 0; n < r.length; n += 1) {
const i = t.scannedOffset + n;
const a = r[n];
if (a === "<") {
t.pendingTagStart = i;
continue;
}
if (a !== ">" || t.pendingTagStart === void 0) continue;
const o = t.pendingTagStart;
t.pendingTagStart = void 0;
const s = THINKING_TAG_EXACT_RE.exec(e.slice(o, i + 1));
if (!s) continue;
if (t.inThinking) t.extracted += e.slice(t.lastMatchEnd, o);
const c = s[1] === "/";
t.inThinking = !c;
t.lastMatchEnd = i + 1;
t.lastTag = {
type: c ? "close" : "open",
end: i + 1
};
}
t.scannedOffset = e.length;
const i = t.extracted.trim();
if (i || t.lastTag?.type !== "open") return i;
return e.slice(t.lastTag.end).trim();
}
//#endregion
export { extractAssistantCommentaryText as a, extractEmbeddedAssistantText as c, formatReasoningMessage as d, isAssistantMessage as f, sanitizeAssistantVisibleStreamText as h, createThinkingTagStreamState as i, extractThinkingFromTaggedStream as l, promoteThinkingTagsToBlocks as m, createAssistantThinkingStream as n, extractAssistantThinking as o, prepareAssistantVisibleText as p, createAssistantVisibleStreamText as r, extractAssistantVisibleText as s, createAssistantStreamBlockState as t, extractThinkingFromTaggedText as u };