UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

581 lines (580 loc) • 19.2 kB
import { n as sliceUtf16Safe, t as avoidTrailingHighSurrogateBreak } from "./utf16-slice-CuDyEXgS.mjs"; import { a as findFenceSpanAt, c as scanFenceSpans, o as isSafeFenceBreak, r as findCodeOwnership } from "./code-regions-CfNY0afj.mjs"; import { t as formatFencedCodeBlock } from "./markdown-code-C5it6V4Q.mjs"; import { n as firstGraphemeClusterLength, t as findGraphemeChunkEnd } from "./grapheme-B63AW15X.mjs"; import { i as findMarkdownTableRanges } from "./ir-Ctdn8mF1.mjs"; //#region src/agents/embedded-agent-block-chunker.code.ts /** Project parser-owned code into the chunker's existing balanced-fence path. */ function prepareIndentedCode(e, t, n, r) { const i = t + e; let a = /\t| {4}/u.test(i) ? findCodeOwnership(i, { includeIndentedSource: true }) : void 0; const o = []; const s = []; let c = 0; let l = 0; if (a) for (const i of a.regions) { const a = i.indentedSource; if (!a || a.nested || i.end <= t.length) continue; const u = Math.max(0, i.start - t.length); const d = i.end - t.length; const f = a.offsets[Math.max(0, t.length - i.start)] ?? 0; const p = a.value.slice(f); const m = formatFencedCodeBlock(p); const h = m.indexOf("\n") + 1; const g = r - h * 2; if (g < 1 || g === 1 && /[\u{10000}-\u{10ffff}]/u.test(p) || a.offsets.some((e, t) => e - (a.offsets[t - 1] ?? 0) > g)) continue; const _ = !e.slice(d).trim(); const v = _ && !n ? m.slice(0, h + p.length) : m; const y = e.slice(c, u); s.push(y, v); l += y.length; o.push({ from: u, to: d, start: l, end: l + v.length, bodyStart: l + h, bodyEnd: l + h + p.length, valueStart: f, regionStart: i.start - t.length, code: a, open: _ }); l += v.length; c = d; if (_ && !n) break; } if (!o.at(-1)?.open || n) s.push(e.slice(c)); const u = o.length ? s.join("") : e; const sourceIndex = (e, t) => { const n = e.code.offsets; let r = 0; let i = n.length; while (r < i) { const e = r + i >>> 1; if (n[e] <= t) r = e + 1; else i = e; } return Math.max(0, r - 1); }; return { text: u, startsWithCode: o[0]?.from === 0, toSource(e) { let t = 0; for (const n of o) { if (e < n.start) break; if (e <= n.end) { if (e <= n.bodyStart) return n.from; if (e >= n.bodyEnd) return n.to; return n.regionStart + sourceIndex(n, n.valueStart + e - n.bodyStart); } t += n.end - n.start - (n.to - n.from); } return e - t; }, codeBoundary(e, t) { const n = o.find((t) => t.bodyStart < e && e < t.bodyEnd); if (!n) return e; const r = Math.max(t - 1, n.bodyStart); let i = e; while (i > r + 1 && (/\s/u.test(u.charAt(i)) || /\s/u.test(u.charAt(i - 1)))) i -= 1; i = avoidTrailingHighSurrogateBreak(u, r, i); if (/\s/u.test(u.charAt(i)) || /\s/u.test(u.charAt(i - 1))) i = e; const a = sourceIndex(n, n.valueStart + i - n.bodyStart); return avoidTrailingHighSurrogateBreak(u, r, n.bodyStart + n.code.offsets[a] - n.valueStart); }, contextAt(n) { const r = `x${e.charAt(n - 1) === "\n" ? "\n" : ""}`; const s = o.find((e) => e.from < n && (n < e.to || e.open && n === e.to)); if (s) return `${s.code.context}${r}`; const c = t.length + n; const l = a ??= findCodeOwnership(i, { includeIndentedSource: true }); for (const e of l.regions) { const t = e.indentedSource; if (t?.nested && t.ownerStart < c && c <= e.end) { const e = t.context.length; return c < t.ownerStart + e ? t.context.slice(0, c - t.ownerStart) : `${t.context}${r}`; } } const u = l.paragraphs?.find((e) => e.start < c && (c <= e.end || !i.slice(e.end, c).trim())); if (!u) return ""; return c > u.end ? `x${i.slice(u.end, c)}` : r; } }; } //#endregion //#region src/agents/embedded-agent-block-chunker.tables.ts function canRenderIndependently(e, t) { if (t.start === 0) return true; const n = findMarkdownTableRanges(e.slice(t.start, t.end))[0]; return n?.start === 0 && n.end === t.end - t.start; } function continuationHeader(e, t, n) { if (!canRenderIndependently(e, t)) return ""; const r = e.indexOf("\n", e.indexOf("\n", t.start) + 1) + 1; const i = e.slice(t.start, r); return r > t.start && r < t.end && i.length < n && e.slice(r, t.end).split("\n").every((e) => i.length + e.length <= n) ? i : ""; } /** * Keep fitting tables whole and split larger tables only at complete rows. * Their headers frame each continuation so channel renderers can parse it. */ function findTableSpans(e, t, n, r) { const i = findMarkdownTableRanges(e); const fits = (e) => e.end - e.start <= n && isSafeFenceBreak(t, e.start); const a = i.filter((r) => { if (fits(r)) return true; if (!isSafeFenceBreak(t, r.start)) return false; const i = continuationHeader(e, r, n); if (!i) return false; r.header = i; return true; }); if (!r || !e.includes("|")) return a; const o = i.at(-1); if (o && !/\n[^\n]*\n/.test(e.slice(o.end))) { if (a.at(-1) === o && !o.header) o.end = e.length; return a; } const s = e.lastIndexOf("\n") + 1; const c = e.slice(s); const l = e.lastIndexOf("\n", s - 2) + 1; const u = { start: s > 0 && /^[\s>|:-]*$/.test(c) && e.slice(l, s).includes("|") ? l : c.includes("|") ? s : e.length, end: e.length }; if (u.start < e.length && fits(u)) a.push(u); return a; } /** A replayed delivery boundary may end the visible source in the middle of a table. */ function findTableContinuationAtBoundary(e, t) { const n = findMarkdownTableRanges(e).at(-1); return n && /^\r?\n?$/.test(e.slice(n.end)) ? continuationHeader(e, n, t) : ""; } /** Keep a synthetic header only while the pending source can still continue its table. */ function resolveTableContinuation(e, t, n) { if (!e) return ""; const r = findMarkdownTableRanges(e + t)[0]; return r?.start === 0 && r.end > e.length || !n && !t.includes("\n") ? e : ""; } /** Framing is excluded from source accounting, just like a reopened code fence. */ function findTableContinuationHeader(e, t, n, r, i) { return r.find((r) => r.header && t > r.start + r.header.length && e.charAt(t) === "\n" && (t < r.end && n <= r.end || t >= r.end && i && /^\r?\n?$/.test(e.slice(r.end))))?.header ?? ""; } /** * Break before a table, between rows of a larger table, or wait for a fitting * streaming table to end. Returns undefined when no table owns the cut. */ function findTableBreakIndex(e, t, n, r) { const i = t + n; const a = r.tables.find((e) => e.start < i && i <= e.end); if (!a) return; if (a.start > t) { const n = e.slice(0, a.start - t).trimEnd().length; if (n > 0 && isSafeFenceBreak(r.fences, t + n)) return n; } if (a.header) { const r = e.lastIndexOf("\n", n); return r > 0 && t + r > a.start + a.header.length ? r : void 0; } return a.start <= t && a.end === t + e.length && /^\r?\n?$/.test(e.slice(n)) ? -1 : void 0; } //#endregion //#region src/agents/embedded-agent-block-chunker.ts function findFenceCloseLineStart(e, t, n = 0) { const r = Math.min(e.length, Math.max(0, t.end - n)); if (r <= 0) return -1; const i = e.lastIndexOf("\n", r - 1); if (i < 0) return -1; const a = e.slice(i + 1, r).match(/^ {0,3}(`{3,}|~{3,})[ \t]*\r?$/)?.[1]; return a && a.charAt(0) === t.marker.charAt(0) && a.length >= t.marker.length ? i + 1 : -1; } function resolveFenceReopenLine(e, t) { const n = `${e.indent}${e.marker}`; if (n.length * 2 + 3 > t) return; return e.openLine.length + n.length + 3 <= t ? e.openLine : n; } var EmbeddedBlockChunker = class { #e = ""; #t = ""; #n = ""; #r = 0; #i = []; #a = []; #o = 0; #s = 0; #c = 0; #l = true; #u = ""; #d; constructor(e) { this.#d = e; } append(e) { if (!e) return; this.#e += e; } /** Start a new source scope without emitting pending text. */ reset(e = [], t = 0) { this.#e = ""; this.#t = ""; this.#n = ""; this.#r = 0; this.#i = []; this.#a = e; this.#o += 1; this.#s = t; this.#c = 0; this.#l = true; this.#u = ""; } /** UTF-16 source positions exclude synthetic framing and include skipped whitespace. */ get consumedLength() { return this.#r; } /** Prepared source boundaries are not evidence that a recipient received a chunk. */ get preparedSourceBreaks() { return this.#i; } get sourceLength() { return this.#r + this.#e.length; } /** Replace pending source; the snapshot owner can attest that the consumed prefix is unchanged. */ replace(e, t = 0, n = false) { const readMaxChars = () => Math.max(1, Math.floor(this.#d?.minChars ?? 1), Math.floor(this.#d?.maxChars ?? Infinity)); const r = t - this.#r; const i = this.#e.slice(0, Math.max(0, r)) + e.slice(Math.max(0, -r)); const a = i !== this.#e; if (!i.startsWith(this.#e) || t + e.length < this.#r) { this.#a = []; this.#c = 0; } this.#e = i; if (t === 0 && e.length < this.#r) { const { spans: t, state: n } = scanFenceSpans(e); const r = n.open ? t.at(-1) : void 0; const i = readMaxChars(); const a = r && this.#d ? resolveFenceReopenLine(r, i) : void 0; this.#t = a ? `${a}\n` : ""; this.#u = prepareIndentedCode(e, "", true, i).contextAt(e.length); } const o = Math.min(this.#r, t + e.length); if (this.#n && t === 0 && !n) this.#n = findTableContinuationAtBoundary(e.slice(0, o), readMaxChars()); if (!n && t === 0 && this.#u && o > 0) { const t = readMaxChars(); this.#u = prepareIndentedCode(e, "", true, t).contextAt(o); } if (o === 0) { this.#l = true; this.#u = ""; } else if (o > t) this.#l = e.charAt(o - t - 1) === "\n"; else if (o < this.#r) this.#l = false; this.#r = o; while ((this.#i.at(-1) ?? 0) > this.#r) this.#i.pop(); return a; } get bufferedText() { return this.#e ? `${this.#t || this.#n}${this.#e}` : ""; } hasBuffered() { return this.#e.length > 0; } drain(e) { const t = this.#a; while (this.#c < t.length) { const n = t[this.#c] - this.#r; if (n <= 0) { this.#c += 1; continue; } if (n > this.#e.length) break; const r = this.bufferedText.length; const i = this.#e.slice(n); this.#e = this.#e.slice(0, n); this.#f(e, r, true); if (this.#a !== t) return; const a = this.#e.length === 0; this.#e += i; if (!a) return; this.#c += 1; } this.#f(e); } #f(e, t = 0, n = false) { const { emit: r } = e; const i = this.#r; const a = this.#i; const o = this.#d; if (!this.#e || !e.force && !o) return; const s = Math.max(1, Math.floor(o?.minChars ?? 1)); const c = Math.max(s, Math.floor(o?.maxChars ?? Infinity)); const sourceBoundaryLength = (e, t) => e.slice(t).match(/^(?:\n[\t ]*)+/)?.[0].length ?? 0; const nextTextStart = (t, n) => { const r = sourceBoundaryLength(t, n); return e.force && n + r === t.length || r >= c ? n + r : n; }; this.#n = resolveTableContinuation(this.#n, this.#e, e.force || this.#e.length + this.#n.length >= c); const l = this.#t || this.#n; const emitChunk = (e, t, o, s) => { a.push(i + o); r(e, { sourceText: this.#e.slice(t, o), sourceGeneration: this.#o, reconciledSourceBreak: n || void 0, sourceStart: this.#s + this.#r + t, sourceEnd: this.#s + this.#r + o, startsAtLineStart: s }); }; if (!o) { emitChunk(this.bufferedText, 0, this.#e.length, Boolean(l) || this.#l); this.#l = this.#e.endsWith("\n"); this.#r += this.#e.length; this.#e = ""; this.#t = ""; this.#n = ""; this.#u = ""; return; } const u = e.force || t >= c; const d = this.bufferedText; if (d.length < s && !u) return; const f = prepareIndentedCode(d, this.#u, u, c); let p = f.text; const m = Boolean(l) || f.startsWithCode || this.#l; if (p.length < s && !u) return; const { spans: h, state: g } = scanFenceSpans(p, { atLineStart: m }); const _ = g.open ? h.at(-1) : void 0; if (u && p.length <= c && !l && !_) { if (p.trim().length > 0) emitChunk(p, 0, this.#e.length, m); this.#l = this.#e.endsWith("\n"); this.#u = f.contextAt(d.length); this.#r += this.#e.length; this.#e = ""; this.#t = ""; this.#n = n ? findTableContinuationAtBoundary(p, c) : ""; return; } const v = []; let y = 0; for (const e of h) { e.start -= y; e.end -= y; const t = resolveFenceReopenLine(e, c); const n = e === _ ? e.indent.length + e.marker.length + 1 : 0; if (!t || t === e.openLine || e.end - e.start + n <= c) continue; p = p.slice(0, e.start) + t + p.slice(e.start + e.openLine.length); const r = e.openLine.length - t.length; v.push({ at: e.start + t.length, length: r }); e.openLine = t; e.end -= r; y += r; } const b = findTableSpans(p, h, c, !u); const x = b.length > 0 ? [...h, ...b].toSorted((e, t) => e.start - t.start) : h; const S = { fences: h, tables: b, unsafe: x }; const originalIndex = (e) => v.reduce((t, n) => t + (n.at <= e ? n.length : 0), e); const sourceOffset = (e) => Math.max(0, f.toSource(originalIndex(e)) - l.length); let C = 0; let w; let T = ""; const emitSourceChunk = (e, t, n) => emitChunk(e, sourceOffset(t), sourceOffset(n), Boolean(w || T) || (t === 0 ? m : p.charAt(t - 1) === "\n")); const E = this.#t ? h[0] : void 0; if (E) { const e = findFenceCloseLineStart(p, E); if (e >= this.#t.length && !p.slice(this.#t.length, e).trim()) C = skipLeadingNewlines(p, E.end); } while (C < p.length) { const t = w ? `${w.reopenFenceLine}\n` : T; const n = t.length + (p.length - C); if (!u && n < s) break; if (o.flushOnParagraph && !u) { const e = findNextParagraphBreak(p, h, C, s); const r = Math.max(1, c - t.length); if (e !== null && e - C <= r) { const n = `${t}${p.slice(C, e)}`; const r = nextTextStart(p, e); if (n.trim().length > 0) emitSourceChunk(n, C, r); C = r; w = void 0; T = ""; continue; } if (n < c) break; } const r = p.slice(C); const i = sourceBoundaryLength(p, C); if (i === r.length) break; if (i >= c - t.length) { C += i; continue; } const a = Math.max(u ? 1 : s, i + 1); const l = u && n <= c && !_ ? this.#p(r, x, o, false, a, C, _) : this.#m({ ...e, force: u }, r, S, o, a, C, c - t.length, _); if (l.index <= 0) { if (u) { emitSourceChunk(`${t}${p.slice(C)}`, C, p.length); C = p.length; w = void 0; T = ""; } break; } if (l.fenceSplit) { const e = f.codeBoundary(originalIndex(C + l.index), originalIndex(C + 1)); let t = 0; for (const n of v) if (n.at + t <= e) t += n.length; l.index = sliceUtf16Safe(r, 0, e - t - C).length; } if (l.index <= 0) continue; const d = C + l.index; let m = d; let g = `${t}${p.slice(C, m)}`; let y; let E = ""; const D = l.fenceSplit; if (g.trim().length === 0) { g = ""; m = skipLeadingNewlines(p, m); } else if (D) { g += g.endsWith("\n") ? D.closeFenceLine : `\n${D.closeFenceLine}`; if (m === findFenceCloseLineStart(p, D.fence)) m = skipLeadingNewlines(p, D.fence.end); else y = D; } else { if (m < p.length && /[^\S\n]/.test(p.charAt(m))) m += 1; const e = skipLeadingNewlines(p, m); E = findTableContinuationHeader(p, d, e, b, !u); if (e > d && b.some((t) => t.start === e)) { const t = p.slice(d, e); if (g.length + t.length <= c) g += t; m = e; } else m = E ? e : nextTextStart(p, m); const t = p.slice(d, m); if (m === p.length && /^\n[\t \n]*$/.test(t) && g.length + t.length <= c) g += t; } if (g) emitSourceChunk(g, C, m); C = m; w = y; T = E; const O = (w ? `${w.reopenFenceLine}\n`.length : T.length) + (p.length - C); if (!u && (O < s || O < c && !o.flushOnParagraph)) break; } if (!w) C = nextTextStart(p, C); if (C === 0) return; const D = sourceOffset(C); if (D > 0) this.#l = this.#e.charAt(D - 1) === "\n"; this.#u = f.contextAt(D + l.length); this.#r += D; this.#e = this.#e.slice(D); this.#t = !this.#u && w ? `${w.reopenFenceLine}\n` : ""; this.#n = this.#u ? "" : T || (n ? findTableContinuationAtBoundary(p, c) : ""); } #p(e, t, n, r, i, a = 0, o) { const s = Math.max(1, Math.floor(i ?? n.minChars)); if (e.length < s) return { index: -1 }; const c = n.breakPreference ?? "paragraph"; const l = c === "paragraph" ? ["\n\n", "\n"] : c === "newline" ? ["\n"] : []; for (const n of l) { let i = r ? e.lastIndexOf(n) : e.indexOf(n); while (r ? i >= s : i !== -1) { for (let r = i; r < i + n.length; r++) if (r >= s && isSafeFenceBreak(t, a + r)) { while (r > s && e[r - 1] === "\n") { if (!isSafeFenceBreak(t, a + r - 1)) break; r -= 1; } return { index: r }; } i = r ? e.lastIndexOf(n, i - 1) : e.indexOf(n, i + n.length); } } if (c !== "newline") { const n = e.matchAll(/[.!?](?=\s|$)/g); let r = -1; for (const e of n) { const n = e.index; if (n < s) continue; const i = n + 1; if (a + i !== o?.end && isSafeFenceBreak(t, a + i)) r = i; } if (r >= s) return { index: r }; } return { index: -1 }; } #m({ force: e, mutablePreview: t }, n, r, i, a, o = 0, s, c) { const l = Math.max(1, Math.floor(a ?? i.minChars)); const u = Math.max(1, Math.floor(s ?? i.maxChars)); if (n.length < l) return { index: -1 }; const d = n.slice(0, Math.min(u, n.length)); const f = this.#p(d, r.unsafe, i, true, l, o, c); if (f.index !== -1) return f; if (n.length < u && !e) return { index: -1 }; const p = findTableBreakIndex(n, o, d.length, r); if (p !== void 0) return { index: p }; for (let e = d.length - 1; e >= l; e--) if (/\s/.test(d.charAt(e)) && isSafeFenceBreak(r.unsafe, o + e)) return { index: e }; if (n.length >= u || e) { const a = (n.codePointAt(0) ?? 0) > 65535 ? 2 : 1; const s = sliceUtf16Safe(n, 0, Math.max(u, a)).length; const d = o + s; const f = findFenceSpanAt(r.fences, d - 1); if (f?.end === d && f !== c) return { index: s }; const p = findFenceSpanAt(r.fences, d) ?? (c?.end === d ? c : void 0); if (p) { const e = resolveFenceReopenLine(p, i.maxChars); if (!e) return { index: s }; const t = `${p.indent}${p.marker}`; const r = sliceUtf16Safe(n, 0, Math.max(1, u - t.length - 1)).length; if (r <= 0) return { index: s }; const a = findFenceCloseLineStart(n, p, o); return { index: a >= l && a <= r ? a : r, fenceSplit: { closeFenceLine: t, reopenFenceLine: e, fence: p } }; } const m = !e && !t; const h = !e && /[\uD800-\uDBFF]$/u.test(n) ? n.slice(0, -1) : n; const g = Math.min(s, h.length - (m ? 1 : 0)); const _ = findGraphemeChunkEnd(h, 0, g, g, false); if (m && _ > 0 && n.length === s) return { index: 0 }; return { index: _ || (firstGraphemeClusterLength(h) >= s ? s : 0) }; } return { index: -1 }; } }; function skipLeadingNewlines(e, t = 0) { let n = t; while (n < e.length && e[n] === "\n") n++; return n; } function findNextParagraphBreak(e, t, n = 0, r = 1) { const i = /\n[\t ]*\n+/g; i.lastIndex = n; let a; while ((a = i.exec(e)) !== null) { const e = a.index; if (e - n < r) continue; const o = findFenceSpanAt(t, e); if (o) { i.lastIndex = o.end; continue; } return e; } return null; } //#endregion export { EmbeddedBlockChunker as t };