UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

254 lines (253 loc) • 8.3 kB
import { r as truncateUtf16Safe } from "./utf16-slice-CuDyEXgS.mjs"; import { t as LruCache } from "./lru-cache-wquJPIr-.mjs"; import { o as racePromiseWithAbortSignal } from "./src-BPmQBLJp.mjs"; import "./abort-signal-D4Q6SEw7.mjs"; import { h as readLocalFileSafely, u as openLocalFileSafely } from "./fs-safe-BbWvmdVn.mjs"; import { n as ToolInputError } from "./tool-input-error-B1hgavSw.mjs"; import "./common-njQNtpnW.mjs"; import { t as parseSkillsPromptCatalog } from "./skill-prompt-catalog-B-1ym10T.mjs"; import { a as tokenizeDocument, i as scoreLexical, r as prepareTextLexicalDocument, t as getTextLexicalIndex } from "./tool-search-index-BNl_APwM.mjs"; import { readFile } from "node:fs/promises"; //#region src/agents/code-mode-skills.ts /** Select Code Mode skills from the exact catalog rendered into this run's prompt. */ function resolveCodeModeSkills(e) { const t = parseSkillsPromptCatalog(e.skillsPrompt); if (t.length === 0) return []; const n = new Map(e.candidates.map((e) => [e.name, e])); const r = []; for (const { name: e, location: i } of t) { const t = n.get(e); if (!t) continue; r.push({ name: e, description: [t.description, t.locationNote].filter(Boolean).join("\n"), location: i, locationNote: t.locationNote, source: { filePath: t.filePath, readContent: t.readContent } }); } return r; } async function readCodeModeSkill(e, t) { if (typeof e.source.readContent === "string") return e.source.readContent; if (e.reader) return await e.reader({ location: e.location, signal: t }); return await readFile(e.source.filePath, { encoding: "utf8", signal: t }); } //#endregion //#region src/agents/installed-skill-catalog.ts const MAX_QUERY_CHARS = 1e3; const MAX_RESULTS = 20; const MAX_DESCRIPTION_CHARS = 512; const MAX_RESULT_CHARS = 16e3; const MAX_SKILL_INSTRUCTION_BYTES = 262144; const MAX_BODY_SKILLS = 1024; const MAX_BODY_BYTES = 16384; const MAX_INDEX_BODY_BYTES = 4194304; const READ_CONCURRENCY = 4; const localBodies = new LruCache(MAX_BODY_SKILLS, { maxBytes: MAX_INDEX_BODY_BYTES, sizeOf: (e) => e.bytes }); function assertCatalogCurrent(e, t) { t?.throwIfAborted(); for (const t of e) t.assertCurrent?.(); } function assertBodyReadable(e) { if (!e()) throw new ToolInputError("Skill instruction-read permission changed during search."); } async function prepareBodyView(e, t, n) { const r = e.toSorted((e, t) => e.name < t.name ? -1 : e.name > t.name ? 1 : 0).slice(0, MAX_BODY_SKILLS); const i = Math.min(MAX_BODY_BYTES, Math.floor(MAX_INDEX_BODY_BYTES / Math.max(1, r.length))); const a = []; let o = 0; for (let e = 0; e < r.length; e += READ_CONCURRENCY) { const s = await Promise.allSettled(r.slice(e, e + READ_CONCURRENCY).map(async (e) => { n?.throwIfAborted(); e.assertCurrent?.(); assertBodyReadable(t); try { const t = await readSearchBody(e, i, n); o += t?.truncated ? 1 : 0; return t && { value: e, document: t.document }; } catch { return; } finally { n?.throwIfAborted(); e.assertCurrent?.(); assertBodyReadable(t); } })); for (const e of s) { if (e.status === "rejected") throw e.reason; if (e.value) a.push(e.value); } } assertCatalogCurrent(e, n); assertBodyReadable(t); return { bodies: getTextLexicalIndex(a.map(({ document: e }) => e)), skills: a.map(({ value: e }) => e), coverage: { bodyIndexed: a.length, metadataOnly: e.length - a.length, truncatedBodies: o } }; } async function readSearchBody(e, t, n) { const r = e.source.readContent; if (typeof r === "string") { const e = r.slice(0, t); if (e.isWellFormed() && Buffer.byteLength(e) <= t) return { document: prepareTextLexicalDocument(e), truncated: e.length < r.length }; const n = Buffer.from(e); return { document: prepareTextLexicalDocument(n.subarray(0, t).toString("utf8")), truncated: e.length < r.length || n.length > t }; } if (e.readSearchContent) { const r = await e.readSearchContent(t, n); if (Buffer.byteLength(r) > t) throw new Error("Skill search reader exceeded its byte budget."); return { document: prepareTextLexicalDocument(r), truncated: false }; } if (e.reader) return; const i = await openLocalFileSafely({ filePath: e.source.filePath }); try { const { stat: e, exactIdentity: r } = i; const a = JSON.stringify([ i.realPath, String(r.dev), String(r.ino), e.size, e.mtimeMs, e.ctimeMs, t ]); const o = localBodies.get(a); if (o) return o.body; const s = Buffer.alloc(t + 1); let c = 0; while (c < s.length) { n?.throwIfAborted(); const { bytesRead: e } = await i.handle.read(s, c, s.length - c, c); if (e === 0) break; c += e; } const l = { document: prepareTextLexicalDocument(s.subarray(0, Math.min(c, t)).toString("utf8")), truncated: c > t }; localBodies.set(a, { body: l, bytes: l.document.text.length * 2 + a.length * 2 + 256 }); return l; } finally { await i.handle.close(); } } const bodyViews = /* @__PURE__ */ new WeakMap(); /** Search only the prepared, eligible catalog. No filesystem or marketplace discovery. */ async function searchInstalledSkills(e, t, n = 5, r, i = () => false) { const a = t.trim(); if (!a || a.length > MAX_QUERY_CHARS) throw new ToolInputError(`query must contain 1-${MAX_QUERY_CHARS} characters.`); if (!Number.isInteger(n) || n < 1 || n > MAX_RESULTS) throw new ToolInputError(`limit must be an integer between 1 and ${MAX_RESULTS}.`); assertCatalogCurrent(e, r); const o = i(); let s = void 0; if (o) while (!s) { const t = bodyViews.get(e); if (t) s = await racePromiseWithAbortSignal(t, r); else { const t = prepareBodyView(e, i, r); bodyViews.set(e, t.catch(() => { bodyViews.delete(e); })); s = await t; } } const c = [...new Set(tokenizeDocument(a))].map((e) => ({ term: e, weight: 1 })); const l = /* @__PURE__ */ new Map(); for (const { value: t, score: n } of scoreLexical(getTextLexicalIndex(e.map((e) => `${e.name} ${e.description}`)), c)) l.set(e[t], n * 2); if (o && s) for (const { value: e, score: t } of scoreLexical(s.bodies, c)) { const n = s.skills[e]; l.set(n, (l.get(n) ?? 0) + t); } const u = [...l].map(([e, t]) => ({ value: e, score: t })); const d = e.find((e) => e.name === a) ?? e.find((e) => e.name.toLowerCase() === a.toLowerCase()); if (d && !u.some(({ value: e }) => e === d)) u.push({ value: d, score: 0 }); u.sort((e, t) => Number(t.value === d) - Number(e.value === d) || t.score - e.score || (e.value.name < t.value.name ? -1 : e.value.name > t.value.name ? 1 : 0)); const f = []; let p = 0; for (const { value: e } of u.slice(0, n)) { const t = { name: e.name, description: truncateUtf16Safe(e.description, MAX_DESCRIPTION_CHARS), location: e.location }; p += JSON.stringify(t).length; if (p > MAX_RESULT_CHARS) break; f.push(t); } assertCatalogCurrent(e, r); if (o) assertBodyReadable(i); const m = o && s ? s.coverage : { bodyIndexed: 0, metadataOnly: e.length, truncatedBodies: 0 }; return { skills: f, hasMore: u.length > f.length, ...m.metadataOnly || m.truncatedBodies ? { coverage: m } : {} }; } /** Instructions are delivered whole or rejected, never silently truncated. */ async function readInstalledSkill(e, t, n) { n?.throwIfAborted(); const r = e.find((e) => e.name === t); if (!r) throw new ToolInputError(`Skill ${JSON.stringify(t)} is not available to this agent. Search the available skills instead.`); r.assertCurrent?.(); const i = !r.promptListed && typeof r.source.readContent !== "string" && !r.reader ? (await readLocalFileSafely({ filePath: r.source.filePath, maxBytes: MAX_SKILL_INSTRUCTION_BYTES })).buffer.toString("utf8") : await readCodeModeSkill(r, n); n?.throwIfAborted(); r.assertCurrent?.(); if (!r.promptListed && Buffer.byteLength(i, "utf8") > 262144) throw new ToolInputError(`Skill ${JSON.stringify(t)} exceeds the ${MAX_SKILL_INSTRUCTION_BYTES}-byte instruction limit.`); return { name: r.name, location: r.location, ...r.locationNote ? { locationNote: r.locationNote } : {}, content: i }; } //#endregion export { resolveCodeModeSkills as i, readInstalledSkill as n, searchInstalledSkills as r, MAX_SKILL_INSTRUCTION_BYTES as t };