@xenosystem/agent-sdk 0.9.11 → 0.9.14

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 (102) hide show
  1. package/LICENSE +15 -15
  2. package/README.md +511 -511
  3. package/dist/agents/index.cjs +5 -5
  4. package/dist/agents/index.js +15 -15
  5. package/dist/agents/metafile-cjs.json +1 -1
  6. package/dist/agents/metafile-esm.json +1 -1
  7. package/dist/artifacts/index.cjs +1 -1
  8. package/dist/artifacts/index.js +1 -1
  9. package/dist/artifacts/metafile-cjs.json +1 -1
  10. package/dist/artifacts/metafile-esm.json +1 -1
  11. package/dist/automation/index.d.cts +1 -0
  12. package/dist/automation/index.d.ts +1 -0
  13. package/dist/automation/metafile-cjs.json +1 -1
  14. package/dist/automation/metafile-esm.json +1 -1
  15. package/dist/control-plane/index.cjs +1 -1
  16. package/dist/control-plane/index.js +1 -1
  17. package/dist/control-plane/metafile-cjs.json +1 -1
  18. package/dist/control-plane/metafile-esm.json +1 -1
  19. package/dist/control-room/metafile-cjs.json +1 -1
  20. package/dist/control-room/metafile-esm.json +1 -1
  21. package/dist/electron/index.cjs +107 -107
  22. package/dist/electron/index.d.cts +8 -0
  23. package/dist/electron/index.d.ts +8 -0
  24. package/dist/electron/index.js +103 -103
  25. package/dist/electron/metafile-cjs.json +1 -1
  26. package/dist/electron/metafile-esm.json +1 -1
  27. package/dist/governance/index.cjs +18 -18
  28. package/dist/governance/index.d.cts +1 -0
  29. package/dist/governance/index.d.ts +1 -0
  30. package/dist/governance/index.js +18 -18
  31. package/dist/governance/metafile-cjs.json +1 -1
  32. package/dist/governance/metafile-esm.json +1 -1
  33. package/dist/hooks/metafile-cjs.json +1 -1
  34. package/dist/hooks/metafile-esm.json +1 -1
  35. package/dist/hosted/index.cjs +1 -1
  36. package/dist/hosted/index.js +1 -1
  37. package/dist/hosted/metafile-cjs.json +1 -1
  38. package/dist/hosted/metafile-esm.json +1 -1
  39. package/dist/index.cjs +347 -329
  40. package/dist/index.d.cts +113 -2
  41. package/dist/index.d.ts +113 -2
  42. package/dist/index.js +329 -311
  43. package/dist/intelligence/metafile-cjs.json +1 -1
  44. package/dist/intelligence/metafile-esm.json +1 -1
  45. package/dist/mcp/index.d.cts +1 -0
  46. package/dist/mcp/index.d.ts +1 -0
  47. package/dist/mcp/metafile-cjs.json +1 -1
  48. package/dist/mcp/metafile-esm.json +1 -1
  49. package/dist/metafile-cjs.json +1 -1
  50. package/dist/metafile-esm.json +1 -1
  51. package/dist/oracle/metafile-cjs.json +1 -1
  52. package/dist/oracle/metafile-esm.json +1 -1
  53. package/dist/providers/metafile-cjs.json +1 -1
  54. package/dist/providers/metafile-esm.json +1 -1
  55. package/dist/recipes/metafile-cjs.json +1 -1
  56. package/dist/recipes/metafile-esm.json +1 -1
  57. package/dist/research/metafile-cjs.json +1 -1
  58. package/dist/research/metafile-esm.json +1 -1
  59. package/dist/session/index.cjs +2 -2
  60. package/dist/session/index.d.cts +8 -0
  61. package/dist/session/index.d.ts +8 -0
  62. package/dist/session/index.js +2 -2
  63. package/dist/session/metafile-cjs.json +1 -1
  64. package/dist/session/metafile-esm.json +1 -1
  65. package/dist/sharing/metafile-cjs.json +1 -1
  66. package/dist/sharing/metafile-esm.json +1 -1
  67. package/dist/skills/index.d.cts +1 -0
  68. package/dist/skills/index.d.ts +1 -0
  69. package/dist/skills/metafile-cjs.json +1 -1
  70. package/dist/skills/metafile-esm.json +1 -1
  71. package/dist/soul/metafile-cjs.json +1 -1
  72. package/dist/soul/metafile-esm.json +1 -1
  73. package/dist/terminal/metafile-cjs.json +1 -1
  74. package/dist/terminal/metafile-esm.json +1 -1
  75. package/dist/ui/index.d.cts +1 -0
  76. package/dist/ui/index.d.ts +1 -0
  77. package/dist/ui/metafile-cjs.json +1 -1
  78. package/dist/ui/metafile-esm.json +1 -1
  79. package/dist/utils/index.d.cts +1 -0
  80. package/dist/utils/index.d.ts +1 -0
  81. package/dist/utils/metafile-cjs.json +1 -1
  82. package/dist/utils/metafile-esm.json +1 -1
  83. package/native/mxc/LICENSE.microsoft-mxc-sdk.md +20 -20
  84. package/native/mxc/README.md +25 -25
  85. package/native/mxc/package.json +58 -58
  86. package/ownership/CLEAN_ROOM_CONTRIBUTOR_GUIDE.md +63 -63
  87. package/ownership/evidence/PROPRIETARY-COMMAND-1/implementation-record.md +77 -77
  88. package/ownership/evidence/PROPRIETARY-COMMAND-1/provenance-review.md +51 -51
  89. package/ownership/evidence/PROPRIETARY-MEDIA-1/implementation-record.md +131 -131
  90. package/ownership/evidence/PROPRIETARY-MEDIA-1/provenance-review.md +50 -50
  91. package/ownership/evidence/PROPRIETARY-PTY-1/implementation-record.md +86 -86
  92. package/ownership/evidence/PROPRIETARY-PTY-1/provenance-review.md +52 -52
  93. package/ownership/evidence/PROPRIETARY-RUNTIME-1/implementation-record.md +68 -68
  94. package/ownership/evidence/PROPRIETARY-RUNTIME-1/provenance-review.md +32 -32
  95. package/ownership/evidence/PROPRIETARY-TOOLCHAIN-1/implementation-record.md +53 -53
  96. package/ownership/evidence/PROPRIETARY-TOOLCHAIN-1/provenance-review.md +32 -32
  97. package/ownership/evidence/PROPRIETARY-UI-1/implementation-record.md +96 -96
  98. package/ownership/evidence/PROPRIETARY-UI-1/provenance-review.md +46 -46
  99. package/ownership/ownership-policy.schema.json +192 -192
  100. package/ownership/templates/clean-room-implementation-record.md +70 -70
  101. package/ownership/templates/provenance-review.md +51 -51
  102. package/package.json +1 -1
