@xenosystem/agent-sdk 0.10.44 → 0.10.45

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/dist/agents/index.cjs +11 -8
  2. package/dist/agents/index.js +11 -8
  3. package/dist/agents/metafile-cjs.json +1 -1
  4. package/dist/agents/metafile-esm.json +1 -1
  5. package/dist/artifacts/index.cjs +1 -1
  6. package/dist/artifacts/index.js +1 -1
  7. package/dist/automation/index.cjs +1 -1
  8. package/dist/automation/index.d.cts +3 -0
  9. package/dist/automation/index.d.ts +3 -0
  10. package/dist/automation/index.js +1 -1
  11. package/dist/automation/metafile-cjs.json +1 -1
  12. package/dist/automation/metafile-esm.json +1 -1
  13. package/dist/control-plane/index.cjs +1 -1
  14. package/dist/control-plane/index.js +1 -1
  15. package/dist/electron/index.cjs +172 -172
  16. package/dist/electron/index.d.cts +4 -0
  17. package/dist/electron/index.d.ts +4 -0
  18. package/dist/electron/index.js +151 -151
  19. package/dist/electron/metafile-cjs.json +1 -1
  20. package/dist/electron/metafile-esm.json +1 -1
  21. package/dist/index.cjs +348 -343
  22. package/dist/index.d.cts +9 -1
  23. package/dist/index.d.ts +9 -1
  24. package/dist/index.js +347 -342
  25. package/dist/mcp/index.d.cts +3 -0
  26. package/dist/mcp/index.d.ts +3 -0
  27. package/dist/metafile-cjs.json +1 -1
  28. package/dist/metafile-esm.json +1 -1
  29. package/dist/session/index.cjs +1 -1
  30. package/dist/session/index.js +1 -1
  31. package/dist/skills/index.cjs +8 -5
  32. package/dist/skills/index.js +8 -5
  33. package/dist/skills/metafile-cjs.json +1 -1
  34. package/dist/skills/metafile-esm.json +1 -1
  35. package/dist/utils/index.cjs +19 -16
  36. package/dist/utils/index.js +19 -16
  37. package/dist/utils/metafile-cjs.json +1 -1
  38. package/dist/utils/metafile-esm.json +1 -1
  39. package/package.json +1 -1
@@ -48,7 +48,7 @@ ${this.stringify(e.data)}
48
48
  `)+`
49
49
  `;await k(this.transcriptPath,a);let c=this.buildMarkdownDocument(o,"session store");if(await k(this.markdownPath,c),!this.workspaceMirrorDisabled){let u=await this.resolveWorkspaceMarkdownPath();if(u)try{let l=this.buildMarkdownDocument(o,"workspace mirror");await k(u,l)}catch(l){this.workspaceMirrorDisabled=!0,j("Transcript workspace mirror disabled",l)}}}async truncateAfterMessageCount(e){let t=await S(this.transcriptPath);if(!t)return;let r=te(t),s=Math.max(0,e),i=0,o=[];for(let u of r){if(u.type==="user_message"||u.type==="assistant_message"){if(i>=s)break;i+=1}o.push(u)}let a=o.length>0?o.map(u=>JSON.stringify(u)).join(`
50
50
  `)+`
51
- `:"";await k(this.transcriptPath,a);let c=this.buildMarkdownDocument(o,"session store");if(await k(this.markdownPath,c),!this.workspaceMirrorDisabled){let u=await this.resolveWorkspaceMarkdownPath();if(u)try{let l=this.buildMarkdownDocument(o,"workspace mirror");await k(u,l)}catch(l){this.workspaceMirrorDisabled=!0,j("Transcript workspace mirror disabled",l)}}}getSequence(){return this.sequence}async initialize(){try{let e=await S(this.transcriptPath);if(!e){this.sequence=0;return}let t=te(e);if(t.length===0){this.sequence=0;return}let r=t[t.length-1];this.sequence=r.sequence+1}catch(e){let t=e instanceof Error?e.message:String(e);j(`Transcript initialization warning: ${t}. Starting with empty transcript.`),this.sequence=0}}async flush(){await this.writeQueue}};var re=M(require("path"),1),bt=require("crypto"),Et=require("fs/promises");var fr={View:"Read",Replace:"Write",GlobTool:"Glob",GrepTool:"Grep",SQLiteAnalyze:"SqliteAnalyze",ReadNotebook:"NotebookRead",NotebookEditCell:"NotebookEdit",CoordinationSend:"Send",CoordinationQuery:"Receive"};function ke(n){return fr[n]??n}var D=class{sessionDir;checkpointsDir;autoInterval;lastCheckpointMessageCount=0;constructor(e,t){this.sessionDir=e,this.checkpointsDir=re.join(e,"checkpoints"),this.autoInterval=t?.autoInterval??10}async initialize(){let e=await this.list();e.length>0&&(this.lastCheckpointMessageCount=e[0].messageCount)}async create(e){await $(this.checkpointsDir);let t=(0,bt.randomUUID)(),r={id:t,name:e.description,trigger:e.trigger,createdAt:new Date().toISOString(),messageCount:e.messages.length,tokenCount:this.estimateTokens(e.messages)},s={info:r,messages:e.messages},i=re.join(this.checkpointsDir,`${t}.json`);return await k(i,JSON.stringify(s,null,2)),this.lastCheckpointMessageCount=e.messages.length,r}async list(){let e=await ft(this.checkpointsDir,/\.json$/),t=[];for(let r of e){let s=await S(r);if(s){let i=b(s,null);if(i){let o=await(0,Et.stat)(r);t.push({info:i.info,modifiedAtMs:o.mtimeMs})}}}return t.sort((r,s)=>new Date(s.info.createdAt).getTime()-new Date(r.info.createdAt).getTime()||s.modifiedAtMs-r.modifiedAtMs).map(({info:r})=>r)}async restore(e){let t=re.join(this.checkpointsDir,`${e}.json`),r;try{r=await S(t)}catch(i){let o=i instanceof Error?i.message:String(i);throw new Error(`Failed to read checkpoint ${e}: ${o}`)}if(!r)throw new Error(`Checkpoint not found: ${e} (path: ${t})`);let s=b(r,null);if(!s)throw new Error(`Invalid checkpoint data for ${e}: JSON parse failed`);if(!s.messages||!Array.isArray(s.messages))throw new Error(`Invalid checkpoint data for ${e}: missing or invalid messages array`);if(!s.info)throw new Error(`Invalid checkpoint data for ${e}: missing info object`);return{messages:s.messages,info:s.info}}shouldAutoCheckpoint(e){return e-this.lastCheckpointMessageCount>=this.autoInterval}static isDangerousOperation(e,t){if(e=ke(e),e==="Write")return!0;if(e==="Bash"){let s=t.command?.toLowerCase()||"";return["rm ","del ","git push","git reset","drop ","truncate"].some(o=>s.includes(o))}return!1}async delete(e){let t=re.join(this.checkpointsDir,`${e}.json`);await L(t)}estimateTokens(e){let t=0;for(let r of e)if(typeof r.content=="string")t+=Math.ceil(r.content.length/4);else if(Array.isArray(r.content))for(let s of r.content)"text"in s&&(t+=Math.ceil(s.text.length/4));return t}};var U=M(require("path"),1),Xe=M(require("os"),1),H=M(require("fs"),1);var mr=Symbol.for("@xenosystem/agent-sdk/shutdown-registry"),hr=globalThis,Ge=hr[mr]??={cleanups:new Set,exitHandlerRegistered:!1,signalHandlersInstalled:!1},We=Ge.cleanups;function wr(){for(let n of We)try{n()}catch{}}function Pt(n){return We.add(n),!Ge.exitHandlerRegistered&&typeof process<"u"&&typeof process.on=="function"&&(Ge.exitHandlerRegistered=!0,process.on("exit",wr)),()=>{We.delete(n)}}var Rt="0.10.44";var yr=1e4,kr=6e4,Sr="session.lock",xr="lock.json",ee=new Map;function Je(n,e){return n!=null&&n.pid===e.pid&&n.hostname===e.hostname&&n.processStartedAt===e.processStartedAt&&n.acquiredAt===e.acquiredAt}function Tr(){for(let[n,e]of ee)try{let t=b(H.readFileSync(n,"utf8"),null);Je(t,e)&&H.unlinkSync(n)}catch{}ee.clear()}Pt(Tr);var X=class n{sessionDir;lockPath;legacyLockPath;sessionId;heartbeatTimer;acquiredOwner;constructor(e){this.sessionDir=e,this.lockPath=U.join(e,Sr),this.legacyLockPath=U.join(e,xr),this.sessionId=U.basename(e)}async acquire(){let e=new Date().toISOString(),t={schemaVersion:1,name:`session:${this.sessionId}`,sessionId:this.sessionId,pid:process.pid,hostname:Xe.hostname(),processStartedAt:new Date(Date.now()-Math.floor(process.uptime()*1e3)).toISOString(),version:Rt,acquiredAt:e,updatedAt:e,heartbeat:e},r=U.dirname(this.lockPath);await H.promises.mkdir(r,{recursive:!0});let s=await this.findExistingLockPath();if(s){if(!await this.isStalePath(s)){let o=await this.readLockAt(s);throw new Error(`Session ${this.sessionId} is already locked by PID ${o?.pid} on ${o?.hostname}`)}await L(s)}try{await H.promises.writeFile(this.lockPath,JSON.stringify(t,null,2),{flag:"wx",encoding:"utf-8"}),this.acquiredOwner=t,ee.set(this.lockPath,t)}catch(i){if(i.code==="EEXIST"){if(!await this.isStalePath(this.lockPath)){let c=await this.readLockAt(this.lockPath);throw new Error(`Session ${this.sessionId} is already locked by PID ${c?.pid} on ${c?.hostname}`)}await L(this.lockPath);try{await H.promises.writeFile(this.lockPath,JSON.stringify(t,null,2),{flag:"wx",encoding:"utf-8"})}catch(c){throw c.code==="EEXIST"?new Error(`Session ${this.sessionId} lock was acquired by another process during stale recovery`):c}this.acquiredOwner=t,ee.set(this.lockPath,t)}else throw i}}async release(){this.stopHeartbeat();let e=this.acquiredOwner;if(this.acquiredOwner=void 0,!e)return;ee.delete(this.lockPath);let t=await this.readLockAt(this.lockPath);Je(t,e)&&await L(this.lockPath)}async isLocked(){let e=await this.findExistingLockPath();return e?!await this.isStalePath(e):!1}async isStale(){let e=await this.findExistingLockPath();return e?this.isStalePath(e):!1}async isStalePath(e){let t=await this.readLockAt(e);if(!t)return!1;if(t.hostname===Xe.hostname())try{return process.kill(t.pid,0),!1}catch(i){return i.code!=="EPERM"}let r=new Date(t.heartbeat).getTime();return Date.now()-r>kr}startHeartbeat(e=yr){this.heartbeatTimer&&this.stopHeartbeat(),this.heartbeatTimer=setInterval(async()=>{try{await this.updateHeartbeat()}catch(t){let r=t instanceof Error?t.message:String(t);if(t?.code==="ENOENT"){G("SessionLock: Session directory removed, stopping heartbeat"),this.stopHeartbeat();return}G(`SessionLock: Failed to update heartbeat: ${r}`)}},e),this.heartbeatTimer.unref()}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0)}async updateHeartbeat(){let e=await this.readLockAt(this.lockPath),t=this.acquiredOwner;if(!(!e||!t)){if(!Je(e,t)){this.acquiredOwner=void 0,ee.delete(this.lockPath),this.stopHeartbeat();return}e.heartbeat=new Date().toISOString(),e.updatedAt=e.heartbeat,await k(this.lockPath,JSON.stringify(e,null,2))}}async readLock(){let e=await this.findExistingLockPath();return e?this.readLockAt(e):null}async readLockAt(e){let t=await S(e);return t?b(t,null):null}async findExistingLockPath(){return await S(this.lockPath)?this.lockPath:await S(this.legacyLockPath)?this.legacyLockPath:null}static async cleanStale(e){let t=await fe(e),r=[];for(let s of t){let i=new n(s);if(await i.isStale()){let a=await i.findExistingLockPath();a&&await L(a),r.push(U.basename(s))}}return r}};var C=M(require("path"),1);var ne=1;var A=M(require("path"),1);function vr(n,e){let t=A.resolve(n),r=A.resolve(n,e);return r===t?!0:t===A.parse(t).root?r.startsWith(t):r.startsWith(t+A.sep)}function J(n,e){if(A.isAbsolute(e))return A.resolve(e);if(!vr(n,e))throw new Error(`PathSecurity: Path traversal attempt detected: ${e}`);return A.resolve(n,e)}function Se(n,e=process.platform){let t=A.resolve(n);return e==="win32"?t.toLowerCase():t}function z(n){if(n!==void 0&&n!=="agent"&&n!=="chatOnly")throw new Error("Invalid session execution mode; expected agent or chatOnly.")}var P=M(require("path"),1),ve=M(require("os"),1),R=M(require("node:fs/promises"),1),be=require("node:crypto");var V=require("node:os");var se=require("node:path");var Dn=(0,V.platform)();var Cn=(0,V.release)(),On=(0,V.homedir)();function xe(){let n=process.env.XENO_AGENT_HOME?.trim();return n?(0,se.resolve)(n):(0,se.resolve)((0,V.homedir)(),".xeno-agent")}var Mt=1,_t="recent.json",br=".lock",At=".entries",Er=3e4,ze=6e4,Dt=new Set(["EACCES","EBUSY","EPERM"]),Pr=[5,10,20,40,80,160,320],Te=new Map;function Rr(n,e){let t=(0,be.createHash)("sha256").update(e).digest("hex");return P.join(`${n}${At}`,`${t}.json`)}async function Ve(n,e,t){let r={schemaVersion:1,key:e,entry:t};await k(Rr(n,e),JSON.stringify(r)+`
51
+ `:"";await k(this.transcriptPath,a);let c=this.buildMarkdownDocument(o,"session store");if(await k(this.markdownPath,c),!this.workspaceMirrorDisabled){let u=await this.resolveWorkspaceMarkdownPath();if(u)try{let l=this.buildMarkdownDocument(o,"workspace mirror");await k(u,l)}catch(l){this.workspaceMirrorDisabled=!0,j("Transcript workspace mirror disabled",l)}}}getSequence(){return this.sequence}async initialize(){try{let e=await S(this.transcriptPath);if(!e){this.sequence=0;return}let t=te(e);if(t.length===0){this.sequence=0;return}let r=t[t.length-1];this.sequence=r.sequence+1}catch(e){let t=e instanceof Error?e.message:String(e);j(`Transcript initialization warning: ${t}. Starting with empty transcript.`),this.sequence=0}}async flush(){await this.writeQueue}};var re=M(require("path"),1),bt=require("crypto"),Et=require("fs/promises");var fr={View:"Read",Replace:"Write",GlobTool:"Glob",GrepTool:"Grep",SQLiteAnalyze:"SqliteAnalyze",ReadNotebook:"NotebookRead",NotebookEditCell:"NotebookEdit",CoordinationSend:"Send",CoordinationQuery:"Receive"};function ke(n){return fr[n]??n}var D=class{sessionDir;checkpointsDir;autoInterval;lastCheckpointMessageCount=0;constructor(e,t){this.sessionDir=e,this.checkpointsDir=re.join(e,"checkpoints"),this.autoInterval=t?.autoInterval??10}async initialize(){let e=await this.list();e.length>0&&(this.lastCheckpointMessageCount=e[0].messageCount)}async create(e){await $(this.checkpointsDir);let t=(0,bt.randomUUID)(),r={id:t,name:e.description,trigger:e.trigger,createdAt:new Date().toISOString(),messageCount:e.messages.length,tokenCount:this.estimateTokens(e.messages)},s={info:r,messages:e.messages},i=re.join(this.checkpointsDir,`${t}.json`);return await k(i,JSON.stringify(s,null,2)),this.lastCheckpointMessageCount=e.messages.length,r}async list(){let e=await ft(this.checkpointsDir,/\.json$/),t=[];for(let r of e){let s=await S(r);if(s){let i=b(s,null);if(i){let o=await(0,Et.stat)(r);t.push({info:i.info,modifiedAtMs:o.mtimeMs})}}}return t.sort((r,s)=>new Date(s.info.createdAt).getTime()-new Date(r.info.createdAt).getTime()||s.modifiedAtMs-r.modifiedAtMs).map(({info:r})=>r)}async restore(e){let t=re.join(this.checkpointsDir,`${e}.json`),r;try{r=await S(t)}catch(i){let o=i instanceof Error?i.message:String(i);throw new Error(`Failed to read checkpoint ${e}: ${o}`)}if(!r)throw new Error(`Checkpoint not found: ${e} (path: ${t})`);let s=b(r,null);if(!s)throw new Error(`Invalid checkpoint data for ${e}: JSON parse failed`);if(!s.messages||!Array.isArray(s.messages))throw new Error(`Invalid checkpoint data for ${e}: missing or invalid messages array`);if(!s.info)throw new Error(`Invalid checkpoint data for ${e}: missing info object`);return{messages:s.messages,info:s.info}}shouldAutoCheckpoint(e){return e-this.lastCheckpointMessageCount>=this.autoInterval}static isDangerousOperation(e,t){if(e=ke(e),e==="Write")return!0;if(e==="Bash"){let s=t.command?.toLowerCase()||"";return["rm ","del ","git push","git reset","drop ","truncate"].some(o=>s.includes(o))}return!1}async delete(e){let t=re.join(this.checkpointsDir,`${e}.json`);await L(t)}estimateTokens(e){let t=0;for(let r of e)if(typeof r.content=="string")t+=Math.ceil(r.content.length/4);else if(Array.isArray(r.content))for(let s of r.content)"text"in s&&(t+=Math.ceil(s.text.length/4));return t}};var U=M(require("path"),1),Xe=M(require("os"),1),H=M(require("fs"),1);var mr=Symbol.for("@xenosystem/agent-sdk/shutdown-registry"),hr=globalThis,Ge=hr[mr]??={cleanups:new Set,exitHandlerRegistered:!1,signalHandlersInstalled:!1},We=Ge.cleanups;function wr(){for(let n of We)try{n()}catch{}}function Pt(n){return We.add(n),!Ge.exitHandlerRegistered&&typeof process<"u"&&typeof process.on=="function"&&(Ge.exitHandlerRegistered=!0,process.on("exit",wr)),()=>{We.delete(n)}}var Rt="0.10.45";var yr=1e4,kr=6e4,Sr="session.lock",xr="lock.json",ee=new Map;function Je(n,e){return n!=null&&n.pid===e.pid&&n.hostname===e.hostname&&n.processStartedAt===e.processStartedAt&&n.acquiredAt===e.acquiredAt}function Tr(){for(let[n,e]of ee)try{let t=b(H.readFileSync(n,"utf8"),null);Je(t,e)&&H.unlinkSync(n)}catch{}ee.clear()}Pt(Tr);var X=class n{sessionDir;lockPath;legacyLockPath;sessionId;heartbeatTimer;acquiredOwner;constructor(e){this.sessionDir=e,this.lockPath=U.join(e,Sr),this.legacyLockPath=U.join(e,xr),this.sessionId=U.basename(e)}async acquire(){let e=new Date().toISOString(),t={schemaVersion:1,name:`session:${this.sessionId}`,sessionId:this.sessionId,pid:process.pid,hostname:Xe.hostname(),processStartedAt:new Date(Date.now()-Math.floor(process.uptime()*1e3)).toISOString(),version:Rt,acquiredAt:e,updatedAt:e,heartbeat:e},r=U.dirname(this.lockPath);await H.promises.mkdir(r,{recursive:!0});let s=await this.findExistingLockPath();if(s){if(!await this.isStalePath(s)){let o=await this.readLockAt(s);throw new Error(`Session ${this.sessionId} is already locked by PID ${o?.pid} on ${o?.hostname}`)}await L(s)}try{await H.promises.writeFile(this.lockPath,JSON.stringify(t,null,2),{flag:"wx",encoding:"utf-8"}),this.acquiredOwner=t,ee.set(this.lockPath,t)}catch(i){if(i.code==="EEXIST"){if(!await this.isStalePath(this.lockPath)){let c=await this.readLockAt(this.lockPath);throw new Error(`Session ${this.sessionId} is already locked by PID ${c?.pid} on ${c?.hostname}`)}await L(this.lockPath);try{await H.promises.writeFile(this.lockPath,JSON.stringify(t,null,2),{flag:"wx",encoding:"utf-8"})}catch(c){throw c.code==="EEXIST"?new Error(`Session ${this.sessionId} lock was acquired by another process during stale recovery`):c}this.acquiredOwner=t,ee.set(this.lockPath,t)}else throw i}}async release(){this.stopHeartbeat();let e=this.acquiredOwner;if(this.acquiredOwner=void 0,!e)return;ee.delete(this.lockPath);let t=await this.readLockAt(this.lockPath);Je(t,e)&&await L(this.lockPath)}async isLocked(){let e=await this.findExistingLockPath();return e?!await this.isStalePath(e):!1}async isStale(){let e=await this.findExistingLockPath();return e?this.isStalePath(e):!1}async isStalePath(e){let t=await this.readLockAt(e);if(!t)return!1;if(t.hostname===Xe.hostname())try{return process.kill(t.pid,0),!1}catch(i){return i.code!=="EPERM"}let r=new Date(t.heartbeat).getTime();return Date.now()-r>kr}startHeartbeat(e=yr){this.heartbeatTimer&&this.stopHeartbeat(),this.heartbeatTimer=setInterval(async()=>{try{await this.updateHeartbeat()}catch(t){let r=t instanceof Error?t.message:String(t);if(t?.code==="ENOENT"){G("SessionLock: Session directory removed, stopping heartbeat"),this.stopHeartbeat();return}G(`SessionLock: Failed to update heartbeat: ${r}`)}},e),this.heartbeatTimer.unref()}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0)}async updateHeartbeat(){let e=await this.readLockAt(this.lockPath),t=this.acquiredOwner;if(!(!e||!t)){if(!Je(e,t)){this.acquiredOwner=void 0,ee.delete(this.lockPath),this.stopHeartbeat();return}e.heartbeat=new Date().toISOString(),e.updatedAt=e.heartbeat,await k(this.lockPath,JSON.stringify(e,null,2))}}async readLock(){let e=await this.findExistingLockPath();return e?this.readLockAt(e):null}async readLockAt(e){let t=await S(e);return t?b(t,null):null}async findExistingLockPath(){return await S(this.lockPath)?this.lockPath:await S(this.legacyLockPath)?this.legacyLockPath:null}static async cleanStale(e){let t=await fe(e),r=[];for(let s of t){let i=new n(s);if(await i.isStale()){let a=await i.findExistingLockPath();a&&await L(a),r.push(U.basename(s))}}return r}};var C=M(require("path"),1);var ne=1;var A=M(require("path"),1);function vr(n,e){let t=A.resolve(n),r=A.resolve(n,e);return r===t?!0:t===A.parse(t).root?r.startsWith(t):r.startsWith(t+A.sep)}function J(n,e){if(A.isAbsolute(e))return A.resolve(e);if(!vr(n,e))throw new Error(`PathSecurity: Path traversal attempt detected: ${e}`);return A.resolve(n,e)}function Se(n,e=process.platform){let t=A.resolve(n);return e==="win32"?t.toLowerCase():t}function z(n){if(n!==void 0&&n!=="agent"&&n!=="chatOnly")throw new Error("Invalid session execution mode; expected agent or chatOnly.")}var P=M(require("path"),1),ve=M(require("os"),1),R=M(require("node:fs/promises"),1),be=require("node:crypto");var V=require("node:os");var se=require("node:path");var Dn=(0,V.platform)();var Cn=(0,V.release)(),On=(0,V.homedir)();function xe(){let n=process.env.XENO_AGENT_HOME?.trim();return n?(0,se.resolve)(n):(0,se.resolve)((0,V.homedir)(),".xeno-agent")}var Mt=1,_t="recent.json",br=".lock",At=".entries",Er=3e4,ze=6e4,Dt=new Set(["EACCES","EBUSY","EPERM"]),Pr=[5,10,20,40,80,160,320],Te=new Map;function Rr(n,e){let t=(0,be.createHash)("sha256").update(e).digest("hex");return P.join(`${n}${At}`,`${t}.json`)}async function Ve(n,e,t){let r={schemaVersion:1,key:e,entry:t};await k(Rr(n,e),JSON.stringify(r)+`
52
52
  `)}async function Mr(n,e){let t=`${n}${At}`,r;try{r=await R.readdir(t)}catch(s){if(s.code==="ENOENT")return;throw s}await Promise.all(r.filter(s=>s.endsWith(".json")).map(async s=>{let i=await R.readFile(P.join(t,s),"utf8").catch(()=>""),o=b(i,null);if(!(!o||o.schemaVersion!==1||typeof o.key!="string")){if(o.entry===null){delete e[o.key];return}typeof o.entry.sessionId!="string"||typeof o.entry.endedAt!="string"||(e[o.key]=o.entry)}}))}function It(n){if(!Number.isInteger(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch(e){return e.code==="EPERM"}}async function _r(n){try{let[e,t]=await Promise.all([R.readFile(P.join(n,"owner.json"),"utf8").catch(()=>""),R.stat(n)]),r=b(e,null);return r?.hostname===ve.hostname()&&It(r.pid)?!1:r?.hostname&&r.hostname!==ve.hostname()||!r?Date.now()-t.mtimeMs>ze:Date.now()-t.mtimeMs>ze||!It(r.pid)}catch{return!1}}async function Ct(n){for(let e=0;;e+=1)try{await R.rm(n,{recursive:!0});return}catch(t){let r=t.code;if(r==="ENOENT")return;let s=Pr[e];if(process.platform!=="win32"||!r||!Dt.has(r)||s===void 0)throw t;await new Promise(i=>setTimeout(i,s))}}async function Ir(n,e){try{let t=await R.readFile(P.join(n,"owner.json"),"utf8");b(t,null)?.token===e&&await Ct(n)}catch(t){if(t.code!=="ENOENT")throw t}}async function Ke(n,e){let t=K(n),r=Te.get(t)??Promise.resolve(),s,i=new Promise(o=>{s=o});Te.set(t,i),await r;try{return await Ar(t,e)}finally{s(),Te.get(t)===i&&Te.delete(t)}}async function Ar(n,e){let t=`${n}${br}`,r=(0,be.randomUUID)(),s=Date.now();await R.mkdir(P.dirname(n),{recursive:!0});for(let i=0;;i+=1){let o={schemaVersion:1,token:r,pid:process.pid,hostname:ve.hostname(),acquiredAt:new Date().toISOString()};try{await R.mkdir(t),await R.writeFile(P.join(t,"owner.json"),JSON.stringify(o),"utf8");break}catch(a){let c=a.code,u=process.platform==="win32"&&!!c&&Dt.has(c);if(c!=="EEXIST"&&!u)throw a;if(await _r(t)){await Ct(t);continue}if(Date.now()-s>=Er)throw new Error(`Timed out waiting for recent-sessions index lock: ${t}`);let l=Math.min(100,5+i*5)+Math.floor(Math.random()*10);await new Promise(d=>setTimeout(d,l))}}try{return await e()}finally{await Ir(t,r)}}function K(n){return n===void 0?P.join(xe(),_t):P.join(n,".xeno-agent",_t)}function ie(n){let e=P.normalize(n).replace(/[\\/]+$/,""),t=e.length>0?e:P.parse(P.normalize(n)).root;return process.platform==="win32"?t.toLowerCase():t}async function q(n){let e=K(n),t=ge(e)?await S(e):null,r=t?b(t,null):null,s=r&&typeof r=="object"?r:null,i={},o=s?.version===Mt&&s.entries&&typeof s.entries=="object"?s.entries:{};for(let[a,c]of Object.entries(o)){if(!c||typeof c!="object")continue;let u=c;typeof u.sessionId!="string"||u.sessionId.length===0||typeof u.endedAt=="string"&&(i[a]={sessionId:u.sessionId,endedAt:u.endedAt,role:typeof u.role=="string"?u.role:void 0})}return await Mr(e,i),{version:Mt,entries:i}}async function Ee(n,e={}){let t=await q(e.homeDir),r=ie(n),s=t.entries[r];if(s&&!(e.role&&s.role&&s.role!==e.role))return s}async function Pe(n,e={}){let t=ie(n.cwd),r={sessionId:n.sessionId,role:n.role,endedAt:n.endedAt??new Date().toISOString()},s=K(e.homeDir);await Ve(s,t,r),await Ke(e.homeDir,async()=>{let i=await q(e.homeDir);i.entries[t]=r,await k(s,JSON.stringify(i,null,2)+`
