openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
6 lines • 8.25 kB
JavaScript
import{r as truncateUtf16Safe}from"./utf16-slice-DA3Mllbx.mjs";import{o as racePromiseWithAbortSignal}from"./src-De06gkOi.mjs";import{t as LruCache}from"./lru-cache-BkKrgG7y.mjs";import"./abort-signal-BKkRe6pu.mjs";import{c as openLocalFileSafely,p as readLocalFileSafely}from"./fs-safe-Bxzu1j4h.mjs";import{n as ToolInputError}from"./tool-input-error-BCfbFipG.mjs";import"./common-DIgvX97L.mjs";import{t as parseSkillsPromptCatalog}from"./skill-prompt-catalog-IMhfPb42.mjs";import{a as tokenizeDocument,i as scoreLexical,r as prepareTextLexicalDocument,t as getTextLexicalIndex}from"./tool-search-index-D6Fb4jw6.mjs";import{readFile}from"node:fs/promises";import{isUtf8}from"node:buffer";
//!src/agents/code-mode-skills.ts
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(`
`),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})}
//!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 searchViews=/* @__PURE__ */ new WeakMap;const catalogViews=new LruCache(4,{maxBytes:67108864,sizeOf:e=>e.bytes});function getSearchView(e){const t=searchViews.get(e);if(t)return t;if(e.some(e=>!e.catalogRevision))return;const n=prepareTextLexicalDocument(JSON.stringify(e.map(e=>[e.catalogRevision,e.name,e.description]))).revision;let r=catalogViews.get(n);if(!r){r={key:n,bytes:128+n.length*2,bodies:{}};catalogViews.set(n,r)}searchViews.set(e,r);return r}const preparedBodies=new LruCache(MAX_BODY_SKILLS*2,{maxBytes:MAX_INDEX_BODY_BYTES*3,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),searchViews.get(e)?.bodies),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 n=e.catalogRevision?`inline:${JSON.stringify([e.catalogRevision,t])}`:void 0;const i=n&&preparedBodies.get(n);if(i)return i.body;const a=r.slice(0,t);const o=!n&&a.isWellFormed()&&Buffer.byteLength(a)<=t?void 0:Buffer.from(a);const s=o?o.subarray(0,t).toString(`utf8`):a;const c={document:prepareTextLexicalDocument(s),truncated:a.length<r.length||o!==void 0&&o.length>t};if(n)preparedBodies.set(n,{body:c,bytes:s.length*2+n.length*2+256});return c}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=preparedBodies.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};preparedBodies.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;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=getSearchView(e);const s=i();let c=void 0;if(s)while(!c){const t=bodyViews.get(e);if(t)c=await racePromiseWithAbortSignal(t,r);else{const t=prepareBodyView(e,i,r);bodyViews.set(e,t.catch(()=>{bodyViews.delete(e)}));c=await t}}const l=[...new Set(tokenizeDocument(a))].map(e=>({term:e,weight:1}));const u=/* @__PURE__ */ new Map;const d=o?.metadata??getTextLexicalIndex(e.map(e=>`${e.name} ${e.description}`));if(o){o.metadata=d;catalogViews.delete(o.key);o.bytes=128+(o.key.length+(o.bodies.revision?.length??0))*2+d.bytes+(o.bodies.index?.bytes??0);catalogViews.set(o.key,o)}for(const{value:t,score:n}of scoreLexical(d,l))u.set(e[t],n*2);if(s&&c)for(const{value:e,score:t}of scoreLexical(c.bodies,l)){const n=c.skills[e];u.set(n,(u.get(n)??0)+t)}const f=[...u].map(([e,t])=>({value:e,score:t}));const p=e.find(e=>e.name===a)??e.find(e=>e.name.toLowerCase()===a.toLowerCase());if(p&&!f.some(({value:e})=>e===p))f.push({value:p,score:0});f.sort((e,t)=>Number(t.value===p)-Number(e.value===p)||t.score-e.score||(e.value.name<t.value.name?-1:e.value.name>t.value.name?1:0));const m=[];let h=0;for(const{value:e}of f.slice(0,n)){const t={name:e.name,description:truncateUtf16Safe(e.description,MAX_DESCRIPTION_CHARS),location:e.location};h+=JSON.stringify(t).length;if(h>MAX_RESULT_CHARS)break;m.push(t)}assertCatalogCurrent(e,r);if(s)assertBodyReadable(i);const g=s&&c?c.coverage:{bodyIndexed:0,metadataOnly:e.length,truncatedBodies:0};return{skills:m,hasMore:f.length>m.length,...g.metadataOnly||g.truncatedBodies?{coverage:g}:{}}}async function readInstalledSkill(e,t,n,r){n?.throwIfAborted();const i=e.find(e=>e.name===t);if(!i)throw new ToolInputError(`Skill ${JSON.stringify(t)} is not available to this agent. Search the available skills instead.`);i.assertCurrent?.();let a;if(r!==void 0){if(!r||r.split(`/`).includes(`..`)||/[\\\0]|^(?:\/|~(?:\/|$)|[a-z]:)/iu.test(r))throw new ToolInputError(`relativePath must stay inside the skill directory.`);if(!i.resourceRoot)throw new ToolInputError(`This placement is instruction-only; omit relativePath.`);const e=await i.resourceRoot;n?.throwIfAborted();i.assertCurrent?.();const{buffer:t}=await e.read(r,MAX_SKILL_INSTRUCTION_BYTES);if(t.includes(0)||!isUtf8(t))throw new ToolInputError(`Skill companions must be UTF-8 text without NUL bytes.`);a=t.toString(`utf8`)}else a=!i.promptListed&&typeof i.source.readContent!==`string`&&!i.reader?(await readLocalFileSafely({filePath:i.source.filePath,maxBytes:MAX_SKILL_INSTRUCTION_BYTES})).buffer.toString(`utf8`):await readCodeModeSkill(i,n);n?.throwIfAborted();i.assertCurrent?.();if(r===void 0&&!i.promptListed&&Buffer.byteLength(a,`utf8`)>262144)throw new ToolInputError(`Skill ${JSON.stringify(t)} exceeds the ${MAX_SKILL_INSTRUCTION_BYTES}-byte instruction limit.`);return{name:i.name,location:i.location,...r!==void 0?{relativePath:r}:{},...i.locationNote?{locationNote:i.locationNote}:{},content:a}}export{resolveCodeModeSkills as a,readCodeModeSkill as i,readInstalledSkill as n,searchInstalledSkills as r,MAX_SKILL_INSTRUCTION_BYTES as t};