@@ -1,11 +1,11 @@
1
- "use strict";var M=Object.defineProperty;var ye=Object.getOwnPropertyDescriptor;var he=Object.getOwnPropertyNames;var Ae=Object.prototype.hasOwnProperty;var Pe=(e,n)=>{for(var r in n)M(e,r,{get:n[r],enumerable:!0})},we=(e,n,r,o)=>{if(n&&typeof n=="object"||typeof n=="function")for(let t of he(n))!Ae.call(e,t)&&t!==r&&M(e,t,{get:()=>n[t],enumerable:!(o=ye(n,t))||o.enumerable});return e};var xe=e=>we(M({},"__esModule",{value:!0}),e);var on={};Pe(on,{AGENT_PROFILE_EXTERNAL_ACTIONS:()=>W,AgentDefinitionLoader:()=>T,AgentDefinitionResolver:()=>q,AgentProfileValidationError:()=>P,XENO_AGENT_PROFILE_SCHEMA_VERSION:()=>N,agentDefinitionFromProfile:()=>nn,agentProfileFromDefinition:()=>ue,compileAgentProfile:()=>ae,createAgentDefinitionFile:()=>Ue,createAgentDefinitionPromptSection:()=>Be,getProjectAgentDefinitionDirs:()=>re,getProjectAgentDefinitionsDir:()=>oe,getUserAgentDefinitionsDir:()=>L,isValidAgentDefinitionName:()=>_,listBuiltInAgentProfiles:()=>en,renderAgentDefinition:()=>He,renderAgentDefinitions:()=>We,resolveAgentDefinition:()=>Le,resolveAgentProfile:()=>rn,resolveAgentToolPolicy:()=>I,resolveBuiltInAgentProfile:()=>de,scanAgentDefinitions:()=>F,toAgentDefinitionMetadata:()=>Ve,validateAgentDefinition:()=>te});module.exports=xe(on);var y=require("node:fs"),m=require("node:path");function K(e){let n=be(e);return{frontmatter:n.frontmatter,content:n.content.trim()}}function be(e){let n=e.replace(/^\uFEFF/,"");if(!n.startsWith("---"))return{frontmatter:{},content:e};let r=n.search(/\r?\n/);if(r<0||n.slice(0,r).trim()!=="---")return{frontmatter:{},content:e};let o=n.slice(r+(n[r]==="\r"?2:1)),t=o.match(/(?:^|\r?\n)---[ \t]*(?:\r?\n|$)/);if(!t||t.index===void 0)throw new Error("YAML frontmatter is not closed.");let i=o.slice(0,t.index),l=t[0],s=t.index+l.length;return{frontmatter:Q(i),content:o.slice(s)}}function Q(e){let n={},r=e.split(/\r?\n/);for(let o=0;o<r.length;o+=1){let t=r[o];if(!t.trim()||t.trimStart().startsWith("#"))continue;if(/^\s/.test(t))throw new Error(`Unexpected indentation at line ${o+1}.`);let i=ve(t,o+1);if(i.key==="<<")throw new Error("YAML merge keys are not supported.");if(i.value!==""){n[i.key]=Z(i.value,o+1);continue}let l=ke(r,o+1);n[i.key]=l.value,o=l.nextIndex-1}return n}function ke(e,n){let r=[],o=n;for(;o<e.length;o+=1){let i=e[o];if(!i.trim()){r.push(i);continue}if(!/^\s/.test(i))break;r.push(i.replace(/^ {2}/,""))}let t=r.filter(i=>i.trim()&&!i.trimStart().startsWith("#"));return t.length===0?{value:{},nextIndex:o}:t.every(i=>i.trimStart().startsWith("- "))?{value:t.map((i,l)=>Z(i.trimStart().slice(2),n+l+1)),nextIndex:o}:{value:Q(r.join(`
2
- `)),nextIndex:o}}function ve(e,n){let r=e.indexOf(":");if(r<=0)throw new Error(`Invalid YAML line ${n}.`);let o=e.slice(0,r).trim(),t=e.slice(r+1).trim();if(!o)throw new Error(`Invalid YAML key at line ${n}.`);return{key:o,value:t}}function Z(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 Y(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 Y(e,n);if(e.includes("[")||e.includes("]")||e.includes("{")||e.includes("}"))throw new Error(`Unsupported YAML scalar at line ${n}.`);return e}function Y(e,n){try{return JSON.parse(e)}catch{throw new Error(`Invalid YAML scalar at line ${n}.`)}}var w=require("node:os");var j=require("node:path"),ln=(0,w.platform)();var an=(0,w.release)(),cn=(0,w.homedir)();function ee(){let e=process.env.XENO_AGENT_HOME?.trim();return e?(0,j.resolve)(e):(0,j.resolve)((0,w.homedir)(),".xeno-agent")}var Se=/^[a-z][a-z0-9_-]{0,63}$/;function De(){return ee()}function L(e=De()){return(0,m.join)(e,"agents")}function ne(e){return(0,m.resolve)(e)}function Ee(e){let n=(0,m.dirname)(e);return n===e?e:n}function re(e=process.cwd()){let n=ne(e),r=[],o=n;for(;;){let t=(0,m.join)(o,".xeno","agents");(0,y.existsSync)(t)&&r.push(t);let i=Ee(o);if(i===o)break;o=i}return r.reverse()}function oe(e=process.cwd()){return(0,m.join)(ne(e),".xeno","agents")}function $e(e){return(0,y.existsSync)(e)?(0,y.readdirSync)(e,{withFileTypes:!0}).filter(n=>n.isFile()&&n.name.toLowerCase().endsWith(".md")).map(n=>(0,m.join)(e,n.name)).sort((n,r)=>n.localeCompare(r)):[]}function k(e){if(typeof e!="string")return;let n=e.trim();return n.length>0?n:void 0}function v(e){return Array.isArray(e)?e.map(n=>String(n).trim()).filter(Boolean):typeof e=="string"?e.split(",").map(n=>n.trim()).filter(Boolean):[]}function Te(e){if(typeof e=="boolean")return e;if(typeof e!="string")return;let n=e.trim().toLowerCase();if(["1","true","yes","on"].includes(n))return!0;if(["0","false","no","off"].includes(n))return!1}function Ie(e){return(0,m.parse)((0,m.basename)(e)).name.toLowerCase()}function _(e){return Se.test(e)}function Ce(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Re(e){if(typeof e!="string")return;let n=e.trim().toLowerCase();if(n==="inherit")return"inherit";if(n==="none"||n==="off"||n==="disabled")return"none";if(n==="read"||n==="readonly"||n==="read-only")return"readOnly";if(n==="default"||n==="standard")return"default";if(n==="full"||n==="fullaccess"||n==="full-access")return"fullAccess"}function Ne(e){if(e===void 0)return;if(typeof e=="string"||Array.isArray(e)){let i=v(e);return i.length>0?{allow:i}:void 0}if(!Ce(e))return;let n=v(e.allow),r=v(e.deny),o=Re(e.mode),t={};return o&&(t.mode=o),n.length>0&&(t.allow=n),r.length>0&&(t.deny=r),Object.keys(t).length>0?t:void 0}function Oe(e){let n=Te(e.worktree??e.defaultWorktreeIsolation);if(n===!0)return"worktree";if(n===!1)return"none";let r=k(e.isolation)?.toLowerCase();if(r==="worktree")return"worktree";if(r==="none"||r==="off"||r==="disabled")return"none"}function te(e){let n=[];return _(e.name)||n.push(`Invalid agent name "${e.name}". Use 1-64 lowercase letters, digits, hyphens, or underscores, starting with a letter.`),e.prompt.trim().length===0&&n.push("Agent definition body is empty."),n}function Me(e,n,r){let o=(0,y.readFileSync)(e,"utf8"),t=K(o),i=t.frontmatter,l=Ie(e),s=k(i.name)?.toLowerCase()??l,d=t.content.trim(),p=te({name:s,prompt:d});if(p.length>0)throw new Error(p.join(" "));let u=k(i.description),c=k(i.model),f=k(i.color),A=k(i.memory??i.memoryScope),x=Oe(i),D=Ne(i.tools);return{name:s,scope:n,path:e,...u?{description:u}:{},...c?{model:c}:{},...f?{color:f}:{},...A?{memory:A}:{},...x?{isolation:x}:{},tags:v(i.tags),skills:v(i.skills),hooks:v(i.hooks),prompt:d,active:!0,priority:r,...D?{toolPolicy:D}:{}}}function E(e,n,r,o,t){for(let i of $e(e))try{o.push(Me(i,n,r))}catch(l){t.push({path:i,scope:n,message:l instanceof Error?l.message:String(l)})}}function je(e){let n=new Map;for(let r of e){let o=n.get(r.name);(!o||r.priority>o.priority)&&n.set(r.name,r)}return n}function qe(e,n){let r=n.get(e.name),o=r?.path===e.path;return{name:e.name,scope:e.scope,path:e.path,...e.description?{description:e.description}:{},...e.model?{model:e.model}:{},...e.color?{color:e.color}:{},...e.memory?{memory:e.memory}:{},...e.isolation?{isolation:e.isolation}:{},tags:e.tags,skills:e.skills,hooks:e.hooks,prompt:e.prompt,active:o,...e.toolPolicy?{toolPolicy:e.toolPolicy}:{},...!o&&r?{shadowedBy:{name:r.name,scope:r.scope,path:r.path}}:{}}}function F(e=process.cwd(),n={}){let r=n.cwd??e,o=n.userDir??L(n.agentHome),t=n.projectDirs??re(r),i=n.pluginDirs??[],l=n.builtInDirs??[],s=[],d=[];n.includeUser!==!1&&E(o,"user",0,s,d),n.includeProject!==!1&&t.forEach((c,f)=>E(c,"project",100+f,s,d)),n.includePlugins&&i.forEach((c,f)=>E(c,"plugin",1e3+f,s,d)),n.includeBuiltIns&&l.forEach((c,f)=>E(c,"built-in",2e3+f,s,d));let p=je(s),u=s.map(c=>qe(c,p));return u.sort((c,f)=>{if(c.active!==f.active)return c.active?-1:1;let A=c.name.localeCompare(f.name);return A!==0?A:c.path.localeCompare(f.path)}),{definitions:u,issues:d,searchPaths:{...n.includeUser!==!1?{user:o}:{},project:n.includeProject===!1?[]:t,plugin:n.includePlugins?i:[],builtIn:n.includeBuiltIns?l:[]}}}function Le(e,n=process.cwd(),r={}){let o=e.trim().toLowerCase(),t=F(n,r);return{definition:t.definitions.find(i=>i.active&&i.name===o)??null,scan:t}}var T=class{constructor(n={}){this.options=n}options;scan(n=this.options.cwd??process.cwd()){return F(n,this.options)}},q=class{constructor(n=new T){this.loader=n}loader;resolve(n,r=process.cwd()){let o=this.loader.scan(r),t=n.trim().toLowerCase();return{definition:o.definitions.find(i=>i.active&&i.name===t)??null,scan:o}}};function $(e){if(!e||e.length===0)return;let n=Array.from(new Set(e.map(r=>r.trim()).filter(Boolean)));return n.length>0?n:void 0}function _e(e,n){if(!e&&!n)return;if(!e)return $(n);if(!n)return $(e);let r=new Set(n);return $(e.filter(o=>r.has(o)))}function Fe(e,n){let r={none:0,readOnly:1,default:2,fullAccess:3,inherit:4},o=n??"inherit",t=e??"inherit";return r[o]<=r[t]?o:t}function I(e,n={}){let r=e.toolPolicy??{},o={mode:Fe(r.mode,n.mode)},t=_e(n.allow,r.allow),i=$([...n.deny??[],...r.deny??[]]);return t&&(o.allow=t),i&&(o.deny=i),o}function Be(e){return{name:`custom-agent:${e.name}`,order:20,provide(){let n=["","","# Custom Agent",`Active agent: ${e.name}`,`Definition scope: ${e.scope}`,`Definition path: ${e.path}`];return e.description&&n.push(`Description: ${e.description}`),n.push("",e.prompt),n.join(`
1
+ "use strict";var M=Object.defineProperty;var ye=Object.getOwnPropertyDescriptor;var he=Object.getOwnPropertyNames;var Ae=Object.prototype.hasOwnProperty;var Pe=(e,n)=>{for(var r in n)M(e,r,{get:n[r],enumerable:!0})},we=(e,n,r,o)=>{if(n&&typeof n=="object"||typeof n=="function")for(let t of he(n))!Ae.call(e,t)&&t!==r&&M(e,t,{get:()=>n[t],enumerable:!(o=ye(n,t))||o.enumerable});return e};var xe=e=>we(M({},"__esModule",{value:!0}),e);var on={};Pe(on,{AGENT_PROFILE_EXTERNAL_ACTIONS:()=>W,AgentDefinitionLoader:()=>T,AgentDefinitionResolver:()=>q,AgentProfileValidationError:()=>P,XENO_AGENT_PROFILE_SCHEMA_VERSION:()=>N,agentDefinitionFromProfile:()=>nn,agentProfileFromDefinition:()=>ue,compileAgentProfile:()=>ae,createAgentDefinitionFile:()=>Ue,createAgentDefinitionPromptSection:()=>Be,getProjectAgentDefinitionDirs:()=>re,getProjectAgentDefinitionsDir:()=>oe,getUserAgentDefinitionsDir:()=>L,isValidAgentDefinitionName:()=>_,listBuiltInAgentProfiles:()=>en,renderAgentDefinition:()=>He,renderAgentDefinitions:()=>We,resolveAgentDefinition:()=>Le,resolveAgentProfile:()=>rn,resolveAgentToolPolicy:()=>I,resolveBuiltInAgentProfile:()=>de,scanAgentDefinitions:()=>F,toAgentDefinitionMetadata:()=>Ve,validateAgentDefinition:()=>te});module.exports=xe(on);var m=require("node:fs"),p=require("node:path");function K(e){let n=be(e);return{frontmatter:n.frontmatter,content:n.content.trim()}}function be(e){let n=e.replace(/^\uFEFF/,"");if(!n.startsWith("---"))return{frontmatter:{},content:e};let r=n.search(/\r?\n/);if(r<0||n.slice(0,r).trim()!=="---")return{frontmatter:{},content:e};let o=n.slice(r+(n[r]==="\r"?2:1)),t=o.match(/(?:^|\r?\n)---[ \t]*(?:\r?\n|$)/);if(!t||t.index===void 0)throw new Error("YAML frontmatter is not closed.");let i=o.slice(0,t.index),l=t[0],s=t.index+l.length;return{frontmatter:Q(i),content:o.slice(s)}}function Q(e){let n={},r=e.split(/\r?\n/);for(let o=0;o<r.length;o+=1){let t=r[o];if(!t.trim()||t.trimStart().startsWith("#"))continue;if(/^\s/.test(t))throw new Error(`Unexpected indentation at line ${o+1}.`);let i=ve(t,o+1);if(i.key==="<<")throw new Error("YAML merge keys are not supported.");if(i.value!==""){n[i.key]=Z(i.value,o+1);continue}let l=ke(r,o+1);n[i.key]=l.value,o=l.nextIndex-1}return n}function ke(e,n){let r=[],o=n;for(;o<e.length;o+=1){let i=e[o];if(!i.trim()){r.push(i);continue}if(!/^\s/.test(i))break;r.push(i.replace(/^ {2}/,""))}let t=r.filter(i=>i.trim()&&!i.trimStart().startsWith("#"));return t.length===0?{value:{},nextIndex:o}:t.every(i=>i.trimStart().startsWith("- "))?{value:t.map((i,l)=>Z(i.trimStart().slice(2),n+l+1)),nextIndex:o}:{value:Q(r.join(`
2
+ `)),nextIndex:o}}function ve(e,n){let r=e.indexOf(":");if(r<=0)throw new Error(`Invalid YAML line ${n}.`);let o=e.slice(0,r).trim(),t=e.slice(r+1).trim();if(!o)throw new Error(`Invalid YAML key at line ${n}.`);return{key:o,value:t}}function Z(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 Y(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 Y(e,n);if(e.includes("[")||e.includes("]")||e.includes("{")||e.includes("}"))throw new Error(`Unsupported YAML scalar at line ${n}.`);return e}function Y(e,n){try{return JSON.parse(e)}catch{throw new Error(`Invalid YAML scalar at line ${n}.`)}}var w=require("node:os");var j=require("node:path"),ln=(0,w.platform)();var an=(0,w.release)(),cn=(0,w.homedir)();function ee(){let e=process.env.XENO_AGENT_HOME?.trim();return e?(0,j.resolve)(e):(0,j.resolve)((0,w.homedir)(),".xeno-agent")}var Se=/^[a-z][a-z0-9_-]{0,63}$/;function De(){return ee()}function L(e=De()){return(0,p.join)(e,"agents")}function ne(e){return(0,p.resolve)(e)}function Ee(e){let n=(0,p.dirname)(e);return n===e?e:n}function re(e=process.cwd()){let n=ne(e),r=[],o=n;for(;;){let i=(0,p.join)(o,".claude","agents"),l=(0,p.join)(o,".xeno","agents");r.push({...(0,m.existsSync)(i)?{claude:i}:{},...(0,m.existsSync)(l)?{xeno:l}:{}});let s=Ee(o);if(s===o)break;o=s}r.reverse();let t=[];for(let i of r)i.claude&&t.push(i.claude),i.xeno&&t.push(i.xeno);return t}function oe(e=process.cwd()){return(0,p.join)(ne(e),".xeno","agents")}function $e(e){return(0,m.existsSync)(e)?(0,m.readdirSync)(e,{withFileTypes:!0}).filter(n=>n.isFile()&&n.name.toLowerCase().endsWith(".md")).map(n=>(0,p.join)(e,n.name)).sort((n,r)=>n.localeCompare(r)):[]}function k(e){if(typeof e!="string")return;let n=e.trim();return n.length>0?n:void 0}function v(e){return Array.isArray(e)?e.map(n=>String(n).trim()).filter(Boolean):typeof e=="string"?e.split(",").map(n=>n.trim()).filter(Boolean):[]}function Te(e){if(typeof e=="boolean")return e;if(typeof e!="string")return;let n=e.trim().toLowerCase();if(["1","true","yes","on"].includes(n))return!0;if(["0","false","no","off"].includes(n))return!1}function Ie(e){return(0,p.parse)((0,p.basename)(e)).name.toLowerCase()}function _(e){return Se.test(e)}function Ce(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Re(e){if(typeof e!="string")return;let n=e.trim().toLowerCase();if(n==="inherit")return"inherit";if(n==="none"||n==="off"||n==="disabled")return"none";if(n==="read"||n==="readonly"||n==="read-only")return"readOnly";if(n==="default"||n==="standard")return"default";if(n==="full"||n==="fullaccess"||n==="full-access")return"fullAccess"}function Ne(e){if(e===void 0)return;if(typeof e=="string"||Array.isArray(e)){let i=v(e);return i.length>0?{allow:i}:void 0}if(!Ce(e))return;let n=v(e.allow),r=v(e.deny),o=Re(e.mode),t={};return o&&(t.mode=o),n.length>0&&(t.allow=n),r.length>0&&(t.deny=r),Object.keys(t).length>0?t:void 0}function Oe(e){let n=Te(e.worktree??e.defaultWorktreeIsolation);if(n===!0)return"worktree";if(n===!1)return"none";let r=k(e.isolation)?.toLowerCase();if(r==="worktree")return"worktree";if(r==="none"||r==="off"||r==="disabled")return"none"}function te(e){let n=[];return _(e.name)||n.push(`Invalid agent name "${e.name}". Use 1-64 lowercase letters, digits, hyphens, or underscores, starting with a letter.`),e.prompt.trim().length===0&&n.push("Agent definition body is empty."),n}function Me(e,n,r){let o=(0,m.readFileSync)(e,"utf8"),t=K(o),i=t.frontmatter,l=Ie(e),s=k(i.name)?.toLowerCase()??l,d=t.content.trim(),g=te({name:s,prompt:d});if(g.length>0)throw new Error(g.join(" "));let u=k(i.description),c=k(i.model),f=k(i.color),A=k(i.memory??i.memoryScope),x=Oe(i),D=Ne(i.tools);return{name:s,scope:n,path:e,...u?{description:u}:{},...c?{model:c}:{},...f?{color:f}:{},...A?{memory:A}:{},...x?{isolation:x}:{},tags:v(i.tags),skills:v(i.skills),hooks:v(i.hooks),prompt:d,active:!0,priority:r,...D?{toolPolicy:D}:{}}}function E(e,n,r,o,t){for(let i of $e(e))try{o.push(Me(i,n,r))}catch(l){t.push({path:i,scope:n,message:l instanceof Error?l.message:String(l)})}}function je(e){let n=new Map;for(let r of e){let o=n.get(r.name);(!o||r.priority>o.priority)&&n.set(r.name,r)}return n}function qe(e,n){let r=n.get(e.name),o=r?.path===e.path;return{name:e.name,scope:e.scope,path:e.path,...e.description?{description:e.description}:{},...e.model?{model:e.model}:{},...e.color?{color:e.color}:{},...e.memory?{memory:e.memory}:{},...e.isolation?{isolation:e.isolation}:{},tags:e.tags,skills:e.skills,hooks:e.hooks,prompt:e.prompt,active:o,...e.toolPolicy?{toolPolicy:e.toolPolicy}:{},...!o&&r?{shadowedBy:{name:r.name,scope:r.scope,path:r.path}}:{}}}function F(e=process.cwd(),n={}){let r=n.cwd??e,o=n.userDir??L(n.agentHome),t=n.projectDirs??re(r),i=n.pluginDirs??[],l=n.builtInDirs??[],s=[],d=[];n.includeUser!==!1&&E(o,"user",0,s,d),n.includeProject!==!1&&t.forEach((c,f)=>E(c,"project",100+f,s,d)),n.includePlugins&&i.forEach((c,f)=>E(c,"plugin",1e3+f,s,d)),n.includeBuiltIns&&l.forEach((c,f)=>E(c,"built-in",2e3+f,s,d));let g=je(s),u=s.map(c=>qe(c,g));return u.sort((c,f)=>{if(c.active!==f.active)return c.active?-1:1;let A=c.name.localeCompare(f.name);return A!==0?A:c.path.localeCompare(f.path)}),{definitions:u,issues:d,searchPaths:{...n.includeUser!==!1?{user:o}:{},project:n.includeProject===!1?[]:t,plugin:n.includePlugins?i:[],builtIn:n.includeBuiltIns?l:[]}}}function Le(e,n=process.cwd(),r={}){let o=e.trim().toLowerCase(),t=F(n,r);return{definition:t.definitions.find(i=>i.active&&i.name===o)??null,scan:t}}var T=class{constructor(n={}){this.options=n}options;scan(n=this.options.cwd??process.cwd()){return F(n,this.options)}},q=class{constructor(n=new T){this.loader=n}loader;resolve(n,r=process.cwd()){let o=this.loader.scan(r),t=n.trim().toLowerCase();return{definition:o.definitions.find(i=>i.active&&i.name===t)??null,scan:o}}};function $(e){if(!e||e.length===0)return;let n=Array.from(new Set(e.map(r=>r.trim()).filter(Boolean)));return n.length>0?n:void 0}function _e(e,n){if(!e&&!n)return;if(!e)return $(n);if(!n)return $(e);let r=new Set(n);return $(e.filter(o=>r.has(o)))}function Fe(e,n){let r={none:0,readOnly:1,default:2,fullAccess:3,inherit:4},o=n??"inherit",t=e??"inherit";return r[o]<=r[t]?o:t}function I(e,n={}){let r=e.toolPolicy??{},o={mode:Fe(r.mode,n.mode)},t=_e(n.allow,r.allow),i=$([...n.deny??[],...r.deny??[]]);return t&&(o.allow=t),i&&(o.deny=i),o}function Be(e){return{name:`custom-agent:${e.name}`,order:20,provide(){let n=["","","# Custom Agent",`Active agent: ${e.name}`,`Definition scope: ${e.scope}`,`Definition path: ${e.path}`];return e.description&&n.push(`Description: ${e.description}`),n.push("",e.prompt),n.join(`
3
3
  `)}}}function Ve(e){return{name:e.name,scope:e.scope,path:e.path,...e.description?{description:e.description}:{},...e.model?{model:e.model}:{},...e.color?{color:e.color}:{},...e.memory?{memory:e.memory}:{},...e.isolation?{isolation:e.isolation}:{},tags:e.tags,skills:e.skills,hooks:e.hooks,active:e.active,...e.toolPolicy?{toolPolicy:e.toolPolicy}:{},...e.shadowedBy?{shadowedBy:e.shadowedBy}:{}}}function b(e,n){return e.length>=n?e:e+" ".repeat(n-e.length)}function We(e,n){let r=[];if(e.length===0)r.push("No custom agent definitions found.");else{r.push(`${b("name",22)} ${b("scope",8)} ${b("status",9)} description`),r.push(`${"-".repeat(22)} ${"-".repeat(8)} ${"-".repeat(9)} ${"-".repeat(32)}`);for(let o of e){let t=o.active?"active":"shadowed";r.push(`${b(o.name,22)} ${b(o.scope,8)} ${b(t,9)} ${o.description??""}`)}}if(n.length>0){r.push("","Invalid definitions:");for(let o of n)r.push(`- ${o.path}: ${o.message}`)}return r.join(`
4
4
  `)+`
5
5
  `}function He(e){let n=[`Agent: ${e.name}`,`Scope: ${e.scope}`,`Path: ${e.path}`,`Status: ${e.active?"active":"shadowed"}`];return e.description&&n.push(`Description: ${e.description}`),e.model&&n.push(`Model: ${e.model}`),e.color&&n.push(`Color: ${e.color}`),e.memory&&n.push(`Memory: ${e.memory}`),e.isolation&&n.push(`Isolation: ${e.isolation}`),e.tags.length>0&&n.push(`Tags: ${e.tags.join(", ")}`),e.skills.length>0&&n.push(`Skills: ${e.skills.join(", ")}`),e.hooks.length>0&&n.push(`Hooks: ${e.hooks.join(", ")}`),e.toolPolicy&&n.push(`Tools: ${JSON.stringify(e.toolPolicy)}`),e.shadowedBy&&n.push(`Shadowed by: ${e.shadowedBy.scope} ${e.shadowedBy.path}`),n.push("",e.prompt,""),n.join(`
6
- `)}function Ue(e){let n=e.name.trim().toLowerCase();if(!_(n))throw new Error(`Invalid agent name "${e.name}". Use 1-64 lowercase letters, digits, hyphens, or underscores, starting with a letter.`);let r=e.scope==="user"?L(e.agentHome):oe(e.cwd??process.cwd());(0,y.mkdirSync)(r,{recursive:!0});let o=(0,m.join)(r,`${n}.md`);if((0,y.existsSync)(o)&&!e.force)throw new Error(`Agent definition already exists: ${o}`);let t=e.description?.trim()||`${n} custom agent`,i=e.prompt?.trim()||`You are ${n}. Replace this paragraph with precise operating instructions, constraints, tools policy, verification expectations, and the kind of work this agent should own.`,s=[...["---",`name: ${n}`,`description: ${JSON.stringify(t)}`,...e.model?.trim()?[`model: ${JSON.stringify(e.model.trim())}`]:[],...e.color?.trim()?[`color: ${JSON.stringify(e.color.trim())}`]:[],...e.memory?.trim()?[`memory: ${JSON.stringify(e.memory.trim())}`]:[],...e.isolation?[`isolation: ${e.isolation}`]:[],"tags: []",...e.skills&&e.skills.length>0?[`skills: ${JSON.stringify(e.skills)}`]:[],...e.hooks&&e.hooks.length>0?[`hooks: ${JSON.stringify(e.hooks)}`]:[],...e.toolPolicy?["tools:",...e.toolPolicy.mode?[` mode: ${e.toolPolicy.mode}`]:[],...e.toolPolicy.allow&&e.toolPolicy.allow.length>0?[` allow: ${JSON.stringify(e.toolPolicy.allow)}`]:[],...e.toolPolicy.deny&&e.toolPolicy.deny.length>0?[` deny: ${JSON.stringify(e.toolPolicy.deny)}`]:[]]:[],"---"],"",i,""].join(`
7
- `);return(0,y.writeFileSync)(o,s,"utf8"),o}var ie=require("node:crypto");var N=2,W=["publish","deploy","push","send","purchase","sign","file-legal","change-infrastructure"],P=class extends Error{constructor(n){super(n),this.name="AgentProfileValidationError"}},Ge=/^[a-z][a-z0-9_-]{0,63}$/,C=W;function g(e){return Array.from(new Set((e??[]).map(n=>n.trim()).filter(Boolean)))}function Je(e,n){if(e===void 0)return n===void 0?void 0:g(n);if(n===void 0)return g(e);let r=new Set(n);return g(e.filter(o=>r.has(o)))}function ze(e,n){if(e===void 0)return;let r=new Set(n);return e.filter(o=>!r.has(o))}function B(e,n,r){let o=n===void 0?null:new Set(n),t=new Set(r??[]);return e===void 0?n===void 0?void 0:g(n).filter(i=>!t.has(i)):g(e).filter(i=>(o===null||o.has(i))&&!t.has(i))}function R(e,n,r){return r[e]<=r[n]?e:n}function Xe(e,n,r){return r[e]>=r[n]?e:n}function V(e){return Array.isArray(e)?e.map(V):!e||typeof e!="object"?e:Object.fromEntries(Object.entries(e).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>[n,V(r)]))}function Ye(e){return(0,ie.createHash)("sha256").update(JSON.stringify(V(e))).digest("hex")}function S(e){return structuredClone(e)}function se(e,n){return e.overrides?.[n]??e.default}function Ke(e,n){let r={deny:0,ask:1,allow:2},o=new Set(e.requireCurrentTurnApproval),t=Object.fromEntries(C.map(d=>[d,se(e,d)]));for(let d of n){let p=d.externalActions;if(p){for(let u of C){let c=p.overrides?.[u]??p.default;c&&(t[u]=R(t[u],c,r))}for(let u of p.requireCurrentTurnApproval??[])o.add(u)}}let l=new Set(Object.values(t)).size===1?t.publish:"deny",s={};for(let d of C)t[d]!==l&&(s[d]=t[d]);return{default:l,...Object.keys(s).length>0?{overrides:s}:{},requireCurrentTurnApproval:[...o].filter(d=>t[d]!=="deny").sort()}}function le(e){if(e.schemaVersion!==N)throw new P(`Unsupported agent profile schema: ${String(e.schemaVersion)}.`);if(!Ge.test(e.id))throw new P(`Invalid agent profile id: ${e.id}.`);if(!e.version.trim())throw new P(`Agent profile ${e.id} has no version.`);if(!e.displayName.trim()||!e.description.trim()||!e.prompt.trim())throw new P(`Agent profile ${e.id} requires displayName, description, and prompt.`);if(e.execution.allowedModes.length===0)throw new P(`Agent profile ${e.id} allows no collaboration modes.`);if(!e.execution.allowedModes.includes(e.execution.defaultMode))throw new P(`Agent profile ${e.id} default mode must be included in allowedModes.`)}function Qe(e,n,r,o,t,i){return{name:`agent-profile:${e.id}`,order:20,provide(){let l=C.map(s=>`${s}=${se(n.externalActions,s)}`).join(", ");return["","","# XENO Agent Profile",`Profile: ${e.displayName} (${e.id}@${e.version})`,`Profile fingerprint: ${i}`,`Role: ${e.description}`,`Collaboration mode: ${o.defaultMode}`,`Isolation: ${o.isolation}`,`Memory: ${r.scope}; soul=${r.soul}`,`Permission profile ceiling: ${n.permissionProfile}`,`External actions: ${l}`,n.externalActions.requireCurrentTurnApproval.length>0?`Current-turn approval required for: ${n.externalActions.requireCurrentTurnApproval.join(", ")}`:"Current-turn approval required for: none",t.evidence.length>0?`Completion evidence: ${t.evidence.join(", ")}`:"Completion evidence: task-dependent",t.requirePrimarySources?"Use primary sources for factual claims and cite them near the claim.":"",t.requireCurrentInformation?"Verify time-sensitive claims against current authoritative information.":"",t.requireHumanReview?"Do not represent the result as professional approval; require human review before consequential use.":"",o.defaultDryRun?"Default to preview or dry-run. Do not perform external state changes without the required approval.":"","",e.prompt,"","Stop conditions:",...t.stopConditions.map(s=>`- ${s}`)].filter(s=>s!=="").join(`
8
- `)}}}function ae(e,n={}){le(e);let r=S(e),o=n.boundaries??[],t=S(r.capabilities.tools),i=r.capabilities.skills.allow?g(r.capabilities.skills.allow):void 0,l=new Set(g(r.capabilities.skills.deny)),s=g(r.capabilities.hooks),d=new Set,p=r.capabilities.mcpServers?g(r.capabilities.mcpServers):void 0,u=r.capabilities.delegatedAgents?g(r.capabilities.delegatedAgents):void 0,c=r.capabilities.permissionProfile,f=r.memory.scope,A=r.memory.soul,x=r.execution.isolation,D={"read-only":0,default:1,"trusted-dev":2},fe={none:0,session:1,project:2,user:3},pe={disabled:0,read:1,learn:2},me={none:0,worktree:1,container:2};for(let a of o){a.tools&&(t=I({toolPolicy:t},a.tools)),i=Je(i,a.skills?.allow);for(let O of a.skills?.deny??[])l.add(O);s=B(s,a.hooks?.allow,void 0)??[];for(let O of a.hooks?.require??[])d.add(O);p=B(p,a.mcpServers?.allow,a.mcpServers?.deny),u=B(u,a.delegatedAgents?.allow,a.delegatedAgents?.deny),a.permissionProfile&&(c=R(c,a.permissionProfile,D)),a.maximumMemoryScope&&(f=R(f,a.maximumMemoryScope,fe)),a.maximumSoulMode&&(A=R(A,a.maximumSoulMode,pe)),a.requiredIsolation&&(x=Xe(x,a.requiredIsolation,me))}let H=[...l].sort();c==="read-only"&&(t=I({toolPolicy:t},{mode:"readOnly",deny:["WebSearch","WebFetch"]})),i=ze(i,H);let ge=g(r.capabilities.skills.preload).filter(a=>!l.has(a)).filter(a=>i===void 0||i.includes(a));s=g([...s,...d]);let U={tools:t,skills:{preload:ge,...i!==void 0?{allow:i}:{},deny:H},hooks:s,...p!==void 0?{mcpServers:p}:{},...u!==void 0?{delegatedAgents:u}:{},permissionProfile:c,externalActions:Ke(r.capabilities.externalActions,o)},G={...r.memory,scope:f,soul:A},J={...r.execution,isolation:x},z={schemaVersion:N,profile:r,boundarySources:o.map(a=>a.source),capabilities:U,memory:G,execution:J,completion:r.completion},X=Ye(z);return{...z,fingerprint:X,promptSection:Qe(r,U,G,J,r.completion,X)}}function h(e){return{schemaVersion:N,id:e.id,version:"1.0.0",displayName:e.displayName,description:e.description,kind:e.kind??"primary",prompt:e.prompt,capabilities:{tools:e.toolPolicy??{mode:"inherit"},skills:{preload:e.skills??[],...e.skillAllow?{allow:e.skillAllow}:{},deny:[]},hooks:[],permissionProfile:e.permissionProfile??"default",externalActions:{default:e.externalDefault??"ask",...e.externalOverrides?{overrides:e.externalOverrides}:{},requireCurrentTurnApproval:e.currentTurnApproval??[]}},memory:{scope:e.memoryScope??"project",role:e.id,soul:e.soul??"read"},execution:{defaultMode:e.defaultMode??"chat",allowedModes:e.allowedModes??["chat","plan","execute","review"],isolation:e.isolation??"none",allowBackground:e.allowBackground??!0,planForComplexTasks:e.planForComplexTasks??!0,defaultDryRun:e.defaultDryRun??!1},completion:{evidence:e.evidence??[],requirePrimarySources:e.primarySources??!1,requireCurrentInformation:e.currentInformation??!1,requireHumanReview:e.humanReview??!1,stopConditions:e.stopConditions??["The requested outcome is complete and required evidence has been reported.","A real authorization, information, or external-state blocker prevents safe progress."]},presentation:{label:e.displayName,color:e.color,glyph:e.glyph},tags:g(e.tags)}}var ce=[h({id:"assistant",displayName:"Assistant",description:"General-purpose XENO collaborator for mixed research, planning, and implementation work.",prompt:["Work as a thoughtful generalist. Establish the user's actual outcome, inspect relevant context, and take scoped action.","Escalate into a narrower specialist profile when domain risk or task depth warrants it."].join(`
6
+ `)}function Ue(e){let n=e.name.trim().toLowerCase();if(!_(n))throw new Error(`Invalid agent name "${e.name}". Use 1-64 lowercase letters, digits, hyphens, or underscores, starting with a letter.`);let r=e.scope==="user"?L(e.agentHome):oe(e.cwd??process.cwd());(0,m.mkdirSync)(r,{recursive:!0});let o=(0,p.join)(r,`${n}.md`);if((0,m.existsSync)(o)&&!e.force)throw new Error(`Agent definition already exists: ${o}`);let t=e.description?.trim()||`${n} custom agent`,i=e.prompt?.trim()||`You are ${n}. Replace this paragraph with precise operating instructions, constraints, tools policy, verification expectations, and the kind of work this agent should own.`,s=[...["---",`name: ${n}`,`description: ${JSON.stringify(t)}`,...e.model?.trim()?[`model: ${JSON.stringify(e.model.trim())}`]:[],...e.color?.trim()?[`color: ${JSON.stringify(e.color.trim())}`]:[],...e.memory?.trim()?[`memory: ${JSON.stringify(e.memory.trim())}`]:[],...e.isolation?[`isolation: ${e.isolation}`]:[],"tags: []",...e.skills&&e.skills.length>0?[`skills: ${JSON.stringify(e.skills)}`]:[],...e.hooks&&e.hooks.length>0?[`hooks: ${JSON.stringify(e.hooks)}`]:[],...e.toolPolicy?["tools:",...e.toolPolicy.mode?[` mode: ${e.toolPolicy.mode}`]:[],...e.toolPolicy.allow&&e.toolPolicy.allow.length>0?[` allow: ${JSON.stringify(e.toolPolicy.allow)}`]:[],...e.toolPolicy.deny&&e.toolPolicy.deny.length>0?[` deny: ${JSON.stringify(e.toolPolicy.deny)}`]:[]]:[],"---"],"",i,""].join(`
7
+ `);return(0,m.writeFileSync)(o,s,"utf8"),o}var ie=require("node:crypto");var N=2,W=["publish","deploy","push","send","purchase","sign","file-legal","change-infrastructure"],P=class extends Error{constructor(n){super(n),this.name="AgentProfileValidationError"}},Ge=/^[a-z][a-z0-9_-]{0,63}$/,C=W;function y(e){return Array.from(new Set((e??[]).map(n=>n.trim()).filter(Boolean)))}function Je(e,n){if(e===void 0)return n===void 0?void 0:y(n);if(n===void 0)return y(e);let r=new Set(n);return y(e.filter(o=>r.has(o)))}function ze(e,n){if(e===void 0)return;let r=new Set(n);return e.filter(o=>!r.has(o))}function B(e,n,r){let o=n===void 0?null:new Set(n),t=new Set(r??[]);return e===void 0?n===void 0?void 0:y(n).filter(i=>!t.has(i)):y(e).filter(i=>(o===null||o.has(i))&&!t.has(i))}function R(e,n,r){return r[e]<=r[n]?e:n}function Xe(e,n,r){return r[e]>=r[n]?e:n}function V(e){return Array.isArray(e)?e.map(V):!e||typeof e!="object"?e:Object.fromEntries(Object.entries(e).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>[n,V(r)]))}function Ye(e){return(0,ie.createHash)("sha256").update(JSON.stringify(V(e))).digest("hex")}function S(e){return structuredClone(e)}function se(e,n){return e.overrides?.[n]??e.default}function Ke(e,n){let r={deny:0,ask:1,allow:2},o=new Set(e.requireCurrentTurnApproval),t=Object.fromEntries(C.map(d=>[d,se(e,d)]));for(let d of n){let g=d.externalActions;if(g){for(let u of C){let c=g.overrides?.[u]??g.default;c&&(t[u]=R(t[u],c,r))}for(let u of g.requireCurrentTurnApproval??[])o.add(u)}}let l=new Set(Object.values(t)).size===1?t.publish:"deny",s={};for(let d of C)t[d]!==l&&(s[d]=t[d]);return{default:l,...Object.keys(s).length>0?{overrides:s}:{},requireCurrentTurnApproval:[...o].filter(d=>t[d]!=="deny").sort()}}function le(e){if(e.schemaVersion!==N)throw new P(`Unsupported agent profile schema: ${String(e.schemaVersion)}.`);if(!Ge.test(e.id))throw new P(`Invalid agent profile id: ${e.id}.`);if(!e.version.trim())throw new P(`Agent profile ${e.id} has no version.`);if(!e.displayName.trim()||!e.description.trim()||!e.prompt.trim())throw new P(`Agent profile ${e.id} requires displayName, description, and prompt.`);if(e.execution.allowedModes.length===0)throw new P(`Agent profile ${e.id} allows no collaboration modes.`);if(!e.execution.allowedModes.includes(e.execution.defaultMode))throw new P(`Agent profile ${e.id} default mode must be included in allowedModes.`)}function Qe(e,n,r,o,t,i){return{name:`agent-profile:${e.id}`,order:20,provide(){let l=C.map(s=>`${s}=${se(n.externalActions,s)}`).join(", ");return["","","# XENO Agent Profile",`Profile: ${e.displayName} (${e.id}@${e.version})`,`Profile fingerprint: ${i}`,`Role: ${e.description}`,`Collaboration mode: ${o.defaultMode}`,`Isolation: ${o.isolation}`,`Memory: ${r.scope}; soul=${r.soul}`,`Permission profile ceiling: ${n.permissionProfile}`,`External actions: ${l}`,n.externalActions.requireCurrentTurnApproval.length>0?`Current-turn approval required for: ${n.externalActions.requireCurrentTurnApproval.join(", ")}`:"Current-turn approval required for: none",t.evidence.length>0?`Completion evidence: ${t.evidence.join(", ")}`:"Completion evidence: task-dependent",t.requirePrimarySources?"Use primary sources for factual claims and cite them near the claim.":"",t.requireCurrentInformation?"Verify time-sensitive claims against current authoritative information.":"",t.requireHumanReview?"Do not represent the result as professional approval; require human review before consequential use.":"",o.defaultDryRun?"Default to preview or dry-run. Do not perform external state changes without the required approval.":"","",e.prompt,"","Stop conditions:",...t.stopConditions.map(s=>`- ${s}`)].filter(s=>s!=="").join(`
8
+ `)}}}function ae(e,n={}){le(e);let r=S(e),o=n.boundaries??[],t=S(r.capabilities.tools),i=r.capabilities.skills.allow?y(r.capabilities.skills.allow):void 0,l=new Set(y(r.capabilities.skills.deny)),s=y(r.capabilities.hooks),d=new Set,g=r.capabilities.mcpServers?y(r.capabilities.mcpServers):void 0,u=r.capabilities.delegatedAgents?y(r.capabilities.delegatedAgents):void 0,c=r.capabilities.permissionProfile,f=r.memory.scope,A=r.memory.soul,x=r.execution.isolation,D={"read-only":0,default:1,"trusted-dev":2},fe={none:0,session:1,project:2,user:3},pe={disabled:0,read:1,learn:2},ge={none:0,worktree:1,container:2};for(let a of o){a.tools&&(t=I({toolPolicy:t},a.tools)),i=Je(i,a.skills?.allow);for(let O of a.skills?.deny??[])l.add(O);s=B(s,a.hooks?.allow,void 0)??[];for(let O of a.hooks?.require??[])d.add(O);g=B(g,a.mcpServers?.allow,a.mcpServers?.deny),u=B(u,a.delegatedAgents?.allow,a.delegatedAgents?.deny),a.permissionProfile&&(c=R(c,a.permissionProfile,D)),a.maximumMemoryScope&&(f=R(f,a.maximumMemoryScope,fe)),a.maximumSoulMode&&(A=R(A,a.maximumSoulMode,pe)),a.requiredIsolation&&(x=Xe(x,a.requiredIsolation,ge))}let H=[...l].sort();c==="read-only"&&(t=I({toolPolicy:t},{mode:"readOnly",deny:["WebSearch","WebFetch"]})),i=ze(i,H);let me=y(r.capabilities.skills.preload).filter(a=>!l.has(a)).filter(a=>i===void 0||i.includes(a));s=y([...s,...d]);let U={tools:t,skills:{preload:me,...i!==void 0?{allow:i}:{},deny:H},hooks:s,...g!==void 0?{mcpServers:g}:{},...u!==void 0?{delegatedAgents:u}:{},permissionProfile:c,externalActions:Ke(r.capabilities.externalActions,o)},G={...r.memory,scope:f,soul:A},J={...r.execution,isolation:x},z={schemaVersion:N,profile:r,boundarySources:o.map(a=>a.source),capabilities:U,memory:G,execution:J,completion:r.completion},X=Ye(z);return{...z,fingerprint:X,promptSection:Qe(r,U,G,J,r.completion,X)}}function h(e){return{schemaVersion:N,id:e.id,version:"1.0.0",displayName:e.displayName,description:e.description,kind:e.kind??"primary",prompt:e.prompt,capabilities:{tools:e.toolPolicy??{mode:"inherit"},skills:{preload:e.skills??[],...e.skillAllow?{allow:e.skillAllow}:{},deny:[]},hooks:[],permissionProfile:e.permissionProfile??"default",externalActions:{default:e.externalDefault??"ask",...e.externalOverrides?{overrides:e.externalOverrides}:{},requireCurrentTurnApproval:e.currentTurnApproval??[]}},memory:{scope:e.memoryScope??"project",role:e.id,soul:e.soul??"read"},execution:{defaultMode:e.defaultMode??"chat",allowedModes:e.allowedModes??["chat","plan","execute","review"],isolation:e.isolation??"none",allowBackground:e.allowBackground??!0,planForComplexTasks:e.planForComplexTasks??!0,defaultDryRun:e.defaultDryRun??!1},completion:{evidence:e.evidence??[],requirePrimarySources:e.primarySources??!1,requireCurrentInformation:e.currentInformation??!1,requireHumanReview:e.humanReview??!1,stopConditions:e.stopConditions??["The requested outcome is complete and required evidence has been reported.","A real authorization, information, or external-state blocker prevents safe progress."]},presentation:{label:e.displayName,color:e.color,glyph:e.glyph},tags:y(e.tags)}}var ce=[h({id:"assistant",displayName:"Assistant",description:"General-purpose XENO collaborator for mixed research, planning, and implementation work.",prompt:["Work as a thoughtful generalist. Establish the user's actual outcome, inspect relevant context, and take scoped action.","Escalate into a narrower specialist profile when domain risk or task depth warrants it."].join(`
9
9
  `),toolPolicy:{mode:"inherit"},skills:[],memoryScope:"user",evidence:["file-references"],currentTurnApproval:[...W],color:"cyan",glyph:"\u25A0",tags:["general","primary"]}),h({id:"swe",displayName:"Software Engineer",description:"Repository-aware software engineer for careful implementation, debugging, refactoring, and verification.",prompt:["Inspect the repository before editing. Follow project instructions and preserve unrelated work.","Trace the smallest root cause, implement the narrowest coherent change, and verify from focused checks outward.","Do not claim completion without concrete test, typecheck, build, or runtime evidence appropriate to the risk."].join(`
10
10
  `),toolPolicy:{mode:"default"},skills:["debug","run","verify"],permissionProfile:"trusted-dev",soul:"learn",evidence:["file-references","tests","typecheck","build","diff"],currentTurnApproval:["publish","deploy","push","change-infrastructure"],color:"green",glyph:"\u25C6",tags:["engineering","implementation"]}),h({id:"reviewer",displayName:"Code Reviewer",description:"Read-only reviewer focused on correctness, regressions, safety, tests, and maintainability.",prompt:["Lead with concrete findings ordered by severity. Cite exact file locations and explain impact.","Do not edit code. Distinguish confirmed defects from risks and questions. State when no material finding is present."].join(`
11
11
  `),kind:"subagent",toolPolicy:{mode:"readOnly"},skills:["code-review","verify"],permissionProfile:"read-only",memoryScope:"session",soul:"read",allowedModes:["chat","review"],defaultMode:"review",evidence:["file-references","diff"],externalDefault:"deny",color:"yellow",glyph:"\u25C7",tags:["engineering","review","read-only"]}),h({id:"writer",displayName:"Writer",description:"Audience-aware writer and editor for clear, accurate, structurally coherent content.",prompt:["Determine audience, purpose, voice, format, and source constraints before drafting.","Preserve factual meaning, avoid invented claims, and revise for clarity, rhythm, consistency, and usefulness."].join(`
@@ -1,17 +1,17 @@
1
- import{existsSync as C,mkdirSync as pe,readFileSync as me,readdirSync as ge,writeFileSync as ye}from"node:fs";import{basename as he,dirname as Ae,join as b,parse as Pe,resolve as we}from"node:path";function W(e){let n=ae(e);return{frontmatter:n.frontmatter,content:n.content.trim()}}function ae(e){let n=e.replace(/^\uFEFF/,"");if(!n.startsWith("---"))return{frontmatter:{},content:e};let r=n.search(/\r?\n/);if(r<0||n.slice(0,r).trim()!=="---")return{frontmatter:{},content:e};let o=n.slice(r+(n[r]==="\r"?2:1)),t=o.match(/(?:^|\r?\n)---[ \t]*(?:\r?\n|$)/);if(!t||t.index===void 0)throw new Error("YAML frontmatter is not closed.");let i=o.slice(0,t.index),l=t[0],s=t.index+l.length;return{frontmatter:H(i),content:o.slice(s)}}function H(e){let n={},r=e.split(/\r?\n/);for(let o=0;o<r.length;o+=1){let t=r[o];if(!t.trim()||t.trimStart().startsWith("#"))continue;if(/^\s/.test(t))throw new Error(`Unexpected indentation at line ${o+1}.`);let i=de(t,o+1);if(i.key==="<<")throw new Error("YAML merge keys are not supported.");if(i.value!==""){n[i.key]=U(i.value,o+1);continue}let l=ce(r,o+1);n[i.key]=l.value,o=l.nextIndex-1}return n}function ce(e,n){let r=[],o=n;for(;o<e.length;o+=1){let i=e[o];if(!i.trim()){r.push(i);continue}if(!/^\s/.test(i))break;r.push(i.replace(/^ {2}/,""))}let t=r.filter(i=>i.trim()&&!i.trimStart().startsWith("#"));return t.length===0?{value:{},nextIndex:o}:t.every(i=>i.trimStart().startsWith("- "))?{value:t.map((i,l)=>U(i.trimStart().slice(2),n+l+1)),nextIndex:o}:{value:H(r.join(`
2
- `)),nextIndex:o}}function de(e,n){let r=e.indexOf(":");if(r<=0)throw new Error(`Invalid YAML line ${n}.`);let o=e.slice(0,r).trim(),t=e.slice(r+1).trim();if(!o)throw new Error(`Invalid YAML key at line ${n}.`);return{key:o,value:t}}function U(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 V(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 V(e,n);if(e.includes("[")||e.includes("]")||e.includes("{")||e.includes("}"))throw new Error(`Unsupported YAML scalar at line ${n}.`);return e}function V(e,n){try{return JSON.parse(e)}catch{throw new Error(`Invalid YAML scalar at line ${n}.`)}}import{homedir as J,platform as ue,release as fe}from"node:os";import{resolve as G}from"node:path";var en=ue();var nn=fe(),rn=J();function z(){let e=process.env.XENO_AGENT_HOME?.trim();return e?G(e):G(J(),".xeno-agent")}var xe=/^[a-z][a-z0-9_-]{0,63}$/;function be(){return z()}function Y(e=be()){return b(e,"agents")}function K(e){return we(e)}function ke(e){let n=Ae(e);return n===e?e:n}function ve(e=process.cwd()){let n=K(e),r=[],o=n;for(;;){let t=b(o,".xeno","agents");C(t)&&r.push(t);let i=ke(o);if(i===o)break;o=i}return r.reverse()}function Se(e=process.cwd()){return b(K(e),".xeno","agents")}function De(e){return C(e)?ge(e,{withFileTypes:!0}).filter(n=>n.isFile()&&n.name.toLowerCase().endsWith(".md")).map(n=>b(e,n.name)).sort((n,r)=>n.localeCompare(r)):[]}function w(e){if(typeof e!="string")return;let n=e.trim();return n.length>0?n:void 0}function x(e){return Array.isArray(e)?e.map(n=>String(n).trim()).filter(Boolean):typeof e=="string"?e.split(",").map(n=>n.trim()).filter(Boolean):[]}function Ee(e){if(typeof e=="boolean")return e;if(typeof e!="string")return;let n=e.trim().toLowerCase();if(["1","true","yes","on"].includes(n))return!0;if(["0","false","no","off"].includes(n))return!1}function $e(e){return Pe(he(e)).name.toLowerCase()}function Q(e){return xe.test(e)}function Te(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ie(e){if(typeof e!="string")return;let n=e.trim().toLowerCase();if(n==="inherit")return"inherit";if(n==="none"||n==="off"||n==="disabled")return"none";if(n==="read"||n==="readonly"||n==="read-only")return"readOnly";if(n==="default"||n==="standard")return"default";if(n==="full"||n==="fullaccess"||n==="full-access")return"fullAccess"}function Ce(e){if(e===void 0)return;if(typeof e=="string"||Array.isArray(e)){let i=x(e);return i.length>0?{allow:i}:void 0}if(!Te(e))return;let n=x(e.allow),r=x(e.deny),o=Ie(e.mode),t={};return o&&(t.mode=o),n.length>0&&(t.allow=n),r.length>0&&(t.deny=r),Object.keys(t).length>0?t:void 0}function Re(e){let n=Ee(e.worktree??e.defaultWorktreeIsolation);if(n===!0)return"worktree";if(n===!1)return"none";let r=w(e.isolation)?.toLowerCase();if(r==="worktree")return"worktree";if(r==="none"||r==="off"||r==="disabled")return"none"}function Ne(e){let n=[];return Q(e.name)||n.push(`Invalid agent name "${e.name}". Use 1-64 lowercase letters, digits, hyphens, or underscores, starting with a letter.`),e.prompt.trim().length===0&&n.push("Agent definition body is empty."),n}function Oe(e,n,r){let o=me(e,"utf8"),t=W(o),i=t.frontmatter,l=$e(e),s=w(i.name)?.toLowerCase()??l,d=t.content.trim(),p=Ne({name:s,prompt:d});if(p.length>0)throw new Error(p.join(" "));let u=w(i.description),c=w(i.model),f=w(i.color),y=w(i.memory??i.memoryScope),A=Re(i),v=Ce(i.tools);return{name:s,scope:n,path:e,...u?{description:u}:{},...c?{model:c}:{},...f?{color:f}:{},...y?{memory:y}:{},...A?{isolation:A}:{},tags:x(i.tags),skills:x(i.skills),hooks:x(i.hooks),prompt:d,active:!0,priority:r,...v?{toolPolicy:v}:{}}}function S(e,n,r,o,t){for(let i of De(e))try{o.push(Oe(i,n,r))}catch(l){t.push({path:i,scope:n,message:l instanceof Error?l.message:String(l)})}}function Me(e){let n=new Map;for(let r of e){let o=n.get(r.name);(!o||r.priority>o.priority)&&n.set(r.name,r)}return n}function je(e,n){let r=n.get(e.name),o=r?.path===e.path;return{name:e.name,scope:e.scope,path:e.path,...e.description?{description:e.description}:{},...e.model?{model:e.model}:{},...e.color?{color:e.color}:{},...e.memory?{memory:e.memory}:{},...e.isolation?{isolation:e.isolation}:{},tags:e.tags,skills:e.skills,hooks:e.hooks,prompt:e.prompt,active:o,...e.toolPolicy?{toolPolicy:e.toolPolicy}:{},...!o&&r?{shadowedBy:{name:r.name,scope:r.scope,path:r.path}}:{}}}function Z(e=process.cwd(),n={}){let r=n.cwd??e,o=n.userDir??Y(n.agentHome),t=n.projectDirs??ve(r),i=n.pluginDirs??[],l=n.builtInDirs??[],s=[],d=[];n.includeUser!==!1&&S(o,"user",0,s,d),n.includeProject!==!1&&t.forEach((c,f)=>S(c,"project",100+f,s,d)),n.includePlugins&&i.forEach((c,f)=>S(c,"plugin",1e3+f,s,d)),n.includeBuiltIns&&l.forEach((c,f)=>S(c,"built-in",2e3+f,s,d));let p=Me(s),u=s.map(c=>je(c,p));return u.sort((c,f)=>{if(c.active!==f.active)return c.active?-1:1;let y=c.name.localeCompare(f.name);return y!==0?y:c.path.localeCompare(f.path)}),{definitions:u,issues:d,searchPaths:{...n.includeUser!==!1?{user:o}:{},project:n.includeProject===!1?[]:t,plugin:n.includePlugins?i:[],builtIn:n.includeBuiltIns?l:[]}}}function cn(e,n=process.cwd(),r={}){let o=e.trim().toLowerCase(),t=Z(n,r);return{definition:t.definitions.find(i=>i.active&&i.name===o)??null,scan:t}}var I=class{constructor(n={}){this.options=n}options;scan(n=this.options.cwd??process.cwd()){return Z(n,this.options)}},X=class{constructor(n=new I){this.loader=n}loader;resolve(n,r=process.cwd()){let o=this.loader.scan(r),t=n.trim().toLowerCase();return{definition:o.definitions.find(i=>i.active&&i.name===t)??null,scan:o}}};function D(e){if(!e||e.length===0)return;let n=Array.from(new Set(e.map(r=>r.trim()).filter(Boolean)));return n.length>0?n:void 0}function qe(e,n){if(!e&&!n)return;if(!e)return D(n);if(!n)return D(e);let r=new Set(n);return D(e.filter(o=>r.has(o)))}function Le(e,n){let r={none:0,readOnly:1,default:2,fullAccess:3,inherit:4},o=n??"inherit",t=e??"inherit";return r[o]<=r[t]?o:t}function R(e,n={}){let r=e.toolPolicy??{},o={mode:Le(r.mode,n.mode)},t=qe(n.allow,r.allow),i=D([...n.deny??[],...r.deny??[]]);return t&&(o.allow=t),i&&(o.deny=i),o}function dn(e){return{name:`custom-agent:${e.name}`,order:20,provide(){let n=["","","# Custom Agent",`Active agent: ${e.name}`,`Definition scope: ${e.scope}`,`Definition path: ${e.path}`];return e.description&&n.push(`Description: ${e.description}`),n.push("",e.prompt),n.join(`
3
- `)}}}function un(e){return{name:e.name,scope:e.scope,path:e.path,...e.description?{description:e.description}:{},...e.model?{model:e.model}:{},...e.color?{color:e.color}:{},...e.memory?{memory:e.memory}:{},...e.isolation?{isolation:e.isolation}:{},tags:e.tags,skills:e.skills,hooks:e.hooks,active:e.active,...e.toolPolicy?{toolPolicy:e.toolPolicy}:{},...e.shadowedBy?{shadowedBy:e.shadowedBy}:{}}}function P(e,n){return e.length>=n?e:e+" ".repeat(n-e.length)}function fn(e,n){let r=[];if(e.length===0)r.push("No custom agent definitions found.");else{r.push(`${P("name",22)} ${P("scope",8)} ${P("status",9)} description`),r.push(`${"-".repeat(22)} ${"-".repeat(8)} ${"-".repeat(9)} ${"-".repeat(32)}`);for(let o of e){let t=o.active?"active":"shadowed";r.push(`${P(o.name,22)} ${P(o.scope,8)} ${P(t,9)} ${o.description??""}`)}}if(n.length>0){r.push("","Invalid definitions:");for(let o of n)r.push(`- ${o.path}: ${o.message}`)}return r.join(`
1
+ import{existsSync as E,mkdirSync as pe,readFileSync as ge,readdirSync as me,writeFileSync as ye}from"node:fs";import{basename as he,dirname as Ae,join as b,parse as Pe,resolve as we}from"node:path";function W(e){let n=ae(e);return{frontmatter:n.frontmatter,content:n.content.trim()}}function ae(e){let n=e.replace(/^\uFEFF/,"");if(!n.startsWith("---"))return{frontmatter:{},content:e};let r=n.search(/\r?\n/);if(r<0||n.slice(0,r).trim()!=="---")return{frontmatter:{},content:e};let o=n.slice(r+(n[r]==="\r"?2:1)),i=o.match(/(?:^|\r?\n)---[ \t]*(?:\r?\n|$)/);if(!i||i.index===void 0)throw new Error("YAML frontmatter is not closed.");let t=o.slice(0,i.index),l=i[0],s=i.index+l.length;return{frontmatter:H(t),content:o.slice(s)}}function H(e){let n={},r=e.split(/\r?\n/);for(let o=0;o<r.length;o+=1){let i=r[o];if(!i.trim()||i.trimStart().startsWith("#"))continue;if(/^\s/.test(i))throw new Error(`Unexpected indentation at line ${o+1}.`);let t=de(i,o+1);if(t.key==="<<")throw new Error("YAML merge keys are not supported.");if(t.value!==""){n[t.key]=U(t.value,o+1);continue}let l=ce(r,o+1);n[t.key]=l.value,o=l.nextIndex-1}return n}function ce(e,n){let r=[],o=n;for(;o<e.length;o+=1){let t=e[o];if(!t.trim()){r.push(t);continue}if(!/^\s/.test(t))break;r.push(t.replace(/^ {2}/,""))}let i=r.filter(t=>t.trim()&&!t.trimStart().startsWith("#"));return i.length===0?{value:{},nextIndex:o}:i.every(t=>t.trimStart().startsWith("- "))?{value:i.map((t,l)=>U(t.trimStart().slice(2),n+l+1)),nextIndex:o}:{value:H(r.join(`
2
+ `)),nextIndex:o}}function de(e,n){let r=e.indexOf(":");if(r<=0)throw new Error(`Invalid YAML line ${n}.`);let o=e.slice(0,r).trim(),i=e.slice(r+1).trim();if(!o)throw new Error(`Invalid YAML key at line ${n}.`);return{key:o,value:i}}function U(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 V(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 V(e,n);if(e.includes("[")||e.includes("]")||e.includes("{")||e.includes("}"))throw new Error(`Unsupported YAML scalar at line ${n}.`);return e}function V(e,n){try{return JSON.parse(e)}catch{throw new Error(`Invalid YAML scalar at line ${n}.`)}}import{homedir as J,platform as ue,release as fe}from"node:os";import{resolve as G}from"node:path";var en=ue();var nn=fe(),rn=J();function z(){let e=process.env.XENO_AGENT_HOME?.trim();return e?G(e):G(J(),".xeno-agent")}var xe=/^[a-z][a-z0-9_-]{0,63}$/;function be(){return z()}function Y(e=be()){return b(e,"agents")}function K(e){return we(e)}function ke(e){let n=Ae(e);return n===e?e:n}function ve(e=process.cwd()){let n=K(e),r=[],o=n;for(;;){let t=b(o,".claude","agents"),l=b(o,".xeno","agents");r.push({...E(t)?{claude:t}:{},...E(l)?{xeno:l}:{}});let s=ke(o);if(s===o)break;o=s}r.reverse();let i=[];for(let t of r)t.claude&&i.push(t.claude),t.xeno&&i.push(t.xeno);return i}function Se(e=process.cwd()){return b(K(e),".xeno","agents")}function De(e){return E(e)?me(e,{withFileTypes:!0}).filter(n=>n.isFile()&&n.name.toLowerCase().endsWith(".md")).map(n=>b(e,n.name)).sort((n,r)=>n.localeCompare(r)):[]}function w(e){if(typeof e!="string")return;let n=e.trim();return n.length>0?n:void 0}function x(e){return Array.isArray(e)?e.map(n=>String(n).trim()).filter(Boolean):typeof e=="string"?e.split(",").map(n=>n.trim()).filter(Boolean):[]}function Ee(e){if(typeof e=="boolean")return e;if(typeof e!="string")return;let n=e.trim().toLowerCase();if(["1","true","yes","on"].includes(n))return!0;if(["0","false","no","off"].includes(n))return!1}function $e(e){return Pe(he(e)).name.toLowerCase()}function Q(e){return xe.test(e)}function Te(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ie(e){if(typeof e!="string")return;let n=e.trim().toLowerCase();if(n==="inherit")return"inherit";if(n==="none"||n==="off"||n==="disabled")return"none";if(n==="read"||n==="readonly"||n==="read-only")return"readOnly";if(n==="default"||n==="standard")return"default";if(n==="full"||n==="fullaccess"||n==="full-access")return"fullAccess"}function Ce(e){if(e===void 0)return;if(typeof e=="string"||Array.isArray(e)){let t=x(e);return t.length>0?{allow:t}:void 0}if(!Te(e))return;let n=x(e.allow),r=x(e.deny),o=Ie(e.mode),i={};return o&&(i.mode=o),n.length>0&&(i.allow=n),r.length>0&&(i.deny=r),Object.keys(i).length>0?i:void 0}function Re(e){let n=Ee(e.worktree??e.defaultWorktreeIsolation);if(n===!0)return"worktree";if(n===!1)return"none";let r=w(e.isolation)?.toLowerCase();if(r==="worktree")return"worktree";if(r==="none"||r==="off"||r==="disabled")return"none"}function Ne(e){let n=[];return Q(e.name)||n.push(`Invalid agent name "${e.name}". Use 1-64 lowercase letters, digits, hyphens, or underscores, starting with a letter.`),e.prompt.trim().length===0&&n.push("Agent definition body is empty."),n}function Oe(e,n,r){let o=ge(e,"utf8"),i=W(o),t=i.frontmatter,l=$e(e),s=w(t.name)?.toLowerCase()??l,d=i.content.trim(),p=Ne({name:s,prompt:d});if(p.length>0)throw new Error(p.join(" "));let u=w(t.description),c=w(t.model),f=w(t.color),y=w(t.memory??t.memoryScope),A=Re(t),v=Ce(t.tools);return{name:s,scope:n,path:e,...u?{description:u}:{},...c?{model:c}:{},...f?{color:f}:{},...y?{memory:y}:{},...A?{isolation:A}:{},tags:x(t.tags),skills:x(t.skills),hooks:x(t.hooks),prompt:d,active:!0,priority:r,...v?{toolPolicy:v}:{}}}function S(e,n,r,o,i){for(let t of De(e))try{o.push(Oe(t,n,r))}catch(l){i.push({path:t,scope:n,message:l instanceof Error?l.message:String(l)})}}function Me(e){let n=new Map;for(let r of e){let o=n.get(r.name);(!o||r.priority>o.priority)&&n.set(r.name,r)}return n}function je(e,n){let r=n.get(e.name),o=r?.path===e.path;return{name:e.name,scope:e.scope,path:e.path,...e.description?{description:e.description}:{},...e.model?{model:e.model}:{},...e.color?{color:e.color}:{},...e.memory?{memory:e.memory}:{},...e.isolation?{isolation:e.isolation}:{},tags:e.tags,skills:e.skills,hooks:e.hooks,prompt:e.prompt,active:o,...e.toolPolicy?{toolPolicy:e.toolPolicy}:{},...!o&&r?{shadowedBy:{name:r.name,scope:r.scope,path:r.path}}:{}}}function Z(e=process.cwd(),n={}){let r=n.cwd??e,o=n.userDir??Y(n.agentHome),i=n.projectDirs??ve(r),t=n.pluginDirs??[],l=n.builtInDirs??[],s=[],d=[];n.includeUser!==!1&&S(o,"user",0,s,d),n.includeProject!==!1&&i.forEach((c,f)=>S(c,"project",100+f,s,d)),n.includePlugins&&t.forEach((c,f)=>S(c,"plugin",1e3+f,s,d)),n.includeBuiltIns&&l.forEach((c,f)=>S(c,"built-in",2e3+f,s,d));let p=Me(s),u=s.map(c=>je(c,p));return u.sort((c,f)=>{if(c.active!==f.active)return c.active?-1:1;let y=c.name.localeCompare(f.name);return y!==0?y:c.path.localeCompare(f.path)}),{definitions:u,issues:d,searchPaths:{...n.includeUser!==!1?{user:o}:{},project:n.includeProject===!1?[]:i,plugin:n.includePlugins?t:[],builtIn:n.includeBuiltIns?l:[]}}}function cn(e,n=process.cwd(),r={}){let o=e.trim().toLowerCase(),i=Z(n,r);return{definition:i.definitions.find(t=>t.active&&t.name===o)??null,scan:i}}var C=class{constructor(n={}){this.options=n}options;scan(n=this.options.cwd??process.cwd()){return Z(n,this.options)}},X=class{constructor(n=new C){this.loader=n}loader;resolve(n,r=process.cwd()){let o=this.loader.scan(r),i=n.trim().toLowerCase();return{definition:o.definitions.find(t=>t.active&&t.name===i)??null,scan:o}}};function D(e){if(!e||e.length===0)return;let n=Array.from(new Set(e.map(r=>r.trim()).filter(Boolean)));return n.length>0?n:void 0}function qe(e,n){if(!e&&!n)return;if(!e)return D(n);if(!n)return D(e);let r=new Set(n);return D(e.filter(o=>r.has(o)))}function Le(e,n){let r={none:0,readOnly:1,default:2,fullAccess:3,inherit:4},o=n??"inherit",i=e??"inherit";return r[o]<=r[i]?o:i}function R(e,n={}){let r=e.toolPolicy??{},o={mode:Le(r.mode,n.mode)},i=qe(n.allow,r.allow),t=D([...n.deny??[],...r.deny??[]]);return i&&(o.allow=i),t&&(o.deny=t),o}function dn(e){return{name:`custom-agent:${e.name}`,order:20,provide(){let n=["","","# Custom Agent",`Active agent: ${e.name}`,`Definition scope: ${e.scope}`,`Definition path: ${e.path}`];return e.description&&n.push(`Description: ${e.description}`),n.push("",e.prompt),n.join(`
3
+ `)}}}function un(e){return{name:e.name,scope:e.scope,path:e.path,...e.description?{description:e.description}:{},...e.model?{model:e.model}:{},...e.color?{color:e.color}:{},...e.memory?{memory:e.memory}:{},...e.isolation?{isolation:e.isolation}:{},tags:e.tags,skills:e.skills,hooks:e.hooks,active:e.active,...e.toolPolicy?{toolPolicy:e.toolPolicy}:{},...e.shadowedBy?{shadowedBy:e.shadowedBy}:{}}}function P(e,n){return e.length>=n?e:e+" ".repeat(n-e.length)}function fn(e,n){let r=[];if(e.length===0)r.push("No custom agent definitions found.");else{r.push(`${P("name",22)} ${P("scope",8)} ${P("status",9)} description`),r.push(`${"-".repeat(22)} ${"-".repeat(8)} ${"-".repeat(9)} ${"-".repeat(32)}`);for(let o of e){let i=o.active?"active":"shadowed";r.push(`${P(o.name,22)} ${P(o.scope,8)} ${P(i,9)} ${o.description??""}`)}}if(n.length>0){r.push("","Invalid definitions:");for(let o of n)r.push(`- ${o.path}: ${o.message}`)}return r.join(`
4
4
  `)+`
5
5
  `}function pn(e){let n=[`Agent: ${e.name}`,`Scope: ${e.scope}`,`Path: ${e.path}`,`Status: ${e.active?"active":"shadowed"}`];return e.description&&n.push(`Description: ${e.description}`),e.model&&n.push(`Model: ${e.model}`),e.color&&n.push(`Color: ${e.color}`),e.memory&&n.push(`Memory: ${e.memory}`),e.isolation&&n.push(`Isolation: ${e.isolation}`),e.tags.length>0&&n.push(`Tags: ${e.tags.join(", ")}`),e.skills.length>0&&n.push(`Skills: ${e.skills.join(", ")}`),e.hooks.length>0&&n.push(`Hooks: ${e.hooks.join(", ")}`),e.toolPolicy&&n.push(`Tools: ${JSON.stringify(e.toolPolicy)}`),e.shadowedBy&&n.push(`Shadowed by: ${e.shadowedBy.scope} ${e.shadowedBy.path}`),n.push("",e.prompt,""),n.join(`
6
- `)}function mn(e){let n=e.name.trim().toLowerCase();if(!Q(n))throw new Error(`Invalid agent name "${e.name}". Use 1-64 lowercase letters, digits, hyphens, or underscores, starting with a letter.`);let r=e.scope==="user"?Y(e.agentHome):Se(e.cwd??process.cwd());pe(r,{recursive:!0});let o=b(r,`${n}.md`);if(C(o)&&!e.force)throw new Error(`Agent definition already exists: ${o}`);let t=e.description?.trim()||`${n} custom agent`,i=e.prompt?.trim()||`You are ${n}. Replace this paragraph with precise operating instructions, constraints, tools policy, verification expectations, and the kind of work this agent should own.`,s=[...["---",`name: ${n}`,`description: ${JSON.stringify(t)}`,...e.model?.trim()?[`model: ${JSON.stringify(e.model.trim())}`]:[],...e.color?.trim()?[`color: ${JSON.stringify(e.color.trim())}`]:[],...e.memory?.trim()?[`memory: ${JSON.stringify(e.memory.trim())}`]:[],...e.isolation?[`isolation: ${e.isolation}`]:[],"tags: []",...e.skills&&e.skills.length>0?[`skills: ${JSON.stringify(e.skills)}`]:[],...e.hooks&&e.hooks.length>0?[`hooks: ${JSON.stringify(e.hooks)}`]:[],...e.toolPolicy?["tools:",...e.toolPolicy.mode?[` mode: ${e.toolPolicy.mode}`]:[],...e.toolPolicy.allow&&e.toolPolicy.allow.length>0?[` allow: ${JSON.stringify(e.toolPolicy.allow)}`]:[],...e.toolPolicy.deny&&e.toolPolicy.deny.length>0?[` deny: ${JSON.stringify(e.toolPolicy.deny)}`]:[]]:[],"---"],"",i,""].join(`
7
- `);return ye(o,s,"utf8"),o}import{createHash as _e}from"node:crypto";var M=2,ee=["publish","deploy","push","send","purchase","sign","file-legal","change-infrastructure"],h=class extends Error{constructor(n){super(n),this.name="AgentProfileValidationError"}},Fe=/^[a-z][a-z0-9_-]{0,63}$/,E=ee;function m(e){return Array.from(new Set((e??[]).map(n=>n.trim()).filter(Boolean)))}function Be(e,n){if(e===void 0)return n===void 0?void 0:m(n);if(n===void 0)return m(e);let r=new Set(n);return m(e.filter(o=>r.has(o)))}function Ve(e,n){if(e===void 0)return;let r=new Set(n);return e.filter(o=>!r.has(o))}function N(e,n,r){let o=n===void 0?null:new Set(n),t=new Set(r??[]);return e===void 0?n===void 0?void 0:m(n).filter(i=>!t.has(i)):m(e).filter(i=>(o===null||o.has(i))&&!t.has(i))}function $(e,n,r){return r[e]<=r[n]?e:n}function We(e,n,r){return r[e]>=r[n]?e:n}function O(e){return Array.isArray(e)?e.map(O):!e||typeof e!="object"?e:Object.fromEntries(Object.entries(e).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>[n,O(r)]))}function He(e){return _e("sha256").update(JSON.stringify(O(e))).digest("hex")}function k(e){return structuredClone(e)}function ne(e,n){return e.overrides?.[n]??e.default}function Ue(e,n){let r={deny:0,ask:1,allow:2},o=new Set(e.requireCurrentTurnApproval),t=Object.fromEntries(E.map(d=>[d,ne(e,d)]));for(let d of n){let p=d.externalActions;if(p){for(let u of E){let c=p.overrides?.[u]??p.default;c&&(t[u]=$(t[u],c,r))}for(let u of p.requireCurrentTurnApproval??[])o.add(u)}}let l=new Set(Object.values(t)).size===1?t.publish:"deny",s={};for(let d of E)t[d]!==l&&(s[d]=t[d]);return{default:l,...Object.keys(s).length>0?{overrides:s}:{},requireCurrentTurnApproval:[...o].filter(d=>t[d]!=="deny").sort()}}function re(e){if(e.schemaVersion!==M)throw new h(`Unsupported agent profile schema: ${String(e.schemaVersion)}.`);if(!Fe.test(e.id))throw new h(`Invalid agent profile id: ${e.id}.`);if(!e.version.trim())throw new h(`Agent profile ${e.id} has no version.`);if(!e.displayName.trim()||!e.description.trim()||!e.prompt.trim())throw new h(`Agent profile ${e.id} requires displayName, description, and prompt.`);if(e.execution.allowedModes.length===0)throw new h(`Agent profile ${e.id} allows no collaboration modes.`);if(!e.execution.allowedModes.includes(e.execution.defaultMode))throw new h(`Agent profile ${e.id} default mode must be included in allowedModes.`)}function Ge(e,n,r,o,t,i){return{name:`agent-profile:${e.id}`,order:20,provide(){let l=E.map(s=>`${s}=${ne(n.externalActions,s)}`).join(", ");return["","","# XENO Agent Profile",`Profile: ${e.displayName} (${e.id}@${e.version})`,`Profile fingerprint: ${i}`,`Role: ${e.description}`,`Collaboration mode: ${o.defaultMode}`,`Isolation: ${o.isolation}`,`Memory: ${r.scope}; soul=${r.soul}`,`Permission profile ceiling: ${n.permissionProfile}`,`External actions: ${l}`,n.externalActions.requireCurrentTurnApproval.length>0?`Current-turn approval required for: ${n.externalActions.requireCurrentTurnApproval.join(", ")}`:"Current-turn approval required for: none",t.evidence.length>0?`Completion evidence: ${t.evidence.join(", ")}`:"Completion evidence: task-dependent",t.requirePrimarySources?"Use primary sources for factual claims and cite them near the claim.":"",t.requireCurrentInformation?"Verify time-sensitive claims against current authoritative information.":"",t.requireHumanReview?"Do not represent the result as professional approval; require human review before consequential use.":"",o.defaultDryRun?"Default to preview or dry-run. Do not perform external state changes without the required approval.":"","",e.prompt,"","Stop conditions:",...t.stopConditions.map(s=>`- ${s}`)].filter(s=>s!=="").join(`
8
- `)}}}function Je(e,n={}){re(e);let r=k(e),o=n.boundaries??[],t=k(r.capabilities.tools),i=r.capabilities.skills.allow?m(r.capabilities.skills.allow):void 0,l=new Set(m(r.capabilities.skills.deny)),s=m(r.capabilities.hooks),d=new Set,p=r.capabilities.mcpServers?m(r.capabilities.mcpServers):void 0,u=r.capabilities.delegatedAgents?m(r.capabilities.delegatedAgents):void 0,c=r.capabilities.permissionProfile,f=r.memory.scope,y=r.memory.soul,A=r.execution.isolation,v={"read-only":0,default:1,"trusted-dev":2},te={none:0,session:1,project:2,user:3},ie={disabled:0,read:1,learn:2},se={none:0,worktree:1,container:2};for(let a of o){a.tools&&(t=R({toolPolicy:t},a.tools)),i=Be(i,a.skills?.allow);for(let T of a.skills?.deny??[])l.add(T);s=N(s,a.hooks?.allow,void 0)??[];for(let T of a.hooks?.require??[])d.add(T);p=N(p,a.mcpServers?.allow,a.mcpServers?.deny),u=N(u,a.delegatedAgents?.allow,a.delegatedAgents?.deny),a.permissionProfile&&(c=$(c,a.permissionProfile,v)),a.maximumMemoryScope&&(f=$(f,a.maximumMemoryScope,te)),a.maximumSoulMode&&(y=$(y,a.maximumSoulMode,ie)),a.requiredIsolation&&(A=We(A,a.requiredIsolation,se))}let j=[...l].sort();c==="read-only"&&(t=R({toolPolicy:t},{mode:"readOnly",deny:["WebSearch","WebFetch"]})),i=Ve(i,j);let le=m(r.capabilities.skills.preload).filter(a=>!l.has(a)).filter(a=>i===void 0||i.includes(a));s=m([...s,...d]);let q={tools:t,skills:{preload:le,...i!==void 0?{allow:i}:{},deny:j},hooks:s,...p!==void 0?{mcpServers:p}:{},...u!==void 0?{delegatedAgents:u}:{},permissionProfile:c,externalActions:Ue(r.capabilities.externalActions,o)},L={...r.memory,scope:f,soul:y},_={...r.execution,isolation:A},F={schemaVersion:M,profile:r,boundarySources:o.map(a=>a.source),capabilities:q,memory:L,execution:_,completion:r.completion},B=He(F);return{...F,fingerprint:B,promptSection:Ge(r,q,L,_,r.completion,B)}}function g(e){return{schemaVersion:M,id:e.id,version:"1.0.0",displayName:e.displayName,description:e.description,kind:e.kind??"primary",prompt:e.prompt,capabilities:{tools:e.toolPolicy??{mode:"inherit"},skills:{preload:e.skills??[],...e.skillAllow?{allow:e.skillAllow}:{},deny:[]},hooks:[],permissionProfile:e.permissionProfile??"default",externalActions:{default:e.externalDefault??"ask",...e.externalOverrides?{overrides:e.externalOverrides}:{},requireCurrentTurnApproval:e.currentTurnApproval??[]}},memory:{scope:e.memoryScope??"project",role:e.id,soul:e.soul??"read"},execution:{defaultMode:e.defaultMode??"chat",allowedModes:e.allowedModes??["chat","plan","execute","review"],isolation:e.isolation??"none",allowBackground:e.allowBackground??!0,planForComplexTasks:e.planForComplexTasks??!0,defaultDryRun:e.defaultDryRun??!1},completion:{evidence:e.evidence??[],requirePrimarySources:e.primarySources??!1,requireCurrentInformation:e.currentInformation??!1,requireHumanReview:e.humanReview??!1,stopConditions:e.stopConditions??["The requested outcome is complete and required evidence has been reported.","A real authorization, information, or external-state blocker prevents safe progress."]},presentation:{label:e.displayName,color:e.color,glyph:e.glyph},tags:m(e.tags)}}var oe=[g({id:"assistant",displayName:"Assistant",description:"General-purpose XENO collaborator for mixed research, planning, and implementation work.",prompt:["Work as a thoughtful generalist. Establish the user's actual outcome, inspect relevant context, and take scoped action.","Escalate into a narrower specialist profile when domain risk or task depth warrants it."].join(`
9
- `),toolPolicy:{mode:"inherit"},skills:[],memoryScope:"user",evidence:["file-references"],currentTurnApproval:[...ee],color:"cyan",glyph:"\u25A0",tags:["general","primary"]}),g({id:"swe",displayName:"Software Engineer",description:"Repository-aware software engineer for careful implementation, debugging, refactoring, and verification.",prompt:["Inspect the repository before editing. Follow project instructions and preserve unrelated work.","Trace the smallest root cause, implement the narrowest coherent change, and verify from focused checks outward.","Do not claim completion without concrete test, typecheck, build, or runtime evidence appropriate to the risk."].join(`
10
- `),toolPolicy:{mode:"default"},skills:["debug","run","verify"],permissionProfile:"trusted-dev",soul:"learn",evidence:["file-references","tests","typecheck","build","diff"],currentTurnApproval:["publish","deploy","push","change-infrastructure"],color:"green",glyph:"\u25C6",tags:["engineering","implementation"]}),g({id:"reviewer",displayName:"Code Reviewer",description:"Read-only reviewer focused on correctness, regressions, safety, tests, and maintainability.",prompt:["Lead with concrete findings ordered by severity. Cite exact file locations and explain impact.","Do not edit code. Distinguish confirmed defects from risks and questions. State when no material finding is present."].join(`
11
- `),kind:"subagent",toolPolicy:{mode:"readOnly"},skills:["code-review","verify"],permissionProfile:"read-only",memoryScope:"session",soul:"read",allowedModes:["chat","review"],defaultMode:"review",evidence:["file-references","diff"],externalDefault:"deny",color:"yellow",glyph:"\u25C7",tags:["engineering","review","read-only"]}),g({id:"writer",displayName:"Writer",description:"Audience-aware writer and editor for clear, accurate, structurally coherent content.",prompt:["Determine audience, purpose, voice, format, and source constraints before drafting.","Preserve factual meaning, avoid invented claims, and revise for clarity, rhythm, consistency, and usefulness."].join(`
12
- `),toolPolicy:{mode:"default",allow:["Read","Glob","Grep","LS","Write","Edit","WebSearch","WebFetch","Think","AskUser","Skill"]},skills:["verify"],evidence:["sources","file-references","diff"],currentTurnApproval:["send","publish"],color:"magenta",glyph:"\u2726",tags:["writing","editing"]}),g({id:"research",displayName:"Researcher",description:"Evidence-first researcher for questions, comparisons, synthesis, and source-backed analysis.",prompt:["Break the question into verifiable claims. Prefer primary and authoritative sources, compare dates, and cite near each claim.","Separate sourced fact, inference, uncertainty, and recommendation. Do not make changes unless the user explicitly expands scope."].join(`
13
- `),toolPolicy:{mode:"readOnly"},skills:["verify"],permissionProfile:"default",memoryScope:"session",soul:"read",allowedModes:["chat","plan","review"],evidence:["sources","file-references"],primarySources:!0,currentInformation:!0,externalDefault:"deny",color:"blue",glyph:"\u25C8",tags:["research","qa","read-only"]}),g({id:"product",displayName:"Product",description:"Product strategist for problem framing, requirements, sequencing, metrics, and trade-off decisions.",prompt:["Start from the user problem and observable outcome. Distinguish evidence, assumptions, constraints, and open decisions.","Translate strategy into testable requirements, acceptance criteria, telemetry, risks, and a sequenced delivery path."].join(`
14
- `),toolPolicy:{mode:"default",allow:["Read","Glob","Grep","LS","Write","Edit","WebSearch","WebFetch","Think","AskUser","Skill"]},skills:["verify"],evidence:["sources","file-references","diff"],currentTurnApproval:["send","publish","change-infrastructure"],color:"cyan",glyph:"\u25A3",tags:["product","planning"]}),g({id:"ci",displayName:"CI Engineer",description:"Continuous-integration specialist for reproducing, repairing, and hardening automated gates.",prompt:["Identify the exact failing job and command. Reproduce it locally or in an equivalent immutable environment before patching.","Fix only the underlying failure, retain logs as evidence, and rerun the matching gate before broader validation."].join(`
15
- `),toolPolicy:{mode:"default"},skills:["ci-repair","debug","run","verify"],permissionProfile:"trusted-dev",soul:"learn",evidence:["tests","typecheck","build","diff"],currentTurnApproval:["push","deploy","change-infrastructure"],color:"green",glyph:"\u25A4",tags:["engineering","ci","automation"]}),g({id:"devops",displayName:"DevOps and Release",description:"Dry-run-first infrastructure and release specialist with explicit external-action gates.",prompt:["Inspect the release or infrastructure contract first. Build an immutable candidate and produce reproducible evidence.","Default to plan, preview, dry-run, and local verification. Never publish, deploy, push, sign, purchase, or mutate infrastructure unless the current user turn explicitly authorizes that exact action and target.","For releases, preserve SDK-before-CLI dependency order and verify the public artifact after publication."].join(`
16
- `),toolPolicy:{mode:"default"},skills:["release","run","verify"],permissionProfile:"default",memoryScope:"project",soul:"learn",isolation:"worktree",defaultMode:"plan",defaultDryRun:!0,evidence:["tests","build","diff","deployment-proof","human-review"],humanReview:!0,currentTurnApproval:["publish","deploy","push","purchase","sign","change-infrastructure"],color:"yellow",glyph:"\u2B22",tags:["devops","release","infrastructure"]}),g({id:"legal-research",displayName:"Legal Research",description:"Restricted legal-information researcher that produces sourced analysis for qualified human review.",prompt:["Identify jurisdiction, effective date, parties, and the precise legal question before analyzing it.","Use current primary legal sources wherever possible. Cite each material proposition and distinguish law, interpretation, uncertainty, and practical next steps.","Provide legal information, not professional representation. Never sign, file, submit, contact a party, accept terms, or make a payment."].join(`
17
- `),toolPolicy:{mode:"readOnly"},skills:["verify"],permissionProfile:"default",memoryScope:"session",soul:"disabled",allowedModes:["chat","plan","review"],defaultMode:"review",evidence:["sources","human-review"],primarySources:!0,currentInformation:!0,humanReview:!0,externalDefault:"deny",color:"red",glyph:"\xA7",tags:["legal","research","restricted","read-only"],stopConditions:["The jurisdiction or effective date is unknown and materially changes the answer.","The task requires legal representation, filing, signature, payment, or contact with a third party.","The sourced analysis is complete and clearly marked for qualified human review."]})],ze={general:"assistant",software:"swe",engineer:"swe","software-engineer":"swe",review:"reviewer","code-reviewer":"reviewer",qa:"research","q-and-a":"research",researcher:"research","product-manager":"product","ci-cd":"ci",cicd:"ci",release:"devops","devops-release":"devops",legal:"legal-research"};function An(){return oe.map(k)}function Xe(e){let n=e.trim().toLowerCase(),r=ze[n]??n,o=oe.find(t=>t.id===r);return o?k(o):null}function Ye(e){let n=e.memory?.trim().toLowerCase(),r=n==="none"||n==="session"||n==="project"||n==="user"?n:"project",o=g({id:e.name,displayName:e.name,description:e.description??`Custom XENO agent ${e.name}.`,prompt:e.prompt,toolPolicy:e.toolPolicy??{mode:"inherit"},skills:e.skills,memoryScope:r,isolation:e.isolation??"none",color:e.color??"cyan",glyph:"\u25A0",tags:["custom",...e.tags]});return e.model&&(o.model={preferred:e.model}),o.capabilities.hooks=[...e.hooks],o}function Pn(e){return re(e),{name:e.id,scope:"built-in",path:`builtin:xeno-agent-profile/${e.id}@${e.version}`,description:e.description,...e.model?.preferred?{model:e.model.preferred}:{},color:e.presentation.color,memory:e.memory.scope,isolation:e.execution.isolation==="container"?"worktree":e.execution.isolation,tags:[...e.tags],skills:[...e.capabilities.skills.preload],hooks:[...e.capabilities.hooks],active:!0,toolPolicy:k(e.capabilities.tools),prompt:e.prompt}}function wn(e){let n=e.definition?Ye(e.definition):Xe(e.name);return n?Je(n,{boundaries:e.boundaries}):null}export{ee as AGENT_PROFILE_EXTERNAL_ACTIONS,I as AgentDefinitionLoader,X as AgentDefinitionResolver,h as AgentProfileValidationError,M as XENO_AGENT_PROFILE_SCHEMA_VERSION,Pn as agentDefinitionFromProfile,Ye as agentProfileFromDefinition,Je as compileAgentProfile,mn as createAgentDefinitionFile,dn as createAgentDefinitionPromptSection,ve as getProjectAgentDefinitionDirs,Se as getProjectAgentDefinitionsDir,Y as getUserAgentDefinitionsDir,Q as isValidAgentDefinitionName,An as listBuiltInAgentProfiles,pn as renderAgentDefinition,fn as renderAgentDefinitions,cn as resolveAgentDefinition,wn as resolveAgentProfile,R as resolveAgentToolPolicy,Xe as resolveBuiltInAgentProfile,Z as scanAgentDefinitions,un as toAgentDefinitionMetadata,Ne as validateAgentDefinition};
6
+ `)}function gn(e){let n=e.name.trim().toLowerCase();if(!Q(n))throw new Error(`Invalid agent name "${e.name}". Use 1-64 lowercase letters, digits, hyphens, or underscores, starting with a letter.`);let r=e.scope==="user"?Y(e.agentHome):Se(e.cwd??process.cwd());pe(r,{recursive:!0});let o=b(r,`${n}.md`);if(E(o)&&!e.force)throw new Error(`Agent definition already exists: ${o}`);let i=e.description?.trim()||`${n} custom agent`,t=e.prompt?.trim()||`You are ${n}. Replace this paragraph with precise operating instructions, constraints, tools policy, verification expectations, and the kind of work this agent should own.`,s=[...["---",`name: ${n}`,`description: ${JSON.stringify(i)}`,...e.model?.trim()?[`model: ${JSON.stringify(e.model.trim())}`]:[],...e.color?.trim()?[`color: ${JSON.stringify(e.color.trim())}`]:[],...e.memory?.trim()?[`memory: ${JSON.stringify(e.memory.trim())}`]:[],...e.isolation?[`isolation: ${e.isolation}`]:[],"tags: []",...e.skills&&e.skills.length>0?[`skills: ${JSON.stringify(e.skills)}`]:[],...e.hooks&&e.hooks.length>0?[`hooks: ${JSON.stringify(e.hooks)}`]:[],...e.toolPolicy?["tools:",...e.toolPolicy.mode?[` mode: ${e.toolPolicy.mode}`]:[],...e.toolPolicy.allow&&e.toolPolicy.allow.length>0?[` allow: ${JSON.stringify(e.toolPolicy.allow)}`]:[],...e.toolPolicy.deny&&e.toolPolicy.deny.length>0?[` deny: ${JSON.stringify(e.toolPolicy.deny)}`]:[]]:[],"---"],"",t,""].join(`
7
+ `);return ye(o,s,"utf8"),o}import{createHash as _e}from"node:crypto";var M=2,ee=["publish","deploy","push","send","purchase","sign","file-legal","change-infrastructure"],h=class extends Error{constructor(n){super(n),this.name="AgentProfileValidationError"}},Fe=/^[a-z][a-z0-9_-]{0,63}$/,$=ee;function g(e){return Array.from(new Set((e??[]).map(n=>n.trim()).filter(Boolean)))}function Be(e,n){if(e===void 0)return n===void 0?void 0:g(n);if(n===void 0)return g(e);let r=new Set(n);return g(e.filter(o=>r.has(o)))}function Ve(e,n){if(e===void 0)return;let r=new Set(n);return e.filter(o=>!r.has(o))}function N(e,n,r){let o=n===void 0?null:new Set(n),i=new Set(r??[]);return e===void 0?n===void 0?void 0:g(n).filter(t=>!i.has(t)):g(e).filter(t=>(o===null||o.has(t))&&!i.has(t))}function T(e,n,r){return r[e]<=r[n]?e:n}function We(e,n,r){return r[e]>=r[n]?e:n}function O(e){return Array.isArray(e)?e.map(O):!e||typeof e!="object"?e:Object.fromEntries(Object.entries(e).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>[n,O(r)]))}function He(e){return _e("sha256").update(JSON.stringify(O(e))).digest("hex")}function k(e){return structuredClone(e)}function ne(e,n){return e.overrides?.[n]??e.default}function Ue(e,n){let r={deny:0,ask:1,allow:2},o=new Set(e.requireCurrentTurnApproval),i=Object.fromEntries($.map(d=>[d,ne(e,d)]));for(let d of n){let p=d.externalActions;if(p){for(let u of $){let c=p.overrides?.[u]??p.default;c&&(i[u]=T(i[u],c,r))}for(let u of p.requireCurrentTurnApproval??[])o.add(u)}}let l=new Set(Object.values(i)).size===1?i.publish:"deny",s={};for(let d of $)i[d]!==l&&(s[d]=i[d]);return{default:l,...Object.keys(s).length>0?{overrides:s}:{},requireCurrentTurnApproval:[...o].filter(d=>i[d]!=="deny").sort()}}function re(e){if(e.schemaVersion!==M)throw new h(`Unsupported agent profile schema: ${String(e.schemaVersion)}.`);if(!Fe.test(e.id))throw new h(`Invalid agent profile id: ${e.id}.`);if(!e.version.trim())throw new h(`Agent profile ${e.id} has no version.`);if(!e.displayName.trim()||!e.description.trim()||!e.prompt.trim())throw new h(`Agent profile ${e.id} requires displayName, description, and prompt.`);if(e.execution.allowedModes.length===0)throw new h(`Agent profile ${e.id} allows no collaboration modes.`);if(!e.execution.allowedModes.includes(e.execution.defaultMode))throw new h(`Agent profile ${e.id} default mode must be included in allowedModes.`)}function Ge(e,n,r,o,i,t){return{name:`agent-profile:${e.id}`,order:20,provide(){let l=$.map(s=>`${s}=${ne(n.externalActions,s)}`).join(", ");return["","","# XENO Agent Profile",`Profile: ${e.displayName} (${e.id}@${e.version})`,`Profile fingerprint: ${t}`,`Role: ${e.description}`,`Collaboration mode: ${o.defaultMode}`,`Isolation: ${o.isolation}`,`Memory: ${r.scope}; soul=${r.soul}`,`Permission profile ceiling: ${n.permissionProfile}`,`External actions: ${l}`,n.externalActions.requireCurrentTurnApproval.length>0?`Current-turn approval required for: ${n.externalActions.requireCurrentTurnApproval.join(", ")}`:"Current-turn approval required for: none",i.evidence.length>0?`Completion evidence: ${i.evidence.join(", ")}`:"Completion evidence: task-dependent",i.requirePrimarySources?"Use primary sources for factual claims and cite them near the claim.":"",i.requireCurrentInformation?"Verify time-sensitive claims against current authoritative information.":"",i.requireHumanReview?"Do not represent the result as professional approval; require human review before consequential use.":"",o.defaultDryRun?"Default to preview or dry-run. Do not perform external state changes without the required approval.":"","",e.prompt,"","Stop conditions:",...i.stopConditions.map(s=>`- ${s}`)].filter(s=>s!=="").join(`
8
+ `)}}}function Je(e,n={}){re(e);let r=k(e),o=n.boundaries??[],i=k(r.capabilities.tools),t=r.capabilities.skills.allow?g(r.capabilities.skills.allow):void 0,l=new Set(g(r.capabilities.skills.deny)),s=g(r.capabilities.hooks),d=new Set,p=r.capabilities.mcpServers?g(r.capabilities.mcpServers):void 0,u=r.capabilities.delegatedAgents?g(r.capabilities.delegatedAgents):void 0,c=r.capabilities.permissionProfile,f=r.memory.scope,y=r.memory.soul,A=r.execution.isolation,v={"read-only":0,default:1,"trusted-dev":2},te={none:0,session:1,project:2,user:3},ie={disabled:0,read:1,learn:2},se={none:0,worktree:1,container:2};for(let a of o){a.tools&&(i=R({toolPolicy:i},a.tools)),t=Be(t,a.skills?.allow);for(let I of a.skills?.deny??[])l.add(I);s=N(s,a.hooks?.allow,void 0)??[];for(let I of a.hooks?.require??[])d.add(I);p=N(p,a.mcpServers?.allow,a.mcpServers?.deny),u=N(u,a.delegatedAgents?.allow,a.delegatedAgents?.deny),a.permissionProfile&&(c=T(c,a.permissionProfile,v)),a.maximumMemoryScope&&(f=T(f,a.maximumMemoryScope,te)),a.maximumSoulMode&&(y=T(y,a.maximumSoulMode,ie)),a.requiredIsolation&&(A=We(A,a.requiredIsolation,se))}let j=[...l].sort();c==="read-only"&&(i=R({toolPolicy:i},{mode:"readOnly",deny:["WebSearch","WebFetch"]})),t=Ve(t,j);let le=g(r.capabilities.skills.preload).filter(a=>!l.has(a)).filter(a=>t===void 0||t.includes(a));s=g([...s,...d]);let q={tools:i,skills:{preload:le,...t!==void 0?{allow:t}:{},deny:j},hooks:s,...p!==void 0?{mcpServers:p}:{},...u!==void 0?{delegatedAgents:u}:{},permissionProfile:c,externalActions:Ue(r.capabilities.externalActions,o)},L={...r.memory,scope:f,soul:y},_={...r.execution,isolation:A},F={schemaVersion:M,profile:r,boundarySources:o.map(a=>a.source),capabilities:q,memory:L,execution:_,completion:r.completion},B=He(F);return{...F,fingerprint:B,promptSection:Ge(r,q,L,_,r.completion,B)}}function m(e){return{schemaVersion:M,id:e.id,version:"1.0.0",displayName:e.displayName,description:e.description,kind:e.kind??"primary",prompt:e.prompt,capabilities:{tools:e.toolPolicy??{mode:"inherit"},skills:{preload:e.skills??[],...e.skillAllow?{allow:e.skillAllow}:{},deny:[]},hooks:[],permissionProfile:e.permissionProfile??"default",externalActions:{default:e.externalDefault??"ask",...e.externalOverrides?{overrides:e.externalOverrides}:{},requireCurrentTurnApproval:e.currentTurnApproval??[]}},memory:{scope:e.memoryScope??"project",role:e.id,soul:e.soul??"read"},execution:{defaultMode:e.defaultMode??"chat",allowedModes:e.allowedModes??["chat","plan","execute","review"],isolation:e.isolation??"none",allowBackground:e.allowBackground??!0,planForComplexTasks:e.planForComplexTasks??!0,defaultDryRun:e.defaultDryRun??!1},completion:{evidence:e.evidence??[],requirePrimarySources:e.primarySources??!1,requireCurrentInformation:e.currentInformation??!1,requireHumanReview:e.humanReview??!1,stopConditions:e.stopConditions??["The requested outcome is complete and required evidence has been reported.","A real authorization, information, or external-state blocker prevents safe progress."]},presentation:{label:e.displayName,color:e.color,glyph:e.glyph},tags:g(e.tags)}}var oe=[m({id:"assistant",displayName:"Assistant",description:"General-purpose XENO collaborator for mixed research, planning, and implementation work.",prompt:["Work as a thoughtful generalist. Establish the user's actual outcome, inspect relevant context, and take scoped action.","Escalate into a narrower specialist profile when domain risk or task depth warrants it."].join(`
9
+ `),toolPolicy:{mode:"inherit"},skills:[],memoryScope:"user",evidence:["file-references"],currentTurnApproval:[...ee],color:"cyan",glyph:"\u25A0",tags:["general","primary"]}),m({id:"swe",displayName:"Software Engineer",description:"Repository-aware software engineer for careful implementation, debugging, refactoring, and verification.",prompt:["Inspect the repository before editing. Follow project instructions and preserve unrelated work.","Trace the smallest root cause, implement the narrowest coherent change, and verify from focused checks outward.","Do not claim completion without concrete test, typecheck, build, or runtime evidence appropriate to the risk."].join(`
10
+ `),toolPolicy:{mode:"default"},skills:["debug","run","verify"],permissionProfile:"trusted-dev",soul:"learn",evidence:["file-references","tests","typecheck","build","diff"],currentTurnApproval:["publish","deploy","push","change-infrastructure"],color:"green",glyph:"\u25C6",tags:["engineering","implementation"]}),m({id:"reviewer",displayName:"Code Reviewer",description:"Read-only reviewer focused on correctness, regressions, safety, tests, and maintainability.",prompt:["Lead with concrete findings ordered by severity. Cite exact file locations and explain impact.","Do not edit code. Distinguish confirmed defects from risks and questions. State when no material finding is present."].join(`
11
+ `),kind:"subagent",toolPolicy:{mode:"readOnly"},skills:["code-review","verify"],permissionProfile:"read-only",memoryScope:"session",soul:"read",allowedModes:["chat","review"],defaultMode:"review",evidence:["file-references","diff"],externalDefault:"deny",color:"yellow",glyph:"\u25C7",tags:["engineering","review","read-only"]}),m({id:"writer",displayName:"Writer",description:"Audience-aware writer and editor for clear, accurate, structurally coherent content.",prompt:["Determine audience, purpose, voice, format, and source constraints before drafting.","Preserve factual meaning, avoid invented claims, and revise for clarity, rhythm, consistency, and usefulness."].join(`
12
+ `),toolPolicy:{mode:"default",allow:["Read","Glob","Grep","LS","Write","Edit","WebSearch","WebFetch","Think","AskUser","Skill"]},skills:["verify"],evidence:["sources","file-references","diff"],currentTurnApproval:["send","publish"],color:"magenta",glyph:"\u2726",tags:["writing","editing"]}),m({id:"research",displayName:"Researcher",description:"Evidence-first researcher for questions, comparisons, synthesis, and source-backed analysis.",prompt:["Break the question into verifiable claims. Prefer primary and authoritative sources, compare dates, and cite near each claim.","Separate sourced fact, inference, uncertainty, and recommendation. Do not make changes unless the user explicitly expands scope."].join(`
13
+ `),toolPolicy:{mode:"readOnly"},skills:["verify"],permissionProfile:"default",memoryScope:"session",soul:"read",allowedModes:["chat","plan","review"],evidence:["sources","file-references"],primarySources:!0,currentInformation:!0,externalDefault:"deny",color:"blue",glyph:"\u25C8",tags:["research","qa","read-only"]}),m({id:"product",displayName:"Product",description:"Product strategist for problem framing, requirements, sequencing, metrics, and trade-off decisions.",prompt:["Start from the user problem and observable outcome. Distinguish evidence, assumptions, constraints, and open decisions.","Translate strategy into testable requirements, acceptance criteria, telemetry, risks, and a sequenced delivery path."].join(`
14
+ `),toolPolicy:{mode:"default",allow:["Read","Glob","Grep","LS","Write","Edit","WebSearch","WebFetch","Think","AskUser","Skill"]},skills:["verify"],evidence:["sources","file-references","diff"],currentTurnApproval:["send","publish","change-infrastructure"],color:"cyan",glyph:"\u25A3",tags:["product","planning"]}),m({id:"ci",displayName:"CI Engineer",description:"Continuous-integration specialist for reproducing, repairing, and hardening automated gates.",prompt:["Identify the exact failing job and command. Reproduce it locally or in an equivalent immutable environment before patching.","Fix only the underlying failure, retain logs as evidence, and rerun the matching gate before broader validation."].join(`
15
+ `),toolPolicy:{mode:"default"},skills:["ci-repair","debug","run","verify"],permissionProfile:"trusted-dev",soul:"learn",evidence:["tests","typecheck","build","diff"],currentTurnApproval:["push","deploy","change-infrastructure"],color:"green",glyph:"\u25A4",tags:["engineering","ci","automation"]}),m({id:"devops",displayName:"DevOps and Release",description:"Dry-run-first infrastructure and release specialist with explicit external-action gates.",prompt:["Inspect the release or infrastructure contract first. Build an immutable candidate and produce reproducible evidence.","Default to plan, preview, dry-run, and local verification. Never publish, deploy, push, sign, purchase, or mutate infrastructure unless the current user turn explicitly authorizes that exact action and target.","For releases, preserve SDK-before-CLI dependency order and verify the public artifact after publication."].join(`
16
+ `),toolPolicy:{mode:"default"},skills:["release","run","verify"],permissionProfile:"default",memoryScope:"project",soul:"learn",isolation:"worktree",defaultMode:"plan",defaultDryRun:!0,evidence:["tests","build","diff","deployment-proof","human-review"],humanReview:!0,currentTurnApproval:["publish","deploy","push","purchase","sign","change-infrastructure"],color:"yellow",glyph:"\u2B22",tags:["devops","release","infrastructure"]}),m({id:"legal-research",displayName:"Legal Research",description:"Restricted legal-information researcher that produces sourced analysis for qualified human review.",prompt:["Identify jurisdiction, effective date, parties, and the precise legal question before analyzing it.","Use current primary legal sources wherever possible. Cite each material proposition and distinguish law, interpretation, uncertainty, and practical next steps.","Provide legal information, not professional representation. Never sign, file, submit, contact a party, accept terms, or make a payment."].join(`
17
+ `),toolPolicy:{mode:"readOnly"},skills:["verify"],permissionProfile:"default",memoryScope:"session",soul:"disabled",allowedModes:["chat","plan","review"],defaultMode:"review",evidence:["sources","human-review"],primarySources:!0,currentInformation:!0,humanReview:!0,externalDefault:"deny",color:"red",glyph:"\xA7",tags:["legal","research","restricted","read-only"],stopConditions:["The jurisdiction or effective date is unknown and materially changes the answer.","The task requires legal representation, filing, signature, payment, or contact with a third party.","The sourced analysis is complete and clearly marked for qualified human review."]})],ze={general:"assistant",software:"swe",engineer:"swe","software-engineer":"swe",review:"reviewer","code-reviewer":"reviewer",qa:"research","q-and-a":"research",researcher:"research","product-manager":"product","ci-cd":"ci",cicd:"ci",release:"devops","devops-release":"devops",legal:"legal-research"};function An(){return oe.map(k)}function Xe(e){let n=e.trim().toLowerCase(),r=ze[n]??n,o=oe.find(i=>i.id===r);return o?k(o):null}function Ye(e){let n=e.memory?.trim().toLowerCase(),r=n==="none"||n==="session"||n==="project"||n==="user"?n:"project",o=m({id:e.name,displayName:e.name,description:e.description??`Custom XENO agent ${e.name}.`,prompt:e.prompt,toolPolicy:e.toolPolicy??{mode:"inherit"},skills:e.skills,memoryScope:r,isolation:e.isolation??"none",color:e.color??"cyan",glyph:"\u25A0",tags:["custom",...e.tags]});return e.model&&(o.model={preferred:e.model}),o.capabilities.hooks=[...e.hooks],o}function Pn(e){return re(e),{name:e.id,scope:"built-in",path:`builtin:xeno-agent-profile/${e.id}@${e.version}`,description:e.description,...e.model?.preferred?{model:e.model.preferred}:{},color:e.presentation.color,memory:e.memory.scope,isolation:e.execution.isolation==="container"?"worktree":e.execution.isolation,tags:[...e.tags],skills:[...e.capabilities.skills.preload],hooks:[...e.capabilities.hooks],active:!0,toolPolicy:k(e.capabilities.tools),prompt:e.prompt}}function wn(e){let n=e.definition?Ye(e.definition):Xe(e.name);return n?Je(n,{boundaries:e.boundaries}):null}export{ee as AGENT_PROFILE_EXTERNAL_ACTIONS,C as AgentDefinitionLoader,X as AgentDefinitionResolver,h as AgentProfileValidationError,M as XENO_AGENT_PROFILE_SCHEMA_VERSION,Pn as agentDefinitionFromProfile,Ye as agentProfileFromDefinition,Je as compileAgentProfile,gn as createAgentDefinitionFile,dn as createAgentDefinitionPromptSection,ve as getProjectAgentDefinitionDirs,Se as getProjectAgentDefinitionsDir,Y as getUserAgentDefinitionsDir,Q as isValidAgentDefinitionName,An as listBuiltInAgentProfiles,pn as renderAgentDefinition,fn as renderAgentDefinitions,cn as resolveAgentDefinition,wn as resolveAgentProfile,R as resolveAgentToolPolicy,Xe as resolveBuiltInAgentProfile,Z as scanAgentDefinitions,un as toAgentDefinitionMetadata,Ne as validateAgentDefinition};
@@ -1 +1 @@
1
- {"inputs":{"src/utils/yaml.ts":{"bytes":5668,"imports":[],"format":"esm"},"src/utils/platform.ts":{"bytes":5600,"imports":[{"path":"node:os","kind":"import-statement","external":true},{"path":"node:child_process","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true}],"format":"esm"},"src/agents/definitions.ts":{"bytes":20576,"imports":[{"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/utils/platform.ts","kind":"import-statement","original":"../utils/platform.js"}],"format":"esm"},"src/agents/profiles.ts":{"bytes":34533,"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"src/agents/definitions.ts","kind":"import-statement","original":"./definitions.js"}],"format":"esm"},"src/agents/index.ts":{"bytes":67,"imports":[{"path":"src/agents/definitions.ts","kind":"import-statement","original":"./definitions.js"},{"path":"src/agents/profiles.ts","kind":"import-statement","original":"./profiles.js"}],"format":"esm"}},"outputs":{"dist/agents/index.cjs":{"imports":[{"path":"node:fs","kind":"require-call","external":true},{"path":"node:path","kind":"require-call","external":true},{"path":"node:os","kind":"require-call","external":true},{"path":"node:path","kind":"require-call","external":true},{"path":"node:crypto","kind":"require-call","external":true}],"exports":[],"entryPoint":"src/agents/index.ts","inputs":{"src/agents/index.ts":{"bytesInOutput":822},"src/agents/definitions.ts":{"bytesInOutput":8827},"src/utils/yaml.ts":{"bytesInOutput":2217},"src/utils/platform.ts":{"bytesInOutput":241},"src/agents/profiles.ts":{"bytesInOutput":15421}},"bytes":28608}}}
1
+ {"inputs":{"src/utils/yaml.ts":{"bytes":5506,"imports":[],"format":"esm"},"src/utils/platform.ts":{"bytes":5600,"imports":[{"path":"node:os","kind":"import-statement","external":true},{"path":"node:child_process","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true}],"format":"esm"},"src/agents/definitions.ts":{"bytes":20961,"imports":[{"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/utils/platform.ts","kind":"import-statement","original":"../utils/platform.js"}],"format":"esm"},"src/agents/profiles.ts":{"bytes":33625,"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"src/agents/definitions.ts","kind":"import-statement","original":"./definitions.js"}],"format":"esm"},"src/agents/index.ts":{"bytes":65,"imports":[{"path":"src/agents/definitions.ts","kind":"import-statement","original":"./definitions.js"},{"path":"src/agents/profiles.ts","kind":"import-statement","original":"./profiles.js"}],"format":"esm"}},"outputs":{"dist/agents/index.cjs":{"imports":[{"path":"node:fs","kind":"require-call","external":true},{"path":"node:path","kind":"require-call","external":true},{"path":"node:os","kind":"require-call","external":true},{"path":"node:path","kind":"require-call","external":true},{"path":"node:crypto","kind":"require-call","external":true}],"exports":[],"entryPoint":"src/agents/index.ts","inputs":{"src/agents/index.ts":{"bytesInOutput":822},"src/agents/definitions.ts":{"bytesInOutput":8989},"src/utils/yaml.ts":{"bytesInOutput":2217},"src/utils/platform.ts":{"bytesInOutput":241},"src/agents/profiles.ts":{"bytesInOutput":15421}},"bytes":28770}}}
@@ -1 +1 @@
1
- {"inputs":{"src/utils/yaml.ts":{"bytes":5668,"imports":[],"format":"esm"},"src/utils/platform.ts":{"bytes":5600,"imports":[{"path":"node:os","kind":"import-statement","external":true},{"path":"node:child_process","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true}],"format":"esm"},"src/agents/definitions.ts":{"bytes":20576,"imports":[{"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/utils/platform.ts","kind":"import-statement","original":"../utils/platform.js"}],"format":"esm"},"src/agents/profiles.ts":{"bytes":34533,"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"src/agents/definitions.ts","kind":"import-statement","original":"./definitions.js"}],"format":"esm"},"src/agents/index.ts":{"bytes":67,"imports":[{"path":"src/agents/definitions.ts","kind":"import-statement","original":"./definitions.js"},{"path":"src/agents/profiles.ts","kind":"import-statement","original":"./profiles.js"}],"format":"esm"}},"outputs":{"dist/agents/index.js":{"imports":[{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"node:os","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"node:crypto","kind":"import-statement","external":true}],"exports":["AGENT_PROFILE_EXTERNAL_ACTIONS","AgentDefinitionLoader","AgentDefinitionResolver","AgentProfileValidationError","XENO_AGENT_PROFILE_SCHEMA_VERSION","agentDefinitionFromProfile","agentProfileFromDefinition","compileAgentProfile","createAgentDefinitionFile","createAgentDefinitionPromptSection","getProjectAgentDefinitionDirs","getProjectAgentDefinitionsDir","getUserAgentDefinitionsDir","isValidAgentDefinitionName","listBuiltInAgentProfiles","renderAgentDefinition","renderAgentDefinitions","resolveAgentDefinition","resolveAgentProfile","resolveAgentToolPolicy","resolveBuiltInAgentProfile","scanAgentDefinitions","toAgentDefinitionMetadata","validateAgentDefinition"],"entryPoint":"src/agents/index.ts","inputs":{"src/agents/definitions.ts":{"bytesInOutput":8785},"src/utils/yaml.ts":{"bytesInOutput":2217},"src/utils/platform.ts":{"bytesInOutput":220},"src/agents/index.ts":{"bytesInOutput":0},"src/agents/profiles.ts":{"bytesInOutput":15422}},"bytes":27411}}}
1
+ {"inputs":{"src/utils/yaml.ts":{"bytes":5506,"imports":[],"format":"esm"},"src/utils/platform.ts":{"bytes":5600,"imports":[{"path":"node:os","kind":"import-statement","external":true},{"path":"node:child_process","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true}],"format":"esm"},"src/agents/definitions.ts":{"bytes":20961,"imports":[{"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/utils/platform.ts","kind":"import-statement","original":"../utils/platform.js"}],"format":"esm"},"src/agents/profiles.ts":{"bytes":33625,"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"src/agents/definitions.ts","kind":"import-statement","original":"./definitions.js"}],"format":"esm"},"src/agents/index.ts":{"bytes":65,"imports":[{"path":"src/agents/definitions.ts","kind":"import-statement","original":"./definitions.js"},{"path":"src/agents/profiles.ts","kind":"import-statement","original":"./profiles.js"}],"format":"esm"}},"outputs":{"dist/agents/index.js":{"imports":[{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"node:os","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"node:crypto","kind":"import-statement","external":true}],"exports":["AGENT_PROFILE_EXTERNAL_ACTIONS","AgentDefinitionLoader","AgentDefinitionResolver","AgentProfileValidationError","XENO_AGENT_PROFILE_SCHEMA_VERSION","agentDefinitionFromProfile","agentProfileFromDefinition","compileAgentProfile","createAgentDefinitionFile","createAgentDefinitionPromptSection","getProjectAgentDefinitionDirs","getProjectAgentDefinitionsDir","getUserAgentDefinitionsDir","isValidAgentDefinitionName","listBuiltInAgentProfiles","renderAgentDefinition","renderAgentDefinitions","resolveAgentDefinition","resolveAgentProfile","resolveAgentToolPolicy","resolveBuiltInAgentProfile","scanAgentDefinitions","toAgentDefinitionMetadata","validateAgentDefinition"],"entryPoint":"src/agents/index.ts","inputs":{"src/agents/definitions.ts":{"bytesInOutput":8923},"src/utils/yaml.ts":{"bytesInOutput":2217},"src/utils/platform.ts":{"bytesInOutput":220},"src/agents/index.ts":{"bytesInOutput":0},"src/agents/profiles.ts":{"bytesInOutput":15422}},"bytes":27549}}}
@@ -1,5 +1,5 @@
1
1
  "use strict";var xe=Object.defineProperty;var sn=Object.getOwnPropertyDescriptor;var an=Object.getOwnPropertyNames;var cn=Object.prototype.hasOwnProperty;var dn=(e,t)=>{for(var n in t)xe(e,n,{get:t[n],enumerable:!0})},fn=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of an(t))!cn.call(e,o)&&o!==n&&xe(e,o,{get:()=>t[o],enumerable:!(i=sn(t,o))||i.enumerable});return e};var pn=e=>fn(xe({},"__esModule",{value:!0}),e);var ki={};dn(ki,{FileXenoArtifactRepository:()=>qe,InMemoryXenoArtifactRepository:()=>B,XENO_ARTIFACT_ACTOR_KINDS:()=>Pe,XENO_ARTIFACT_FILE_REPOSITORY_SCHEMA_VERSION:()=>We,XENO_ARTIFACT_SCHEMA_VERSION:()=>h,XENO_ARTIFACT_SENSITIVITIES:()=>Ve,XENO_ARTIFACT_STATES:()=>Ne,XENO_BUILTIN_ARTIFACT_KINDS:()=>Ce,XENO_EVIDENCE_EDGE_TYPES:()=>ee,XENO_EVIDENCE_GRAPH_SCHEMA_VERSION:()=>me,XENO_EVIDENCE_NODE_TYPES:()=>Q,XENO_REVIEW_DIMENSIONS:()=>Bt,XENO_REVIEW_EVIDENCE_KINDS:()=>Ut,XENO_REVIEW_REPORT_SCHEMA_VERSION:()=>ot,XENO_SPEC_EXECUTION_SCHEMA_VERSION:()=>ce,XENO_SPEC_SCHEMA_VERSION:()=>z,XenoArtifactRepositoryError:()=>u,XenoArtifactReviewService:()=>U,XenoArtifactStateTransitionError:()=>ve,XenoArtifactValidationError:()=>M,XenoDiffParseError:()=>X,XenoEvidenceGraphBuilder:()=>Le,XenoEvidenceGraphValidationError:()=>ye,XenoMultiAgentReviewCoordinator:()=>rt,XenoReviewValidationError:()=>E,XenoSpecLifecycleService:()=>Qe,XenoSpecValidationError:()=>w,assertValidXenoArtifact:()=>I,assertValidXenoEvidenceGraph:()=>J,assertValidXenoReviewPack:()=>st,assertValidXenoReviewReport:()=>fe,assertValidXenoReviewTarget:()=>at,assertValidXenoSpecDocument:()=>be,assertValidXenoSpecExecution:()=>it,assertXenoArtifactStateTransition:()=>ie,buildXenoArtifactReviewAnchor:()=>Ze,canTransitionXenoArtifactState:()=>yt,canonicalizeArtifactJson:()=>S,defaultXenoReviewPack:()=>ai,detectXenoSpecDrift:()=>ti,legacyAgentArtifactToXenoArtifact:()=>yi,normalizeRepositoryRelativePath:()=>Ft,parseUnifiedDiff:()=>Ke,sha256ArtifactBytes:()=>T,sha256ArtifactJson:()=>k,summarizeXenoArtifactReview:()=>ge,toolEvidenceToXenoArtifact:()=>wi,turnDiffSummaryToXenoArtifact:()=>Ri,unifiedDiffToXenoArtifact:()=>Ge,validateXenoArtifact:()=>At,validateXenoArtifactReviewEvent:()=>he,validateXenoEvidenceGraph:()=>wt,validateXenoSpecDocument:()=>Mt,xenoArtifactToDiffDocument:()=>Ye,xenoArtifactToLegacyAgentArtifact:()=>Ii,xenoArtifactToReviewReport:()=>di,xenoArtifactToSpecDocument:()=>tt,xenoArtifactToSpecExecution:()=>Ht,xenoArtifactToToolEvidence:()=>Ei,xenoArtifactToTurnDiffSummary:()=>Xi,xenoReviewReportToArtifact:()=>ci,xenoReviewReportToGitHubComments:()=>fi,xenoSpecArtifactIds:()=>W,xenoSpecExecutionToArtifact:()=>nt,xenoSpecToArtifactBundle:()=>et});module.exports=pn(ki);var h=1,me=1,Ce=["plan","requirements","design","task-graph","patch","diff","file","document","diagram","screenshot","recording","browser-snapshot","test-report","review-report","security-report","performance-report","release-report","sbom","provenance","attestation"],Ne=["draft","pending_review","approved","rejected","superseded","archived"],Ve=["public","internal","confidential","restricted"],Pe=["agent","tool","user","system","integration"],Q=["requirement","design-decision","risk","task","agent","run","tool-call","edit","commit","test-case","test-run","finding","approval","artifact","release","claim"],ee=["decomposes","depends_on","implements","changes","tests","verifies","finds","fixes","reviews","approves","rejects","supersedes","derived_from","produced_by","supports_claim","contradicts_claim","released_as"];var De=require("node:buffer");var vt=require("node:crypto");function T(e){return{algorithm:"sha256",value:(0,vt.createHash)("sha256").update(e).digest("hex")}}function S(e){return JSON.stringify($e(e,new Set))}function k(e){return T(S(e))}function $e(e,t){if(e===null||typeof e!="object"){if(typeof e=="number"&&!Number.isFinite(e))throw new TypeError("Artifact JSON cannot contain non-finite numbers");return e}if(t.has(e))throw new TypeError("Artifact JSON cannot contain cycles");if(t.add(e),Array.isArray(e)){let i=e.map(o=>$e(o,t));return t.delete(e),i}let n={};for(let i of Object.keys(e).sort((o,r)=>o.localeCompare(r))){let o=e[i];if(o===void 0)throw new TypeError(`Artifact JSON property ${i} is undefined`);n[i]=$e(o,t)}return t.delete(e),n}var un=/^[a-z0-9][a-z0-9._/-]{0,127}$/,Oe="custom:";function F(e,t=Oe){return e.startsWith(t)?un.test(e.slice(t.length)):!1}var M=class extends Error{code="ARTIFACT_INVALID";issues;constructor(t,n){super(t),this.name="XenoArtifactValidationError",this.issues=n.map(i=>({...i}))}},ve=class extends Error{constructor(n,i){super(`Artifact state cannot transition from ${n} to ${i}`);this.fromState=n;this.toState=i;this.name="XenoArtifactStateTransitionError"}fromState;toState;code="ARTIFACT_STATE_TRANSITION_INVALID"},ln={draft:["pending_review","superseded","archived"],pending_review:["approved","rejected","superseded","archived"],approved:["superseded","archived"],rejected:["superseded","archived"],superseded:["archived"],archived:[]},mn="[\\u0000-\\u001f\\u007f]",vn=new RegExp(mn),ht=/^[a-f0-9]{64}$/,hn=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,gn=new Set(Ne),An=new Set(Ve),yn=new Set(Pe),In=new Set(Ce),wn=new Set(Q),En=new Set(ee);function p(e,t,n,i){e.push({path:t,code:n,message:i})}function l(e,t,n,i=1024){return typeof e!="string"||e.trim().length===0?(p(n,t,"required_string","Value must be a non-empty string"),!1):(e.length>i&&p(n,t,"string_too_long",`Value must not exceed ${i} characters`),vn.test(e)&&p(n,t,"control_character","Value must not contain control characters"),!0)}function te(e,t,n){e!==void 0&&(!Number.isFinite(Date.parse(e))||!e.includes("T"))&&p(n,t,"invalid_timestamp","Value must be an ISO 8601 timestamp")}function L(e,t,n,i){typeof e=="string"&&e.startsWith(t)&&(F(e,t)||p(i,n,"invalid_custom_name",`Custom name after ${t} is invalid`))}function gt(e,t,n){if(!e||typeof e!="object"){p(n,t,"missing_actor","Actor is required");return}l(e.kind,`${t}.kind`,n,64),yn.has(e.kind)||p(n,`${t}.kind`,"unknown_actor_kind","Actor kind is not supported"),l(e.id,`${t}.id`,n,512),e?.displayName!==void 0&&l(e.displayName,`${t}.displayName`,n,512),e?.profileFingerprint!==void 0&&!/^[a-f0-9]{64}$/.test(e.profileFingerprint)&&p(n,`${t}.profileFingerprint`,"invalid_fingerprint","Profile fingerprint must be 64 lowercase hexadecimal characters")}function Fe(e,t,n){if(!e||typeof e!="object"){p(n,t,"invalid_anchor","Anchor must be an object");return}switch(e.kind){case"file":l(e.path,`${t}.path`,n,4096);break;case"source-line":l(e.path,`${t}.path`,n,4096),(!Number.isInteger(e.startLine)||e.startLine<1)&&p(n,`${t}.startLine`,"invalid_line","startLine must be a positive integer"),e.endLine!==void 0&&(!Number.isInteger(e.endLine)||e.endLine<e.startLine)&&p(n,`${t}.endLine`,"invalid_line_range","endLine must be greater than or equal to startLine");break;case"diff-hunk":l(e.path,`${t}.path`,n,4096),l(e.hunkId,`${t}.hunkId`,n,512);break;case"symbol":l(e.path,`${t}.path`,n,4096),l(e.symbol,`${t}.symbol`,n,1024);break;case"dom-node":l(e.pageId,`${t}.pageId`,n,512),!e.selector&&!e.accessibilityId&&!e.snapshotArtifactId&&p(n,t,"missing_dom_locator","DOM anchors require a selector, accessibility ID, or snapshot artifact ID");break;case"timeline":l(e.recordingArtifactId,`${t}.recordingArtifactId`,n,512),(!Number.isFinite(e.startMs)||e.startMs<0)&&p(n,`${t}.startMs`,"invalid_time","startMs must be a non-negative finite number"),e.endMs!==void 0&&(!Number.isFinite(e.endMs)||e.endMs<e.startMs)&&p(n,`${t}.endMs`,"invalid_time_range","endMs must be greater than or equal to startMs");break;case"region":l(e.mediaArtifactId,`${t}.mediaArtifactId`,n,512),[e.x,e.y,e.width,e.height].every(Number.isFinite)?(e.width<=0||e.height<=0)&&p(n,t,"invalid_region_size","Region width and height must be positive"):p(n,t,"invalid_region","Region coordinates must be finite numbers");break;case"artifact":l(e.artifactId,`${t}.artifactId`,n,512);break;default:typeof e.kind!="string"||!e.kind.startsWith("custom:")?p(n,`${t}.kind`,"unknown_anchor","Anchor kind is not supported"):L(e.kind,"custom:",`${t}.kind`,n)}}function ne(e,t,n,i){if(!(e===null||typeof e=="string"||typeof e=="boolean")){if(typeof e=="number"){Number.isFinite(e)||p(n,t,"non_finite_number","JSON numbers must be finite");return}if(typeof e!="object"){p(n,t,"non_json_value","Value must be JSON-serializable");return}if(i.has(e)){p(n,t,"cyclic_value","Value must not contain cycles");return}if(i.add(e),Array.isArray(e))e.forEach((o,r)=>ne(o,`${t}[${r}]`,n,i));else for(let[o,r]of Object.entries(e))r===void 0?p(n,`${t}.${o}`,"undefined_value","Undefined is not valid JSON"):ne(r,`${t}.${o}`,n,i);i.delete(e)}}function At(e){let t=[];if(!e||typeof e!="object")return[{path:"$",code:"invalid_artifact",message:"Artifact must be an object"}];if(e.schemaVersion!==1&&p(t,"schemaVersion","unsupported_schema",`schemaVersion must be ${1}`),l(e.artifactId,"artifactId",t,512),(!Number.isInteger(e.revision)||e.revision<1)&&p(t,"revision","invalid_revision","revision must be a positive integer"),l(e.kind,"kind",t,160),typeof e.kind=="string"&&!In.has(e.kind)&&!e.kind.startsWith("custom:")&&p(t,"kind","unknown_artifact_kind","Artifact kind is not supported"),L(e.kind,"custom:","kind",t),l(e.title,"title",t,1024),e.description!==void 0&&l(e.description,"description",t,32768),l(e.state,"state",t,64),gn.has(e.state)||p(t,"state","unknown_state","Artifact state is not supported"),l(e.createdAt,"createdAt",t,128),te(e.createdAt,"createdAt",t),te(e.updatedAt,"updatedAt",t),e.updatedAt&&Number.isFinite(Date.parse(e.createdAt))&&Date.parse(e.updatedAt)<Date.parse(e.createdAt)&&p(t,"updatedAt","timestamp_order","updatedAt must not precede createdAt"),l(e.mediaType,"mediaType",t,255),l(e.sensitivity,"sensitivity",t,64),An.has(e.sensitivity)||p(t,"sensitivity","unknown_sensitivity","Sensitivity is not supported"),e.identity)for(let[i,o]of Object.entries(e.identity))o!==void 0&&l(o,`identity.${i}`,t,512);if(!e.content||typeof e.content!="object")p(t,"content","missing_content","content descriptor is required");else{!e.content.hash||typeof e.content.hash!="object"?p(t,"content.hash","missing_hash","content hash is required"):(l(e.content.hash.algorithm,"content.hash.algorithm",t,128),L(e.content.hash.algorithm,"custom:","content.hash.algorithm",t),typeof e.content.hash.algorithm=="string"&&e.content.hash.algorithm!=="sha256"&&!e.content.hash.algorithm.startsWith("custom:")&&p(t,"content.hash.algorithm","unknown_hash_algorithm","Hash algorithm is not supported"),l(e.content.hash.value,"content.hash.value",t,512),e.content.hash.algorithm==="sha256"&&!ht.test(e.content.hash.value)&&p(t,"content.hash.value","invalid_sha256","SHA-256 hash must be 64 lowercase hexadecimal characters")),(!Number.isSafeInteger(e.content.sizeBytes)||e.content.sizeBytes<0)&&p(t,"content.sizeBytes","invalid_size","sizeBytes must be a non-negative safe integer");let i=e.content.storage;if(!i||typeof i!="object")p(t,"content.storage","missing_storage","storage reference is required");else if(i.type==="inline")if(i.text===void 0==(i.base64===void 0))p(t,"content.storage","invalid_inline_storage","Inline storage requires exactly one of text or base64");else{let o;i.text!==void 0?o=De.Buffer.from(i.text,"utf8"):i.base64!==void 0&&(hn.test(i.base64)?o=De.Buffer.from(i.base64,"base64"):p(t,"content.storage.base64","invalid_base64","Inline base64 content is malformed")),o&&e.content.sizeBytes!==o.byteLength&&p(t,"content.sizeBytes","content_size_mismatch","sizeBytes does not match inline content"),o&&e.content.hash.algorithm==="sha256"&&T(o).value!==e.content.hash.value&&p(t,"content.hash.value","content_hash_mismatch","Hash does not match inline content")}else i.type==="file"?l(i.path,"content.storage.path",t,4096):i.type==="blob"?l(i.uri,"content.storage.uri",t,8192):i.type==="git"?(l(i.commit,"content.storage.commit",t,512),l(i.path,"content.storage.path",t,4096)):i.type==="url"?(l(i.url,"content.storage.url",t,8192),te(i.expiresAt,"content.storage.expiresAt",t)):i.type==="external"?(l(i.provider,"content.storage.provider",t,255),l(i.locator,"content.storage.locator",t,8192)):p(t,"content.storage.type","unknown_storage","Storage type is not supported");e.content.encoding!==void 0&&(typeof e.content.encoding!="string"||e.content.encoding!=="utf8"&&e.content.encoding!=="base64"&&e.content.encoding!=="binary"&&!e.content.encoding.startsWith("custom:"))&&p(t,"content.encoding","unknown_encoding","Content encoding is not supported"),L(e.content.encoding,"custom:","content.encoding",t)}!e.provenance||typeof e.provenance!="object"?p(t,"provenance","missing_provenance","provenance is required"):(gt(e.provenance.producer,"provenance.producer",t),e.provenance.capabilityLeaseIds?.forEach((i,o)=>l(i,`provenance.capabilityLeaseIds[${o}]`,t,512)),e.provenance.sourceArtifactIds?.forEach((i,o)=>l(i,`provenance.sourceArtifactIds[${o}]`,t,512)),e.provenance.attributes&&ne(e.provenance.attributes,"provenance.attributes",t,new Set));let n=new Set;return e.relationships?.forEach((i,o)=>{let r=`relationships[${o}]`;l(i.relation,`${r}.relation`,t,160),typeof i.relation=="string"&&!En.has(i.relation)&&!i.relation.startsWith("custom:")&&p(t,`${r}.relation`,"unknown_relationship","Relationship type is not supported"),L(i.relation,"custom:",`${r}.relation`,t),l(i.target?.type,`${r}.target.type`,t,160),typeof i.target?.type=="string"&&!wn.has(i.target.type)&&!i.target.type.startsWith("custom:")&&p(t,`${r}.target.type`,"unknown_reference_type","Evidence reference type is not supported"),L(i.target?.type,"custom:",`${r}.target.type`,t),l(i.target?.id,`${r}.target.id`,t,512);let a=`${i.relation}:${i.target?.type}:${i.target?.id}:${i.target?.revision??""}`;n.has(a)&&p(t,r,"duplicate_relationship","Duplicate relationship"),n.add(a),i.attributes&&ne(i.attributes,`${r}.attributes`,t,new Set)}),e.anchors?.forEach((i,o)=>Fe(i,`anchors[${o}]`,t)),e.revision===1&&e.predecessorRevision!==void 0&&p(t,"predecessorRevision","unexpected_predecessor","First revision cannot have a predecessor"),e.revision>1&&(!Number.isInteger(e.predecessorRevision)||(e.predecessorRevision??0)>=e.revision)&&p(t,"predecessorRevision","invalid_predecessor","Later revisions require an earlier predecessor revision"),te(e.retention?.retainUntil,"retention.retainUntil",t),e.retention?.legalHold!==void 0&&typeof e.retention.legalHold!="boolean"&&p(t,"retention.legalHold","invalid_boolean","legalHold must be a boolean"),e.extensions&&ne(e.extensions,"extensions",t,new Set),t}function I(e){let t=At(e);if(t.length>0)throw new M("XENO artifact validation failed",t)}function yt(e,t){return ln[e].includes(t)}function ie(e,t){if(!yt(e,t))throw new ve(e,t)}function he(e,t){let n=[];return e.schemaVersion!==1&&p(n,"schemaVersion","unsupported_schema",`schemaVersion must be ${1}`),l(e.eventId,"eventId",n,512),l(e.artifactId,"artifactId",n,512),(!Number.isInteger(e.artifactRevision)||e.artifactRevision<1)&&p(n,"artifactRevision","invalid_revision","artifactRevision must be a positive integer"),(!Number.isInteger(e.sequence)||e.sequence<1)&&p(n,"sequence","invalid_sequence","sequence must be a positive integer"),l(e.recordedAt,"recordedAt",n,128),te(e.recordedAt,"recordedAt",n),gt(e.actor,"actor",n),!e.artifactHash||typeof e.artifactHash!="object"?p(n,"artifactHash","missing_hash","Artifact hash is required"):(l(e.artifactHash.algorithm,"artifactHash.algorithm",n,128),L(e.artifactHash.algorithm,"custom:","artifactHash.algorithm",n),l(e.artifactHash.value,"artifactHash.value",n,512),e.artifactHash.algorithm==="sha256"&&!ht.test(e.artifactHash.value)&&p(n,"artifactHash.value","invalid_sha256","SHA-256 hash must be 64 lowercase hexadecimal characters"),typeof e.artifactHash.algorithm=="string"&&e.artifactHash.algorithm!=="sha256"&&!e.artifactHash.algorithm.startsWith("custom:")&&p(n,"artifactHash.algorithm","unknown_hash_algorithm","Hash algorithm is not supported")),["review-requested","comment-added","comment-resolved","comment-reopened","decision-recorded","review-withdrawn"].includes(e.type)||p(n,"type","unknown_review_event","Review event type is not supported"),e.type==="comment-added"?(l(e.commentId,"commentId",n,512),l(e.body,"body",n,65536),e.anchor&&Fe(e.anchor,"anchor",n)):e.type==="comment-resolved"||e.type==="comment-reopened"?l(e.commentId,"commentId",n,512):e.type==="decision-recorded"&&(["approved","rejected","changes_requested"].includes(e.decision)||p(n,"decision","unknown_review_decision","Review decision is not supported"),e.scope&&Fe(e.scope,"scope",n)),t&&(e.artifactId!==t.artifactId&&p(n,"artifactId","artifact_mismatch","Review event targets a different artifact"),e.artifactRevision!==t.revision&&p(n,"artifactRevision","revision_mismatch","Review event targets a different revision"),e.artifactHash&&(e.artifactHash.algorithm!==t.content.hash.algorithm||e.artifactHash.value!==t.content.hash.value)&&p(n,"artifactHash","hash_mismatch","Review event hash does not match the artifact revision")),n}function ge(e){let t="not_requested",n,i,o,r=0,a=new Set,c=new Set;for(let s of[...e].sort((d,f)=>d.sequence-f.sequence))o=s.recordedAt,s.type==="review-requested"?t="pending":s.type==="review-withdrawn"?t="withdrawn":s.type==="comment-added"?(a.add(s.commentId),c.delete(s.commentId),t==="not_requested"&&(t="pending")):s.type==="comment-resolved"?c.add(s.commentId):s.type==="comment-reopened"?c.delete(s.commentId):s.type==="decision-recorded"&&(s.scope?r+=1:(n=s.decision,i=s.eventId,t=s.decision));return{status:t,totalComments:a.size,unresolvedComments:[...a].filter(s=>!c.has(s)).length,...n?{latestDecision:n}:{},...i?{latestDecisionEventId:i}:{},...r>0?{scopedDecisionCount:r}:{},...o?{lastReviewedAt:o}:{}}}var ye=class extends Error{code="EVIDENCE_GRAPH_INVALID";issues;constructor(t){super("XENO evidence graph validation failed"),this.name="XenoEvidenceGraphValidationError",this.issues=t.map(n=>({...n}))}},Rn=new Set(["depends_on","decomposes","supersedes"]),Xn=new Set(Q),Sn=new Set(ee);function A(e,t,n,i){e.push({path:t,code:n,message:i})}function re(e){return e.includes("T")&&Number.isFinite(Date.parse(e))}function It(e,t){return e.startsWith(Oe)?F(e):t.has(e)}function wt(e){let t=[];if(!e||typeof e!="object")return[{path:"$",code:"invalid_graph",message:"Evidence graph must be an object"}];e.schemaVersion!==1&&A(t,"schemaVersion","unsupported_schema",`schemaVersion must be ${1}`),(typeof e.graphId!="string"||e.graphId.trim().length===0)&&A(t,"graphId","required_string","graphId must be a non-empty string"),(!Number.isInteger(e.version)||e.version<1)&&A(t,"version","invalid_version","version must be a positive integer"),re(e.createdAt)||A(t,"createdAt","invalid_timestamp","createdAt must be an ISO 8601 timestamp"),re(e.updatedAt)||A(t,"updatedAt","invalid_timestamp","updatedAt must be an ISO 8601 timestamp"),re(e.createdAt)&&re(e.updatedAt)&&Date.parse(e.updatedAt)<Date.parse(e.createdAt)&&A(t,"updatedAt","timestamp_order","updatedAt must not precede createdAt");let n=new Map;Array.isArray(e.nodes)||A(t,"nodes","invalid_nodes","nodes must be an array"),(Array.isArray(e.nodes)?e.nodes:[]).forEach((f,g)=>{let R=`nodes[${g}]`;typeof f.id!="string"||f.id.trim().length===0?A(t,`${R}.id`,"required_string","Node ID must be a non-empty string"):n.has(f.id)?A(t,`${R}.id`,"duplicate_node",`Node ID ${f.id} is duplicated`):n.set(f.id,f),(typeof f.type!="string"||!It(f.type,Xn))&&A(t,`${R}.type`,"invalid_node_type","Node type is invalid"),f.artifactRevision!==void 0&&(!Number.isInteger(f.artifactRevision)||f.artifactRevision<1)&&A(t,`${R}.artifactRevision`,"invalid_revision","artifactRevision must be a positive integer")});let i=new Set,o=new Set;Array.isArray(e.edges)||A(t,"edges","invalid_edges","edges must be an array"),(Array.isArray(e.edges)?e.edges:[]).forEach((f,g)=>{let R=`edges[${g}]`;typeof f.id!="string"||f.id.trim().length===0?A(t,`${R}.id`,"required_string","Edge ID must be a non-empty string"):i.has(f.id)&&A(t,`${R}.id`,"duplicate_edge",`Edge ID ${f.id} is duplicated`),i.add(f.id),(typeof f.type!="string"||!It(f.type,Sn))&&A(t,`${R}.type`,"invalid_edge_type","Edge type is invalid");let O=`${f.type}:${f.from}:${f.to}`;o.has(O)&&A(t,R,"duplicate_edge_identity","Equivalent evidence edge is duplicated"),o.add(O),n.has(f.from)||A(t,`${R}.from`,"dangling_reference",`Source node ${f.from} does not exist`),n.has(f.to)||A(t,`${R}.to`,"dangling_reference",`Target node ${f.to} does not exist`),f.from===f.to&&A(t,R,"self_edge","Evidence edges cannot point to the same node"),re(f.createdAt)||A(t,`${R}.createdAt`,"invalid_timestamp","createdAt must be an ISO 8601 timestamp")});let r=(Array.isArray(e.edges)?e.edges:[]).filter(f=>Rn.has(f.type)),a=new Map;for(let f of r){let g=a.get(f.from)??[];g.push(f.to),a.set(f.from,g)}let c=new Set,s=new Set,d=f=>{if(c.has(f))return!0;if(s.has(f))return!1;c.add(f);for(let g of a.get(f)??[])if(d(g))return!0;return c.delete(f),s.add(f),!1};for(let f of n.keys())if(d(f)){A(t,"edges","cyclic_graph","Dependency, decomposition, and supersession edges must be acyclic");break}return t}function J(e){let t=wt(e);if(t.length>0)throw new ye(t)}var Le=class{now;graph;constructor(t){if("schemaVersion"in t)J(t),this.now=()=>new Date().toISOString(),this.graph=Ae(t);else{this.now=t.now??(()=>new Date().toISOString());let n=this.now();this.graph={schemaVersion:1,graphId:t.graphId,version:1,createdAt:n,updatedAt:n,nodes:[],edges:[]},J(this.graph)}}addNode(t){let n=Ae(this.graph);return n.nodes.push(Et(t)),this.touch(n),J(n),this.graph=n,this}addEdge(t){let n=Ae(this.graph);return n.edges.push(Rt(t)),this.touch(n),J(n),this.graph=n,this}build(){return J(this.graph),Ae(this.graph)}touch(t){t.version+=1,t.updatedAt=this.now()}};function Et(e){return{...e,...e.attributes?{attributes:structuredClone(e.attributes)}:{}}}function Rt(e){return{...e,...e.producer?{producer:{...e.producer}}:{},...e.attributes?{attributes:structuredClone(e.attributes)}:{}}}function Ae(e){return{...e,nodes:e.nodes.map(Et),edges:e.edges.map(Rt)}}var u=class extends Error{constructor(n,i,o,r){super(i,r);this.code=n;this.detail=o;this.name="XenoArtifactRepositoryError"}code;detail},B=class{records=new Map;currentRevisions=new Map;now;idFactory;eventIds=new Set;idCounter=0;constructor(t={}){this.now=t.now??(()=>new Date().toISOString()),this.idFactory=t.idFactory??(n=>(this.idCounter+=1,`${n}_${Date.now().toString(36)}_${this.idCounter.toString(36)}`)),t.initialState&&this.hydrate(t.initialState)}exportState(){let t=[...this.records.values()].flatMap(n=>[...n.values()]).sort(Xt).map(n=>({artifact:oe(n.artifact),recordVersion:n.recordVersion,lifecycleEvents:structuredClone(n.lifecycleEvents),reviewEvents:structuredClone(n.reviewEvents)}));return{schemaVersion:1,records:t}}async create(t){if(I(t),this.assertInitialState(t),t.revision!==1)throw new u("ARTIFACT_REVISION_INVALID","A new artifact must begin at revision 1",{artifactId:t.artifactId,revision:t.revision});if(this.records.has(t.artifactId))throw new u("ARTIFACT_ALREADY_EXISTS",`Artifact ${t.artifactId} already exists`,{artifactId:t.artifactId});let n=oe(t),i=this.createLifecycleEvent({artifact:n,sequence:1,actor:n.provenance.producer,fromState:null,toState:n.state,reason:"artifact-created"}),o={artifact:n,recordVersion:1,lifecycleEvents:[i],reviewEvents:[]};return this.records.set(n.artifactId,new Map([[n.revision,o]])),this.currentRevisions.set(n.artifactId,n.revision),H(o)}async createRevision(t,n={}){I(t),this.assertInitialState(t);let i=this.getMutable(t.artifactId);this.assertVersion(i,n.expectedRecordVersion);let o=i.artifact.revision+1;if(t.revision!==o||t.predecessorRevision!==i.artifact.revision)throw new u("ARTIFACT_REVISION_INVALID",`Revision ${t.revision} does not follow current revision ${i.artifact.revision}`,{artifactId:t.artifactId,currentRevision:i.artifact.revision,requestedRevision:t.revision});if(_n(t,i.artifact))throw new u("ARTIFACT_CONTENT_UNCHANGED","A new artifact revision must have a different content hash",{artifactId:t.artifactId,revision:t.revision});if(i.artifact.state==="archived")throw new u("ARTIFACT_REVISION_INVALID","Archived artifacts cannot receive new revisions",{artifactId:t.artifactId,revision:i.artifact.revision});if(i.artifact.state!=="superseded"){ie(i.artifact.state,"superseded");let s=this.now(),d=this.createLifecycleEvent({artifact:i.artifact,sequence:i.lifecycleEvents.length+1,actor:n.actor??t.provenance.producer,fromState:i.artifact.state,toState:"superseded",reason:n.reason??`superseded-by-revision-${t.revision}`,recordedAt:s});i.artifact.state="superseded",i.artifact.updatedAt=s,i.lifecycleEvents.push(d),i.recordVersion+=1}let r=oe(t),a=this.createLifecycleEvent({artifact:r,sequence:1,actor:n.actor??r.provenance.producer,fromState:null,toState:r.state,reason:n.reason??`revision-created-from-${i.artifact.revision}`}),c={artifact:r,recordVersion:1,lifecycleEvents:[a],reviewEvents:[]};return this.records.get(r.artifactId)?.set(r.revision,c),this.currentRevisions.set(r.artifactId,r.revision),H(c)}async get(t,n){let i=this.records.get(t);if(!i)return;let o=n??this.currentRevisions.get(t);if(o===void 0)return;let r=i.get(o);return r?H(r):void 0}async require(t,n){let i=await this.get(t,n);if(!i)throw new u("ARTIFACT_NOT_FOUND",`Artifact ${t}${n===void 0?"":` revision ${n}`} was not found`,{artifactId:t,...n===void 0?{}:{revision:n}});return i}async list(t={}){let n=[];for(let[i,o]of this.records)if(!(t.artifactIds&&!t.artifactIds.includes(i)))if(t.includeSuperseded)n.push(...o.values());else{let r=this.currentRevisions.get(i);if(r!==void 0){let a=o.get(r);a&&n.push(a)}}return n.filter(i=>Tn(i.artifact,t)).sort(Xt).map(H)}async listRevisions(t){let n=this.records.get(t);return n?[...n.values()].sort((i,o)=>i.artifact.revision-o.artifact.revision).map(H):[]}async transition(t){let n=this.getMutable(t.artifactId,t.revision);if(this.assertVersion(n,t.expectedRecordVersion),ie(n.artifact.state,t.toState),t.toState==="approved"||t.toState==="rejected"){let a=t.reviewEventId?n.reviewEvents.find(s=>s.eventId===t.reviewEventId&&s.type==="decision-recorded"):void 0,c=ge(n.reviewEvents);if(!a||a.decision!==t.toState||c.latestDecisionEventId!==a.eventId)throw new u("ARTIFACT_REVIEW_DECISION_REQUIRED",`Transition to ${t.toState} requires a matching decision event`,{artifactId:t.artifactId,revision:n.artifact.revision});if(t.toState==="approved"&&c.unresolvedComments>0)throw new u("ARTIFACT_UNRESOLVED_COMMENTS",`Artifact has ${c.unresolvedComments} unresolved review comment(s)`,{artifactId:t.artifactId,revision:n.artifact.revision,unresolvedComments:c.unresolvedComments})}let i=this.now(),o=n.artifact.state,r=this.createLifecycleEvent({artifact:n.artifact,sequence:n.lifecycleEvents.length+1,actor:t.actor,fromState:o,toState:t.toState,reason:t.reason,reviewEventId:t.reviewEventId,recordedAt:i});return n.artifact.state=t.toState,n.artifact.updatedAt=i,n.lifecycleEvents.push(r),n.recordVersion+=1,H(n)}async appendReviewEvent(t){let n=t.event,i=this.getMutable(n.artifactId,n.artifactRevision);if(this.assertVersion(i,t.expectedRecordVersion),i.artifact.state==="archived"||i.artifact.state==="superseded")throw new u("ARTIFACT_REVIEW_INVALID",`Cannot append review events to a ${i.artifact.state} artifact revision`,{artifactId:n.artifactId,revision:n.artifactRevision});if(this.assertReviewCommentState(i,n),(n.type==="review-requested"||n.type==="review-withdrawn"||n.type==="decision-recorded")&&i.artifact.state!=="pending_review")throw new u("ARTIFACT_REVIEW_INVALID",`${n.type} requires an artifact in pending_review state`,{artifactId:n.artifactId,revision:n.artifactRevision});let o={...structuredClone(n),schemaVersion:1,eventId:this.nextEventId("review_event"),sequence:i.reviewEvents.length+1,recordedAt:this.now()},r=he(o,i.artifact);if(r.length>0)throw new M("XENO artifact review event validation failed",r);return i.reviewEvents.push(o),i.recordVersion+=1,H(i)}getMutable(t,n){let i=this.records.get(t),o=n??this.currentRevisions.get(t),r=o===void 0?void 0:i?.get(o);if(!r)throw new u("ARTIFACT_NOT_FOUND",`Artifact ${t}${n===void 0?"":` revision ${n}`} was not found`,{artifactId:t,...n===void 0?{}:{revision:n}});return r}assertVersion(t,n){if(n!==void 0&&n!==t.recordVersion)throw new u("ARTIFACT_CONFLICT",`Expected record version ${n}, found ${t.recordVersion}`,{artifactId:t.artifact.artifactId,revision:t.artifact.revision,expectedRecordVersion:n,actualRecordVersion:t.recordVersion})}assertInitialState(t){if(t.state!=="draft"&&t.state!=="pending_review")throw new u("ARTIFACT_REVISION_INVALID","New artifact revisions must begin in draft or pending_review state",{artifactId:t.artifactId,revision:t.revision})}assertReviewCommentState(t,n){if(n.type==="comment-added"){if(t.reviewEvents.some(r=>r.type==="comment-added"&&r.commentId===n.commentId))throw new u("ARTIFACT_REVIEW_INVALID",`Comment ${n.commentId} already exists`);if(n.parentCommentId&&!t.reviewEvents.some(r=>r.type==="comment-added"&&r.commentId===n.parentCommentId))throw new u("ARTIFACT_REVIEW_INVALID",`Parent comment ${n.parentCommentId} does not exist`);return}if(n.type!=="comment-resolved"&&n.type!=="comment-reopened")return;if(!t.reviewEvents.some(r=>r.type==="comment-added"&&r.commentId===n.commentId))throw new u("ARTIFACT_REVIEW_INVALID",`Comment ${n.commentId} does not exist`);let o=kn(t.reviewEvents,n.commentId);if(n.type==="comment-resolved"&&o.resolved)throw new u("ARTIFACT_REVIEW_INVALID",`Comment ${n.commentId} is already resolved`);if(n.type==="comment-reopened"&&!o.resolved)throw new u("ARTIFACT_REVIEW_INVALID",`Comment ${n.commentId} is not resolved`)}createLifecycleEvent(t){return{schemaVersion:1,eventId:this.nextEventId("artifact_event"),artifactId:t.artifact.artifactId,revision:t.artifact.revision,sequence:t.sequence,recordedAt:t.recordedAt??this.now(),actor:{...t.actor},fromState:t.fromState,toState:t.toState,...t.reason?{reason:t.reason}:{},...t.reviewEventId?{reviewEventId:t.reviewEventId}:{}}}nextEventId(t){let n=this.idFactory(t);if(typeof n!="string"||n.trim().length===0||this.eventIds.has(n))throw new u("ARTIFACT_CONFLICT",`Event ID factory produced an invalid or duplicate ${t} ID`);return this.eventIds.add(n),n}hydrate(t){if(t.schemaVersion!==1||!Array.isArray(t.records))throw new u("ARTIFACT_REVISION_INVALID","Artifact repository state has an unsupported schema or record collection");let n=[...t.records].sort((i,o)=>i.artifact.artifactId.localeCompare(o.artifact.artifactId)||i.artifact.revision-o.artifact.revision);for(let i of n){let o=bn(i,this.eventIds),r=this.records.get(o.artifact.artifactId);if(r||(r=new Map,this.records.set(o.artifact.artifactId,r)),r.has(o.artifact.revision))throw new u("ARTIFACT_REVISION_INVALID",`Duplicate persisted revision ${o.artifact.artifactId}:${o.artifact.revision}`);r.set(o.artifact.revision,o),this.currentRevisions.set(o.artifact.artifactId,o.artifact.revision)}for(let[i,o]of this.records){let r=[...o.values()].sort((a,c)=>a.artifact.revision-c.artifact.revision);for(let a=0;a<r.length;a+=1){let c=r[a],s=a+1;if(c.artifact.revision!==s)throw new u("ARTIFACT_REVISION_INVALID",`Persisted artifact ${i} is missing revision ${s}`);if(a===0&&c.artifact.predecessorRevision!==void 0)throw new u("ARTIFACT_REVISION_INVALID",`Initial revision for ${i} cannot declare a predecessor`);if(a>0&&c.artifact.predecessorRevision!==s-1)throw new u("ARTIFACT_REVISION_INVALID",`Persisted revision ${i}:${s} has an invalid predecessor`);if(a<r.length-1&&c.artifact.state!=="superseded")throw new u("ARTIFACT_REVISION_INVALID",`Non-current revision ${i}:${s} must be superseded`)}}}};function bn(e,t){if(I(e.artifact),!Number.isInteger(e.recordVersion)||e.recordVersion<1)throw new u("ARTIFACT_REVISION_INVALID","Persisted artifact recordVersion must be a positive integer",{artifactId:e.artifact.artifactId,revision:e.artifact.revision});if(!Array.isArray(e.lifecycleEvents)||e.lifecycleEvents.length===0||!Array.isArray(e.reviewEvents))throw new u("ARTIFACT_REVISION_INVALID","Persisted artifact records require lifecycle and review event arrays",{artifactId:e.artifact.artifactId,revision:e.artifact.revision});let n=e.lifecycleEvents.length+e.reviewEvents.length;if(e.recordVersion!==n)throw new u("ARTIFACT_REVISION_INVALID",`Persisted record version ${e.recordVersion} does not match ${n} mutations`,{artifactId:e.artifact.artifactId,revision:e.artifact.revision});let i=null;for(let r=0;r<e.lifecycleEvents.length;r+=1){let a=e.lifecycleEvents[r];if(a.schemaVersion!==1||a.artifactId!==e.artifact.artifactId||a.revision!==e.artifact.revision||a.sequence!==r+1||a.fromState!==i||typeof a.eventId!="string"||a.eventId.length===0||t.has(a.eventId)||!Number.isFinite(Date.parse(a.recordedAt)))throw new u("ARTIFACT_REVISION_INVALID",`Persisted lifecycle event ${r+1} is invalid`,{artifactId:e.artifact.artifactId,revision:e.artifact.revision});if(i===null){if(a.toState!=="draft"&&a.toState!=="pending_review")throw new u("ARTIFACT_REVISION_INVALID","A persisted artifact must begin in draft or pending_review state",{artifactId:e.artifact.artifactId,revision:e.artifact.revision})}else ie(i,a.toState);t.add(a.eventId),i=a.toState}if(i!==e.artifact.state)throw new u("ARTIFACT_REVISION_INVALID","Persisted artifact state does not match its lifecycle tail",{artifactId:e.artifact.artifactId,revision:e.artifact.revision});let o=new Map;for(let r=0;r<e.reviewEvents.length;r+=1){let a=e.reviewEvents[r];if(a.sequence!==r+1||t.has(a.eventId))throw new u("ARTIFACT_REVIEW_INVALID",`Persisted review event ${r+1} has an invalid sequence or duplicate ID`,{artifactId:e.artifact.artifactId,revision:e.artifact.revision});let c=he(a,e.artifact);if(c.length>0)throw new M("Persisted XENO artifact review event validation failed",c);if(a.type==="comment-added"){if(o.has(a.commentId)||a.parentCommentId!==void 0&&!o.has(a.parentCommentId))throw new u("ARTIFACT_REVIEW_INVALID",`Persisted comment ${a.commentId} has an invalid identity or parent`);o.set(a.commentId,!1)}else if(a.type==="comment-resolved"||a.type==="comment-reopened"){let s=o.get(a.commentId);if(s===void 0||a.type==="comment-resolved"&&s||a.type==="comment-reopened"&&!s)throw new u("ARTIFACT_REVIEW_INVALID",`Persisted comment transition for ${a.commentId} is invalid`);o.set(a.commentId,a.type==="comment-resolved")}t.add(a.eventId)}return{artifact:oe(e.artifact),recordVersion:e.recordVersion,lifecycleEvents:structuredClone(e.lifecycleEvents),reviewEvents:structuredClone(e.reviewEvents)}}function _n(e,t){return e.content.hash.algorithm===t.content.hash.algorithm&&e.content.hash.value===t.content.hash.value}function Tn(e,t){return!(t.kinds&&!t.kinds.includes(e.kind)||t.states&&!t.states.includes(e.state)||t.runId&&e.identity?.runId!==t.runId||t.sessionId&&e.identity?.sessionId!==t.sessionId||t.turnId&&e.identity?.turnId!==t.turnId||t.taskId&&e.identity?.taskId!==t.taskId||t.workspaceId&&e.identity?.workspaceId!==t.workspaceId||t.repositoryId&&e.identity?.repositoryId!==t.repositoryId||t.producerId&&e.provenance.producer.id!==t.producerId||t.sensitivity&&!t.sensitivity.includes(e.sensitivity))}function Xt(e,t){return e.artifact.createdAt.localeCompare(t.artifact.createdAt)||e.artifact.artifactId.localeCompare(t.artifact.artifactId)||e.artifact.revision-t.artifact.revision}function kn(e,t){let n=!1;for(let i of e)(i.type==="comment-resolved"||i.type==="comment-reopened")&&i.commentId===t&&(n=i.type==="comment-resolved");return{resolved:n}}function oe(e){return structuredClone(e)}function H(e){return{artifact:oe(e.artifact),recordVersion:e.recordVersion,etag:`${e.artifact.artifactId}:${e.artifact.revision}:${e.recordVersion}`,lifecycleEvents:structuredClone(e.lifecycleEvents),reviewEvents:structuredClone(e.reviewEvents),reviewSummary:ge(e.reviewEvents)}}var Ue=require("node:crypto"),b=require("node:fs/promises"),N=require("node:path");var V=require("node:fs"),Me=require("node:os"),bt=require("node:path");function xn(){return new Date().toISOString()}function Cn(){return new Date(Date.now()-Math.floor(process.uptime()*1e3)).toISOString()}function _t(e){try{return JSON.parse((0,V.readFileSync)(e,"utf8"))}catch{return null}}function Nn(e){if(!e||e<=0)return!1;try{return process.kill(e,0),!0}catch{return!1}}function Vn(e){return e.hostname!==(0,Me.hostname)()?!0:Nn(e.pid)}function St(e,t){(0,V.mkdirSync)((0,bt.dirname)(e),{recursive:!0}),(0,V.writeFileSync)(e,JSON.stringify(t,null,2)+`
2
- `,{encoding:"utf8",flag:"wx"})}function Pn(e,t){let n=_t(e);n?.pid!==t.pid||n.hostname!==t.hostname||(0,V.rmSync)(e,{force:!0})}function Tt(e,t,n){let i=xn(),o={schemaVersion:1,name:t,pid:process.pid,hostname:(0,Me.hostname)(),processStartedAt:Cn(),version:n,acquiredAt:i,updatedAt:i};try{St(e,o)}catch(r){if(r.code!=="EEXIST")throw r;let c=_t(e);if(c&&Vn(c))throw new Error(`${t} is already locked by PID ${c.pid} on ${c.hostname}.`);(0,V.rmSync)(e,{force:!0}),St(e,o)}return{record:o,release:()=>{Pn(e,o)}}}var kt="0.9.10";var We=1,$n="repository.v1.json",On=5e3,Dn=20,Fn=64*1024*1024,qe=class{directory;snapshotPath;backupPath;lockPath;now;lockTimeoutMs;lockRetryMs;maxSnapshotBytes;onRecovery;mutationTail=Promise.resolve();constructor(t){if(!t||typeof t.directory!="string"||t.directory.trim().length===0)throw new TypeError("Artifact repository directory is required");let n=t.snapshotFileName??$n;if((0,N.basename)(n)!==n||!/^[A-Za-z0-9_.-]+$/.test(n))throw new TypeError("Artifact snapshot filename must be a safe basename");this.directory=(0,N.resolve)(t.directory),this.snapshotPath=(0,N.join)(this.directory,n),this.backupPath=`${this.snapshotPath}.bak`,this.lockPath=`${this.snapshotPath}.lock`,this.now=t.now??(()=>new Date().toISOString()),this.lockTimeoutMs=He(t.lockTimeoutMs,On,100,6e4,"lockTimeoutMs"),this.lockRetryMs=He(t.lockRetryMs,Dn,1,1e3,"lockRetryMs"),this.maxSnapshotBytes=He(t.maxSnapshotBytes,Fn,1024,1024*1024*1024,"maxSnapshotBytes"),this.onRecovery=t.onRecovery}async create(t){return this.mutate(n=>n.create(t))}async createRevision(t,n){return this.mutate(i=>i.createRevision(t,n))}async get(t,n){return(await this.load()).repository.get(t,n)}async require(t,n){return(await this.load()).repository.require(t,n)}async list(t){return(await this.load()).repository.list(t)}async listRevisions(t){return(await this.load()).repository.listRevisions(t)}async transition(t){return this.mutate(n=>n.transition(t))}async appendReviewEvent(t){return this.mutate(n=>n.appendReviewEvent(t))}async inspectSnapshot(){return this.readSnapshot(this.snapshotPath,!0)}async mutate(t){return this.enqueueMutation(async()=>{let n=await this.acquireLock();try{let i=await this.load(),o=await t(i.repository);return await this.persist(i),o}finally{n.release()}})}async enqueueMutation(t){let n=this.mutationTail.then(t,t);return this.mutationTail=n.then(()=>{},()=>{}),n}async acquireLock(){let t=Date.now(),n;for(;Date.now()-t<=this.lockTimeoutMs;)try{return Tt(this.lockPath,`artifact-repository:${(0,N.basename)(this.snapshotPath)}`,kt)}catch(i){if(!(i instanceof Error)||!/already locked by PID/.test(i.message))throw i;n=i,await qn(this.lockRetryMs)}throw new u("ARTIFACT_PERSISTENCE_LOCKED",`Artifact repository remained locked for ${this.lockTimeoutMs}ms`,{snapshotPath:this.snapshotPath},{cause:n})}async load(){let t,n,i=!1;try{n=await this.readSnapshot(this.snapshotPath,!1)}catch(r){t=Ie(r)}if(!n&&(t||await jn(this.backupPath)))try{let r=await this.readSnapshot(this.backupPath,!0);r&&(this.onRecovery?.({snapshotPath:this.snapshotPath,backupPath:this.backupPath,reason:t?.message??"primary snapshot missing"}),n=r,i=!0)}catch(r){throw t?new u("ARTIFACT_PERSISTENCE_CORRUPT","Artifact repository primary and backup snapshots are unreadable",{snapshotPath:this.snapshotPath,backupPath:this.backupPath},{cause:new AggregateError([t,Ie(r)])}):r}if(!n&&t)throw t;let o=n?.state??{schemaVersion:1,records:[]};return{repository:new B({now:this.now,idFactory:r=>`${r}_${(0,Ue.randomUUID)()}`,initialState:o}),generation:n?.generation??0,createdAt:n?.createdAt??this.now(),hasSnapshot:n!==void 0,recoveredFromBackup:i,...n?{sourceSnapshot:n}:{}}}async persist(t){let n=this.now(),o={...{schemaVersion:We,generation:t.generation,createdAt:t.createdAt,updatedAt:n,state:t.repository.exportState()},generation:t.generation+1},r=Mn(o),a=`${JSON.stringify(r,null,2)}
2
+ `,{encoding:"utf8",flag:"wx"})}function Pn(e,t){let n=_t(e);n?.pid!==t.pid||n.hostname!==t.hostname||(0,V.rmSync)(e,{force:!0})}function Tt(e,t,n){let i=xn(),o={schemaVersion:1,name:t,pid:process.pid,hostname:(0,Me.hostname)(),processStartedAt:Cn(),version:n,acquiredAt:i,updatedAt:i};try{St(e,o)}catch(r){if(r.code!=="EEXIST")throw r;let c=_t(e);if(c&&Vn(c))throw new Error(`${t} is already locked by PID ${c.pid} on ${c.hostname}.`);(0,V.rmSync)(e,{force:!0}),St(e,o)}return{record:o,release:()=>{Pn(e,o)}}}var kt="0.9.14";var We=1,$n="repository.v1.json",On=5e3,Dn=20,Fn=64*1024*1024,qe=class{directory;snapshotPath;backupPath;lockPath;now;lockTimeoutMs;lockRetryMs;maxSnapshotBytes;onRecovery;mutationTail=Promise.resolve();constructor(t){if(!t||typeof t.directory!="string"||t.directory.trim().length===0)throw new TypeError("Artifact repository directory is required");let n=t.snapshotFileName??$n;if((0,N.basename)(n)!==n||!/^[A-Za-z0-9_.-]+$/.test(n))throw new TypeError("Artifact snapshot filename must be a safe basename");this.directory=(0,N.resolve)(t.directory),this.snapshotPath=(0,N.join)(this.directory,n),this.backupPath=`${this.snapshotPath}.bak`,this.lockPath=`${this.snapshotPath}.lock`,this.now=t.now??(()=>new Date().toISOString()),this.lockTimeoutMs=He(t.lockTimeoutMs,On,100,6e4,"lockTimeoutMs"),this.lockRetryMs=He(t.lockRetryMs,Dn,1,1e3,"lockRetryMs"),this.maxSnapshotBytes=He(t.maxSnapshotBytes,Fn,1024,1024*1024*1024,"maxSnapshotBytes"),this.onRecovery=t.onRecovery}async create(t){return this.mutate(n=>n.create(t))}async createRevision(t,n){return this.mutate(i=>i.createRevision(t,n))}async get(t,n){return(await this.load()).repository.get(t,n)}async require(t,n){return(await this.load()).repository.require(t,n)}async list(t){return(await this.load()).repository.list(t)}async listRevisions(t){return(await this.load()).repository.listRevisions(t)}async transition(t){return this.mutate(n=>n.transition(t))}async appendReviewEvent(t){return this.mutate(n=>n.appendReviewEvent(t))}async inspectSnapshot(){return this.readSnapshot(this.snapshotPath,!0)}async mutate(t){return this.enqueueMutation(async()=>{let n=await this.acquireLock();try{let i=await this.load(),o=await t(i.repository);return await this.persist(i),o}finally{n.release()}})}async enqueueMutation(t){let n=this.mutationTail.then(t,t);return this.mutationTail=n.then(()=>{},()=>{}),n}async acquireLock(){let t=Date.now(),n;for(;Date.now()-t<=this.lockTimeoutMs;)try{return Tt(this.lockPath,`artifact-repository:${(0,N.basename)(this.snapshotPath)}`,kt)}catch(i){if(!(i instanceof Error)||!/already locked by PID/.test(i.message))throw i;n=i,await qn(this.lockRetryMs)}throw new u("ARTIFACT_PERSISTENCE_LOCKED",`Artifact repository remained locked for ${this.lockTimeoutMs}ms`,{snapshotPath:this.snapshotPath},{cause:n})}async load(){let t,n,i=!1;try{n=await this.readSnapshot(this.snapshotPath,!1)}catch(r){t=Ie(r)}if(!n&&(t||await jn(this.backupPath)))try{let r=await this.readSnapshot(this.backupPath,!0);r&&(this.onRecovery?.({snapshotPath:this.snapshotPath,backupPath:this.backupPath,reason:t?.message??"primary snapshot missing"}),n=r,i=!0)}catch(r){throw t?new u("ARTIFACT_PERSISTENCE_CORRUPT","Artifact repository primary and backup snapshots are unreadable",{snapshotPath:this.snapshotPath,backupPath:this.backupPath},{cause:new AggregateError([t,Ie(r)])}):r}if(!n&&t)throw t;let o=n?.state??{schemaVersion:1,records:[]};return{repository:new B({now:this.now,idFactory:r=>`${r}_${(0,Ue.randomUUID)()}`,initialState:o}),generation:n?.generation??0,createdAt:n?.createdAt??this.now(),hasSnapshot:n!==void 0,recoveredFromBackup:i,...n?{sourceSnapshot:n}:{}}}async persist(t){let n=this.now(),o={...{schemaVersion:We,generation:t.generation,createdAt:t.createdAt,updatedAt:n,state:t.repository.exportState()},generation:t.generation+1},r=Mn(o),a=`${JSON.stringify(r,null,2)}
3
3
  `;if(Buffer.byteLength(a,"utf8")>this.maxSnapshotBytes)throw new u("ARTIFACT_PERSISTENCE_IO",`Artifact repository snapshot exceeds ${this.maxSnapshotBytes} bytes`,{snapshotPath:this.snapshotPath,maxSnapshotBytes:this.maxSnapshotBytes});await(0,b.mkdir)(this.directory,{recursive:!0,mode:448}),t.hasSnapshot&&!t.recoveredFromBackup&&t.sourceSnapshot&&await xt(this.backupPath,`${JSON.stringify(t.sourceSnapshot,null,2)}
4
4
  `),await xt(this.snapshotPath,a)}async readSnapshot(t,n){let i;try{i=await(0,b.stat)(t)}catch(o){if(!n&&Je(o,"ENOENT")||n&&Je(o,"ENOENT"))return;throw Be("Unable to inspect artifact repository snapshot",t,o)}if(!i.isFile()||i.size>this.maxSnapshotBytes)throw new u("ARTIFACT_PERSISTENCE_CORRUPT","Artifact repository snapshot is not a bounded regular file",{snapshotPath:t,sizeBytes:i.size,maxSnapshotBytes:this.maxSnapshotBytes});try{let o=await(0,b.readFile)(t);if(o.byteLength>this.maxSnapshotBytes)throw new Error("snapshot grew beyond the configured size limit while reading");return Ln(JSON.parse(o.toString("utf8")),t)}catch(o){throw o instanceof u?o:Be("Unable to parse artifact repository snapshot",t,o,!0)}}};function Ln(e,t){if(!je(e)||e.schemaVersion!==We||!Number.isInteger(e.generation)||e.generation<0||typeof e.createdAt!="string"||!Number.isFinite(Date.parse(e.createdAt))||typeof e.updatedAt!="string"||!Number.isFinite(Date.parse(e.updatedAt))||!je(e.state)||e.state.schemaVersion!==1||!Array.isArray(e.state.records)||!je(e.checksum)||e.checksum.algorithm!=="sha256"||typeof e.checksum.value!="string")throw new u("ARTIFACT_PERSISTENCE_CORRUPT","Artifact repository snapshot envelope is invalid",{snapshotPath:t});let n=e,i=Hn(n),o=Ct(i);if(n.checksum.value!==o)throw new u("ARTIFACT_PERSISTENCE_CORRUPT","Artifact repository snapshot checksum does not match its payload",{snapshotPath:t});return new B({initialState:n.state}),structuredClone(n)}function Mn(e){return{...structuredClone(e),checksum:{algorithm:"sha256",value:Ct(e)}}}function Hn(e){return{schemaVersion:e.schemaVersion,generation:e.generation,createdAt:e.createdAt,updatedAt:e.updatedAt,state:e.state}}function Ct(e){return T(JSON.stringify(e)).value}async function xt(e,t){await(0,b.mkdir)((0,N.dirname)(e),{recursive:!0,mode:448});let n=`${e}.tmp.${process.pid}.${(0,Ue.randomUUID)()}`,i;try{i=await(0,b.open)(n,"wx",384),await i.writeFile(t,{encoding:"utf8"}),await i.sync(),await i.close(),i=void 0,await(0,b.rename)(n,e);try{let o=await(0,b.open)((0,N.dirname)(e),"r");try{await o.sync()}finally{await o.close()}}catch{}}finally{i&&await i.close().catch(()=>{}),await(0,b.unlink)(n).catch(()=>{})}}function He(e,t,n,i,o){if(e===void 0)return t;if(!Number.isInteger(e)||e<n||e>i)throw new TypeError(`${o} must be an integer between ${n} and ${i}`);return e}function je(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Je(e,t){return e instanceof Error&&e.code===t}async function jn(e){try{return(await(0,b.stat)(e)).isFile()}catch(t){if(Je(t,"ENOENT"))return!1;throw Be("Unable to inspect artifact repository backup",e,t)}}function Ie(e){return e instanceof Error?e:new Error(String(e))}function Be(e,t,n,i=!1){return new u(i?"ARTIFACT_PERSISTENCE_CORRUPT":"ARTIFACT_PERSISTENCE_IO",`${e}: ${Ie(n).message}`,{snapshotPath:t},{cause:Ie(n)})}function qn(e){return new Promise(t=>setTimeout(t,e))}var ze=require("node:buffer");var Jn=16*1024*1024,Bn=5e3,Un=1e5,Wn=1e6,zn=/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(?:\s?(.*))?$/,X=class extends Error{constructor(n,i){super(i===void 0?n:`${n} at diff line ${i}`);this.line=i;this.name="XenoDiffParseError"}line;code="XENO_DIFF_INVALID"};function Ke(e,t={}){if(typeof e!="string")throw new TypeError("Unified diff must be a string");let n=we(t.maxBytes,Jn,1024,256*1024*1024,"maxBytes"),i=we(t.maxFiles,Bn,1,1e5,"maxFiles"),o=we(t.maxHunks,Un,1,1e6,"maxHunks"),r=we(t.maxLines,Wn,1,5e6,"maxLines");if(ze.Buffer.byteLength(e,"utf8")>n)throw new X(`Unified diff exceeds ${n} bytes`);let a=e.replace(/\r\n/g,`
5
5
  `).replace(/\r/g,`