53
53
  `)})}async function Ot(n,e={}){let t=ie(n),r=K(e.homeDir);(await q(e.homeDir)).entries[t]&&(await Ve(r,t,null),await Ke(e.homeDir,async()=>{let i=await q(e.homeDir);delete i.entries[t],await k(r,JSON.stringify(i,null,2)+`
54
54
  `)}))}async function oe(n,e={}){let t=await q(e.homeDir),r=Object.entries(t.entries).filter(([,i])=>i.sessionId===n).map(([i])=>i);if(r.length===0)return;let s=K(e.homeDir);await Promise.all(r.map(i=>Ve(s,i,null))),await Ke(e.homeDir,async()=>{let i=await q(e.homeDir);for(let[o,a]of Object.entries(i.entries))a.sessionId===n&&delete i.entries[o];await k(s,JSON.stringify(i,null,2)+`
@@ -48,7 +48,7 @@ ${this.stringify(e.data)}
48
48
  `)+`
49
49
  `;await y(this.transcriptPath,a);let c=this.buildMarkdownDocument(o,"session store");if(await y(this.markdownPath,c),!this.workspaceMirrorDisabled){let u=await this.resolveWorkspaceMarkdownPath();if(u)try{let l=this.buildMarkdownDocument(o,"workspace mirror");await y(u,l)}catch(l){this.workspaceMirrorDisabled=!0,B("Transcript workspace mirror disabled",l)}}}async truncateAfterMessageCount(e){let t=await k(this.transcriptPath);if(!t)return;let r=Y(t),s=Math.max(0,e),i=0,o=[];for(let u of r){if(u.type==="user_message"||u.type==="assistant_message"){if(i>=s)break;i+=1}o.push(u)}let a=o.length>0?o.map(u=>JSON.stringify(u)).join(`
50
50
  `)+`
