openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
655 lines (654 loc) • 18.8 kB
JavaScript
import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs";
import { r as estimateStringCharsWithMinimumRawWeight } from "./cjk-chars-CgnWl5qA.mjs";
import { t as truncateUtf8Prefix } from "./utf8-truncate-BH7Ecfuh.mjs";
import { r as jsonUtf8Bytes } from "./json-utf8-bytes-DNwtq2cu.mjs";
import { a as wrapExternalContent, i as truncateSanitizedExternalContent } from "./external-content-CGL7l-3s.mjs";
import "./tool-result-text-budget-DoGfZSLd.mjs";
import { s as toolResultFitsBudget, t as DEFAULT_MAX_LIVE_TOOL_RESULT_CHARS } from "./tool-result-limits-BISboI8s.mjs";
//#region src/agents/code-mode-json-fit.ts
function createJsonPrefixFitter(e, t, n) {
const r = Buffer.byteLength(e, "utf8");
let i;
let a;
let o;
let s;
let c = 0;
let l = 0;
let u = 0;
const d = [];
let f = 256;
return (p) => {
if (p <= 0) return {
text: "",
bytes: 0,
jsonBytes: 2,
budget: {
chars: 2,
contextChars: 4
}
};
if (r <= p && (o ??= Buffer.byteLength(a ??= JSON.stringify(e), "utf8")) + n(r) <= p) return {
text: e,
bytes: r,
jsonBytes: o,
get budget() {
return s ??= {
chars: estimateStringCharsWithMinimumRawWeight(a),
contextChars: estimateStringCharsWithMinimumRawWeight(a, { minimumRawWeight: 2 })
};
}
};
i ??= Buffer.from(e.slice(0, Math.ceil(Math.min(r, t))));
let m = 0;
let h = 2;
let g = 0;
let _ = d.length - 1;
while (g <= _) {
const e = g + _ >>> 1;
const t = d[e];
if (t.end <= p && t.jsonBytes + n(t.end) <= p) {
m = t.end;
h = t.jsonBytes;
g = e + 1;
} else _ = e - 1;
}
while (m < i.byteLength) {
const e = i[m];
const t = e < 128 ? 1 : e < 224 ? 2 : e < 240 ? 3 : 4;
const a = m + t;
if (a >= r || a > p) break;
const o = h + (e === 34 || e === 92 || e === 8 || e === 9 || e === 10 || e === 12 || e === 13 ? 2 : e < 32 ? 6 : t);
if (o + n(a) > p) break;
m = a;
h = o;
if (m >= f) {
d.push({
end: m,
jsonBytes: h
});
f = m + 256;
}
}
const v = i;
let y;
let b;
return {
get text() {
return y ??= v.toString("utf8", 0, m);
},
bytes: m,
jsonBytes: h,
get budget() {
if (!b) {
const e = Math.min(c, m);
const t = Math.max(c, m);
const n = v.toString("utf8", e, t);
const r = m >= c ? 1 : -1;
l += r * (estimateStringCharsWithMinimumRawWeight(n) - (t - e));
u += r * (estimateStringCharsWithMinimumRawWeight(n, { minimumRawWeight: 2 }) - 2 * (t - e));
c = m;
b = {
chars: h + l,
contextChars: 2 * h + u
};
}
return b;
}
};
};
}
//#endregion
//#region src/agents/code-mode-result-preview.ts
const MAX_REFERENCE_BYTES = 768;
const MAX_VISITS = 128;
const MAX_DEPTH = 5;
const MAX_KEYS = 16;
const MAX_ARRAYS = 8;
function sampleIndices(e) {
return e ? [.../* @__PURE__ */ new Set([
0,
Math.floor(e / 2),
e - 1
])] : [];
}
function kind(e) {
return e === null ? "null" : Array.isArray(e) ? "array" : typeof e;
}
function previewText(e, t) {
const n = truncateUtf8Prefix(e, t);
return n === e ? e : `${n}…`;
}
function sampleShape(e) {
if (!isRecord(e)) return kind(e);
const t = [];
for (const n in e) {
t.push(`${JSON.stringify(previewText(n, 40))}:${kind(e[n])}`);
if (t.length === 6) break;
}
return `{${t.join(",")}}`;
}
function sampledValue(e, t = 0) {
if (typeof e === "string") return previewText(e, 48);
if (!isRecord(e) && !Array.isArray(e)) return e;
if (t >= 2) return Array.isArray(e) ? `[array: ${e.length} items]` : "[object]";
if (Array.isArray(e)) return e.slice(0, 2).map((e) => sampledValue(e, t + 1));
const n = Object.create(null);
let r = 0;
for (const i in e) {
n[previewText(i, 40)] = sampledValue(e[i], t + 1);
if (++r === 6) break;
}
return n;
}
function envelopeFields(e) {
if (!isRecord(e)) return;
const t = [];
let n = 0;
for (const r in e) {
if (++n > MAX_KEYS) break;
const i = e[r];
if ((i === null || typeof i !== "object") && (typeof i !== "string" || i.length <= 48)) t.push([previewText(r, 40), i]);
}
t.sort((e, t) => Number(typeof e[1] === "string") - Number(typeof t[1] === "string"));
const r = Object.create(null);
let i = 0;
for (const [e, n] of t) {
r[e] = n;
if (jsonUtf8Bytes(r) > 96) delete r[e];
else if (++i === 4) break;
}
return i ? r : void 0;
}
function inspectArrays(e) {
const t = [{
value: e,
path: "$",
depth: 0
}];
const n = [];
let r = false;
for (const e of t) {
if (!isRecord(e.value) && !Array.isArray(e.value)) continue;
if (Array.isArray(e.value)) {
n.push({
path: e.path,
value: e.value
});
n.sort((e, t) => t.value.length - e.value.length || (e.path < t.path ? -1 : e.path > t.path ? 1 : 0));
if (n.length > MAX_ARRAYS) {
n.pop();
r = true;
}
}
if (e.depth === MAX_DEPTH) {
r = true;
continue;
}
const enqueue = (n, i) => {
if (t.length >= MAX_VISITS || Buffer.byteLength(i) > 192) r = true;
else t.push({
value: n,
path: i,
depth: e.depth + 1
});
};
if (Array.isArray(e.value)) {
const t = sampleIndices(e.value.length);
r ||= t.length < e.value.length;
for (const n of t) enqueue(e.value[n], `${e.path}[${n}]`);
continue;
}
let i = 0;
for (const t in e.value) {
if (++i > MAX_KEYS) {
r = true;
break;
}
if (t.length > 192) {
r = true;
continue;
}
const n = /^[A-Za-z_$][A-Za-z0-9_$]*$/u.test(t) ? `.${t}` : `[${JSON.stringify(t)}]`;
enqueue(e.value[t], e.path + n);
}
}
return {
arrays: n,
limited: r
};
}
/** Keep the usable identity intact; only descriptive samples may shrink. */
function fitCodeModeResultReference(e, t) {
if (jsonUtf8Bytes(e) <= t) return e;
const n = {
...e,
shape: "",
preview: "",
previewTruncated: true
};
const r = t - jsonUtf8Bytes(n);
if (r < 0) return;
const i = 2 + Math.floor(r / 3);
const a = createJsonPrefixFitter(e.shape, i, () => 0)(i);
const o = 2 + r - (a.jsonBytes - 2);
const s = createJsonPrefixFitter(e.preview, o, () => 0)(o);
return {
...n,
shape: a.text,
preview: s.text
};
}
function createCodeModeResultReference(e, t, n) {
const { arrays: r, limited: i } = inspectArrays(n);
const a = r.map(({ path: e, value: t }) => {
const n = sampleIndices(t.length);
const r = [...new Set(n.map((e) => sampleShape(t[e])))];
return {
path: e,
count: t.length,
observed: `sampled ${n.length}/${t.length}${r.length > 1 ? " heterogeneous" : ""}: ${r.join(" | ")}`,
items: n.map((e) => ({
index: e,
value: sampledValue(t[e])
}))
};
});
const o = Buffer.byteLength(t, "utf8");
const s = fitCodeModeResultReference({
id: e,
bytes: o,
count: Array.isArray(n) ? n.length : n !== null && typeof n === "object" ? Object.keys(n).length : 1,
shape: `${i ? "limited traversal; " : ""}${a.length ? a.map((e) => `${e.path}: ${e.count} items, ${e.observed}`).join("; ") : sampleShape(n)}`,
preview: o <= 256 ? t : JSON.stringify(a.length ? {
sampled: true,
traversalLimited: i,
fields: envelopeFields(n),
arrays: a.map(({ observed: e, ...t }) => t)
} : {
sampled: true,
traversalLimited: i,
value: sampledValue(n)
}),
previewTruncated: o > 256
}, MAX_REFERENCE_BYTES);
if (!s) throw new Error("Code Mode reference identity exceeds its descriptor allowance.");
return s;
}
//#endregion
//#region src/agents/tool-search-control-result.ts
/** Shared by budget fitting and delivery so formatting cannot consume unreserved context. */
function serializeToolSearchControlResult(e, t = false) {
return JSON.stringify(e, null, t ? void 0 : 2);
}
/** Shared by the source projector and final formatter; no terminal receipts are consumed here. */
function renderToolSearchControlText(e, t, n = {}) {
if (!t) return {
text: e,
truncated: false
};
const r = n.budget ?? {
maxChars: 16e3,
maxContextChars: Infinity
};
const { maxChars: i } = r;
const a = e.length <= i ? truncateSanitizedExternalContent(e, i) : void 0;
if (a && !a.truncated) {
const e = wrapExternalContent(a.text, { source: "api" });
if (toolResultFitsBudget(e, r)) return {
text: e,
truncated: false
};
}
if (n.allowPartial) {
let t = 0;
let n = i;
let a = "";
while (t <= n) {
const i = Math.floor((t + n) / 2);
const o = truncateSanitizedExternalContent(e, i).text;
const s = wrapExternalContent(`${o}\n[truncated]`, { source: "api" });
if (toolResultFitsBudget(s, r)) {
a = s;
t = i + 1;
} else n = i - 1;
}
if (a) return {
text: a,
truncated: true
};
}
return {
text: wrapExternalContent("[truncated] The tool has already run, but its result exceeds the model output budget and was omitted in full. Do not advance a continuation cursor. For a read-only operation, request a smaller page from the same starting position; do not repeat a mutation just to recover its output.", { source: "api" }),
truncated: true
};
}
//#endregion
//#region src/agents/code-mode-json.ts
function toCodeModeJsonSafe(e) {
if (e === void 0) return null;
if (e === null || typeof e === "string" || typeof e === "boolean") return e;
return JSON.parse(stringifyCodeModeJsonSafe(e));
}
/** Serialize once before checking a data allowance; detachment can happen after admission. */
function stringifyCodeModeJsonSafe(e) {
try {
return JSON.stringify(e) ?? "null";
} catch {
if (e instanceof Error) return JSON.stringify({
name: e.name,
message: e.message
});
switch (typeof e) {
case "number": return JSON.stringify(e);
case "bigint":
case "symbol":
case "function": return JSON.stringify(String(e));
default: return JSON.stringify(Object.prototype.toString.call(e));
}
}
}
const EMPTY_CODE_MODE_OUTPUT = {
count: 0,
source: {
kind: "complete",
json: "[]"
}
};
function sourceBytes(e) {
return e.kind === "prefix" ? e.originalBytes : Buffer.byteLength(e.json, "utf8");
}
function retainSource(e, t, n) {
return t <= n ? {
kind: "complete",
json: e
} : {
kind: "prefix",
json: truncateUtf8Prefix(e, n),
originalBytes: t
};
}
/** Capture after guest conversion, before any public projection discards source facts. */
function captureCodeModeValue(e, t, n = t) {
const r = stringifyCodeModeJsonSafe(e);
const i = r.startsWith("{") || r.startsWith("[") ? Math.max(t, n) : t;
return retainSource(r, Buffer.byteLength(r, "utf8"), i);
}
function captureCodeModeOutput(e, t) {
if (e.length === 0) return EMPTY_CODE_MODE_OUTPUT;
const n = JSON.stringify(e.map(toCodeModeJsonSafe));
return {
count: e.length,
source: retainSource(n, Buffer.byteLength(n, "utf8"), t)
};
}
const TRUNCATION_GUIDANCE = "Output truncated; rerun with narrower args.";
const RETAINED_GUIDANCE = "Full result saved for this run; use results.load(reference.id) in a later exec.";
function jsonBudget(e) {
return {
chars: estimateStringCharsWithMinimumRawWeight(e),
contextChars: estimateStringCharsWithMinimumRawWeight(e, { minimumRawWeight: 2 })
};
}
function retainedMarker(e, t) {
const n = jsonUtf8Bytes({
truncated: true,
reference: null,
guidance: RETAINED_GUIDANCE
}) - 4;
const r = fitCodeModeResultReference(e, t - n);
return r ? {
truncated: true,
reference: r,
guidance: RETAINED_GUIDANCE
} : void 0;
}
function createTruncationMarker(e, t, n = TRUNCATION_GUIDANCE) {
const r = sourceBytes(e);
const i = {
truncated: true,
omittedBytes: r,
guidance: n,
prefix: ""
};
const a = String(r).length;
const o = 10 ** (a - 1);
const s = jsonUtf8Bytes(i) - 2 - a;
let c;
const l = createJsonPrefixFitter(e.json, t, (e) => {
let t = a;
for (let n = o; n > 1 && r - e < n; n /= 10) t--;
return s + t;
});
return (e) => {
const t = l(e);
const n = r - t.bytes;
return {
marker() {
return {
...i,
omittedBytes: n,
prefix: t.text
};
},
budget() {
const e = c ??= jsonBudget(JSON.stringify(i));
const a = String(n).length - String(r).length;
return {
chars: e.chars - 2 + a + t.budget.chars,
contextChars: e.contextChars - 4 + a * 2 + t.budget.contextChars
};
},
prefixBytes: t.bytes,
jsonBytes: s + String(n).length + t.jsonBytes
};
};
}
function createErrorFitter(e, t) {
const n = " [error truncated]";
const r = createJsonPrefixFitter(e, t, () => 18);
return (e) => {
const t = r(e);
return {
text() {
return `${t.text}${n}`;
},
budget() {
return {
chars: t.budget.chars + 18,
contextChars: t.budget.contextChars + 36
};
},
jsonBytes: t.jsonBytes + 18
};
};
}
function boundCodeModeError(e, t) {
return jsonUtf8Bytes(e) <= t ? e : createErrorFitter(e, t)(t).text();
}
/** One bounded cumulative source and delivery receipt, shared across every worker leg. */
var CodeModeOutputState = class {
constructor(e, t) {
this.maxBytes = e;
this.modelBudget = t;
this.source = EMPTY_CODE_MODE_OUTPUT;
this.delivered = {
kind: "entries",
count: 0
};
}
append(e) {
if (e.count === 0) return;
if (this.source.count === 0) {
this.source = e;
return;
}
const t = this.source.source;
const n = sourceBytes(t) + sourceBytes(e.source) - 1;
const r = t.kind === "prefix" ? t.json : t.json.slice(0, -1) + "," + e.source.json.slice(1);
this.source = {
count: this.source.count + e.count,
source: retainSource(r, n, this.maxBytes)
};
}
take(e = {}) {
return this.takeResult({}, e);
}
takeResult(e, t = {}, n = false, r) {
const fit = (t) => {
const r = this.createProjector(t, e);
const fitsTrial = (e) => {
if (n || !this.modelBudget) return fits(r(e));
const t = r(e, "budget");
return t.chars <= this.modelBudget.maxChars && t.contextChars <= this.modelBudget.maxContextChars;
};
const fits = (t) => {
const r = renderToolSearchControlText(serializeToolSearchControlResult({
...e,
...t.channels
}, true), n, { budget: this.modelBudget });
return !r.truncated && toolResultFitsBudget(r.text, this.modelBudget);
};
const i = !n && this.modelBudget && Math.max(this.source.source.json.length, t.value?.json.length ?? 0, t.error?.length ?? 0) > this.modelBudget.maxChars ? void 0 : r(this.maxBytes);
if ((this.modelBudget || n) && !(i ? fits(i) : fitsTrial(this.maxBytes))) {
let e = 0;
let t = this.maxBytes - 1;
let n;
while (e <= t) {
const r = Math.floor((e + t) / 2);
if (fitsTrial(r)) {
n = r;
e = r + 1;
} else t = r - 1;
}
return n === void 0 ? void 0 : r(n);
}
return i ?? r(this.maxBytes);
};
const i = fit(t);
if (!i) throw new Error("Model tool-result budget cannot fit Code Mode status; use a larger model context.");
let a = i;
const fitNonRetention = (e) => fit({
...t,
valueGuidance: e
}) ?? fit({
...t,
valueGuidance: "Not retained; return less data."
}) ?? i;
if (r && t.value && a.valueTruncated && (t.value.json.startsWith("{") || t.value.json.startsWith("["))) {
const e = r(t.value);
if ("reference" in e) {
let n = false;
try {
const r = fit({
...t,
reference: e.reference
});
if (r?.referenceUsed) {
a = r;
n = true;
} else a = fitNonRetention("Not retained: reference exceeds output budget. Return less data.");
} finally {
if (!n) e.release();
}
} else a = fitNonRetention(e.reason);
}
const o = this.delivered;
const { receipt: s, channels: c } = a;
this.delivered = s;
const l = s.kind === "entries" ? c.output.slice(o.kind === "entries" ? o.count : 0) : o.kind === "summary" && o.originalBytes === s.originalBytes && o.prefixBytes === s.prefixBytes ? [] : c.output;
return {
...e,
...c,
output: l
};
}
createProjector(e, t) {
const { count: n, source: r } = this.source;
const { value: i, error: a, reference: o } = e;
const s = n === 0 ? 0 : sourceBytes(r);
const c = o ? jsonUtf8Bytes({
truncated: true,
reference: o,
guidance: RETAINED_GUIDANCE
}) : i === void 0 ? 0 : sourceBytes(i);
const l = o ? retainedMarker({
...o,
shape: "",
preview: "",
previewTruncated: true
}, Infinity) : void 0;
const u = l ? jsonUtf8Bytes(l) : 0;
const d = o ? Math.min(s, createTruncationMarker(r, this.maxBytes)(0).jsonBytes + 2) : 0;
const f = a === void 0 ? 0 : jsonUtf8Bytes(a);
let p;
let m;
let h;
let g;
let _;
let v;
let y;
let b;
let x;
const S = this.maxBytes;
function project(l, C = "channels") {
const w = l - Math.min(s + c, Math.floor(l / 2));
const T = a !== void 0 && f > w ? (x ??= createErrorFitter(a, S))(w) : void 0;
const E = l - (T?.jsonBytes ?? f);
const D = Math.max(Math.floor(E / 2), E >= u + d ? u : 0);
const O = E - Math.min(c, D);
let k;
let A;
if (s <= O) A = s;
else A = (k = (y ??= createTruncationMarker(r, S))(O - 2)).jsonBytes + 2;
const j = E - A;
const M = o ? retainedMarker(o, j) : void 0;
const N = i !== void 0 && (o !== void 0 || i.kind !== "complete" || c > j);
const P = i && !M && N ? (b ??= createTruncationMarker(i, S, e.valueGuidance))(j) : void 0;
if (C === "budget") {
if (!h) {
const n = {
output: null,
...e.value === void 0 ? {} : { value: null },
...e.error === void 0 ? {} : { error: null }
};
const r = jsonBudget(serializeToolSearchControlResult({
...t,
...n
}, true));
const i = Object.keys(n).length * 4;
h = {
chars: r.chars - i,
contextChars: r.contextChars - i * 2
};
}
const n = k?.budget() ?? (g ??= jsonBudget(r.json));
const o = i === void 0 ? void 0 : M ? jsonBudget(JSON.stringify(M)) : P?.budget() ?? (_ ??= jsonBudget(i.json));
const s = a === void 0 ? void 0 : T?.budget() ?? (v ??= jsonBudget(JSON.stringify(a)));
return {
chars: h.chars + n.chars + (k ? 2 : 0) + (o?.chars ?? 0) + (s?.chars ?? 0),
contextChars: h.contextChars + n.contextChars + (k ? 4 : 0) + (o?.contextChars ?? 0) + (s?.contextChars ?? 0)
};
}
return {
receipt: k ? {
kind: "summary",
originalBytes: s,
prefixBytes: k.prefixBytes
} : {
kind: "entries",
count: n
},
valueTruncated: N,
referenceUsed: M !== void 0,
channels: {
output: k ? [k.marker()] : p ??= JSON.parse(r.json),
...i === void 0 ? {} : M ? { value: M } : P ? { value: P.marker() } : m ??= { value: JSON.parse(i.json) },
...a === void 0 ? {} : { error: T?.text() ?? a }
}
};
}
return project;
}
};
//#endregion
export { captureCodeModeValue as a, renderToolSearchControlText as c, captureCodeModeOutput as i, serializeToolSearchControlResult as l, EMPTY_CODE_MODE_OUTPUT as n, stringifyCodeModeJsonSafe as o, boundCodeModeError as r, toCodeModeJsonSafe as s, CodeModeOutputState as t, createCodeModeResultReference as u };