@crewx/sdk 0.9.0-rc.178 → 0.9.0-rc.179

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.
@@ -1,2 +1,2 @@
1
- import {join,resolve,dirname,relative,sep,isAbsolute}from'path';import'url';import {createHash}from'crypto';import {isIP}from'net';import {existsSync,readFileSync,statSync,readdirSync,constants}from'fs';import {realpath,stat,readdir,open,lstat}from'fs/promises';import {load}from'js-yaml';var Vr=Object.defineProperty;var w=(e,n)=>()=>(e&&(n=e(e=0)),n);var Fr=(e,n)=>{for(var t in n)Vr(e,t,{get:n[t],enumerable:true});};var g=w(()=>{});var U,Pn=w(()=>{g();U=class extends Error{constructor(t,i=t,r){super(i);this.code=t;this.currentRevision=r;}code;currentRevision;name="UiRuntimeError"};});function lt(e){return Br.test(e)||Hr.test(e)}function ae(){throw new U("INPUT_INVALID","JSON value is not projection-safe")}function $r(e){let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function dt(e,n,t,i,r,o){if(n>i&&ae(),e===null||typeof e=="string"||typeof e=="boolean")return typeof e=="string"&&(zr.test(e)||Gr.test(e)&&!Kr(r,o)||Jr.test(e))&&ae(),e;if(typeof e=="number")return Number.isFinite(e)||ae(),e;(typeof e!="object"||e===void 0||typeof e=="function"||typeof e=="bigint")&&ae();let a=e;t.has(a)&&ae(),t.add(a);try{if(Array.isArray(e))return e.map(c=>dt(c,n+1,t,i,r,o));$r(a)||ae();let s={};for(let[c,d]of Object.entries(e))lt(c)&&ae(),s[c]=dt(d,n+1,t,i,[...r,c],o);return s}finally{t.delete(a);}}function ce(e,n=0,t=[]){(!Number.isInteger(n)||n<0||n>Xr)&&ae(),(!Array.isArray(t)||t.some(r=>typeof r!="string"))&&ae();let i=dt(e,0,new Set,Wr+n,[],t);return (i===null||Array.isArray(i)||typeof i!="object")&&ae(),i}function He(e,n){if(!e||!n)return false;let t=e.split("."),i=n.split(".");return t.length>=i.length&&i.every((r,o)=>t[o]===r)}function Kr(e,n){if(e.length===0)return false;let t=e.join(".");return n.some(i=>He(t,i))}function ze(e){try{let n=JSON.stringify(e);return n===void 0&&ae(),n}catch{ae();}}function pt(e){return Array.isArray(e)?e.map(pt):e!==null&&typeof e=="object"?Object.fromEntries(Object.keys(e).sort().map(n=>[n,pt(e[n])])):e}function Q(e){return ze(pt(e))}function ut(e){return Buffer.byteLength(e,"utf8")}var Br,Hr,zr,Jr,Gr,Wr,Xr,Ne=w(()=>{g();Pn();Br=/(?:proof|token|secret|password|cookie|authorization|private[_-]?key|stack|exception|plugin[_-]?text)/i,Hr=/(?:url|uri|endpoint|path|file(?:name|path)?|cwd|shell|directory|dir|folder)$/i,zr=/<\/?[A-Za-z][^>]*>/,Jr=/^(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)/,Gr=/^(?:https?|file|ftp|ws|wss):\/\//i;Wr=8,Xr=4;});var Sn,ft=w(()=>{g();Sn=["text/plain","application/json"];});var Ti=w(()=>{g();ft();});function Je(e){return qr.has(e)||Zr.test(e)||Qr.test(e)}var Di,qr,Zr,Qr,Mn,tn,me,yt,At,It,gt,mt,Ce=w(()=>{g();Di=["__proto__","prototype","constructor","proof","token","secret","password","cookie","authorization","private_key","private-key","stack","exception","plugin_text","url","uri","endpoint","path","filename","filepath","cwd","shell","directory","dir","folder"],qr=new Set(Di),Zr=/(?:proof|token|secret|password|cookie|authorization|private[_-]?key|stack|exception|plugin[_-]?text)/i,Qr=/(?:url|uri|endpoint|path|file(?:name|path)?|cwd|shell|directory|dir|folder)$/i;Mn=/^[A-Za-z0-9_]+$/,tn=/^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)*$/,me=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,yt=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/,At=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,It=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/,gt=["blue","violet","emerald","amber","rose","sky","slate","indigo"],mt=["inline","panel"];});function ht(e){return typeof e=="string"&&Sn.includes(e)}var Ni=w(()=>{g();ft();Ce();});function On(e){if(!_t(e))return false;let n=Object.keys(e);return !(n.some(t=>t!=="in"&&t!=="out")||n.length===0||Object.hasOwn(e,"in")&&!es(e.in)||Object.hasOwn(e,"out")&&!ns(e.out))}function es(e){return _t(e)?Object.keys(e).every(t=>t==="mediaType"||t==="required")&&Object.hasOwn(e,"mediaType")&&ht(e.mediaType)&&(!Object.hasOwn(e,"required")||typeof e.required=="boolean"):false}function ns(e){return _t(e)?Object.keys(e).every(t=>t==="mediaType"||t==="range")&&Object.hasOwn(e,"mediaType")&&ht(e.mediaType)&&(!Object.hasOwn(e,"range")||typeof e.range=="boolean"):false}function _t(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}var Et=w(()=>{g();Ti();Ni();new TextDecoder("utf-8",{fatal:true,ignoreBOM:true});});function Rn(e){return ts.includes(e)}function Un(e){return Number.isSafeInteger(e)&&e>=Ln.min&&e<=Ln.max}var ts,Ln,bi,Tt=w(()=>{g();ts=[5,15,30,60],Ln=Object.freeze({min:15e3,max:6e5,default:3e5}),bi=1;});function wn(e){return Number.isSafeInteger(e)&&e>=Cn.min&&e<=Cn.max}function kn(e){return is.includes(e)}var Cn,Pi,is,Dt=w(()=>{g();Cn=Object.freeze({min:6e4,max:18e5,default:6e5}),Pi=1,is=["start","status","cancel"];});function oe(e){let t=e.renderer!==void 0||e.surfaces!==void 0||e.stateProjection!==void 0||e.dataPaths!==void 0||e.usage!==void 0||e.detailPanel!==void 0||e.displayModes!==void 0||e.summaryProjection!==void 0||e.downloads!==void 0||e.legacy!==void 0||Object.values(e.actions).some(r=>r.resultProjection!==void 0)?{id:e.id,version:e.version,...e.renderer===void 0?{}:{renderer:e.renderer},...e.surfaces===void 0?{}:{surfaces:e.surfaces},...e.stateProjection===void 0?{}:{stateProjection:e.stateProjection},...e.dataPaths===void 0?{}:{dataPaths:e.dataPaths},...e.summaryProjection===void 0?{}:{summaryProjection:e.summaryProjection},...e.legacy===void 0?{}:{legacy:e.legacy},...e.usage===void 0?{}:{usage:e.usage},...e.detailPanel===void 0?{}:{detailPanel:e.detailPanel},...e.displayModes===void 0?{}:{displayModes:e.displayModes},...e.downloads===void 0?{}:{downloads:e.downloads},...e.sourceHash===void 0?{}:{sourceHash:e.sourceHash},actions:e.actions}:e.sourceHash===void 0?{id:e.id,version:e.version,actions:e.actions}:{id:e.id,version:e.version,sourceHash:e.sourceHash,actions:e.actions},i=ce(t);return createHash("sha256").update(Q(i)).digest("hex")}function bt(e){return `${e.id}\0${e.version}`}function de(e){if(!/^\d+$/.test(String(e.version))||e.version<1||e.id.length<1||e.id.length>128)throw new U("DEFINITION_UNSUPPORTED","UI definition is invalid");if(e.sourceHash!==void 0&&(typeof e.sourceHash!="string"||!rs.test(e.sourceHash)))throw new U("DEFINITION_UNSUPPORTED","UI definition source hash is invalid");if(!/^[0-9a-f]{64}$/.test(e.hash)||oe(e)!==e.hash)throw new U("DEFINITION_UNSUPPORTED","UI definition hash is invalid");for(let[n,t]of Object.entries(e.actions)){if(!n||!Array.isArray(t.capabilities)||t.capabilities.some(i=>!as(i)))throw new U("DEFINITION_UNSUPPORTED","UI action declaration is invalid");if(t.confirmation!==void 0&&t.confirmation!=="none"&&t.confirmation!=="native")throw new U("DEFINITION_UNSUPPORTED","UI action confirmation is invalid");if(t.inputKeys&&(!Array.isArray(t.inputKeys)||t.inputKeys.some(i=>typeof i!="string"||!i)))throw new U("DEFINITION_UNSUPPORTED","UI action input declaration is invalid");if(t.dataInputs!==void 0&&(!Array.isArray(t.dataInputs)||new Set(t.dataInputs).size!==t.dataInputs.length||t.dataInputs.some(i=>typeof i!="string"||!i||t.inputKeys!==void 0&&!t.inputKeys.includes(i))))throw new U("DEFINITION_UNSUPPORTED","UI action data input declaration is invalid");if(t.resultProjection&&Nt(t.resultProjection),t.schedule!==void 0&&(!Rn(t.schedule.everyMinutes)||!Un(t.schedule.timeoutMs)))throw new U("DEFINITION_UNSUPPORTED","UI action schedule declaration is invalid");if(t.job!==void 0&&(typeof t.job!="object"||Object.keys(t.job).some(i=>i!=="deadlineMs")||!wn(t.job.deadlineMs)))throw new U("DEFINITION_UNSUPPORTED","UI action job declaration is invalid");if(t.jobAccess!==void 0&&(!Array.isArray(t.jobAccess)||t.jobAccess.length===0||new Set(t.jobAccess).size!==t.jobAccess.length||!t.jobAccess.every(kn)||t.job!==void 0))throw new U("DEFINITION_UNSUPPORTED","UI action job control declaration is invalid");if(t.content!==void 0&&!On(t.content))throw new U("DEFINITION_UNSUPPORTED","UI action content declaration is invalid");if(t.env!==void 0&&(!Array.isArray(t.env)||t.env.length===0||new Set(t.env).size!==t.env.length||t.env.some(i=>i!=="CREWX_APP_INSTANCE_ID"&&i!=="CREWX_THREAD_ID")))throw new U("DEFINITION_UNSUPPORTED","UI action environment declaration is invalid")}if(e.renderer!==void 0&&(!e.renderer||e.renderer.length>128))throw new U("DEFINITION_UNSUPPORTED","UI definition renderer is invalid");if(e.surfaces&&(!Array.isArray(e.surfaces)||e.surfaces.some(n=>!n||n.length>64)))throw new U("DEFINITION_UNSUPPORTED","UI definition surfaces are invalid");if(e.usage!==void 0&&e.usage!=="card"&&e.usage!=="window")throw new U("DEFINITION_UNSUPPORTED","UI definition usage is invalid");if(e.detailPanel!==void 0&&typeof e.detailPanel!="boolean")throw new U("DEFINITION_UNSUPPORTED","UI definition detailPanel is invalid");if(e.displayModes&&(!Array.isArray(e.displayModes)||e.displayModes.length===0||new Set(e.displayModes).size!==e.displayModes.length||e.displayModes.some(n=>n!=="inline"&&n!=="floating"&&n!=="focused")))throw new U("DEFINITION_UNSUPPORTED","UI definition displayModes are invalid");if(e.usage==="card"&&e.displayModes!==void 0)throw new U("DEFINITION_UNSUPPORTED","Card definitions cannot declare displayModes");if(e.usage==="window"&&e.detailPanel!==void 0)throw new U("DEFINITION_UNSUPPORTED","Window definitions cannot declare detailPanel");if(e.stateProjection&&Nt(e.stateProjection),e.summaryProjection){Nt(e.summaryProjection);let n=new Set(e.stateProjection?.allow??[]);if(e.summaryProjection.allow.some(t=>!n.has(t)))throw new U("DEFINITION_UNSUPPORTED","UI summary projection exceeds state projection")}if(e.legacy!==void 0){if(!e.legacy||typeof e.legacy!="object"||Array.isArray(e.legacy)||Object.keys(e.legacy).some(r=>!["readTool","actionTool","hostTools","agentAccess"].includes(r)))throw new U("DEFINITION_UNSUPPORTED","UI legacy metadata is invalid");let n=new Set;for(let[r,o]of [["readTool",e.legacy.readTool],["actionTool",e.legacy.actionTool]])if(o!==void 0){if(ss(o,r==="readTool"),n.has(o.name))throw new U("DEFINITION_UNSUPPORTED","UI legacy tool names collide");n.add(o.name);}let t=e.legacy.hostTools;if(t!==void 0){if(!t||typeof t!="object"||Array.isArray(t))throw new U("DEFINITION_UNSUPPORTED","UI legacy host tools are invalid");let r={"doc.open":"crewx_app_html_viewer_open","pty.connect":"crewx_app_terminal_connect"};for(let[o,a]of Object.entries(t)){if(!Object.hasOwn(r,o)||r[o]!==a||typeof a!="string"||!/^[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(a)||n.has(a))throw new U("DEFINITION_UNSUPPORTED","UI legacy host tools are invalid");n.add(a);}}let i=e.legacy.agentAccess;if(i!==void 0&&(!i||typeof i!="object"||Array.isArray(i)||Object.entries(i).some(([r,o])=>!r||!Object.hasOwn(e.actions,r)||o!=="allowed"&&o!=="denied")))throw new U("DEFINITION_UNSUPPORTED","UI legacy agent access is invalid");if(e.legacy.actionTool!==void 0&&(!i||Object.keys(i).length===0))throw new U("DEFINITION_UNSUPPORTED","UI legacy action tool requires its complete agent access map")}if(e.downloads!==void 0&&e.downloads!==true)throw new U("DEFINITION_UNSUPPORTED","UI definition downloads is invalid");if(e.dataPaths!==void 0){let n=new Set(["__proto__","prototype","constructor"]);if(!Array.isArray(e.dataPaths)||e.dataPaths.length>16||new Set(e.dataPaths).size!==e.dataPaths.length||e.dataPaths.some(t=>typeof t!="string"||!/^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)*$/.test(t)||t.split(".").some(i=>n.has(i))||!(e.stateProjection?.allow??[]).some(i=>He(t,i))))throw new U("DEFINITION_UNSUPPORTED","UI definition dataPaths are invalid")}}function ss(e,n){if(!e||typeof e!="object"||Array.isArray(e))throw new U("DEFINITION_UNSUPPORTED","UI legacy tool metadata is invalid");let t=e,i=["name","description","inputSchema","textFallback","visibility"],r=Object.hasOwn(t,"fixedResult");if(Object.keys(t).some(o=>!i.includes(o)&&!(n&&o==="fixedResult"))||i.some(o=>!Object.hasOwn(t,o))||typeof t.name!="string"||!/^[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(t.name)||typeof t.description!="string"||t.description.trim().length===0||t.description.length>8192||typeof t.textFallback!="string"||t.textFallback.trim().length===0||t.textFallback.length>16384||!t.inputSchema||typeof t.inputSchema!="object"||Array.isArray(t.inputSchema)||!Array.isArray(t.visibility)||t.visibility.length===0||t.visibility.some(o=>o!=="model"&&o!=="app")||new Set(t.visibility).size!==t.visibility.length)throw new U("DEFINITION_UNSUPPORTED","UI legacy tool metadata is invalid");try{let o=ce(t.inputSchema);if(o.type!==void 0&&o.type!=="object")throw new Error("schema type");if(r){if(!n)throw new Error("fixed result location");let a=t.fixedResult;if(!a||typeof a!="object"||Array.isArray(a))throw new Error("fixed result");let s=a;if(Object.keys(s).sort().join(",")!=="argsPolicy,structuredContent"||s.argsPolicy!=="empty-only"&&s.argsPolicy!=="ignore"||!s.structuredContent||typeof s.structuredContent!="object"||Array.isArray(s.structuredContent))throw new Error("fixed result");let c=ce(s.structuredContent);if(ut(ze(c))>4*1024)throw new Error("fixed result size")}}catch{throw new U("DEFINITION_UNSUPPORTED","UI legacy tool metadata is not projection-safe")}}function Nt(e){if(!Array.isArray(e.allow)||e.allow.some(n=>!/^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)*$/.test(n)))throw new U("DEFINITION_UNSUPPORTED","UI projection policy is invalid")}function as(e){return e.length>0&&e.length<=128&&e!=="*"&&e!=="all"&&!/[/*]/.test(e)}var rs,we=w(()=>{g();Ne();Pn();Et();Tt();Dt();rs=/^[0-9a-f]{64}$/;});var Si=w(()=>{g();Ne();});var q,be,Pt=w(()=>{g();q="dist/tools.json",be="dist/main.mjs";});var on,Mi=w(()=>{g();on="window";});function Oi(e){if(!Array.isArray(e)||e.length===0)return false;let n=new Set;for(let t of e){if(!cs.some(i=>i===t)||n.has(t))return false;n.add(t);}return true}var cs,Li=w(()=>{g();cs=["CREWX_APP_INSTANCE_ID","CREWX_THREAD_ID"];});function H(e){throw new St(e)}function _s(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;try{let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}catch{return false}}function Es(e,n){let t=Object.getOwnPropertyDescriptor(e,n);return (!t||!("value"in t))&&H("CSP_ORIGIN_INVALID"),t.value}function xn(e,n){if(!Object.prototype.hasOwnProperty.call(e,n))return [];let t=Es(e,n);Array.isArray(t)||H("CSP_ORIGIN_INVALID"),Reflect.ownKeys(t).some(o=>typeof o!="string"||o!=="length"&&!/^(?:0|[1-9][0-9]*)$/.test(o))&&H("CSP_ORIGIN_INVALID");let r=[];for(let o=0;o<t.length;o+=1)(!Object.prototype.hasOwnProperty.call(t,o)||typeof t[o]!="string")&&H("CSP_ORIGIN_INVALID"),r.push(t[o]);return Object.keys(t).length!==t.length&&H("CSP_ORIGIN_INVALID"),r}function Ts(e){let n;try{n=JSON.stringify(e);}catch{H("CSP_ORIGIN_INVALID");}return n===void 0&&H("CSP_ORIGIN_INVALID"),new TextEncoder().encode(n).byteLength}function Ci(e,n){/\s|\\/u.test(e)&&H("CSP_ORIGIN_INVALID");let t=As.exec(e);t||H("CSP_ORIGIN_INVALID");let i=t[1].toLowerCase(),r=t[2];(r.includes("@")||r.includes("%")||r.includes("*"))&&H("CSP_ORIGIN_INVALID"),(r.startsWith("[")?Is:gs).test(r)||H("CSP_ORIGIN_INVALID"),i==="wss"&&n!=="connectDomains"&&H("CSP_ORIGIN_INVALID");let a;try{a=new URL(e);}catch{H("CSP_ORIGIN_INVALID");}(a.protocol!==`${i}:`||a.username!==""||a.password!==""||a.search!==""||a.hash!=="")&&H("CSP_ORIGIN_INVALID");let s=a.hostname.toLowerCase();if((!s||s.includes("%"))&&H("CSP_ORIGIN_INVALID"),!s.startsWith("[")){let d=s.endsWith(".")?s.slice(0,-1):s;(d.length===0||d.length>253)&&H("CSP_ORIGIN_INVALID"),d.split(".").some(u=>u.length>63||!ms.test(u))&&H("CSP_ORIGIN_INVALID");}let c=a.origin;return (c==="null"||!c.startsWith(`${i}://`))&&H("CSP_ORIGIN_INVALID"),{origin:c,hostname:s}}function Ds(e){let n=e.split(".").map(Number);return ((n[0]*256+n[1])*256+n[2])*256+n[3]}function wi(e,n,t){let i=4294967295<<32-t>>>0;return (e&i)===(n&i)}function ji(e){let n=Ds(e);return wi(n,3221225472,24)?n!==3221225481&&n!==3221225482:hs.some(([t,i])=>wi(n,t,i))}function Ns(e){let n=e.indexOf("::"),t=(n<0?e:e.slice(0,n)).split(":").filter(Boolean),i=n<0?[]:e.slice(n+2).split(":").filter(Boolean);return (n<0?t:[...t,...Array(8-t.length-i.length).fill("0"),...i]).reduce((o,a)=>o<<16n|BigInt(Number.parseInt(a,16)),0n)}function bs(e){let n=Ns(e),t=Number(n>>112n),i=Number(n>>96n&0xffffn);if(n>>32n===0xffffn){let r=Number(n&0xffffffffn);return ji([r>>>24&255,r>>>16&255,r>>>8&255,r&255].join("."))}return t<8192||t>16383||t===8193&&i<=511||t===8193&&i===3512||t===8194||t===16383&&i<=4095}function Ps(e,n){let t=e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e,i=isIP(t);if(i===4)return ji(t);if(i===6)return bs(t);let r=e.toLowerCase().replace(/\.$/,"");return !r||!r.includes(".")||n.has(r)?true:ys.some(o=>r===o||r.endsWith(`.${o}`))}function ki(e){return Object.freeze([...new Set(e.map(n=>n.origin))].sort())}function xi(e){return JSON.stringify({baseUriDomains:[],connectDomains:e.connectDomains,declared:e.declared,frameDomains:e.frameDomains,resourceDomains:[]})}function vi(e,n={}){if(e===void 0){let A=xi({declared:false,connectDomains:[],frameDomains:[]});return Object.freeze({declared:false,connectDomains:Object.freeze([]),frameDomains:Object.freeze([]),resourceDomains:Object.freeze([]),baseUriDomains:Object.freeze([]),cspHash:createHash("sha256").update(A,"utf8").digest("hex")})}_s(e)||H("CSP_ORIGIN_INVALID");let t=Reflect.ownKeys(e);t.some(A=>typeof A!="string")&&H("CSP_ORIGIN_INVALID"),t.some(A=>!fs.has(A))&&H("CSP_AXIS_UNKNOWN");let i=xn(e,"connectDomains"),r=xn(e,"frameDomains"),o=xn(e,"resourceDomains"),a=xn(e,"baseUriDomains");(o.length>0||a.length>0)&&H("CSP_AXIS_UNSUPPORTED"),(Ts(e)>ps||i.length>Ui||r.length>Ui||i.length+r.length>ls||[...i,...r].some(A=>new TextEncoder().encode(A).byteLength>us))&&H("CSP_LIMIT_EXCEEDED");let c=i.map(A=>Ci(A,"connectDomains")),d=r.map(A=>Ci(A,"frameDomains")),l=new Set((n.runtimeHostnames??[]).map(A=>A.toLowerCase().replace(/\.$/,"")));[...c,...d].some(A=>Ps(A.hostname,l))&&H("CSP_ORIGIN_FORBIDDEN");let u={declared:true,connectDomains:ki(c),frameDomains:ki(d)},f=xi(u);return Object.freeze({...u,resourceDomains:Object.freeze([]),baseUriDomains:Object.freeze([]),cspHash:createHash("sha256").update(f,"utf8").digest("hex")})}var ps,Ui,ls,us,fs,ys,As,Is,gs,ms,hs,St,Vi=w(()=>{g();ps=4096,Ui=16,ls=32,us=512,fs=new Set(["connectDomains","frameDomains","resourceDomains","baseUriDomains"]),ys=["localhost","local","internal","home.arpa","test","example","invalid","onion","lan","corp","home","intranet","private","localdomain"],As=/^(https|wss):\/\/([^/?#]+)$/i,Is=/^\[[^\]]+\](?::[0-9]+)?$/,gs=/^[^:\[\]]+(?::[0-9]+)?$/,ms=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/,hs=[[0,8],[1681915904,10],[167772160,8],[2130706432,8],[2851995648,16],[2886729728,12],[3221225984,24],[3227017984,24],[3232235520,16],[3323068416,15],[3325256704,24],[3405803776,24],[3758096384,4],[4026531840,4]],St=class extends Error{constructor(t){super(t);this.code=t;}code;name="UiPluginCspNormalizationError"};});function sn(e,n){return n===void 0||n===""?e:e===""?n:n.startsWith("[")?`${e}${n}`:`${e}.${n}`}function p(e,n=e,t,i){throw new re(e,n,t,i)}function B(e,n){try{return n()}catch(t){throw t instanceof re?t.withPathPrefix(e):t}}function z(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;try{let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}catch{return false}}function M(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function sa(e,n){let t={};for(let[i,r]of Object.entries(e))n.includes(i)||(t[i]=r);return t}function $(e,n,t=[]){let i=new Set([...n,...t]),r=Object.keys(e).find(a=>!i.has(a));r!==void 0&&p("MANIFEST_INVALID","MANIFEST_INVALID",r,"unknown-key");let o=n.find(a=>!M(e,a));o!==void 0&&p("MANIFEST_INVALID","MANIFEST_INVALID",o,"missing-key");}function Fn(e,n=false,t=false,i=false){return Ls.test(e)||!i&&Us.test(e)||Rs.test(e)||t&&Fi.test(e)||Cs.test(e)&&!(n&&/^\s*data:/i.test(e)&&!Fi.test(e))}function Vn(e,n=new Set,t=0,i=false,r=false,o=""){if(typeof e=="string"){Fn(e,i,r)&&p("UNSAFE_VALUE","UNSAFE_VALUE",o,"unsafe-value");return}if(!(e===null||typeof e!="object")){(t>8||n.has(e))&&p("MANIFEST_INVALID","MANIFEST_INVALID",o),n.add(e);try{if(Array.isArray(e)){e.forEach((a,s)=>Vn(a,n,t+1,!1,!1,sn(o,`[${s}]`)));return}z(e)||p("MANIFEST_INVALID","MANIFEST_INVALID",o);for(let[a,s]of Object.entries(e))Vn(s,n,t+1,i&&t===0&&(a==="name"||a==="description"),r,sn(o,a));}finally{n.delete(e);}}}function he(e,n){let t=e[n];return typeof t!="string"&&p("MANIFEST_INVALID"),t}function ue(e,n,t){let i=e[n];return (!Number.isSafeInteger(i)||i<t)&&p("MANIFEST_INVALID"),i}function Mt(e){return Os.test(e)||p("MANIFEST_INVALID"),e}function Ge(e){return Ms.test(e)||p("TOKEN_INVALID"),e}function aa(e){return Ki.test(e)||p("MANIFEST_INVALID"),e}function ca(e){z(e)||p("MANIFEST_INVALID");let n={};for(let[t,i]of Object.entries(e)){let r=aa(t);z(i)||p("MANIFEST_INVALID");let o=i.type;if(o==="text"){$(i,["type","maxLength"]),n[r]={type:o,maxLength:ue(i,"maxLength",1)};continue}if(o==="text-list"){$(i,["type","max","itemMaxLength"]),n[r]={type:o,max:ue(i,"max",0),itemMaxLength:ue(i,"itemMaxLength",1)};continue}if(o==="step-list"){$(i,["type","min","max","labelMaxLength","detailMaxLength"]);let a=ue(i,"min",0),s=ue(i,"max",1);a>s&&p("MANIFEST_INVALID"),n[r]={type:o,min:a,max:s,labelMaxLength:ue(i,"labelMaxLength",1),detailMaxLength:ue(i,"detailMaxLength",1)};continue}typeof o=="string"&&p("SCHEMA_TYPE_UNSUPPORTED"),p("MANIFEST_INVALID");}return n}function da(e,n,t){let i=e[n];(!i||i.type!==t)&&p("MANIFEST_INVALID");}function jn(e,n,t){let i=he(e,"field");return Ki.test(i)||p("MANIFEST_INVALID"),da(n,i,t),i}function pa(e,n){z(e)||p("MANIFEST_INVALID");let t=e.primitive;switch(typeof t!="string"&&p("MANIFEST_INVALID"),ra.includes(t)||p("PRIMITIVE_UNKNOWN"),t){case "card-shell":return $(e,["primitive"]),{primitive:t};case "meta-banner":return $(e,["primitive","badgeToken","noticeToken"]),{primitive:t,badgeToken:Ge(he(e,"badgeToken")),noticeToken:Ge(he(e,"noticeToken"))};case "heading":return $(e,["primitive","field"]),{primitive:t,field:jn(e,n,"text")};case "labeled-text":return $(e,["primitive","titleToken","field","variant"]),e.variant!=="callout"&&p("MANIFEST_INVALID"),{primitive:t,titleToken:Ge(he(e,"titleToken")),field:jn(e,n,"text"),variant:"callout"};case "step-flow":return $(e,["primitive","titleToken","field"]),{primitive:t,titleToken:Ge(he(e,"titleToken")),field:jn(e,n,"step-list")};case "text-list":{$(e,["primitive","titleToken","field"],["emptyToken","hideWhenEmpty"]);let i={primitive:t,titleToken:Ge(he(e,"titleToken")),field:jn(e,n,"text-list")};return M(e,"emptyToken")&&(i.emptyToken=Ge(he(e,"emptyToken"))),M(e,"hideWhenEmpty")&&(typeof e.hideWhenEmpty!="boolean"&&p("MANIFEST_INVALID"),i.hideWhenEmpty=e.hideWhenEmpty),i}}return p("MANIFEST_INVALID")}function la(e,n){return Array.isArray(e)||p("MANIFEST_INVALID"),e.map(t=>pa(t,n))}function X(e="v2 manifest exceeds a contract limit",n,t){return p("LIMIT_EXCEEDED",e,n,t)}function pe(e="initial state is not projection-safe"){return p("INITIAL_STATE_INVALID",e)}function Bi(e,n){return (typeof e!="string"||e.length===0||e.length>4096||e.trim().length===0||Qs.test(e)||ea.test(e))&&p("MANIFEST_INVALID",`${n} is invalid`),(Fn(e,true,true)||ws.test(e)||ks.test(e)||xs.test(e))&&p("UNSAFE_VALUE",`${n} contains an unsafe value`),e}function Ot(e,n){return (typeof e!="string"||!me.test(e))&&p("MANIFEST_INVALID",`${n} is invalid`),e}function ua(e){return (typeof e!="string"||!yt.test(e)||e==="*"||e==="all")&&p("MANIFEST_INVALID","action capability is invalid"),e}function Yi(e){return (typeof e!="string"||!Zs.test(e))&&p("MANIFEST_INVALID","resource hash is invalid"),e}function Lt(e,n=new Set,t=0,i=""){if(typeof e=="string"){e.length>4096&&X("v2 manifest string is too long",i,"string-too-long");return}if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){Number.isFinite(e)||p("MANIFEST_INVALID","v2 manifest contains a non-finite number",i,"non-finite-number");return}(e===void 0||typeof e=="function"||typeof e=="bigint")&&p("MANIFEST_INVALID","v2 manifest contains a non-JSON value",i,"non-json-value"),typeof e!="object"&&p("MANIFEST_INVALID","MANIFEST_INVALID",i),t>8&&X("v2 manifest nesting is too deep",i,"too-deep"),n.has(e)&&p("MANIFEST_INVALID","v2 manifest contains a cycle",i,"cycle"),n.add(e);try{if(Array.isArray(e)){e.length>128&&X("v2 manifest array is too long",i,"array-too-long"),e.forEach((r,o)=>Lt(r,n,t+1,sn(i,`[${o}]`)));return}z(e)||p("MANIFEST_INVALID","v2 manifest contains a non-plain object",i,"non-plain-object");for(let[r,o]of Object.entries(e))Lt(o,n,t+1,sn(i,r));}finally{n.delete(e);}}}function qi(e){return (typeof e!="string"||e.length>4096||!tn.test(e))&&(typeof e=="string"&&e.length>4096&&X("projection path is too long"),p("MANIFEST_INVALID","projection paths must be canonical exact paths")),e.split(".").some(t=>Je(t))&&p("MANIFEST_INVALID","projection paths cannot address reserved state keys"),e}function Rt(e){z(e)||p("MANIFEST_INVALID","projection policy must be an object"),$(e,["allow"]),Array.isArray(e.allow)||p("MANIFEST_INVALID","projection allow must be an array"),e.allow.length>128&&X("projection allowlist is too long");let n=[],t=new Set;for(let i of e.allow){let r=qi(i);t.has(r)&&p("MANIFEST_INVALID","projection allowlist contains a duplicate path"),t.add(r),n.push(r);}return {allow:n}}function fa(e,n){if(e===void 0)return;Array.isArray(e)||p("MANIFEST_INVALID","dataPaths must be an array"),e.length>na&&X("dataPaths exceed the v2 limit");let t=[],i=new Set;for(let r of e){let o=qi(r);i.has(o)&&p("MANIFEST_INVALID","dataPaths contain a duplicate path"),n.some(a=>He(o,a))||p("MANIFEST_INVALID","dataPaths must be projection-allowed"),i.add(o),t.push(o);}return t}function ya(e){Array.isArray(e)||p("MANIFEST_INVALID","deviceFeatures must be an array",void 0,"array"),e.length>ta&&p("MANIFEST_INVALID","deviceFeatures allow at most 16 names",void 0,"too-many-items");let n=[],t=new Set;for(let[i,r]of e.entries()){let o=`[${i}]`;typeof r!="string"&&p("MANIFEST_INVALID","a device feature name must be a string",o,"string"),r.length===0&&p("MANIFEST_INVALID","a device feature name must not be empty",o,"empty"),r.length>ia&&p("MANIFEST_INVALID","a device feature name is at most 32 characters",o,"too-long"),oa.test(r)||p("MANIFEST_INVALID","a device feature name starts with a lowercase letter and holds only letters and digits",o,"format"),t.has(r)&&p("MANIFEST_INVALID","deviceFeatures contain a duplicate name",o,"duplicate-item"),t.add(r),n.push(r);}return n}function Aa(e){if(e!==false)return e!==true&&p("MANIFEST_INVALID","downloads must be true or false",void 0,"boolean"),true}function $e(e,n,t=Number.MAX_SAFE_INTEGER){return (!Number.isSafeInteger(e)||e<0||e>t)&&p("MANIFEST_INVALID",`${n} is invalid`),e}function Hi(e,n){return (typeof e!="number"||!Number.isFinite(e))&&p("MANIFEST_INVALID",`${n} is invalid`),e}function Ut(e,n=0,t=new Set){if(typeof e=="string")return (e.length>4096||Fn(e))&&p("UNSAFE_VALUE","schema enum contains an unsafe string"),e;if(e===null||typeof e=="boolean")return e;if(typeof e=="number")return Number.isFinite(e)||p("MANIFEST_INVALID","schema enum contains a non-finite number"),e;(n>8||typeof e!="object"||e===void 0)&&X("schema enum is too deep"),t.has(e)&&p("MANIFEST_INVALID","schema enum contains a cycle"),t.add(e);try{if(Array.isArray(e))return e.length>128&&X("schema enum array is too long"),e.map(r=>Ut(r,n+1,t));z(e)||p("MANIFEST_INVALID","schema enum contains a non-plain object");let i={};for(let[r,o]of Object.entries(e))Je(r)&&p("MANIFEST_INVALID","schema enum contains a reserved key"),i[r]=Ut(o,n+1,t);return i}finally{t.delete(e);}}function Ia(e,n){if(e===void 0)return;Array.isArray(e)||p("MANIFEST_INVALID","schema required must be an array"),e.length>64&&X("schema required list is too long");let t=[],i=new Set;for(let r of e)(typeof r!="string"||!tn.test(r))&&p("MANIFEST_INVALID","schema required contains an invalid key"),r.length>4096&&X("schema required key is too long"),i.has(r)&&p("MANIFEST_INVALID","schema required contains a duplicate key"),n&&!Object.prototype.hasOwnProperty.call(n,r)&&p("MANIFEST_INVALID","schema required references an undeclared property"),i.add(r),t.push(r);return t}function ga(e,n){let t=n?tn:Mn;return e.length>4096&&X("schema property name is too long"),(!t.test(e)||e.split(".").some(i=>Je(i)))&&p("MANIFEST_INVALID","schema property name is invalid"),e}function Ct(e,n=0,t=false){z(e)||p("MANIFEST_INVALID","action inputSchema must be an object"),n>8&&X("action inputSchema is too deep");let i=e.type;i!=="object"&&i!=="string"&&i!=="number"&&i!=="integer"&&i!=="boolean"&&i!=="array"&&i!=="null"&&(typeof i=="string"&&p("SCHEMA_TYPE_UNSUPPORTED","action inputSchema type is unsupported"),p("MANIFEST_INVALID","action inputSchema type is required"));let r=["type","enum"];i==="string"&&r.push("minLength","maxLength"),i==="array"&&r.push("minItems","maxItems","items"),i==="object"&&r.push("minProperties","maxProperties","properties","required","additionalProperties"),(i==="number"||i==="integer")&&r.push("minimum","maximum"),$(e,["type"],r.filter(s=>s!=="type"));let o={type:i};if(M(e,"enum")&&(Array.isArray(e.enum)||p("MANIFEST_INVALID","schema enum must be an array"),e.enum.length>128&&X("schema enum is too long"),o.enum=e.enum.map(s=>Ut(s))),i==="string"&&(M(e,"minLength")&&(o.minLength=$e(e.minLength,"schema minLength",4096)),M(e,"maxLength")&&(o.maxLength=$e(e.maxLength,"schema maxLength",4096)),o.minLength!==void 0&&o.maxLength!==void 0&&o.minLength>o.maxLength&&p("MANIFEST_INVALID","schema string length bounds are inverted")),(i==="number"||i==="integer")&&(M(e,"minimum")&&(o.minimum=Hi(e.minimum,"schema minimum")),M(e,"maximum")&&(o.maximum=Hi(e.maximum,"schema maximum")),o.minimum!==void 0&&o.maximum!==void 0&&o.minimum>o.maximum&&p("MANIFEST_INVALID","schema numeric bounds are inverted")),i==="array"&&(M(e,"minItems")&&(o.minItems=$e(e.minItems,"schema minItems",128)),M(e,"maxItems")&&(o.maxItems=$e(e.maxItems,"schema maxItems",128)),o.minItems!==void 0&&o.maxItems!==void 0&&o.minItems>o.maxItems&&p("MANIFEST_INVALID","schema array length bounds are inverted"),M(e,"items")&&(o.items=Ct(e.items,n+1,false))),i==="object"){let s;if(M(e,"properties")){z(e.properties)||p("MANIFEST_INVALID","schema properties must be an object");let d=Object.entries(e.properties);d.length>64&&X("schema properties are too many"),s={};for(let[l,u]of d){let f=ga(l,t);s[f]=Ct(u,n+1,false);}o.properties=s;}M(e,"minProperties")&&(o.minProperties=$e(e.minProperties,"schema minProperties",64)),M(e,"maxProperties")&&(o.maxProperties=$e(e.maxProperties,"schema maxProperties",64)),o.minProperties!==void 0&&o.maxProperties!==void 0&&o.minProperties>o.maxProperties&&p("MANIFEST_INVALID","schema object property bounds are inverted");let c=Ia(e.required,s);c!==void 0&&(o.required=c),M(e,"additionalProperties")&&(e.additionalProperties!==false&&p("MANIFEST_INVALID","schema additionalProperties must be false"),o.additionalProperties=false);}let a=JSON.stringify(o);return (a===void 0||Buffer.byteLength(a,"utf8")>2097152)&&X("action inputSchema subtree is too large"),o}function ma(e){let n=Ct(e,0,true);return (n.type!=="object"||!n.properties)&&p("MANIFEST_INVALID","action inputSchema must declare object properties"),n}function ha(e){if(z(e)||p("MANIFEST_INVALID","action backend must be an object"),e.type==="core"){$(e,$s);let n=e.handler;return (typeof n!="string"||!At.test(n))&&p("MANIFEST_INVALID","core backend handler is invalid"),{type:"core",handler:n}}if(e.type==="skill"&&M(e,"entry"))return $(e,Ks),e.entry!==be&&p("MANIFEST_INVALID",`skill backend entry must be ${be}`),{type:"skill",entry:be};if(e.type==="skill"){$(e,Ws,Xs),(!Array.isArray(e.command)||e.command.length===0||e.command.length>16)&&p("MANIFEST_INVALID","skill backend command is invalid");let n=[];for(let i of e.command)(typeof i!="string"||i.length===0||i.length>256||!It.test(i))&&p("MANIFEST_INVALID","skill backend command token is invalid"),n.push(i);let t=M(e,"env")?Na(e.env):void 0;return {type:"skill",command:n,...t===void 0?{}:{env:t}}}p("MANIFEST_INVALID","action backend type is unsupported");}function _a(e){z(e)||p("MANIFEST_INVALID","action must be an object"),$(e,Fs,Bs),M(e,"_meta")&&B("_meta",()=>Zi(e._meta));let n=B("actionId",()=>Ot(e.actionId,"actionId"));lt(n)&&p("MANIFEST_INVALID",`actionId "${n}" is not projection-safe`,"actionId");let t=B("capability",()=>ua(e.capability)),i=e.mutation;typeof i!="boolean"&&p("MANIFEST_INVALID","action mutation must be boolean","mutation");let r=B("inputSchema",()=>ma(e.inputSchema)),o;if(M(e,"dataInputs")){Array.isArray(e.dataInputs)||p("MANIFEST_INVALID","action dataInputs must be an array","dataInputs");let A=r.properties,I=new Set,h=[];for(let T of e.dataInputs)(typeof T!="string"||!M(A,T)||I.has(T))&&p("MANIFEST_INVALID","action dataInputs must be unique declared properties","dataInputs"),I.add(T),h.push(T);o=h;}let a=B("resultProjection",()=>Rt(e.resultProjection)),s=B("backend",()=>ha(e.backend)),c;M(e,"content")&&((s.type!=="skill"||!On(e.content))&&p("MANIFEST_INVALID","action content declaration is invalid","content"),c=ba(e.content));let d;if(M(e,"confirmation")){let A=e.confirmation;A!=="none"&&A!=="native"&&p("MANIFEST_INVALID","action confirmation is invalid","confirmation"),d=A;}let l;M(e,"schedule")&&(l=B("schedule",()=>Da(e.schedule,{backend:s,inputSchema:r,hasContent:c!==void 0,hasDataInputs:o!==void 0,confirmation:d})));let u;M(e,"job")&&(l!==void 0&&p("MANIFEST_INVALID","an action is either the scheduled run or a job, not both","job"),u=B("job",()=>Ta(e.job,{backend:s,inputSchema:r,hasContent:c!==void 0,hasDataInputs:o!==void 0,confirmation:d})));let f;return M(e,"jobAccess")&&(u!==void 0&&p("MANIFEST_INVALID","an action is either the job or a job control, not both","jobAccess"),f=B("jobAccess",()=>Ea(e.jobAccess,{backend:s,hasContent:c!==void 0}))),{actionId:n,capability:t,mutation:i,inputSchema:r,resultProjection:a,backend:s,...c===void 0?{}:{content:c},...o===void 0?{}:{dataInputs:o},...d===void 0?{}:{confirmation:d},...l===void 0?{}:{schedule:l},...u===void 0?{}:{job:u},...f===void 0?{}:{jobAccess:f}}}function Ea(e,n){return (n.backend.type!=="skill"||!("entry"in n.backend)||n.backend.entry!==be)&&p("MANIFEST_INVALID","jobAccess needs a tool-mode action","jobAccess"),n.hasContent&&p("MANIFEST_INVALID","a job control action takes no content","jobAccess"),(!Array.isArray(e)||e.length===0)&&p("MANIFEST_INVALID","jobAccess must list at least one operation","jobAccess"),(new Set(e).size!==e.length||!e.every(kn))&&p("MANIFEST_INVALID","jobAccess must name each operation once: start, status or cancel","jobAccess"),Object.freeze([...e])}function Ta(e,n){(n.backend.type!=="skill"||!("entry"in n.backend)||n.backend.entry!==be)&&p("MANIFEST_INVALID","job needs a tool-mode action","job"),(n.hasContent||n.hasDataInputs||n.confirmation!==void 0&&n.confirmation!=="none")&&p("MANIFEST_INVALID","a job action takes no content, dataInputs or native confirmation","job"),(n.inputSchema.required??[]).length>0&&p("MANIFEST_INVALID","a job action input must accept {}","inputSchema.required"),z(e)||p("MANIFEST_INVALID","job must be an object","job"),$(e,[],Js);let t=M(e,"deadlineMs")?e.deadlineMs:Cn.default;return wn(t)||p("MANIFEST_INVALID","job deadlineMs is invalid","job.deadlineMs"),{deadlineMs:t}}function Da(e,n){(n.backend.type!=="skill"||!("entry"in n.backend)||n.backend.entry!==be)&&p("MANIFEST_INVALID","schedule needs a tool-mode action","schedule"),(n.hasContent||n.hasDataInputs||n.confirmation!==void 0&&n.confirmation!=="none")&&p("MANIFEST_INVALID","a scheduled action takes no content, dataInputs or native confirmation","schedule"),(n.inputSchema.required??[]).length>0&&p("MANIFEST_INVALID","a scheduled action input must accept {}","inputSchema.required"),z(e)||p("MANIFEST_INVALID","schedule must be an object","schedule"),$(e,Hs,zs),Rn(e.everyMinutes)||p("MANIFEST_INVALID","schedule everyMinutes is invalid","schedule.everyMinutes");let t=M(e,"timeoutMs")?e.timeoutMs:Ln.default;return Un(t)||p("MANIFEST_INVALID","schedule timeoutMs is invalid","schedule.timeoutMs"),{everyMinutes:e.everyMinutes,timeoutMs:t}}function Na(e){return Oi(e)||p("MANIFEST_INVALID","skill backend env is invalid"),Object.freeze([...e])}function ba(e){return Object.freeze({...e.in===void 0?{}:{in:Object.freeze({...e.in})},...e.out===void 0?{}:{out:Object.freeze({...e.out})}})}function Pa(e){return z(e)||p("INITIAL_STATE_INVALID","initialState must be an object"),$(e,Ys,qs),e.path!=="ui/state.json"&&p("MANIFEST_INVALID","initialState path is not fixed"),M(e,"hash")?{path:"ui/state.json",hash:Yi(e.hash)}:{path:"ui/state.json"}}function Sa(e){let n=["wasm","terminal","htmlDocuments","appBrowser"];return (!z(e)||Object.keys(e).length===0||Object.keys(e).some(t=>!n.includes(t)||e[t]!==true))&&p("MANIFEST_INVALID","runtime must contain only known capability flags set to true"),{...e.wasm===true?{wasm:true}:{},...e.terminal===true?{terminal:true}:{},...e.htmlDocuments===true?{htmlDocuments:true}:{},...e.appBrowser===true?{appBrowser:true}:{}}}function Ma(e,n){let t;try{t=vi(e);}catch(i){let r=i!==null&&typeof i=="object"&&"code"in i&&typeof i.code=="string"?i.code:"CSP_ORIGIN_INVALID";return p("MANIFEST_INVALID",r,void 0,r.toLowerCase().replace(/_/g,"-"))}if(t.frameDomains.length>0&&p("MANIFEST_INVALID","external origins in csp are not enabled in this rollout",void 0,"csp-not-enabled"),t.connectDomains.length!==0)return n?.terminal===true&&p("MANIFEST_INVALID","runtime.terminal cannot be combined with csp.connectDomains","connectDomains","terminal-with-connect-domains"),Object.freeze({connectDomains:t.connectDomains})}function Oa(e,n){Vn(z(e)?sa(e,["csp","downloads"]):e,new Set,0,true,true),Lt(e),z(e)||p("MANIFEST_INVALID"),$(e,vs,Vs),M(e,"_meta")&&B("_meta",()=>Zi(e._meta)),e.manifestVersion!==2&&p("MANIFEST_INVALID");let t;M(e,"runtime")&&(t=B("runtime",()=>Sa(e.runtime)));let i;M(e,"csp")&&(i=B("csp",()=>Ma(e.csp,t)));let r=B("pluginId",()=>Ot(e.pluginId,"pluginId")),o=B("definitionId",()=>Ot(e.definitionId,"definitionId")),a=B("version",()=>ue(e,"version",1)),s=B("name",()=>Bi(e.name,"name")),c=B("description",()=>Bi(e.description,"description")),d;M(e,"icon")&&((typeof e.icon!="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(e.icon))&&p("MANIFEST_INVALID","icon is invalid","icon"),d=e.icon);let l;M(e,"tone")&&((typeof e.tone!="string"||!gt.includes(e.tone))&&p("MANIFEST_INVALID","tone is invalid","tone"),l=e.tone),e.entry!=="ui/index.html"&&p("MANIFEST_INVALID","entry path is not fixed","entry","fixed-value");let u;M(e,"entryHash")&&(u=B("entryHash",()=>Yi(e.entryHash)));let f;M(e,"initialState")&&(f=B("initialState",()=>Pa(e.initialState)));let A;M(e,"usage")&&(e.usage!=="card"&&e.usage!=="window"&&p("MANIFEST_INVALID","usage is invalid","usage"),A=e.usage);let I;M(e,"detailPanel")&&(typeof e.detailPanel!="boolean"&&p("MANIFEST_INVALID","detailPanel is invalid","detailPanel"),I=e.detailPanel);let h;if(M(e,"displayModes")){((A??on)!==on||!Array.isArray(e.displayModes)||e.displayModes.length===0)&&p("MANIFEST_INVALID","displayModes are only valid for window Apps","displayModes");let P=new Set(["inline","floating","focused"]);(new Set(e.displayModes).size!==e.displayModes.length||e.displayModes.some(R=>typeof R!="string"||!P.has(R)))&&p("MANIFEST_INVALID","displayModes are invalid","displayModes"),h=e.displayModes;}(A??on)===on&&I!==void 0&&p("MANIFEST_INVALID","detailPanel is card-only","detailPanel");let T=n.mode??"local";T!=="local"&&T!=="installed"&&T!=="published"&&p("MANIFEST_INVALID","manifest mode is invalid"),T!=="local"&&u===void 0&&p("MANIFEST_INVALID","installed manifests require entryHash","entryHash","required-when-installed"),T!=="local"&&f!==void 0&&f.hash===void 0&&p("MANIFEST_INVALID","installed manifests require initialState.hash","initialState.hash","required-when-installed"),(!Array.isArray(e.surfaces)||e.surfaces.length===0)&&p("MANIFEST_INVALID","surfaces are invalid","surfaces"),e.surfaces.length>2&&X("surfaces exceed the v2 limit","surfaces","too-many-items");let J=[],V=new Set;for(let P of e.surfaces)(typeof P!="string"||!mt.includes(P))&&p("MANIFEST_INVALID","surface is unsupported","surfaces"),V.has(P)&&p("MANIFEST_INVALID","surfaces contain a duplicate","surfaces","duplicate-item"),V.add(P),J.push(P);z(e.size)||p("MANIFEST_INVALID","size must be an object","size"),B("size",()=>$(e.size,["height"]));let b=B("size",()=>ue(e.size,"height",1));b>720&&X("size.height exceeds the v2 limit","size.height","too-large");let C=B("stateProjection",()=>Rt(e.stateProjection)),W=e.summaryProjection===void 0?void 0:B("summaryProjection",()=>Rt(e.summaryProjection));W!==void 0&&W.allow.some(P=>!C.allow.includes(P))&&p("MANIFEST_INVALID","summaryProjection must be a subset of stateProjection.allow","summaryProjection");let D=B("dataPaths",()=>fa(e.dataPaths,C.allow)),O=M(e,"deviceFeatures")?B("deviceFeatures",()=>ya(e.deviceFeatures)):void 0,S=M(e,"downloads")?B("downloads",()=>Aa(e.downloads)):void 0;Array.isArray(e.actions)||p("MANIFEST_INVALID","actions must be an array","actions"),e.actions.length>32&&X("actions exceed the v2 limit","actions","too-many-items");let y=[],m=new Set,N=0,L=0;for(let[P,R]of e.actions.entries()){let G=`actions[${P}]`,x=B(G,()=>_a(R));if(m.has(x.actionId)&&p("MANIFEST_INVALID","actions contain a duplicate actionId",`${G}.actionId`,"duplicate-item"),x.schedule!==void 0&&(N+=1,N>bi&&p("MANIFEST_INVALID","an App declares at most one scheduled action",`${G}.schedule`,"duplicate-item")),x.job!==void 0&&(L+=1,L>Pi&&p("MANIFEST_INVALID","an App declares at most one job action",`${G}.job`,"duplicate-item")),x.backend.type==="core"&&x.backend.handler==="state.set"){x.mutation||p("MANIFEST_INVALID","state.set actions must be mutations",`${G}.mutation`);for(let ge of Object.keys(x.inputSchema.properties))C.allow.includes(ge)||p("MANIFEST_INVALID","state.set input paths must be projection-allowed",`${G}.inputSchema.properties`);}m.add(x.actionId),y.push(x);}return {manifestVersion:2,pluginId:r,definitionId:o,version:a,name:s,description:c,...d===void 0?{}:{icon:d},...l===void 0?{}:{tone:l},entry:"ui/index.html",...u===void 0?{}:{entryHash:u},...t===void 0?{}:{runtime:t},...i===void 0?{}:{csp:i},...f===void 0?{}:{initialState:f},...A===void 0?{}:{usage:A},...I===void 0?{}:{detailPanel:I},...h===void 0?{}:{displayModes:h},surfaces:J,size:{height:b},stateProjection:C,...W===void 0?{}:{summaryProjection:W},...D===void 0?{}:{dataPaths:D},...O===void 0?{}:{deviceFeatures:O},...S===void 0?{}:{downloads:S},actions:y}}function Zi(e){z(e)||p("MANIFEST_INVALID","_meta must be an object");let n=JSON.stringify(e);(n===void 0||Buffer.byteLength(n,"utf8")>Gs)&&X("_meta exceeds the 4 KiB limit",void 0,"meta-too-large");}function La(e){let n={},t={};for(let o of e.actions){n[o.actionId]={capabilities:[o.capability],inputKeys:Object.keys(o.inputSchema.properties??{}),...o.dataInputs===void 0?{}:{dataInputs:o.dataInputs},resultProjection:o.resultProjection,...o.confirmation===void 0?{}:{confirmation:o.confirmation},...o.content===void 0?{}:{content:o.content},...o.schedule===void 0?{}:{schedule:o.schedule},...o.job===void 0?{}:{job:o.job},...o.jobAccess===void 0?{}:{jobAccess:o.jobAccess},...o.backend.type!=="skill"||o.backend.env===void 0?{}:{env:o.backend.env}};let a=o.backend.type==="skill"||o.backend.type==="core"&&o.backend.handler==="state.set";t[o.actionId]={actionId:o.actionId,mutation:o.mutation,backend:o.backend,launchPolicy:a?"allowed":"denied",...a?{}:{denialCode:"EXEC_DENIED"}};}let i={id:e.definitionId,version:e.version,renderer:"sandbox-html",...e.usage===void 0?{}:{usage:e.usage},...e.detailPanel===void 0?{}:{detailPanel:e.detailPanel},...e.displayModes===void 0?{}:{displayModes:e.displayModes},surfaces:e.surfaces,stateProjection:e.stateProjection,...e.summaryProjection===void 0?{}:{summaryProjection:e.summaryProjection},...e.dataPaths===void 0?{}:{dataPaths:e.dataPaths},...e.downloads===void 0?{}:{downloads:e.downloads},actions:n},r={entry:{path:"ui/index.html",...e.entryHash===void 0?{}:{hash:e.entryHash}},...e.initialState===void 0?{}:{initialState:e.initialState}};return {manifest:e,definition:i,handlers:t,resources:r}}function wt(e,n,t,i,r,o){if(typeof e=="string"){let a=r.length>0&&o.some(s=>He(r.join("."),s));return (e.length>4096||Fn(e,false,false,a))&&pe("state contains an unsafe string"),e}if(e===null||typeof e=="boolean")return e;if(typeof e=="number")return Number.isFinite(e)||pe("state contains a non-finite number"),e;(e===void 0||typeof e!="object"||typeof e=="function"||typeof e=="bigint")&&pe("state contains a non-JSON value"),t>8&&pe("state is too deep"),n.has(e)&&pe("state contains a cycle"),n.add(e);try{let a;if(Array.isArray(e))e.length>128&&pe("state array is too long"),a=e.map(c=>wt(c,n,t+1,2097152,r,o));else {z(e)||pe("state contains a non-plain object");let c={};for(let[d,l]of Object.entries(e))(d.length>4096||!Mn.test(d)||Je(d))&&(d.length>4096&&pe("state key is too long"),pe("state contains a reserved or invalid key")),c[d]=wt(l,n,t+1,2097152,[...r,d],o);a=c;}let s=JSON.stringify(a);return (s===void 0||Buffer.byteLength(s,"utf8")>i)&&pe("state subtree is too large"),a}finally{n.delete(e);}}function xt(e,n=[]){z(e)||pe("initial state must be a JSON object");let t=wt(e,new Set,0,2097152,[],n);return (t===null||Array.isArray(t)||typeof t!="object")&&pe(),t}function Ra(e,n={}){Vn(e),z(e)||p("MANIFEST_INVALID"),$(e,js),e.manifestVersion!==1&&p("MANIFEST_INVALID");let t=Mt(he(e,"pluginId")),i=Mt(he(e,"definitionId")),r=ue(e,"version",1),o=ue(e,"primitiveSet",1),a=n.supportedPrimitiveSet??Ss;(!Number.isSafeInteger(a)||a<1)&&p("MANIFEST_INVALID"),o>a&&p("PRIMITIVE_SET_UNSUPPORTED"),z(e.activation)||p("MANIFEST_INVALID"),$(e.activation,["kind","language"]),e.activation.kind!=="fenced-code"&&p("MANIFEST_INVALID");let s=Mt(he(e.activation,"language")),c=ca(e.schema),d=la(e.layout,c);return {manifestVersion:1,pluginId:t,definitionId:i,version:r,primitiveSet:o,activation:{kind:"fenced-code",language:s},schema:c,layout:d}}function Ua(e,n={}){return z(e)||p("MANIFEST_INVALID"),Object.hasOwn(e,"lineage")&&p("MANIFEST_INVALID","lineage is only allowed in product bundle indexes"),e.manifestVersion===2?Oa(e,n):Ra(e,n)}function an(e,n={}){try{return Ua(e,n)}catch(t){if(t instanceof re)throw t;return p("MANIFEST_INVALID")}}function cn(e,n={}){let t=an(e,n);return t.manifestVersion===2?La(t):t}var Ss,Ms,Os,Ki,Ls,Rs,Us,Cs,Fi,ws,ks,xs,js,vs,Vs,Fs,Bs,Hs,zs,Js,Gs,$s,Ws,Xs,Ks,Ys,qs,Zs,Qs,ea,na,ta,ia,oa,ra,re,jt=w(()=>{g();Mi();Ne();Et();Li();Pt();Tt();Dt();Vi();Ce();Ss=1,Ms=/^[a-z][a-zA-Z0-9]*(\.[a-zA-Z0-9]+)+$/,Os=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,Ki=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,Ls=/<\/?[A-Za-z][^>]*>/,Rs=/^(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)/,Us=/^(?:https?|file|ftp|ws|wss):\/\//i,Cs=/^\s*(?:javascript|data):/i,Fi=/data:[^,\s]*,/i,ws=/(?:https?|file|ftp|ws|wss):\/\//i,ks=/javascript:/i,xs=/(?:^[\s]*|[\s"'(=])(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)(?=[^\s"'<>])[^\s"'<>]*/,js=["manifestVersion","pluginId","definitionId","version","primitiveSet","activation","schema","layout"],vs=["manifestVersion","pluginId","definitionId","version","name","description","entry","surfaces","size","stateProjection","actions"],Vs=["_meta","icon","tone","entryHash","runtime","csp","initialState","usage","detailPanel","displayModes","summaryProjection","dataPaths","focusedAiDataPaths","deviceFeatures","downloads"],Fs=["actionId","capability","mutation","inputSchema","resultProjection","backend"],Bs=["confirmation","dataInputs","content","schedule","job","jobAccess","_meta"],Hs=["everyMinutes"],zs=["timeoutMs"],Js=["deadlineMs"],Gs=4*1024,$s=["type","handler"],Ws=["type","command"],Xs=["env"],Ks=["type","entry"],Ys=["path"],qs=["hash"],Zs=/^[0-9a-f]{64}$/,Qs=/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/,ea=/[\r\n]/,na=16,ta=16,ia=32,oa=/^[a-z][A-Za-z0-9]{0,31}$/,ra=["card-shell","meta-banner","heading","labeled-text","step-flow","text-list"],re=class e extends Error{constructor(t,i=t,r,o){super(i);this.code=t;this.path=r;this.rule=o;}code;path;rule;name="UiPluginValidationError";withPathPrefix(t){return new e(this.code,this.message,sn(t,this.path),this.rule)}};});function oo(e){return typeof e=="string"&&e.length<=wa&&Ca.test(e)}function k(e,n,t,i,r){throw new Ee(e,{path:n,rule:t,...i===void 0?{}:{message:i},...r===void 0?{}:{file:r}})}function ee(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;try{let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}catch{return false}}function K(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function ye(e){let n=`_meta["${Le}"]`;return e===void 0||e===""?n:e.startsWith("[")?`${n}${e}`:`${n}.${e}`}function va(e){return e.toLowerCase().replace(/_/g,"-")}function Va(e){if(e===void 0||e==="")return "";let n=/^([^.[]+)(.*)$/.exec(e);if(!n)return ye(e);let[,t,i]=n;switch(t){case "pluginId":return `name${i}`;case "name":return `display_name${i}`;case "description":return `description${i}`;case "_meta":return `_meta${i}`;case "version":return ye("definitionVersion");case "definitionId":return ye("definitionId");default:return ye(`${t}${i}`)}}function ro(e,n,t){return {path:t(e.path),rule:e.rule??va(e.code),...e.message!==e.code?{message:e.message}:{},file:n}}function so(e){return JSON.parse(JSON.stringify(e))}function Ft(e,n,t=0,i=new Set){if(typeof e=="string"){e.length>4096&&k("LIMIT_EXCEEDED",n,"string-too-long"),(ka.test(e)||xa.test(e)||ja.test(e))&&k("UNSAFE_VALUE",n,"unsafe-value");return}if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){Number.isFinite(e)||k("MANIFEST_INVALID",n,"non-finite-number");return}typeof e!="object"&&k("MANIFEST_INVALID",n,"non-json-value"),t>8&&k("LIMIT_EXCEEDED",n,"too-deep"),i.has(e)&&k("MANIFEST_INVALID",n,"cycle"),i.add(e);try{if(Array.isArray(e)){e.length>128&&k("LIMIT_EXCEEDED",n,"array-too-long"),e.forEach((r,o)=>Ft(r,`${n}[${o}]`,t+1,i));return}ee(e)||k("MANIFEST_INVALID",n,"non-plain-object");for(let[r,o]of Object.entries(e))Ft(o,n===""?r:`${n}.${r}`,t+1,i);}finally{i.delete(e);}}}function fe(e,n){return (typeof e!="string"||e.length===0)&&k("MANIFEST_INVALID",n,"string"),e}function Xe(e,n){return ee(e)||k("MANIFEST_INVALID",n,"object"),e}function Fa(e,n){Array.isArray(e)||k("MANIFEST_INVALID",n,"array"),e.forEach((t,i)=>fe(t,`${n}[${i}]`));}function Ba(e,n){typeof e!="boolean"&&k("MANIFEST_INVALID",n,"boolean");}function dn(e,n,t,i){for(let r of Object.keys(e))!t.includes(r)&&!i.includes(r)&&k("MANIFEST_INVALID",`${n}.${r}`,"unknown-key");for(let r of t)K(e,r)||k("MANIFEST_INVALID",`${n}.${r}`,"missing-key");}function Ha(e,n){if(e!=="icon")switch(Ft(n,e),e){case "long_description":case "homepage":case "documentation":case "support":case "license":fe(n,e);return;case "author":{let t=Xe(n,e);dn(t,e,["name"],["email","url"]);for(let i of Object.keys(t))fe(t[i],`${e}.${i}`);return}case "repository":{let t=Xe(n,e);dn(t,e,[],["type","url"]);for(let i of Object.keys(t))fe(t[i],`${e}.${i}`);return}case "icons":{Array.isArray(n)||k("MANIFEST_INVALID",e,"array"),n.forEach((t,i)=>{let r=`${e}[${i}]`,o=Xe(t,r);dn(o,r,["src","size"],["theme"]),fe(o.src,`${r}.src`),fe(o.size,`${r}.size`),K(o,"theme")&&fe(o.theme,`${r}.theme`);});return}case "screenshots":case "keywords":case "privacy_policies":Fa(n,e);return;case "tools":{Array.isArray(n)||k("MANIFEST_INVALID",e,"array"),n.forEach((t,i)=>{let r=`${e}[${i}]`,o=Xe(t,r);dn(o,r,["name"],["description"]),fe(o.name,`${r}.name`),K(o,"description")&&fe(o.description,`${r}.description`);});return}case "prompts":{Array.isArray(n)||k("MANIFEST_INVALID",e,"array"),n.forEach((t,i)=>{let r=`${e}[${i}]`,o=Xe(t,r);dn(o,r,["name","text"],["description","arguments"]),fe(o.name,`${r}.name`),fe(o.text,`${r}.text`);});return}case "tools_generated":case "prompts_generated":Ba(n,e);return;case "localization":case "compatibility":case "user_config":Xe(n,e);return;default:k("MANIFEST_INVALID",e,"unknown-key");}}function Bn(e){return typeof e=="string"&&me.test(e)?e:void 0}function ao(e){return Number.isSafeInteger(e)&&e>=1?e:void 0}function za(e){let n=Bn(e.name);if(n===void 0)return;let t=e._meta,i=ee(t)?t[Le]:void 0,r=ee(i)?i:{},o=K(r,"definitionId")?Bn(r.definitionId):n,a=K(r,"definitionVersion")?ao(r.definitionVersion):1;return {pluginId:n,...o===void 0?{}:{definitionId:o},...a===void 0?{}:{definitionVersion:a}}}function Ja(e){let n=Bn(e.pluginId);if(n===void 0)return;let t=Bn(e.definitionId),i=ao(e.version);return {pluginId:n,...t===void 0?{}:{definitionId:t},...i===void 0?{}:{definitionVersion:i}}}function Jt(e){try{let n=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e));if(!ee(n))return !1;let t=n._meta;return ee(t)&&K(t,Le)}catch{return false}}function Ga(e,n){if(e===xe)return n.builtinOnly===true;let t=n._meta,i=ee(t)?t[Le]:void 0;return ee(i)&&i.builtinOnly===true}function $a(e,n){K(e,"server")&&k("MANIFEST_INVALID","server","server-unsupported","phase 1 runs CrewX-owned Apps only");for(let s of Object.keys(e))Ht.includes(s)||k("MANIFEST_INVALID",s,"unknown-key");for(let s of zt)K(e,s)||k("MANIFEST_INVALID",s,"missing-key");e.manifest_version!==vt&&k("MANIFEST_INVALID","manifest_version","unsupported-version",`manifest_version must be "${vt}"`),oo(e.version)||k("MANIFEST_INVALID","version","semver","version must be a semver.org version such as 0.1.0");let t=e._meta;ee(t)||k("MANIFEST_INVALID","_meta","object"),K(t,Le)||k("MANIFEST_INVALID",ye(),"missing-key");let i=t[Le];ee(i)||k("MANIFEST_INVALID",ye(),"object");for(let s of Object.keys(i))Vt.includes(s)||io.includes(s)||k("MANIFEST_INVALID",ye(s),"unknown-key");for(let s of Vt)s==="actions"&&n!==void 0||K(i,s)||k("MANIFEST_INVALID",ye(s),"missing-key");if(n!==void 0&&K(i,"actions")&&k("MANIFEST_INVALID",ye("actions"),"two-truths",`actions are declared in both ${Y} and ${q}; a server.ts App keeps them in the tools file only`),Wa(i.actions),K(i,"definitionVersion")){let s=i.definitionVersion;(!Number.isSafeInteger(s)||s<1)&&k("MANIFEST_INVALID",ye("definitionVersion"),"positive-integer");}let r={};for(let s of to)K(e,s)&&(Ha(s,e[s]),r[s]=so(e[s]));let o={};for(let[s,c]of Object.entries(t))s!==Le&&(o[s]=c);let a={manifestVersion:2,pluginId:e.name,definitionId:K(i,"definitionId")?i.definitionId:e.name,version:K(i,"definitionVersion")?i.definitionVersion:1,name:e.display_name,description:e.description};for(let[s,c]of Object.entries(i))s==="definitionId"||s==="definitionVersion"||(a[s]=c);return n!==void 0&&(a.actions=n.map(s=>({...s,backend:{type:"skill",entry:be}}))),Object.keys(o).length>0&&(a._meta=o),{v2Input:a,...Object.keys(o).length>0?{vendorMeta:o}:{},passthrough:r}}function Wa(e){Array.isArray(e)&&e.forEach((n,t)=>{let i=ee(n)?n.backend:void 0;ee(i)&&K(i,"entry")&&k("MANIFEST_INVALID",ye(`actions[${t}].backend.entry`),"entry-not-authorable",`an action in ${Y} cannot name an entry; a server.ts App declares its actions in ${q}`);});}function Xa(e,n,t){ee(e)||k("MANIFEST_INVALID","","not-object","manifest.json must be a JSON object",Y);let i;try{i=$a(e,t);}catch(a){throw a instanceof Ee?new Ee(a.code,{...a.reason,file:Y}):a}let r;try{let a=an(i.v2Input,{mode:n.mode??"local"});a.manifestVersion!==2&&k("MANIFEST_INVALID","","v2-required"),r=a;}catch(a){throw a instanceof re?new Ee(a.code,ro(a,Y,Va)):a}let o=e.tools;if(Array.isArray(o)){let a=new Set(r.actions.map(s=>s.actionId));o.forEach((s,c)=>{let d=s.name;if(!a.has(d))throw new Ee("MANIFEST_INVALID",{path:`tools[${c}].name`,rule:"tool-not-action",message:"every tools[].name must be an action id",file:Y})});}return {file:Y,manifest:r,v2Input:i.v2Input,releaseVersion:e.version,...Object.keys(i.passthrough).length>0?{mcpb:i.passthrough}:{}}}function Ka(e,n){try{let t=an(e,{mode:n.mode??"local"});if(t.manifestVersion!==2)throw new Ee("MANIFEST_INVALID",{path:"manifestVersion",rule:"v2-required",message:"a workspace App requires manifestVersion 2",file:xe});return {file:xe,manifest:t,v2Input:e}}catch(t){throw t instanceof re?new Ee(t.code,ro(t,xe,i=>i??"")):t}}function Bt(e){return oe(cn(e).definition)}function eo(e){let{entryHash:n,initialState:t,...i}=e,r={...i};return t!==void 0&&(r.initialState={path:t.path}),so(r)}function Ya(e,n){let t=eo(e),i=eo(n);return [...new Set([...Object.keys(t),...Object.keys(i)])].sort().filter(o=>Q(t[o]??null)!==Q(i[o]??null))}function qa(e,n){return e.entryHash!==void 0&&n.entryHash!==void 0&&e.entryHash!==n.entryHash||e.initialState?.hash!==void 0&&n.initialState?.hash!==void 0&&e.initialState.hash!==n.initialState.hash}function Za(e,n){let t=Ya(e,n),i=qa(e,n),r="";try{let o=Bt(e),a=Bt(n);i=i||o!==a,r=` (definition hash ${o.slice(0,12)} vs ${a.slice(0,12)})`;}catch{i=true;}t.length===0&&!i||k("MANIFEST_DUAL_MISMATCH","","dual-manifest-mismatch",`${Y} and ${xe} normalize to different definitions${r}`+(t.length>0?`; differing fields: ${t.join(", ")}`:""));}function _e(e,n,t="MANIFEST_INVALID",i){return {code:t,reason:{path:e,rule:n,...i===void 0?{}:{message:i},file:q},files:[]}}function no(e){return {..._e("","tools-needs-manifest-json","MANIFEST_INVALID",`${q} is read with ${Y} only`),files:e}}function Qa(e,n){if(e.byteLength>n)return {failure:_e("","file-too-large","LIMIT_EXCEEDED")};let t;try{t=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e));}catch{return {failure:_e("","invalid-json")}}if(!ee(t))return {failure:_e("","not-object","MANIFEST_INVALID",`${q} must be a JSON object`)};for(let r of Object.keys(t))if(r!=="schemaVersion"&&r!=="actions")return {failure:_e(r,"unknown-key")};for(let r of ["schemaVersion","actions"])if(!K(t,r))return {failure:_e(r,"missing-key")};if(t.schemaVersion!==1)return {failure:_e("schemaVersion","unsupported-version","MANIFEST_INVALID",`schemaVersion must be ${1}`)};let i=t.actions;if(!Array.isArray(i))return {failure:_e("actions","array")};for(let[r,o]of i.entries()){if(!ee(o))return {failure:_e(`actions[${r}]`,"object")};if(K(o,"backend"))return {failure:_e(`actions[${r}].backend`,"tools-backend","MANIFEST_INVALID",`an action in ${q} cannot carry a backend`)}}return {actions:i}}function ec(e,n){let t=n.maxBytes??262144,i=[],r=new TextDecoder("utf-8",{fatal:true});for(let o of le){let a=e[o];if(a===void 0)continue;if(a.byteLength>t)return {parsed:i,failure:{code:"LIMIT_EXCEEDED",reason:{path:"",rule:"file-too-large",file:o},files:[o]}};let s;try{s=JSON.parse(r.decode(a));}catch{return {parsed:i,failure:{code:"MANIFEST_INVALID",reason:{path:"",rule:"invalid-json",file:o},files:[o]}}}if(!ee(s))return {parsed:i,failure:{code:"MANIFEST_INVALID",reason:{path:"",rule:"not-object",message:`${o} must be a JSON object`,file:o},files:[o]}};i.push({file:o,raw:s});}return {parsed:i}}function Gt(e,n={}){let{parsed:t,failure:i}=ec(e,n),r=le.filter(A=>e[A]!==void 0);if(i!==void 0)return {ok:false,rejection:i,parseFailure:true,builtinOnly:false};let o=e[q],a=o===void 0?void 0:Qa(o,n.maxBytes??262144);if(t.length===0)return {ok:false,rejection:a===void 0?{code:"MANIFEST_INVALID",reason:{path:"",rule:"no-manifest-file",message:"neither manifest.json nor ui-plugin.json is present"},files:[]}:no(r),parseFailure:true,builtinOnly:false};let s=t[0],c=s.file===Y?za(s.raw):Ja(s.raw),d=t.some(A=>Ga(A.file,A.raw)),l;if(a!==void 0){let A=t.some(I=>I.file===Y)?a.failure:no(r);if(A!==void 0)return {ok:false,rejection:A,parseFailure:false,...c===void 0?{}:{identity:c},builtinOnly:d};l=a.actions;}let u=[];try{for(let A of t)u.push(A.file===Y?Xa(A.raw,n,l):Ka(A.raw,n));u.length===2&&Za(u[0].manifest,u[1].manifest);}catch(A){if(A instanceof Ee)return {ok:false,rejection:{code:A.code,reason:A.reason,files:A.code==="MANIFEST_DUAL_MISMATCH"?[...le]:A.reason.file===void 0||A.reason.file===q?r:[A.reason.file]},parseFailure:false,...c===void 0?{}:{identity:c},builtinOnly:d};throw A}let f=u[0];return {ok:true,...f,identity:c??{pluginId:f.manifest.pluginId},files:r}}var Y,xe,le,vt,Le,Ht,zt,to,Vt,io,Ca,wa,ka,xa,ja,Ee,$t=w(()=>{g();we();Ne();Pt();Ce();jt();Y="manifest.json",xe="ui-plugin.json",le=[Y,xe],vt="0.3",Le="dev.crewx",Ht=Object.freeze(["manifest_version","name","display_name","version","description","long_description","author","repository","homepage","documentation","support","icon","icons","screenshots","localization","server","tools","tools_generated","prompts","prompts_generated","keywords","license","privacy_policies","compatibility","user_config","_meta"]),zt=Object.freeze(["manifest_version","name","display_name","version","description","_meta"]),to=Object.freeze(Ht.filter(e=>e!=="server"&&!zt.includes(e))),Vt=Object.freeze(["entry","surfaces","size","stateProjection","actions"]),io=Object.freeze(["definitionId","definitionVersion","icon","tone","entryHash","runtime","initialState","usage","detailPanel","displayModes","summaryProjection","dataPaths","focusedAiDataPaths","csp","deviceFeatures","downloads"]),Ca=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/,wa=256,ka=/<\/?[A-Za-z][^>]*>/,xa=/^\s*javascript:/i,ja=/data:[^,\s]*,/i;Ee=class extends Error{constructor(t,i){super(`${t}: ${i.path||"<file>"} (${i.rule})`);this.code=t;this.reason=i;}code;reason};});function Ao(e){if(e===void 0)return {kind:"none"};if(typeof e!="string")return {kind:"invalid",reason:"bad-path"};if(ic.test(e))return {kind:"url",declared:e};if(!sc(e))return {kind:"invalid",reason:"bad-path",declared:e};let n=e.lastIndexOf("."),t=n<0?void 0:nc.get(e.slice(n+1).toLowerCase());return t===void 0?{kind:"invalid",reason:"bad-type",declared:e}:{kind:"file",path:e,contentType:t}}function sc(e){return e.length===0||e.length>512||e.startsWith("/")||e.includes("\\")||e.includes("\0")?false:e.split("/").every(n=>n!==""&&n!=="."&&n!=="..")}async function Xt(e,n){let t=Ao(e);if(t.kind==="none")return {diagnostics:[]};if(t.kind==="url")return {diagnostics:[{code:"ICON_NOT_FILE",severity:"warning",declared:t.declared}]};if(t.kind==="invalid")return {diagnostics:[Wt(t.reason,t.declared)]};let i=await n(t.path);if(typeof i=="string")return {diagnostics:[Wt(i,t.path)]};let r=Io(t.contentType,i);if(!r.ok)return {diagnostics:[Wt(r.reason,t.path)]};let o={path:t.path,contentType:t.contentType,byteLength:i.byteLength,bytes:i},a=r.square===false?[{code:"ICON_NOT_SQUARE",severity:"warning",declared:t.path}]:[];return {file:o,diagnostics:a}}function Wt(e,n){return {code:"ICON_INVALID",severity:"error",reason:e,...n===void 0?{}:{declared:n}}}function Io(e,n){if(n.byteLength>262144)return {ok:false,reason:"too-large"};if(e==="image/png")return !uo(n,oc)||Ic(n,12,16)!=="IHDR"||n.byteLength<24?{ok:false,reason:"bytes-mismatch"}:{ok:true,square:lo(fo(n,16),fo(n,20))};if(e==="image/jpeg"){if(!uo(n,rc))return {ok:false,reason:"bytes-mismatch"};let t=yc(n);return {ok:true,square:t===void 0?void 0:lo(t.width,t.height)}}return ac(n)}function ac(e){let n;try{n=tc.decode(e);}catch{return {ok:false,reason:"bytes-mismatch"}}return uc(n)?{ok:false,reason:"unsafe-svg"}:cc.test(n)?{ok:true,square:fc(n)}:{ok:false,reason:"bytes-mismatch"}}function uc(e){if(dc.some(n=>n.test(e)))return true;for(let n of e.matchAll(pc))if(!(n[1]??n[2]??n[3]??"").startsWith("#"))return true;for(let n of e.matchAll(lc))if(co.lastIndex=n.index??0,!co.test(e))return true;return false}function fc(e){let n=/<svg\b[^>]*>/i.exec(e)?.[0];if(n===void 0)return;let t=go(n,"viewBox");if(t!==void 0){let o=t.trim().split(/[\s,]+/).map(Number);return o.length===4&&o.every(Number.isFinite)?o[2]===o[3]:void 0}let i=po(n,"width"),r=po(n,"height");return i===void 0||r===void 0?void 0:i===r}function go(e,n){let t=new RegExp(`\\s${n}\\s*=\\s*(?:"([^"]*)"|'([^']*)')`).exec(e);return t?.[1]??t?.[2]}function po(e,n){let t=go(e,n),i=t===void 0?null:/^\s*(\d+(?:\.\d+)?)(?:px)?\s*$/.exec(t);return i===null?void 0:Number(i[1])}function yc(e){let n=2;for(;n+4<=e.byteLength;){if(e[n]!==255)return;let t=e[n+1];if(t===255){n+=1;continue}if(t===216||t===1||t>=208&&t<=215){n+=2;continue}if(t===217)return;let i=e[n+2]<<8|e[n+3];if(i<2)return;if(Ac(t))return n+9>e.byteLength?void 0:{height:yo(e,n+5),width:yo(e,n+7)};n+=2+i;}}function Ac(e){return e>=192&&e<=207&&e!==196&&e!==200&&e!==204}function lo(e,n){if(!(e<=0||n<=0))return e===n}function uo(e,n){return e.byteLength>=n.length&&n.every((t,i)=>e[i]===t)}function Ic(e,n,t){return String.fromCharCode(...e.subarray(n,t))}function fo(e,n){return (e[n]<<24|e[n+1]<<16|e[n+2]<<8|e[n+3])>>>0}function yo(e,n){return e[n]<<8|e[n+1]}var nc,tc,ic,oc,rc,cc,dc,pc,lc,co,Kt=w(()=>{g();nc=new Map([["svg","image/svg+xml"],["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"]]),tc=new TextDecoder("utf-8",{fatal:true}),ic=/^[A-Za-z][A-Za-z0-9+.-]*:/,oc=[137,80,78,71,13,10,26,10],rc=[255,216,255];cc=/^\s*(?:<\?[\s\S]*?\?>\s*|<!--[\s\S]*?-->\s*)*<svg(?=[\s/>])/,dc=[/<script/i,/[\s"'/]on[a-z]+\s*=/i,/<foreignobject/i,/<!doctype/i,/<!entity/i,/<(?:iframe|embed|object)\b/i,/@import/i],pc=/(?:^|[\s"'/])(?:xlink:)?href\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+))/gi,lc=/url\(/gi,co=/url\(\s*["']?#/iy;});var ho=w(()=>{g();Si();$t();Kt();jt();Ce();});function E(e,n=e){throw new Te(e,n)}var Te,zn=w(()=>{g();Te=class extends Error{constructor(t,i=t){super(i);this.code=t;}code;name="McpAppContractError"};});var _o=w(()=>{g();});var Eo=w(()=>{g();we();Ne();zn();_o();});function Do(e,n){return To.add(e),n!==void 0&&gc.set(e,n),e}function Ke(e){return e!==null&&typeof e=="object"&&To.has(e)}var To,gc,Jn=w(()=>{g();To=new WeakSet,gc=new WeakMap;});function un(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Yt(e,n,t=[]){let i=new Set([...n,...t]),r=Object.keys(e);return n.every(o=>Object.hasOwn(e,o))&&r.every(o=>i.has(o))}function Po(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let n of Object.values(e))Po(n);return Object.freeze(e)}function ne(e){throw new De("LINEAGE_INVALID",e)}function Nc(e){throw new De("LINEAGE_STALE",e)}function So(e){if(!un(e)||!Yt(e,_c,Ec)||!un(e.actions))return ne("Lineage definition shape is invalid");for(let n of Object.values(e.actions))if(!un(n)||!Yt(n,Tc,Dc))return ne("Lineage action definition shape is invalid");return e}function bc(e){if(!un(e)||!Yt(e,mc,hc))return ne("Lineage entry shape is invalid");if(!Number.isSafeInteger(e.version)||e.version<1||typeof e.hash!="string"||!No.test(e.hash))return ne("Lineage entry identity is invalid");if(e.sourceHash!==void 0&&(typeof e.sourceHash!="string"||!No.test(e.sourceHash)))return ne("Lineage source hash is invalid");if(e.compat!==void 0&&e.compat!=="break")return ne("Lineage compatibility marker is invalid");let n=So(e.definition);if(n.version!==e.version)return ne("Lineage version does not match its definition");if(e.sourceHash!==void 0&&n.sourceHash!==e.sourceHash)return ne("Lineage source hash does not match its definition");let t;try{t=oe(n),de({...n,hash:e.hash});}catch{return ne("Lineage definition is invalid")}return t!==e.hash?ne("Lineage definition hash does not match"):Po({version:e.version,hash:e.hash,definition:n,...e.sourceHash===void 0?{}:{sourceHash:e.sourceHash},...e.compat===void 0?{}:{compat:e.compat}})}function bo(e){return e.stateProjection?.allow??[]}function Pc(e,n){let t=[],i=new Set(bo(n));bo(e).some(s=>!i.has(s))&&t.push("S1_STATE_PROJECTION");let r=new Set(n.dataPaths??[]);(e.dataPaths??[]).some(s=>!r.has(s))&&t.push("S2_DATA_PATHS");for(let[s,c]of Object.entries(e.actions)){let d=n.actions[s];if(d&&(c.confirmation??"native")==="native"&&(d.confirmation??"native")!=="native"){t.push("S3_ACTION_CONFIRMATION");break}}Object.keys(e.legacy?.agentAccess??{}).some(s=>!Object.hasOwn(n.actions,s))&&t.push("S4_LEGACY_AGENT_ACTIONS");let a=e.summaryProjection?.allow;if(a!==void 0){let s=new Set(n.summaryProjection?.allow??[]);a.some(c=>!s.has(c))&&t.push("S5_SUMMARY_PROJECTION");}return t}function Sc(e,n){return Q(e)===Q(n)}function qt(e,n){if(!Array.isArray(e)||e.length===0)return ne("Definition lineage is missing");if(!un(n)||typeof n.hash!="string")return ne("Current definition is invalid");let t,i;try{let{hash:s,...c}=n;i=So(c),t={...i,hash:s},de(t);}catch{return ne("Current definition is invalid")}let r=e.map(bc),o=r[0].definition.id;if(r.some(s=>s.definition.id!==o))return ne("Lineage definition ids do not match");if(r.some((s,c)=>c>0&&s.version<=r[c-1].version))return ne("Lineage generations are not in increasing version order");if(r.some((s,c)=>r.findIndex(d=>d.hash===s.hash)!==c))return ne("Lineage contains a duplicate hash");let a=r[r.length-1];if(a.version!==t.version||a.hash!==t.hash||a.definition.id!==t.id||!Sc(a.definition,i))return Nc("The last lineage generation does not match the current package");if(t.legacy!==void 0){let s=new Set(Object.keys(t.actions)),c=new Set;for(let l of r)if(l.sourceHash===void 0)for(let u of Object.keys(l.definition.actions))s.has(u)&&c.add(u);let d=Object.keys(t.legacy.agentAccess??{});if(d.length!==c.size||d.some(l=>!c.has(l))){let l="S4_LEGACY_AGENT_ACCESS_COMPLETE";throw new De("LINEAGE_INVALID",`Lineage compatibility failed: ${l}`,[l])}}for(let s=0;s<r.length-1;s+=1){if(r.slice(s,-1).some(l=>l.compat==="break"))continue;let d=Pc(r[s].definition,t);if(d.length>0)throw new De("LINEAGE_INVALID",`Lineage compatibility failed: ${d.join(", ")}`,d)}return Object.freeze({entries:Object.freeze(r),current:t})}var De,No,mc,hc,_c,Ec,Tc,Dc,Zt=w(()=>{g();we();Ne();De=class extends Error{constructor(t,i=t,r=[]){super(i);this.code=t;this.violations=r;}code;violations;name="UiDefinitionLineageError"},No=/^[0-9a-f]{64}$/,mc=["version","hash","definition"],hc=["sourceHash","compat"],_c=["id","version","actions"],Ec=["sourceHash","usage","detailPanel","displayModes","renderer","surfaces","stateProjection","dataPaths","summaryProjection","downloads","legacy"],Tc=["capabilities"],Dc=["inputKeys","dataInputs","confirmation","resultProjection","content","env","schedule","job","jobAccess"];});var Mo,Oo,Lo,Ro,Uo=w(()=>{g();Mo="text/html;profile=mcp-app",Oo=["crewx_app_terminal_connect","crewx_app_html_viewer_open","crewx_app_browser"],Lo=["crewx_listWorkspaces","crewx_queryAgent","crewx_executeAgent","crewx_getTaskResult","crewx_listTasks","crewx_listAgents","callBrowser","openTab","listTabs","closeTab"],Ro="text/html";});function fn(e){return typeof e=="string"&&Mc.includes(e)}function Gn(e,n){return e==="card"&&n?.type==="core"&&fn(n.handler)}var Mc,$n=w(()=>{g();Mc=Object.freeze(["card.secret-env"]);});function Co(e,n=[],t){if(e.content!==void 0||e.confirmation!=="none")return "denied";let i=Oc();return i&&Object.hasOwn(i,e.actionId)?i[e.actionId]:e.backend?.type==="core"&&e.backend.handler.startsWith("host.")?"denied":e.backend?.type==="core"&&e.backend.handler==="state.set"?"allowed":e.backend?.type==="core"&&fn(e.backend.handler)||e.backend?.type==="skill"?"approval_required":e.backend===void 0&&n.includes(e.actionId)?"allowed":"denied"}function Oc(e){return;}var wo=w(()=>{g();we();Jn();$n();});function vc(e){return In.has(e)&&(e.initialState===void 0||In.has(e.initialState))}function Vo(e,n,t,i){let r=i===void 0?void 0:Object.freeze({hash:i.hash,bytes:Object.freeze(i.bytes)}),o=Object.freeze({mimeType:Ro,entryHash:e,html:n,bytes:Object.freeze(t),...r===void 0?{}:{initialState:r}});return r!==void 0&&In.add(r),In.add(o),o}function Vc(e){let n=[];return e?.terminal===true&&n.push({name:"crewx_app_terminal_connect",description:"Open a local-only terminal session for this App.",inputSchema:{type:"object",properties:{workspace:{type:"string"},threadId:{type:"string"},instanceId:{type:"string"}},required:["threadId","instanceId"],additionalProperties:false},textFallback:"A local terminal connection is ready for this App.",visibility:Object.freeze(["app"]),kind:"host",resourceBinding:Se}),e?.htmlDocuments===true&&n.push({name:"crewx_app_html_viewer_open",description:"List workspace HTML documents or open one through a short-lived Host capability.",inputSchema:{type:"object",properties:{workspace:{type:"string"},threadId:{type:"string"},instanceId:{type:"string"},operation:{type:"string",enum:["list","open"]},documentId:{type:"string"}},required:["threadId","instanceId","operation"],additionalProperties:false},textFallback:"Workspace HTML documents are available through this App.",visibility:Object.freeze(["app"]),kind:"host",resourceBinding:Se}),e?.appBrowser===true&&n.push({name:"crewx_app_browser",description:"Grant this App a native Desktop browser window. Browser commands use the custom Host RPC, not this tool.",inputSchema:{type:"object",properties:{workspace:{type:"string"},threadId:{type:"string"},instanceId:{type:"string"}},required:["threadId","instanceId"],additionalProperties:false},textFallback:"Desktop browser access is granted to this App. Browser commands use the custom Host RPC ui/crewx-app-browser.",visibility:Object.freeze(["app"]),kind:"host",resourceBinding:Se}),n}function Ue(e,n,t){return (typeof e!="string"||!jo.test(e))&&E(n,`${t} must be a safe identifier`),e}function yn(e,n,t){let i=e??t;return (typeof i!="string"||i.trim().length===0||i.length>Uc)&&E("TOOL_INVALID",`${n} must be a meaningful description`),i}function ei(e){return (typeof e!="string"||e.length===0||e.length>Ye||!/<html(?:\s|>)/i.test(e)||!/<\/html\s*>/i.test(e))&&E("HTML_INVALID","MCP App HTML must be a non-empty HTML document"),e}function An(e,n=0){try{let t=ce(e,n);return t.type!==void 0&&t.type!=="object"&&E("TOOL_INVALID","MCP App inputSchema must describe an object"),t}catch(t){if(t instanceof Te)throw t;E("TOOL_INVALID","MCP App inputSchema must be projection-safe JSON");}}function Fc(e){return (typeof e!="string"||e.trim().length===0||e.length>Cc)&&E("TOOL_INVALID","MCP App tools require a meaningful text fallback"),e}function Bc(e){e===void 0&&E("TOOL_INVALID","MCP App tool visibility is required");let n=[...e];return (n.length===0||n.some(t=>t!=="model"&&t!=="app")||new Set(n).size!==n.length)&&E("TOOL_INVALID","MCP App tool visibility must contain model and/or app once"),n}function Bo(e){return (typeof e!="string"||!vo.test(e))&&E("RESOURCE_URI_INVALID","MCP App resource URI is not a registered ui:// URI"),e}function Ho(e){let n=Ue(e.appId,"APP_ID_INVALID","Local App id"),t=yn(e.name,"Local App name",n),i=yn(e.description,"Local App description",`${t} interactive view`),r=Yn(e.definition),o=ei(e.html),a=Wn(e.entryHash,"Local App entry hash"),s=e.entryBytes===void 0?Array.from(new TextEncoder().encode(o)):Kn(e.entryBytes,"Local App entry bytes");(Xn(s)!==a||Go(s)!==o)&&E("HTML_INVALID","Local App entry bytes do not match the HTML hash");let c=Hc(e),d=[];Array.isArray(e.actions)||E("TOOL_INVALID","Local App actions must be an array");for(let b of e.actions){let C=Ue(b.actionId,"TOOL_ID_INVALID","Local App action id");(d.includes(C)||!Object.prototype.hasOwnProperty.call(r.actions,C))&&E("TOOL_INVALID",`Local App action is not declared by the UI definition: ${C}`),d.push(C);}let l=Ue(e.readToolName,"TOOL_ID_INVALID","Local App read tool name"),u=e.actionToolName===void 0?void 0:Ue(e.actionToolName,"TOOL_ID_INVALID","Local App action tool name");d.length===0&&u!==void 0&&E("TOOL_INVALID","A static local App cannot register an action tool"),d.length>0&&u===void 0&&E("TOOL_INVALID","A stateful local App requires an action tool name"),u!==void 0&&u===l&&E("TOOL_ID_CONFLICT",`Local App read and action tools share a name: ${l}`);let f=Vc(e.runtime);f.some(b=>b.name===l||b.name===u)&&E("TOOL_ID_CONFLICT","Local App read or action tool conflicts with a requested Host capability");let A={name:l,description:`${t} current state`,inputSchema:jc,textFallback:`${t} current state is available through its open instance.`,visibility:Object.freeze(["model","app"]),kind:"read",resourceBinding:Se},I=[Object.freeze(A)];if(I.push(...f.map(b=>Object.freeze(b))),u!==void 0){let b={name:u,description:`${t} actions`,inputSchema:ni(e.actions),textFallback:`${t} action requests are handled by the open App instance.`,visibility:Object.freeze(["app"]),kind:"action",resourceBinding:Se,actionIds:Object.freeze([...d])};I.push(Object.freeze(b));}let h=[],T=new Set(I.map(b=>b.name));if(u!==void 0)for(let b of e.actions){let C=`${u}__${b.actionId}`;if(C.length>128||!jo.test(C)){h.push(Object.freeze({toolName:C,actionId:b.actionId,reason:"name_too_long"}));continue}if(T.has(C)){h.push(Object.freeze({toolName:C,actionId:b.actionId,reason:"name_collision"}));continue}let W=Co({actionId:b.actionId,confirmation:r.actions[b.actionId]?.confirmation,content:r.actions[b.actionId]?.content,backend:b.backend},e.modelActions),D=Object.freeze([...Wc(W,r.usage,b.backend)]),O={name:C,description:`${C} action`,inputSchema:An(b.inputSchema),textFallback:`${C} action requests are handled by the open App instance.`,visibility:D,kind:"action",resourceBinding:Se,actionId:b.actionId,actionIds:Object.freeze([b.actionId]),_meta:Object.freeze({ui:Object.freeze({visibility:D})})};I.push(Object.freeze(O)),T.add(C);}let J=Vo(a,o,s,c===void 0?void 0:{hash:c.hash,bytes:[...c.bytes]}),V={appId:n,name:t,description:i,...e.icon===void 0?{}:{icon:$o(e.icon)},...e.tone===void 0?{}:{tone:Wo(e.tone)},builtinOnly:false,definition:r,...e.runtime===void 0?{}:{runtime:Object.freeze({...e.runtime})},...e.deviceFeatures===void 0?{}:{deviceFeatures:Object.freeze([...e.deviceFeatures])},...e.downloads===void 0?{}:{downloads:e.downloads},resourceBinding:Se,resource:J,tools:Object.freeze(I),toolDiagnostics:Object.freeze(h)};return Z(V)}function zo(e={}){return new Qt(e)}function ni(e){if(e.length===0)return An({type:"object",properties:{},additionalProperties:false});let n=e.map(i=>i.actionId),t=new Map;for(let i of e)t.set(i.actionId,An(i.inputSchema));return An(zc(n,t),Fo)}function Hc(e){let n=e.definition.dataPaths??[];if(e.initialStateBytes===void 0){e.initialStateHash!==void 0&&E("STATE_INVALID","Initial state hash has no bytes"),e.initialState!==void 0&&ce(e.initialState,0,n);return}e.initialStateHash===void 0&&E("STATE_INVALID","Initial state bytes require a hash");let t=Wn(e.initialStateHash,"Initial state hash"),i=Kn(e.initialStateBytes,"Initial state bytes");Xn(i)!==t&&E("STATE_INVALID","Initial state bytes do not match the hash");let r;try{let o=new TextDecoder("utf-8",{fatal:!0}).decode(Uint8Array.from(i));r=ce(JSON.parse(o),0,n);}catch{E("STATE_INVALID","Initial state bytes are not projection-safe JSON");}return e.initialState!==void 0&&Q(r)!==Q(ce(e.initialState,0,n))&&E("STATE_INVALID","Initial state bytes do not match the state value"),{hash:t,bytes:Object.freeze([...i])}}function zc(e,n){let t=e.map(i=>({type:"object",properties:{actionId:{type:"string",const:i},input:n.get(i)??{type:"object"}},required:["actionId","input"],additionalProperties:false}));return Object.freeze({type:"object",oneOf:Object.freeze(t),properties:Object.freeze({actionId:Object.freeze({type:"string",enum:Object.freeze([...e])}),input:Object.freeze({type:"object"})}),required:Object.freeze(["actionId","input"]),additionalProperties:false})}function Jc(e){let n=gn(e),t=Ue(n.appId,"APP_ID_INVALID","MCP App id"),i=ei(n.html);Bo(n.uiUri);let r=n.definition===void 0?void 0:Yn(n.definition),o=e.provenance;o!==void 0&&(!Ke(o)||o.appId!==t||o.definitionId!==r?.id||o.version!==r?.version||o.definitionHash!==r?.hash)&&E("TOOL_INVALID","Product App built-in registration provenance is not verified");let a=Object.freeze(n.tools.map(d=>Z(gn(d)))),s=Z({...n,appId:t,html:i,...r===void 0?{}:{definition:r},...o===void 0?{}:{provenance:o},tools:a}),c=Z({uri:s.uiUri,mimeType:Mo,text:i,...s.csp===void 0?{}:{_meta:{ui:{csp:s.csp}}}});return Z({appId:t,name:s.name,description:s.description,...s.icon===void 0?{}:{icon:s.icon},...s.tone===void 0?{}:{tone:s.tone},builtinOnly:s.builtinOnly,uiUri:s.uiUri,...r===void 0?{}:{definition:r},resourceBinding:Object.freeze({kind:"mcp",uri:s.uiUri}),resource:c,tools:a,descriptor:s})}function Gc(e){(e.resourceBinding.kind!=="instance"||e.builtinOnly!==false)&&E("STATE_INVALID","Local App registration binding is invalid"),Object.prototype.hasOwnProperty.call(e,"uiUri")&&E("STATE_INVALID","Local App registration cannot contain uiUri");let n=Ue(e.appId,"APP_ID_INVALID","Local App id"),t=Yn(e.definition),i=e.provenance;i!==void 0&&(!Ke(i)||i.appId!==n||i.definitionId!==t.id||i.version!==t.version||i.definitionHash!==t.hash)&&E("TOOL_INVALID","Product App local registration provenance is not verified");let r=$c(e.resource),o=e.tools.map(s=>{Ue(s.name,"TOOL_ID_INVALID","Local App tool name"),yn(s.description,"Local App tool description","Local App tool"),Fc(s.textFallback);let c=An(s.inputSchema,s.kind==="action"&&!("actionId"in s)?Fo:0);if((s.resourceBinding.kind!=="instance"||Object.prototype.hasOwnProperty.call(s,"resourceUri"))&&E("TOOL_INVALID","Local App tools cannot carry an MCP resource URI"),s.kind==="host")return (!xc.has(s.name)||s.visibility.length!==1||s.visibility[0]!=="app"||Object.prototype.hasOwnProperty.call(s,"actionId"))&&E("TOOL_INVALID","Local App Host tools must use an allow-listed name and app-only visibility"),Z({...s,inputSchema:c,visibility:Object.freeze(["app"])});if(s.kind==="action"){if("actionId"in s){let l=Ue(s.actionId,"TOOL_ID_INVALID","Local App action id");Object.prototype.hasOwnProperty.call(t.actions,l)||E("TOOL_INVALID","Local App action tool references an undeclared action");let u=Bc(s._meta.ui.visibility);return JSON.stringify(u)!==JSON.stringify(s.visibility)&&E("TOOL_INVALID","Local App action metadata visibility must match the tool visibility"),Z({...s,actionId:l,actionIds:Object.freeze([l]),inputSchema:c,visibility:u,_meta:{ui:{visibility:u}}})}let d=[...s.actionIds];return (d.length===0||d.some(l=>!Object.prototype.hasOwnProperty.call(t.actions,l)))&&E("TOOL_INVALID","Local App action tool references an undeclared action"),Z({...s,inputSchema:c,actionIds:Object.freeze(d)})}return Z({...s,inputSchema:c})}),a=Z({appId:n,name:yn(e.name,"Local App name",e.appId),description:yn(e.description,"Local App description",e.name),...e.icon===void 0?{}:{icon:$o(e.icon)},...e.tone===void 0?{}:{tone:Wo(e.tone)},builtinOnly:false,definition:t,...e.runtime===void 0?{}:{runtime:Object.freeze({...e.runtime})},...e.deviceFeatures===void 0?{}:{deviceFeatures:Object.freeze([...e.deviceFeatures])},...e.downloads===void 0?{}:{downloads:e.downloads},...i===void 0?{}:{provenance:i},resourceBinding:Se,resource:r,tools:Object.freeze(o),toolDiagnostics:Object.freeze([...e.toolDiagnostics??[]])});return ko.has(e)?e:(ko.add(a),a)}function $c(e){let n=ei(e.html),t=Wn(e.entryHash,"Local App entry hash");if(vc(e))return e;let i=Kn(e.bytes,"Local App entry bytes");(Xn(i)!==t||Go(i)!==n)&&E("HTML_INVALID","Local App entry bytes do not match the HTML hash");let r=e.initialState===void 0?void 0:{hash:Wn(e.initialState.hash,"Initial state hash"),bytes:Kn(e.initialState.bytes,"Initial state bytes")};return r&&Xn(r.bytes)!==r.hash&&E("STATE_INVALID","Initial state bytes do not match the hash"),Vo(t,n,i,r)}function Wc(e,n,t){if(Gn(n,t))return ["model"];let i=t?.type==="core"&&fn(t.handler);return e==="denied"||i?["app"]:["model","app"]}function Xc(e){return Z({appId:e.appId,name:e.name,description:e.description,...e.icon===void 0?{}:{icon:e.icon},...e.tone===void 0?{}:{tone:e.tone},builtinOnly:false,definition:Jo(e.definition),...e.provenance===void 0?{}:{provenance:e.provenance},entryHash:e.resource.entryHash,resourceBinding:Se,tools:e.tools})}function Kc(e){return Z({appId:e.appId,name:e.name,description:e.description,...e.icon===void 0?{}:{icon:e.icon},...e.tone===void 0?{}:{tone:e.tone},builtinOnly:e.builtinOnly,uiUri:e.uiUri,...e.definition===void 0?{}:{definition:Jo(e.definition)},resourceBinding:Object.freeze({kind:"mcp",uri:e.uiUri}),tools:e.tools})}function Yn(e){try{if(Object.isFrozen(e))return de(e),Z(e);let n=gn(e);return de(n),Z(n)}catch(n){if(n instanceof Te)throw n;E("STATE_INVALID","UI definition is not a valid immutable definition");}}function Jo(e){return Z({id:e.id,version:e.version,hash:e.hash})}function Yc(e){return e!==null&&typeof e=="object"&&typeof e.id=="string"&&Number.isSafeInteger(e.version)&&typeof e.hash=="string"}function xo(e,n,t){return `${e}\0${n}\0${t}`}function Wn(e,n){return (typeof e!="string"||!Rc.test(e))&&E("SERIALIZATION_INVALID",`${n} is invalid`),e}function Xn(e){return createHash("sha256").update(Uint8Array.from(e)).digest("hex")}function Kn(e,n){return (!Array.isArray(e)||e.some(t=>!Number.isInteger(t)||t<0||t>255))&&E("SERIALIZATION_INVALID",`${n} is invalid`),[...e]}function Go(e){try{return new TextDecoder("utf-8",{fatal:!0}).decode(Uint8Array.from(e))}catch{E("SERIALIZATION_INVALID","UTF-8 bytes are invalid");}}function $o(e){return (typeof e!="string"||!wc.test(e))&&E("TOOL_INVALID","MCP App icon is invalid"),e}function Wo(e){return (typeof e!="string"||!kc.has(e))&&E("TOOL_INVALID","MCP App tone is invalid"),e}function gn(e,n=new Map){if(e===null||typeof e!="object")return e;let t=e;if(n.has(t)&&E("SERIALIZATION_INVALID","MCP App value contains a cycle"),Array.isArray(e)){let o=[];n.set(t,o);for(let a of e)o.push(gn(a,n));return n.delete(t),o}let i;try{i=Object.getPrototypeOf(e);}catch{E("SERIALIZATION_INVALID","MCP App value cannot be cloned");}i!==Object.prototype&&i!==null&&E("SERIALIZATION_INVALID","MCP App value must be plain JSON");let r={};n.set(t,r);for(let[o,a]of Object.entries(e))Object.defineProperty(r,o,{configurable:true,enumerable:true,value:gn(a,n),writable:true});return n.delete(t),r}function Z(e,n=new Set){if(e===null||typeof e!="object"||n.has(e)||In.has(e))return e;n.add(e);for(let t of Object.values(e))Z(t,n);return Object.freeze(e),e}var jo,vo,Rc,Ye,Uc,Cc,wc,kc,xc,Se,jc,In,ko,Fo,Qt,qn=w(()=>{g();Eo();we();Ne();Jn();zn();Zt();Uo();wo();$n();jo=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,vo=/^ui:\/\/crewx\/([A-Za-z][A-Za-z0-9._-]{0,127})\/([0-9a-f]{12})$/,Rc=/^[0-9a-f]{64}$/,Ye=8*1024*1024,Uc=8*1024,Cc=16*1024,wc=/^[a-z][a-z0-9-]{0,63}$/,kc=new Set(["blue","violet","emerald","amber","rose","sky","slate","indigo"]),xc=new Set(Oo),new Set(Lo),Se=Object.freeze({kind:"instance"}),jc=Object.freeze({type:"object",properties:Object.freeze({}),additionalProperties:false}),In=new WeakSet,ko=new WeakSet;Fo=4;Qt=class{builtinApps;localApps;builtinDescriptors;builtinTools;mcpResources=new Map;localById=new Map;registrationById=new Map;launcherById=new Map;definitionByKey=new Map;handlerByKey=new Map;mcpToolByName=new Map;localToolByName=new Map;constructor(n){let t=n.builtins??n.builtin,i=[],r=[],o=[],a=new Set,s=new Set;for(let u of t?.listMcpApps()??[]){let f=Jc(u);a.has(f.appId)&&E("APP_ID_CONFLICT",`MCP App id is already registered: ${f.appId}`),a.add(f.appId);let A=f.tools;for(let I of A)s.has(I.name)&&E("TOOL_ID_CONFLICT",`MCP App tool name is already registered: ${I.name}`),s.add(I.name),this.mcpToolByName.set(I.name,I),o.push(I);this.mcpResources.set(f.resource.uri,f.resource),i.push(f),r.push(f.descriptor);}let c=(n.localApps??n.locals??[]).map(Gc),d=new Set(c.flatMap(u=>u.tools.filter(f=>!(f.kind==="action"&&"actionId"in f)).map(f=>f.name))),l=[];for(let u of c){let f=u;a.has(f.appId)&&E("APP_ID_CONFLICT",`MCP App id is already registered: ${f.appId}`),a.add(f.appId);let A=[],I=[...f.toolDiagnostics??[]];for(let h of f.tools){if(s.has(h.name)){if(h.kind==="host"&&this.localToolByName.get(h.name)?.kind==="host"){A.push(h);continue}if(h.kind==="action"&&"actionId"in h){I.push(Object.freeze({toolName:h.name,actionId:h.actionId,reason:"name_collision"}));continue}E("TOOL_ID_CONFLICT",`MCP App tool name is already registered: ${h.name}`);}if(h.kind==="action"&&"actionId"in h&&d.has(h.name)){I.push(Object.freeze({toolName:h.name,actionId:h.actionId,reason:"name_collision"}));continue}s.add(h.name),this.localToolByName.set(h.name,h),A.push(h);}(A.length!==f.tools.length||I.length!==(f.toolDiagnostics?.length??0))&&(f=Z({...f,tools:Object.freeze(A),toolDiagnostics:Object.freeze(I)})),l.push(f),this.localById.set(f.appId,f);}for(let u of i)this.registrationById.set(u.appId,u),this.launcherById.set(u.appId,Kc(u)),u.definition&&this.addDefinition(u.definition);for(let u of l)this.registrationById.set(u.appId,u),this.launcherById.set(u.appId,Xc(u)),this.addDefinition(u.definition);for(let u of n.definitions??[])this.addDefinition(u);for(let u of n.handlers??[])this.addHandler(u);this.builtinApps=Object.freeze(i),this.localApps=Object.freeze(l),this.builtinDescriptors=Object.freeze(r),this.builtinTools=Object.freeze(o);}getMcpApp(n){return this.builtinApps.find(t=>t.appId===n)?.descriptor??null}listMcpApps(){return this.builtinDescriptors}listMcpAppTools(){return this.builtinTools}resolveMcpAppTool(n){return this.mcpToolByName.get(n)??null}resolveMcpAppResource(n){return typeof n!="string"||!vo.test(n)?null:this.mcpResources.get(n)??null}requireMcpAppResource(n){Bo(n);let t=this.mcpResources.get(n);return t||E("RESOURCE_NOT_FOUND",`MCP App resource is not registered: ${n}`),t}listLocalMcpApps(){return this.localApps}getLocalMcpApp(n){return this.localById.get(n)??null}listLocalMcpAppTools(){return Object.freeze([...this.localToolByName.values()])}resolveLocalMcpAppTool(n){return this.localToolByName.get(n)??null}resolveLocalMcpAppResource(n,t){let i=this.localById.get(n);return !i||t!==void 0&&i.definition.hash!==t?null:i.resource}listRegistrations(){return Object.freeze([...this.builtinApps,...this.localApps])}getRegistration(n){return this.registrationById.get(n)??null}listLaunchers(){return Object.freeze([...this.launcherById.values()].filter(n=>{let t=this.registrationById.get(n.appId),i=t?"descriptor"in t?t.descriptor.provenance:t.provenance:void 0,r=Ke(i)&&i.launcher===false;return t?.definition?.usage!=="card"&&!r}))}listCardApps(){return Object.freeze([...this.launcherById.values()].filter(n=>this.registrationById.get(n.appId)?.definition?.usage==="card"))}getLauncher(n){return this.launcherById.get(n)??null}resolveDefinition(n){if(!Yc(n))return null;let t=this.definitionByKey.get(bt(n));if(!t||t.hash!==n.hash)return null;try{return oe(t)===t.hash?t:null}catch{return null}}resolveActionHandler(n,t,i){return typeof n!="string"||typeof i!="string"||!Number.isSafeInteger(t)?null:this.handlerByKey.get(xo(n,t,i))??null}addDefinition(n){let t=Yn(n),i=bt(t),r=this.definitionByKey.get(i);r&&r.hash!==t.hash&&E("STATE_INVALID",`UI definition generation conflicts: ${i}`),r||this.definitionByKey.set(i,t);}addHandler(n){(!n||typeof n.definitionId!="string"||typeof n.actionId!="string"||!Number.isSafeInteger(n.version)||n.version<1||typeof n.handle!="function")&&E("STATE_INVALID","UI action handler registration is invalid");let t=xo(n.definitionId,n.version,n.actionId);this.handlerByKey.has(t)&&E("TOOL_INVALID",`Duplicate UI action handler registration: ${t}`),this.handlerByKey.set(t,Object.freeze({...n}));}};});function qc(e){let n=Ho({appId:e.appId,name:e.name,description:e.description,...e.icon===void 0?{}:{icon:e.icon},...e.tone===void 0?{}:{tone:e.tone},...e.normalized.manifest.runtime===void 0?{}:{runtime:e.normalized.manifest.runtime},...e.normalized.manifest.deviceFeatures===void 0?{}:{deviceFeatures:e.normalized.manifest.deviceFeatures},...e.normalized.manifest.downloads===void 0?{}:{downloads:e.normalized.manifest.downloads},definition:e.definition,html:e.html,entryHash:e.entryHash,entryBytes:e.entryBytes,initialState:e.initialState,...e.initialStateHash===void 0?{}:{initialStateHash:e.initialStateHash},...e.initialStateBytes===void 0?{}:{initialStateBytes:e.initialStateBytes},readToolName:e.toolNames.read,...e.toolNames.action===void 0?{}:{actionToolName:e.toolNames.action},actions:e.normalized.manifest.actions.map(i=>({actionId:i.actionId,inputSchema:i.inputSchema,backend:i.backend}))});return e.provenance===void 0?n:Object.freeze({...n,provenance:e.provenance})}function Xo(e){let n=e.normalized.manifest.actions;if(n.some(i=>i.backend.type==="skill")&&n.some(i=>i.backend.type==="core"))throw new Error("Mixed workspace App execution models");let t=qc(e);zo({localApps:[t],definitions:[e.definition]});}var Ko=w(()=>{g();qn();});function Yo(){return Object.freeze({[ti]:{candidates:new Map,assetCatalogs:new Map,preparedCandidates:new Map}})}function Zc(e){if(e===null||typeof e!="object"||!(ti in e))throw new TypeError("scanCache must be created by createWorkspaceAppScanCache");return e[ti]}function qo(e,n){let t=Zc(e),i=t.rootIdentity;return i!==void 0&&(i.dev!==n.dev||i.ino!==n.ino||i.realPath!==n.realPath)&&(t.candidates.clear(),t.assetCatalogs.clear(),t.preparedCandidates.clear(),t.lastCandidateScanUnchanged=void 0,t.lastCandidateKeys=void 0,t.scanStartedAtNs=void 0,t.lastAssetCatalogsUnchanged=void 0,t.lastSnapshot=void 0,t.lastSnapshotBuildInputs=void 0,t.lastSnapshotCandidates=void 0,t.lastSnapshotCatalogFingerprint=void 0),t.rootIdentity=n,t}var ti,Zo=w(()=>{g();ti=Symbol("crewx.workspace-app-scan-cache.state");});function se(e){let n=typeof e=="object"&&e!==null&&"code"in e?String(e.code):"";return n==="ENOENT"?new _("NOT_FOUND"):n==="ELOOP"?new _("PATH_ESCAPED"):n==="EFBIG"||n==="EOVERFLOW"?new _("LIMIT_EXCEEDED"):n==="EACCES"||n==="EPERM"||n==="ENOTDIR"?new _("READ_DENIED"):new _("READ_DENIED")}function td(e){if(typeof e!="string"||e.length===0||!isAbsolute(e))throw new _("READ_DENIED")}function ii(e){if(typeof e!="string"||isAbsolute(e)||/[\\\u0000]/.test(e))throw new _("PATH_ESCAPED");if(e==="")return [];let n=e.split("/");if(n.some(t=>t.length===0||t==="."||t===".."))throw new _("PATH_ESCAPED");return n}function nt(e,n){let t=relative(e,n);return t===""||t!==".."&&!t.startsWith(`..${sep}`)&&!isAbsolute(t)}function Ze(e){return {dev:e.dev,ino:e.ino,size:e.size,mtimeNs:e.mtimeNs,ctimeNs:e.ctimeNs}}function ai(e,n){return e.dev===n.dev&&e.ino===n.ino}function ci(e,n){return ai(e,n)&&e.size===n.size&&e.mtimeNs===n.mtimeNs&&e.ctimeNs===n.ctimeNs}async function Zn(e){td(e);let n,t;try{n=await realpath(e),t=await stat(n,{bigint:!0});}catch(i){throw se(i)}if(!t.isDirectory())throw new _("READ_DENIED");return {realRoot:n,identity:Ze(t)}}async function nr(e,n,t){if(t.length<2||t[0]!=="apps"&&t[0]!=="skills")return;let i,r;try{if(i=resolve(e,t[0],t[1]),r=await realpath(i),!(await stat(r,{bigint:!0})).isDirectory())throw new _("READ_DENIED")}catch(o){throw o instanceof _?o:se(o)}if(!nt(n,r))throw new _("PATH_ESCAPED");return r}async function Qn(e,n,t,i){let r,o,a;try{r=await lstat(e,{bigint:!0}),o=await realpath(e),a=await stat(o,{bigint:!0});}catch(s){throw se(s)}if(!nt(n,o)||t!==void 0&&!nt(t,o))throw new _("PATH_ESCAPED");if(!r.isFile()||!a.isFile())throw new _("READ_DENIED");if(!ai(i,r)||!ai(i,a)||i.dev!==a.dev)throw new _("PATH_ESCAPED")}async function qe(e,n){let t,i;try{t=await realpath(e),i=await stat(t,{bigint:!0});}catch{throw new _("PATH_ESCAPED")}if(t!==n.realRoot||!ci(n.identity,Ze(i)))throw new _("PATH_ESCAPED")}function id(e){return e.isSymbolicLink()?{name:e.name,kind:"symlink"}:e.isDirectory()?{name:e.name,kind:"directory"}:e.isFile()?{name:e.name,kind:"file"}:{name:e.name,kind:"other"}}var _,si,nd,er,Qe,tt,tr,ir,pi=w(()=>{g();_=class extends Error{constructor(t){super(t);this.code=t;}code;name="AppDiscoveryFsError"},si=constants.O_NOFOLLOW,nd=constants.O_NONBLOCK,er=constants.O_RDONLY|(si??0)|(nd??0);Qe=class{async getRootIdentity(n){let t=await Zn(n);return await qe(n,t),{dev:t.identity.dev,ino:t.identity.ino,realPath:t.realRoot}}async listDirectory(n,t){let i=ii(t),r=await Zn(n),o=resolve(n,...i),a,s;try{a=await realpath(o),s=await stat(a,{bigint:!0});}catch(c){let d=se(c);if(d.code==="NOT_FOUND")return [];throw d}if(!nt(r.realRoot,a)||!s.isDirectory())throw new _("PATH_ESCAPED");try{let c=await readdir(a,{withFileTypes:!0,encoding:"utf8"});return await qe(n,r),c.map(id)}catch(c){let d=se(c);if(d.code==="NOT_FOUND")return [];throw d}}async readdir(n,t){return this.listDirectory(n,t)}async readDirectory(n,t){return this.listDirectory(n,t)}async readVerifiedFile(n,t,i){if(!Number.isSafeInteger(i)||i<0)throw new _("READ_DENIED");if(si===void 0)throw new _("UNSUPPORTED");let r=ii(t),o=await Zn(n),a=resolve(n,...r),s=relative(n,a);if(s===".."||s.startsWith(`..${sep}`)||isAbsolute(s))throw new _("PATH_ESCAPED");let c;try{c=await open(a,er);}catch(d){throw se(d)}try{let d;try{let I=await c.stat({bigint:!0});d=Ze(I);}catch(I){throw se(I)}if(d.size>BigInt(i))throw new _("LIMIT_EXCEEDED");if(d.size>BigInt(Number.MAX_SAFE_INTEGER))throw new _("LIMIT_EXCEEDED");await qe(n,o);let l=await nr(n,o.realRoot,r);await Qn(a,o.realRoot,l,d);let u=new Uint8Array(new ArrayBuffer(Number(d.size))),f=0;for(;f<u.byteLength;){let I;try{I=(await c.read(u,f,u.byteLength-f,f)).bytesRead;}catch(h){throw se(h)}if(I<=0)throw new _("IDENTITY_CHANGED");f+=I;}let A;try{let I=await c.stat({bigint:!0});A=Ze(I);}catch(I){throw se(I)}if(!ci(d,A))throw new _("IDENTITY_CHANGED");return await Qn(a,o.realRoot,l,A),await qe(n,o),new Uint8Array(u)}finally{await c.close().catch(()=>{});}}async fingerprintVerifiedFile(n,t,i){if(!Number.isSafeInteger(i)||i<0)throw new _("READ_DENIED");if(si===void 0)throw new _("UNSUPPORTED");let r=ii(t),o=await Zn(n),a=resolve(n,...r),s=relative(n,a);if(s===".."||s.startsWith(`..${sep}`)||isAbsolute(s))throw new _("PATH_ESCAPED");let c;try{c=await open(a,er);}catch(d){throw se(d)}try{let d;try{let f=await c.stat({bigint:!0});d=Ze(f);}catch(f){throw se(f)}if(d.size>BigInt(i)||d.size>BigInt(Number.MAX_SAFE_INTEGER))throw new _("LIMIT_EXCEEDED");await qe(n,o);let l=await nr(n,o.realRoot,r);await Qn(a,o.realRoot,l,d);let u;try{let f=await c.stat({bigint:!0});u=Ze(f);}catch(f){throw se(f)}if(!ci(d,u))throw new _("IDENTITY_CHANGED");return await Qn(a,o.realRoot,l,u),await qe(n,o),{...u,candidateRealPath:l??o.realRoot}}catch(d){throw d instanceof _?d:se(d)}finally{await c.close().catch(()=>{});}}async readFileVerified(n,t,i){return this.readVerifiedFile(n,t,i)}},tt=new Qe,tr=tt,ir=Qe;});function En(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;try{let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}catch{return false}}function rr(e){return typeof e=="string"&&me.test(e)?e:void 0}function pd(e){return e.length>0&&e!=="."&&e!==".."&&!/[\\/\u0000]/.test(e)}function ve(e,n){let t=new TextEncoder().encode(e),i=new TextEncoder().encode(n),r=Math.min(t.byteLength,i.byteLength);for(let o=0;o<r;o+=1){let a=t[o]-i[o];if(a!==0)return a}return t.byteLength-i.byteLength}function ld(e){if(typeof e=="string")return {name:e,kind:"directory"};if(e===null||typeof e!="object")return null;let n=e;if(typeof n.name!="string")return null;if(n.kind==="file"||n.kind==="directory"||n.kind==="symlink"||n.kind==="other")return {name:n.name,kind:n.kind};if(n.type==="file"||n.type==="directory"||n.type==="symlink"||n.type==="other")return {name:n.name,kind:n.type};let t=n.isDirectory;if(typeof t=="function"&&t.call(e))return {name:n.name,kind:"directory"};let i=n.isSymbolicLink;if(typeof i=="function"&&i.call(e))return {name:n.name,kind:"symlink"};let r=n.isFile;return typeof r=="function"&&r.call(e)?{name:n.name,kind:"file"}:{name:n.name,kind:"other"}}function ud(e){if(e instanceof Uint8Array)return new Uint8Array(e);if(e instanceof ArrayBuffer)return new Uint8Array(e.slice(0));if(Array.isArray(e)&&e.every(n=>Number.isInteger(n)&&n>=0&&n<=255))return Uint8Array.from(e);throw new TypeError("filesystem port returned an invalid byte array")}function fd(e){return cd.decode(e)}function yd(e){return JSON.parse(fd(e))}function sr(e){switch(e){case "ENOENT":return "NOT_FOUND";case "ELOOP":case "EXDEV":return "PATH_ESCAPED";case "EFBIG":case "EOVERFLOW":return "LIMIT_EXCEEDED";case "EACCES":case "EPERM":case "ENOTDIR":return "READ_DENIED";default:return e}}function Ad(e){if(e instanceof _)return sr(e.code);if(e!==null&&typeof e=="object"&&"code"in e){let n=e.code;if(typeof n=="string")return sr(n)}}function Me(e,n){let t=n();return Number.isFinite(t)&&Number.isFinite(e)&&t-e<=5e3}function Id(e){if(typeof e.readVerifiedFile=="function")return e.readVerifiedFile;if(typeof e.readFileVerified=="function")return e.readFileVerified}function gd(e){if(typeof e.listDirectory=="function")return e.listDirectory;if(typeof e.readDirectory=="function")return e.readDirectory;if(typeof e.readdir=="function")return e.readdir}async function ar(e,n,t,i){let r=Id(e);if(!r)throw new _("READ_DENIED");return ud(await r.call(e,n,t,i))}async function fi(e,n,t){let i=gd(e);if(!i)throw new _("READ_DENIED");let r=await i.call(e,n,t);if(!Array.isArray(r))throw new _("READ_DENIED");return r.map(ld).filter(o=>o!==null)}function md(e,n,t,i){return Object.freeze({code:e,...{},source:n,relativePath:t})}function hd(e){if(!En(e))throw new TypeError("productBundle.reservedIds must be an object with appIds and definitionIds arrays");try{let n=Reflect.ownKeys(e);if(n.length!==2||!n.includes("appIds")||!n.includes("definitionIds"))throw new TypeError("productBundle.reservedIds must contain exactly appIds and definitionIds");let t=(i,r)=>{if(!Array.isArray(i))throw new TypeError("productBundle.reservedIds."+r+" must be an array");let o=[];for(let a=0;a<i.length;a+=1){let s=i[a];if(typeof s!="string"||s.length===0)throw new TypeError("productBundle.reservedIds."+r+" must contain non-empty strings");o.push(s);}return Object.freeze([...new Set(o)].sort(ve))};return Object.freeze({appIds:t(e.appIds,"appIds"),definitionIds:t(e.definitionIds,"definitionIds")})}catch(n){throw n instanceof TypeError?n:new TypeError("productBundle.reservedIds must be a valid reservation object")}}function _d(e,n){return e.appIds.length===n.appIds.length&&e.appIds.every((t,i)=>t===n.appIds[i])&&e.definitionIds.length===n.definitionIds.length&&e.definitionIds.every((t,i)=>t===n.definitionIds[i])}function Tn(e){return Object.freeze({appIds:Object.freeze([...new Set(e.map(n=>n.appId))].sort(ve)),definitionIds:Object.freeze([...new Set(e.map(n=>n.definition.id))].sort(ve))})}function it(e,n){let t=Object.keys(e).sort(ve),i=[...n].sort(ve);return t.length===i.length&&t.every((r,o)=>r===i[o])}function cr(e){if(typeof e!="string"||e.length===0||e.startsWith("/")||/[\\\u0000]/.test(e))return;let n=e.split("/");if(!n.some(t=>t.length===0||t==="."||t===".."))return n}function Ed(e){let n;try{n=yd(e);}catch{return}if(!En(n)||!it(n,["version","packages"])||n.version!==1||!Array.isArray(n.packages)||n.packages.length>yi)return;let t=new Set,i=new Set,r=0,o=[];for(let a of n.packages){if(!En(a))return;let s=["packageDir","appId","definition","files"],c=Object.hasOwn(a,"lineage"),d=Object.hasOwn(a,"launcher"),l=[...c?["lineage"]:[],...d?["launcher"]:[]];if(!it(a,[...s,...l])||d&&a.launcher!==false)return;let u=cr(a.packageDir),f=rr(a.appId);if(!u||u.length!==2||u[0]!=="apps"||!pd(u[1])||!f||t.has(a.packageDir)||!En(a.definition)||!it(a.definition,["id","version","hash"]))return;let A=rr(a.definition.id),I=a.definition.version,h=a.definition.hash;if(!A||!Number.isSafeInteger(I)||I<1||typeof h!="string"||!ui.test(h)||!Array.isArray(a.files)||a.files.length<2||a.files.length>Ai)return;let T=new Set,J=[];for(let V of a.files){if(!En(V)||!it(V,["path","sha256"]))return;let b=cr(V.path);if(!b||typeof V.sha256!="string"||!ui.test(V.sha256))return;let C=b.join("/"),W=`${a.packageDir}/${C}`;if(T.has(C)||i.has(W))return;T.add(C),i.add(W),J.push(Object.freeze({path:C,sha256:V.sha256}));}if(!le.some(V=>T.has(V))||!T.has("ui/index.html")||(r+=J.length,r>rd))return;t.add(a.packageDir),o.push(Object.freeze({packageDir:a.packageDir,...d?{launcher:false}:{},appId:f,definition:Object.freeze({id:A,version:I,hash:h}),lineage:Array.isArray(a.lineage)?a.lineage:[],files:Object.freeze(J.sort((V,b)=>ve(V.path,b.path)))}));}return Object.freeze({version:1,packages:Object.freeze(o)})}function je(e){let n=Ad(e);return n==="PATH_ESCAPED"||n==="IDENTITY_CHANGED"||n==="TOCTOU"?"PATH_ESCAPED":n==="LIMIT_EXCEEDED"?"LIMIT_EXCEEDED":"BUNDLE_INTEGRITY"}async function Td(e,n,t,i,r){let o=[],a=async(s,c)=>{if(!Me(i,r))throw new _("LIMIT_EXCEEDED");if(c>2)throw new _("LIMIT_EXCEEDED");let d=await fi(e,n,s);for(let l of d){if(typeof l.name!="string"||l.name.length===0||l.name==="."||l.name===".."||/[\\/\u0000]/.test(l.name))throw new _("PATH_ESCAPED");let u=`${s}/${l.name}`;if(l.kind==="file"){if(o.push(u.slice(t.length+1)),o.length>Ai)throw new _("LIMIT_EXCEEDED")}else if(l.kind==="directory")await a(u,c+1);else throw l.kind==="symlink"?new _("PATH_ESCAPED"):new _("READ_DENIED")}};return await a(t,0),o.sort(ve)}function Dd(e){return le.includes(e)?262144:e==="ui/index.html"?Ye:e==="ui/state.json"?2097152:e.startsWith("ui/assets/")?ad:sd}async function dr(e,n,t,i){if(e===void 0)return {packages:[],diagnostics:[],incomplete:false,reservedIds:dd};let r=hd(e.reservedIds),o=[],a=(y,m,N)=>md(y,"bundled",m),s=(y=[],m=false,N)=>({...N===void 0?{}:{indexHash:N},packages:y,diagnostics:o,incomplete:m,reservedIds:r});if(typeof e.root!="string"||e.root.length===0||typeof e.expectedIndexHash!="string"||!ui.test(e.expectedIndexHash))return o.push(a("BUNDLE_INTEGRITY","bundle-index.json")),s();let c;try{c=await ar(n,e.root,"bundle-index.json",od);}catch(y){return o.push(a(je(y),"bundle-index.json")),s()}let d=createHash("sha256").update(c).digest("hex");if(d!==e.expectedIndexHash)return o.push(a("BUNDLE_INTEGRITY","bundle-index.json")),s();let l=Ed(c);if(l===void 0)return o.push(a("BUNDLE_INTEGRITY","bundle-index.json")),s();if(!_d(Tn(l.packages),r))return o.push(a("BUNDLE_INTEGRITY","bundle-index.json")),s([],false,d);if(!Me(t,i))return o.push(a("LIMIT_EXCEEDED","bundle-index.json")),s(l.packages.map(y=>({indexEntry:y,failureCode:"LIMIT_EXCEEDED"})),true,d);let u;try{u=await fi(n,e.root,"");}catch(y){return o.push(a(je(y),"bundle-index.json")),s(l.packages.map(m=>({indexEntry:m,failureCode:je(y)})),false,d)}if(!Me(t,i))return o.push(a("LIMIT_EXCEEDED","bundle-index.json")),s(l.packages.map(y=>({indexEntry:y,failureCode:"LIMIT_EXCEEDED"})),true,d);let f=u.find(y=>y.name==="bundle-index.json"&&y.kind==="file"),A=u.find(y=>y.name==="apps"&&y.kind==="directory"),I=y=>l.packages.map(m=>({indexEntry:m,failureCode:y}));if(!f)return o.push(a("BUNDLE_INTEGRITY","bundle-index.json")),s(I("BUNDLE_INTEGRITY"),false,d);let h=u.filter(y=>y.name!=="bundle-index.json"&&y.name!=="apps");if(h.length>0){let y=h.some(m=>m.kind==="symlink")?"PATH_ESCAPED":"BUNDLE_INTEGRITY";return o.push(a(y,"bundle-index.json")),s(I("BUNDLE_INTEGRITY"),false,d)}if(u.some(y=>y.name==="apps"&&y.kind!=="directory"))return o.push(a("PATH_ESCAPED","apps")),s(I("PATH_ESCAPED"),false,d);let T=[];if(A)try{T=await fi(n,e.root,"apps");}catch(y){return o.push(a(je(y),"apps")),s(I(je(y)),false,d)}if(!Me(t,i)||T.length>yi)return o.push(a("LIMIT_EXCEEDED","apps")),s(I("LIMIT_EXCEEDED"),true,d);let J=new Map(l.packages.map(y=>[y.packageDir.slice(5),y])),V=T.filter(y=>!J.has(y.name));for(let y of V)o.push(a(y.kind==="symlink"?"PATH_ESCAPED":"BUNDLE_INTEGRITY",`apps/${y.name}`));if(V.length>0){let y=V.some(m=>m.kind==="symlink")?"PATH_ESCAPED":"BUNDLE_INTEGRITY";return s(I(y),false,d)}let b=new Set,C=new Map,W=new Map;for(let y of l.packages){let m=C.get(y.appId)??[];m.push(y),C.set(y.appId,m);let N=`${y.definition.id}\0${String(y.definition.version)}`,L=W.get(N)??[];L.push(y),W.set(N,L);}for(let y of [...C.values(),...W.values()])if(y.length>1)for(let m of y)b.add(m);let D=[],O=c.byteLength,S=false;for(let y of l.packages){if(!Me(t,i)){S=true,D.push({indexEntry:y,failureCode:"LIMIT_EXCEEDED"});continue}let m;try{let P=y.lineage[y.lineage.length-1];if(!P)throw new De("LINEAGE_INVALID","Definition lineage is missing");if(P.definition.id!==y.definition.id||P.version!==y.definition.version||P.hash!==y.definition.hash)throw new De("LINEAGE_STALE","Last lineage generation does not match bundle identity");m=qt(y.lineage,{...P.definition,hash:P.hash}).entries;}catch(P){let R=P instanceof De?P.code:"LINEAGE_INVALID";o.push(a(R,y.packageDir)),D.push({indexEntry:y,failureCode:R});continue}let N=T.find(P=>P.name===y.packageDir.slice(5));if(!A||!N){D.push({indexEntry:y,failureCode:"BUNDLE_INTEGRITY"});continue}if(N.kind!=="directory"){D.push({indexEntry:y,failureCode:N.kind==="symlink"?"PATH_ESCAPED":"BUNDLE_INTEGRITY"});continue}let L;try{let P=await Td(n,e.root,y.packageDir,t,i);if(!Me(t,i)){S=!0,D.push({indexEntry:y,failureCode:"LIMIT_EXCEEDED"});continue}let R=y.files.map(x=>x.path);if(P.length!==R.length||P.some((x,ge)=>x!==R[ge])){D.push({indexEntry:y,failureCode:"BUNDLE_INTEGRITY"});continue}L=new Map;let G;for(let x of y.files){if(!Me(t,i)){G="LIMIT_EXCEEDED",S=!0;break}if(O>=li){G="LIMIT_EXCEEDED";break}let ge;try{ge=await ar(n,e.root,`${y.packageDir}/${x.path}`,Dd(x.path));}catch(ct){G=je(ct);break}if(!Me(t,i)){G="LIMIT_EXCEEDED",S=!0;break}if(O+ge.byteLength>li){O=li,G="LIMIT_EXCEEDED";break}if(O+=ge.byteLength,createHash("sha256").update(ge).digest("hex")!==x.sha256){G="BUNDLE_INTEGRITY";break}L.set(x.path,ge);}if(G!==void 0){D.push({indexEntry:y,failureCode:G});continue}}catch(P){Me(t,i)||(S=true),D.push({indexEntry:y,failureCode:je(P)});continue}D.push({indexEntry:y,lineage:m,files:L,...b.has(y)?{failureCode:"DUPLICATE_ID"}:{}});}return s(D,S,d)}var od,yi,Ai,rd,sd,ad,li,ui,cd,dd,Ii=w(()=>{g();Zt();Ce();$t();qn();pi();od=256*1024,yi=64,Ai=128,rd=yi*Ai,sd=2*1024*1024,ad=8*1024*1024,li=32*1024*1024,ui=/^[0-9a-f]{64}$/,cd=new TextDecoder("utf-8",{fatal:true}),dd=Object.freeze({appIds:Object.freeze([]),definitionIds:Object.freeze([])});});var Ur={};Fr(Ur,{AppDiscoveryFsError:()=>_,LOCAL_APP_TOOL_PREFIX:()=>Pd,MCP_APP_WORKSPACE_TOOL_PREFIX:()=>Sd,NodeAppDiscoveryFs:()=>Qe,NodeAppDiscoveryFsAdapter:()=>ir,WORKSPACE_APP_TOOL_PREFIX:()=>en,createWorkspaceAppScanCache:()=>Yo,defaultAppDiscoveryFs:()=>tt,defaultNodeAppDiscoveryFs:()=>tr,deriveWorkspaceAppToolName:()=>Md,deriveWorkspaceAppToolNames:()=>hi,discoverWorkspaceAppCandidates:()=>ip,discoverWorkspaceApps:()=>_i,isWorkspacePackage:()=>bd,productAppBundleReservations:()=>Tn,scanWorkspaceApps:()=>op});function bd(e,n){let t=n.split("/");return t.length===2&&t[0]===e&&/^[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(t[1])}function hi(e){if(typeof e!="string"||!me.test(e))throw new TypeError("pluginId must be a safe UI plugin identifier");let n=`${en}${e}`.length+7<=128?e:`hash_${createHash("sha256").update(e,"utf8").digest("hex")}`;return {read:`${en}${n}_read`,action:`${en}${n}_action`}}function Md(e,n="read"){let t=hi(e);return n==="read"?t.read:t.action}function lr(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;try{let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}catch{return false}}function Ld(e,n){return n.length===0||n==="."||n===".."||/[\\/\u0000]/.test(n)?e==="skills"?"skills":"apps":`${e==="skills"?"skills":"apps"}/${n}`}function Rd(e){return e.length>0&&e!=="."&&e!==".."&&!/[\\/\u0000]/.test(e)}function Nn(e,n){let t=new TextEncoder().encode(e),i=new TextEncoder().encode(n),r=Math.min(t.byteLength,i.byteLength);for(let o=0;o<r;o+=1){let a=t[o]-i[o];if(a!==0)return a}return t.byteLength-i.byteLength}function Tr(e){if(typeof e=="string")return {name:e,kind:"directory"};if(e===null||typeof e!="object")return null;let n=e;if(typeof n.name!="string")return null;if(n.kind==="file"||n.kind==="directory"||n.kind==="symlink"||n.kind==="other")return {name:n.name,kind:n.kind};if(n.type==="file"||n.type==="directory"||n.type==="symlink"||n.type==="other")return {name:n.name,kind:n.type};let t=n.isDirectory;if(typeof t=="function"&&t.call(e))return {name:n.name,kind:"directory"};let i=n.isSymbolicLink;if(typeof i=="function"&&i.call(e))return {name:n.name,kind:"symlink"};let r=n.isFile;return typeof r=="function"&&r.call(e)?{name:n.name,kind:"file"}:{name:n.name,kind:"other"}}function Ud(e){if(e instanceof Uint8Array)return new Uint8Array(e);if(e instanceof ArrayBuffer)return new Uint8Array(e.slice(0));if(Array.isArray(e)&&e.every(n=>Number.isInteger(n)&&n>=0&&n<=255))return Uint8Array.from(e);throw new TypeError("filesystem port returned an invalid byte array")}function Dr(e){return Od.decode(e)}function Cd(e){return JSON.parse(Dr(e))}function wd(e){if(e===void 0)return;let n=e.definitionId!==void 0&&e.definitionVersion!==void 0?`${e.definitionId}\0${String(e.definitionVersion)}`:void 0;return {pluginId:e.pluginId,...n===void 0?{}:{definitionKey:n}}}function ot(e,n,t,i,r){let o={code:e,...i===void 0?{}:{pluginId:i},source:n,relativePath:t,...r?.reason===void 0?{}:{reason:Object.freeze({...r.reason})},...r?.files===void 0?{}:{files:Object.freeze([...r.files])}};return Object.freeze(o)}function ur(e){switch(e){case "ENOENT":return "NOT_FOUND";case "ELOOP":case "EXDEV":return "PATH_ESCAPED";case "EFBIG":case "EOVERFLOW":return "LIMIT_EXCEEDED";case "EACCES":case "EPERM":case "ENOTDIR":return "READ_DENIED";default:return e}}function te(e){if(e instanceof _)return ur(e.code);if(e!==null&&typeof e=="object"&&"code"in e){let n=e.code;if(typeof n=="string")return ur(n)}}function Fe(e,n){return e==="PATH_ESCAPED"||e==="IDENTITY_CHANGED"||e==="TOCTOU"?"PATH_ESCAPED":e==="LIMIT_EXCEEDED"?"LIMIT_EXCEEDED":n==="manifest"&&e==="NOT_FOUND"?"MANIFEST_MISSING":n==="entry"?"ENTRY_INVALID":n==="initial"?"INITIAL_STATE_INVALID":"MANIFEST_INVALID"}function fr(e){return {reason:e.reason,...e.code==="MANIFEST_DUAL_MISMATCH"?{files:e.files}:{}}}function yr(e){return e==="MANIFEST_DUAL_MISMATCH"?e:Nr(e)}function kd(e){return Nr(e.code)}function Nr(e){switch(e){case "MANIFEST_INVALID":case "PRIMITIVE_UNKNOWN":case "PRIMITIVE_SET_UNSUPPORTED":case "SCHEMA_TYPE_UNSUPPORTED":case "TOKEN_INVALID":case "UNSAFE_VALUE":return "MANIFEST_INVALID";case "LIMIT_EXCEEDED":return "LIMIT_EXCEEDED";case "INITIAL_STATE_INVALID":return "INITIAL_STATE_INVALID";default:return br("UiPluginValidationError",e)}}function br(e,n){throw new Error(`Unmapped ${e} code: ${String(n)}`)}function Pr(e){switch(e){case "APP_ID_INVALID":case "TOOL_ID_INVALID":case "RESOURCE_URI_INVALID":case "TOOL_INVALID":case "SERIALIZATION_INVALID":return "MANIFEST_INVALID";case "APP_ID_CONFLICT":case "TOOL_ID_CONFLICT":return "DUPLICATE_ID";case "RESOURCE_NOT_FOUND":case "HTML_INVALID":return "ENTRY_INVALID";case "STATE_INVALID":case "STATE_PROJECTION_INVALID":case "BUTTON_INVALID":return "INITIAL_STATE_INVALID";default:return br("McpAppContractError",e)}}function Oe(e,n){let t=n();return Number.isFinite(t)&&Number.isFinite(e)&&t-e<=5e3}function xd(e){return {pluginId:e.appId,definitionKey:`${e.definition.id}\0${String(e.definition.version)}`}}function jd(e,n){let t=n.get("package.json");if(t!==void 0)try{let r=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(t));if(lr(r)){let o=r.bin,a=typeof o=="string"?o:lr(o)?Object.values(o).find(s=>typeof s=="string"):void 0;for(let s of [a,r.main]){if(typeof s!="string")continue;let c=vd(s);if(c&&n.has(c))return c}}}catch{}return [`${e.slice(e.lastIndexOf("/")+1)}.js`,"index.js","main.js"].find(r=>n.has(r))}function vd(e){if(e.startsWith("/")||e.includes("\\")||e.includes("\0"))return;let n=e.split("/").filter(t=>t!==".");if(!(n.length===0||n.some(t=>t.length===0||t==="..")))return n.join("/")}function Vd(){return globalThis.performance?.now()??Date.now()}function Ve(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let n of Object.values(e))Ve(n);return Object.freeze(e)}function Ar(e){return Object.freeze(Array.from(e))}async function bn(e,n,t,i){if(n.pinnedFiles!==void 0){let s=n.pinnedFiles.get(t);if(s===void 0)throw new _("NOT_FOUND");if(s.byteLength>i)throw new _("LIMIT_EXCEEDED");return new Uint8Array(s)}let r=`${n.relativePath}/${t}`,o=n.scanContext,a=e.fingerprintVerifiedFile;if(o===void 0||!o.cacheable||typeof a!="function")return hr(e,n.root,r,i);try{let s=o.priorFingerprints.get(r)??await a.call(e,o.workspaceRoot,r,i);o.candidateRealPath=s.candidateRealPath;let c=await hr(e,n.root,r,i),d=await a.call(e,o.workspaceRoot,r,i);return o.candidateRealPath=d.candidateRealPath,Mr(s,d)&&d.size===BigInt(c.byteLength)&&!Or(d,o.scanStartedAtNs)?o.files.set(r,{relativePath:r,byteLimit:i,fingerprint:d}):o.cacheable=!1,c}catch(s){let c=!t.includes("/")&&te(s)==="NOT_FOUND"&&o.directoryListings.some(l=>l.relativePath===n.relativePath&&!rt(l.key,t)),d=t===q&&te(s)==="NOT_FOUND"&&Bd(o.directoryListings,n.relativePath);throw !c&&!d&&(o.cacheable=false),s}}async function Fd(e,n,t){if(n.pinnedFiles!==void 0)return {iconDiagnostics:[]};let i=await Xt(t,async o=>{try{return await bn(e,n,o,262144)}catch(a){let s=te(a);return s==="NOT_FOUND"?"missing":s==="LIMIT_EXCEEDED"?"too-large":"bad-path"}}),r=i.file;return {...r===void 0?{}:{iconFile:{path:r.path,sha256:createHash("sha256").update(r.bytes).digest("hex"),contentType:r.contentType,byteLength:r.byteLength}},iconDiagnostics:i.diagnostics}}function Bd(e,n){let t=e.find(r=>r.relativePath===n);if(t===void 0)return false;if(!rt(t.key,"dist"))return true;let i=e.find(r=>r.relativePath===`${n}/dist`);return i!==void 0&&!rt(i.key,"tools.json")}function Sr(e,n){return JSON.stringify([e.realPath,n.source,n.relativePath])}async function zd(e,n,t,i,r,o,a,s){let c=e.fingerprintVerifiedFile,d=Sr(t,i),l=r.candidates.get(d),u=i.relativePath,f;try{f=await mr(e,n,u);}catch(S){if(te(S)!=="NOT_FOUND")throw S}let A=f===void 0?void 0:{relativePath:u,key:f};if(A!==void 0&&(i.source==="apps"||i.source==="skills")&&!le.some(S=>rt(A.key,S)))return Oe(a,s)?l!==void 0&&l.candidate===void 0&&l.candidateRealPath===void 0&&l.files.length===0&&l.directoryListings.length===1&&l.directoryListings[0]?.relativePath===A.relativePath&&l.directoryListings[0]?.key===A.key&&(i.source==="apps"?l.diagnostic?.code==="MANIFEST_MISSING":l.diagnostic===void 0)&&typeof c=="function"?{memo:l}:typeof c!="function"?{}:{context:{state:r,cacheKey:d,workspaceRoot:n,scanStartedAtNs:o,directoryListings:Object.freeze([A]),priorFingerprints:new Map,files:new Map,cacheable:true}}:{timeLimitReached:true};let I=async S=>{if(S==="")return A;let y=`${i.relativePath}${S}`;try{let m=await mr(e,n,y);return m===void 0?void 0:{relativePath:y,key:m}}catch(m){if(te(m)==="NOT_FOUND")return;throw m}},h=await Promise.all(Ir.map(I)),T=await Promise.all(Hd.map(I));if(!Oe(a,s))return {timeLimitReached:true};let J=typeof c=="function"&&h.every(S=>S!==void 0),V=h.filter(S=>S!==void 0),b=[...V,...T.filter(S=>S!==void 0)],C=new Map,W=l!==void 0&&J,D;if(l!==void 0&&typeof c=="function"){let S=await Promise.all(l.files.map(async y=>{if(!Oe(a,s))return {kind:"time",file:y};try{let m=await c.call(e,n,y.relativePath,y.byteLimit);return {kind:"fingerprint",file:y,current:m}}catch(m){return te(m)==="NOT_FOUND"?{kind:"missing",file:y}:{kind:"error",file:y,error:m}}}));if(S.some(y=>y.kind==="time"))return {timeLimitReached:true};for(let y of S){if(y.kind==="error")throw y.error;if(y.kind==="missing"){W=false;continue}if(y.kind!=="fingerprint")continue;let{file:m,current:N}=y;C.set(m.relativePath,N),D??=N.candidateRealPath,(N.candidateRealPath!==l.candidateRealPath||!Mr(N,m.fingerprint)||Or(N,o))&&(W=false);}}let O=l!==void 0&&l.directoryListings.length===b.length&&l.directoryListings.every((S,y)=>S.relativePath===b[y]?.relativePath&&S.key===b[y]?.key);return l!==void 0&&J&&O&&W&&D===l.candidateRealPath?{memo:l}:!J||V.length!==Ir.length?{}:{context:{state:r,cacheKey:d,workspaceRoot:n,scanStartedAtNs:o,directoryListings:Object.freeze(b),priorFingerprints:C,files:new Map,...D===void 0?{}:{candidateRealPath:D},cacheable:true}}}function rt(e,n){try{let t=JSON.parse(e);return Array.isArray(t)&&t.some(i=>Array.isArray(i)&&i[0]===n)}catch{return true}}async function mr(e,n,t){let i=Lr(e);if(typeof i!="function")return;let r=await i.call(e,n,t);if(!Array.isArray(r)||r.some(a=>typeof a=="string"))return;let o=r.map(Tr);if(!o.some(a=>a===null))return JSON.stringify(o.slice().sort((a,s)=>Nn(a.name,s.name)||Nn(a.kind,s.kind)).map(a=>[a.name,a.kind]))}function Mr(e,n){return e.dev===n.dev&&e.ino===n.ino&&e.size===n.size&&e.mtimeNs===n.mtimeNs&&e.ctimeNs===n.ctimeNs}function Or(e,n){let t=e.mtimeNs-n;return t>=-gr&&t<=gr}function gi(e){let n=e.scanContext,t=e.source==="skills"&&e.candidate===void 0&&e.diagnostic===void 0&&n?.files.size===0,i=e.source==="apps"&&e.candidate===void 0&&e.diagnostic?.code==="MANIFEST_MISSING"&&n?.files.size===0,r=t||i;if(n===void 0||!n.cacheable||n.candidateRealPath===void 0&&!r||n.files.size===0&&!r)return;let o=Object.freeze({...!r&&n.candidateRealPath!==void 0?{candidateRealPath:n.candidateRealPath}:{},directoryListings:n.directoryListings,files:Object.freeze([...n.files.values()]),...e.candidate===void 0?{}:{candidate:e.candidate},...e.diagnostic===void 0?{}:{diagnostic:e.diagnostic},...e.identity===void 0?{}:{identity:e.identity},...e.provenance===void 0?{}:{provenance:e.provenance}});n.state.candidates.set(n.cacheKey,o);}function Jd(e,n,t){let i=createHash("sha256"),r=new TextEncoder().encode(Q(e)),o=a=>{let s=new Uint8Array(8);new DataView(s.buffer).setBigUint64(0,BigInt(a)),i.update(s);};return o(r.byteLength),i.update(r),o(n.byteLength),i.update(n),o(t.byteLength),i.update(t),i.digest("hex")}function Gd(e,n){let t={...e.definition,sourceHash:n},i;try{i=oe(t);}catch(o){throw o instanceof U&&o.code==="INPUT_INVALID"?new re("MANIFEST_INVALID","normalized definition is invalid"):o}let r={...t,hash:i};try{de(r);}catch{throw new re("MANIFEST_INVALID","normalized definition is invalid")}return r}function $d(e,n){return e.actions.some(t=>t.backend.type==="core"&&t.backend.handler!=="state.set"&&!Gn(n,t.backend))}function Wd(e){if(typeof e.readVerifiedFile=="function")return e.readVerifiedFile;if(typeof e.readFileVerified=="function")return e.readFileVerified}function Lr(e){if(typeof e.listDirectory=="function")return e.listDirectory;if(typeof e.readDirectory=="function")return e.readDirectory;if(typeof e.readdir=="function")return e.readdir}async function hr(e,n,t,i){let r=Wd(e);if(!r)throw new _("READ_DENIED");return Ud(await r.call(e,n,t,i))}async function Xd(e,n,t){let i=Lr(e);if(!i)throw new _("READ_DENIED");let r=await i.call(e,n,t);if(!Array.isArray(r))throw new _("READ_DENIED");return r.map(Tr).filter(o=>o!==null)}function Kd(e){let n=[];for(let t of [e.reserved,e.builtin])t&&n.push(t);return e.builtins&&"listMcpApps"in e.builtins?n.push(_r(e.builtins)):e.builtins&&n.push(e.builtins),e.builtinCatalog&&n.push(_r(e.builtinCatalog)),n.push({...e.reservedAppIds===void 0?{}:{appIds:e.reservedAppIds},...e.reservedDefinitionIds===void 0?{}:{definitionIds:e.reservedDefinitionIds},...e.reservedToolNames===void 0?{}:{toolNames:e.reservedToolNames}}),n}function _r(e){let n=[],t=[],i=[];for(let r of e.listMcpApps())typeof r.appId=="string"&&n.push(r.appId),r.definition&&typeof r.definition.id=="string"&&t.push(r.definition.id);for(let r of e.listMcpAppTools())typeof r.name=="string"&&i.push(r.name);return {appIds:n,definitionIds:t,toolNames:i}}function Ae(e,n){e.diagnostic||(e.diagnostic=ot(n,e.source,e.relativePath,e.identity?.pluginId));}function Yd(e,n){let t=new Set,i=new Map;for(let o of e){let a=o.identity?.pluginId;if(a===void 0)continue;let s=i.get(a)??[];s.push(o),i.set(a,s);}for(let o of i.values()){if(o.length<2)continue;let a=o.filter(c=>c.provenance!==void 0);if(a.length>0){let c=o.find(d=>n.has(d));if(c){for(let d of a)t.add(d);for(let d of o)d!==c&&d.provenance===void 0&&Ae(d,"RESERVED_ID");continue}for(let d of o)d.provenance===void 0&&Ae(d,"RESERVED_ID");if(a.length>1)for(let d of a)Ae(d,"DUPLICATE_ID");continue}let s=o.filter(c=>c.source==="apps");if(s.length>1){for(let c of s)Ae(c,"DUPLICATE_ID");for(let c of o.filter(d=>d.source==="skills"))Ae(c,"DUPLICATE_ID");}else for(let c of o.filter(d=>d.source==="skills"))Ae(c,"DUPLICATE_ID");}let r=new Map;for(let o of e){if(o.diagnostic?.code==="RESERVED_ID"||t.has(o)||o.provenance===void 0&&!n.has(o)&&i.get(o.identity?.pluginId??"")?.some(c=>c.provenance!==void 0))continue;let a=o.identity?.definitionKey;if(a===void 0)continue;let s=r.get(a)??[];s.push(o),r.set(a,s);}for(let o of r.values())if(o.length>1)for(let a of o)Ae(a,"DUPLICATE_ID");return t}function qd(e,n,t){let i=new Set,r=new Set,o=new Set,a=new Set([...t.appIds,...n.productBundleReservationMetadata?.reservedAppIds??[]]),s=new Set([...t.definitionIds,...n.productBundleReservationMetadata?.reservedDefinitionIds??[]]);for(let l of Kd(n)){for(let u of l.appIds??[])typeof u=="string"&&i.add(u);for(let u of l.definitionIds??[])typeof u=="string"&&r.add(u);for(let u of l.toolNames??[])typeof u=="string"&&o.add(u);}for(let l of e){let u=l.candidate;if(!u)continue;if(i.has(u.pluginId)||r.has(u.definitionId)){Ae(l,"RESERVED_ID");continue}[u.toolNames.read,u.toolNames.action].filter(A=>A!==void 0).some(A=>o.has(A))&&Ae(l,"DUPLICATE_ID");}let c=[...e.filter(l=>l.provenance!==void 0&&l.diagnostic===void 0).flatMap(l=>l.candidate?[l.candidate]:[]),...(n.productBundleReservationMetadata?.candidates??[]).filter(l=>n.productBundleReservationMetadata?.indexHash!==void 0&&l.provenance?.indexHash===n.productBundleReservationMetadata.indexHash)],d=new Set;for(let l of e){let u=l.candidate;if(!(!u||l.diagnostic||l.source!=="apps"||l.provenance!==void 0)&&e.filter(f=>f.source==="apps"&&f.identity?.pluginId===u.pluginId).length===1&&c.some(f=>f.pluginId===u.pluginId)&&!(s.has(u.definitionId)&&!c.some(f=>f.pluginId===u.pluginId&&f.definitionId===u.definitionId))&&!c.some(f=>f.pluginId!==u.pluginId&&f.definitionId===u.definitionId)&&!e.some(f=>f.identity?.pluginId!==u.pluginId&&f.identity?.definitionKey===`${u.definitionId}\0${u.version}`&&f.diagnostic?.code!=="RESERVED_ID"))try{Xo(u),d.add(l);}catch(f){Ae(l,f instanceof Te?Pr(f.code):"EXEC_DENIED");}}for(let l of e){let u=l.candidate;u&&l.provenance===void 0&&!d.has(l)&&(a.has(u.pluginId)||s.has(u.definitionId))&&Ae(l,"RESERVED_ID");}return d}function Zd(e){return [...e].sort((n,t)=>{let i=pr.indexOf(n.source)-pr.indexOf(t.source);return i!==0?i:Nn(n.relativePath,t.relativePath)})}function F(e,n,t){e.diagnostic=ot(n,e.source,e.relativePath,e.identity?.pluginId,t);}async function Er(e,n,t){let i=Gt(t,{mode:"local"});if(!i.ok&&i.parseFailure){F(n,yr(i.rejection.code),fr(i.rejection));return}let r=wd(i.identity);if(n.bundleIdentity===void 0)n.identity=r;else if(r?.pluginId!==n.bundleIdentity.appId||r.definitionKey!==`${n.bundleIdentity.definitionId}\0${String(n.bundleIdentity.version)}`){F(n,"BUNDLE_INTEGRITY");return}if(!i.ok&&i.builtinOnly){F(n,"RESERVED_ID");return}if(!i.ok){F(n,yr(i.rejection.code),fr(i.rejection));return}let o=i.manifest,a={pluginId:o.pluginId,definitionKey:`${o.definitionId}\0${String(o.version)}`};if(n.bundleIdentity===void 0&&(n.identity=a),o.actions.length>0)try{ni(o.actions.map(R=>({actionId:R.actionId,inputSchema:R.inputSchema})));}catch(R){if(R instanceof Te){F(n,Pr(R.code));return}throw R}let s;try{s=await bn(e,n,"ui/index.html",Ye);}catch(R){F(n,Fe(te(R),"entry"));return}if(s.byteLength>Ye){F(n,"LIMIT_EXCEEDED");return}let c;try{c=Dr(s);}catch{F(n,"ENTRY_INVALID");return}if(s.byteLength===0||c.length===0){F(n,"ENTRY_INVALID");return}let d=createHash("sha256").update(s).digest("hex");if(o.entryHash!==void 0&&o.entryHash!==d){F(n,"ENTRY_INVALID");return}let l={},u,f;if(o.initialState!==void 0){try{u=await bn(e,n,"ui/state.json",2097152);}catch(R){F(n,Fe(te(R),"initial"));return}if(u.byteLength>2097152){F(n,"LIMIT_EXCEEDED");return}try{let R=Cd(u),G=o.dataPaths??[],x=xt(R,G);l=ce(x,0,G),ze(l);}catch{F(n,"INITIAL_STATE_INVALID");return}if(f=createHash("sha256").update(u).digest("hex"),o.initialState.hash!==void 0&&o.initialState.hash!==f){F(n,"INITIAL_STATE_INVALID");return}}let A={...o,entryHash:d,...o.initialState===void 0?{}:{initialState:{path:"ui/state.json",hash:f}}},I=cn(A),h=Jd(A,s,u??new Uint8Array),T;try{T=Gd(I,h);}catch(R){if(R instanceof re){F(n,kd(R));return}throw R}let J;if(n.bundleLineage!==void 0){let R=n.bundleLineage[n.bundleLineage.length-1];if(!R){F(n,"LINEAGE_INVALID");return}let{legacy:G,...x}=R.definition,{hash:ge,...ct}=T;if(Q(x)!==Q(ct)){F(n,"LINEAGE_STALE");return}if(G!==void 0&&(T={...T,legacy:G}),G!==void 0)try{T={...T,hash:oe(T)},de(T);}catch{F(n,"LINEAGE_INVALID");return}J=n.bundleLineage;}if(n.bundleIdentity!==void 0&&n.bundleIdentity.appId!==o.pluginId){F(n,"BUNDLE_INTEGRITY");return}if(n.bundleIdentity!==void 0&&(n.bundleIdentity.definitionId!==T.id||n.bundleIdentity.version!==T.version||n.bundleIdentity.definitionHash!==T.hash)){F(n,"LINEAGE_STALE");return}let V=await Fd(e,n,i.mcpb?.icon),b=hi(o.pluginId),C=o.actions.length===0?{read:b.read}:b,W=Ve(I),D=Ve(A),O=Ve(T),S=Ve({...I.handlers}),y=Ar(s),m=u===void 0?void 0:Ar(u),N=Object.freeze({...n.provenance===void 0?{}:{provenance:n.provenance},entry:Object.freeze({path:"ui/index.html",hash:d,bytes:y}),...m===void 0?{}:{initialState:Object.freeze({path:"ui/state.json",hash:f,bytes:m})}}),L={appId:o.pluginId,pluginId:o.pluginId,definitionId:o.definitionId,version:o.version,...i.releaseVersion===void 0?{}:{releaseVersion:i.releaseVersion},manifestFile:i.file,...i.mcpb===void 0?{}:{mcpb:Ve(i.mcpb)},relativePath:n.relativePath,manifest:D,normalized:W,name:o.name,description:o.description,...o.icon===void 0?{}:{icon:o.icon},...o.tone===void 0?{}:{tone:o.tone},...V.iconFile===void 0?{}:{iconFile:Object.freeze({...V.iconFile})},...V.iconDiagnostics.length===0?{}:{iconDiagnostics:Object.freeze([...V.iconDiagnostics])},definition:O,handlers:S,resources:N,html:c,entryBytes:y,entryHash:d,initialState:Ve(l),...m===void 0?{}:{initialStateBytes:m},...f===void 0?{}:{initialStateHash:f},sourceHash:h,toolNames:Object.freeze(C)},P=n.provenance===void 0?{...L,source:n.source}:{...L,provenance:n.provenance,lineage:J??[]};n.candidate=Object.freeze(P),$d(o,T.usage)&&F(n,"EXEC_DENIED");}async function Rr(e,n){let t={};for(let i of le)try{t[i]=await bn(e,n,i,262144);}catch(r){if(te(r)==="NOT_FOUND")continue;return {files:t,failure:Fe(te(r),"manifest")}}if(t[Y]!==void 0)try{t[q]=await bn(e,n,q,262144);}catch(i){if(te(i)!=="NOT_FOUND")return {files:t,failure:Fe(te(i),"manifest")}}return {files:t}}function mi(e){return le.some(n=>e[n]!==void 0)}async function Qd(e,n){let{files:t,failure:i}=await Rr(e,n);if(i!==void 0){F(n,i);return}let r=t[Y];return r!==void 0&&!Jt(r)&&(delete t[Y],delete t[q]),mi(t)?t:void 0}function ep(e,n,t,i=Nd,r=false,o=new Set){let a=Zd(e),s=Yd(a,o),c=Object.freeze(a.filter(f=>f.candidate!==void 0&&f.diagnostic===void 0&&!s.has(f)).map(f=>f.candidate)),d=Object.freeze(a.filter(f=>f.diagnostic!==void 0).map(f=>f.diagnostic)),l=r?Object.freeze({...t===void 0?{}:{indexHash:t},candidates:Object.freeze(a.filter(f=>f.source==="bundled"&&f.diagnostic===void 0&&t!==void 0&&f.candidate?.provenance?.indexHash===t).map(f=>f.candidate)),diagnostics:Object.freeze(d.filter(f=>f.source==="bundled").map(f=>Object.freeze({...f}))),reservedAppIds:Object.freeze([...i.appIds]),reservedDefinitionIds:Object.freeze([...i.definitionIds])}):void 0,u={apps:c,diagnostics:d,complete:n===void 0,...n===void 0?{}:{incompleteReason:n},...t===void 0?{}:{productBundleIndexHash:t},...l===void 0?{}:{productBundleSnapshotMetadata:l}};return Object.defineProperty(u,"candidates",{configurable:false,enumerable:false,get:()=>c}),Object.freeze(u)}function np(e){if(e===null||typeof e!="object"&&typeof e!="function")return false;let n=e;return typeof n.readVerifiedFile=="function"||typeof n.readFileVerified=="function"||typeof n.listDirectory=="function"||typeof n.readDirectory=="function"||typeof n.readdir=="function"}function tp(e,n){if(np(e))return {fs:e,options:n??{}};let t=e??n??{};return {fs:t.filesystem??t.fileSystem??t.fs??tt,options:t}}async function _i(e,n,t){if(typeof e!="string"||e.length===0)throw new TypeError("workspaceRoot must be explicit");let{fs:i,options:r}=tp(n,t),o=r.clock??Vd,a=o(),s=await dr(r.productBundle,i,a,o),c=o(),d=BigInt(Date.now())*1000000n,l=[],u=0,f,A=false,I,h;if(r.scanCache!==void 0&&typeof i.getRootIdentity=="function"&&typeof i.fingerprintVerifiedFile=="function")try{h=await i.getRootIdentity(e),I=qo(r.scanCache,h),I.scanStartedAtNs=d;}catch(D){if(te(D)!=="NOT_FOUND")throw D}let T=I!==void 0&&r.productBundle===void 0&&s.packages.length===0&&s.diagnostics.length===0,J=new Set,V=true;l.push(...s.diagnostics.map(D=>({source:D.source,root:r.productBundle?.root??e,name:"",relativePath:D.relativePath,diagnostic:D})));let b=s.reservedIds;s.incomplete&&(f="time_limit");for(let D of s.packages){if(!Oe(c,o)){A=true,f="time_limit";break}let O=D.indexEntry,S=O.packageDir,y=D.files===void 0?void 0:jd(S,D.files),m=s.indexHash===void 0?void 0:Do(Object.freeze({kind:"bundled",launcher:O.launcher!==false,indexHash:s.indexHash,packageDir:S,appId:O.appId,definitionId:O.definition.id,version:O.definition.version,definitionHash:O.definition.hash,files:O.files}),y),N={source:"bundled",root:r.productBundle?.root??e,name:S.slice(5),relativePath:S,...m===void 0?{}:{provenance:m},...D.files===void 0?{}:{pinnedFiles:D.files},...D.lineage===void 0?{}:{bundleLineage:D.lineage},bundleIdentity:{appId:O.appId,definitionId:O.definition.id,version:O.definition.version,definitionHash:O.definition.hash},identity:xd(O)};if(l.push(N),u+=1,D.failureCode!==void 0){F(N,D.failureCode);continue}if(D.files?.has(q)===true){F(N,"EXEC_DENIED",{reason:{path:"",rule:"bundled-tool-mode-unsupported",file:q}});continue}let L={};for(let P of le){let R=D.files?.get(P);R!==void 0&&(L[P]=R);}if(!mi(L)){F(N,"BUNDLE_INTEGRITY");continue}if(await Er(i,N,L),!Oe(c,o)){A=true,f="time_limit";break}}let C=[{source:"apps",directory:"apps"},{source:"skills",directory:"skills"}];e:for(let D of C){let{source:O,directory:S}=D,y;try{y=await Xd(i,e,S);}catch(N){if(te(N)==="NOT_FOUND")continue;T=false,V=false,l.push({source:O,root:e,name:"",relativePath:O,diagnostic:ot(Fe(te(N),"manifest"),O,O)});continue}let m=y.filter(N=>N.kind==="directory"||N.kind==="symlink").filter(N=>Rd(N.name)).map(N=>({source:O,root:e,name:N.name,relativePath:Ld(O,N.name)})).sort((N,L)=>Nn(N.relativePath,L.relativePath));for(let N of m){let L={...N};if(l.push(L),h!==void 0?J.add(Sr(h,L)):T=false,!Oe(c,o)){A=true,f="time_limit";break e}let P;if(I!==void 0&&h!==void 0){try{let x=await zd(i,e,h,L,I,d,c,o);if(x.timeLimitReached){A=!0,f="time_limit";break e}L.scanContext=x.context,P=x.memo;}catch(x){T=false,F(L,Fe(te(x),"manifest"));continue}P===void 0&&(T=false);}if(P!==void 0){if(L.candidate=P.candidate,L.diagnostic=P.diagnostic,L.identity=P.identity,O==="skills"&&P.candidate===void 0&&P.diagnostic===void 0)continue;if(u>=64){F(L,"LIMIT_EXCEEDED");continue}if(N.relativePath.split("/").length-1>2){F(L,"LIMIT_EXCEEDED");continue}if(u+=1,!Oe(c,o)){A=true,f="time_limit";break e}continue}let R;if(O==="skills"&&(R=await Qd(i,L),R===void 0)){L.diagnostic===void 0&&gi(L);continue}if(u>=64){F(L,"LIMIT_EXCEEDED");continue}if(N.relativePath.split("/").length-1>2){F(L,"LIMIT_EXCEEDED");continue}if(!Oe(c,o)){A=true,f="time_limit";break e}if(u+=1,R===void 0){let x=await Rr(i,L);if(x.failure!==void 0||!mi(x.files)){F(L,x.failure??Fe("NOT_FOUND","manifest")),gi(L);continue}R=x.files;}if(await Er(i,L,R),gi(L),!Oe(c,o)){A=true,f="time_limit";break e}}}if(I!==void 0&&h!==void 0){let D=[...J].sort(Nn),O=I.lastCandidateKeys,S=O!==void 0&&O.length===D.length&&O.every((m,N)=>m===D[N]);if(T=T&&S,V&&!A&&f===void 0)for(let m of I.candidates.keys())try{JSON.parse(m)[0]===h.realPath&&!J.has(m)&&I.candidates.delete(m);}catch{I.candidates.delete(m);}let y=[...I.candidates.keys()].filter(m=>{try{return JSON.parse(m)[0]===h.realPath}catch{return false}});T=T&&y.length===J.size&&y.every(m=>J.has(m))&&!A&&f===void 0,I.lastCandidateScanUnchanged=T,V&&!A&&f===void 0&&(I.lastCandidateKeys=Object.freeze(D));}A&&l.push({source:"apps",root:e,name:"",relativePath:"apps",diagnostic:ot("DISCOVERY_TIME_LIMIT","apps","apps")});let W=qd(l,r,b);return ep(l,f,s.indexHash,b,r.productBundle!==void 0,W)}var Nd,en,Pd,Sd,pr,Od,Ir,Hd,gr,ip,op,Cr=w(()=>{g();we();Pn();Ne();ho();Kt();Ce();qn();Ko();$n();zn();Zo();pi();Jn();Ii();Ii();Nd=Tn([]);en="crewx_local_app_",Pd=en,Sd=en;pr=["bundled","apps","skills"],Od=new TextDecoder("utf-8",{fatal:true});Ir=["","/ui"],Hd=["/dist"],gr=2000000000n;ip=_i,op=_i;});g();var wr="SKILL.md",dp=/^---\s*\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;function kr(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function pp(e){return e.isDirectory()||e.isSymbolicLink()}function vr(e){try{return existsSync(e)&&statSync(e).isDirectory()}catch{return false}}var lp=["index.js","main.js"];function Of(e,n){let t=join(e,"package.json");if(existsSync(t))try{let r=JSON.parse(readFileSync(t,"utf8"));if(r.bin){let o=typeof r.bin=="string"?r.bin:Object.values(r.bin).find(a=>typeof a=="string");if(o){let a=resolve(e,o);if(existsSync(a))return a}}if(typeof r.main=="string"){let o=resolve(e,r.main);if(existsSync(o))return o}}catch{}let i=resolve(e,`${n}.js`);if(existsSync(i))return i;for(let r of lp){let o=resolve(e,r);if(existsSync(o))return o}}function up(e){let n;try{n=readFileSync(e,"utf8");}catch{return {frontmatter:{},readable:false,valid:false,hasFrontmatter:false}}let t=n.match(dp);if(!t)return {frontmatter:{},readable:true,valid:true,hasFrontmatter:false};try{let i=load(t[1]??"");if(!kr(i))return {frontmatter:{},readable:!0,valid:!1,hasFrontmatter:!0};let r=kr(i.metadata)?i.metadata:void 0;return {frontmatter:{...typeof i.name=="string"?{name:i.name}:{},...typeof(r?.version??i.version)=="string"?{version:r?.version??i.version}:{},...typeof i.description=="string"?{description:i.description}:{}},readable:!0,valid:!0,hasFrontmatter:!0}}catch{return {frontmatter:{},readable:true,valid:false,hasFrontmatter:true}}}function fp(e){return [join(e,wr),join(e,"skill",wr)]}function st(e,n){if(!vr(e))return null;for(let t of fp(e)){if(!existsSync(t))continue;let r=up(t).frontmatter;return {name:r.name??n,...r.version===void 0?{}:{version:r.version},...r.description===void 0?{}:{description:r.description},skillMdPath:t,dir:e}}return null}function Ei(e){try{return readdirSync(e,{withFileTypes:!0}).filter(pp)}catch{return []}}function yp(e){return e.length===0||/[\\\u0000]/.test(e)?false:e.split("/").every(n=>n.length>0&&n!=="."&&n!=="..")}function xr(e,n,t){!e||n.has(e.name)||(n.add(e.name),t.push(e));}function at(e){let n=[],t=new Set;for(let i of e)if(vr(i))for(let r of Ei(i)){if(r.name.startsWith("@")){let o=join(i,r.name);for(let a of Ei(o))xr(st(join(o,a.name),a.name),t,n);continue}xr(st(join(i,r.name),r.name),t,n);}return n.sort((i,r)=>i.name.localeCompare(r.name))}function Ap(e,n){if(!yp(e))throw new Error(`Skill not found: ${e}`);for(let i of n){let r=st(join(i,e),e);if(r)return r;for(let o of Ei(i)){if(!o.name.startsWith("@"))continue;let a=st(join(i,o.name,e),e);if(a)return a}}let t=at(n).find(i=>i.name===e);if(t)return t;throw new Error(`Skill not found: ${e}`)}async function Lf(e){if(!e||e.root===null)return {skills:[],diagnostics:[]};let{discoverWorkspaceApps:n}=await Promise.resolve().then(()=>(Cr(),Ur)),t=await n(e.root,{productBundle:e}),i=[],r=new Set;for(let o of t.apps){let a=o.provenance?.kind==="bundled"?o.provenance.packageDir:void 0;if(!a)continue;let s=join(e.root,...a.split("/"));for(let c of at([dirname(s)]))resolve(c.dir)!==resolve(s)||r.has(c.name)||(r.add(c.name),i.push(c));for(let c of [join(s,"skill"),join(s,"skills")])for(let d of at([c]))r.has(d.name)||(r.add(d.name),i.push(d));}return {skills:i.sort((o,a)=>o.name.localeCompare(a.name)),diagnostics:t.diagnostics.filter(o=>o.source==="bundled")}}var Rf=at,Uf=Ap;
2
- export{at as discover,Lf as discoverBundledProductSkills,Rf as discoverSkills,Of as findEntrypoint,up as readSkillFrontmatter,Ap as resolve,Uf as resolveSkill};
1
+ import {join,resolve,dirname,relative,sep,isAbsolute}from'path';import'url';import {createHash}from'crypto';import {isIP}from'net';import {existsSync,readFileSync,statSync,readdirSync,constants}from'fs';import {realpath,stat,readdir,open,lstat}from'fs/promises';import {load}from'js-yaml';var $r=Object.defineProperty;var C=(e,n)=>()=>(e&&(n=e(e=0)),n);var Wr=(e,n)=>{for(var t in n)$r(e,t,{get:n[t],enumerable:true});};var g=C(()=>{});var L,Sn=C(()=>{g();L=class extends Error{constructor(t,i=t,r){super(i);this.code=t;this.currentRevision=r;}code;currentRevision;name="UiRuntimeError"};});function lt(e){return Xr.test(e)||Kr.test(e)}function pe(){throw new L("INPUT_INVALID","JSON value is not projection-safe")}function Qr(e){let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function dt(e,n,t,i,r,o){if(n>i&&pe(),e===null||typeof e=="string"||typeof e=="boolean")return typeof e=="string"&&(Yr.test(e)||Zr.test(e)&&!ts(r,o)||qr.test(e))&&pe(),e;if(typeof e=="number")return Number.isFinite(e)||pe(),e;(typeof e!="object"||e===void 0||typeof e=="function"||typeof e=="bigint")&&pe();let a=e;t.has(a)&&pe(),t.add(a);try{if(Array.isArray(e))return e.map(c=>dt(c,n+1,t,i,r,o));Qr(a)||pe();let s={};for(let[c,d]of Object.entries(e))lt(c)&&pe(),s[c]=dt(d,n+1,t,i,[...r,c],o);return s}finally{t.delete(a);}}function le(e,n=0,t=[]){(!Number.isInteger(n)||n<0||n>ns)&&pe(),(!Array.isArray(t)||t.some(r=>typeof r!="string"))&&pe();let i=dt(e,0,new Set,es+n,[],t);return (i===null||Array.isArray(i)||typeof i!="object")&&pe(),i}function ze(e,n){if(!e||!n)return false;let t=e.split("."),i=n.split(".");return t.length>=i.length&&i.every((r,o)=>t[o]===r)}function ts(e,n){if(e.length===0)return false;let t=e.join(".");return n.some(i=>ze(t,i))}function Ge(e){try{let n=JSON.stringify(e);return n===void 0&&pe(),n}catch{pe();}}function pt(e){return Array.isArray(e)?e.map(pt):e!==null&&typeof e=="object"?Object.fromEntries(Object.keys(e).sort().map(n=>[n,pt(e[n])])):e}function Q(e){return Ge(pt(e))}function ut(e){return Buffer.byteLength(e,"utf8")}var Xr,Kr,Yr,qr,Zr,es,ns,Pe=C(()=>{g();Sn();Xr=/(?:proof|token|secret|password|cookie|authorization|private[_-]?key|stack|exception|plugin[_-]?text)/i,Kr=/(?:url|uri|endpoint|path|file(?:name|path)?|cwd|shell|directory|dir|folder)$/i,Yr=/<\/?[A-Za-z][^>]*>/,qr=/^(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)/,Zr=/^(?:https?|file|ftp|ws|wss):\/\//i;es=8,ns=4;});var Mn,ft=C(()=>{g();Mn=["text/plain","application/json"];});var Ni=C(()=>{g();ft();});function Je(e){return os.has(e)||rs.test(e)||ss.test(e)}var Di,os,rs,ss,On,on,_e,yt,At,It,gt,mt,we=C(()=>{g();Di=["__proto__","prototype","constructor","proof","token","secret","password","cookie","authorization","private_key","private-key","stack","exception","plugin_text","url","uri","endpoint","path","filename","filepath","cwd","shell","directory","dir","folder"],os=new Set(Di),rs=/(?:proof|token|secret|password|cookie|authorization|private[_-]?key|stack|exception|plugin[_-]?text)/i,ss=/(?:url|uri|endpoint|path|file(?:name|path)?|cwd|shell|directory|dir|folder)$/i;On=/^[A-Za-z0-9_]+$/,on=/^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)*$/,_e=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,yt=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/,At=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,It=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/,gt=["blue","violet","emerald","amber","rose","sky","slate","indigo"],mt=["inline","panel"];});function ht(e){return typeof e=="string"&&Mn.includes(e)}var bi=C(()=>{g();ft();we();});function Ln(e){if(!_t(e))return false;let n=Object.keys(e);return !(n.some(t=>t!=="in"&&t!=="out")||n.length===0||Object.hasOwn(e,"in")&&!as(e.in)||Object.hasOwn(e,"out")&&!cs(e.out))}function as(e){return _t(e)?Object.keys(e).every(t=>t==="mediaType"||t==="required")&&Object.hasOwn(e,"mediaType")&&ht(e.mediaType)&&(!Object.hasOwn(e,"required")||typeof e.required=="boolean"):false}function cs(e){return _t(e)?Object.keys(e).every(t=>t==="mediaType"||t==="range")&&Object.hasOwn(e,"mediaType")&&ht(e.mediaType)&&(!Object.hasOwn(e,"range")||typeof e.range=="boolean"):false}function _t(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}var Et=C(()=>{g();Ni();bi();new TextDecoder("utf-8",{fatal:true,ignoreBOM:true});});function Un(e){return ds.includes(e)}function Cn(e){return Number.isSafeInteger(e)&&e>=Rn.min&&e<=Rn.max}var ds,Rn,Pi,Tt=C(()=>{g();ds=[5,15,30,60],Rn=Object.freeze({min:15e3,max:6e5,default:3e5}),Pi=1;});function kn(e){return Number.isSafeInteger(e)&&e>=wn.min&&e<=wn.max}function xn(e){return ps.includes(e)}var wn,Si,ps,Nt=C(()=>{g();wn=Object.freeze({min:6e4,max:18e5,default:6e5}),Si=1,ps=["start","status","cancel"];});function se(e){let t=e.renderer!==void 0||e.surfaces!==void 0||e.stateProjection!==void 0||e.dataPaths!==void 0||e.usage!==void 0||e.detailPanel!==void 0||e.displayModes!==void 0||e.summaryProjection!==void 0||e.downloads!==void 0||e.legacy!==void 0||Object.values(e.actions).some(r=>r.resultProjection!==void 0)?{id:e.id,version:e.version,...e.renderer===void 0?{}:{renderer:e.renderer},...e.surfaces===void 0?{}:{surfaces:e.surfaces},...e.stateProjection===void 0?{}:{stateProjection:e.stateProjection},...e.dataPaths===void 0?{}:{dataPaths:e.dataPaths},...e.summaryProjection===void 0?{}:{summaryProjection:e.summaryProjection},...e.legacy===void 0?{}:{legacy:e.legacy},...e.usage===void 0?{}:{usage:e.usage},...e.detailPanel===void 0?{}:{detailPanel:e.detailPanel},...e.displayModes===void 0?{}:{displayModes:e.displayModes},...e.downloads===void 0?{}:{downloads:e.downloads},...e.sourceHash===void 0?{}:{sourceHash:e.sourceHash},actions:e.actions}:e.sourceHash===void 0?{id:e.id,version:e.version,actions:e.actions}:{id:e.id,version:e.version,sourceHash:e.sourceHash,actions:e.actions},i=le(t);return createHash("sha256").update(Q(i)).digest("hex")}function bt(e){return `${e.id}\0${e.version}`}function ue(e){if(!/^\d+$/.test(String(e.version))||e.version<1||e.id.length<1||e.id.length>128)throw new L("DEFINITION_UNSUPPORTED","UI definition is invalid");if(e.sourceHash!==void 0&&(typeof e.sourceHash!="string"||!us.test(e.sourceHash)))throw new L("DEFINITION_UNSUPPORTED","UI definition source hash is invalid");if(!/^[0-9a-f]{64}$/.test(e.hash)||se(e)!==e.hash)throw new L("DEFINITION_UNSUPPORTED","UI definition hash is invalid");for(let[n,t]of Object.entries(e.actions)){if(!n||!Array.isArray(t.capabilities)||t.capabilities.some(i=>!ys(i)))throw new L("DEFINITION_UNSUPPORTED","UI action declaration is invalid");if(t.confirmation!==void 0&&t.confirmation!=="none"&&t.confirmation!=="native")throw new L("DEFINITION_UNSUPPORTED","UI action confirmation is invalid");if(t.inputKeys&&(!Array.isArray(t.inputKeys)||t.inputKeys.some(i=>typeof i!="string"||!i)))throw new L("DEFINITION_UNSUPPORTED","UI action input declaration is invalid");if(t.dataInputs!==void 0&&(!Array.isArray(t.dataInputs)||new Set(t.dataInputs).size!==t.dataInputs.length||t.dataInputs.some(i=>typeof i!="string"||!i||t.inputKeys!==void 0&&!t.inputKeys.includes(i))))throw new L("DEFINITION_UNSUPPORTED","UI action data input declaration is invalid");if(t.resultProjection&&Dt(t.resultProjection),t.schedule!==void 0&&(!Un(t.schedule.everyMinutes)||!Cn(t.schedule.timeoutMs)))throw new L("DEFINITION_UNSUPPORTED","UI action schedule declaration is invalid");if(t.job!==void 0&&(typeof t.job!="object"||Object.keys(t.job).some(i=>i!=="deadlineMs")||!kn(t.job.deadlineMs)))throw new L("DEFINITION_UNSUPPORTED","UI action job declaration is invalid");if(t.jobAccess!==void 0&&(!Array.isArray(t.jobAccess)||t.jobAccess.length===0||new Set(t.jobAccess).size!==t.jobAccess.length||!t.jobAccess.every(xn)||t.job!==void 0))throw new L("DEFINITION_UNSUPPORTED","UI action job control declaration is invalid");if(t.content!==void 0&&!Ln(t.content))throw new L("DEFINITION_UNSUPPORTED","UI action content declaration is invalid");if(t.env!==void 0&&(!Array.isArray(t.env)||t.env.length===0||new Set(t.env).size!==t.env.length||t.env.some(i=>i!=="CREWX_APP_INSTANCE_ID"&&i!=="CREWX_THREAD_ID")))throw new L("DEFINITION_UNSUPPORTED","UI action environment declaration is invalid")}if(e.renderer!==void 0&&(!e.renderer||e.renderer.length>128))throw new L("DEFINITION_UNSUPPORTED","UI definition renderer is invalid");if(e.surfaces&&(!Array.isArray(e.surfaces)||e.surfaces.some(n=>!n||n.length>64)))throw new L("DEFINITION_UNSUPPORTED","UI definition surfaces are invalid");if(e.usage!==void 0&&e.usage!=="card"&&e.usage!=="window")throw new L("DEFINITION_UNSUPPORTED","UI definition usage is invalid");if(e.detailPanel!==void 0&&typeof e.detailPanel!="boolean")throw new L("DEFINITION_UNSUPPORTED","UI definition detailPanel is invalid");if(e.displayModes&&(!Array.isArray(e.displayModes)||e.displayModes.length===0||new Set(e.displayModes).size!==e.displayModes.length||e.displayModes.some(n=>n!=="inline"&&n!=="floating"&&n!=="focused")))throw new L("DEFINITION_UNSUPPORTED","UI definition displayModes are invalid");if(e.usage==="card"&&e.displayModes!==void 0)throw new L("DEFINITION_UNSUPPORTED","Card definitions cannot declare displayModes");if(e.usage==="window"&&e.detailPanel!==void 0)throw new L("DEFINITION_UNSUPPORTED","Window definitions cannot declare detailPanel");if(e.stateProjection&&Dt(e.stateProjection),e.summaryProjection){Dt(e.summaryProjection);let n=new Set(e.stateProjection?.allow??[]);if(e.summaryProjection.allow.some(t=>!n.has(t)))throw new L("DEFINITION_UNSUPPORTED","UI summary projection exceeds state projection")}if(e.legacy!==void 0){if(!e.legacy||typeof e.legacy!="object"||Array.isArray(e.legacy)||Object.keys(e.legacy).some(r=>!["readTool","actionTool","hostTools","agentAccess"].includes(r)))throw new L("DEFINITION_UNSUPPORTED","UI legacy metadata is invalid");let n=new Set;for(let[r,o]of [["readTool",e.legacy.readTool],["actionTool",e.legacy.actionTool]])if(o!==void 0){if(fs(o,r==="readTool"),n.has(o.name))throw new L("DEFINITION_UNSUPPORTED","UI legacy tool names collide");n.add(o.name);}let t=e.legacy.hostTools;if(t!==void 0){if(!t||typeof t!="object"||Array.isArray(t))throw new L("DEFINITION_UNSUPPORTED","UI legacy host tools are invalid");let r={"doc.open":"crewx_app_html_viewer_open","pty.connect":"crewx_app_terminal_connect"};for(let[o,a]of Object.entries(t)){if(!Object.hasOwn(r,o)||r[o]!==a||typeof a!="string"||!/^[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(a)||n.has(a))throw new L("DEFINITION_UNSUPPORTED","UI legacy host tools are invalid");n.add(a);}}let i=e.legacy.agentAccess;if(i!==void 0&&(!i||typeof i!="object"||Array.isArray(i)||Object.entries(i).some(([r,o])=>!r||!Object.hasOwn(e.actions,r)||o!=="allowed"&&o!=="denied")))throw new L("DEFINITION_UNSUPPORTED","UI legacy agent access is invalid");if(e.legacy.actionTool!==void 0&&(!i||Object.keys(i).length===0))throw new L("DEFINITION_UNSUPPORTED","UI legacy action tool requires its complete agent access map")}if(e.downloads!==void 0&&e.downloads!==true)throw new L("DEFINITION_UNSUPPORTED","UI definition downloads is invalid");if(e.dataPaths!==void 0){let n=new Set(["__proto__","prototype","constructor"]);if(!Array.isArray(e.dataPaths)||e.dataPaths.length>16||new Set(e.dataPaths).size!==e.dataPaths.length||e.dataPaths.some(t=>typeof t!="string"||!/^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)*$/.test(t)||t.split(".").some(i=>n.has(i))||!(e.stateProjection?.allow??[]).some(i=>ze(t,i))))throw new L("DEFINITION_UNSUPPORTED","UI definition dataPaths are invalid")}}function fs(e,n){if(!e||typeof e!="object"||Array.isArray(e))throw new L("DEFINITION_UNSUPPORTED","UI legacy tool metadata is invalid");let t=e,i=["name","description","inputSchema","textFallback","visibility"],r=Object.hasOwn(t,"fixedResult");if(Object.keys(t).some(o=>!i.includes(o)&&!(n&&o==="fixedResult"))||i.some(o=>!Object.hasOwn(t,o))||typeof t.name!="string"||!/^[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(t.name)||typeof t.description!="string"||t.description.trim().length===0||t.description.length>8192||typeof t.textFallback!="string"||t.textFallback.trim().length===0||t.textFallback.length>16384||!t.inputSchema||typeof t.inputSchema!="object"||Array.isArray(t.inputSchema)||!Array.isArray(t.visibility)||t.visibility.length===0||t.visibility.some(o=>o!=="model"&&o!=="app")||new Set(t.visibility).size!==t.visibility.length)throw new L("DEFINITION_UNSUPPORTED","UI legacy tool metadata is invalid");try{let o=le(t.inputSchema);if(o.type!==void 0&&o.type!=="object")throw new Error("schema type");if(r){if(!n)throw new Error("fixed result location");let a=t.fixedResult;if(!a||typeof a!="object"||Array.isArray(a))throw new Error("fixed result");let s=a;if(Object.keys(s).sort().join(",")!=="argsPolicy,structuredContent"||s.argsPolicy!=="empty-only"&&s.argsPolicy!=="ignore"||!s.structuredContent||typeof s.structuredContent!="object"||Array.isArray(s.structuredContent))throw new Error("fixed result");let c=le(s.structuredContent);if(ut(Ge(c))>4*1024)throw new Error("fixed result size")}}catch{throw new L("DEFINITION_UNSUPPORTED","UI legacy tool metadata is not projection-safe")}}function Dt(e){if(!Array.isArray(e.allow)||e.allow.some(n=>!/^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)*$/.test(n)))throw new L("DEFINITION_UNSUPPORTED","UI projection policy is invalid")}function ys(e){return e.length>0&&e.length<=128&&e!=="*"&&e!=="all"&&!/[/*]/.test(e)}var us,ke=C(()=>{g();Pe();Sn();Et();Tt();Nt();us=/^[0-9a-f]{64}$/;});var Mi=C(()=>{g();Pe();});var q,Se,Pt=C(()=>{g();q="dist/tools.json",Se="dist/main.mjs";});var rn,Oi=C(()=>{g();rn="window";});function Li(e){if(!Array.isArray(e)||e.length===0)return false;let n=new Set;for(let t of e){if(!As.some(i=>i===t)||n.has(t))return false;n.add(t);}return true}var As,Ri=C(()=>{g();As=["CREWX_APP_INSTANCE_ID","CREWX_THREAD_ID"];});function G(e){throw new St(e)}function Ss(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;try{let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}catch{return false}}function Ms(e,n){let t=Object.getOwnPropertyDescriptor(e,n);return (!t||!("value"in t))&&G("CSP_ORIGIN_INVALID"),t.value}function jn(e,n){if(!Object.prototype.hasOwnProperty.call(e,n))return [];let t=Ms(e,n);Array.isArray(t)||G("CSP_ORIGIN_INVALID"),Reflect.ownKeys(t).some(o=>typeof o!="string"||o!=="length"&&!/^(?:0|[1-9][0-9]*)$/.test(o))&&G("CSP_ORIGIN_INVALID");let r=[];for(let o=0;o<t.length;o+=1)(!Object.prototype.hasOwnProperty.call(t,o)||typeof t[o]!="string")&&G("CSP_ORIGIN_INVALID"),r.push(t[o]);return Object.keys(t).length!==t.length&&G("CSP_ORIGIN_INVALID"),r}function Os(e){let n;try{n=JSON.stringify(e);}catch{G("CSP_ORIGIN_INVALID");}return n===void 0&&G("CSP_ORIGIN_INVALID"),new TextEncoder().encode(n).byteLength}function wi(e,n){/\s|\\/u.test(e)&&G("CSP_ORIGIN_INVALID");let t=Ts.exec(e);t||G("CSP_ORIGIN_INVALID");let i=t[1].toLowerCase(),r=t[2];(r.includes("@")||r.includes("%")||r.includes("*"))&&G("CSP_ORIGIN_INVALID"),(r.startsWith("[")?Ns:Ds).test(r)||G("CSP_ORIGIN_INVALID"),i==="wss"&&n!=="connectDomains"&&G("CSP_ORIGIN_INVALID");let a;try{a=new URL(e);}catch{G("CSP_ORIGIN_INVALID");}(a.protocol!==`${i}:`||a.username!==""||a.password!==""||a.search!==""||a.hash!=="")&&G("CSP_ORIGIN_INVALID");let s=a.hostname.toLowerCase();if((!s||s.includes("%"))&&G("CSP_ORIGIN_INVALID"),!s.startsWith("[")){let d=s.endsWith(".")?s.slice(0,-1):s;(d.length===0||d.length>253)&&G("CSP_ORIGIN_INVALID"),d.split(".").some(u=>u.length>63||!bs.test(u))&&G("CSP_ORIGIN_INVALID");}let c=a.origin;return (c==="null"||!c.startsWith(`${i}://`))&&G("CSP_ORIGIN_INVALID"),{origin:c,hostname:s}}function Ls(e){let n=e.split(".").map(Number);return ((n[0]*256+n[1])*256+n[2])*256+n[3]}function ki(e,n,t){let i=4294967295<<32-t>>>0;return (e&i)===(n&i)}function vi(e){let n=Ls(e);return ki(n,3221225472,24)?n!==3221225481&&n!==3221225482:Ps.some(([t,i])=>ki(n,t,i))}function Rs(e){let n=e.indexOf("::"),t=(n<0?e:e.slice(0,n)).split(":").filter(Boolean),i=n<0?[]:e.slice(n+2).split(":").filter(Boolean);return (n<0?t:[...t,...Array(8-t.length-i.length).fill("0"),...i]).reduce((o,a)=>o<<16n|BigInt(Number.parseInt(a,16)),0n)}function Us(e){let n=Rs(e),t=Number(n>>112n),i=Number(n>>96n&0xffffn);if(n>>32n===0xffffn){let r=Number(n&0xffffffffn);return vi([r>>>24&255,r>>>16&255,r>>>8&255,r&255].join("."))}return t<8192||t>16383||t===8193&&i<=511||t===8193&&i===3512||t===8194||t===16383&&i<=4095}function Cs(e,n){let t=e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e,i=isIP(t);if(i===4)return vi(t);if(i===6)return Us(t);let r=e.toLowerCase().replace(/\.$/,"");return !r||!r.includes(".")||n.has(r)?true:Es.some(o=>r===o||r.endsWith(`.${o}`))}function xi(e){return Object.freeze([...new Set(e.map(n=>n.origin))].sort())}function ji(e){return JSON.stringify({baseUriDomains:[],connectDomains:e.connectDomains,declared:e.declared,frameDomains:e.frameDomains,resourceDomains:[]})}function Vi(e,n={}){if(e===void 0){let A=ji({declared:false,connectDomains:[],frameDomains:[]});return Object.freeze({declared:false,connectDomains:Object.freeze([]),frameDomains:Object.freeze([]),resourceDomains:Object.freeze([]),baseUriDomains:Object.freeze([]),cspHash:createHash("sha256").update(A,"utf8").digest("hex")})}Ss(e)||G("CSP_ORIGIN_INVALID");let t=Reflect.ownKeys(e);t.some(A=>typeof A!="string")&&G("CSP_ORIGIN_INVALID"),t.some(A=>!_s.has(A))&&G("CSP_AXIS_UNKNOWN");let i=jn(e,"connectDomains"),r=jn(e,"frameDomains"),o=jn(e,"resourceDomains"),a=jn(e,"baseUriDomains");(o.length>0||a.length>0)&&G("CSP_AXIS_UNSUPPORTED"),(Os(e)>gs||i.length>Ci||r.length>Ci||i.length+r.length>ms||[...i,...r].some(A=>new TextEncoder().encode(A).byteLength>hs))&&G("CSP_LIMIT_EXCEEDED");let c=i.map(A=>wi(A,"connectDomains")),d=r.map(A=>wi(A,"frameDomains")),l=new Set((n.runtimeHostnames??[]).map(A=>A.toLowerCase().replace(/\.$/,"")));[...c,...d].some(A=>Cs(A.hostname,l))&&G("CSP_ORIGIN_FORBIDDEN");let u={declared:true,connectDomains:xi(c),frameDomains:xi(d)},f=ji(u);return Object.freeze({...u,resourceDomains:Object.freeze([]),baseUriDomains:Object.freeze([]),cspHash:createHash("sha256").update(f,"utf8").digest("hex")})}var gs,Ci,ms,hs,_s,Es,Ts,Ns,Ds,bs,Ps,St,Fi=C(()=>{g();gs=4096,Ci=16,ms=32,hs=512,_s=new Set(["connectDomains","frameDomains","resourceDomains","baseUriDomains"]),Es=["localhost","local","internal","home.arpa","test","example","invalid","onion","lan","corp","home","intranet","private","localdomain"],Ts=/^(https|wss):\/\/([^/?#]+)$/i,Ns=/^\[[^\]]+\](?::[0-9]+)?$/,Ds=/^[^:\[\]]+(?::[0-9]+)?$/,bs=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/,Ps=[[0,8],[1681915904,10],[167772160,8],[2130706432,8],[2851995648,16],[2886729728,12],[3221225984,24],[3227017984,24],[3232235520,16],[3323068416,15],[3325256704,24],[3405803776,24],[3758096384,4],[4026531840,4]],St=class extends Error{constructor(t){super(t);this.code=t;}code;name="UiPluginCspNormalizationError"};});function an(e,n){return n===void 0||n===""?e:e===""?n:n.startsWith("[")?`${e}${n}`:`${e}.${n}`}function p(e,n=e,t,i){throw new ae(e,n,t,i)}function F(e,n){try{return n()}catch(t){throw t instanceof ae?t.withPathPrefix(e):t}}function z(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;try{let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}catch{return false}}function P(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function fa(e,n){let t={};for(let[i,r]of Object.entries(e))n.includes(i)||(t[i]=r);return t}function $(e,n,t=[]){let i=new Set([...n,...t]),r=Object.keys(e).find(a=>!i.has(a));r!==void 0&&p("MANIFEST_INVALID","MANIFEST_INVALID",r,"unknown-key");let o=n.find(a=>!P(e,a));o!==void 0&&p("MANIFEST_INVALID","MANIFEST_INVALID",o,"missing-key");}function Bn(e,n=false,t=false,i=false){return js.test(e)||!i&&Vs.test(e)||vs.test(e)||t&&Bi.test(e)||Fs.test(e)&&!(n&&/^\s*data:/i.test(e)&&!Bi.test(e))}function Fn(e,n=new Set,t=0,i=false,r=false,o=""){if(typeof e=="string"){Bn(e,i,r)&&p("UNSAFE_VALUE","UNSAFE_VALUE",o,"unsafe-value");return}if(!(e===null||typeof e!="object")){(t>8||n.has(e))&&p("MANIFEST_INVALID","MANIFEST_INVALID",o),n.add(e);try{if(Array.isArray(e)){e.forEach((a,s)=>Fn(a,n,t+1,!1,!1,an(o,`[${s}]`)));return}z(e)||p("MANIFEST_INVALID","MANIFEST_INVALID",o);for(let[a,s]of Object.entries(e))Fn(s,n,t+1,i&&t===0&&(a==="name"||a==="description"),r,an(o,a));}finally{n.delete(e);}}}function Ee(e,n){let t=e[n];return typeof t!="string"&&p("MANIFEST_INVALID"),t}function Ae(e,n,t){let i=e[n];return (!Number.isSafeInteger(i)||i<t)&&p("MANIFEST_INVALID"),i}function Mt(e){return xs.test(e)||p("MANIFEST_INVALID"),e}function $e(e){return ks.test(e)||p("TOKEN_INVALID"),e}function ya(e){return no.test(e)||p("MANIFEST_INVALID"),e}function Aa(e){z(e)||p("MANIFEST_INVALID");let n={};for(let[t,i]of Object.entries(e)){let r=ya(t);z(i)||p("MANIFEST_INVALID");let o=i.type;if(o==="text"){$(i,["type","maxLength"]),n[r]={type:o,maxLength:Ae(i,"maxLength",1)};continue}if(o==="text-list"){$(i,["type","max","itemMaxLength"]),n[r]={type:o,max:Ae(i,"max",0),itemMaxLength:Ae(i,"itemMaxLength",1)};continue}if(o==="step-list"){$(i,["type","min","max","labelMaxLength","detailMaxLength"]);let a=Ae(i,"min",0),s=Ae(i,"max",1);a>s&&p("MANIFEST_INVALID"),n[r]={type:o,min:a,max:s,labelMaxLength:Ae(i,"labelMaxLength",1),detailMaxLength:Ae(i,"detailMaxLength",1)};continue}typeof o=="string"&&p("SCHEMA_TYPE_UNSUPPORTED"),p("MANIFEST_INVALID");}return n}function Ia(e,n,t){let i=e[n];(!i||i.type!==t)&&p("MANIFEST_INVALID");}function vn(e,n,t){let i=Ee(e,"field");return no.test(i)||p("MANIFEST_INVALID"),Ia(n,i,t),i}function ga(e,n){z(e)||p("MANIFEST_INVALID");let t=e.primitive;switch(typeof t!="string"&&p("MANIFEST_INVALID"),ua.includes(t)||p("PRIMITIVE_UNKNOWN"),t){case "card-shell":return $(e,["primitive"]),{primitive:t};case "meta-banner":return $(e,["primitive","badgeToken","noticeToken"]),{primitive:t,badgeToken:$e(Ee(e,"badgeToken")),noticeToken:$e(Ee(e,"noticeToken"))};case "heading":return $(e,["primitive","field"]),{primitive:t,field:vn(e,n,"text")};case "labeled-text":return $(e,["primitive","titleToken","field","variant"]),e.variant!=="callout"&&p("MANIFEST_INVALID"),{primitive:t,titleToken:$e(Ee(e,"titleToken")),field:vn(e,n,"text"),variant:"callout"};case "step-flow":return $(e,["primitive","titleToken","field"]),{primitive:t,titleToken:$e(Ee(e,"titleToken")),field:vn(e,n,"step-list")};case "text-list":{$(e,["primitive","titleToken","field"],["emptyToken","hideWhenEmpty"]);let i={primitive:t,titleToken:$e(Ee(e,"titleToken")),field:vn(e,n,"text-list")};return P(e,"emptyToken")&&(i.emptyToken=$e(Ee(e,"emptyToken"))),P(e,"hideWhenEmpty")&&(typeof e.hideWhenEmpty!="boolean"&&p("MANIFEST_INVALID"),i.hideWhenEmpty=e.hideWhenEmpty),i}}return p("MANIFEST_INVALID")}function ma(e,n){return Array.isArray(e)||p("MANIFEST_INVALID"),e.map(t=>ga(t,n))}function X(e="v2 manifest exceeds a contract limit",n,t){return p("LIMIT_EXCEEDED",e,n,t)}function fe(e="initial state is not projection-safe"){return p("INITIAL_STATE_INVALID",e)}function Hi(e,n){return (typeof e!="string"||e.length===0||e.length>4096||e.trim().length===0||sa.test(e)||aa.test(e))&&p("MANIFEST_INVALID",`${n} is invalid`),(Bn(e,true,true)||Bs.test(e)||Hs.test(e)||zs.test(e))&&p("UNSAFE_VALUE",`${n} contains an unsafe value`),e}function Ot(e,n){return (typeof e!="string"||!_e.test(e))&&p("MANIFEST_INVALID",`${n} is invalid`),e}function ha(e){return (typeof e!="string"||!yt.test(e)||e==="*"||e==="all")&&p("MANIFEST_INVALID","action capability is invalid"),e}function to(e){return (typeof e!="string"||!ra.test(e))&&p("MANIFEST_INVALID","resource hash is invalid"),e}function Lt(e,n=new Set,t=0,i=""){if(typeof e=="string"){e.length>4096&&X("v2 manifest string is too long",i,"string-too-long");return}if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){Number.isFinite(e)||p("MANIFEST_INVALID","v2 manifest contains a non-finite number",i,"non-finite-number");return}(e===void 0||typeof e=="function"||typeof e=="bigint")&&p("MANIFEST_INVALID","v2 manifest contains a non-JSON value",i,"non-json-value"),typeof e!="object"&&p("MANIFEST_INVALID","MANIFEST_INVALID",i),t>8&&X("v2 manifest nesting is too deep",i,"too-deep"),n.has(e)&&p("MANIFEST_INVALID","v2 manifest contains a cycle",i,"cycle"),n.add(e);try{if(Array.isArray(e)){e.length>128&&X("v2 manifest array is too long",i,"array-too-long"),e.forEach((r,o)=>Lt(r,n,t+1,an(i,`[${o}]`)));return}z(e)||p("MANIFEST_INVALID","v2 manifest contains a non-plain object",i,"non-plain-object");for(let[r,o]of Object.entries(e))Lt(o,n,t+1,an(i,r));}finally{n.delete(e);}}}function io(e){return (typeof e!="string"||e.length>4096||!on.test(e))&&(typeof e=="string"&&e.length>4096&&X("projection path is too long"),p("MANIFEST_INVALID","projection paths must be canonical exact paths")),e.split(".").some(t=>Je(t))&&p("MANIFEST_INVALID","projection paths cannot address reserved state keys"),e}function Rt(e){z(e)||p("MANIFEST_INVALID","projection policy must be an object"),$(e,["allow"]),Array.isArray(e.allow)||p("MANIFEST_INVALID","projection allow must be an array"),e.allow.length>128&&X("projection allowlist is too long");let n=[],t=new Set;for(let i of e.allow){let r=io(i);t.has(r)&&p("MANIFEST_INVALID","projection allowlist contains a duplicate path"),t.add(r),n.push(r);}return {allow:n}}function _a(e,n){if(e===void 0)return;Array.isArray(e)||p("MANIFEST_INVALID","dataPaths must be an array"),e.length>ca&&X("dataPaths exceed the v2 limit");let t=[],i=new Set;for(let r of e){let o=io(r);i.has(o)&&p("MANIFEST_INVALID","dataPaths contain a duplicate path"),n.some(a=>ze(o,a))||p("MANIFEST_INVALID","dataPaths must be projection-allowed"),i.add(o),t.push(o);}return t}function Ea(e){Array.isArray(e)||p("MANIFEST_INVALID","deviceFeatures must be an array",void 0,"array"),e.length>da&&p("MANIFEST_INVALID","deviceFeatures allow at most 16 names",void 0,"too-many-items");let n=[],t=new Set;for(let[i,r]of e.entries()){let o=`[${i}]`;typeof r!="string"&&p("MANIFEST_INVALID","a device feature name must be a string",o,"string"),r.length===0&&p("MANIFEST_INVALID","a device feature name must not be empty",o,"empty"),r.length>pa&&p("MANIFEST_INVALID","a device feature name is at most 32 characters",o,"too-long"),la.test(r)||p("MANIFEST_INVALID","a device feature name starts with a lowercase letter and holds only letters and digits",o,"format"),t.has(r)&&p("MANIFEST_INVALID","deviceFeatures contain a duplicate name",o,"duplicate-item"),t.add(r),n.push(r);}return n}function Ta(e){if(e!==false)return e!==true&&p("MANIFEST_INVALID","downloads must be true or false",void 0,"boolean"),true}function Na(e){return (!z(e)||e.view!==true||Object.keys(e).some(n=>n!=="view"&&n!=="entry"))&&p("MANIFEST_INVALID",'share must be { "view": true } or { "view": true, "entry": "<path>" }',void 0,"share-shape"),P(e,"entry")?{view:true,entry:ba(e.entry)}:{view:true}}function ba(e){typeof e!="string"&&p("MANIFEST_INVALID","share.entry must be a string","entry","entry-shape");let n=(i,r)=>p("MANIFEST_INVALID",`share.entry ${r}`,"entry",i);e.length===0&&n("empty","must not be empty"),e.length>zi&&n("too-long",`must be at most ${zi} characters`),e.startsWith("/")&&n("absolute","must be relative to the App folder");let t=e.split("/");t.length>Gi&&n("too-many-segments",`must have at most ${Gi} segments`);for(let i of t)i.length===0&&n("empty-segment","must not contain an empty segment"),(i==="."||i==="..")&&n("dot-segment",'must not contain "." or ".." segments'),Da.test(i)||n("segment-shape",'segments start with an ASCII letter or digit, then use only letters, digits, ".", "_" and "-"');return t[t.length-1].endsWith(".html")||n("extension","must name a file ending in .html"),e}function Pa(e){return (!z(e)||Object.keys(e).length!==1||typeof e.root!="string")&&p("MANIFEST_INVALID",'files must be exactly { "root": "<workspace folder>" }',void 0,"files-shape"),{root:Ra(e.root)}}function Ra(e){let n=e.normalize("NFC"),t=(o,a)=>p("MANIFEST_INVALID",`files.root ${a}`,"root",o);n.length===0&&t("empty","must not be empty"),La.test(n)&&t("forbidden-character","must not contain control characters, backslash or colon"),(n.startsWith("/")||n.startsWith("~"))&&t("absolute","must be relative to the workspace"),Array.from(n).length>Ji&&t("too-long",`must be at most ${Ji} characters`);let i=n.split("/"),r=i[0].toLowerCase().replace(/[. ]+$/,"");Oa.includes(r)&&t("reserved-folder","must not start in an App code folder or a tool folder"),i.length<Sa&&t("too-shallow","must name a folder inside a top-level folder, such as docs/trips"),i.length>$i&&t("too-many-segments",`must have at most ${$i} segments`);for(let o of i)o.length===0&&t("empty-segment","must not contain an empty segment"),(o==="."||o==="..")&&t("dot-segment",'must not contain "." or ".." segments'),Array.from(o).length>Wi&&t("segment-too-long",`segments must be at most ${Wi} characters`),Ma.test(o)||t("segment-shape",'segments must start with a letter or digit and contain only letters, digits, combining marks, "_" or "-"');return n}function We(e,n,t=Number.MAX_SAFE_INTEGER){return (!Number.isSafeInteger(e)||e<0||e>t)&&p("MANIFEST_INVALID",`${n} is invalid`),e}function Xi(e,n){return (typeof e!="number"||!Number.isFinite(e))&&p("MANIFEST_INVALID",`${n} is invalid`),e}function Ut(e,n=0,t=new Set){if(typeof e=="string")return (e.length>4096||Bn(e))&&p("UNSAFE_VALUE","schema enum contains an unsafe string"),e;if(e===null||typeof e=="boolean")return e;if(typeof e=="number")return Number.isFinite(e)||p("MANIFEST_INVALID","schema enum contains a non-finite number"),e;(n>8||typeof e!="object"||e===void 0)&&X("schema enum is too deep"),t.has(e)&&p("MANIFEST_INVALID","schema enum contains a cycle"),t.add(e);try{if(Array.isArray(e))return e.length>128&&X("schema enum array is too long"),e.map(r=>Ut(r,n+1,t));z(e)||p("MANIFEST_INVALID","schema enum contains a non-plain object");let i={};for(let[r,o]of Object.entries(e))Je(r)&&p("MANIFEST_INVALID","schema enum contains a reserved key"),i[r]=Ut(o,n+1,t);return i}finally{t.delete(e);}}function Ua(e,n){if(e===void 0)return;Array.isArray(e)||p("MANIFEST_INVALID","schema required must be an array"),e.length>64&&X("schema required list is too long");let t=[],i=new Set;for(let r of e)(typeof r!="string"||!on.test(r))&&p("MANIFEST_INVALID","schema required contains an invalid key"),r.length>4096&&X("schema required key is too long"),i.has(r)&&p("MANIFEST_INVALID","schema required contains a duplicate key"),n&&!Object.prototype.hasOwnProperty.call(n,r)&&p("MANIFEST_INVALID","schema required references an undeclared property"),i.add(r),t.push(r);return t}function Ca(e,n){let t=n?on:On;return e.length>4096&&X("schema property name is too long"),(!t.test(e)||e.split(".").some(i=>Je(i)))&&p("MANIFEST_INVALID","schema property name is invalid"),e}function Ct(e,n=0,t=false){z(e)||p("MANIFEST_INVALID","action inputSchema must be an object"),n>8&&X("action inputSchema is too deep");let i=e.type;i!=="object"&&i!=="string"&&i!=="number"&&i!=="integer"&&i!=="boolean"&&i!=="array"&&i!=="null"&&(typeof i=="string"&&p("SCHEMA_TYPE_UNSUPPORTED","action inputSchema type is unsupported"),p("MANIFEST_INVALID","action inputSchema type is required"));let r=["type","enum"];i==="string"&&r.push("minLength","maxLength"),i==="array"&&r.push("minItems","maxItems","items"),i==="object"&&r.push("minProperties","maxProperties","properties","required","additionalProperties"),(i==="number"||i==="integer")&&r.push("minimum","maximum"),$(e,["type"],r.filter(s=>s!=="type"));let o={type:i};if(P(e,"enum")&&(Array.isArray(e.enum)||p("MANIFEST_INVALID","schema enum must be an array"),e.enum.length>128&&X("schema enum is too long"),o.enum=e.enum.map(s=>Ut(s))),i==="string"&&(P(e,"minLength")&&(o.minLength=We(e.minLength,"schema minLength",4096)),P(e,"maxLength")&&(o.maxLength=We(e.maxLength,"schema maxLength",4096)),o.minLength!==void 0&&o.maxLength!==void 0&&o.minLength>o.maxLength&&p("MANIFEST_INVALID","schema string length bounds are inverted")),(i==="number"||i==="integer")&&(P(e,"minimum")&&(o.minimum=Xi(e.minimum,"schema minimum")),P(e,"maximum")&&(o.maximum=Xi(e.maximum,"schema maximum")),o.minimum!==void 0&&o.maximum!==void 0&&o.minimum>o.maximum&&p("MANIFEST_INVALID","schema numeric bounds are inverted")),i==="array"&&(P(e,"minItems")&&(o.minItems=We(e.minItems,"schema minItems",128)),P(e,"maxItems")&&(o.maxItems=We(e.maxItems,"schema maxItems",128)),o.minItems!==void 0&&o.maxItems!==void 0&&o.minItems>o.maxItems&&p("MANIFEST_INVALID","schema array length bounds are inverted"),P(e,"items")&&(o.items=Ct(e.items,n+1,false))),i==="object"){let s;if(P(e,"properties")){z(e.properties)||p("MANIFEST_INVALID","schema properties must be an object");let d=Object.entries(e.properties);d.length>64&&X("schema properties are too many"),s={};for(let[l,u]of d){let f=Ca(l,t);s[f]=Ct(u,n+1,false);}o.properties=s;}P(e,"minProperties")&&(o.minProperties=We(e.minProperties,"schema minProperties",64)),P(e,"maxProperties")&&(o.maxProperties=We(e.maxProperties,"schema maxProperties",64)),o.minProperties!==void 0&&o.maxProperties!==void 0&&o.minProperties>o.maxProperties&&p("MANIFEST_INVALID","schema object property bounds are inverted");let c=Ua(e.required,s);c!==void 0&&(o.required=c),P(e,"additionalProperties")&&(e.additionalProperties!==false&&p("MANIFEST_INVALID","schema additionalProperties must be false"),o.additionalProperties=false);}let a=JSON.stringify(o);return (a===void 0||Buffer.byteLength(a,"utf8")>2097152)&&X("action inputSchema subtree is too large"),o}function wa(e){let n=Ct(e,0,true);return (n.type!=="object"||!n.properties)&&p("MANIFEST_INVALID","action inputSchema must declare object properties"),n}function ka(e){if(z(e)||p("MANIFEST_INVALID","action backend must be an object"),e.type==="core"){$(e,Qs);let n=e.handler;return (typeof n!="string"||!At.test(n))&&p("MANIFEST_INVALID","core backend handler is invalid"),{type:"core",handler:n}}if(e.type==="skill"&&P(e,"entry"))return $(e,ta),e.entry!==Se&&p("MANIFEST_INVALID",`skill backend entry must be ${Se}`),{type:"skill",entry:Se};if(e.type==="skill"){$(e,ea,na),(!Array.isArray(e.command)||e.command.length===0||e.command.length>16)&&p("MANIFEST_INVALID","skill backend command is invalid");let n=[];for(let i of e.command)(typeof i!="string"||i.length===0||i.length>256||!It.test(i))&&p("MANIFEST_INVALID","skill backend command token is invalid"),n.push(i);let t=P(e,"env")?Fa(e.env):void 0;return {type:"skill",command:n,...t===void 0?{}:{env:t}}}p("MANIFEST_INVALID","action backend type is unsupported");}function xa(e){z(e)||p("MANIFEST_INVALID","action must be an object"),$(e,Ws,Xs),P(e,"_meta")&&F("_meta",()=>oo(e._meta));let n=F("actionId",()=>Ot(e.actionId,"actionId"));lt(n)&&p("MANIFEST_INVALID",`actionId "${n}" is not projection-safe`,"actionId");let t=F("capability",()=>ha(e.capability)),i=e.mutation;typeof i!="boolean"&&p("MANIFEST_INVALID","action mutation must be boolean","mutation");let r=F("inputSchema",()=>wa(e.inputSchema)),o;if(P(e,"dataInputs")){Array.isArray(e.dataInputs)||p("MANIFEST_INVALID","action dataInputs must be an array","dataInputs");let A=r.properties,I=new Set,h=[];for(let T of e.dataInputs)(typeof T!="string"||!P(A,T)||I.has(T))&&p("MANIFEST_INVALID","action dataInputs must be unique declared properties","dataInputs"),I.add(T),h.push(T);o=h;}let a=F("resultProjection",()=>Rt(e.resultProjection)),s=F("backend",()=>ka(e.backend)),c;P(e,"content")&&((s.type!=="skill"||!Ln(e.content))&&p("MANIFEST_INVALID","action content declaration is invalid","content"),c=Ba(e.content));let d;if(P(e,"confirmation")){let A=e.confirmation;A!=="none"&&A!=="native"&&p("MANIFEST_INVALID","action confirmation is invalid","confirmation"),d=A;}let l;P(e,"schedule")&&(l=F("schedule",()=>Va(e.schedule,{backend:s,inputSchema:r,hasContent:c!==void 0,hasDataInputs:o!==void 0,confirmation:d})));let u;P(e,"job")&&(l!==void 0&&p("MANIFEST_INVALID","an action is either the scheduled run or a job, not both","job"),u=F("job",()=>va(e.job,{backend:s,inputSchema:r,hasContent:c!==void 0,hasDataInputs:o!==void 0,confirmation:d})));let f;return P(e,"jobAccess")&&(u!==void 0&&p("MANIFEST_INVALID","an action is either the job or a job control, not both","jobAccess"),f=F("jobAccess",()=>ja(e.jobAccess,{backend:s,hasContent:c!==void 0}))),{actionId:n,capability:t,mutation:i,inputSchema:r,resultProjection:a,backend:s,...c===void 0?{}:{content:c},...o===void 0?{}:{dataInputs:o},...d===void 0?{}:{confirmation:d},...l===void 0?{}:{schedule:l},...u===void 0?{}:{job:u},...f===void 0?{}:{jobAccess:f}}}function ja(e,n){return (n.backend.type!=="skill"||!("entry"in n.backend)||n.backend.entry!==Se)&&p("MANIFEST_INVALID","jobAccess needs a tool-mode action","jobAccess"),n.hasContent&&p("MANIFEST_INVALID","a job control action takes no content","jobAccess"),(!Array.isArray(e)||e.length===0)&&p("MANIFEST_INVALID","jobAccess must list at least one operation","jobAccess"),(new Set(e).size!==e.length||!e.every(xn))&&p("MANIFEST_INVALID","jobAccess must name each operation once: start, status or cancel","jobAccess"),Object.freeze([...e])}function va(e,n){(n.backend.type!=="skill"||!("entry"in n.backend)||n.backend.entry!==Se)&&p("MANIFEST_INVALID","job needs a tool-mode action","job"),(n.hasContent||n.hasDataInputs||n.confirmation!==void 0&&n.confirmation!=="none")&&p("MANIFEST_INVALID","a job action takes no content, dataInputs or native confirmation","job"),(n.inputSchema.required??[]).length>0&&p("MANIFEST_INVALID","a job action input must accept {}","inputSchema.required"),z(e)||p("MANIFEST_INVALID","job must be an object","job"),$(e,[],qs);let t=P(e,"deadlineMs")?e.deadlineMs:wn.default;return kn(t)||p("MANIFEST_INVALID","job deadlineMs is invalid","job.deadlineMs"),{deadlineMs:t}}function Va(e,n){(n.backend.type!=="skill"||!("entry"in n.backend)||n.backend.entry!==Se)&&p("MANIFEST_INVALID","schedule needs a tool-mode action","schedule"),(n.hasContent||n.hasDataInputs||n.confirmation!==void 0&&n.confirmation!=="none")&&p("MANIFEST_INVALID","a scheduled action takes no content, dataInputs or native confirmation","schedule"),(n.inputSchema.required??[]).length>0&&p("MANIFEST_INVALID","a scheduled action input must accept {}","inputSchema.required"),z(e)||p("MANIFEST_INVALID","schedule must be an object","schedule"),$(e,Ks,Ys),Un(e.everyMinutes)||p("MANIFEST_INVALID","schedule everyMinutes is invalid","schedule.everyMinutes");let t=P(e,"timeoutMs")?e.timeoutMs:Rn.default;return Cn(t)||p("MANIFEST_INVALID","schedule timeoutMs is invalid","schedule.timeoutMs"),{everyMinutes:e.everyMinutes,timeoutMs:t}}function Fa(e){return Li(e)||p("MANIFEST_INVALID","skill backend env is invalid"),Object.freeze([...e])}function Ba(e){return Object.freeze({...e.in===void 0?{}:{in:Object.freeze({...e.in})},...e.out===void 0?{}:{out:Object.freeze({...e.out})}})}function Ha(e){return z(e)||p("INITIAL_STATE_INVALID","initialState must be an object"),$(e,ia,oa),e.path!=="ui/state.json"&&p("MANIFEST_INVALID","initialState path is not fixed"),P(e,"hash")?{path:"ui/state.json",hash:to(e.hash)}:{path:"ui/state.json"}}function za(e){let n=["wasm","terminal","htmlDocuments","appBrowser"];return (!z(e)||Object.keys(e).length===0||Object.keys(e).some(t=>!n.includes(t)||e[t]!==true))&&p("MANIFEST_INVALID","runtime must contain only known capability flags set to true"),{...e.wasm===true?{wasm:true}:{},...e.terminal===true?{terminal:true}:{},...e.htmlDocuments===true?{htmlDocuments:true}:{},...e.appBrowser===true?{appBrowser:true}:{}}}function Ga(e,n){let t;try{t=Vi(e);}catch(i){let r=i!==null&&typeof i=="object"&&"code"in i&&typeof i.code=="string"?i.code:"CSP_ORIGIN_INVALID";return p("MANIFEST_INVALID",r,void 0,r.toLowerCase().replace(/_/g,"-"))}if(t.frameDomains.length>0&&p("MANIFEST_INVALID","external origins in csp are not enabled in this rollout",void 0,"csp-not-enabled"),t.connectDomains.length!==0)return n?.terminal===true&&p("MANIFEST_INVALID","runtime.terminal cannot be combined with csp.connectDomains","connectDomains","terminal-with-connect-domains"),Object.freeze({connectDomains:t.connectDomains})}function Ja(e,n){Fn(z(e)?fa(e,["csp","downloads","files","share"]):e,new Set,0,true,true),Lt(e),z(e)||p("MANIFEST_INVALID"),$(e,Js,$s),P(e,"_meta")&&F("_meta",()=>oo(e._meta)),e.manifestVersion!==2&&p("MANIFEST_INVALID");let t;P(e,"runtime")&&(t=F("runtime",()=>za(e.runtime)));let i;P(e,"csp")&&(i=F("csp",()=>Ga(e.csp,t)));let r=F("pluginId",()=>Ot(e.pluginId,"pluginId")),o=F("definitionId",()=>Ot(e.definitionId,"definitionId")),a=F("version",()=>Ae(e,"version",1)),s=F("name",()=>Hi(e.name,"name")),c=F("description",()=>Hi(e.description,"description")),d;P(e,"icon")&&((typeof e.icon!="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(e.icon))&&p("MANIFEST_INVALID","icon is invalid","icon"),d=e.icon);let l;P(e,"tone")&&((typeof e.tone!="string"||!gt.includes(e.tone))&&p("MANIFEST_INVALID","tone is invalid","tone"),l=e.tone),e.entry!=="ui/index.html"&&p("MANIFEST_INVALID","entry path is not fixed","entry","fixed-value");let u;P(e,"entryHash")&&(u=F("entryHash",()=>to(e.entryHash)));let f;P(e,"initialState")&&(f=F("initialState",()=>Ha(e.initialState)));let A;P(e,"usage")&&(e.usage!=="card"&&e.usage!=="window"&&p("MANIFEST_INVALID","usage is invalid","usage"),A=e.usage);let I;P(e,"detailPanel")&&(typeof e.detailPanel!="boolean"&&p("MANIFEST_INVALID","detailPanel is invalid","detailPanel"),I=e.detailPanel);let h;if(P(e,"displayModes")){((A??rn)!==rn||!Array.isArray(e.displayModes)||e.displayModes.length===0)&&p("MANIFEST_INVALID","displayModes are only valid for window Apps","displayModes");let B=new Set(["inline","floating","focused"]);(new Set(e.displayModes).size!==e.displayModes.length||e.displayModes.some(H=>typeof H!="string"||!B.has(H)))&&p("MANIFEST_INVALID","displayModes are invalid","displayModes"),h=e.displayModes;}(A??rn)===rn&&I!==void 0&&p("MANIFEST_INVALID","detailPanel is card-only","detailPanel");let T=n.mode??"local";T!=="local"&&T!=="installed"&&T!=="published"&&p("MANIFEST_INVALID","manifest mode is invalid"),T!=="local"&&u===void 0&&p("MANIFEST_INVALID","installed manifests require entryHash","entryHash","required-when-installed"),T!=="local"&&f!==void 0&&f.hash===void 0&&p("MANIFEST_INVALID","installed manifests require initialState.hash","initialState.hash","required-when-installed"),(!Array.isArray(e.surfaces)||e.surfaces.length===0)&&p("MANIFEST_INVALID","surfaces are invalid","surfaces"),e.surfaces.length>2&&X("surfaces exceed the v2 limit","surfaces","too-many-items");let J=[],v=new Set;for(let B of e.surfaces)(typeof B!="string"||!mt.includes(B))&&p("MANIFEST_INVALID","surface is unsupported","surfaces"),v.has(B)&&p("MANIFEST_INVALID","surfaces contain a duplicate","surfaces","duplicate-item"),v.add(B),J.push(B);z(e.size)||p("MANIFEST_INVALID","size must be an object","size"),F("size",()=>$(e.size,["height"]));let b=F("size",()=>Ae(e.size,"height",1));b>720&&X("size.height exceeds the v2 limit","size.height","too-large");let U=F("stateProjection",()=>Rt(e.stateProjection)),W=e.summaryProjection===void 0?void 0:F("summaryProjection",()=>Rt(e.summaryProjection));W!==void 0&&W.allow.some(B=>!U.allow.includes(B))&&p("MANIFEST_INVALID","summaryProjection must be a subset of stateProjection.allow","summaryProjection");let N=F("dataPaths",()=>_a(e.dataPaths,U.allow)),M=P(e,"deviceFeatures")?F("deviceFeatures",()=>Ea(e.deviceFeatures)):void 0,S=P(e,"downloads")?F("downloads",()=>Ta(e.downloads)):void 0,y=P(e,"share")?F("share",()=>Na(e.share)):void 0,m=P(e,"files")?F("files",()=>Pa(e.files)):void 0;Array.isArray(e.actions)||p("MANIFEST_INVALID","actions must be an array","actions"),e.actions.length>32&&X("actions exceed the v2 limit","actions","too-many-items");let D=[],O=new Set,k=0,R=0;for(let[B,H]of e.actions.entries()){let ie=`actions[${B}]`,re=F(ie,()=>xa(H));if(O.has(re.actionId)&&p("MANIFEST_INVALID","actions contain a duplicate actionId",`${ie}.actionId`,"duplicate-item"),re.schedule!==void 0&&(k+=1,k>Pi&&p("MANIFEST_INVALID","an App declares at most one scheduled action",`${ie}.schedule`,"duplicate-item")),re.job!==void 0&&(R+=1,R>Si&&p("MANIFEST_INVALID","an App declares at most one job action",`${ie}.job`,"duplicate-item")),re.backend.type==="core"&&re.backend.handler==="state.set"){re.mutation||p("MANIFEST_INVALID","state.set actions must be mutations",`${ie}.mutation`);for(let Jr of Object.keys(re.inputSchema.properties))U.allow.includes(Jr)||p("MANIFEST_INVALID","state.set input paths must be projection-allowed",`${ie}.inputSchema.properties`);}O.add(re.actionId),D.push(re);}return {manifestVersion:2,pluginId:r,definitionId:o,version:a,name:s,description:c,...d===void 0?{}:{icon:d},...l===void 0?{}:{tone:l},entry:"ui/index.html",...u===void 0?{}:{entryHash:u},...t===void 0?{}:{runtime:t},...i===void 0?{}:{csp:i},...f===void 0?{}:{initialState:f},...A===void 0?{}:{usage:A},...I===void 0?{}:{detailPanel:I},...h===void 0?{}:{displayModes:h},surfaces:J,size:{height:b},stateProjection:U,...W===void 0?{}:{summaryProjection:W},...N===void 0?{}:{dataPaths:N},...M===void 0?{}:{deviceFeatures:M},...S===void 0?{}:{downloads:S},...y===void 0?{}:{share:y},...m===void 0?{}:{files:m},actions:D}}function oo(e){z(e)||p("MANIFEST_INVALID","_meta must be an object");let n=JSON.stringify(e);(n===void 0||Buffer.byteLength(n,"utf8")>Zs)&&X("_meta exceeds the 4 KiB limit",void 0,"meta-too-large");}function $a(e){let n={},t={};for(let o of e.actions){n[o.actionId]={capabilities:[o.capability],inputKeys:Object.keys(o.inputSchema.properties??{}),...o.dataInputs===void 0?{}:{dataInputs:o.dataInputs},resultProjection:o.resultProjection,...o.confirmation===void 0?{}:{confirmation:o.confirmation},...o.content===void 0?{}:{content:o.content},...o.schedule===void 0?{}:{schedule:o.schedule},...o.job===void 0?{}:{job:o.job},...o.jobAccess===void 0?{}:{jobAccess:o.jobAccess},...o.backend.type!=="skill"||o.backend.env===void 0?{}:{env:o.backend.env}};let a=o.backend.type==="skill"||o.backend.type==="core"&&o.backend.handler==="state.set";t[o.actionId]={actionId:o.actionId,mutation:o.mutation,backend:o.backend,launchPolicy:a?"allowed":"denied",...a?{}:{denialCode:"EXEC_DENIED"}};}let i={id:e.definitionId,version:e.version,renderer:"sandbox-html",...e.usage===void 0?{}:{usage:e.usage},...e.detailPanel===void 0?{}:{detailPanel:e.detailPanel},...e.displayModes===void 0?{}:{displayModes:e.displayModes},surfaces:e.surfaces,stateProjection:e.stateProjection,...e.summaryProjection===void 0?{}:{summaryProjection:e.summaryProjection},...e.dataPaths===void 0?{}:{dataPaths:e.dataPaths},...e.downloads===void 0?{}:{downloads:e.downloads},actions:n},r={entry:{path:"ui/index.html",...e.entryHash===void 0?{}:{hash:e.entryHash}},...e.initialState===void 0?{}:{initialState:e.initialState}};return {manifest:e,definition:i,handlers:t,resources:r}}function wt(e,n,t,i,r,o){if(typeof e=="string"){let a=r.length>0&&o.some(s=>ze(r.join("."),s));return (e.length>4096||Bn(e,false,false,a))&&fe("state contains an unsafe string"),e}if(e===null||typeof e=="boolean")return e;if(typeof e=="number")return Number.isFinite(e)||fe("state contains a non-finite number"),e;(e===void 0||typeof e!="object"||typeof e=="function"||typeof e=="bigint")&&fe("state contains a non-JSON value"),t>8&&fe("state is too deep"),n.has(e)&&fe("state contains a cycle"),n.add(e);try{let a;if(Array.isArray(e))e.length>128&&fe("state array is too long"),a=e.map(c=>wt(c,n,t+1,2097152,r,o));else {z(e)||fe("state contains a non-plain object");let c={};for(let[d,l]of Object.entries(e))(d.length>4096||!On.test(d)||Je(d))&&(d.length>4096&&fe("state key is too long"),fe("state contains a reserved or invalid key")),c[d]=wt(l,n,t+1,2097152,[...r,d],o);a=c;}let s=JSON.stringify(a);return (s===void 0||Buffer.byteLength(s,"utf8")>i)&&fe("state subtree is too large"),a}finally{n.delete(e);}}function xt(e,n=[]){z(e)||fe("initial state must be a JSON object");let t=wt(e,new Set,0,2097152,[],n);return (t===null||Array.isArray(t)||typeof t!="object")&&fe(),t}function Wa(e,n={}){Fn(e),z(e)||p("MANIFEST_INVALID"),$(e,Gs),e.manifestVersion!==1&&p("MANIFEST_INVALID");let t=Mt(Ee(e,"pluginId")),i=Mt(Ee(e,"definitionId")),r=Ae(e,"version",1),o=Ae(e,"primitiveSet",1),a=n.supportedPrimitiveSet??ws;(!Number.isSafeInteger(a)||a<1)&&p("MANIFEST_INVALID"),o>a&&p("PRIMITIVE_SET_UNSUPPORTED"),z(e.activation)||p("MANIFEST_INVALID"),$(e.activation,["kind","language"]),e.activation.kind!=="fenced-code"&&p("MANIFEST_INVALID");let s=Mt(Ee(e.activation,"language")),c=Aa(e.schema),d=ma(e.layout,c);return {manifestVersion:1,pluginId:t,definitionId:i,version:r,primitiveSet:o,activation:{kind:"fenced-code",language:s},schema:c,layout:d}}function Xa(e,n={}){return z(e)||p("MANIFEST_INVALID"),Object.hasOwn(e,"lineage")&&p("MANIFEST_INVALID","lineage is only allowed in product bundle indexes"),e.manifestVersion===2?Ja(e,n):Wa(e,n)}function cn(e,n={}){try{return Xa(e,n)}catch(t){if(t instanceof ae)throw t;return p("MANIFEST_INVALID")}}function dn(e,n={}){let t=cn(e,n);return t.manifestVersion===2?$a(t):t}var ws,ks,xs,no,js,vs,Vs,Fs,Bi,Bs,Hs,zs,Gs,Js,$s,Ws,Xs,Ks,Ys,qs,Zs,Qs,ea,na,ta,ia,oa,ra,sa,aa,ca,da,pa,la,ua,ae,zi,Gi,Da,Ji,Sa,$i,Wi,Ma,Oa,La,jt=C(()=>{g();Oi();Pe();Et();Ri();Pt();Tt();Nt();Fi();we();ws=1,ks=/^[a-z][a-zA-Z0-9]*(\.[a-zA-Z0-9]+)+$/,xs=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,no=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,js=/<\/?[A-Za-z][^>]*>/,vs=/^(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)/,Vs=/^(?:https?|file|ftp|ws|wss):\/\//i,Fs=/^\s*(?:javascript|data):/i,Bi=/data:[^,\s]*,/i,Bs=/(?:https?|file|ftp|ws|wss):\/\//i,Hs=/javascript:/i,zs=/(?:^[\s]*|[\s"'(=])(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)(?=[^\s"'<>])[^\s"'<>]*/,Gs=["manifestVersion","pluginId","definitionId","version","primitiveSet","activation","schema","layout"],Js=["manifestVersion","pluginId","definitionId","version","name","description","entry","surfaces","size","stateProjection","actions"],$s=["_meta","icon","tone","entryHash","runtime","csp","initialState","usage","detailPanel","displayModes","summaryProjection","dataPaths","focusedAiDataPaths","deviceFeatures","downloads","share","files"],Ws=["actionId","capability","mutation","inputSchema","resultProjection","backend"],Xs=["confirmation","dataInputs","content","schedule","job","jobAccess","_meta"],Ks=["everyMinutes"],Ys=["timeoutMs"],qs=["deadlineMs"],Zs=4*1024,Qs=["type","handler"],ea=["type","command"],na=["env"],ta=["type","entry"],ia=["path"],oa=["hash"],ra=/^[0-9a-f]{64}$/,sa=/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/,aa=/[\r\n]/,ca=16,da=16,pa=32,la=/^[a-z][A-Za-z0-9]{0,31}$/,ua=["card-shell","meta-banner","heading","labeled-text","step-flow","text-list"],ae=class e extends Error{constructor(t,i=t,r,o){super(i);this.code=t;this.path=r;this.rule=o;}code;path;rule;name="UiPluginValidationError";withPathPrefix(t){return new e(this.code,this.message,an(t,this.path),this.rule)}};zi=200,Gi=3,Da=/^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/;Ji=200,Sa=2,$i=4,Wi=100,Ma=/^[\p{L}\p{N}][\p{L}\p{N}\p{M}_-]*$/u,Oa=[".git",".crewx","node_modules","apps","skills"],La=/[\u0000-\u001f\u007f-\u009f\\:<>"|?*]/;});function lo(e){return typeof e=="string"&&e.length<=Ya&&Ka.test(e)}function w(e,n,t,i,r){throw new Ne(e,{path:n,rule:t,...i===void 0?{}:{message:i},...r===void 0?{}:{file:r}})}function ee(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;try{let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}catch{return false}}function K(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function ge(e){let n=`_meta["${Re}"]`;return e===void 0||e===""?n:e.startsWith("[")?`${n}${e}`:`${n}.${e}`}function ec(e){return e.toLowerCase().replace(/_/g,"-")}function nc(e){if(e===void 0||e==="")return "";let n=/^([^.[]+)(.*)$/.exec(e);if(!n)return ge(e);let[,t,i]=n;switch(t){case "pluginId":return `name${i}`;case "name":return `display_name${i}`;case "description":return `description${i}`;case "_meta":return `_meta${i}`;case "version":return ge("definitionVersion");case "definitionId":return ge("definitionId");default:return ge(`${t}${i}`)}}function uo(e,n,t){return {path:t(e.path),rule:e.rule??ec(e.code),...e.message!==e.code?{message:e.message}:{},file:n}}function fo(e){return JSON.parse(JSON.stringify(e))}function Ft(e,n,t=0,i=new Set){if(typeof e=="string"){e.length>4096&&w("LIMIT_EXCEEDED",n,"string-too-long"),(qa.test(e)||Za.test(e)||Qa.test(e))&&w("UNSAFE_VALUE",n,"unsafe-value");return}if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){Number.isFinite(e)||w("MANIFEST_INVALID",n,"non-finite-number");return}typeof e!="object"&&w("MANIFEST_INVALID",n,"non-json-value"),t>8&&w("LIMIT_EXCEEDED",n,"too-deep"),i.has(e)&&w("MANIFEST_INVALID",n,"cycle"),i.add(e);try{if(Array.isArray(e)){e.length>128&&w("LIMIT_EXCEEDED",n,"array-too-long"),e.forEach((r,o)=>Ft(r,`${n}[${o}]`,t+1,i));return}ee(e)||w("MANIFEST_INVALID",n,"non-plain-object");for(let[r,o]of Object.entries(e))Ft(o,n===""?r:`${n}.${r}`,t+1,i);}finally{i.delete(e);}}}function Ie(e,n){return (typeof e!="string"||e.length===0)&&w("MANIFEST_INVALID",n,"string"),e}function Ke(e,n){return ee(e)||w("MANIFEST_INVALID",n,"object"),e}function tc(e,n){Array.isArray(e)||w("MANIFEST_INVALID",n,"array"),e.forEach((t,i)=>Ie(t,`${n}[${i}]`));}function ic(e,n){typeof e!="boolean"&&w("MANIFEST_INVALID",n,"boolean");}function pn(e,n,t,i){for(let r of Object.keys(e))!t.includes(r)&&!i.includes(r)&&w("MANIFEST_INVALID",`${n}.${r}`,"unknown-key");for(let r of t)K(e,r)||w("MANIFEST_INVALID",`${n}.${r}`,"missing-key");}function oc(e,n){if(e!=="icon")switch(Ft(n,e),e){case "long_description":case "homepage":case "documentation":case "support":case "license":Ie(n,e);return;case "author":{let t=Ke(n,e);pn(t,e,["name"],["email","url"]);for(let i of Object.keys(t))Ie(t[i],`${e}.${i}`);return}case "repository":{let t=Ke(n,e);pn(t,e,[],["type","url"]);for(let i of Object.keys(t))Ie(t[i],`${e}.${i}`);return}case "icons":{Array.isArray(n)||w("MANIFEST_INVALID",e,"array"),n.forEach((t,i)=>{let r=`${e}[${i}]`,o=Ke(t,r);pn(o,r,["src","size"],["theme"]),Ie(o.src,`${r}.src`),Ie(o.size,`${r}.size`),K(o,"theme")&&Ie(o.theme,`${r}.theme`);});return}case "screenshots":case "keywords":case "privacy_policies":tc(n,e);return;case "tools":{Array.isArray(n)||w("MANIFEST_INVALID",e,"array"),n.forEach((t,i)=>{let r=`${e}[${i}]`,o=Ke(t,r);pn(o,r,["name"],["description"]),Ie(o.name,`${r}.name`),K(o,"description")&&Ie(o.description,`${r}.description`);});return}case "prompts":{Array.isArray(n)||w("MANIFEST_INVALID",e,"array"),n.forEach((t,i)=>{let r=`${e}[${i}]`,o=Ke(t,r);pn(o,r,["name","text"],["description","arguments"]),Ie(o.name,`${r}.name`),Ie(o.text,`${r}.text`);});return}case "tools_generated":case "prompts_generated":ic(n,e);return;case "localization":case "compatibility":case "user_config":Ke(n,e);return;default:w("MANIFEST_INVALID",e,"unknown-key");}}function Hn(e){return typeof e=="string"&&_e.test(e)?e:void 0}function yo(e){return Number.isSafeInteger(e)&&e>=1?e:void 0}function rc(e){let n=Hn(e.name);if(n===void 0)return;let t=e._meta,i=ee(t)?t[Re]:void 0,r=ee(i)?i:{},o=K(r,"definitionId")?Hn(r.definitionId):n,a=K(r,"definitionVersion")?yo(r.definitionVersion):1;return {pluginId:n,...o===void 0?{}:{definitionId:o},...a===void 0?{}:{definitionVersion:a}}}function sc(e){let n=Hn(e.pluginId);if(n===void 0)return;let t=Hn(e.definitionId),i=yo(e.version);return {pluginId:n,...t===void 0?{}:{definitionId:t},...i===void 0?{}:{definitionVersion:i}}}function Gt(e){try{let n=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e));if(!ee(n))return !1;let t=n._meta;return ee(t)&&K(t,Re)}catch{return false}}function ac(e,n){if(e===je)return n.builtinOnly===true;let t=n._meta,i=ee(t)?t[Re]:void 0;return ee(i)&&i.builtinOnly===true}function cc(e,n){K(e,"server")&&w("MANIFEST_INVALID","server","server-unsupported","phase 1 runs CrewX-owned Apps only");for(let s of Object.keys(e))Ht.includes(s)||w("MANIFEST_INVALID",s,"unknown-key");for(let s of zt)K(e,s)||w("MANIFEST_INVALID",s,"missing-key");e.manifest_version!==vt&&w("MANIFEST_INVALID","manifest_version","unsupported-version",`manifest_version must be "${vt}"`),lo(e.version)||w("MANIFEST_INVALID","version","semver","version must be a semver.org version such as 0.1.0");let t=e._meta;ee(t)||w("MANIFEST_INVALID","_meta","object"),K(t,Re)||w("MANIFEST_INVALID",ge(),"missing-key");let i=t[Re];ee(i)||w("MANIFEST_INVALID",ge(),"object");for(let s of Object.keys(i))Vt.includes(s)||po.includes(s)||w("MANIFEST_INVALID",ge(s),"unknown-key");for(let s of Vt)s==="actions"&&n!==void 0||K(i,s)||w("MANIFEST_INVALID",ge(s),"missing-key");if(n!==void 0&&K(i,"actions")&&w("MANIFEST_INVALID",ge("actions"),"two-truths",`actions are declared in both ${Y} and ${q}; a server.ts App keeps them in the tools file only`),dc(i.actions),K(i,"definitionVersion")){let s=i.definitionVersion;(!Number.isSafeInteger(s)||s<1)&&w("MANIFEST_INVALID",ge("definitionVersion"),"positive-integer");}let r={};for(let s of co)K(e,s)&&(oc(s,e[s]),r[s]=fo(e[s]));let o={};for(let[s,c]of Object.entries(t))s!==Re&&(o[s]=c);let a={manifestVersion:2,pluginId:e.name,definitionId:K(i,"definitionId")?i.definitionId:e.name,version:K(i,"definitionVersion")?i.definitionVersion:1,name:e.display_name,description:e.description};for(let[s,c]of Object.entries(i))s==="definitionId"||s==="definitionVersion"||(a[s]=c);return n!==void 0&&(a.actions=n.map(s=>({...s,backend:{type:"skill",entry:Se}}))),Object.keys(o).length>0&&(a._meta=o),{v2Input:a,...Object.keys(o).length>0?{vendorMeta:o}:{},passthrough:r}}function dc(e){Array.isArray(e)&&e.forEach((n,t)=>{let i=ee(n)?n.backend:void 0;ee(i)&&K(i,"entry")&&w("MANIFEST_INVALID",ge(`actions[${t}].backend.entry`),"entry-not-authorable",`an action in ${Y} cannot name an entry; a server.ts App declares its actions in ${q}`);});}function pc(e,n,t){ee(e)||w("MANIFEST_INVALID","","not-object","manifest.json must be a JSON object",Y);let i;try{i=cc(e,t);}catch(a){throw a instanceof Ne?new Ne(a.code,{...a.reason,file:Y}):a}let r;try{let a=cn(i.v2Input,{mode:n.mode??"local"});a.manifestVersion!==2&&w("MANIFEST_INVALID","","v2-required"),r=a;}catch(a){throw a instanceof ae?new Ne(a.code,uo(a,Y,nc)):a}let o=e.tools;if(Array.isArray(o)){let a=new Set(r.actions.map(s=>s.actionId));o.forEach((s,c)=>{let d=s.name;if(!a.has(d))throw new Ne("MANIFEST_INVALID",{path:`tools[${c}].name`,rule:"tool-not-action",message:"every tools[].name must be an action id",file:Y})});}return {file:Y,manifest:r,v2Input:i.v2Input,releaseVersion:e.version,...Object.keys(i.passthrough).length>0?{mcpb:i.passthrough}:{}}}function lc(e,n){try{let t=cn(e,{mode:n.mode??"local"});if(t.manifestVersion!==2)throw new Ne("MANIFEST_INVALID",{path:"manifestVersion",rule:"v2-required",message:"a workspace App requires manifestVersion 2",file:je});return {file:je,manifest:t,v2Input:e}}catch(t){throw t instanceof ae?new Ne(t.code,uo(t,je,i=>i??"")):t}}function Bt(e){return se(dn(e).definition)}function so(e){let{entryHash:n,initialState:t,...i}=e,r={...i};return t!==void 0&&(r.initialState={path:t.path}),fo(r)}function uc(e,n){let t=so(e),i=so(n);return [...new Set([...Object.keys(t),...Object.keys(i)])].sort().filter(o=>Q(t[o]??null)!==Q(i[o]??null))}function fc(e,n){return e.entryHash!==void 0&&n.entryHash!==void 0&&e.entryHash!==n.entryHash||e.initialState?.hash!==void 0&&n.initialState?.hash!==void 0&&e.initialState.hash!==n.initialState.hash}function yc(e,n){let t=uc(e,n),i=fc(e,n),r="";try{let o=Bt(e),a=Bt(n);i=i||o!==a,r=` (definition hash ${o.slice(0,12)} vs ${a.slice(0,12)})`;}catch{i=true;}t.length===0&&!i||w("MANIFEST_DUAL_MISMATCH","","dual-manifest-mismatch",`${Y} and ${je} normalize to different definitions${r}`+(t.length>0?`; differing fields: ${t.join(", ")}`:""));}function Te(e,n,t="MANIFEST_INVALID",i){return {code:t,reason:{path:e,rule:n,...i===void 0?{}:{message:i},file:q},files:[]}}function ao(e){return {...Te("","tools-needs-manifest-json","MANIFEST_INVALID",`${q} is read with ${Y} only`),files:e}}function Ac(e,n){if(e.byteLength>n)return {failure:Te("","file-too-large","LIMIT_EXCEEDED")};let t;try{t=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e));}catch{return {failure:Te("","invalid-json")}}if(!ee(t))return {failure:Te("","not-object","MANIFEST_INVALID",`${q} must be a JSON object`)};for(let r of Object.keys(t))if(r!=="schemaVersion"&&r!=="actions")return {failure:Te(r,"unknown-key")};for(let r of ["schemaVersion","actions"])if(!K(t,r))return {failure:Te(r,"missing-key")};if(t.schemaVersion!==1)return {failure:Te("schemaVersion","unsupported-version","MANIFEST_INVALID",`schemaVersion must be ${1}`)};let i=t.actions;if(!Array.isArray(i))return {failure:Te("actions","array")};for(let[r,o]of i.entries()){if(!ee(o))return {failure:Te(`actions[${r}]`,"object")};if(K(o,"backend"))return {failure:Te(`actions[${r}].backend`,"tools-backend","MANIFEST_INVALID",`an action in ${q} cannot carry a backend`)}}return {actions:i}}function Ic(e,n){let t=n.maxBytes??262144,i=[],r=new TextDecoder("utf-8",{fatal:true});for(let o of ye){let a=e[o];if(a===void 0)continue;if(a.byteLength>t)return {parsed:i,failure:{code:"LIMIT_EXCEEDED",reason:{path:"",rule:"file-too-large",file:o},files:[o]}};let s;try{s=JSON.parse(r.decode(a));}catch{return {parsed:i,failure:{code:"MANIFEST_INVALID",reason:{path:"",rule:"invalid-json",file:o},files:[o]}}}if(!ee(s))return {parsed:i,failure:{code:"MANIFEST_INVALID",reason:{path:"",rule:"not-object",message:`${o} must be a JSON object`,file:o},files:[o]}};i.push({file:o,raw:s});}return {parsed:i}}function Jt(e,n={}){let{parsed:t,failure:i}=Ic(e,n),r=ye.filter(A=>e[A]!==void 0);if(i!==void 0)return {ok:false,rejection:i,parseFailure:true,builtinOnly:false};let o=e[q],a=o===void 0?void 0:Ac(o,n.maxBytes??262144);if(t.length===0)return {ok:false,rejection:a===void 0?{code:"MANIFEST_INVALID",reason:{path:"",rule:"no-manifest-file",message:"neither manifest.json nor ui-plugin.json is present"},files:[]}:ao(r),parseFailure:true,builtinOnly:false};let s=t[0],c=s.file===Y?rc(s.raw):sc(s.raw),d=t.some(A=>ac(A.file,A.raw)),l;if(a!==void 0){let A=t.some(I=>I.file===Y)?a.failure:ao(r);if(A!==void 0)return {ok:false,rejection:A,parseFailure:false,...c===void 0?{}:{identity:c},builtinOnly:d};l=a.actions;}let u=[];try{for(let A of t)u.push(A.file===Y?pc(A.raw,n,l):lc(A.raw,n));u.length===2&&yc(u[0].manifest,u[1].manifest);}catch(A){if(A instanceof Ne)return {ok:false,rejection:{code:A.code,reason:A.reason,files:A.code==="MANIFEST_DUAL_MISMATCH"?[...ye]:A.reason.file===void 0||A.reason.file===q?r:[A.reason.file]},parseFailure:false,...c===void 0?{}:{identity:c},builtinOnly:d};throw A}let f=u[0];return {ok:true,...f,identity:c??{pluginId:f.manifest.pluginId},files:r}}var Y,je,ye,vt,Re,Ht,zt,co,Vt,po,Ka,Ya,qa,Za,Qa,Ne,$t=C(()=>{g();ke();Pe();Pt();we();jt();Y="manifest.json",je="ui-plugin.json",ye=[Y,je],vt="0.3",Re="dev.crewx",Ht=Object.freeze(["manifest_version","name","display_name","version","description","long_description","author","repository","homepage","documentation","support","icon","icons","screenshots","localization","server","tools","tools_generated","prompts","prompts_generated","keywords","license","privacy_policies","compatibility","user_config","_meta"]),zt=Object.freeze(["manifest_version","name","display_name","version","description","_meta"]),co=Object.freeze(Ht.filter(e=>e!=="server"&&!zt.includes(e))),Vt=Object.freeze(["entry","surfaces","size","stateProjection","actions"]),po=Object.freeze(["definitionId","definitionVersion","icon","tone","entryHash","runtime","initialState","usage","detailPanel","displayModes","summaryProjection","dataPaths","focusedAiDataPaths","csp","deviceFeatures","downloads","share","files"]),Ka=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/,Ya=256,qa=/<\/?[A-Za-z][^>]*>/,Za=/^\s*javascript:/i,Qa=/data:[^,\s]*,/i;Ne=class extends Error{constructor(t,i){super(`${t}: ${i.path||"<file>"} (${i.rule})`);this.code=t;this.reason=i;}code;reason};});function Eo(e){if(e===void 0)return {kind:"none"};if(typeof e!="string")return {kind:"invalid",reason:"bad-path"};if(hc.test(e))return {kind:"url",declared:e};if(!Tc(e))return {kind:"invalid",reason:"bad-path",declared:e};let n=e.lastIndexOf("."),t=n<0?void 0:gc.get(e.slice(n+1).toLowerCase());return t===void 0?{kind:"invalid",reason:"bad-type",declared:e}:{kind:"file",path:e,contentType:t}}function Tc(e){return e.length===0||e.length>512||e.startsWith("/")||e.includes("\\")||e.includes("\0")?false:e.split("/").every(n=>n!==""&&n!=="."&&n!=="..")}async function Xt(e,n){let t=Eo(e);if(t.kind==="none")return {diagnostics:[]};if(t.kind==="url")return {diagnostics:[{code:"ICON_NOT_FILE",severity:"warning",declared:t.declared}]};if(t.kind==="invalid")return {diagnostics:[Wt(t.reason,t.declared)]};let i=await n(t.path);if(typeof i=="string")return {diagnostics:[Wt(i,t.path)]};let r=To(t.contentType,i);if(!r.ok)return {diagnostics:[Wt(r.reason,t.path)]};let o={path:t.path,contentType:t.contentType,byteLength:i.byteLength,bytes:i},a=r.square===false?[{code:"ICON_NOT_SQUARE",severity:"warning",declared:t.path}]:[];return {file:o,diagnostics:a}}function Wt(e,n){return {code:"ICON_INVALID",severity:"error",reason:e,...n===void 0?{}:{declared:n}}}function To(e,n){if(n.byteLength>262144)return {ok:false,reason:"too-large"};if(e==="image/png")return !mo(n,_c)||Uc(n,12,16)!=="IHDR"||n.byteLength<24?{ok:false,reason:"bytes-mismatch"}:{ok:true,square:go(ho(n,16),ho(n,20))};if(e==="image/jpeg"){if(!mo(n,Ec))return {ok:false,reason:"bytes-mismatch"};let t=Lc(n);return {ok:true,square:t===void 0?void 0:go(t.width,t.height)}}return Nc(n)}function Nc(e){let n;try{n=mc.decode(e);}catch{return {ok:false,reason:"bytes-mismatch"}}return Mc(n)?{ok:false,reason:"unsafe-svg"}:Dc.test(n)?{ok:true,square:Oc(n)}:{ok:false,reason:"bytes-mismatch"}}function Mc(e){if(bc.some(n=>n.test(e)))return true;for(let n of e.matchAll(Pc))if(!(n[1]??n[2]??n[3]??"").startsWith("#"))return true;for(let n of e.matchAll(Sc))if(Ao.lastIndex=n.index??0,!Ao.test(e))return true;return false}function Oc(e){let n=/<svg\b[^>]*>/i.exec(e)?.[0];if(n===void 0)return;let t=No(n,"viewBox");if(t!==void 0){let o=t.trim().split(/[\s,]+/).map(Number);return o.length===4&&o.every(Number.isFinite)?o[2]===o[3]:void 0}let i=Io(n,"width"),r=Io(n,"height");return i===void 0||r===void 0?void 0:i===r}function No(e,n){let t=new RegExp(`\\s${n}\\s*=\\s*(?:"([^"]*)"|'([^']*)')`).exec(e);return t?.[1]??t?.[2]}function Io(e,n){let t=No(e,n),i=t===void 0?null:/^\s*(\d+(?:\.\d+)?)(?:px)?\s*$/.exec(t);return i===null?void 0:Number(i[1])}function Lc(e){let n=2;for(;n+4<=e.byteLength;){if(e[n]!==255)return;let t=e[n+1];if(t===255){n+=1;continue}if(t===216||t===1||t>=208&&t<=215){n+=2;continue}if(t===217)return;let i=e[n+2]<<8|e[n+3];if(i<2)return;if(Rc(t))return n+9>e.byteLength?void 0:{height:_o(e,n+5),width:_o(e,n+7)};n+=2+i;}}function Rc(e){return e>=192&&e<=207&&e!==196&&e!==200&&e!==204}function go(e,n){if(!(e<=0||n<=0))return e===n}function mo(e,n){return e.byteLength>=n.length&&n.every((t,i)=>e[i]===t)}function Uc(e,n,t){return String.fromCharCode(...e.subarray(n,t))}function ho(e,n){return (e[n]<<24|e[n+1]<<16|e[n+2]<<8|e[n+3])>>>0}function _o(e,n){return e[n]<<8|e[n+1]}var gc,mc,hc,_c,Ec,Dc,bc,Pc,Sc,Ao,Kt=C(()=>{g();gc=new Map([["svg","image/svg+xml"],["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"]]),mc=new TextDecoder("utf-8",{fatal:true}),hc=/^[A-Za-z][A-Za-z0-9+.-]*:/,_c=[137,80,78,71,13,10,26,10],Ec=[255,216,255];Dc=/^\s*(?:<\?[\s\S]*?\?>\s*|<!--[\s\S]*?-->\s*)*<svg(?=[\s/>])/,bc=[/<script/i,/[\s"'/]on[a-z]+\s*=/i,/<foreignobject/i,/<!doctype/i,/<!entity/i,/<(?:iframe|embed|object)\b/i,/@import/i],Pc=/(?:^|[\s"'/])(?:xlink:)?href\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+))/gi,Sc=/url\(/gi,Ao=/url\(\s*["']?#/iy;});var bo=C(()=>{g();Mi();$t();Kt();jt();we();});function E(e,n=e){throw new De(e,n)}var De,Gn=C(()=>{g();De=class extends Error{constructor(t,i=t){super(i);this.code=t;}code;name="McpAppContractError"};});var Po=C(()=>{g();});var So=C(()=>{g();ke();Pe();Gn();Po();});function Oo(e,n){return Mo.add(e),n!==void 0&&Cc.set(e,n),e}function Ye(e){return e!==null&&typeof e=="object"&&Mo.has(e)}var Mo,Cc,Jn=C(()=>{g();Mo=new WeakSet,Cc=new WeakMap;});function fn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Yt(e,n,t=[]){let i=new Set([...n,...t]),r=Object.keys(e);return n.every(o=>Object.hasOwn(e,o))&&r.every(o=>i.has(o))}function Uo(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let n of Object.values(e))Uo(n);return Object.freeze(e)}function ne(e){throw new be("LINEAGE_INVALID",e)}function Fc(e){throw new be("LINEAGE_STALE",e)}function Co(e){if(!fn(e)||!Yt(e,xc,jc)||!fn(e.actions))return ne("Lineage definition shape is invalid");for(let n of Object.values(e.actions))if(!fn(n)||!Yt(n,vc,Vc))return ne("Lineage action definition shape is invalid");return e}function Bc(e){if(!fn(e)||!Yt(e,wc,kc))return ne("Lineage entry shape is invalid");if(!Number.isSafeInteger(e.version)||e.version<1||typeof e.hash!="string"||!Lo.test(e.hash))return ne("Lineage entry identity is invalid");if(e.sourceHash!==void 0&&(typeof e.sourceHash!="string"||!Lo.test(e.sourceHash)))return ne("Lineage source hash is invalid");if(e.compat!==void 0&&e.compat!=="break")return ne("Lineage compatibility marker is invalid");let n=Co(e.definition);if(n.version!==e.version)return ne("Lineage version does not match its definition");if(e.sourceHash!==void 0&&n.sourceHash!==e.sourceHash)return ne("Lineage source hash does not match its definition");let t;try{t=se(n),ue({...n,hash:e.hash});}catch{return ne("Lineage definition is invalid")}return t!==e.hash?ne("Lineage definition hash does not match"):Uo({version:e.version,hash:e.hash,definition:n,...e.sourceHash===void 0?{}:{sourceHash:e.sourceHash},...e.compat===void 0?{}:{compat:e.compat}})}function Ro(e){return e.stateProjection?.allow??[]}function Hc(e,n){let t=[],i=new Set(Ro(n));Ro(e).some(s=>!i.has(s))&&t.push("S1_STATE_PROJECTION");let r=new Set(n.dataPaths??[]);(e.dataPaths??[]).some(s=>!r.has(s))&&t.push("S2_DATA_PATHS");for(let[s,c]of Object.entries(e.actions)){let d=n.actions[s];if(d&&(c.confirmation??"native")==="native"&&(d.confirmation??"native")!=="native"){t.push("S3_ACTION_CONFIRMATION");break}}Object.keys(e.legacy?.agentAccess??{}).some(s=>!Object.hasOwn(n.actions,s))&&t.push("S4_LEGACY_AGENT_ACTIONS");let a=e.summaryProjection?.allow;if(a!==void 0){let s=new Set(n.summaryProjection?.allow??[]);a.some(c=>!s.has(c))&&t.push("S5_SUMMARY_PROJECTION");}return t}function zc(e,n){return Q(e)===Q(n)}function qt(e,n){if(!Array.isArray(e)||e.length===0)return ne("Definition lineage is missing");if(!fn(n)||typeof n.hash!="string")return ne("Current definition is invalid");let t,i;try{let{hash:s,...c}=n;i=Co(c),t={...i,hash:s},ue(t);}catch{return ne("Current definition is invalid")}let r=e.map(Bc),o=r[0].definition.id;if(r.some(s=>s.definition.id!==o))return ne("Lineage definition ids do not match");if(r.some((s,c)=>c>0&&s.version<=r[c-1].version))return ne("Lineage generations are not in increasing version order");if(r.some((s,c)=>r.findIndex(d=>d.hash===s.hash)!==c))return ne("Lineage contains a duplicate hash");let a=r[r.length-1];if(a.version!==t.version||a.hash!==t.hash||a.definition.id!==t.id||!zc(a.definition,i))return Fc("The last lineage generation does not match the current package");if(t.legacy!==void 0){let s=new Set(Object.keys(t.actions)),c=new Set;for(let l of r)if(l.sourceHash===void 0)for(let u of Object.keys(l.definition.actions))s.has(u)&&c.add(u);let d=Object.keys(t.legacy.agentAccess??{});if(d.length!==c.size||d.some(l=>!c.has(l))){let l="S4_LEGACY_AGENT_ACCESS_COMPLETE";throw new be("LINEAGE_INVALID",`Lineage compatibility failed: ${l}`,[l])}}for(let s=0;s<r.length-1;s+=1){if(r.slice(s,-1).some(l=>l.compat==="break"))continue;let d=Hc(r[s].definition,t);if(d.length>0)throw new be("LINEAGE_INVALID",`Lineage compatibility failed: ${d.join(", ")}`,d)}return Object.freeze({entries:Object.freeze(r),current:t})}var be,Lo,wc,kc,xc,jc,vc,Vc,Zt=C(()=>{g();ke();Pe();be=class extends Error{constructor(t,i=t,r=[]){super(i);this.code=t;this.violations=r;}code;violations;name="UiDefinitionLineageError"},Lo=/^[0-9a-f]{64}$/,wc=["version","hash","definition"],kc=["sourceHash","compat"],xc=["id","version","actions"],jc=["sourceHash","usage","detailPanel","displayModes","renderer","surfaces","stateProjection","dataPaths","summaryProjection","downloads","legacy"],vc=["capabilities"],Vc=["inputKeys","dataInputs","confirmation","resultProjection","content","env","schedule","job","jobAccess"];});var wo,ko,xo,jo,vo=C(()=>{g();wo="text/html;profile=mcp-app",ko=["crewx_app_terminal_connect","crewx_app_html_viewer_open","crewx_app_browser","crewx_files_list","crewx_files_read","crewx_files_write","crewx_docs_share"],xo=["crewx_listWorkspaces","crewx_queryAgent","crewx_executeAgent","crewx_getTaskResult","crewx_listTasks","crewx_listAgents","callBrowser","openTab","listTabs","closeTab"],jo="text/html";});function yn(e){return typeof e=="string"&&Gc.includes(e)}function $n(e,n){return e==="card"&&n?.type==="core"&&yn(n.handler)}var Gc,Wn=C(()=>{g();Gc=Object.freeze(["card.secret-env"]);});function Vo(e,n=[],t){if(e.content!==void 0||e.confirmation!=="none")return "denied";let i=Jc();return i&&Object.hasOwn(i,e.actionId)?i[e.actionId]:e.backend?.type==="core"&&e.backend.handler.startsWith("host.")?"denied":e.backend?.type==="core"&&e.backend.handler==="state.set"?"allowed":e.backend?.type==="core"&&yn(e.backend.handler)||e.backend?.type==="skill"?"approval_required":e.backend===void 0&&n.includes(e.actionId)?"allowed":"denied"}function Jc(e){return;}var Fo=C(()=>{g();ke();Jn();Wn();});function ed(e){return gn.has(e)&&(e.initialState===void 0||gn.has(e.initialState))}function Jo(e,n,t,i){let r=i===void 0?void 0:Object.freeze({hash:i.hash,bytes:Object.freeze(i.bytes)}),o=Object.freeze({mimeType:jo,entryHash:e,html:n,bytes:Object.freeze(t),...r===void 0?{}:{initialState:r}});return r!==void 0&&gn.add(r),gn.add(o),o}function nd(e){let n=[];return e?.terminal===true&&n.push({name:"crewx_app_terminal_connect",description:"Open a local-only terminal session for this App.",inputSchema:{type:"object",properties:{workspace:{type:"string"},threadId:{type:"string"},instanceId:{type:"string"}},required:["threadId","instanceId"],additionalProperties:false},textFallback:"A local terminal connection is ready for this App.",visibility:Object.freeze(["app"]),kind:"host",resourceBinding:ce}),e?.htmlDocuments===true&&n.push({name:"crewx_app_html_viewer_open",description:"List workspace HTML documents or open one through a short-lived Host capability.",inputSchema:{type:"object",properties:{workspace:{type:"string"},threadId:{type:"string"},instanceId:{type:"string"},operation:{type:"string",enum:["list","open"]},documentId:{type:"string"}},required:["threadId","instanceId","operation"],additionalProperties:false},textFallback:"Workspace HTML documents are available through this App.",visibility:Object.freeze(["app"]),kind:"host",resourceBinding:ce}),e?.appBrowser===true&&n.push({name:"crewx_app_browser",description:"Grant this App a native Desktop browser window. Browser commands use the custom Host RPC, not this tool.",inputSchema:{type:"object",properties:{workspace:{type:"string"},threadId:{type:"string"},instanceId:{type:"string"}},required:["threadId","instanceId"],additionalProperties:false},textFallback:"Desktop browser access is granted to this App. Browser commands use the custom Host RPC ui/crewx-app-browser.",visibility:Object.freeze(["app"]),kind:"host",resourceBinding:ce}),n}function td(e){let n=[];return e?.appFiles===true&&n.push({name:"crewx_files_list",description:"List the .md files of this App on the phone, sorted by ref, at most 200 per page. Pass `next` as `after` for the next page.",inputSchema:{type:"object",properties:{prefix:{type:"string",description:'A folder such as "workouts/". Omit for every file.'},after:{type:"string",description:"Return only refs after this one (the `next` of the previous page)."}},additionalProperties:false},textFallback:"The markdown files of this App are listed through this App.",visibility:Object.freeze(["app"]),kind:"host",resourceBinding:ce},{name:"crewx_files_read",description:"Read one .md file: its text and its version (sha256 of the UTF-8 bytes).",inputSchema:{type:"object",properties:{ref:{...Qt}},required:["ref"],additionalProperties:false},textFallback:"A markdown file of this App is read through this App.",visibility:Object.freeze(["app"]),kind:"host",resourceBinding:ce},{name:"crewx_files_write",description:"Write one .md file (at most 256 KiB). expectedVersion null creates it and fails if it exists; a version string replaces it only if the file still has that version.",inputSchema:{type:"object",properties:{ref:{...Qt},text:{type:"string",maxLength:256*1024},expectedVersion:{type:["string","null"],description:"null = create only, or the version the file had when you read it."}},required:["ref","text","expectedVersion"],additionalProperties:false},textFallback:"A markdown file of this App is written through this App.",visibility:Object.freeze(["app"]),kind:"host",resourceBinding:ce}),e?.resultShare===true&&n.push({name:"crewx_docs_share",description:"Open the Host share sheet for one markdown file of this App; resolves when the sheet closes.",inputSchema:{type:"object",properties:{ref:{...Qt}},required:["ref"],additionalProperties:false},textFallback:"The Host share sheet opens for a markdown file of this App.",visibility:Object.freeze(["app"]),kind:"host",resourceBinding:ce}),n}function Ce(e,n,t){return (typeof e!="string"||!zo.test(e))&&E(n,`${t} must be a safe identifier`),e}function An(e,n,t){let i=e??t;return (typeof i!="string"||i.trim().length===0||i.length>Xc)&&E("TOOL_INVALID",`${n} must be a meaningful description`),i}function ni(e){return (typeof e!="string"||e.length===0||e.length>qe||!/<html(?:\s|>)/i.test(e)||!/<\/html\s*>/i.test(e))&&E("HTML_INVALID","MCP App HTML must be a non-empty HTML document"),e}function In(e,n=0){try{let t=le(e,n);return t.type!==void 0&&t.type!=="object"&&E("TOOL_INVALID","MCP App inputSchema must describe an object"),t}catch(t){if(t instanceof De)throw t;E("TOOL_INVALID","MCP App inputSchema must be projection-safe JSON");}}function id(e){return (typeof e!="string"||e.trim().length===0||e.length>Kc)&&E("TOOL_INVALID","MCP App tools require a meaningful text fallback"),e}function od(e){e===void 0&&E("TOOL_INVALID","MCP App tool visibility is required");let n=[...e];return (n.length===0||n.some(t=>t!=="model"&&t!=="app")||new Set(n).size!==n.length)&&E("TOOL_INVALID","MCP App tool visibility must contain model and/or app once"),n}function Wo(e){return (typeof e!="string"||!Go.test(e))&&E("RESOURCE_URI_INVALID","MCP App resource URI is not a registered ui:// URI"),e}function Xo(e){let n=Ce(e.appId,"APP_ID_INVALID","Local App id"),t=An(e.name,"Local App name",n),i=An(e.description,"Local App description",`${t} interactive view`),r=qn(e.definition),o=ni(e.html),a=Xn(e.entryHash,"Local App entry hash"),s=e.entryBytes===void 0?Array.from(new TextEncoder().encode(o)):Yn(e.entryBytes,"Local App entry bytes");(Kn(s)!==a||qo(s)!==o)&&E("HTML_INVALID","Local App entry bytes do not match the HTML hash");let c=rd(e),d=[];Array.isArray(e.actions)||E("TOOL_INVALID","Local App actions must be an array");for(let b of e.actions){let U=Ce(b.actionId,"TOOL_ID_INVALID","Local App action id");(d.includes(U)||!Object.prototype.hasOwnProperty.call(r.actions,U))&&E("TOOL_INVALID",`Local App action is not declared by the UI definition: ${U}`),d.push(U);}let l=Ce(e.readToolName,"TOOL_ID_INVALID","Local App read tool name"),u=e.actionToolName===void 0?void 0:Ce(e.actionToolName,"TOOL_ID_INVALID","Local App action tool name");d.length===0&&u!==void 0&&E("TOOL_INVALID","A static local App cannot register an action tool"),d.length>0&&u===void 0&&E("TOOL_INVALID","A stateful local App requires an action tool name"),u!==void 0&&u===l&&E("TOOL_ID_CONFLICT",`Local App read and action tools share a name: ${l}`);let f=[...nd(e.runtime),...td(e.hostTools)];f.some(b=>b.name===l||b.name===u)&&E("TOOL_ID_CONFLICT","Local App read or action tool conflicts with a requested Host capability");let A={name:l,description:`${t} current state`,inputSchema:Qc,textFallback:`${t} current state is available through its open instance.`,visibility:Object.freeze(["model","app"]),kind:"read",resourceBinding:ce},I=[Object.freeze(A)];if(I.push(...f.map(b=>Object.freeze(b))),u!==void 0){let b={name:u,description:`${t} actions`,inputSchema:ti(e.actions),textFallback:`${t} action requests are handled by the open App instance.`,visibility:Object.freeze(["app"]),kind:"action",resourceBinding:ce,actionIds:Object.freeze([...d])};I.push(Object.freeze(b));}let h=[],T=new Set(I.map(b=>b.name));if(u!==void 0)for(let b of e.actions){let U=`${u}__${b.actionId}`;if(U.length>128||!zo.test(U)){h.push(Object.freeze({toolName:U,actionId:b.actionId,reason:"name_too_long"}));continue}if(T.has(U)){h.push(Object.freeze({toolName:U,actionId:b.actionId,reason:"name_collision"}));continue}let W=Vo({actionId:b.actionId,confirmation:r.actions[b.actionId]?.confirmation,content:r.actions[b.actionId]?.content,backend:b.backend},e.modelActions),N=Object.freeze([...pd(W,r.usage,b.backend)]),M={name:U,description:`${U} action`,inputSchema:In(b.inputSchema),textFallback:`${U} action requests are handled by the open App instance.`,visibility:N,kind:"action",resourceBinding:ce,actionId:b.actionId,actionIds:Object.freeze([b.actionId]),_meta:Object.freeze({ui:Object.freeze({visibility:N})})};I.push(Object.freeze(M)),T.add(U);}let J=Jo(a,o,s,c===void 0?void 0:{hash:c.hash,bytes:[...c.bytes]}),v={appId:n,name:t,description:i,...e.icon===void 0?{}:{icon:Zo(e.icon)},...e.tone===void 0?{}:{tone:Qo(e.tone)},builtinOnly:false,definition:r,...e.runtime===void 0?{}:{runtime:Object.freeze({...e.runtime})},...e.deviceFeatures===void 0?{}:{deviceFeatures:Object.freeze([...e.deviceFeatures])},...e.downloads===void 0?{}:{downloads:e.downloads},...e.share===void 0?{}:{share:Object.freeze({...e.share})},...e.files===void 0?{}:{files:Object.freeze({...e.files})},resourceBinding:ce,resource:J,tools:Object.freeze(I),toolDiagnostics:Object.freeze(h)};return Z(v)}function Ko(e={}){return new ei(e)}function ti(e){if(e.length===0)return In({type:"object",properties:{},additionalProperties:false});let n=e.map(i=>i.actionId),t=new Map;for(let i of e)t.set(i.actionId,In(i.inputSchema));return In(sd(n,t),$o)}function rd(e){let n=e.definition.dataPaths??[];if(e.initialStateBytes===void 0){e.initialStateHash!==void 0&&E("STATE_INVALID","Initial state hash has no bytes"),e.initialState!==void 0&&le(e.initialState,0,n);return}e.initialStateHash===void 0&&E("STATE_INVALID","Initial state bytes require a hash");let t=Xn(e.initialStateHash,"Initial state hash"),i=Yn(e.initialStateBytes,"Initial state bytes");Kn(i)!==t&&E("STATE_INVALID","Initial state bytes do not match the hash");let r;try{let o=new TextDecoder("utf-8",{fatal:!0}).decode(Uint8Array.from(i));r=le(JSON.parse(o),0,n);}catch{E("STATE_INVALID","Initial state bytes are not projection-safe JSON");}return e.initialState!==void 0&&Q(r)!==Q(le(e.initialState,0,n))&&E("STATE_INVALID","Initial state bytes do not match the state value"),{hash:t,bytes:Object.freeze([...i])}}function sd(e,n){let t=e.map(i=>({type:"object",properties:{actionId:{type:"string",const:i},input:n.get(i)??{type:"object"}},required:["actionId","input"],additionalProperties:false}));return Object.freeze({type:"object",oneOf:Object.freeze(t),properties:Object.freeze({actionId:Object.freeze({type:"string",enum:Object.freeze([...e])}),input:Object.freeze({type:"object"})}),required:Object.freeze(["actionId","input"]),additionalProperties:false})}function ad(e){let n=mn(e),t=Ce(n.appId,"APP_ID_INVALID","MCP App id"),i=ni(n.html);Wo(n.uiUri);let r=n.definition===void 0?void 0:qn(n.definition),o=e.provenance;o!==void 0&&(!Ye(o)||o.appId!==t||o.definitionId!==r?.id||o.version!==r?.version||o.definitionHash!==r?.hash)&&E("TOOL_INVALID","Product App built-in registration provenance is not verified");let a=Object.freeze(n.tools.map(d=>Z(mn(d)))),s=Z({...n,appId:t,html:i,...r===void 0?{}:{definition:r},...o===void 0?{}:{provenance:o},tools:a}),c=Z({uri:s.uiUri,mimeType:wo,text:i,...s.csp===void 0?{}:{_meta:{ui:{csp:s.csp}}}});return Z({appId:t,name:s.name,description:s.description,...s.icon===void 0?{}:{icon:s.icon},...s.tone===void 0?{}:{tone:s.tone},builtinOnly:s.builtinOnly,uiUri:s.uiUri,...r===void 0?{}:{definition:r},resourceBinding:Object.freeze({kind:"mcp",uri:s.uiUri}),resource:c,tools:a,descriptor:s})}function cd(e){(e.resourceBinding.kind!=="instance"||e.builtinOnly!==false)&&E("STATE_INVALID","Local App registration binding is invalid"),Object.prototype.hasOwnProperty.call(e,"uiUri")&&E("STATE_INVALID","Local App registration cannot contain uiUri");let n=Ce(e.appId,"APP_ID_INVALID","Local App id"),t=qn(e.definition),i=e.provenance;i!==void 0&&(!Ye(i)||i.appId!==n||i.definitionId!==t.id||i.version!==t.version||i.definitionHash!==t.hash)&&E("TOOL_INVALID","Product App local registration provenance is not verified");let r=dd(e.resource),o=e.tools.map(s=>{Ce(s.name,"TOOL_ID_INVALID","Local App tool name"),An(s.description,"Local App tool description","Local App tool"),id(s.textFallback);let c=In(s.inputSchema,s.kind==="action"&&!("actionId"in s)?$o:0);if((s.resourceBinding.kind!=="instance"||Object.prototype.hasOwnProperty.call(s,"resourceUri"))&&E("TOOL_INVALID","Local App tools cannot carry an MCP resource URI"),s.kind==="host")return (!Zc.has(s.name)||s.visibility.length!==1||s.visibility[0]!=="app"||Object.prototype.hasOwnProperty.call(s,"actionId"))&&E("TOOL_INVALID","Local App Host tools must use an allow-listed name and app-only visibility"),Z({...s,inputSchema:c,visibility:Object.freeze(["app"])});if(s.kind==="action"){if("actionId"in s){let l=Ce(s.actionId,"TOOL_ID_INVALID","Local App action id");Object.prototype.hasOwnProperty.call(t.actions,l)||E("TOOL_INVALID","Local App action tool references an undeclared action");let u=od(s._meta.ui.visibility);return JSON.stringify(u)!==JSON.stringify(s.visibility)&&E("TOOL_INVALID","Local App action metadata visibility must match the tool visibility"),Z({...s,actionId:l,actionIds:Object.freeze([l]),inputSchema:c,visibility:u,_meta:{ui:{visibility:u}}})}let d=[...s.actionIds];return (d.length===0||d.some(l=>!Object.prototype.hasOwnProperty.call(t.actions,l)))&&E("TOOL_INVALID","Local App action tool references an undeclared action"),Z({...s,inputSchema:c,actionIds:Object.freeze(d)})}return Z({...s,inputSchema:c})}),a=Z({appId:n,name:An(e.name,"Local App name",e.appId),description:An(e.description,"Local App description",e.name),...e.icon===void 0?{}:{icon:Zo(e.icon)},...e.tone===void 0?{}:{tone:Qo(e.tone)},builtinOnly:false,definition:t,...e.runtime===void 0?{}:{runtime:Object.freeze({...e.runtime})},...e.deviceFeatures===void 0?{}:{deviceFeatures:Object.freeze([...e.deviceFeatures])},...e.downloads===void 0?{}:{downloads:e.downloads},...e.share===void 0?{}:{share:Object.freeze({...e.share})},...e.files===void 0?{}:{files:Object.freeze({...e.files})},...i===void 0?{}:{provenance:i},resourceBinding:ce,resource:r,tools:Object.freeze(o),toolDiagnostics:Object.freeze([...e.toolDiagnostics??[]])});return Bo.has(e)?e:(Bo.add(a),a)}function dd(e){let n=ni(e.html),t=Xn(e.entryHash,"Local App entry hash");if(ed(e))return e;let i=Yn(e.bytes,"Local App entry bytes");(Kn(i)!==t||qo(i)!==n)&&E("HTML_INVALID","Local App entry bytes do not match the HTML hash");let r=e.initialState===void 0?void 0:{hash:Xn(e.initialState.hash,"Initial state hash"),bytes:Yn(e.initialState.bytes,"Initial state bytes")};return r&&Kn(r.bytes)!==r.hash&&E("STATE_INVALID","Initial state bytes do not match the hash"),Jo(t,n,i,r)}function pd(e,n,t){if($n(n,t))return ["model"];let i=t?.type==="core"&&yn(t.handler);return e==="denied"||i?["app"]:["model","app"]}function ld(e){return Z({appId:e.appId,name:e.name,description:e.description,...e.icon===void 0?{}:{icon:e.icon},...e.tone===void 0?{}:{tone:e.tone},builtinOnly:false,definition:Yo(e.definition),...e.provenance===void 0?{}:{provenance:e.provenance},entryHash:e.resource.entryHash,resourceBinding:ce,tools:e.tools})}function ud(e){return Z({appId:e.appId,name:e.name,description:e.description,...e.icon===void 0?{}:{icon:e.icon},...e.tone===void 0?{}:{tone:e.tone},builtinOnly:e.builtinOnly,uiUri:e.uiUri,...e.definition===void 0?{}:{definition:Yo(e.definition)},resourceBinding:Object.freeze({kind:"mcp",uri:e.uiUri}),tools:e.tools})}function qn(e){try{if(Object.isFrozen(e))return ue(e),Z(e);let n=mn(e);return ue(n),Z(n)}catch(n){if(n instanceof De)throw n;E("STATE_INVALID","UI definition is not a valid immutable definition");}}function Yo(e){return Z({id:e.id,version:e.version,hash:e.hash})}function fd(e){return e!==null&&typeof e=="object"&&typeof e.id=="string"&&Number.isSafeInteger(e.version)&&typeof e.hash=="string"}function Ho(e,n,t){return `${e}\0${n}\0${t}`}function Xn(e,n){return (typeof e!="string"||!Wc.test(e))&&E("SERIALIZATION_INVALID",`${n} is invalid`),e}function Kn(e){return createHash("sha256").update(Uint8Array.from(e)).digest("hex")}function Yn(e,n){return (!Array.isArray(e)||e.some(t=>!Number.isInteger(t)||t<0||t>255))&&E("SERIALIZATION_INVALID",`${n} is invalid`),[...e]}function qo(e){try{return new TextDecoder("utf-8",{fatal:!0}).decode(Uint8Array.from(e))}catch{E("SERIALIZATION_INVALID","UTF-8 bytes are invalid");}}function Zo(e){return (typeof e!="string"||!Yc.test(e))&&E("TOOL_INVALID","MCP App icon is invalid"),e}function Qo(e){return (typeof e!="string"||!qc.has(e))&&E("TOOL_INVALID","MCP App tone is invalid"),e}function mn(e,n=new Map){if(e===null||typeof e!="object")return e;let t=e;if(n.has(t)&&E("SERIALIZATION_INVALID","MCP App value contains a cycle"),Array.isArray(e)){let o=[];n.set(t,o);for(let a of e)o.push(mn(a,n));return n.delete(t),o}let i;try{i=Object.getPrototypeOf(e);}catch{E("SERIALIZATION_INVALID","MCP App value cannot be cloned");}i!==Object.prototype&&i!==null&&E("SERIALIZATION_INVALID","MCP App value must be plain JSON");let r={};n.set(t,r);for(let[o,a]of Object.entries(e))Object.defineProperty(r,o,{configurable:true,enumerable:true,value:mn(a,n),writable:true});return n.delete(t),r}function Z(e,n=new Set){if(e===null||typeof e!="object"||n.has(e)||gn.has(e))return e;n.add(e);for(let t of Object.values(e))Z(t,n);return Object.freeze(e),e}var zo,Go,Wc,qe,Xc,Kc,Yc,qc,Zc,ce,Qc,gn,Bo,Qt,$o,ei,Zn=C(()=>{g();So();ke();Pe();Jn();Gn();Zt();vo();Fo();Wn();zo=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,Go=/^ui:\/\/crewx\/([A-Za-z][A-Za-z0-9._-]{0,127})\/([0-9a-f]{12})$/,Wc=/^[0-9a-f]{64}$/,qe=8*1024*1024,Xc=8*1024,Kc=16*1024,Yc=/^[a-z][a-z0-9-]{0,63}$/,qc=new Set(["blue","violet","emerald","amber","rose","sky","slate","indigo"]),Zc=new Set(ko),new Set(xo),ce=Object.freeze({kind:"instance"}),Qc=Object.freeze({type:"object",properties:Object.freeze({}),additionalProperties:false}),gn=new WeakSet,Bo=new WeakSet;Qt={type:"string",description:'Relative path in NFC, 1 to 3 segments joined by "/", each [\\p{L}\\p{N}][\\p{L}\\p{N}\\p{M}_-]{0,99}, the last ending in ".md". At most 200 code points.'};$o=4;ei=class{builtinApps;localApps;builtinDescriptors;builtinTools;mcpResources=new Map;localById=new Map;registrationById=new Map;launcherById=new Map;definitionByKey=new Map;handlerByKey=new Map;mcpToolByName=new Map;localToolByName=new Map;constructor(n){let t=n.builtins??n.builtin,i=[],r=[],o=[],a=new Set,s=new Set;for(let u of t?.listMcpApps()??[]){let f=ad(u);a.has(f.appId)&&E("APP_ID_CONFLICT",`MCP App id is already registered: ${f.appId}`),a.add(f.appId);let A=f.tools;for(let I of A)s.has(I.name)&&E("TOOL_ID_CONFLICT",`MCP App tool name is already registered: ${I.name}`),s.add(I.name),this.mcpToolByName.set(I.name,I),o.push(I);this.mcpResources.set(f.resource.uri,f.resource),i.push(f),r.push(f.descriptor);}let c=(n.localApps??n.locals??[]).map(cd),d=new Set(c.flatMap(u=>u.tools.filter(f=>!(f.kind==="action"&&"actionId"in f)).map(f=>f.name))),l=[];for(let u of c){let f=u;a.has(f.appId)&&E("APP_ID_CONFLICT",`MCP App id is already registered: ${f.appId}`),a.add(f.appId);let A=[],I=[...f.toolDiagnostics??[]];for(let h of f.tools){if(s.has(h.name)){if(h.kind==="host"&&this.localToolByName.get(h.name)?.kind==="host"){A.push(h);continue}if(h.kind==="action"&&"actionId"in h){I.push(Object.freeze({toolName:h.name,actionId:h.actionId,reason:"name_collision"}));continue}E("TOOL_ID_CONFLICT",`MCP App tool name is already registered: ${h.name}`);}if(h.kind==="action"&&"actionId"in h&&d.has(h.name)){I.push(Object.freeze({toolName:h.name,actionId:h.actionId,reason:"name_collision"}));continue}s.add(h.name),this.localToolByName.set(h.name,h),A.push(h);}(A.length!==f.tools.length||I.length!==(f.toolDiagnostics?.length??0))&&(f=Z({...f,tools:Object.freeze(A),toolDiagnostics:Object.freeze(I)})),l.push(f),this.localById.set(f.appId,f);}for(let u of i)this.registrationById.set(u.appId,u),this.launcherById.set(u.appId,ud(u)),u.definition&&this.addDefinition(u.definition);for(let u of l)this.registrationById.set(u.appId,u),this.launcherById.set(u.appId,ld(u)),this.addDefinition(u.definition);for(let u of n.definitions??[])this.addDefinition(u);for(let u of n.handlers??[])this.addHandler(u);this.builtinApps=Object.freeze(i),this.localApps=Object.freeze(l),this.builtinDescriptors=Object.freeze(r),this.builtinTools=Object.freeze(o);}getMcpApp(n){return this.builtinApps.find(t=>t.appId===n)?.descriptor??null}listMcpApps(){return this.builtinDescriptors}listMcpAppTools(){return this.builtinTools}resolveMcpAppTool(n){return this.mcpToolByName.get(n)??null}resolveMcpAppResource(n){return typeof n!="string"||!Go.test(n)?null:this.mcpResources.get(n)??null}requireMcpAppResource(n){Wo(n);let t=this.mcpResources.get(n);return t||E("RESOURCE_NOT_FOUND",`MCP App resource is not registered: ${n}`),t}listLocalMcpApps(){return this.localApps}getLocalMcpApp(n){return this.localById.get(n)??null}listLocalMcpAppTools(){return Object.freeze([...this.localToolByName.values()])}resolveLocalMcpAppTool(n){return this.localToolByName.get(n)??null}resolveLocalMcpAppResource(n,t){let i=this.localById.get(n);return !i||t!==void 0&&i.definition.hash!==t?null:i.resource}listRegistrations(){return Object.freeze([...this.builtinApps,...this.localApps])}getRegistration(n){return this.registrationById.get(n)??null}listLaunchers(){return Object.freeze([...this.launcherById.values()].filter(n=>{let t=this.registrationById.get(n.appId),i=t?"descriptor"in t?t.descriptor.provenance:t.provenance:void 0,r=Ye(i)&&i.launcher===false;return t?.definition?.usage!=="card"&&!r}))}listCardApps(){return Object.freeze([...this.launcherById.values()].filter(n=>this.registrationById.get(n.appId)?.definition?.usage==="card"))}getLauncher(n){return this.launcherById.get(n)??null}resolveDefinition(n){if(!fd(n))return null;let t=this.definitionByKey.get(bt(n));if(!t||t.hash!==n.hash)return null;try{return se(t)===t.hash?t:null}catch{return null}}resolveActionHandler(n,t,i){return typeof n!="string"||typeof i!="string"||!Number.isSafeInteger(t)?null:this.handlerByKey.get(Ho(n,t,i))??null}addDefinition(n){let t=qn(n),i=bt(t),r=this.definitionByKey.get(i);r&&r.hash!==t.hash&&E("STATE_INVALID",`UI definition generation conflicts: ${i}`),r||this.definitionByKey.set(i,t);}addHandler(n){(!n||typeof n.definitionId!="string"||typeof n.actionId!="string"||!Number.isSafeInteger(n.version)||n.version<1||typeof n.handle!="function")&&E("STATE_INVALID","UI action handler registration is invalid");let t=Ho(n.definitionId,n.version,n.actionId);this.handlerByKey.has(t)&&E("TOOL_INVALID",`Duplicate UI action handler registration: ${t}`),this.handlerByKey.set(t,Object.freeze({...n}));}};});function yd(e,n){let t=Xo({appId:e.appId,name:e.name,description:e.description,...e.icon===void 0?{}:{icon:e.icon},...e.tone===void 0?{}:{tone:e.tone},...e.normalized.manifest.runtime===void 0?{}:{runtime:e.normalized.manifest.runtime},...e.normalized.manifest.deviceFeatures===void 0?{}:{deviceFeatures:e.normalized.manifest.deviceFeatures},...e.normalized.manifest.downloads===void 0?{}:{downloads:e.normalized.manifest.downloads},...e.normalized.manifest.share===void 0?{}:{share:e.normalized.manifest.share},...e.normalized.manifest.files===void 0?{}:{files:e.normalized.manifest.files},definition:e.definition,html:e.html,entryHash:e.entryHash,entryBytes:e.entryBytes,initialState:e.initialState,...e.initialStateHash===void 0?{}:{initialStateHash:e.initialStateHash},...e.initialStateBytes===void 0?{}:{initialStateBytes:e.initialStateBytes},readToolName:e.toolNames.read,...e.toolNames.action===void 0?{}:{actionToolName:e.toolNames.action},actions:e.normalized.manifest.actions.map(r=>({actionId:r.actionId,inputSchema:r.inputSchema,backend:r.backend})),...{}});return e.provenance===void 0?t:Object.freeze({...t,provenance:e.provenance})}function er(e){let n=e.normalized.manifest.actions;if(n.some(i=>i.backend.type==="skill")&&n.some(i=>i.backend.type==="core"))throw new Error("Mixed workspace App execution models");let t=yd(e);Ko({localApps:[t],definitions:[e.definition]});}var nr=C(()=>{g();Zn();});function tr(){return Object.freeze({[ii]:{candidates:new Map,assetCatalogs:new Map,preparedCandidates:new Map}})}function Ad(e){if(e===null||typeof e!="object"||!(ii in e))throw new TypeError("scanCache must be created by createWorkspaceAppScanCache");return e[ii]}function ir(e,n){let t=Ad(e),i=t.rootIdentity;return i!==void 0&&(i.dev!==n.dev||i.ino!==n.ino||i.realPath!==n.realPath)&&(t.candidates.clear(),t.assetCatalogs.clear(),t.preparedCandidates.clear(),t.lastCandidateScanUnchanged=void 0,t.lastCandidateKeys=void 0,t.scanStartedAtNs=void 0,t.lastAssetCatalogsUnchanged=void 0,t.lastSnapshot=void 0,t.lastSnapshotBuildInputs=void 0,t.lastSnapshotCandidates=void 0,t.lastSnapshotCatalogFingerprint=void 0),t.rootIdentity=n,t}var ii,or=C(()=>{g();ii=Symbol("crewx.workspace-app-scan-cache.state");});function de(e){let n=typeof e=="object"&&e!==null&&"code"in e?String(e.code):"";return n==="ENOENT"?new _("NOT_FOUND"):n==="ELOOP"?new _("PATH_ESCAPED"):n==="EFBIG"||n==="EOVERFLOW"?new _("LIMIT_EXCEEDED"):n==="EACCES"||n==="EPERM"||n==="ENOTDIR"?new _("READ_DENIED"):new _("READ_DENIED")}function hd(e){if(typeof e!="string"||e.length===0||!isAbsolute(e))throw new _("READ_DENIED")}function oi(e){if(typeof e!="string"||isAbsolute(e)||/[\\\u0000]/.test(e))throw new _("PATH_ESCAPED");if(e==="")return [];let n=e.split("/");if(n.some(t=>t.length===0||t==="."||t===".."))throw new _("PATH_ESCAPED");return n}function tt(e,n){let t=relative(e,n);return t===""||t!==".."&&!t.startsWith(`..${sep}`)&&!isAbsolute(t)}function Qe(e){return {dev:e.dev,ino:e.ino,size:e.size,mtimeNs:e.mtimeNs,ctimeNs:e.ctimeNs}}function ci(e,n){return e.dev===n.dev&&e.ino===n.ino}function di(e,n){return ci(e,n)&&e.size===n.size&&e.mtimeNs===n.mtimeNs&&e.ctimeNs===n.ctimeNs}async function Qn(e){hd(e);let n,t;try{n=await realpath(e),t=await stat(n,{bigint:!0});}catch(i){throw de(i)}if(!t.isDirectory())throw new _("READ_DENIED");return {realRoot:n,identity:Qe(t)}}async function ar(e,n,t){if(t.length<2||t[0]!=="apps"&&t[0]!=="skills")return;let i,r;try{if(i=resolve(e,t[0],t[1]),r=await realpath(i),!(await stat(r,{bigint:!0})).isDirectory())throw new _("READ_DENIED")}catch(o){throw o instanceof _?o:de(o)}if(!tt(n,r))throw new _("PATH_ESCAPED");return r}async function et(e,n,t,i){let r,o,a;try{r=await lstat(e,{bigint:!0}),o=await realpath(e),a=await stat(o,{bigint:!0});}catch(s){throw de(s)}if(!tt(n,o)||t!==void 0&&!tt(t,o))throw new _("PATH_ESCAPED");if(!r.isFile()||!a.isFile())throw new _("READ_DENIED");if(!ci(i,r)||!ci(i,a)||i.dev!==a.dev)throw new _("PATH_ESCAPED")}async function Ze(e,n){let t,i;try{t=await realpath(e),i=await stat(t,{bigint:!0});}catch{throw new _("PATH_ESCAPED")}if(t!==n.realRoot||!di(n.identity,Qe(i)))throw new _("PATH_ESCAPED")}function _d(e){return e.isSymbolicLink()?{name:e.name,kind:"symlink"}:e.isDirectory()?{name:e.name,kind:"directory"}:e.isFile()?{name:e.name,kind:"file"}:{name:e.name,kind:"other"}}var _,ai,md,sr,en,it,cr,dr,li=C(()=>{g();_=class extends Error{constructor(t){super(t);this.code=t;}code;name="AppDiscoveryFsError"},ai=constants.O_NOFOLLOW,md=constants.O_NONBLOCK,sr=constants.O_RDONLY|(ai??0)|(md??0);en=class{async getRootIdentity(n){let t=await Qn(n);return await Ze(n,t),{dev:t.identity.dev,ino:t.identity.ino,realPath:t.realRoot}}async listDirectory(n,t){let i=oi(t),r=await Qn(n),o=resolve(n,...i),a,s;try{a=await realpath(o),s=await stat(a,{bigint:!0});}catch(c){let d=de(c);if(d.code==="NOT_FOUND")return [];throw d}if(!tt(r.realRoot,a)||!s.isDirectory())throw new _("PATH_ESCAPED");try{let c=await readdir(a,{withFileTypes:!0,encoding:"utf8"});return await Ze(n,r),c.map(_d)}catch(c){let d=de(c);if(d.code==="NOT_FOUND")return [];throw d}}async readdir(n,t){return this.listDirectory(n,t)}async readDirectory(n,t){return this.listDirectory(n,t)}async readVerifiedFile(n,t,i){if(!Number.isSafeInteger(i)||i<0)throw new _("READ_DENIED");if(ai===void 0)throw new _("UNSUPPORTED");let r=oi(t),o=await Qn(n),a=resolve(n,...r),s=relative(n,a);if(s===".."||s.startsWith(`..${sep}`)||isAbsolute(s))throw new _("PATH_ESCAPED");let c;try{c=await open(a,sr);}catch(d){throw de(d)}try{let d;try{let I=await c.stat({bigint:!0});d=Qe(I);}catch(I){throw de(I)}if(d.size>BigInt(i))throw new _("LIMIT_EXCEEDED");if(d.size>BigInt(Number.MAX_SAFE_INTEGER))throw new _("LIMIT_EXCEEDED");await Ze(n,o);let l=await ar(n,o.realRoot,r);await et(a,o.realRoot,l,d);let u=new Uint8Array(new ArrayBuffer(Number(d.size))),f=0;for(;f<u.byteLength;){let I;try{I=(await c.read(u,f,u.byteLength-f,f)).bytesRead;}catch(h){throw de(h)}if(I<=0)throw new _("IDENTITY_CHANGED");f+=I;}let A;try{let I=await c.stat({bigint:!0});A=Qe(I);}catch(I){throw de(I)}if(!di(d,A))throw new _("IDENTITY_CHANGED");return await et(a,o.realRoot,l,A),await Ze(n,o),new Uint8Array(u)}finally{await c.close().catch(()=>{});}}async fingerprintVerifiedFile(n,t,i){if(!Number.isSafeInteger(i)||i<0)throw new _("READ_DENIED");if(ai===void 0)throw new _("UNSUPPORTED");let r=oi(t),o=await Qn(n),a=resolve(n,...r),s=relative(n,a);if(s===".."||s.startsWith(`..${sep}`)||isAbsolute(s))throw new _("PATH_ESCAPED");let c;try{c=await open(a,sr);}catch(d){throw de(d)}try{let d;try{let f=await c.stat({bigint:!0});d=Qe(f);}catch(f){throw de(f)}if(d.size>BigInt(i)||d.size>BigInt(Number.MAX_SAFE_INTEGER))throw new _("LIMIT_EXCEEDED");await Ze(n,o);let l=await ar(n,o.realRoot,r);await et(a,o.realRoot,l,d);let u;try{let f=await c.stat({bigint:!0});u=Qe(f);}catch(f){throw de(f)}if(!di(d,u))throw new _("IDENTITY_CHANGED");return await et(a,o.realRoot,l,u),await Ze(n,o),{...u,candidateRealPath:l??o.realRoot}}catch(d){throw d instanceof _?d:de(d)}finally{await c.close().catch(()=>{});}}async readFileVerified(n,t,i){return this.readVerifiedFile(n,t,i)}},it=new en,cr=it,dr=en;});function Tn(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;try{let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}catch{return false}}function lr(e){return typeof e=="string"&&_e.test(e)?e:void 0}function Sd(e){return e.length>0&&e!=="."&&e!==".."&&!/[\\/\u0000]/.test(e)}function Ve(e,n){let t=new TextEncoder().encode(e),i=new TextEncoder().encode(n),r=Math.min(t.byteLength,i.byteLength);for(let o=0;o<r;o+=1){let a=t[o]-i[o];if(a!==0)return a}return t.byteLength-i.byteLength}function Md(e){if(typeof e=="string")return {name:e,kind:"directory"};if(e===null||typeof e!="object")return null;let n=e;if(typeof n.name!="string")return null;if(n.kind==="file"||n.kind==="directory"||n.kind==="symlink"||n.kind==="other")return {name:n.name,kind:n.kind};if(n.type==="file"||n.type==="directory"||n.type==="symlink"||n.type==="other")return {name:n.name,kind:n.type};let t=n.isDirectory;if(typeof t=="function"&&t.call(e))return {name:n.name,kind:"directory"};let i=n.isSymbolicLink;if(typeof i=="function"&&i.call(e))return {name:n.name,kind:"symlink"};let r=n.isFile;return typeof r=="function"&&r.call(e)?{name:n.name,kind:"file"}:{name:n.name,kind:"other"}}function Od(e){if(e instanceof Uint8Array)return new Uint8Array(e);if(e instanceof ArrayBuffer)return new Uint8Array(e.slice(0));if(Array.isArray(e)&&e.every(n=>Number.isInteger(n)&&n>=0&&n<=255))return Uint8Array.from(e);throw new TypeError("filesystem port returned an invalid byte array")}function Ld(e){return bd.decode(e)}function Rd(e){return JSON.parse(Ld(e))}function ur(e){switch(e){case "ENOENT":return "NOT_FOUND";case "ELOOP":case "EXDEV":return "PATH_ESCAPED";case "EFBIG":case "EOVERFLOW":return "LIMIT_EXCEEDED";case "EACCES":case "EPERM":case "ENOTDIR":return "READ_DENIED";default:return e}}function Ud(e){if(e instanceof _)return ur(e.code);if(e!==null&&typeof e=="object"&&"code"in e){let n=e.code;if(typeof n=="string")return ur(n)}}function Oe(e,n){let t=n();return Number.isFinite(t)&&Number.isFinite(e)&&t-e<=5e3}function Cd(e){if(typeof e.readVerifiedFile=="function")return e.readVerifiedFile;if(typeof e.readFileVerified=="function")return e.readFileVerified}function wd(e){if(typeof e.listDirectory=="function")return e.listDirectory;if(typeof e.readDirectory=="function")return e.readDirectory;if(typeof e.readdir=="function")return e.readdir}async function fr(e,n,t,i){let r=Cd(e);if(!r)throw new _("READ_DENIED");return Od(await r.call(e,n,t,i))}async function yi(e,n,t){let i=wd(e);if(!i)throw new _("READ_DENIED");let r=await i.call(e,n,t);if(!Array.isArray(r))throw new _("READ_DENIED");return r.map(Md).filter(o=>o!==null)}function kd(e,n,t,i){return Object.freeze({code:e,...{},source:n,relativePath:t})}function xd(e){if(!Tn(e))throw new TypeError("productBundle.reservedIds must be an object with appIds and definitionIds arrays");try{let n=Reflect.ownKeys(e);if(n.length!==2||!n.includes("appIds")||!n.includes("definitionIds"))throw new TypeError("productBundle.reservedIds must contain exactly appIds and definitionIds");let t=(i,r)=>{if(!Array.isArray(i))throw new TypeError("productBundle.reservedIds."+r+" must be an array");let o=[];for(let a=0;a<i.length;a+=1){let s=i[a];if(typeof s!="string"||s.length===0)throw new TypeError("productBundle.reservedIds."+r+" must contain non-empty strings");o.push(s);}return Object.freeze([...new Set(o)].sort(Ve))};return Object.freeze({appIds:t(e.appIds,"appIds"),definitionIds:t(e.definitionIds,"definitionIds")})}catch(n){throw n instanceof TypeError?n:new TypeError("productBundle.reservedIds must be a valid reservation object")}}function jd(e,n){return e.appIds.length===n.appIds.length&&e.appIds.every((t,i)=>t===n.appIds[i])&&e.definitionIds.length===n.definitionIds.length&&e.definitionIds.every((t,i)=>t===n.definitionIds[i])}function Nn(e){return Object.freeze({appIds:Object.freeze([...new Set(e.map(n=>n.appId))].sort(Ve)),definitionIds:Object.freeze([...new Set(e.map(n=>n.definition.id))].sort(Ve))})}function ot(e,n){let t=Object.keys(e).sort(Ve),i=[...n].sort(Ve);return t.length===i.length&&t.every((r,o)=>r===i[o])}function yr(e){if(typeof e!="string"||e.length===0||e.startsWith("/")||/[\\\u0000]/.test(e))return;let n=e.split("/");if(!n.some(t=>t.length===0||t==="."||t===".."))return n}function vd(e){let n;try{n=Rd(e);}catch{return}if(!Tn(n)||!ot(n,["version","packages"])||n.version!==1||!Array.isArray(n.packages)||n.packages.length>Ai)return;let t=new Set,i=new Set,r=0,o=[];for(let a of n.packages){if(!Tn(a))return;let s=["packageDir","appId","definition","files"],c=Object.hasOwn(a,"lineage"),d=Object.hasOwn(a,"launcher"),l=[...c?["lineage"]:[],...d?["launcher"]:[]];if(!ot(a,[...s,...l])||d&&a.launcher!==false)return;let u=yr(a.packageDir),f=lr(a.appId);if(!u||u.length!==2||u[0]!=="apps"||!Sd(u[1])||!f||t.has(a.packageDir)||!Tn(a.definition)||!ot(a.definition,["id","version","hash"]))return;let A=lr(a.definition.id),I=a.definition.version,h=a.definition.hash;if(!A||!Number.isSafeInteger(I)||I<1||typeof h!="string"||!fi.test(h)||!Array.isArray(a.files)||a.files.length<2||a.files.length>Ii)return;let T=new Set,J=[];for(let v of a.files){if(!Tn(v)||!ot(v,["path","sha256"]))return;let b=yr(v.path);if(!b||typeof v.sha256!="string"||!fi.test(v.sha256))return;let U=b.join("/"),W=`${a.packageDir}/${U}`;if(T.has(U)||i.has(W))return;T.add(U),i.add(W),J.push(Object.freeze({path:U,sha256:v.sha256}));}if(!ye.some(v=>T.has(v))||!T.has("ui/index.html")||(r+=J.length,r>Td))return;t.add(a.packageDir),o.push(Object.freeze({packageDir:a.packageDir,...d?{launcher:false}:{},appId:f,definition:Object.freeze({id:A,version:I,hash:h}),lineage:Array.isArray(a.lineage)?a.lineage:[],files:Object.freeze(J.sort((v,b)=>Ve(v.path,b.path)))}));}return Object.freeze({version:1,packages:Object.freeze(o)})}function ve(e){let n=Ud(e);return n==="PATH_ESCAPED"||n==="IDENTITY_CHANGED"||n==="TOCTOU"?"PATH_ESCAPED":n==="LIMIT_EXCEEDED"?"LIMIT_EXCEEDED":"BUNDLE_INTEGRITY"}async function Vd(e,n,t,i,r){let o=[],a=async(s,c)=>{if(!Oe(i,r))throw new _("LIMIT_EXCEEDED");if(c>2)throw new _("LIMIT_EXCEEDED");let d=await yi(e,n,s);for(let l of d){if(typeof l.name!="string"||l.name.length===0||l.name==="."||l.name===".."||/[\\/\u0000]/.test(l.name))throw new _("PATH_ESCAPED");let u=`${s}/${l.name}`;if(l.kind==="file"){if(o.push(u.slice(t.length+1)),o.length>Ii)throw new _("LIMIT_EXCEEDED")}else if(l.kind==="directory")await a(u,c+1);else throw l.kind==="symlink"?new _("PATH_ESCAPED"):new _("READ_DENIED")}};return await a(t,0),o.sort(Ve)}function Fd(e){return ye.includes(e)?262144:e==="ui/index.html"?qe:e==="ui/state.json"?2097152:e.startsWith("ui/assets/")?Dd:Nd}async function Ar(e,n,t,i){if(e===void 0)return {packages:[],diagnostics:[],incomplete:false,reservedIds:Pd};let r=xd(e.reservedIds),o=[],a=(y,m,D)=>kd(y,"bundled",m),s=(y=[],m=false,D)=>({...D===void 0?{}:{indexHash:D},packages:y,diagnostics:o,incomplete:m,reservedIds:r});if(typeof e.root!="string"||e.root.length===0||typeof e.expectedIndexHash!="string"||!fi.test(e.expectedIndexHash))return o.push(a("BUNDLE_INTEGRITY","bundle-index.json")),s();let c;try{c=await fr(n,e.root,"bundle-index.json",Ed);}catch(y){return o.push(a(ve(y),"bundle-index.json")),s()}let d=createHash("sha256").update(c).digest("hex");if(d!==e.expectedIndexHash)return o.push(a("BUNDLE_INTEGRITY","bundle-index.json")),s();let l=vd(c);if(l===void 0)return o.push(a("BUNDLE_INTEGRITY","bundle-index.json")),s();if(!jd(Nn(l.packages),r))return o.push(a("BUNDLE_INTEGRITY","bundle-index.json")),s([],false,d);if(!Oe(t,i))return o.push(a("LIMIT_EXCEEDED","bundle-index.json")),s(l.packages.map(y=>({indexEntry:y,failureCode:"LIMIT_EXCEEDED"})),true,d);let u;try{u=await yi(n,e.root,"");}catch(y){return o.push(a(ve(y),"bundle-index.json")),s(l.packages.map(m=>({indexEntry:m,failureCode:ve(y)})),false,d)}if(!Oe(t,i))return o.push(a("LIMIT_EXCEEDED","bundle-index.json")),s(l.packages.map(y=>({indexEntry:y,failureCode:"LIMIT_EXCEEDED"})),true,d);let f=u.find(y=>y.name==="bundle-index.json"&&y.kind==="file"),A=u.find(y=>y.name==="apps"&&y.kind==="directory"),I=y=>l.packages.map(m=>({indexEntry:m,failureCode:y}));if(!f)return o.push(a("BUNDLE_INTEGRITY","bundle-index.json")),s(I("BUNDLE_INTEGRITY"),false,d);let h=u.filter(y=>y.name!=="bundle-index.json"&&y.name!=="apps");if(h.length>0){let y=h.some(m=>m.kind==="symlink")?"PATH_ESCAPED":"BUNDLE_INTEGRITY";return o.push(a(y,"bundle-index.json")),s(I("BUNDLE_INTEGRITY"),false,d)}if(u.some(y=>y.name==="apps"&&y.kind!=="directory"))return o.push(a("PATH_ESCAPED","apps")),s(I("PATH_ESCAPED"),false,d);let T=[];if(A)try{T=await yi(n,e.root,"apps");}catch(y){return o.push(a(ve(y),"apps")),s(I(ve(y)),false,d)}if(!Oe(t,i)||T.length>Ai)return o.push(a("LIMIT_EXCEEDED","apps")),s(I("LIMIT_EXCEEDED"),true,d);let J=new Map(l.packages.map(y=>[y.packageDir.slice(5),y])),v=T.filter(y=>!J.has(y.name));for(let y of v)o.push(a(y.kind==="symlink"?"PATH_ESCAPED":"BUNDLE_INTEGRITY",`apps/${y.name}`));if(v.length>0){let y=v.some(m=>m.kind==="symlink")?"PATH_ESCAPED":"BUNDLE_INTEGRITY";return s(I(y),false,d)}let b=new Set,U=new Map,W=new Map;for(let y of l.packages){let m=U.get(y.appId)??[];m.push(y),U.set(y.appId,m);let D=`${y.definition.id}\0${String(y.definition.version)}`,O=W.get(D)??[];O.push(y),W.set(D,O);}for(let y of [...U.values(),...W.values()])if(y.length>1)for(let m of y)b.add(m);let N=[],M=c.byteLength,S=false;for(let y of l.packages){if(!Oe(t,i)){S=true,N.push({indexEntry:y,failureCode:"LIMIT_EXCEEDED"});continue}let m;try{let k=y.lineage[y.lineage.length-1];if(!k)throw new be("LINEAGE_INVALID","Definition lineage is missing");if(k.definition.id!==y.definition.id||k.version!==y.definition.version||k.hash!==y.definition.hash)throw new be("LINEAGE_STALE","Last lineage generation does not match bundle identity");m=qt(y.lineage,{...k.definition,hash:k.hash}).entries;}catch(k){let R=k instanceof be?k.code:"LINEAGE_INVALID";o.push(a(R,y.packageDir)),N.push({indexEntry:y,failureCode:R});continue}let D=T.find(k=>k.name===y.packageDir.slice(5));if(!A||!D){N.push({indexEntry:y,failureCode:"BUNDLE_INTEGRITY"});continue}if(D.kind!=="directory"){N.push({indexEntry:y,failureCode:D.kind==="symlink"?"PATH_ESCAPED":"BUNDLE_INTEGRITY"});continue}let O;try{let k=await Vd(n,e.root,y.packageDir,t,i);if(!Oe(t,i)){S=!0,N.push({indexEntry:y,failureCode:"LIMIT_EXCEEDED"});continue}let R=y.files.map(H=>H.path);if(k.length!==R.length||k.some((H,ie)=>H!==R[ie])){N.push({indexEntry:y,failureCode:"BUNDLE_INTEGRITY"});continue}O=new Map;let B;for(let H of y.files){if(!Oe(t,i)){B="LIMIT_EXCEEDED",S=!0;break}if(M>=ui){B="LIMIT_EXCEEDED";break}let ie;try{ie=await fr(n,e.root,`${y.packageDir}/${H.path}`,Fd(H.path));}catch(re){B=ve(re);break}if(!Oe(t,i)){B="LIMIT_EXCEEDED",S=!0;break}if(M+ie.byteLength>ui){M=ui,B="LIMIT_EXCEEDED";break}if(M+=ie.byteLength,createHash("sha256").update(ie).digest("hex")!==H.sha256){B="BUNDLE_INTEGRITY";break}O.set(H.path,ie);}if(B!==void 0){N.push({indexEntry:y,failureCode:B});continue}}catch(k){Oe(t,i)||(S=true),N.push({indexEntry:y,failureCode:ve(k)});continue}N.push({indexEntry:y,lineage:m,files:O,...b.has(y)?{failureCode:"DUPLICATE_ID"}:{}});}return s(N,S,d)}var Ed,Ai,Ii,Td,Nd,Dd,ui,fi,bd,Pd,gi=C(()=>{g();Zt();we();$t();Zn();li();Ed=256*1024,Ai=64,Ii=128,Td=Ai*Ii,Nd=2*1024*1024,Dd=8*1024*1024,ui=32*1024*1024,fi=/^[0-9a-f]{64}$/,bd=new TextDecoder("utf-8",{fatal:true}),Pd=Object.freeze({appIds:Object.freeze([]),definitionIds:Object.freeze([])});});var vr={};Wr(vr,{AppDiscoveryFsError:()=>_,LOCAL_APP_TOOL_PREFIX:()=>zd,MCP_APP_WORKSPACE_TOOL_PREFIX:()=>Gd,NodeAppDiscoveryFs:()=>en,NodeAppDiscoveryFsAdapter:()=>dr,WORKSPACE_APP_TOOL_PREFIX:()=>nn,createWorkspaceAppScanCache:()=>tr,defaultAppDiscoveryFs:()=>it,defaultNodeAppDiscoveryFs:()=>cr,deriveWorkspaceAppToolName:()=>Jd,deriveWorkspaceAppToolNames:()=>_i,discoverWorkspaceAppCandidates:()=>_p,discoverWorkspaceApps:()=>Ei,isWorkspacePackage:()=>Hd,productAppBundleReservations:()=>Nn,scanWorkspaceApps:()=>Ep});function Hd(e,n){let t=n.split("/");return t.length===2&&t[0]===e&&/^[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(t[1])}function _i(e){if(typeof e!="string"||!_e.test(e))throw new TypeError("pluginId must be a safe UI plugin identifier");let n=`${nn}${e}`.length+7<=128?e:`hash_${createHash("sha256").update(e,"utf8").digest("hex")}`;return {read:`${nn}${n}_read`,action:`${nn}${n}_action`}}function Jd(e,n="read"){let t=_i(e);return n==="read"?t.read:t.action}function gr(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;try{let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}catch{return false}}function Wd(e,n){return n.length===0||n==="."||n===".."||/[\\/\u0000]/.test(n)?e==="skills"?"skills":"apps":`${e==="skills"?"skills":"apps"}/${n}`}function Xd(e){return e.length>0&&e!=="."&&e!==".."&&!/[\\/\u0000]/.test(e)}function bn(e,n){let t=new TextEncoder().encode(e),i=new TextEncoder().encode(n),r=Math.min(t.byteLength,i.byteLength);for(let o=0;o<r;o+=1){let a=t[o]-i[o];if(a!==0)return a}return t.byteLength-i.byteLength}function Mr(e){if(typeof e=="string")return {name:e,kind:"directory"};if(e===null||typeof e!="object")return null;let n=e;if(typeof n.name!="string")return null;if(n.kind==="file"||n.kind==="directory"||n.kind==="symlink"||n.kind==="other")return {name:n.name,kind:n.kind};if(n.type==="file"||n.type==="directory"||n.type==="symlink"||n.type==="other")return {name:n.name,kind:n.type};let t=n.isDirectory;if(typeof t=="function"&&t.call(e))return {name:n.name,kind:"directory"};let i=n.isSymbolicLink;if(typeof i=="function"&&i.call(e))return {name:n.name,kind:"symlink"};let r=n.isFile;return typeof r=="function"&&r.call(e)?{name:n.name,kind:"file"}:{name:n.name,kind:"other"}}function Kd(e){if(e instanceof Uint8Array)return new Uint8Array(e);if(e instanceof ArrayBuffer)return new Uint8Array(e.slice(0));if(Array.isArray(e)&&e.every(n=>Number.isInteger(n)&&n>=0&&n<=255))return Uint8Array.from(e);throw new TypeError("filesystem port returned an invalid byte array")}function Or(e){return $d.decode(e)}function Yd(e){return JSON.parse(Or(e))}function qd(e){if(e===void 0)return;let n=e.definitionId!==void 0&&e.definitionVersion!==void 0?`${e.definitionId}\0${String(e.definitionVersion)}`:void 0;return {pluginId:e.pluginId,...n===void 0?{}:{definitionKey:n}}}function rt(e,n,t,i,r){let o={code:e,...i===void 0?{}:{pluginId:i},source:n,relativePath:t,...r?.reason===void 0?{}:{reason:Object.freeze({...r.reason})},...r?.files===void 0?{}:{files:Object.freeze([...r.files])}};return Object.freeze(o)}function mr(e){switch(e){case "ENOENT":return "NOT_FOUND";case "ELOOP":case "EXDEV":return "PATH_ESCAPED";case "EFBIG":case "EOVERFLOW":return "LIMIT_EXCEEDED";case "EACCES":case "EPERM":case "ENOTDIR":return "READ_DENIED";default:return e}}function te(e){if(e instanceof _)return mr(e.code);if(e!==null&&typeof e=="object"&&"code"in e){let n=e.code;if(typeof n=="string")return mr(n)}}function Be(e,n){return e==="PATH_ESCAPED"||e==="IDENTITY_CHANGED"||e==="TOCTOU"?"PATH_ESCAPED":e==="LIMIT_EXCEEDED"?"LIMIT_EXCEEDED":n==="manifest"&&e==="NOT_FOUND"?"MANIFEST_MISSING":n==="entry"?"ENTRY_INVALID":n==="initial"?"INITIAL_STATE_INVALID":"MANIFEST_INVALID"}function hr(e){return {reason:e.reason,...e.code==="MANIFEST_DUAL_MISMATCH"?{files:e.files}:{}}}function _r(e){return e==="MANIFEST_DUAL_MISMATCH"?e:Lr(e)}function Zd(e){return Lr(e.code)}function Lr(e){switch(e){case "MANIFEST_INVALID":case "PRIMITIVE_UNKNOWN":case "PRIMITIVE_SET_UNSUPPORTED":case "SCHEMA_TYPE_UNSUPPORTED":case "TOKEN_INVALID":case "UNSAFE_VALUE":return "MANIFEST_INVALID";case "LIMIT_EXCEEDED":return "LIMIT_EXCEEDED";case "INITIAL_STATE_INVALID":return "INITIAL_STATE_INVALID";default:return Rr("UiPluginValidationError",e)}}function Rr(e,n){throw new Error(`Unmapped ${e} code: ${String(n)}`)}function Ur(e){switch(e){case "APP_ID_INVALID":case "TOOL_ID_INVALID":case "RESOURCE_URI_INVALID":case "TOOL_INVALID":case "SERIALIZATION_INVALID":return "MANIFEST_INVALID";case "APP_ID_CONFLICT":case "TOOL_ID_CONFLICT":return "DUPLICATE_ID";case "RESOURCE_NOT_FOUND":case "HTML_INVALID":return "ENTRY_INVALID";case "STATE_INVALID":case "STATE_PROJECTION_INVALID":case "BUTTON_INVALID":return "INITIAL_STATE_INVALID";default:return Rr("McpAppContractError",e)}}function Le(e,n){let t=n();return Number.isFinite(t)&&Number.isFinite(e)&&t-e<=5e3}function Qd(e){return {pluginId:e.appId,definitionKey:`${e.definition.id}\0${String(e.definition.version)}`}}function ep(e,n){let t=n.get("package.json");if(t!==void 0)try{let r=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(t));if(gr(r)){let o=r.bin,a=typeof o=="string"?o:gr(o)?Object.values(o).find(s=>typeof s=="string"):void 0;for(let s of [a,r.main]){if(typeof s!="string")continue;let c=np(s);if(c&&n.has(c))return c}}}catch{}return [`${e.slice(e.lastIndexOf("/")+1)}.js`,"index.js","main.js"].find(r=>n.has(r))}function np(e){if(e.startsWith("/")||e.includes("\\")||e.includes("\0"))return;let n=e.split("/").filter(t=>t!==".");if(!(n.length===0||n.some(t=>t.length===0||t==="..")))return n.join("/")}function tp(){return globalThis.performance?.now()??Date.now()}function Fe(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let n of Object.values(e))Fe(n);return Object.freeze(e)}function Er(e){return Object.freeze(Array.from(e))}async function Pn(e,n,t,i){if(n.pinnedFiles!==void 0){let s=n.pinnedFiles.get(t);if(s===void 0)throw new _("NOT_FOUND");if(s.byteLength>i)throw new _("LIMIT_EXCEEDED");return new Uint8Array(s)}let r=`${n.relativePath}/${t}`,o=n.scanContext,a=e.fingerprintVerifiedFile;if(o===void 0||!o.cacheable||typeof a!="function")return br(e,n.root,r,i);try{let s=o.priorFingerprints.get(r)??await a.call(e,o.workspaceRoot,r,i);o.candidateRealPath=s.candidateRealPath;let c=await br(e,n.root,r,i),d=await a.call(e,o.workspaceRoot,r,i);return o.candidateRealPath=d.candidateRealPath,wr(s,d)&&d.size===BigInt(c.byteLength)&&!kr(d,o.scanStartedAtNs)?o.files.set(r,{relativePath:r,byteLimit:i,fingerprint:d}):o.cacheable=!1,c}catch(s){let c=!t.includes("/")&&te(s)==="NOT_FOUND"&&o.directoryListings.some(l=>l.relativePath===n.relativePath&&!st(l.key,t)),d=t===q&&te(s)==="NOT_FOUND"&&op(o.directoryListings,n.relativePath);throw !c&&!d&&(o.cacheable=false),s}}async function ip(e,n,t){if(n.pinnedFiles!==void 0)return {iconDiagnostics:[]};let i=await Xt(t,async o=>{try{return await Pn(e,n,o,262144)}catch(a){let s=te(a);return s==="NOT_FOUND"?"missing":s==="LIMIT_EXCEEDED"?"too-large":"bad-path"}}),r=i.file;return {...r===void 0?{}:{iconFile:{path:r.path,sha256:createHash("sha256").update(r.bytes).digest("hex"),contentType:r.contentType,byteLength:r.byteLength}},iconDiagnostics:i.diagnostics}}function op(e,n){let t=e.find(r=>r.relativePath===n);if(t===void 0)return false;if(!st(t.key,"dist"))return true;let i=e.find(r=>r.relativePath===`${n}/dist`);return i!==void 0&&!st(i.key,"tools.json")}function Cr(e,n){return JSON.stringify([e.realPath,n.source,n.relativePath])}async function sp(e,n,t,i,r,o,a,s){let c=e.fingerprintVerifiedFile,d=Cr(t,i),l=r.candidates.get(d),u=i.relativePath,f;try{f=await Dr(e,n,u);}catch(S){if(te(S)!=="NOT_FOUND")throw S}let A=f===void 0?void 0:{relativePath:u,key:f};if(A!==void 0&&(i.source==="apps"||i.source==="skills")&&!ye.some(S=>st(A.key,S)))return Le(a,s)?l!==void 0&&l.candidate===void 0&&l.candidateRealPath===void 0&&l.files.length===0&&l.directoryListings.length===1&&l.directoryListings[0]?.relativePath===A.relativePath&&l.directoryListings[0]?.key===A.key&&(i.source==="apps"?l.diagnostic?.code==="MANIFEST_MISSING":l.diagnostic===void 0)&&typeof c=="function"?{memo:l}:typeof c!="function"?{}:{context:{state:r,cacheKey:d,workspaceRoot:n,scanStartedAtNs:o,directoryListings:Object.freeze([A]),priorFingerprints:new Map,files:new Map,cacheable:true}}:{timeLimitReached:true};let I=async S=>{if(S==="")return A;let y=`${i.relativePath}${S}`;try{let m=await Dr(e,n,y);return m===void 0?void 0:{relativePath:y,key:m}}catch(m){if(te(m)==="NOT_FOUND")return;throw m}},h=await Promise.all(Tr.map(I)),T=await Promise.all(rp.map(I));if(!Le(a,s))return {timeLimitReached:true};let J=typeof c=="function"&&h.every(S=>S!==void 0),v=h.filter(S=>S!==void 0),b=[...v,...T.filter(S=>S!==void 0)],U=new Map,W=l!==void 0&&J,N;if(l!==void 0&&typeof c=="function"){let S=await Promise.all(l.files.map(async y=>{if(!Le(a,s))return {kind:"time",file:y};try{let m=await c.call(e,n,y.relativePath,y.byteLimit);return {kind:"fingerprint",file:y,current:m}}catch(m){return te(m)==="NOT_FOUND"?{kind:"missing",file:y}:{kind:"error",file:y,error:m}}}));if(S.some(y=>y.kind==="time"))return {timeLimitReached:true};for(let y of S){if(y.kind==="error")throw y.error;if(y.kind==="missing"){W=false;continue}if(y.kind!=="fingerprint")continue;let{file:m,current:D}=y;U.set(m.relativePath,D),N??=D.candidateRealPath,(D.candidateRealPath!==l.candidateRealPath||!wr(D,m.fingerprint)||kr(D,o))&&(W=false);}}let M=l!==void 0&&l.directoryListings.length===b.length&&l.directoryListings.every((S,y)=>S.relativePath===b[y]?.relativePath&&S.key===b[y]?.key);return l!==void 0&&J&&M&&W&&N===l.candidateRealPath?{memo:l}:!J||v.length!==Tr.length?{}:{context:{state:r,cacheKey:d,workspaceRoot:n,scanStartedAtNs:o,directoryListings:Object.freeze(b),priorFingerprints:U,files:new Map,...N===void 0?{}:{candidateRealPath:N},cacheable:true}}}function st(e,n){try{let t=JSON.parse(e);return Array.isArray(t)&&t.some(i=>Array.isArray(i)&&i[0]===n)}catch{return true}}async function Dr(e,n,t){let i=xr(e);if(typeof i!="function")return;let r=await i.call(e,n,t);if(!Array.isArray(r)||r.some(a=>typeof a=="string"))return;let o=r.map(Mr);if(!o.some(a=>a===null))return JSON.stringify(o.slice().sort((a,s)=>bn(a.name,s.name)||bn(a.kind,s.kind)).map(a=>[a.name,a.kind]))}function wr(e,n){return e.dev===n.dev&&e.ino===n.ino&&e.size===n.size&&e.mtimeNs===n.mtimeNs&&e.ctimeNs===n.ctimeNs}function kr(e,n){let t=e.mtimeNs-n;return t>=-Nr&&t<=Nr}function mi(e){let n=e.scanContext,t=e.source==="skills"&&e.candidate===void 0&&e.diagnostic===void 0&&n?.files.size===0,i=e.source==="apps"&&e.candidate===void 0&&e.diagnostic?.code==="MANIFEST_MISSING"&&n?.files.size===0,r=t||i;if(n===void 0||!n.cacheable||n.candidateRealPath===void 0&&!r||n.files.size===0&&!r)return;let o=Object.freeze({...!r&&n.candidateRealPath!==void 0?{candidateRealPath:n.candidateRealPath}:{},directoryListings:n.directoryListings,files:Object.freeze([...n.files.values()]),...e.candidate===void 0?{}:{candidate:e.candidate},...e.diagnostic===void 0?{}:{diagnostic:e.diagnostic},...e.identity===void 0?{}:{identity:e.identity},...e.provenance===void 0?{}:{provenance:e.provenance}});n.state.candidates.set(n.cacheKey,o);}function ap(e,n,t){let i=createHash("sha256"),r=new TextEncoder().encode(Q(e)),o=a=>{let s=new Uint8Array(8);new DataView(s.buffer).setBigUint64(0,BigInt(a)),i.update(s);};return o(r.byteLength),i.update(r),o(n.byteLength),i.update(n),o(t.byteLength),i.update(t),i.digest("hex")}function cp(e,n){let t={...e.definition,sourceHash:n},i;try{i=se(t);}catch(o){throw o instanceof L&&o.code==="INPUT_INVALID"?new ae("MANIFEST_INVALID","normalized definition is invalid"):o}let r={...t,hash:i};try{ue(r);}catch{throw new ae("MANIFEST_INVALID","normalized definition is invalid")}return r}function dp(e,n){return e.actions.some(t=>t.backend.type==="core"&&t.backend.handler!=="state.set"&&!$n(n,t.backend))}function pp(e){if(typeof e.readVerifiedFile=="function")return e.readVerifiedFile;if(typeof e.readFileVerified=="function")return e.readFileVerified}function xr(e){if(typeof e.listDirectory=="function")return e.listDirectory;if(typeof e.readDirectory=="function")return e.readDirectory;if(typeof e.readdir=="function")return e.readdir}async function br(e,n,t,i){let r=pp(e);if(!r)throw new _("READ_DENIED");return Kd(await r.call(e,n,t,i))}async function lp(e,n,t){let i=xr(e);if(!i)throw new _("READ_DENIED");let r=await i.call(e,n,t);if(!Array.isArray(r))throw new _("READ_DENIED");return r.map(Mr).filter(o=>o!==null)}function up(e){let n=[];for(let t of [e.reserved,e.builtin])t&&n.push(t);return e.builtins&&"listMcpApps"in e.builtins?n.push(Pr(e.builtins)):e.builtins&&n.push(e.builtins),e.builtinCatalog&&n.push(Pr(e.builtinCatalog)),n.push({...e.reservedAppIds===void 0?{}:{appIds:e.reservedAppIds},...e.reservedDefinitionIds===void 0?{}:{definitionIds:e.reservedDefinitionIds},...e.reservedToolNames===void 0?{}:{toolNames:e.reservedToolNames}}),n}function Pr(e){let n=[],t=[],i=[];for(let r of e.listMcpApps())typeof r.appId=="string"&&n.push(r.appId),r.definition&&typeof r.definition.id=="string"&&t.push(r.definition.id);for(let r of e.listMcpAppTools())typeof r.name=="string"&&i.push(r.name);return {appIds:n,definitionIds:t,toolNames:i}}function me(e,n){e.diagnostic||(e.diagnostic=rt(n,e.source,e.relativePath,e.identity?.pluginId));}function fp(e,n){let t=new Set,i=new Map;for(let o of e){let a=o.identity?.pluginId;if(a===void 0)continue;let s=i.get(a)??[];s.push(o),i.set(a,s);}for(let o of i.values()){if(o.length<2)continue;let a=o.filter(c=>c.provenance!==void 0);if(a.length>0){let c=o.find(d=>n.has(d));if(c){for(let d of a)t.add(d);for(let d of o)d!==c&&d.provenance===void 0&&me(d,"RESERVED_ID");continue}for(let d of o)d.provenance===void 0&&me(d,"RESERVED_ID");if(a.length>1)for(let d of a)me(d,"DUPLICATE_ID");continue}let s=o.filter(c=>c.source==="apps");if(s.length>1){for(let c of s)me(c,"DUPLICATE_ID");for(let c of o.filter(d=>d.source==="skills"))me(c,"DUPLICATE_ID");}else for(let c of o.filter(d=>d.source==="skills"))me(c,"DUPLICATE_ID");}let r=new Map;for(let o of e){if(o.diagnostic?.code==="RESERVED_ID"||t.has(o)||o.provenance===void 0&&!n.has(o)&&i.get(o.identity?.pluginId??"")?.some(c=>c.provenance!==void 0))continue;let a=o.identity?.definitionKey;if(a===void 0)continue;let s=r.get(a)??[];s.push(o),r.set(a,s);}for(let o of r.values())if(o.length>1)for(let a of o)me(a,"DUPLICATE_ID");return t}function yp(e,n,t){let i=new Set,r=new Set,o=new Set,a=new Set([...t.appIds,...n.productBundleReservationMetadata?.reservedAppIds??[]]),s=new Set([...t.definitionIds,...n.productBundleReservationMetadata?.reservedDefinitionIds??[]]);for(let l of up(n)){for(let u of l.appIds??[])typeof u=="string"&&i.add(u);for(let u of l.definitionIds??[])typeof u=="string"&&r.add(u);for(let u of l.toolNames??[])typeof u=="string"&&o.add(u);}for(let l of e){let u=l.candidate;if(!u)continue;if(i.has(u.pluginId)||r.has(u.definitionId)){me(l,"RESERVED_ID");continue}[u.toolNames.read,u.toolNames.action].filter(A=>A!==void 0).some(A=>o.has(A))&&me(l,"DUPLICATE_ID");}let c=[...e.filter(l=>l.provenance!==void 0&&l.diagnostic===void 0).flatMap(l=>l.candidate?[l.candidate]:[]),...(n.productBundleReservationMetadata?.candidates??[]).filter(l=>n.productBundleReservationMetadata?.indexHash!==void 0&&l.provenance?.indexHash===n.productBundleReservationMetadata.indexHash)],d=new Set;for(let l of e){let u=l.candidate;if(!(!u||l.diagnostic||l.source!=="apps"||l.provenance!==void 0)&&e.filter(f=>f.source==="apps"&&f.identity?.pluginId===u.pluginId).length===1&&c.some(f=>f.pluginId===u.pluginId)&&!(s.has(u.definitionId)&&!c.some(f=>f.pluginId===u.pluginId&&f.definitionId===u.definitionId))&&!c.some(f=>f.pluginId!==u.pluginId&&f.definitionId===u.definitionId)&&!e.some(f=>f.identity?.pluginId!==u.pluginId&&f.identity?.definitionKey===`${u.definitionId}\0${u.version}`&&f.diagnostic?.code!=="RESERVED_ID"))try{er(u),d.add(l);}catch(f){me(l,f instanceof De?Ur(f.code):"EXEC_DENIED");}}for(let l of e){let u=l.candidate;u&&l.provenance===void 0&&!d.has(l)&&(a.has(u.pluginId)||s.has(u.definitionId))&&me(l,"RESERVED_ID");}return d}function Ap(e){return [...e].sort((n,t)=>{let i=Ir.indexOf(n.source)-Ir.indexOf(t.source);return i!==0?i:bn(n.relativePath,t.relativePath)})}function V(e,n,t){e.diagnostic=rt(n,e.source,e.relativePath,e.identity?.pluginId,t);}async function Sr(e,n,t){let i=Jt(t,{mode:"local"});if(!i.ok&&i.parseFailure){V(n,_r(i.rejection.code),hr(i.rejection));return}let r=qd(i.identity);if(n.bundleIdentity===void 0)n.identity=r;else if(r?.pluginId!==n.bundleIdentity.appId||r.definitionKey!==`${n.bundleIdentity.definitionId}\0${String(n.bundleIdentity.version)}`){V(n,"BUNDLE_INTEGRITY");return}if(!i.ok&&i.builtinOnly){V(n,"RESERVED_ID");return}if(!i.ok){V(n,_r(i.rejection.code),hr(i.rejection));return}let o=i.manifest,a={pluginId:o.pluginId,definitionKey:`${o.definitionId}\0${String(o.version)}`};if(n.bundleIdentity===void 0&&(n.identity=a),o.actions.length>0)try{ti(o.actions.map(R=>({actionId:R.actionId,inputSchema:R.inputSchema})));}catch(R){if(R instanceof De){V(n,Ur(R.code));return}throw R}let s;try{s=await Pn(e,n,"ui/index.html",qe);}catch(R){V(n,Be(te(R),"entry"));return}if(s.byteLength>qe){V(n,"LIMIT_EXCEEDED");return}let c;try{c=Or(s);}catch{V(n,"ENTRY_INVALID");return}if(s.byteLength===0||c.length===0){V(n,"ENTRY_INVALID");return}let d=createHash("sha256").update(s).digest("hex");if(o.entryHash!==void 0&&o.entryHash!==d){V(n,"ENTRY_INVALID");return}let l={},u,f;if(o.initialState!==void 0){try{u=await Pn(e,n,"ui/state.json",2097152);}catch(R){V(n,Be(te(R),"initial"));return}if(u.byteLength>2097152){V(n,"LIMIT_EXCEEDED");return}try{let R=Yd(u),B=o.dataPaths??[],H=xt(R,B);l=le(H,0,B),Ge(l);}catch{V(n,"INITIAL_STATE_INVALID");return}if(f=createHash("sha256").update(u).digest("hex"),o.initialState.hash!==void 0&&o.initialState.hash!==f){V(n,"INITIAL_STATE_INVALID");return}}let A={...o,entryHash:d,...o.initialState===void 0?{}:{initialState:{path:"ui/state.json",hash:f}}},I=dn(A),h=ap(A,s,u??new Uint8Array),T;try{T=cp(I,h);}catch(R){if(R instanceof ae){V(n,Zd(R));return}throw R}let J;if(n.bundleLineage!==void 0){let R=n.bundleLineage[n.bundleLineage.length-1];if(!R){V(n,"LINEAGE_INVALID");return}let{legacy:B,...H}=R.definition,{hash:ie,...re}=T;if(Q(H)!==Q(re)){V(n,"LINEAGE_STALE");return}if(B!==void 0&&(T={...T,legacy:B}),B!==void 0)try{T={...T,hash:se(T)},ue(T);}catch{V(n,"LINEAGE_INVALID");return}J=n.bundleLineage;}if(n.bundleIdentity!==void 0&&n.bundleIdentity.appId!==o.pluginId){V(n,"BUNDLE_INTEGRITY");return}if(n.bundleIdentity!==void 0&&(n.bundleIdentity.definitionId!==T.id||n.bundleIdentity.version!==T.version||n.bundleIdentity.definitionHash!==T.hash)){V(n,"LINEAGE_STALE");return}let v=await ip(e,n,i.mcpb?.icon),b=_i(o.pluginId),U=o.actions.length===0?{read:b.read}:b,W=Fe(I),N=Fe(A),M=Fe(T),S=Fe({...I.handlers}),y=Er(s),m=u===void 0?void 0:Er(u),D=Object.freeze({...n.provenance===void 0?{}:{provenance:n.provenance},entry:Object.freeze({path:"ui/index.html",hash:d,bytes:y}),...m===void 0?{}:{initialState:Object.freeze({path:"ui/state.json",hash:f,bytes:m})}}),O={appId:o.pluginId,pluginId:o.pluginId,definitionId:o.definitionId,version:o.version,...i.releaseVersion===void 0?{}:{releaseVersion:i.releaseVersion},manifestFile:i.file,...i.mcpb===void 0?{}:{mcpb:Fe(i.mcpb)},relativePath:n.relativePath,manifest:N,normalized:W,name:o.name,description:o.description,...o.icon===void 0?{}:{icon:o.icon},...o.tone===void 0?{}:{tone:o.tone},...v.iconFile===void 0?{}:{iconFile:Object.freeze({...v.iconFile})},...v.iconDiagnostics.length===0?{}:{iconDiagnostics:Object.freeze([...v.iconDiagnostics])},definition:M,handlers:S,resources:D,html:c,entryBytes:y,entryHash:d,initialState:Fe(l),...m===void 0?{}:{initialStateBytes:m},...f===void 0?{}:{initialStateHash:f},sourceHash:h,toolNames:Object.freeze(U)},k=n.provenance===void 0?{...O,source:n.source}:{...O,provenance:n.provenance,lineage:J??[]};n.candidate=Object.freeze(k),dp(o,T.usage)&&V(n,"EXEC_DENIED");}async function jr(e,n){let t={};for(let i of ye)try{t[i]=await Pn(e,n,i,262144);}catch(r){if(te(r)==="NOT_FOUND")continue;return {files:t,failure:Be(te(r),"manifest")}}if(t[Y]!==void 0)try{t[q]=await Pn(e,n,q,262144);}catch(i){if(te(i)!=="NOT_FOUND")return {files:t,failure:Be(te(i),"manifest")}}return {files:t}}function hi(e){return ye.some(n=>e[n]!==void 0)}async function Ip(e,n){let{files:t,failure:i}=await jr(e,n);if(i!==void 0){V(n,i);return}let r=t[Y];return r!==void 0&&!Gt(r)&&(delete t[Y],delete t[q]),hi(t)?t:void 0}function gp(e,n,t,i=Bd,r=false,o=new Set){let a=Ap(e),s=fp(a,o),c=Object.freeze(a.filter(f=>f.candidate!==void 0&&f.diagnostic===void 0&&!s.has(f)).map(f=>f.candidate)),d=Object.freeze(a.filter(f=>f.diagnostic!==void 0).map(f=>f.diagnostic)),l=r?Object.freeze({...t===void 0?{}:{indexHash:t},candidates:Object.freeze(a.filter(f=>f.source==="bundled"&&f.diagnostic===void 0&&t!==void 0&&f.candidate?.provenance?.indexHash===t).map(f=>f.candidate)),diagnostics:Object.freeze(d.filter(f=>f.source==="bundled").map(f=>Object.freeze({...f}))),reservedAppIds:Object.freeze([...i.appIds]),reservedDefinitionIds:Object.freeze([...i.definitionIds])}):void 0,u={apps:c,diagnostics:d,complete:n===void 0,...n===void 0?{}:{incompleteReason:n},...t===void 0?{}:{productBundleIndexHash:t},...l===void 0?{}:{productBundleSnapshotMetadata:l}};return Object.defineProperty(u,"candidates",{configurable:false,enumerable:false,get:()=>c}),Object.freeze(u)}function mp(e){if(e===null||typeof e!="object"&&typeof e!="function")return false;let n=e;return typeof n.readVerifiedFile=="function"||typeof n.readFileVerified=="function"||typeof n.listDirectory=="function"||typeof n.readDirectory=="function"||typeof n.readdir=="function"}function hp(e,n){if(mp(e))return {fs:e,options:n??{}};let t=e??n??{};return {fs:t.filesystem??t.fileSystem??t.fs??it,options:t}}async function Ei(e,n,t){if(typeof e!="string"||e.length===0)throw new TypeError("workspaceRoot must be explicit");let{fs:i,options:r}=hp(n,t),o=r.clock??tp,a=o(),s=await Ar(r.productBundle,i,a,o),c=o(),d=BigInt(Date.now())*1000000n,l=[],u=0,f,A=false,I,h;if(r.scanCache!==void 0&&typeof i.getRootIdentity=="function"&&typeof i.fingerprintVerifiedFile=="function")try{h=await i.getRootIdentity(e),I=ir(r.scanCache,h),I.scanStartedAtNs=d;}catch(N){if(te(N)!=="NOT_FOUND")throw N}let T=I!==void 0&&r.productBundle===void 0&&s.packages.length===0&&s.diagnostics.length===0,J=new Set,v=true;l.push(...s.diagnostics.map(N=>({source:N.source,root:r.productBundle?.root??e,name:"",relativePath:N.relativePath,diagnostic:N})));let b=s.reservedIds;s.incomplete&&(f="time_limit");for(let N of s.packages){if(!Le(c,o)){A=true,f="time_limit";break}let M=N.indexEntry,S=M.packageDir,y=N.files===void 0?void 0:ep(S,N.files),m=s.indexHash===void 0?void 0:Oo(Object.freeze({kind:"bundled",launcher:M.launcher!==false,indexHash:s.indexHash,packageDir:S,appId:M.appId,definitionId:M.definition.id,version:M.definition.version,definitionHash:M.definition.hash,files:M.files}),y),D={source:"bundled",root:r.productBundle?.root??e,name:S.slice(5),relativePath:S,...m===void 0?{}:{provenance:m},...N.files===void 0?{}:{pinnedFiles:N.files},...N.lineage===void 0?{}:{bundleLineage:N.lineage},bundleIdentity:{appId:M.appId,definitionId:M.definition.id,version:M.definition.version,definitionHash:M.definition.hash},identity:Qd(M)};if(l.push(D),u+=1,N.failureCode!==void 0){V(D,N.failureCode);continue}if(N.files?.has(q)===true){V(D,"EXEC_DENIED",{reason:{path:"",rule:"bundled-tool-mode-unsupported",file:q}});continue}let O={};for(let k of ye){let R=N.files?.get(k);R!==void 0&&(O[k]=R);}if(!hi(O)){V(D,"BUNDLE_INTEGRITY");continue}if(await Sr(i,D,O),!Le(c,o)){A=true,f="time_limit";break}}let U=[{source:"apps",directory:"apps"},{source:"skills",directory:"skills"}];e:for(let N of U){let{source:M,directory:S}=N,y;try{y=await lp(i,e,S);}catch(D){if(te(D)==="NOT_FOUND")continue;T=false,v=false,l.push({source:M,root:e,name:"",relativePath:M,diagnostic:rt(Be(te(D),"manifest"),M,M)});continue}let m=y.filter(D=>D.kind==="directory"||D.kind==="symlink").filter(D=>Xd(D.name)).map(D=>({source:M,root:e,name:D.name,relativePath:Wd(M,D.name)})).sort((D,O)=>bn(D.relativePath,O.relativePath));for(let D of m){let O={...D};if(l.push(O),h!==void 0?J.add(Cr(h,O)):T=false,!Le(c,o)){A=true,f="time_limit";break e}let k;if(I!==void 0&&h!==void 0){try{let H=await sp(i,e,h,O,I,d,c,o);if(H.timeLimitReached){A=!0,f="time_limit";break e}O.scanContext=H.context,k=H.memo;}catch(H){T=false,V(O,Be(te(H),"manifest"));continue}k===void 0&&(T=false);}if(k!==void 0){if(O.candidate=k.candidate,O.diagnostic=k.diagnostic,O.identity=k.identity,M==="skills"&&k.candidate===void 0&&k.diagnostic===void 0)continue;if(u>=64){V(O,"LIMIT_EXCEEDED");continue}if(D.relativePath.split("/").length-1>2){V(O,"LIMIT_EXCEEDED");continue}if(u+=1,!Le(c,o)){A=true,f="time_limit";break e}continue}let R;if(M==="skills"&&(R=await Ip(i,O),R===void 0)){O.diagnostic===void 0&&mi(O);continue}if(u>=64){V(O,"LIMIT_EXCEEDED");continue}if(D.relativePath.split("/").length-1>2){V(O,"LIMIT_EXCEEDED");continue}if(!Le(c,o)){A=true,f="time_limit";break e}if(u+=1,R===void 0){let H=await jr(i,O);if(H.failure!==void 0||!hi(H.files)){V(O,H.failure??Be("NOT_FOUND","manifest")),mi(O);continue}R=H.files;}if(await Sr(i,O,R),mi(O),!Le(c,o)){A=true,f="time_limit";break e}}}if(I!==void 0&&h!==void 0){let N=[...J].sort(bn),M=I.lastCandidateKeys,S=M!==void 0&&M.length===N.length&&M.every((m,D)=>m===N[D]);if(T=T&&S,v&&!A&&f===void 0)for(let m of I.candidates.keys())try{JSON.parse(m)[0]===h.realPath&&!J.has(m)&&I.candidates.delete(m);}catch{I.candidates.delete(m);}let y=[...I.candidates.keys()].filter(m=>{try{return JSON.parse(m)[0]===h.realPath}catch{return false}});T=T&&y.length===J.size&&y.every(m=>J.has(m))&&!A&&f===void 0,I.lastCandidateScanUnchanged=T,v&&!A&&f===void 0&&(I.lastCandidateKeys=Object.freeze(N));}A&&l.push({source:"apps",root:e,name:"",relativePath:"apps",diagnostic:rt("DISCOVERY_TIME_LIMIT","apps","apps")});let W=yp(l,r,b);return gp(l,f,s.indexHash,b,r.productBundle!==void 0,W)}var Bd,nn,zd,Gd,Ir,$d,Tr,rp,Nr,_p,Ep,Vr=C(()=>{g();ke();Sn();Pe();bo();Kt();we();Zn();nr();Wn();Gn();or();li();Jn();gi();gi();Bd=Nn([]);nn="crewx_local_app_",zd=nn,Gd=nn;Ir=["bundled","apps","skills"],$d=new TextDecoder("utf-8",{fatal:true});Tr=["","/ui"],rp=["/dist"],Nr=2000000000n;_p=Ei,Ep=Ei;});g();var Fr="SKILL.md",Pp=/^---\s*\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;function Br(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function Sp(e){return e.isDirectory()||e.isSymbolicLink()}function Gr(e){try{return existsSync(e)&&statSync(e).isDirectory()}catch{return false}}var Mp=["index.js","main.js"];function $f(e,n){let t=join(e,"package.json");if(existsSync(t))try{let r=JSON.parse(readFileSync(t,"utf8"));if(r.bin){let o=typeof r.bin=="string"?r.bin:Object.values(r.bin).find(a=>typeof a=="string");if(o){let a=resolve(e,o);if(existsSync(a))return a}}if(typeof r.main=="string"){let o=resolve(e,r.main);if(existsSync(o))return o}}catch{}let i=resolve(e,`${n}.js`);if(existsSync(i))return i;for(let r of Mp){let o=resolve(e,r);if(existsSync(o))return o}}function Op(e){let n;try{n=readFileSync(e,"utf8");}catch{return {frontmatter:{},readable:false,valid:false,hasFrontmatter:false}}let t=n.match(Pp);if(!t)return {frontmatter:{},readable:true,valid:true,hasFrontmatter:false};try{let i=load(t[1]??"");if(!Br(i))return {frontmatter:{},readable:!0,valid:!1,hasFrontmatter:!0};let r=Br(i.metadata)?i.metadata:void 0;return {frontmatter:{...typeof i.name=="string"?{name:i.name}:{},...typeof(r?.version??i.version)=="string"?{version:r?.version??i.version}:{},...typeof i.description=="string"?{description:i.description}:{}},readable:!0,valid:!0,hasFrontmatter:!0}}catch{return {frontmatter:{},readable:true,valid:false,hasFrontmatter:true}}}function Lp(e){return [join(e,Fr),join(e,"skill",Fr)]}function at(e,n){if(!Gr(e))return null;for(let t of Lp(e)){if(!existsSync(t))continue;let r=Op(t).frontmatter;return {name:r.name??n,...r.version===void 0?{}:{version:r.version},...r.description===void 0?{}:{description:r.description},skillMdPath:t,dir:e}}return null}function Ti(e){try{return readdirSync(e,{withFileTypes:!0}).filter(Sp)}catch{return []}}function Rp(e){return e.length===0||/[\\\u0000]/.test(e)?false:e.split("/").every(n=>n.length>0&&n!=="."&&n!=="..")}function Hr(e,n,t){!e||n.has(e.name)||(n.add(e.name),t.push(e));}function ct(e){let n=[],t=new Set;for(let i of e)if(Gr(i))for(let r of Ti(i)){if(r.name.startsWith("@")){let o=join(i,r.name);for(let a of Ti(o))Hr(at(join(o,a.name),a.name),t,n);continue}Hr(at(join(i,r.name),r.name),t,n);}return n.sort((i,r)=>i.name.localeCompare(r.name))}function Up(e,n){if(!Rp(e))throw new Error(`Skill not found: ${e}`);for(let i of n){let r=at(join(i,e),e);if(r)return r;for(let o of Ti(i)){if(!o.name.startsWith("@"))continue;let a=at(join(i,o.name,e),e);if(a)return a}}let t=ct(n).find(i=>i.name===e);if(t)return t;throw new Error(`Skill not found: ${e}`)}async function Wf(e){if(!e||e.root===null)return {skills:[],diagnostics:[]};let{discoverWorkspaceApps:n}=await Promise.resolve().then(()=>(Vr(),vr)),t=await n(e.root,{productBundle:e}),i=[],r=new Set;for(let o of t.apps){let a=o.provenance?.kind==="bundled"?o.provenance.packageDir:void 0;if(!a)continue;let s=join(e.root,...a.split("/"));for(let c of ct([dirname(s)]))resolve(c.dir)!==resolve(s)||r.has(c.name)||(r.add(c.name),i.push(c));for(let c of [join(s,"skill"),join(s,"skills")])for(let d of ct([c]))r.has(d.name)||(r.add(d.name),i.push(d));}return {skills:i.sort((o,a)=>o.name.localeCompare(a.name)),diagnostics:t.diagnostics.filter(o=>o.source==="bundled")}}var Xf=ct,Kf=Up;
2
+ export{ct as discover,Wf as discoverBundledProductSkills,Xf as discoverSkills,$f as findEntrypoint,Op as readSkillFrontmatter,Up as resolve,Kf as resolveSkill};