openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
176 lines (175 loc) • 6.08 kB
JavaScript
import { i as createAbortError } from "../src-BPmQBLJp.mjs";
import { t as isAbortError } from "../abort-signal-D4Q6SEw7.mjs";
import { n as runCommandWithTimeout } from "../exec-runner-Br73vG-X.mjs";
import "../exec-aRIvS9s4.mjs";
import { t as fromMarkdown } from "../lib-spciPqyM.mjs";
import { i as shouldLogVerbose, r as logVerbose } from "../globals-CgepmiqE.mjs";
import "../http-body-B9w7rzPz.mjs";
import { i as readResponseWithLimit, t as cancelUnreadResponseBody } from "../http-response-body-B-i_0116.mjs";
import { o as isBlockedHostnameOrIp } from "../ssrf-DHBNJw0c.mjs";
import { r as fetchWithSsrFGuard, t as GUARDED_FETCH_MODE } from "../fetch-guard-BLMw2n18.mjs";
import { c as resolveTimeoutMs, l as CLI_OUTPUT_MAX_BUFFER, s as resolveScopeDecision } from "../resolve-Qea3Nian.mjs";
import { t as finalizeInboundContext } from "../inbound-context-0zDtB0Zn.mjs";
import { r as decodeResponseBytes } from "../web-shared-DLIuWlIC.mjs";
import { t as applyTemplate } from "../templating-C8TE1xGN.mjs";
import "../defaults-pk9GvaEF.mjs";
//#region packages/markdown-core/src/link-spans.ts
/** Returns parser-owned source spans for links, images, and reference definitions. */
function findMarkdownLinkSourceSpans(e) {
const t = [];
const n = [fromMarkdown(e)];
while (n.length > 0) {
const e = n.pop();
if (!e) continue;
if ([
"link",
"image",
"linkReference",
"imageReference",
"definition"
].includes(e.type)) {
const n = e.position?.start?.offset;
const r = e.position?.end?.offset;
if (n !== void 0 && r !== void 0) t.push([n, r]);
continue;
}
for (const t of e.children ?? []) n.push(t);
}
return t.toSorted((e, t) => e[0] - t[0]);
}
//#endregion
//#region src/link-understanding/apply.ts
const BARE_LINK_RE = /https?:\/\/\S+/gi;
function isLinkUrlTemplate(e) {
return e.includes("LinkUrl") || e.includes("LinkFinalUrl");
}
async function fetchLinkContent(e) {
const { response: t, finalUrl: n, release: r } = await fetchWithSsrFGuard({
url: e.url,
timeoutMs: e.timeoutMs,
mode: GUARDED_FETCH_MODE.STRICT,
auditContext: "link-understanding",
signal: e.signal,
init: { headers: {
Accept: "text/*,application/json,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"User-Agent": "OpenClaw-LinkUnderstanding/1.0"
} }
});
try {
if (!t.ok) {
cancelUnreadResponseBody(t);
throw new Error(`Link fetch failed with HTTP ${t.status}`);
}
const e = await readResponseWithLimit(t, CLI_OUTPUT_MAX_BUFFER);
const r = decodeResponseBytes(t, e).trim();
if (!r) return null;
return {
content: r,
finalUrl: n
};
} finally {
await r();
}
}
async function applyLinkUnderstanding(e) {
const t = e.cfg.tools?.links;
if (!t || t.enabled === false) return;
if (resolveScopeDecision({
scope: t.scope,
ctx: e.ctx
}) === "deny") {
if (shouldLogVerbose()) logVerbose("Link understanding disabled by scope policy.");
return;
}
const n = (e.ctx.CommandBody ?? e.ctx.RawBody ?? e.ctx.Body ?? "").trim();
if (!n) return;
const r = typeof t.maxLinks === "number" && Number.isFinite(t.maxLinks) && t.maxLinks > 0 ? Math.floor(t.maxLinks) : 3;
const i = [];
let a = 0;
for (const [e, t] of findMarkdownLinkSourceSpans(n)) {
i.push(n.slice(a, e), " ");
a = t;
}
i.push(n.slice(a));
const o = /* @__PURE__ */ new Set();
const s = [];
for (const e of i.join("").matchAll(BARE_LINK_RE)) {
const t = e[0]?.trim();
if (!t) continue;
const n = URL.parse(t);
if (!n || n.protocol !== "http:" && n.protocol !== "https:" || isBlockedHostnameOrIp(n.hostname) || o.has(t)) continue;
o.add(t);
s.push(t);
if (s.length >= r) break;
}
if (s.length === 0) return;
const c = t?.models ?? [];
if (c.length === 0) return;
const l = [];
const u = t.timeoutSeconds != null ? resolveTimeoutMs(t.timeoutSeconds, 30) : Math.max(...c.map((e) => resolveTimeoutMs(e.timeoutSeconds, 30)));
for (const n of s) {
if (e.signal?.aborted) break;
let r;
try {
r = await fetchLinkContent({
url: n,
timeoutMs: u,
signal: e.signal
});
} catch (t) {
if (e.signal?.aborted) throw createAbortError("Link understanding fetch aborted", { cause: e.signal.reason });
if (isAbortError(t)) throw t;
if (shouldLogVerbose()) logVerbose("Link understanding fetch blocked or failed.");
continue;
}
if (!r) continue;
let i;
for (const a of c) {
if (e.signal?.aborted) break;
try {
if ((a.type ?? "cli") !== "cli") continue;
const o = a.command.trim();
if (!o) continue;
const s = a.args ?? [];
const c = (o.split(/[\\/]/).pop() ?? o).toLowerCase();
if ((c === "curl" || c === "wget") && s.some(isLinkUrlTemplate)) {
i = r.content;
break;
}
const l = { ...e.ctx };
const u = [o, ...s.filter((e) => !isLinkUrlTemplate(e)).map((e) => applyTemplate(e, l))];
const d = await runCommandWithTimeout(u, {
timeoutMs: resolveTimeoutMs(a.timeoutSeconds ?? t.timeoutSeconds, 30),
input: r.content,
signal: e.signal,
killProcessTree: true,
env: {
OPENCLAW_LINK_FINAL_URL: r.finalUrl,
OPENCLAW_LINK_URL: n
}
});
if (e.signal?.aborted) throw createAbortError("Link understanding command aborted", { cause: e.signal.reason });
if (d.code !== 0) throw new Error(`Link understanding command exited with code ${d.code ?? "unknown"}`);
i = d.stdout.trim();
if (i) break;
} catch (e) {
if (isAbortError(e)) throw e;
if (shouldLogVerbose()) logVerbose("Link understanding CLI failed; trying the next entry.");
}
}
if (e.signal?.aborted) break;
l.push(i || r.content);
}
if (l.length === 0 || e.signal?.aborted) return;
e.ctx.LinkUnderstanding = [...e.ctx.LinkUnderstanding ?? [], ...l];
const d = l.join("\n");
const enrich = (e) => {
const t = (e ?? "").trim();
return t ? `${t}\n\n${d}` : d;
};
e.ctx.agentText = enrich(e.ctx.agentText ?? e.ctx.BodyForAgent ?? e.ctx.Body);
e.ctx.Body = enrich(e.ctx.Body);
finalizeInboundContext(e.ctx, { forceBodyForCommands: true });
}
//#endregion
export { applyLinkUnderstanding };