51
- `:"";await y(this.transcriptPath,a);let c=this.buildMarkdownDocument(o,"session store");if(await y(this.markdownPath,c),!this.workspaceMirrorDisabled){let u=await this.resolveWorkspaceMarkdownPath();if(u)try{let l=this.buildMarkdownDocument(o,"workspace mirror");await y(u,l)}catch(l){this.workspaceMirrorDisabled=!0,B("Transcript workspace mirror disabled",l)}}}getSequence(){return this.sequence}async initialize(){try{let e=await k(this.transcriptPath);if(!e){this.sequence=0;return}let t=Y(e);if(t.length===0){this.sequence=0;return}let r=t[t.length-1];this.sequence=r.sequence+1}catch(e){let t=e instanceof Error?e.message:String(e);B(`Transcript initialization warning: ${t}. Starting with empty transcript.`),this.sequence=0}}async flush(){await this.writeQueue}};import*as Z from"path";import{randomUUID as or}from"crypto";import{stat as ar}from"fs/promises";var ir={View:"Read",Replace:"Write",GlobTool:"Glob",GrepTool:"Grep",SQLiteAnalyze:"SqliteAnalyze",ReadNotebook:"NotebookRead",NotebookEditCell:"NotebookEdit",CoordinationSend:"Send",CoordinationQuery:"Receive"};function ce(n){return ir[n]??n}var D=class{sessionDir;checkpointsDir;autoInterval;lastCheckpointMessageCount=0;constructor(e,t){this.sessionDir=e,this.checkpointsDir=Z.join(e,"checkpoints"),this.autoInterval=t?.autoInterval??10}async initialize(){let e=await this.list();e.length>0&&(this.lastCheckpointMessageCount=e[0].messageCount)}async create(e){await O(this.checkpointsDir);let t=or(),r={id:t,name:e.description,trigger:e.trigger,createdAt:new Date().toISOString(),messageCount:e.messages.length,tokenCount:this.estimateTokens(e.messages)},s={info:r,messages:e.messages},i=Z.join(this.checkpointsDir,`${t}.json`);return await y(i,JSON.stringify(s,null,2)),this.lastCheckpointMessageCount=e.messages.length,r}async list(){let e=await nt(this.checkpointsDir,/\.json$/),t=[];for(let r of e){let s=await k(r);if(s){let i=v(s,null);if(i){let o=await ar(r);t.push({info:i.info,modifiedAtMs:o.mtimeMs})}}}return t.sort((r,s)=>new Date(s.info.createdAt).getTime()-new Date(r.info.createdAt).getTime()||s.modifiedAtMs-r.modifiedAtMs).map(({info:r})=>r)}async restore(e){let t=Z.join(this.checkpointsDir,`${e}.json`),r;try{r=await k(t)}catch(i){let o=i instanceof Error?i.message:String(i);throw new Error(`Failed to read checkpoint ${e}: ${o}`)}if(!r)throw new Error(`Checkpoint not found: ${e} (path: ${t})`);let s=v(r,null);if(!s)throw new Error(`Invalid checkpoint data for ${e}: JSON parse failed`);if(!s.messages||!Array.isArray(s.messages))throw new Error(`Invalid checkpoint data for ${e}: missing or invalid messages array`);if(!s.info)throw new Error(`Invalid checkpoint data for ${e}: missing info object`);return{messages:s.messages,info:s.info}}shouldAutoCheckpoint(e){return e-this.lastCheckpointMessageCount>=this.autoInterval}static isDangerousOperation(e,t){if(e=ce(e),e==="Write")return!0;if(e==="Bash"){let s=t.command?.toLowerCase()||"";return["rm ","del ","git push","git reset","drop ","truncate"].some(o=>s.includes(o))}return!1}async delete(e){let t=Z.join(this.checkpointsDir,`${e}.json`);await N(t)}estimateTokens(e){let t=0;for(let r of e)if(typeof r.content=="string")t+=Math.ceil(r.content.length/4);else if(Array.isArray(r.content))for(let s of r.content)"text"in s&&(t+=Math.ceil(s.text.length/4));return t}};import*as j from"path";import*as Ae from"os";import*as F from"fs";var cr=Symbol.for("@xenosystem/agent-sdk/shutdown-registry"),ur=globalThis,_e=ur[cr]??={cleanups:new Set,exitHandlerRegistered:!1,signalHandlersInstalled:!1},Ie=_e.cleanups;function lr(){for(let n of Ie)try{n()}catch{}}function gt(n){return Ie.add(n),!_e.exitHandlerRegistered&&typeof process<"u"&&typeof process.on=="function"&&(_e.exitHandlerRegistered=!0,process.on("exit",lr)),()=>{Ie.delete(n)}}var ft="0.10.44";var dr=1e4,pr=6e4,gr="session.lock",fr="lock.json",J=new Map;function De(n,e){return n!=null&&n.pid===e.pid&&n.hostname===e.hostname&&n.processStartedAt===e.processStartedAt&&n.acquiredAt===e.acquiredAt}function mr(){for(let[n,e]of J)try{let t=v(F.readFileSync(n,"utf8"),null);De(t,e)&&F.unlinkSync(n)}catch{}J.clear()}gt(mr);var z=class n{sessionDir;lockPath;legacyLockPath;sessionId;heartbeatTimer;acquiredOwner;constructor(e){this.sessionDir=e,this.lockPath=j.join(e,gr),this.legacyLockPath=j.join(e,fr),this.sessionId=j.basename(e)}async acquire(){let e=new Date().toISOString(),t={schemaVersion:1,name:`session:${this.sessionId}`,sessionId:this.sessionId,pid:process.pid,hostname:Ae.hostname(),processStartedAt:new Date(Date.now()-Math.floor(process.uptime()*1e3)).toISOString(),version:ft,acquiredAt:e,updatedAt:e,heartbeat:e},r=j.dirname(this.lockPath);await F.promises.mkdir(r,{recursive:!0});let s=await this.findExistingLockPath();if(s){if(!await this.isStalePath(s)){let o=await this.readLockAt(s);throw new Error(`Session ${this.sessionId} is already locked by PID ${o?.pid} on ${o?.hostname}`)}await N(s)}try{await F.promises.writeFile(this.lockPath,JSON.stringify(t,null,2),{flag:"wx",encoding:"utf-8"}),this.acquiredOwner=t,J.set(this.lockPath,t)}catch(i){if(i.code==="EEXIST"){if(!await this.isStalePath(this.lockPath)){let c=await this.readLockAt(this.lockPath);throw new Error(`Session ${this.sessionId} is already locked by PID ${c?.pid} on ${c?.hostname}`)}await N(this.lockPath);try{await F.promises.writeFile(this.lockPath,JSON.stringify(t,null,2),{flag:"wx",encoding:"utf-8"})}catch(c){throw c.code==="EEXIST"?new Error(`Session ${this.sessionId} lock was acquired by another process during stale recovery`):c}this.acquiredOwner=t,J.set(this.lockPath,t)}else throw i}}async release(){this.stopHeartbeat();let e=this.acquiredOwner;if(this.acquiredOwner=void 0,!e)return;J.delete(this.lockPath);let t=await this.readLockAt(this.lockPath);De(t,e)&&await N(this.lockPath)}async isLocked(){let e=await this.findExistingLockPath();return e?!await this.isStalePath(e):!1}async isStale(){let e=await this.findExistingLockPath();return e?this.isStalePath(e):!1}async isStalePath(e){let t=await this.readLockAt(e);if(!t)return!1;if(t.hostname===Ae.hostname())try{return process.kill(t.pid,0),!1}catch(i){return i.code!=="EPERM"}let r=new Date(t.heartbeat).getTime();return Date.now()-r>pr}startHeartbeat(e=dr){this.heartbeatTimer&&this.stopHeartbeat(),this.heartbeatTimer=setInterval(async()=>{try{await this.updateHeartbeat()}catch(t){let r=t instanceof Error?t.message:String(t);if(t?.code==="ENOENT"){H("SessionLock: Session directory removed, stopping heartbeat"),this.stopHeartbeat();return}H(`SessionLock: Failed to update heartbeat: ${r}`)}},e),this.heartbeatTimer.unref()}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0)}async updateHeartbeat(){let e=await this.readLockAt(this.lockPath),t=this.acquiredOwner;if(!(!e||!t)){if(!De(e,t)){this.acquiredOwner=void 0,J.delete(this.lockPath),this.stopHeartbeat();return}e.heartbeat=new Date().toISOString(),e.updatedAt=e.heartbeat,await y(this.lockPath,JSON.stringify(e,null,2))}}async readLock(){let e=await this.findExistingLockPath();return e?this.readLockAt(e):null}async readLockAt(e){let t=await k(e);return t?v(t,null):null}async findExistingLockPath(){return await k(this.lockPath)?this.lockPath:await k(this.legacyLockPath)?this.legacyLockPath:null}static async cleanStale(e){let t=await oe(e),r=[];for(let s of t){let i=new n(s);if(await i.isStale()){let a=await i.findExistingLockPath();a&&await N(a),r.push(j.basename(s))}}return r}};import*as I from"path";var ee=1;import*as M from"path";function hr(n,e){let t=M.resolve(n),r=M.resolve(n,e);return r===t?!0:t===M.parse(t).root?r.startsWith(t):r.startsWith(t+M.sep)}function q(n,e){if(M.isAbsolute(e))return M.resolve(e);if(!hr(n,e))throw new Error(`PathSecurity: Path traversal attempt detected: ${e}`);return M.resolve(n,e)}function ue(n,e=process.platform){let t=M.resolve(n);return e==="win32"?t.toLowerCase():t}function G(n){if(n!==void 0&&n!=="agent"&&n!=="chatOnly")throw new Error("Invalid session execution mode; expected agent or chatOnly.")}import*as E from"path";import*as pe from"os";import*as P from"node:fs/promises";import{createHash as kr,randomUUID as Sr}from"node:crypto";import{homedir as ht,platform as wr,release as yr}from"node:os";import{delimiter as qn,join as Gn,resolve as mt}from"node:path";var Xn=wr();var Jn=yr(),zn=ht();function le(){let n=process.env.XENO_AGENT_HOME?.trim();return n?mt(n):mt(ht(),".xeno-agent")}var wt=1,yt="recent.json",xr=".lock",St=".entries",Tr=3e4,Ce=6e4,xt=new Set(["EACCES","EBUSY","EPERM"]),vr=[5,10,20,40,80,160,320],de=new Map;function br(n,e){let t=kr("sha256").update(e).digest("hex");return E.join(`${n}${St}`,`${t}.json`)}async function Oe(n,e,t){let r={schemaVersion:1,key:e,entry:t};await y(br(n,e),JSON.stringify(r)+`
51
+ `:"";await y(this.transcriptPath,a);let c=this.buildMarkdownDocument(o,"session store");if(await y(this.markdownPath,c),!this.workspaceMirrorDisabled){let u=await this.resolveWorkspaceMarkdownPath();if(u)try{let l=this.buildMarkdownDocument(o,"workspace mirror");await y(u,l)}catch(l){this.workspaceMirrorDisabled=!0,B("Transcript workspace mirror disabled",l)}}}getSequence(){return this.sequence}async initialize(){try{let e=await k(this.transcriptPath);if(!e){this.sequence=0;return}let t=Y(e);if(t.length===0){this.sequence=0;return}let r=t[t.length-1];this.sequence=r.sequence+1}catch(e){let t=e instanceof Error?e.message:String(e);B(`Transcript initialization warning: ${t}. Starting with empty transcript.`),this.sequence=0}}async flush(){await this.writeQueue}};import*as Z from"path";import{randomUUID as or}from"crypto";import{stat as ar}from"fs/promises";var ir={View:"Read",Replace:"Write",GlobTool:"Glob",GrepTool:"Grep",SQLiteAnalyze:"SqliteAnalyze",ReadNotebook:"NotebookRead",NotebookEditCell:"NotebookEdit",CoordinationSend:"Send",CoordinationQuery:"Receive"};function ce(n){return ir[n]??n}var D=class{sessionDir;checkpointsDir;autoInterval;lastCheckpointMessageCount=0;constructor(e,t){this.sessionDir=e,this.checkpointsDir=Z.join(e,"checkpoints"),this.autoInterval=t?.autoInterval??10}async initialize(){let e=await this.list();e.length>0&&(this.lastCheckpointMessageCount=e[0].messageCount)}async create(e){await O(this.checkpointsDir);let t=or(),r={id:t,name:e.description,trigger:e.trigger,createdAt:new Date().toISOString(),messageCount:e.messages.length,tokenCount:this.estimateTokens(e.messages)},s={info:r,messages:e.messages},i=Z.join(this.checkpointsDir,`${t}.json`);return await y(i,JSON.stringify(s,null,2)),this.lastCheckpointMessageCount=e.messages.length,r}async list(){let e=await nt(this.checkpointsDir,/\.json$/),t=[];for(let r of e){let s=await k(r);if(s){let i=v(s,null);if(i){let o=await ar(r);t.push({info:i.info,modifiedAtMs:o.mtimeMs})}}}return t.sort((r,s)=>new Date(s.info.createdAt).getTime()-new Date(r.info.createdAt).getTime()||s.modifiedAtMs-r.modifiedAtMs).map(({info:r})=>r)}async restore(e){let t=Z.join(this.checkpointsDir,`${e}.json`),r;try{r=await k(t)}catch(i){let o=i instanceof Error?i.message:String(i);throw new Error(`Failed to read checkpoint ${e}: ${o}`)}if(!r)throw new Error(`Checkpoint not found: ${e} (path: ${t})`);let s=v(r,null);if(!s)throw new Error(`Invalid checkpoint data for ${e}: JSON parse failed`);if(!s.messages||!Array.isArray(s.messages))throw new Error(`Invalid checkpoint data for ${e}: missing or invalid messages array`);if(!s.info)throw new Error(`Invalid checkpoint data for ${e}: missing info object`);return{messages:s.messages,info:s.info}}shouldAutoCheckpoint(e){return e-this.lastCheckpointMessageCount>=this.autoInterval}static isDangerousOperation(e,t){if(e=ce(e),e==="Write")return!0;if(e==="Bash"){let s=t.command?.toLowerCase()||"";return["rm ","del ","git push","git reset","drop ","truncate"].some(o=>s.includes(o))}return!1}async delete(e){let t=Z.join(this.checkpointsDir,`${e}.json`);await N(t)}estimateTokens(e){let t=0;for(let r of e)if(typeof r.content=="string")t+=Math.ceil(r.content.length/4);else if(Array.isArray(r.content))for(let s of r.content)"text"in s&&(t+=Math.ceil(s.text.length/4));return t}};import*as j from"path";import*as Ae from"os";import*as F from"fs";var cr=Symbol.for("@xenosystem/agent-sdk/shutdown-registry"),ur=globalThis,_e=ur[cr]??={cleanups:new Set,exitHandlerRegistered:!1,signalHandlersInstalled:!1},Ie=_e.cleanups;function lr(){for(let n of Ie)try{n()}catch{}}function gt(n){return Ie.add(n),!_e.exitHandlerRegistered&&typeof process<"u"&&typeof process.on=="function"&&(_e.exitHandlerRegistered=!0,process.on("exit",lr)),()=>{Ie.delete(n)}}var ft="0.10.45";var dr=1e4,pr=6e4,gr="session.lock",fr="lock.json",J=new Map;function De(n,e){return n!=null&&n.pid===e.pid&&n.hostname===e.hostname&&n.processStartedAt===e.processStartedAt&&n.acquiredAt===e.acquiredAt}function mr(){for(let[n,e]of J)try{let t=v(F.readFileSync(n,"utf8"),null);De(t,e)&&F.unlinkSync(n)}catch{}J.clear()}gt(mr);var z=class n{sessionDir;lockPath;legacyLockPath;sessionId;heartbeatTimer;acquiredOwner;constructor(e){this.sessionDir=e,this.lockPath=j.join(e,gr),this.legacyLockPath=j.join(e,fr),this.sessionId=j.basename(e)}async acquire(){let e=new Date().toISOString(),t={schemaVersion:1,name:`session:${this.sessionId}`,sessionId:this.sessionId,pid:process.pid,hostname:Ae.hostname(),processStartedAt:new Date(Date.now()-Math.floor(process.uptime()*1e3)).toISOString(),version:ft,acquiredAt:e,updatedAt:e,heartbeat:e},r=j.dirname(this.lockPath);await F.promises.mkdir(r,{recursive:!0});let s=await this.findExistingLockPath();if(s){if(!await this.isStalePath(s)){let o=await this.readLockAt(s);throw new Error(`Session ${this.sessionId} is already locked by PID ${o?.pid} on ${o?.hostname}`)}await N(s)}try{await F.promises.writeFile(this.lockPath,JSON.stringify(t,null,2),{flag:"wx",encoding:"utf-8"}),this.acquiredOwner=t,J.set(this.lockPath,t)}catch(i){if(i.code==="EEXIST"){if(!await this.isStalePath(this.lockPath)){let c=await this.readLockAt(this.lockPath);throw new Error(`Session ${this.sessionId} is already locked by PID ${c?.pid} on ${c?.hostname}`)}await N(this.lockPath);try{await F.promises.writeFile(this.lockPath,JSON.stringify(t,null,2),{flag:"wx",encoding:"utf-8"})}catch(c){throw c.code==="EEXIST"?new Error(`Session ${this.sessionId} lock was acquired by another process during stale recovery`):c}this.acquiredOwner=t,J.set(this.lockPath,t)}else throw i}}async release(){this.stopHeartbeat();let e=this.acquiredOwner;if(this.acquiredOwner=void 0,!e)return;J.delete(this.lockPath);let t=await this.readLockAt(this.lockPath);De(t,e)&&await N(this.lockPath)}async isLocked(){let e=await this.findExistingLockPath();return e?!await this.isStalePath(e):!1}async isStale(){let e=await this.findExistingLockPath();return e?this.isStalePath(e):!1}async isStalePath(e){let t=await this.readLockAt(e);if(!t)return!1;if(t.hostname===Ae.hostname())try{return process.kill(t.pid,0),!1}catch(i){return i.code!=="EPERM"}let r=new Date(t.heartbeat).getTime();return Date.now()-r>pr}startHeartbeat(e=dr){this.heartbeatTimer&&this.stopHeartbeat(),this.heartbeatTimer=setInterval(async()=>{try{await this.updateHeartbeat()}catch(t){let r=t instanceof Error?t.message:String(t);if(t?.code==="ENOENT"){H("SessionLock: Session directory removed, stopping heartbeat"),this.stopHeartbeat();return}H(`SessionLock: Failed to update heartbeat: ${r}`)}},e),this.heartbeatTimer.unref()}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0)}async updateHeartbeat(){let e=await this.readLockAt(this.lockPath),t=this.acquiredOwner;if(!(!e||!t)){if(!De(e,t)){this.acquiredOwner=void 0,J.delete(this.lockPath),this.stopHeartbeat();return}e.heartbeat=new Date().toISOString(),e.updatedAt=e.heartbeat,await y(this.lockPath,JSON.stringify(e,null,2))}}async readLock(){let e=await this.findExistingLockPath();return e?this.readLockAt(e):null}async readLockAt(e){let t=await k(e);return t?v(t,null):null}async findExistingLockPath(){return await k(this.lockPath)?this.lockPath:await k(this.legacyLockPath)?this.legacyLockPath:null}static async cleanStale(e){let t=await oe(e),r=[];for(let s of t){let i=new n(s);if(await i.isStale()){let a=await i.findExistingLockPath();a&&await N(a),r.push(j.basename(s))}}return r}};import*as I from"path";var ee=1;import*as M from"path";function hr(n,e){let t=M.resolve(n),r=M.resolve(n,e);return r===t?!0:t===M.parse(t).root?r.startsWith(t):r.startsWith(t+M.sep)}function q(n,e){if(M.isAbsolute(e))return M.resolve(e);if(!hr(n,e))throw new Error(`PathSecurity: Path traversal attempt detected: ${e}`);return M.resolve(n,e)}function ue(n,e=process.platform){let t=M.resolve(n);return e==="win32"?t.toLowerCase():t}function G(n){if(n!==void 0&&n!=="agent"&&n!=="chatOnly")throw new Error("Invalid session execution mode; expected agent or chatOnly.")}import*as E from"path";import*as pe from"os";import*as P from"node:fs/promises";import{createHash as kr,randomUUID as Sr}from"node:crypto";import{homedir as ht,platform as wr,release as yr}from"node:os";import{delimiter as qn,join as Gn,resolve as mt}from"node:path";var Xn=wr();var Jn=yr(),zn=ht();function le(){let n=process.env.XENO_AGENT_HOME?.trim();return n?mt(n):mt(ht(),".xeno-agent")}var wt=1,yt="recent.json",xr=".lock",St=".entries",Tr=3e4,Ce=6e4,xt=new Set(["EACCES","EBUSY","EPERM"]),vr=[5,10,20,40,80,160,320],de=new Map;function br(n,e){let t=kr("sha256").update(e).digest("hex");return E.join(`${n}${St}`,`${t}.json`)}async function Oe(n,e,t){let r={schemaVersion:1,key:e,entry:t};await y(br(n,e),JSON.stringify(r)+`
52
52
  `)}async function Er(n,e){let t=`${n}${St}`,r;try{r=await P.readdir(t)}catch(s){if(s.code==="ENOENT")return;throw s}await Promise.all(r.filter(s=>s.endsWith(".json")).map(async s=>{let i=await P.readFile(E.join(t,s),"utf8").catch(()=>""),o=v(i,null);if(!(!o||o.schemaVersion!==1||typeof o.key!="string")){if(o.entry===null){delete e[o.key];return}typeof o.entry.sessionId!="string"||typeof o.entry.endedAt!="string"||(e[o.key]=o.entry)}}))}function kt(n){if(!Number.isInteger(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch(e){return e.code==="EPERM"}}async function Pr(n){try{let[e,t]=await Promise.all([P.readFile(E.join(n,"owner.json"),"utf8").catch(()=>""),P.stat(n)]),r=v(e,null);return r?.hostname===pe.hostname()&&kt(r.pid)?!1:r?.hostname&&r.hostname!==pe.hostname()||!r?Date.now()-t.mtimeMs>Ce:Date.now()-t.mtimeMs>Ce||!kt(r.pid)}catch{return!1}}async function Tt(n){for(let e=0;;e+=1)try{await P.rm(n,{recursive:!0});return}catch(t){let r=t.code;if(r==="ENOENT")return;let s=vr[e];if(process.platform!=="win32"||!r||!xt.has(r)||s===void 0)throw t;await new Promise(i=>setTimeout(i,s))}}async function Rr(n,e){try{let t=await P.readFile(E.join(n,"owner.json"),"utf8");v(t,null)?.token===e&&await Tt(n)}catch(t){if(t.code!=="ENOENT")throw t}}async function Ne(n,e){let t=V(n),r=de.get(t)??Promise.resolve(),s,i=new Promise(o=>{s=o});de.set(t,i),await r;try{return await Mr(t,e)}finally{s(),de.get(t)===i&&de.delete(t)}}async function Mr(n,e){let t=`${n}${xr}`,r=Sr(),s=Date.now();await P.mkdir(E.dirname(n),{recursive:!0});for(let i=0;;i+=1){let o={schemaVersion:1,token:r,pid:process.pid,hostname:pe.hostname(),acquiredAt:new Date().toISOString()};try{await P.mkdir(t),await P.writeFile(E.join(t,"owner.json"),JSON.stringify(o),"utf8");break}catch(a){let c=a.code,u=process.platform==="win32"&&!!c&&xt.has(c);if(c!=="EEXIST"&&!u)throw a;if(await Pr(t)){await Tt(t);continue}if(Date.now()-s>=Tr)throw new Error(`Timed out waiting for recent-sessions index lock: ${t}`);let l=Math.min(100,5+i*5)+Math.floor(Math.random()*10);await new Promise(d=>setTimeout(d,l))}}try{return await e()}finally{await Rr(t,r)}}function V(n){return n===void 0?E.join(le(),yt):E.join(n,".xeno-agent",yt)}function ge(n){let e=E.normalize(n).replace(/[\\/]+$/,""),t=e.length>0?e:E.parse(E.normalize(n)).root;return process.platform==="win32"?t.toLowerCase():t}async function W(n){let e=V(n),t=ie(e)?await k(e):null,r=t?v(t,null):null,s=r&&typeof r=="object"?r:null,i={},o=s?.version===wt&&s.entries&&typeof s.entries=="object"?s.entries:{};for(let[a,c]of Object.entries(o)){if(!c||typeof c!="object")continue;let u=c;typeof u.sessionId!="string"||u.sessionId.length===0||typeof u.endedAt=="string"&&(i[a]={sessionId:u.sessionId,endedAt:u.endedAt,role:typeof u.role=="string"?u.role:void 0})}return await Er(e,i),{version:wt,entries:i}}async function $e(n,e={}){let t=await W(e.homeDir),r=ge(n),s=t.entries[r];if(s&&!(e.role&&s.role&&s.role!==e.role))return s}async function Le(n,e={}){let t=ge(n.cwd),r={sessionId:n.sessionId,role:n.role,endedAt:n.endedAt??new Date().toISOString()},s=V(e.homeDir);await Oe(s,t,r),await Ne(e.homeDir,async()=>{let i=await W(e.homeDir);i.entries[t]=r,await y(s,JSON.stringify(i,null,2)+`
53
53
  `)})}async function _r(n,e={}){let t=ge(n),r=V(e.homeDir);(await W(e.homeDir)).entries[t]&&(await Oe(r,t,null),await Ne(e.homeDir,async()=>{let i=await W(e.homeDir);delete i.entries[t],await y(r,JSON.stringify(i,null,2)+`
54
54
  `)}))}async function fe(n,e={}){let t=await W(e.homeDir),r=Object.entries(t.entries).filter(([,i])=>i.sessionId===n).map(([i])=>i);if(r.length===0)return;let s=V(e.homeDir);await Promise.all(r.map(i=>Oe(s,i,null))),await Ne(e.homeDir,async()=>{let i=await W(e.homeDir);for(let[o,a]of Object.entries(i.entries))a.sessionId===n&&delete i.entries[o];await y(s,JSON.stringify(i,null,2)+`
@@ -1,6 +1,9 @@
1
- "use strict";var D=Object.defineProperty;var ae=Object.getOwnPropertyDescriptor;var ue=Object.getOwnPropertyNames;var de=Object.prototype.hasOwnProperty;var me=(e,n)=>{for(var t in n)D(e,t,{get:n[t],enumerable:!0})},fe=(e,n,t,o)=>{if(n&&typeof n=="object"||typeof n=="function")for(let r of ue(n))!de.call(e,r)&&r!==t&&D(e,r,{get:()=>n[r],enumerable:!(o=ae(n,r))||o.enumerable});return e};var pe=e=>fe(D({},"__esModule",{value:!0}),e);var Be={};me(Be,{XENO_SKILL_SCHEMA_VERSION:()=>S,compileXenoSkillActivation:()=>Ae,createXenoSkillTool:()=>Ie,discoverXenoSkills:()=>he,findXenoSkill:()=>O,importLegacyXenoSkill:()=>we,invokeXenoSkill:()=>te,isToolAllowedByXenoSkillActivation:()=>De,loadXenoSkill:()=>_,renderXenoSkillCatalog:()=>Xe});module.exports=pe(Be);var S=2;var q=require("node:crypto"),f=require("node:fs"),d=require("node:path");function $(e){let n=ye(e);return{frontmatter:n.frontmatter,content:n.content.trim()}}function ye(e){let n=e.replace(/^\uFEFF/,"");if(!n.startsWith("---"))return{frontmatter:{},content:e};let t=n.search(/\r?\n/);if(t<0||n.slice(0,t).trim()!=="---")return{frontmatter:{},content:e};let o=n.slice(t+(n[t]==="\r"?2:1)),r=o.match(/(?:^|\r?\n)---[ \t]*(?:\r?\n|$)/);if(!r||r.index===void 0)throw new Error("YAML frontmatter is not closed.");let i=o.slice(0,r.index),c=r[0],m=r.index+c.length;return{frontmatter:K(i),content:o.slice(m)}}function K(e){let n={},t=e.split(/\r?\n/);for(let o=0;o<t.length;o+=1){let r=t[o];if(!r.trim()||r.trimStart().startsWith("#"))continue;if(/^\s/.test(r))throw new Error(`Unexpected indentation at line ${o+1}.`);let i=ke(r,o+1);if(i.key==="<<")throw new Error("YAML merge keys are not supported.");if(i.value!==""){n[i.key]=M(i.value,o+1);continue}let c=ge(t,o+1);n[i.key]=c.value,o=c.nextIndex-1}return n}function ge(e,n){let t=[],o=n;for(;o<e.length;o+=1){let i=e[o];if(!i.trim()){t.push(i);continue}if(!/^\s/.test(i))break;t.push(i.replace(/^ {2}/,""))}let r=t.filter(i=>i.trim()&&!i.trimStart().startsWith("#"));return r.length===0?{value:{},nextIndex:o}:r.every(i=>i.trimStart().startsWith("- "))?{value:r.map((i,c)=>M(i.trimStart().slice(2),n+c+1)),nextIndex:o}:{value:K(t.join(`
2
- `)),nextIndex:o}}function ke(e,n){let t=e.indexOf(":");if(t<=0)throw new Error(`Invalid YAML line ${n}.`);let o=e.slice(0,t).trim(),r=e.slice(t+1).trim();if(!o)throw new Error(`Invalid YAML key at line ${n}.`);return{key:o,value:r}}function M(e,n){if(e==="")return"";if(e==="[]")return[];if(e==="{}")return{};if(e==="true")return!0;if(e==="false")return!1;if(e==="null"||e==="~")return null;if(/^-?\d+(?:\.\d+)?$/.test(e))return Number(e);if(e.startsWith('"'))return j(e,n);if(e.startsWith("'")){if(!e.endsWith("'"))throw new Error(`Unclosed quoted scalar at line ${n}.`);return e.slice(1,-1).replace(/''/g,"'")}if(e.startsWith("[")||e.startsWith("{"))return j(e,n);if(e.includes("[")||e.includes("]")||e.includes("{")||e.includes("}"))throw new Error(`Unsupported YAML scalar at line ${n}.`);return e}function j(e,n){try{return JSON.parse(e)}catch{throw new Error(`Invalid YAML scalar at line ${n}.`)}}var P=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,Se=2e3,V=2*1024*1024,z=2e3,Y=64*1024*1024;function he(e){let n={maxSkills:E(e.maxSkills,Se,1,2e4),maxSkillBytes:E(e.maxSkillBytes,V,1024,16777216),maxResourceFiles:E(e.maxResourceFiles,z,0,2e4),maxResourceBytes:E(e.maxResourceBytes,Y,0,536870912)},t=[],o=[],r=new Set;for(let s of e.roots){if(o.length>=n.maxSkills)break;let l=(0,d.resolve)(s.path),a;try{if(!(0,f.statSync)(l,{throwIfNoEntry:!1})?.isDirectory())continue;a=(0,f.readdirSync)(l,{withFileTypes:!0}).sort((p,y)=>p.name.localeCompare(y.name))}catch(p){t.push({severity:"warning",code:"SKILL_ROOT_UNREADABLE",message:`Unable to inspect skill root: ${F(p)}`,path:l});continue}for(let p of a){if(o.length>=n.maxSkills)break;let y=(0,d.join)(l,p.name);try{let g=(0,f.lstatSync)(y);if(g.isSymbolicLink()&&!s.followSymlinks){t.push({severity:"warning",code:"SKILL_SYMLINK_REJECTED",message:"Skill directory symlinks require an explicitly trusted discovery root",path:y});continue}let u=g.isSymbolicLink()?(0,f.realpathSync)(y):y;if(!(0,f.statSync)(u).isDirectory())continue;let k=(0,f.realpathSync)(u);if(r.has(k))continue;let w=W(k,s,n,t);if(!w)continue;r.add(k),o.push(w.descriptor)}catch(g){t.push({severity:"error",code:"SKILL_INVALID",message:F(g),path:y})}}}let i=new Map;for(let s of o){let l=i.get(s.key)??[];l.push(s),i.set(s.key,l)}let c=[],m=[];for(let[s,l]of[...i].sort(([a],[p])=>a.localeCompare(p))){let a=l.sort((u,k)=>k.precedence-u.precedence||u.entrypoint.localeCompare(k.entrypoint)),p=a[0]?.precedence,y=a.filter(u=>u.precedence===p);if(y.length>1&&new Set(y.map(u=>u.contentHash)).size>1){t.push({severity:"error",code:"SKILL_AMBIGUOUS",key:s,message:`Skill ${s} has conflicting definitions at precedence ${p}; qualify or remove one definition`});continue}let g=a[0];c.push(g),a.length>1&&m.push({key:s,selected:g,shadowed:a.slice(1)})}return c.sort((s,l)=>s.key.localeCompare(l.key)),{schemaVersion:2,generatedAt:(e.now?.()??new Date).toISOString(),catalogHash:b(h(c.map(Le))),skills:c,shadowed:m,diagnostics:t}}function _(e){if(e.source==="legacy"){let r=$((0,f.readFileSync)(e.entrypoint,"utf8")).content.trim();if(J(e,r)!==e.contentHash)throw new Error(`Skill ${e.key} changed after discovery; refresh the catalog before invoking it`);return{descriptor:structuredClone(e),instructions:r}}let n=[],t=W(e.directory,{path:(0,d.dirname)(e.directory),source:e.source,precedence:e.precedence,...e.namespace?{namespace:e.namespace}:{},followSymlinks:!1},{maxSkills:1,maxSkillBytes:Math.max(V,e.instructionBytes),maxResourceFiles:Math.max(z,e.resources.length),maxResourceBytes:Math.max(Y,e.resources.reduce((o,r)=>o+r.sizeBytes,0))},n);if(!t||n.some(o=>o.severity==="error"))throw new Error(`Unable to load skill ${e.key}: ${n.map(o=>o.message).join("; ")||"invalid skill"}`);if(t.descriptor.contentHash!==e.contentHash)throw new Error(`Skill ${e.key} changed after discovery; refresh the catalog before invoking it`);return{descriptor:structuredClone(e),instructions:t.instructions}}function we(e){let n=e.id.trim().toLowerCase();if(!P.test(n)||n.length>64)throw new Error(`Legacy skill name is invalid: ${e.id}`);let t=e.content.trim();if(!t)throw new Error("Legacy skill content cannot be empty");let o=e.path?(0,d.dirname)((0,d.resolve)(e.path)):process.cwd(),r={schemaVersion:2,key:e.namespace?`${e.namespace}:${n}`:n,name:n,description:e.description?.trim()||e.name?.trim()||`Imported legacy XENO skill ${n}`,source:"legacy",precedence:e.precedence??0,directory:o,entrypoint:e.path?(0,d.resolve)(e.path):(0,d.join)(o,`${n}.md`),...e.namespace?{namespace:e.namespace}:{},...e.version?{version:e.version}:{},metadata:{"xeno.imported-from":e.source??"legacy"},modelInvocable:e.modelInvocable??!0,userInvocable:e.userInvocable??!0,requestedPreapprovedTools:[...new Set(e.allowedTools??[])].sort(),toolPolicy:G(e.toolPolicy),externalActions:e.externalActions??"ask",contentHash:"",instructionBytes:Buffer.byteLength(t,"utf8"),resources:[]};return r.contentHash=J(r,t),{descriptor:r,instructions:t}}function Xe(e){let n=e.skills.filter(t=>t.modelInvocable);return n.length===0?"":["<available_skills>",...n.flatMap(t=>[" <skill>",` <name>${U(t.key)}</name>`,` <description>${U(t.description)}</description>`,` <hash>${t.contentHash}</hash>`," </skill>"]),"</available_skills>","Use the Skill tool to load full instructions only when a listed skill is relevant."].join(`
3
- `)}function O(e,n){let t=n.trim().toLowerCase();if(!t)return;let o=e.skills.find(i=>i.key.toLowerCase()===t);if(o)return o;let r=e.skills.filter(i=>i.name.toLowerCase()===t);return r.length===1?r[0]:void 0}function W(e,n,t,o){let r=(0,d.join)(e,"SKILL.md"),i=(0,f.lstatSync)(r,{throwIfNoEntry:!1});if(!i)return;if(i.isSymbolicLink()||!i.isFile())throw new Error("SKILL.md must be a regular, non-symlink file");if(i.size>t.maxSkillBytes)throw new Error(`SKILL.md exceeds ${t.maxSkillBytes} bytes`);let c=(0,f.readFileSync)(r,"utf8"),m=$(c),s=m.frontmatter,l=H(s.name,"name"),a=H(s.description,"description");if(!P.test(l)||l.length>64)throw new Error(`Skill name does not match ${P.source} or exceeds 64 characters`);if(l!==(0,d.basename)(e))throw new Error(`Skill name ${l} must match its parent directory ${(0,d.basename)(e)}`);if(a.length>1024)throw new Error("Skill description exceeds 1024 characters");let p=T(s.license,"license"),y=T(s.compatibility,"compatibility");if(y&&y.length>500)throw new Error("Skill compatibility exceeds 500 characters");let g=be(s.metadata,"metadata"),u=L(s.xeno),k=R(s["allowed-tools"]??s.allowedTools),w=G({allow:R(u?.["allowed-tools"]??u?.allowedTools??L(u?.tools)?.allow),deny:R(u?.["denied-tools"]??u?.deniedTools??L(u?.tools)?.deny)}),ie=ve(u?.["external-actions"]??u?.externalActions),se=!(x(s["disable-model-invocation"])??!1)&&(x(u?.modelInvocable)??!0),le=x(s["user-invocable"])??x(u?.userInvocable)??!0,B=xe(e,r,t,o),A=m.content.trim();if(!A)throw new Error("SKILL.md instructions cannot be empty");let ce=b(h({raw:c,resources:B.map(N=>({path:N.relativePath,sha256:N.sha256}))})),X=n.namespace?.trim();return{descriptor:{schemaVersion:2,key:X?`${X}:${l}`:l,name:l,description:a,source:n.source,precedence:n.precedence,directory:e,entrypoint:r,...X?{namespace:X}:{},...g.version?{version:g.version}:{},...p?{license:p}:{},...y?{compatibility:y}:{},metadata:g,modelInvocable:se,userInvocable:le,requestedPreapprovedTools:k,toolPolicy:w,externalActions:ie,contentHash:ce,instructionBytes:Buffer.byteLength(A,"utf8"),resources:B},instructions:A}}function xe(e,n,t,o){let r=[],i=0,c=m=>{for(let s of(0,f.readdirSync)(m,{withFileTypes:!0}).sort((l,a)=>l.name.localeCompare(a.name))){let l=(0,d.join)(m,s.name);if(l===n)continue;let a=(0,f.lstatSync)(l);if(a.isSymbolicLink()){o.push({severity:"warning",code:"SKILL_SYMLINK_REJECTED",message:"Skill resource symlinks are not included",path:l});continue}if(a.isDirectory()){c(l);continue}if(!a.isFile())continue;if(r.length>=t.maxResourceFiles)throw new Error(`Skill resource count exceeds ${t.maxResourceFiles}`);if(i+=a.size,i>t.maxResourceBytes)throw new Error(`Skill resources exceed ${t.maxResourceBytes} bytes`);let p=(0,d.relative)(e,l).split(d.sep).join("/");r.push({relativePath:p,kind:Ee(p),sizeBytes:a.size,sha256:b((0,f.readFileSync)(l))})}};return c(e),r.sort((m,s)=>m.relativePath.localeCompare(s.relativePath))}function Ee(e){let n=e.split("/",1)[0]?.toLowerCase();return n==="scripts"?"script":n==="references"?"reference":n==="assets"?"asset":n==="templates"?"template":"other"}function Le(e){return{key:e.key,source:e.source,precedence:e.precedence,contentHash:e.contentHash,modelInvocable:e.modelInvocable,userInvocable:e.userInvocable}}function J(e,n){return b(h({key:e.key,description:e.description,instructions:n,requestedPreapprovedTools:e.requestedPreapprovedTools,toolPolicy:e.toolPolicy,externalActions:e.externalActions}))}function G(e){let n=[...new Set(e?.allow?.map(o=>o.trim()).filter(Boolean)??[])].sort(),t=[...new Set(e?.deny?.map(o=>o.trim()).filter(Boolean)??[])].sort();return{...n.length>0?{allow:n}:{},...t.length>0?{deny:t}:{}}}function R(e){return typeof e=="string"?[...new Set(e.split(/\s+/u).map(n=>n.trim()).filter(Boolean))].sort():Array.isArray(e)?[...new Set(e.filter(n=>typeof n=="string").map(n=>n.trim()).filter(Boolean))].sort():[]}function be(e,n){if(e===void 0)return{};let t=L(e);if(!t)throw new Error(`${n} must be a string-to-string mapping`);let o={};for(let[r,i]of Object.entries(t)){if(typeof i!="string")throw new Error(`${n}.${r} must be a string`);o[r]=i}return o}function H(e,n){let t=T(e,n);if(!t)throw new Error(`Skill ${n} is required`);return t}function T(e,n){if(e===void 0)return;if(typeof e!="string")throw new Error(`Skill ${n} must be a string`);let t=e.trim();if(!t)throw new Error(`Skill ${n} cannot be empty`);return t}function L(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function x(e){return typeof e=="boolean"?e:void 0}function ve(e){return e==="deny"||e==="allow"||e==="ask"?e:"ask"}function E(e,n,t,o){if(e===void 0)return n;if(!Number.isInteger(e)||e<t||e>o)throw new Error(`Skill discovery limit must be an integer between ${t} and ${o}`);return e}function h(e){return Array.isArray(e)?`[${e.map(h).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).filter(([,n])=>n!==void 0).sort(([n],[t])=>n.localeCompare(t)).map(([n,t])=>`${JSON.stringify(n)}:${h(t)}`).join(",")}}`:JSON.stringify(e)??"null"}function b(e){return(0,q.createHash)("sha256").update(e).digest("hex")}function U(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function F(e){return e instanceof Error?e.message:String(e)}var ne=require("node:crypto");var Q=128*1024;function Ie(e){return{definition:{name:"Skill",description:"Load one available SKILL.md instruction body on demand. Use only a name from <available_skills>.",input_schema:{type:"object",properties:{name:{type:"string",description:"Exact skill key or unique skill name"},arguments:{type:"string",description:"Optional arguments supplied to the skill"}},required:["name"],additionalProperties:!1}},projectPolicyInput:n=>({observabilityInput:{name:typeof n.name=="string"?n.name:"",hasArguments:typeof n.arguments=="string"&&n.arguments.length>0},permissionInput:{name:typeof n.name=="string"?n.name:""},permissionPreview:`Load skill ${typeof n.name=="string"?n.name:""}`,approvalKey:`skill:${typeof n.name=="string"?n.name:"unknown"}`,riskLevel:"low"}),execute:async n=>{let t=typeof n.name=="string"?n.name.trim():"",o=typeof n.arguments=="string"?n.arguments.trim():"";if(!t)return ee("SKILL_INVALID_INPUT","Skill name is required");try{return{success:!0,output:(await te({...e,name:t,arguments:o,invocation:"model"})).output}}catch(r){return ee("SKILL_INVOCATION_DENIED",C(r))}}}}async function te(e){let n=e.getCatalog(),t=O(n,e.name);if(!t)throw new Error(`Skill not found or ambiguous: ${e.name}`);let o=e.arguments?.trim()??"",r={schemaVersion:2,recordedAt:(e.now?.()??new Date).toISOString(),skillKey:t.key,skillHash:t.contentHash,invocation:e.invocation,...o?{argumentsHash:Oe(o)}:{}};try{let i=await Re(t,e.invocation,e);if(i==="deny")throw await v(e,{...r,type:"skill-denied",reason:"Invocation policy denied the skill"}),new Error(`Skill ${t.key} is denied by the active policy`);if(i==="ask"&&(!e.ask||!await e.ask(t)))throw await v(e,{...r,type:"skill-denied",reason:"User did not approve skill invocation"}),new Error(`Skill ${t.key} requires approval`);let c=await(e.loadSkill??_)(t);if(c.descriptor.contentHash!==t.contentHash)throw new Error(`Skill ${t.key} loader returned a mismatched content hash`);let m=re(e.invocationPolicy),s=oe(t,o,m);await e.onActivate?.(structuredClone(s));let l=$e(c,s,{arguments:o,projectDirectory:typeof e.projectDirectory=="function"?e.projectDirectory():e.projectDirectory});if(Buffer.byteLength(l,"utf8")>Q)throw new Error(`Skill ${t.key} exceeds the ${Q}-byte invocation limit; move details into references/`);return await v(e,{...r,type:"skill-invoked"}),{loaded:c,activation:s,output:l}}catch(i){throw/denied by the active policy|requires approval/u.test(C(i))||await v(e,{...r,type:"skill-load-failed",reason:C(i)}),i}}function Ae(e,n="",t){return oe(e,n,t)}function oe(e,n,t){let o=Z(t?.allow),r=Z(e.toolPolicy.allow),i=[o,r].filter(s=>s!==void 0),c=i.length<=1?i[0]:void 0,m=[...new Set([...e.toolPolicy.deny??[],...t?.deny??[]])].sort();return{descriptor:structuredClone(e),arguments:n,toolAllowLayers:i,...c?{effectiveAllowedTools:c}:{},effectiveDeniedTools:m,externalActions:Pe(e.externalActions,t?.externalActions??"allow")}}function De(e,n){return I(n,e.effectiveDeniedTools)?!1:e.toolAllowLayers.every(t=>I(n,t))}function $e(e,n,t){let o=e.descriptor,r=e.instructions,i=/\$ARGUMENTS(?:\[\d+\])?|\$\d+/u.test(r),c=_e(t.arguments);r=r.replace(/\$ARGUMENTS\[(\d+)\]/gu,(s,l)=>c[Number.parseInt(l,10)]??"").replace(/\$(\d+)\b/gu,(s,l)=>c[Number.parseInt(l,10)]??"").replace(/\$ARGUMENTS\b/gu,t.arguments).replace(/\$\{(?:XENO|CLAUDE)_SKILL_DIR\}/gu,o.directory).replace(/\$\{(?:XENO|CLAUDE)_PROJECT_DIR\}/gu,t.projectDirectory??process.cwd()),t.arguments&&!i&&(r+=`
1
+ "use strict";var D=Object.defineProperty;var ae=Object.getOwnPropertyDescriptor;var ue=Object.getOwnPropertyNames;var de=Object.prototype.hasOwnProperty;var me=(e,n)=>{for(var t in n)D(e,t,{get:n[t],enumerable:!0})},fe=(e,n,t,o)=>{if(n&&typeof n=="object"||typeof n=="function")for(let r of ue(n))!de.call(e,r)&&r!==t&&D(e,r,{get:()=>n[r],enumerable:!(o=ae(n,r))||o.enumerable});return e};var pe=e=>fe(D({},"__esModule",{value:!0}),e);var Ne={};me(Ne,{XENO_SKILL_SCHEMA_VERSION:()=>S,compileXenoSkillActivation:()=>De,createXenoSkillTool:()=>Ae,discoverXenoSkills:()=>we,findXenoSkill:()=>O,importLegacyXenoSkill:()=>Xe,invokeXenoSkill:()=>te,isToolAllowedByXenoSkillActivation:()=>$e,loadXenoSkill:()=>_,renderXenoSkillCatalog:()=>xe});module.exports=pe(Ne);var S=2;var q=require("node:crypto"),g=require("node:fs"),f=require("node:path");function $(e){let n=ge(e);return{frontmatter:n.frontmatter,content:n.content.trim()}}function ge(e){let n=e.replace(/^\uFEFF/,"");if(!n.startsWith("---"))return{frontmatter:{},content:e};let t=n.search(/\r?\n/);if(t<0||n.slice(0,t).trim()!=="---")return{frontmatter:{},content:e};let o=n.slice(t+(n[t]==="\r"?2:1)),r=o.match(/(?:^|\r?\n)---[ \t]*(?:\r?\n|$)/);if(!r||r.index===void 0)throw new Error("YAML frontmatter is not closed.");let i=o.slice(0,r.index),a=r[0],u=r.index+a.length;return{frontmatter:K(i),content:o.slice(u)}}function K(e){let n={},t=e.split(/\r?\n/);for(let o=0;o<t.length;o+=1){let r=t[o];if(!r.trim()||r.trimStart().startsWith("#"))continue;if(/^\s/.test(r))throw new Error(`Unexpected indentation at line ${o+1}.`);let i=Se(r,o+1);if(i.key==="<<")throw new Error("YAML merge keys are not supported.");let a=i.value.match(/^([|>])([+-]?)$/);if(a){let s=ye(t,o+1,a[1],a[2]??"");n[i.key]=s.value,o=s.nextIndex-1;continue}if(i.value!==""){n[i.key]=M(i.value,o+1);continue}let u=ke(t,o+1);n[i.key]=u.value,o=u.nextIndex-1}return n}function ye(e,n,t,o){let r=[],i=n;for(;i<e.length;i+=1){let c=e[i];if(c.trim()===""){r.push("");continue}if(!/^\s/.test(c))break;r.push(c)}let a=r.filter(c=>c.trim()!=="").map(c=>c.match(/^ */)[0].length),u=a.length>0?Math.min(...a):0,s=r.map(c=>c.trim()===""?"":c.slice(u));for(;s.length>0&&s[s.length-1]==="";)s.pop();let l;return t==="|"?l=s.join(`
2
+ `):(l="",s.forEach((c,m)=>{if(m===0){l=c;return}let p=s[m-1];c===""?l+=`
3
+ `:p===""?l+=c:l+=" "+c})),{value:o==="-"?l:l+`
4
+ `,nextIndex:i}}function ke(e,n){let t=[],o=n;for(;o<e.length;o+=1){let i=e[o];if(!i.trim()){t.push(i);continue}if(!/^\s/.test(i))break;t.push(i.replace(/^ {2}/,""))}let r=t.filter(i=>i.trim()&&!i.trimStart().startsWith("#"));return r.length===0?{value:{},nextIndex:o}:r.every(i=>i.trimStart().startsWith("- "))?{value:r.map((i,a)=>M(i.trimStart().slice(2),n+a+1)),nextIndex:o}:{value:K(t.join(`
5
+ `)),nextIndex:o}}function Se(e,n){let t=e.indexOf(":");if(t<=0)throw new Error(`Invalid YAML line ${n}.`);let o=e.slice(0,t).trim(),r=e.slice(t+1).trim();if(!o)throw new Error(`Invalid YAML key at line ${n}.`);return{key:o,value:r}}function M(e,n){if(e==="")return"";if(e==="[]")return[];if(e==="{}")return{};if(e==="true")return!0;if(e==="false")return!1;if(e==="null"||e==="~")return null;if(/^-?\d+(?:\.\d+)?$/.test(e))return Number(e);if(e.startsWith('"'))return j(e,n);if(e.startsWith("'")){if(!e.endsWith("'"))throw new Error(`Unclosed quoted scalar at line ${n}.`);return e.slice(1,-1).replace(/''/g,"'")}if(e.startsWith("[")||e.startsWith("{"))return j(e,n);if(e.includes("[")||e.includes("]")||e.includes("{")||e.includes("}"))throw new Error(`Unsupported YAML scalar at line ${n}.`);return e}function j(e,n){try{return JSON.parse(e)}catch{throw new Error(`Invalid YAML scalar at line ${n}.`)}}var P=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,he=2e3,V=2*1024*1024,z=2e3,Y=64*1024*1024;function we(e){let n={maxSkills:b(e.maxSkills,he,1,2e4),maxSkillBytes:b(e.maxSkillBytes,V,1024,16777216),maxResourceFiles:b(e.maxResourceFiles,z,0,2e4),maxResourceBytes:b(e.maxResourceBytes,Y,0,536870912)},t=[],o=[],r=new Set;for(let s of e.roots){if(o.length>=n.maxSkills)break;let l=(0,f.resolve)(s.path),c;try{if(!(0,g.statSync)(l,{throwIfNoEntry:!1})?.isDirectory())continue;c=(0,g.readdirSync)(l,{withFileTypes:!0}).sort((m,p)=>m.name.localeCompare(p.name))}catch(m){t.push({severity:"warning",code:"SKILL_ROOT_UNREADABLE",message:`Unable to inspect skill root: ${F(m)}`,path:l});continue}for(let m of c){if(o.length>=n.maxSkills)break;let p=(0,f.join)(l,m.name);try{let y=(0,g.lstatSync)(p);if(y.isSymbolicLink()&&!s.followSymlinks){t.push({severity:"warning",code:"SKILL_SYMLINK_REJECTED",message:"Skill directory symlinks require an explicitly trusted discovery root",path:p});continue}let d=y.isSymbolicLink()?(0,g.realpathSync)(p):p;if(!(0,g.statSync)(d).isDirectory())continue;let k=(0,g.realpathSync)(d);if(r.has(k))continue;let w=W(k,s,n,t);if(!w)continue;r.add(k),o.push(w.descriptor)}catch(y){t.push({severity:"error",code:"SKILL_INVALID",message:F(y),path:p})}}}let i=new Map;for(let s of o){let l=i.get(s.key)??[];l.push(s),i.set(s.key,l)}let a=[],u=[];for(let[s,l]of[...i].sort(([c],[m])=>c.localeCompare(m))){let c=l.sort((d,k)=>k.precedence-d.precedence||d.entrypoint.localeCompare(k.entrypoint)),m=c[0]?.precedence,p=c.filter(d=>d.precedence===m);if(p.length>1&&new Set(p.map(d=>d.contentHash)).size>1){t.push({severity:"error",code:"SKILL_AMBIGUOUS",key:s,message:`Skill ${s} has conflicting definitions at precedence ${m}; qualify or remove one definition`});continue}let y=c[0];a.push(y),c.length>1&&u.push({key:s,selected:y,shadowed:c.slice(1)})}return a.sort((s,l)=>s.key.localeCompare(l.key)),{schemaVersion:2,generatedAt:(e.now?.()??new Date).toISOString(),catalogHash:E(h(a.map(Ee))),skills:a,shadowed:u,diagnostics:t}}function _(e){if(e.source==="legacy"){let r=$((0,g.readFileSync)(e.entrypoint,"utf8")).content.trim();if(J(e,r)!==e.contentHash)throw new Error(`Skill ${e.key} changed after discovery; refresh the catalog before invoking it`);return{descriptor:structuredClone(e),instructions:r}}let n=[],t=W(e.directory,{path:(0,f.dirname)(e.directory),source:e.source,precedence:e.precedence,...e.namespace?{namespace:e.namespace}:{},followSymlinks:!1},{maxSkills:1,maxSkillBytes:Math.max(V,e.instructionBytes),maxResourceFiles:Math.max(z,e.resources.length),maxResourceBytes:Math.max(Y,e.resources.reduce((o,r)=>o+r.sizeBytes,0))},n);if(!t||n.some(o=>o.severity==="error"))throw new Error(`Unable to load skill ${e.key}: ${n.map(o=>o.message).join("; ")||"invalid skill"}`);if(t.descriptor.contentHash!==e.contentHash)throw new Error(`Skill ${e.key} changed after discovery; refresh the catalog before invoking it`);return{descriptor:structuredClone(e),instructions:t.instructions}}function Xe(e){let n=e.id.trim().toLowerCase();if(!P.test(n)||n.length>64)throw new Error(`Legacy skill name is invalid: ${e.id}`);let t=e.content.trim();if(!t)throw new Error("Legacy skill content cannot be empty");let o=e.path?(0,f.dirname)((0,f.resolve)(e.path)):process.cwd(),r={schemaVersion:2,key:e.namespace?`${e.namespace}:${n}`:n,name:n,description:e.description?.trim()||e.name?.trim()||`Imported legacy XENO skill ${n}`,source:"legacy",precedence:e.precedence??0,directory:o,entrypoint:e.path?(0,f.resolve)(e.path):(0,f.join)(o,`${n}.md`),...e.namespace?{namespace:e.namespace}:{},...e.version?{version:e.version}:{},metadata:{"xeno.imported-from":e.source??"legacy"},modelInvocable:e.modelInvocable??!0,userInvocable:e.userInvocable??!0,requestedPreapprovedTools:[...new Set(e.allowedTools??[])].sort(),toolPolicy:G(e.toolPolicy),externalActions:e.externalActions??"ask",contentHash:"",instructionBytes:Buffer.byteLength(t,"utf8"),resources:[]};return r.contentHash=J(r,t),{descriptor:r,instructions:t}}function xe(e){let n=e.skills.filter(t=>t.modelInvocable);return n.length===0?"":["<available_skills>",...n.flatMap(t=>[" <skill>",` <name>${U(t.key)}</name>`,` <description>${U(t.description)}</description>`,` <hash>${t.contentHash}</hash>`," </skill>"]),"</available_skills>","Use the Skill tool to load full instructions only when a listed skill is relevant."].join(`
6
+ `)}function O(e,n){let t=n.trim().toLowerCase();if(!t)return;let o=e.skills.find(i=>i.key.toLowerCase()===t);if(o)return o;let r=e.skills.filter(i=>i.name.toLowerCase()===t);return r.length===1?r[0]:void 0}function W(e,n,t,o){let r=(0,f.join)(e,"SKILL.md"),i=(0,g.lstatSync)(r,{throwIfNoEntry:!1});if(!i)return;if(i.isSymbolicLink()||!i.isFile())throw new Error("SKILL.md must be a regular, non-symlink file");if(i.size>t.maxSkillBytes)throw new Error(`SKILL.md exceeds ${t.maxSkillBytes} bytes`);let a=(0,g.readFileSync)(r,"utf8"),u=$(a),s=u.frontmatter,l=H(s.name,"name"),c=H(s.description,"description");if(!P.test(l)||l.length>64)throw new Error(`Skill name does not match ${P.source} or exceeds 64 characters`);if(l!==(0,f.basename)(e))throw new Error(`Skill name ${l} must match its parent directory ${(0,f.basename)(e)}`);if(c.length>1024)throw new Error("Skill description exceeds 1024 characters");let m=T(s.license,"license"),p=T(s.compatibility,"compatibility");if(p&&p.length>500)throw new Error("Skill compatibility exceeds 500 characters");let y=Le(s.metadata,"metadata"),d=v(s.xeno),k=R(s["allowed-tools"]??s.allowedTools),w=G({allow:R(d?.["allowed-tools"]??d?.allowedTools??v(d?.tools)?.allow),deny:R(d?.["denied-tools"]??d?.deniedTools??v(d?.tools)?.deny)}),ie=Ie(d?.["external-actions"]??d?.externalActions),se=!(x(s["disable-model-invocation"])??!1)&&(x(d?.modelInvocable)??!0),le=x(s["user-invocable"])??x(d?.userInvocable)??!0,B=be(e,r,t,o),A=u.content.trim();if(!A)throw new Error("SKILL.md instructions cannot be empty");let ce=E(h({raw:a,resources:B.map(N=>({path:N.relativePath,sha256:N.sha256}))})),X=n.namespace?.trim();return{descriptor:{schemaVersion:2,key:X?`${X}:${l}`:l,name:l,description:c,source:n.source,precedence:n.precedence,directory:e,entrypoint:r,...X?{namespace:X}:{},...y.version?{version:y.version}:{},...m?{license:m}:{},...p?{compatibility:p}:{},metadata:y,modelInvocable:se,userInvocable:le,requestedPreapprovedTools:k,toolPolicy:w,externalActions:ie,contentHash:ce,instructionBytes:Buffer.byteLength(A,"utf8"),resources:B},instructions:A}}function be(e,n,t,o){let r=[],i=0,a=u=>{for(let s of(0,g.readdirSync)(u,{withFileTypes:!0}).sort((l,c)=>l.name.localeCompare(c.name))){let l=(0,f.join)(u,s.name);if(l===n)continue;let c=(0,g.lstatSync)(l);if(c.isSymbolicLink()){o.push({severity:"warning",code:"SKILL_SYMLINK_REJECTED",message:"Skill resource symlinks are not included",path:l});continue}if(c.isDirectory()){a(l);continue}if(!c.isFile())continue;if(r.length>=t.maxResourceFiles)throw new Error(`Skill resource count exceeds ${t.maxResourceFiles}`);if(i+=c.size,i>t.maxResourceBytes)throw new Error(`Skill resources exceed ${t.maxResourceBytes} bytes`);let m=(0,f.relative)(e,l).split(f.sep).join("/");r.push({relativePath:m,kind:ve(m),sizeBytes:c.size,sha256:E((0,g.readFileSync)(l))})}};return a(e),r.sort((u,s)=>u.relativePath.localeCompare(s.relativePath))}function ve(e){let n=e.split("/",1)[0]?.toLowerCase();return n==="scripts"?"script":n==="references"?"reference":n==="assets"?"asset":n==="templates"?"template":"other"}function Ee(e){return{key:e.key,source:e.source,precedence:e.precedence,contentHash:e.contentHash,modelInvocable:e.modelInvocable,userInvocable:e.userInvocable}}function J(e,n){return E(h({key:e.key,description:e.description,instructions:n,requestedPreapprovedTools:e.requestedPreapprovedTools,toolPolicy:e.toolPolicy,externalActions:e.externalActions}))}function G(e){let n=[...new Set(e?.allow?.map(o=>o.trim()).filter(Boolean)??[])].sort(),t=[...new Set(e?.deny?.map(o=>o.trim()).filter(Boolean)??[])].sort();return{...n.length>0?{allow:n}:{},...t.length>0?{deny:t}:{}}}function R(e){return typeof e=="string"?[...new Set(e.split(/\s+/u).map(n=>n.trim()).filter(Boolean))].sort():Array.isArray(e)?[...new Set(e.filter(n=>typeof n=="string").map(n=>n.trim()).filter(Boolean))].sort():[]}function Le(e,n){if(e===void 0)return{};let t=v(e);if(!t)throw new Error(`${n} must be a string-to-string mapping`);let o={};for(let[r,i]of Object.entries(t)){if(typeof i!="string")throw new Error(`${n}.${r} must be a string`);o[r]=i}return o}function H(e,n){let t=T(e,n);if(!t)throw new Error(`Skill ${n} is required`);return t}function T(e,n){if(e===void 0)return;if(typeof e!="string")throw new Error(`Skill ${n} must be a string`);let t=e.trim();if(!t)throw new Error(`Skill ${n} cannot be empty`);return t}function v(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function x(e){return typeof e=="boolean"?e:void 0}function Ie(e){return e==="deny"||e==="allow"||e==="ask"?e:"ask"}function b(e,n,t,o){if(e===void 0)return n;if(!Number.isInteger(e)||e<t||e>o)throw new Error(`Skill discovery limit must be an integer between ${t} and ${o}`);return e}function h(e){return Array.isArray(e)?`[${e.map(h).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).filter(([,n])=>n!==void 0).sort(([n],[t])=>n.localeCompare(t)).map(([n,t])=>`${JSON.stringify(n)}:${h(t)}`).join(",")}}`:JSON.stringify(e)??"null"}function E(e){return(0,q.createHash)("sha256").update(e).digest("hex")}function U(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function F(e){return e instanceof Error?e.message:String(e)}var ne=require("node:crypto");var Q=128*1024;function Ae(e){return{definition:{name:"Skill",description:"Load one available SKILL.md instruction body on demand. Use only a name from <available_skills>.",input_schema:{type:"object",properties:{name:{type:"string",description:"Exact skill key or unique skill name"},arguments:{type:"string",description:"Optional arguments supplied to the skill"}},required:["name"],additionalProperties:!1}},projectPolicyInput:n=>({observabilityInput:{name:typeof n.name=="string"?n.name:"",hasArguments:typeof n.arguments=="string"&&n.arguments.length>0},permissionInput:{name:typeof n.name=="string"?n.name:""},permissionPreview:`Load skill ${typeof n.name=="string"?n.name:""}`,approvalKey:`skill:${typeof n.name=="string"?n.name:"unknown"}`,riskLevel:"low"}),execute:async n=>{let t=typeof n.name=="string"?n.name.trim():"",o=typeof n.arguments=="string"?n.arguments.trim():"";if(!t)return ee("SKILL_INVALID_INPUT","Skill name is required");try{return{success:!0,output:(await te({...e,name:t,arguments:o,invocation:"model"})).output}}catch(r){return ee("SKILL_INVOCATION_DENIED",C(r))}}}}async function te(e){let n=e.getCatalog(),t=O(n,e.name);if(!t)throw new Error(`Skill not found or ambiguous: ${e.name}`);let o=e.arguments?.trim()??"",r={schemaVersion:2,recordedAt:(e.now?.()??new Date).toISOString(),skillKey:t.key,skillHash:t.contentHash,invocation:e.invocation,...o?{argumentsHash:Ce(o)}:{}};try{let i=await Pe(t,e.invocation,e);if(i==="deny")throw await L(e,{...r,type:"skill-denied",reason:"Invocation policy denied the skill"}),new Error(`Skill ${t.key} is denied by the active policy`);if(i==="ask"&&(!e.ask||!await e.ask(t)))throw await L(e,{...r,type:"skill-denied",reason:"User did not approve skill invocation"}),new Error(`Skill ${t.key} requires approval`);let a=await(e.loadSkill??_)(t);if(a.descriptor.contentHash!==t.contentHash)throw new Error(`Skill ${t.key} loader returned a mismatched content hash`);let u=re(e.invocationPolicy),s=oe(t,o,u);await e.onActivate?.(structuredClone(s));let l=Re(a,s,{arguments:o,projectDirectory:typeof e.projectDirectory=="function"?e.projectDirectory():e.projectDirectory});if(Buffer.byteLength(l,"utf8")>Q)throw new Error(`Skill ${t.key} exceeds the ${Q}-byte invocation limit; move details into references/`);return await L(e,{...r,type:"skill-invoked"}),{loaded:a,activation:s,output:l}}catch(i){throw/denied by the active policy|requires approval/u.test(C(i))||await L(e,{...r,type:"skill-load-failed",reason:C(i)}),i}}function De(e,n="",t){return oe(e,n,t)}function oe(e,n,t){let o=Z(t?.allow),r=Z(e.toolPolicy.allow),i=[o,r].filter(s=>s!==void 0),a=i.length<=1?i[0]:void 0,u=[...new Set([...e.toolPolicy.deny??[],...t?.deny??[]])].sort();return{descriptor:structuredClone(e),arguments:n,toolAllowLayers:i,...a?{effectiveAllowedTools:a}:{},effectiveDeniedTools:u,externalActions:Te(e.externalActions,t?.externalActions??"allow")}}function $e(e,n){return I(n,e.effectiveDeniedTools)?!1:e.toolAllowLayers.every(t=>I(n,t))}function Re(e,n,t){let o=e.descriptor,r=e.instructions,i=/\$ARGUMENTS(?:\[\d+\])?|\$\d+/u.test(r),a=Oe(t.arguments);r=r.replace(/\$ARGUMENTS\[(\d+)\]/gu,(s,l)=>a[Number.parseInt(l,10)]??"").replace(/\$(\d+)\b/gu,(s,l)=>a[Number.parseInt(l,10)]??"").replace(/\$ARGUMENTS\b/gu,t.arguments).replace(/\$\{(?:XENO|CLAUDE)_SKILL_DIR\}/gu,o.directory).replace(/\$\{(?:XENO|CLAUDE)_PROJECT_DIR\}/gu,t.projectDirectory??process.cwd()),t.arguments&&!i&&(r+=`
4
7
 
5
- ARGUMENTS: ${t.arguments}`);let m=o.resources.length>0?["","Bundled resources (load only when needed; paths are relative to the skill directory):",...o.resources.map(s=>`- ${s.relativePath} (${s.kind}, ${s.sizeBytes} bytes, sha256:${s.sha256})`)]:[];return[`<xeno_skill key="${Ce(o.key)}" hash="${o.contentHash}">`,`Source: ${o.source}`,`External actions: ${n.externalActions}`,...n.toolAllowLayers.map((s,l)=>`Tool allow layer ${l+1}: ${s.join(", ")||"none"}`),...n.effectiveDeniedTools.length>0?[`Denied tools: ${n.effectiveDeniedTools.join(", ")}`]:[],o.requestedPreapprovedTools.length>0?`Requested pre-approvals (not authority grants): ${o.requestedPreapprovedTools.join(", ")}`:"Requested pre-approvals: none","",r,...m,"</xeno_skill>"].join(`
6
- `)}async function Re(e,n,t){if(n==="model"&&!e.modelInvocable||n==="user"&&!e.userInvocable)return"deny";let o=re(t.invocationPolicy);return I(e.key,o?.deny??[])||o?.allow&&!I(e.key,o.allow)?"deny":t.authorize?t.authorize(e,n):"allow"}function re(e){return typeof e=="function"?e():e}function Pe(e,n){let t={deny:0,ask:1,allow:2};return t[e]<=t[n]?e:n}function Z(e){if(e)return[...new Set(e.map(n=>n.trim()).filter(Boolean))].sort()}function I(e,n){let t=e.toLowerCase();return n.some(o=>{let r=o.trim().toLowerCase();return r?new RegExp(`^${r.split("*").map(Te).join(".*")}$`,"u").test(t):!1})}function Te(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function _e(e){return(e.match(/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\S+/gu)??[]).map(t=>t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t)}async function v(e,n){await e.onAudit?.(n)}function ee(e,n){return{success:!1,output:n,error:n,errorCode:e}}function Oe(e){return(0,ne.createHash)("sha256").update(e).digest("hex")}function Ce(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function C(e){return e instanceof Error?e.message:String(e)}0&&(module.exports={XENO_SKILL_SCHEMA_VERSION,compileXenoSkillActivation,createXenoSkillTool,discoverXenoSkills,findXenoSkill,importLegacyXenoSkill,invokeXenoSkill,isToolAllowedByXenoSkillActivation,loadXenoSkill,renderXenoSkillCatalog});
8
+ ARGUMENTS: ${t.arguments}`);let u=o.resources.length>0?["","Bundled resources (load only when needed; paths are relative to the skill directory):",...o.resources.map(s=>`- ${s.relativePath} (${s.kind}, ${s.sizeBytes} bytes, sha256:${s.sha256})`)]:[];return[`<xeno_skill key="${Be(o.key)}" hash="${o.contentHash}">`,`Source: ${o.source}`,`External actions: ${n.externalActions}`,...n.toolAllowLayers.map((s,l)=>`Tool allow layer ${l+1}: ${s.join(", ")||"none"}`),...n.effectiveDeniedTools.length>0?[`Denied tools: ${n.effectiveDeniedTools.join(", ")}`]:[],o.requestedPreapprovedTools.length>0?`Requested pre-approvals (not authority grants): ${o.requestedPreapprovedTools.join(", ")}`:"Requested pre-approvals: none","",r,...u,"</xeno_skill>"].join(`
9
+ `)}async function Pe(e,n,t){if(n==="model"&&!e.modelInvocable||n==="user"&&!e.userInvocable)return"deny";let o=re(t.invocationPolicy);return I(e.key,o?.deny??[])||o?.allow&&!I(e.key,o.allow)?"deny":t.authorize?t.authorize(e,n):"allow"}function re(e){return typeof e=="function"?e():e}function Te(e,n){let t={deny:0,ask:1,allow:2};return t[e]<=t[n]?e:n}function Z(e){if(e)return[...new Set(e.map(n=>n.trim()).filter(Boolean))].sort()}function I(e,n){let t=e.toLowerCase();return n.some(o=>{let r=o.trim().toLowerCase();return r?new RegExp(`^${r.split("*").map(_e).join(".*")}$`,"u").test(t):!1})}function _e(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Oe(e){return(e.match(/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\S+/gu)??[]).map(t=>t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t)}async function L(e,n){await e.onAudit?.(n)}function ee(e,n){return{success:!1,output:n,error:n,errorCode:e}}function Ce(e){return(0,ne.createHash)("sha256").update(e).digest("hex")}function Be(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function C(e){return e instanceof Error?e.message:String(e)}0&&(module.exports={XENO_SKILL_SCHEMA_VERSION,compileXenoSkillActivation,createXenoSkillTool,discoverXenoSkills,findXenoSkill,importLegacyXenoSkill,invokeXenoSkill,isToolAllowedByXenoSkillActivation,loadXenoSkill,renderXenoSkillCatalog});
@@ -1,6 +1,9 @@
1
- var g=2;import{createHash as ye}from"node:crypto";import{lstatSync as T,readFileSync as _,readdirSync as z,realpathSync as M,statSync as H}from"node:fs";import{basename as U,dirname as Y,join as E,relative as ge,resolve as $,sep as ke}from"node:path";function A(e){let n=me(e);return{frontmatter:n.frontmatter,content:n.content.trim()}}function me(e){let n=e.replace(/^\uFEFF/,"");if(!n.startsWith("---"))return{frontmatter:{},content:e};let t=n.search(/\r?\n/);if(t<0||n.slice(0,t).trim()!=="---")return{frontmatter:{},content:e};let o=n.slice(t+(n[t]==="\r"?2:1)),r=o.match(/(?:^|\r?\n)---[ \t]*(?:\r?\n|$)/);if(!r||r.index===void 0)throw new Error("YAML frontmatter is not closed.");let i=o.slice(0,r.index),c=r[0],d=r.index+c.length;return{frontmatter:j(i),content:o.slice(d)}}function j(e){let n={},t=e.split(/\r?\n/);for(let o=0;o<t.length;o+=1){let r=t[o];if(!r.trim()||r.trimStart().startsWith("#"))continue;if(/^\s/.test(r))throw new Error(`Unexpected indentation at line ${o+1}.`);let i=pe(r,o+1);if(i.key==="<<")throw new Error("YAML merge keys are not supported.");if(i.value!==""){n[i.key]=K(i.value,o+1);continue}let c=fe(t,o+1);n[i.key]=c.value,o=c.nextIndex-1}return n}function fe(e,n){let t=[],o=n;for(;o<e.length;o+=1){let i=e[o];if(!i.trim()){t.push(i);continue}if(!/^\s/.test(i))break;t.push(i.replace(/^ {2}/,""))}let r=t.filter(i=>i.trim()&&!i.trimStart().startsWith("#"));return r.length===0?{value:{},nextIndex:o}:r.every(i=>i.trimStart().startsWith("- "))?{value:r.map((i,c)=>K(i.trimStart().slice(2),n+c+1)),nextIndex:o}:{value:j(t.join(`
2
- `)),nextIndex:o}}function pe(e,n){let t=e.indexOf(":");if(t<=0)throw new Error(`Invalid YAML line ${n}.`);let o=e.slice(0,t).trim(),r=e.slice(t+1).trim();if(!o)throw new Error(`Invalid YAML key at line ${n}.`);return{key:o,value:r}}function K(e,n){if(e==="")return"";if(e==="[]")return[];if(e==="{}")return{};if(e==="true")return!0;if(e==="false")return!1;if(e==="null"||e==="~")return null;if(/^-?\d+(?:\.\d+)?$/.test(e))return Number(e);if(e.startsWith('"'))return N(e,n);if(e.startsWith("'")){if(!e.endsWith("'"))throw new Error(`Unclosed quoted scalar at line ${n}.`);return e.slice(1,-1).replace(/''/g,"'")}if(e.startsWith("[")||e.startsWith("{"))return N(e,n);if(e.includes("[")||e.includes("]")||e.includes("{")||e.includes("}"))throw new Error(`Unsupported YAML scalar at line ${n}.`);return e}function N(e,n){try{return JSON.parse(e)}catch{throw new Error(`Invalid YAML scalar at line ${n}.`)}}var R=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,Se=2e3,W=2*1024*1024,J=2e3,G=64*1024*1024;function Ke(e){let n={maxSkills:X(e.maxSkills,Se,1,2e4),maxSkillBytes:X(e.maxSkillBytes,W,1024,16777216),maxResourceFiles:X(e.maxResourceFiles,J,0,2e4),maxResourceBytes:X(e.maxResourceBytes,G,0,536870912)},t=[],o=[],r=new Set;for(let s of e.roots){if(o.length>=n.maxSkills)break;let l=$(s.path),a;try{if(!H(l,{throwIfNoEntry:!1})?.isDirectory())continue;a=z(l,{withFileTypes:!0}).sort((m,f)=>m.name.localeCompare(f.name))}catch(m){t.push({severity:"warning",code:"SKILL_ROOT_UNREADABLE",message:`Unable to inspect skill root: ${V(m)}`,path:l});continue}for(let m of a){if(o.length>=n.maxSkills)break;let f=E(l,m.name);try{let p=T(f);if(p.isSymbolicLink()&&!s.followSymlinks){t.push({severity:"warning",code:"SKILL_SYMLINK_REJECTED",message:"Skill directory symlinks require an explicitly trusted discovery root",path:f});continue}let u=p.isSymbolicLink()?M(f):f;if(!H(u).isDirectory())continue;let y=M(u);if(r.has(y))continue;let S=ee(y,s,n,t);if(!S)continue;r.add(y),o.push(S.descriptor)}catch(p){t.push({severity:"error",code:"SKILL_INVALID",message:V(p),path:f})}}}let i=new Map;for(let s of o){let l=i.get(s.key)??[];l.push(s),i.set(s.key,l)}let c=[],d=[];for(let[s,l]of[...i].sort(([a],[m])=>a.localeCompare(m))){let a=l.sort((u,y)=>y.precedence-u.precedence||u.entrypoint.localeCompare(y.entrypoint)),m=a[0]?.precedence,f=a.filter(u=>u.precedence===m);if(f.length>1&&new Set(f.map(u=>u.contentHash)).size>1){t.push({severity:"error",code:"SKILL_AMBIGUOUS",key:s,message:`Skill ${s} has conflicting definitions at precedence ${m}; qualify or remove one definition`});continue}let p=a[0];c.push(p),a.length>1&&d.push({key:s,selected:p,shadowed:a.slice(1)})}return c.sort((s,l)=>s.key.localeCompare(l.key)),{schemaVersion:2,generatedAt:(e.now?.()??new Date).toISOString(),catalogHash:L(k(c.map(Xe))),skills:c,shadowed:d,diagnostics:t}}function Q(e){if(e.source==="legacy"){let r=A(_(e.entrypoint,"utf8")).content.trim();if(ne(e,r)!==e.contentHash)throw new Error(`Skill ${e.key} changed after discovery; refresh the catalog before invoking it`);return{descriptor:structuredClone(e),instructions:r}}let n=[],t=ee(e.directory,{path:Y(e.directory),source:e.source,precedence:e.precedence,...e.namespace?{namespace:e.namespace}:{},followSymlinks:!1},{maxSkills:1,maxSkillBytes:Math.max(W,e.instructionBytes),maxResourceFiles:Math.max(J,e.resources.length),maxResourceBytes:Math.max(G,e.resources.reduce((o,r)=>o+r.sizeBytes,0))},n);if(!t||n.some(o=>o.severity==="error"))throw new Error(`Unable to load skill ${e.key}: ${n.map(o=>o.message).join("; ")||"invalid skill"}`);if(t.descriptor.contentHash!==e.contentHash)throw new Error(`Skill ${e.key} changed after discovery; refresh the catalog before invoking it`);return{descriptor:structuredClone(e),instructions:t.instructions}}function Me(e){let n=e.id.trim().toLowerCase();if(!R.test(n)||n.length>64)throw new Error(`Legacy skill name is invalid: ${e.id}`);let t=e.content.trim();if(!t)throw new Error("Legacy skill content cannot be empty");let o=e.path?Y($(e.path)):process.cwd(),r={schemaVersion:2,key:e.namespace?`${e.namespace}:${n}`:n,name:n,description:e.description?.trim()||e.name?.trim()||`Imported legacy XENO skill ${n}`,source:"legacy",precedence:e.precedence??0,directory:o,entrypoint:e.path?$(e.path):E(o,`${n}.md`),...e.namespace?{namespace:e.namespace}:{},...e.version?{version:e.version}:{},metadata:{"xeno.imported-from":e.source??"legacy"},modelInvocable:e.modelInvocable??!0,userInvocable:e.userInvocable??!0,requestedPreapprovedTools:[...new Set(e.allowedTools??[])].sort(),toolPolicy:te(e.toolPolicy),externalActions:e.externalActions??"ask",contentHash:"",instructionBytes:Buffer.byteLength(t,"utf8"),resources:[]};return r.contentHash=ne(r,t),{descriptor:r,instructions:t}}function He(e){let n=e.skills.filter(t=>t.modelInvocable);return n.length===0?"":["<available_skills>",...n.flatMap(t=>[" <skill>",` <name>${q(t.key)}</name>`,` <description>${q(t.description)}</description>`,` <hash>${t.contentHash}</hash>`," </skill>"]),"</available_skills>","Use the Skill tool to load full instructions only when a listed skill is relevant."].join(`
3
- `)}function Z(e,n){let t=n.trim().toLowerCase();if(!t)return;let o=e.skills.find(i=>i.key.toLowerCase()===t);if(o)return o;let r=e.skills.filter(i=>i.name.toLowerCase()===t);return r.length===1?r[0]:void 0}function ee(e,n,t,o){let r=E(e,"SKILL.md"),i=T(r,{throwIfNoEntry:!1});if(!i)return;if(i.isSymbolicLink()||!i.isFile())throw new Error("SKILL.md must be a regular, non-symlink file");if(i.size>t.maxSkillBytes)throw new Error(`SKILL.md exceeds ${t.maxSkillBytes} bytes`);let c=_(r,"utf8"),d=A(c),s=d.frontmatter,l=F(s.name,"name"),a=F(s.description,"description");if(!R.test(l)||l.length>64)throw new Error(`Skill name does not match ${R.source} or exceeds 64 characters`);if(l!==U(e))throw new Error(`Skill name ${l} must match its parent directory ${U(e)}`);if(a.length>1024)throw new Error("Skill description exceeds 1024 characters");let m=P(s.license,"license"),f=P(s.compatibility,"compatibility");if(f&&f.length>500)throw new Error("Skill compatibility exceeds 500 characters");let p=xe(s.metadata,"metadata"),u=x(s.xeno),y=D(s["allowed-tools"]??s.allowedTools),S=te({allow:D(u?.["allowed-tools"]??u?.allowedTools??x(u?.tools)?.allow),deny:D(u?.["denied-tools"]??u?.deniedTools??x(u?.tools)?.deny)}),ce=Ee(u?.["external-actions"]??u?.externalActions),ae=!(w(s["disable-model-invocation"])??!1)&&(w(u?.modelInvocable)??!0),ue=w(s["user-invocable"])??w(u?.userInvocable)??!0,C=he(e,r,t,o),I=d.content.trim();if(!I)throw new Error("SKILL.md instructions cannot be empty");let de=L(k({raw:c,resources:C.map(B=>({path:B.relativePath,sha256:B.sha256}))})),h=n.namespace?.trim();return{descriptor:{schemaVersion:2,key:h?`${h}:${l}`:l,name:l,description:a,source:n.source,precedence:n.precedence,directory:e,entrypoint:r,...h?{namespace:h}:{},...p.version?{version:p.version}:{},...m?{license:m}:{},...f?{compatibility:f}:{},metadata:p,modelInvocable:ae,userInvocable:ue,requestedPreapprovedTools:y,toolPolicy:S,externalActions:ce,contentHash:de,instructionBytes:Buffer.byteLength(I,"utf8"),resources:C},instructions:I}}function he(e,n,t,o){let r=[],i=0,c=d=>{for(let s of z(d,{withFileTypes:!0}).sort((l,a)=>l.name.localeCompare(a.name))){let l=E(d,s.name);if(l===n)continue;let a=T(l);if(a.isSymbolicLink()){o.push({severity:"warning",code:"SKILL_SYMLINK_REJECTED",message:"Skill resource symlinks are not included",path:l});continue}if(a.isDirectory()){c(l);continue}if(!a.isFile())continue;if(r.length>=t.maxResourceFiles)throw new Error(`Skill resource count exceeds ${t.maxResourceFiles}`);if(i+=a.size,i>t.maxResourceBytes)throw new Error(`Skill resources exceed ${t.maxResourceBytes} bytes`);let m=ge(e,l).split(ke).join("/");r.push({relativePath:m,kind:we(m),sizeBytes:a.size,sha256:L(_(l))})}};return c(e),r.sort((d,s)=>d.relativePath.localeCompare(s.relativePath))}function we(e){let n=e.split("/",1)[0]?.toLowerCase();return n==="scripts"?"script":n==="references"?"reference":n==="assets"?"asset":n==="templates"?"template":"other"}function Xe(e){return{key:e.key,source:e.source,precedence:e.precedence,contentHash:e.contentHash,modelInvocable:e.modelInvocable,userInvocable:e.userInvocable}}function ne(e,n){return L(k({key:e.key,description:e.description,instructions:n,requestedPreapprovedTools:e.requestedPreapprovedTools,toolPolicy:e.toolPolicy,externalActions:e.externalActions}))}function te(e){let n=[...new Set(e?.allow?.map(o=>o.trim()).filter(Boolean)??[])].sort(),t=[...new Set(e?.deny?.map(o=>o.trim()).filter(Boolean)??[])].sort();return{...n.length>0?{allow:n}:{},...t.length>0?{deny:t}:{}}}function D(e){return typeof e=="string"?[...new Set(e.split(/\s+/u).map(n=>n.trim()).filter(Boolean))].sort():Array.isArray(e)?[...new Set(e.filter(n=>typeof n=="string").map(n=>n.trim()).filter(Boolean))].sort():[]}function xe(e,n){if(e===void 0)return{};let t=x(e);if(!t)throw new Error(`${n} must be a string-to-string mapping`);let o={};for(let[r,i]of Object.entries(t)){if(typeof i!="string")throw new Error(`${n}.${r} must be a string`);o[r]=i}return o}function F(e,n){let t=P(e,n);if(!t)throw new Error(`Skill ${n} is required`);return t}function P(e,n){if(e===void 0)return;if(typeof e!="string")throw new Error(`Skill ${n} must be a string`);let t=e.trim();if(!t)throw new Error(`Skill ${n} cannot be empty`);return t}function x(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function w(e){return typeof e=="boolean"?e:void 0}function Ee(e){return e==="deny"||e==="allow"||e==="ask"?e:"ask"}function X(e,n,t,o){if(e===void 0)return n;if(!Number.isInteger(e)||e<t||e>o)throw new Error(`Skill discovery limit must be an integer between ${t} and ${o}`);return e}function k(e){return Array.isArray(e)?`[${e.map(k).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).filter(([,n])=>n!==void 0).sort(([n],[t])=>n.localeCompare(t)).map(([n,t])=>`${JSON.stringify(n)}:${k(t)}`).join(",")}}`:JSON.stringify(e)??"null"}function L(e){return ye("sha256").update(e).digest("hex")}function q(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function V(e){return e instanceof Error?e.message:String(e)}import{createHash as Le}from"node:crypto";var oe=128*1024;function ze(e){return{definition:{name:"Skill",description:"Load one available SKILL.md instruction body on demand. Use only a name from <available_skills>.",input_schema:{type:"object",properties:{name:{type:"string",description:"Exact skill key or unique skill name"},arguments:{type:"string",description:"Optional arguments supplied to the skill"}},required:["name"],additionalProperties:!1}},projectPolicyInput:n=>({observabilityInput:{name:typeof n.name=="string"?n.name:"",hasArguments:typeof n.arguments=="string"&&n.arguments.length>0},permissionInput:{name:typeof n.name=="string"?n.name:""},permissionPreview:`Load skill ${typeof n.name=="string"?n.name:""}`,approvalKey:`skill:${typeof n.name=="string"?n.name:"unknown"}`,riskLevel:"low"}),execute:async n=>{let t=typeof n.name=="string"?n.name.trim():"",o=typeof n.arguments=="string"?n.arguments.trim():"";if(!t)return ie("SKILL_INVALID_INPUT","Skill name is required");try{return{success:!0,output:(await be({...e,name:t,arguments:o,invocation:"model"})).output}}catch(r){return ie("SKILL_INVOCATION_DENIED",O(r))}}}}async function be(e){let n=e.getCatalog(),t=Z(n,e.name);if(!t)throw new Error(`Skill not found or ambiguous: ${e.name}`);let o=e.arguments?.trim()??"",r={schemaVersion:2,recordedAt:(e.now?.()??new Date).toISOString(),skillKey:t.key,skillHash:t.contentHash,invocation:e.invocation,...o?{argumentsHash:Re(o)}:{}};try{let i=await Ie(t,e.invocation,e);if(i==="deny")throw await b(e,{...r,type:"skill-denied",reason:"Invocation policy denied the skill"}),new Error(`Skill ${t.key} is denied by the active policy`);if(i==="ask"&&(!e.ask||!await e.ask(t)))throw await b(e,{...r,type:"skill-denied",reason:"User did not approve skill invocation"}),new Error(`Skill ${t.key} requires approval`);let c=await(e.loadSkill??Q)(t);if(c.descriptor.contentHash!==t.contentHash)throw new Error(`Skill ${t.key} loader returned a mismatched content hash`);let d=le(e.invocationPolicy),s=se(t,o,d);await e.onActivate?.(structuredClone(s));let l=ve(c,s,{arguments:o,projectDirectory:typeof e.projectDirectory=="function"?e.projectDirectory():e.projectDirectory});if(Buffer.byteLength(l,"utf8")>oe)throw new Error(`Skill ${t.key} exceeds the ${oe}-byte invocation limit; move details into references/`);return await b(e,{...r,type:"skill-invoked"}),{loaded:c,activation:s,output:l}}catch(i){throw/denied by the active policy|requires approval/u.test(O(i))||await b(e,{...r,type:"skill-load-failed",reason:O(i)}),i}}function Ye(e,n="",t){return se(e,n,t)}function se(e,n,t){let o=re(t?.allow),r=re(e.toolPolicy.allow),i=[o,r].filter(s=>s!==void 0),c=i.length<=1?i[0]:void 0,d=[...new Set([...e.toolPolicy.deny??[],...t?.deny??[]])].sort();return{descriptor:structuredClone(e),arguments:n,toolAllowLayers:i,...c?{effectiveAllowedTools:c}:{},effectiveDeniedTools:d,externalActions:Ae(e.externalActions,t?.externalActions??"allow")}}function We(e,n){return v(n,e.effectiveDeniedTools)?!1:e.toolAllowLayers.every(t=>v(n,t))}function ve(e,n,t){let o=e.descriptor,r=e.instructions,i=/\$ARGUMENTS(?:\[\d+\])?|\$\d+/u.test(r),c=$e(t.arguments);r=r.replace(/\$ARGUMENTS\[(\d+)\]/gu,(s,l)=>c[Number.parseInt(l,10)]??"").replace(/\$(\d+)\b/gu,(s,l)=>c[Number.parseInt(l,10)]??"").replace(/\$ARGUMENTS\b/gu,t.arguments).replace(/\$\{(?:XENO|CLAUDE)_SKILL_DIR\}/gu,o.directory).replace(/\$\{(?:XENO|CLAUDE)_PROJECT_DIR\}/gu,t.projectDirectory??process.cwd()),t.arguments&&!i&&(r+=`
1
+ var y=2;import{createHash as ye}from"node:crypto";import{lstatSync as T,readFileSync as _,readdirSync as z,realpathSync as M,statSync as H}from"node:fs";import{basename as U,dirname as Y,join as b,relative as ke,resolve as $,sep as Se}from"node:path";function A(e){let n=me(e);return{frontmatter:n.frontmatter,content:n.content.trim()}}function me(e){let n=e.replace(/^\uFEFF/,"");if(!n.startsWith("---"))return{frontmatter:{},content:e};let t=n.search(/\r?\n/);if(t<0||n.slice(0,t).trim()!=="---")return{frontmatter:{},content:e};let o=n.slice(t+(n[t]==="\r"?2:1)),r=o.match(/(?:^|\r?\n)---[ \t]*(?:\r?\n|$)/);if(!r||r.index===void 0)throw new Error("YAML frontmatter is not closed.");let i=o.slice(0,r.index),a=r[0],u=r.index+a.length;return{frontmatter:j(i),content:o.slice(u)}}function j(e){let n={},t=e.split(/\r?\n/);for(let o=0;o<t.length;o+=1){let r=t[o];if(!r.trim()||r.trimStart().startsWith("#"))continue;if(/^\s/.test(r))throw new Error(`Unexpected indentation at line ${o+1}.`);let i=ge(r,o+1);if(i.key==="<<")throw new Error("YAML merge keys are not supported.");let a=i.value.match(/^([|>])([+-]?)$/);if(a){let s=fe(t,o+1,a[1],a[2]??"");n[i.key]=s.value,o=s.nextIndex-1;continue}if(i.value!==""){n[i.key]=K(i.value,o+1);continue}let u=pe(t,o+1);n[i.key]=u.value,o=u.nextIndex-1}return n}function fe(e,n,t,o){let r=[],i=n;for(;i<e.length;i+=1){let c=e[i];if(c.trim()===""){r.push("");continue}if(!/^\s/.test(c))break;r.push(c)}let a=r.filter(c=>c.trim()!=="").map(c=>c.match(/^ */)[0].length),u=a.length>0?Math.min(...a):0,s=r.map(c=>c.trim()===""?"":c.slice(u));for(;s.length>0&&s[s.length-1]==="";)s.pop();let l;return t==="|"?l=s.join(`
2
+ `):(l="",s.forEach((c,m)=>{if(m===0){l=c;return}let f=s[m-1];c===""?l+=`
3
+ `:f===""?l+=c:l+=" "+c})),{value:o==="-"?l:l+`
4
+ `,nextIndex:i}}function pe(e,n){let t=[],o=n;for(;o<e.length;o+=1){let i=e[o];if(!i.trim()){t.push(i);continue}if(!/^\s/.test(i))break;t.push(i.replace(/^ {2}/,""))}let r=t.filter(i=>i.trim()&&!i.trimStart().startsWith("#"));return r.length===0?{value:{},nextIndex:o}:r.every(i=>i.trimStart().startsWith("- "))?{value:r.map((i,a)=>K(i.trimStart().slice(2),n+a+1)),nextIndex:o}:{value:j(t.join(`
5
+ `)),nextIndex:o}}function ge(e,n){let t=e.indexOf(":");if(t<=0)throw new Error(`Invalid YAML line ${n}.`);let o=e.slice(0,t).trim(),r=e.slice(t+1).trim();if(!o)throw new Error(`Invalid YAML key at line ${n}.`);return{key:o,value:r}}function K(e,n){if(e==="")return"";if(e==="[]")return[];if(e==="{}")return{};if(e==="true")return!0;if(e==="false")return!1;if(e==="null"||e==="~")return null;if(/^-?\d+(?:\.\d+)?$/.test(e))return Number(e);if(e.startsWith('"'))return N(e,n);if(e.startsWith("'")){if(!e.endsWith("'"))throw new Error(`Unclosed quoted scalar at line ${n}.`);return e.slice(1,-1).replace(/''/g,"'")}if(e.startsWith("[")||e.startsWith("{"))return N(e,n);if(e.includes("[")||e.includes("]")||e.includes("{")||e.includes("}"))throw new Error(`Unsupported YAML scalar at line ${n}.`);return e}function N(e,n){try{return JSON.parse(e)}catch{throw new Error(`Invalid YAML scalar at line ${n}.`)}}var R=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,he=2e3,W=2*1024*1024,J=2e3,G=64*1024*1024;function Me(e){let n={maxSkills:X(e.maxSkills,he,1,2e4),maxSkillBytes:X(e.maxSkillBytes,W,1024,16777216),maxResourceFiles:X(e.maxResourceFiles,J,0,2e4),maxResourceBytes:X(e.maxResourceBytes,G,0,536870912)},t=[],o=[],r=new Set;for(let s of e.roots){if(o.length>=n.maxSkills)break;let l=$(s.path),c;try{if(!H(l,{throwIfNoEntry:!1})?.isDirectory())continue;c=z(l,{withFileTypes:!0}).sort((m,f)=>m.name.localeCompare(f.name))}catch(m){t.push({severity:"warning",code:"SKILL_ROOT_UNREADABLE",message:`Unable to inspect skill root: ${V(m)}`,path:l});continue}for(let m of c){if(o.length>=n.maxSkills)break;let f=b(l,m.name);try{let p=T(f);if(p.isSymbolicLink()&&!s.followSymlinks){t.push({severity:"warning",code:"SKILL_SYMLINK_REJECTED",message:"Skill directory symlinks require an explicitly trusted discovery root",path:f});continue}let d=p.isSymbolicLink()?M(f):f;if(!H(d).isDirectory())continue;let g=M(d);if(r.has(g))continue;let S=ee(g,s,n,t);if(!S)continue;r.add(g),o.push(S.descriptor)}catch(p){t.push({severity:"error",code:"SKILL_INVALID",message:V(p),path:f})}}}let i=new Map;for(let s of o){let l=i.get(s.key)??[];l.push(s),i.set(s.key,l)}let a=[],u=[];for(let[s,l]of[...i].sort(([c],[m])=>c.localeCompare(m))){let c=l.sort((d,g)=>g.precedence-d.precedence||d.entrypoint.localeCompare(g.entrypoint)),m=c[0]?.precedence,f=c.filter(d=>d.precedence===m);if(f.length>1&&new Set(f.map(d=>d.contentHash)).size>1){t.push({severity:"error",code:"SKILL_AMBIGUOUS",key:s,message:`Skill ${s} has conflicting definitions at precedence ${m}; qualify or remove one definition`});continue}let p=c[0];a.push(p),c.length>1&&u.push({key:s,selected:p,shadowed:c.slice(1)})}return a.sort((s,l)=>s.key.localeCompare(l.key)),{schemaVersion:2,generatedAt:(e.now?.()??new Date).toISOString(),catalogHash:v(k(a.map(xe))),skills:a,shadowed:u,diagnostics:t}}function Q(e){if(e.source==="legacy"){let r=A(_(e.entrypoint,"utf8")).content.trim();if(ne(e,r)!==e.contentHash)throw new Error(`Skill ${e.key} changed after discovery; refresh the catalog before invoking it`);return{descriptor:structuredClone(e),instructions:r}}let n=[],t=ee(e.directory,{path:Y(e.directory),source:e.source,precedence:e.precedence,...e.namespace?{namespace:e.namespace}:{},followSymlinks:!1},{maxSkills:1,maxSkillBytes:Math.max(W,e.instructionBytes),maxResourceFiles:Math.max(J,e.resources.length),maxResourceBytes:Math.max(G,e.resources.reduce((o,r)=>o+r.sizeBytes,0))},n);if(!t||n.some(o=>o.severity==="error"))throw new Error(`Unable to load skill ${e.key}: ${n.map(o=>o.message).join("; ")||"invalid skill"}`);if(t.descriptor.contentHash!==e.contentHash)throw new Error(`Skill ${e.key} changed after discovery; refresh the catalog before invoking it`);return{descriptor:structuredClone(e),instructions:t.instructions}}function He(e){let n=e.id.trim().toLowerCase();if(!R.test(n)||n.length>64)throw new Error(`Legacy skill name is invalid: ${e.id}`);let t=e.content.trim();if(!t)throw new Error("Legacy skill content cannot be empty");let o=e.path?Y($(e.path)):process.cwd(),r={schemaVersion:2,key:e.namespace?`${e.namespace}:${n}`:n,name:n,description:e.description?.trim()||e.name?.trim()||`Imported legacy XENO skill ${n}`,source:"legacy",precedence:e.precedence??0,directory:o,entrypoint:e.path?$(e.path):b(o,`${n}.md`),...e.namespace?{namespace:e.namespace}:{},...e.version?{version:e.version}:{},metadata:{"xeno.imported-from":e.source??"legacy"},modelInvocable:e.modelInvocable??!0,userInvocable:e.userInvocable??!0,requestedPreapprovedTools:[...new Set(e.allowedTools??[])].sort(),toolPolicy:te(e.toolPolicy),externalActions:e.externalActions??"ask",contentHash:"",instructionBytes:Buffer.byteLength(t,"utf8"),resources:[]};return r.contentHash=ne(r,t),{descriptor:r,instructions:t}}function Ue(e){let n=e.skills.filter(t=>t.modelInvocable);return n.length===0?"":["<available_skills>",...n.flatMap(t=>[" <skill>",` <name>${q(t.key)}</name>`,` <description>${q(t.description)}</description>`,` <hash>${t.contentHash}</hash>`," </skill>"]),"</available_skills>","Use the Skill tool to load full instructions only when a listed skill is relevant."].join(`
6
+ `)}function Z(e,n){let t=n.trim().toLowerCase();if(!t)return;let o=e.skills.find(i=>i.key.toLowerCase()===t);if(o)return o;let r=e.skills.filter(i=>i.name.toLowerCase()===t);return r.length===1?r[0]:void 0}function ee(e,n,t,o){let r=b(e,"SKILL.md"),i=T(r,{throwIfNoEntry:!1});if(!i)return;if(i.isSymbolicLink()||!i.isFile())throw new Error("SKILL.md must be a regular, non-symlink file");if(i.size>t.maxSkillBytes)throw new Error(`SKILL.md exceeds ${t.maxSkillBytes} bytes`);let a=_(r,"utf8"),u=A(a),s=u.frontmatter,l=F(s.name,"name"),c=F(s.description,"description");if(!R.test(l)||l.length>64)throw new Error(`Skill name does not match ${R.source} or exceeds 64 characters`);if(l!==U(e))throw new Error(`Skill name ${l} must match its parent directory ${U(e)}`);if(c.length>1024)throw new Error("Skill description exceeds 1024 characters");let m=P(s.license,"license"),f=P(s.compatibility,"compatibility");if(f&&f.length>500)throw new Error("Skill compatibility exceeds 500 characters");let p=be(s.metadata,"metadata"),d=x(s.xeno),g=D(s["allowed-tools"]??s.allowedTools),S=te({allow:D(d?.["allowed-tools"]??d?.allowedTools??x(d?.tools)?.allow),deny:D(d?.["denied-tools"]??d?.deniedTools??x(d?.tools)?.deny)}),ce=ve(d?.["external-actions"]??d?.externalActions),ae=!(w(s["disable-model-invocation"])??!1)&&(w(d?.modelInvocable)??!0),ue=w(s["user-invocable"])??w(d?.userInvocable)??!0,C=we(e,r,t,o),I=u.content.trim();if(!I)throw new Error("SKILL.md instructions cannot be empty");let de=v(k({raw:a,resources:C.map(B=>({path:B.relativePath,sha256:B.sha256}))})),h=n.namespace?.trim();return{descriptor:{schemaVersion:2,key:h?`${h}:${l}`:l,name:l,description:c,source:n.source,precedence:n.precedence,directory:e,entrypoint:r,...h?{namespace:h}:{},...p.version?{version:p.version}:{},...m?{license:m}:{},...f?{compatibility:f}:{},metadata:p,modelInvocable:ae,userInvocable:ue,requestedPreapprovedTools:g,toolPolicy:S,externalActions:ce,contentHash:de,instructionBytes:Buffer.byteLength(I,"utf8"),resources:C},instructions:I}}function we(e,n,t,o){let r=[],i=0,a=u=>{for(let s of z(u,{withFileTypes:!0}).sort((l,c)=>l.name.localeCompare(c.name))){let l=b(u,s.name);if(l===n)continue;let c=T(l);if(c.isSymbolicLink()){o.push({severity:"warning",code:"SKILL_SYMLINK_REJECTED",message:"Skill resource symlinks are not included",path:l});continue}if(c.isDirectory()){a(l);continue}if(!c.isFile())continue;if(r.length>=t.maxResourceFiles)throw new Error(`Skill resource count exceeds ${t.maxResourceFiles}`);if(i+=c.size,i>t.maxResourceBytes)throw new Error(`Skill resources exceed ${t.maxResourceBytes} bytes`);let m=ke(e,l).split(Se).join("/");r.push({relativePath:m,kind:Xe(m),sizeBytes:c.size,sha256:v(_(l))})}};return a(e),r.sort((u,s)=>u.relativePath.localeCompare(s.relativePath))}function Xe(e){let n=e.split("/",1)[0]?.toLowerCase();return n==="scripts"?"script":n==="references"?"reference":n==="assets"?"asset":n==="templates"?"template":"other"}function xe(e){return{key:e.key,source:e.source,precedence:e.precedence,contentHash:e.contentHash,modelInvocable:e.modelInvocable,userInvocable:e.userInvocable}}function ne(e,n){return v(k({key:e.key,description:e.description,instructions:n,requestedPreapprovedTools:e.requestedPreapprovedTools,toolPolicy:e.toolPolicy,externalActions:e.externalActions}))}function te(e){let n=[...new Set(e?.allow?.map(o=>o.trim()).filter(Boolean)??[])].sort(),t=[...new Set(e?.deny?.map(o=>o.trim()).filter(Boolean)??[])].sort();return{...n.length>0?{allow:n}:{},...t.length>0?{deny:t}:{}}}function D(e){return typeof e=="string"?[...new Set(e.split(/\s+/u).map(n=>n.trim()).filter(Boolean))].sort():Array.isArray(e)?[...new Set(e.filter(n=>typeof n=="string").map(n=>n.trim()).filter(Boolean))].sort():[]}function be(e,n){if(e===void 0)return{};let t=x(e);if(!t)throw new Error(`${n} must be a string-to-string mapping`);let o={};for(let[r,i]of Object.entries(t)){if(typeof i!="string")throw new Error(`${n}.${r} must be a string`);o[r]=i}return o}function F(e,n){let t=P(e,n);if(!t)throw new Error(`Skill ${n} is required`);return t}function P(e,n){if(e===void 0)return;if(typeof e!="string")throw new Error(`Skill ${n} must be a string`);let t=e.trim();if(!t)throw new Error(`Skill ${n} cannot be empty`);return t}function x(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function w(e){return typeof e=="boolean"?e:void 0}function ve(e){return e==="deny"||e==="allow"||e==="ask"?e:"ask"}function X(e,n,t,o){if(e===void 0)return n;if(!Number.isInteger(e)||e<t||e>o)throw new Error(`Skill discovery limit must be an integer between ${t} and ${o}`);return e}function k(e){return Array.isArray(e)?`[${e.map(k).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).filter(([,n])=>n!==void 0).sort(([n],[t])=>n.localeCompare(t)).map(([n,t])=>`${JSON.stringify(n)}:${k(t)}`).join(",")}}`:JSON.stringify(e)??"null"}function v(e){return ye("sha256").update(e).digest("hex")}function q(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function V(e){return e instanceof Error?e.message:String(e)}import{createHash as Ee}from"node:crypto";var oe=128*1024;function Ye(e){return{definition:{name:"Skill",description:"Load one available SKILL.md instruction body on demand. Use only a name from <available_skills>.",input_schema:{type:"object",properties:{name:{type:"string",description:"Exact skill key or unique skill name"},arguments:{type:"string",description:"Optional arguments supplied to the skill"}},required:["name"],additionalProperties:!1}},projectPolicyInput:n=>({observabilityInput:{name:typeof n.name=="string"?n.name:"",hasArguments:typeof n.arguments=="string"&&n.arguments.length>0},permissionInput:{name:typeof n.name=="string"?n.name:""},permissionPreview:`Load skill ${typeof n.name=="string"?n.name:""}`,approvalKey:`skill:${typeof n.name=="string"?n.name:"unknown"}`,riskLevel:"low"}),execute:async n=>{let t=typeof n.name=="string"?n.name.trim():"",o=typeof n.arguments=="string"?n.arguments.trim():"";if(!t)return ie("SKILL_INVALID_INPUT","Skill name is required");try{return{success:!0,output:(await Le({...e,name:t,arguments:o,invocation:"model"})).output}}catch(r){return ie("SKILL_INVOCATION_DENIED",O(r))}}}}async function Le(e){let n=e.getCatalog(),t=Z(n,e.name);if(!t)throw new Error(`Skill not found or ambiguous: ${e.name}`);let o=e.arguments?.trim()??"",r={schemaVersion:2,recordedAt:(e.now?.()??new Date).toISOString(),skillKey:t.key,skillHash:t.contentHash,invocation:e.invocation,...o?{argumentsHash:Pe(o)}:{}};try{let i=await Ae(t,e.invocation,e);if(i==="deny")throw await E(e,{...r,type:"skill-denied",reason:"Invocation policy denied the skill"}),new Error(`Skill ${t.key} is denied by the active policy`);if(i==="ask"&&(!e.ask||!await e.ask(t)))throw await E(e,{...r,type:"skill-denied",reason:"User did not approve skill invocation"}),new Error(`Skill ${t.key} requires approval`);let a=await(e.loadSkill??Q)(t);if(a.descriptor.contentHash!==t.contentHash)throw new Error(`Skill ${t.key} loader returned a mismatched content hash`);let u=le(e.invocationPolicy),s=se(t,o,u);await e.onActivate?.(structuredClone(s));let l=Ie(a,s,{arguments:o,projectDirectory:typeof e.projectDirectory=="function"?e.projectDirectory():e.projectDirectory});if(Buffer.byteLength(l,"utf8")>oe)throw new Error(`Skill ${t.key} exceeds the ${oe}-byte invocation limit; move details into references/`);return await E(e,{...r,type:"skill-invoked"}),{loaded:a,activation:s,output:l}}catch(i){throw/denied by the active policy|requires approval/u.test(O(i))||await E(e,{...r,type:"skill-load-failed",reason:O(i)}),i}}function We(e,n="",t){return se(e,n,t)}function se(e,n,t){let o=re(t?.allow),r=re(e.toolPolicy.allow),i=[o,r].filter(s=>s!==void 0),a=i.length<=1?i[0]:void 0,u=[...new Set([...e.toolPolicy.deny??[],...t?.deny??[]])].sort();return{descriptor:structuredClone(e),arguments:n,toolAllowLayers:i,...a?{effectiveAllowedTools:a}:{},effectiveDeniedTools:u,externalActions:De(e.externalActions,t?.externalActions??"allow")}}function Je(e,n){return L(n,e.effectiveDeniedTools)?!1:e.toolAllowLayers.every(t=>L(n,t))}function Ie(e,n,t){let o=e.descriptor,r=e.instructions,i=/\$ARGUMENTS(?:\[\d+\])?|\$\d+/u.test(r),a=Re(t.arguments);r=r.replace(/\$ARGUMENTS\[(\d+)\]/gu,(s,l)=>a[Number.parseInt(l,10)]??"").replace(/\$(\d+)\b/gu,(s,l)=>a[Number.parseInt(l,10)]??"").replace(/\$ARGUMENTS\b/gu,t.arguments).replace(/\$\{(?:XENO|CLAUDE)_SKILL_DIR\}/gu,o.directory).replace(/\$\{(?:XENO|CLAUDE)_PROJECT_DIR\}/gu,t.projectDirectory??process.cwd()),t.arguments&&!i&&(r+=`
4
7
 
5
- ARGUMENTS: ${t.arguments}`);let d=o.resources.length>0?["","Bundled resources (load only when needed; paths are relative to the skill directory):",...o.resources.map(s=>`- ${s.relativePath} (${s.kind}, ${s.sizeBytes} bytes, sha256:${s.sha256})`)]:[];return[`<xeno_skill key="${Pe(o.key)}" hash="${o.contentHash}">`,`Source: ${o.source}`,`External actions: ${n.externalActions}`,...n.toolAllowLayers.map((s,l)=>`Tool allow layer ${l+1}: ${s.join(", ")||"none"}`),...n.effectiveDeniedTools.length>0?[`Denied tools: ${n.effectiveDeniedTools.join(", ")}`]:[],o.requestedPreapprovedTools.length>0?`Requested pre-approvals (not authority grants): ${o.requestedPreapprovedTools.join(", ")}`:"Requested pre-approvals: none","",r,...d,"</xeno_skill>"].join(`
6
- `)}async function Ie(e,n,t){if(n==="model"&&!e.modelInvocable||n==="user"&&!e.userInvocable)return"deny";let o=le(t.invocationPolicy);return v(e.key,o?.deny??[])||o?.allow&&!v(e.key,o.allow)?"deny":t.authorize?t.authorize(e,n):"allow"}function le(e){return typeof e=="function"?e():e}function Ae(e,n){let t={deny:0,ask:1,allow:2};return t[e]<=t[n]?e:n}function re(e){if(e)return[...new Set(e.map(n=>n.trim()).filter(Boolean))].sort()}function v(e,n){let t=e.toLowerCase();return n.some(o=>{let r=o.trim().toLowerCase();return r?new RegExp(`^${r.split("*").map(De).join(".*")}$`,"u").test(t):!1})}function De(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function $e(e){return(e.match(/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\S+/gu)??[]).map(t=>t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t)}async function b(e,n){await e.onAudit?.(n)}function ie(e,n){return{success:!1,output:n,error:n,errorCode:e}}function Re(e){return Le("sha256").update(e).digest("hex")}function Pe(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function O(e){return e instanceof Error?e.message:String(e)}export{g as XENO_SKILL_SCHEMA_VERSION,Ye as compileXenoSkillActivation,ze as createXenoSkillTool,Ke as discoverXenoSkills,Z as findXenoSkill,Me as importLegacyXenoSkill,be as invokeXenoSkill,We as isToolAllowedByXenoSkillActivation,Q as loadXenoSkill,He as renderXenoSkillCatalog};
8
+ ARGUMENTS: ${t.arguments}`);let u=o.resources.length>0?["","Bundled resources (load only when needed; paths are relative to the skill directory):",...o.resources.map(s=>`- ${s.relativePath} (${s.kind}, ${s.sizeBytes} bytes, sha256:${s.sha256})`)]:[];return[`<xeno_skill key="${Te(o.key)}" hash="${o.contentHash}">`,`Source: ${o.source}`,`External actions: ${n.externalActions}`,...n.toolAllowLayers.map((s,l)=>`Tool allow layer ${l+1}: ${s.join(", ")||"none"}`),...n.effectiveDeniedTools.length>0?[`Denied tools: ${n.effectiveDeniedTools.join(", ")}`]:[],o.requestedPreapprovedTools.length>0?`Requested pre-approvals (not authority grants): ${o.requestedPreapprovedTools.join(", ")}`:"Requested pre-approvals: none","",r,...u,"</xeno_skill>"].join(`
9
+ `)}async function Ae(e,n,t){if(n==="model"&&!e.modelInvocable||n==="user"&&!e.userInvocable)return"deny";let o=le(t.invocationPolicy);return L(e.key,o?.deny??[])||o?.allow&&!L(e.key,o.allow)?"deny":t.authorize?t.authorize(e,n):"allow"}function le(e){return typeof e=="function"?e():e}function De(e,n){let t={deny:0,ask:1,allow:2};return t[e]<=t[n]?e:n}function re(e){if(e)return[...new Set(e.map(n=>n.trim()).filter(Boolean))].sort()}function L(e,n){let t=e.toLowerCase();return n.some(o=>{let r=o.trim().toLowerCase();return r?new RegExp(`^${r.split("*").map($e).join(".*")}$`,"u").test(t):!1})}function $e(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Re(e){return(e.match(/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\S+/gu)??[]).map(t=>t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t)}async function E(e,n){await e.onAudit?.(n)}function ie(e,n){return{success:!1,output:n,error:n,errorCode:e}}function Pe(e){return Ee("sha256").update(e).digest("hex")}function Te(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function O(e){return e instanceof Error?e.message:String(e)}export{y as XENO_SKILL_SCHEMA_VERSION,We as compileXenoSkillActivation,Ye as createXenoSkillTool,Me as discoverXenoSkills,Z as findXenoSkill,He as importLegacyXenoSkill,Le as invokeXenoSkill,Je as isToolAllowedByXenoSkillActivation,Q as loadXenoSkill,Ue as renderXenoSkillCatalog};
@@ -1 +1 @@
1
- {"inputs":{"src/skills/types.ts":{"bytes":4878,"imports":[],"format":"esm"},"src/utils/yaml.ts":{"bytes":5506,"imports":[],"format":"esm"},"src/skills/catalog.ts":{"bytes":18933,"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"src/utils/yaml.ts","kind":"import-statement","original":"../utils/yaml.js"},{"path":"src/skills/types.ts","kind":"import-statement","original":"./types.js"}],"format":"esm"},"src/skills/tool.ts":{"bytes":11489,"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"src/skills/catalog.ts","kind":"import-statement","original":"./catalog.js"},{"path":"src/skills/types.ts","kind":"import-statement","original":"./types.js"}],"format":"esm"},"src/skills/index.ts":{"bytes":85,"imports":[{"path":"src/skills/types.ts","kind":"import-statement","original":"./types.js"},{"path":"src/skills/catalog.ts","kind":"import-statement","original":"./catalog.js"},{"path":"src/skills/tool.ts","kind":"import-statement","original":"./tool.js"}],"format":"esm"}},"outputs":{"dist/skills/index.cjs":{"imports":[{"path":"node:crypto","kind":"require-call","external":true},{"path":"node:fs","kind":"require-call","external":true},{"path":"node:path","kind":"require-call","external":true},{"path":"node:crypto","kind":"require-call","external":true}],"exports":[],"entryPoint":"src/skills/index.ts","inputs":{"src/skills/index.ts":{"bytesInOutput":324},"src/skills/types.ts":{"bytesInOutput":8},"src/skills/catalog.ts":{"bytesInOutput":9696},"src/utils/yaml.ts":{"bytesInOutput":2217},"src/skills/tool.ts":{"bytesInOutput":5403}},"bytes":18322}}}
1
+ {"inputs":{"src/skills/types.ts":{"bytes":4878,"imports":[],"format":"esm"},"src/utils/yaml.ts":{"bytes":7264,"imports":[],"format":"esm"},"src/skills/catalog.ts":{"bytes":18933,"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"src/utils/yaml.ts","kind":"import-statement","original":"../utils/yaml.js"},{"path":"src/skills/types.ts","kind":"import-statement","original":"./types.js"}],"format":"esm"},"src/skills/tool.ts":{"bytes":11489,"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"src/skills/catalog.ts","kind":"import-statement","original":"./catalog.js"},{"path":"src/skills/types.ts","kind":"import-statement","original":"./types.js"}],"format":"esm"},"src/skills/index.ts":{"bytes":85,"imports":[{"path":"src/skills/types.ts","kind":"import-statement","original":"./types.js"},{"path":"src/skills/catalog.ts","kind":"import-statement","original":"./catalog.js"},{"path":"src/skills/tool.ts","kind":"import-statement","original":"./tool.js"}],"format":"esm"}},"outputs":{"dist/skills/index.cjs":{"imports":[{"path":"node:crypto","kind":"require-call","external":true},{"path":"node:fs","kind":"require-call","external":true},{"path":"node:path","kind":"require-call","external":true},{"path":"node:crypto","kind":"require-call","external":true}],"exports":[],"entryPoint":"src/skills/index.ts","inputs":{"src/skills/index.ts":{"bytesInOutput":324},"src/skills/types.ts":{"bytesInOutput":8},"src/skills/catalog.ts":{"bytesInOutput":9696},"src/utils/yaml.ts":{"bytesInOutput":2821},"src/skills/tool.ts":{"bytesInOutput":5403}},"bytes":18926}}}
@@ -1 +1 @@
1
- {"inputs":{"src/skills/types.ts":{"bytes":4878,"imports":[],"format":"esm"},"src/utils/yaml.ts":{"bytes":5506,"imports":[],"format":"esm"},"src/skills/catalog.ts":{"bytes":18933,"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"src/utils/yaml.ts","kind":"import-statement","original":"../utils/yaml.js"},{"path":"src/skills/types.ts","kind":"import-statement","original":"./types.js"}],"format":"esm"},"src/skills/tool.ts":{"bytes":11489,"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"src/skills/catalog.ts","kind":"import-statement","original":"./catalog.js"},{"path":"src/skills/types.ts","kind":"import-statement","original":"./types.js"}],"format":"esm"},"src/skills/index.ts":{"bytes":85,"imports":[{"path":"src/skills/types.ts","kind":"import-statement","original":"./types.js"},{"path":"src/skills/catalog.ts","kind":"import-statement","original":"./catalog.js"},{"path":"src/skills/tool.ts","kind":"import-statement","original":"./tool.js"}],"format":"esm"}},"outputs":{"dist/skills/index.js":{"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"node:crypto","kind":"import-statement","external":true}],"exports":["XENO_SKILL_SCHEMA_VERSION","compileXenoSkillActivation","createXenoSkillTool","discoverXenoSkills","findXenoSkill","importLegacyXenoSkill","invokeXenoSkill","isToolAllowedByXenoSkillActivation","loadXenoSkill","renderXenoSkillCatalog"],"entryPoint":"src/skills/index.ts","inputs":{"src/skills/types.ts":{"bytesInOutput":8},"src/skills/index.ts":{"bytesInOutput":0},"src/skills/catalog.ts":{"bytesInOutput":9541},"src/utils/yaml.ts":{"bytesInOutput":2217},"src/skills/tool.ts":{"bytesInOutput":5407}},"bytes":17455}}}
1
+ {"inputs":{"src/skills/types.ts":{"bytes":4878,"imports":[],"format":"esm"},"src/utils/yaml.ts":{"bytes":7264,"imports":[],"format":"esm"},"src/skills/catalog.ts":{"bytes":18933,"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"src/utils/yaml.ts","kind":"import-statement","original":"../utils/yaml.js"},{"path":"src/skills/types.ts","kind":"import-statement","original":"./types.js"}],"format":"esm"},"src/skills/tool.ts":{"bytes":11489,"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"src/skills/catalog.ts","kind":"import-statement","original":"./catalog.js"},{"path":"src/skills/types.ts","kind":"import-statement","original":"./types.js"}],"format":"esm"},"src/skills/index.ts":{"bytes":85,"imports":[{"path":"src/skills/types.ts","kind":"import-statement","original":"./types.js"},{"path":"src/skills/catalog.ts","kind":"import-statement","original":"./catalog.js"},{"path":"src/skills/tool.ts","kind":"import-statement","original":"./tool.js"}],"format":"esm"}},"outputs":{"dist/skills/index.js":{"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"node:crypto","kind":"import-statement","external":true}],"exports":["XENO_SKILL_SCHEMA_VERSION","compileXenoSkillActivation","createXenoSkillTool","discoverXenoSkills","findXenoSkill","importLegacyXenoSkill","invokeXenoSkill","isToolAllowedByXenoSkillActivation","loadXenoSkill","renderXenoSkillCatalog"],"entryPoint":"src/skills/index.ts","inputs":{"src/skills/types.ts":{"bytesInOutput":8},"src/skills/index.ts":{"bytesInOutput":0},"src/skills/catalog.ts":{"bytesInOutput":9541},"src/utils/yaml.ts":{"bytesInOutput":2821},"src/skills/tool.ts":{"bytesInOutput":5407}},"bytes":18059}}}