@crewx/sdk 0.9.0-rc.181 → 0.9.0-rc.182

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
- 'use strict';var Hi=require('crypto'),net=require('net'),ne=require('fs'),promises=require('fs/promises'),ce=require('path'),Os=require('js-yaml'),vs=require('os'),js=require('tar'),zlib=require('zlib');function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var Hi__namespace=/*#__PURE__*/_interopNamespace(Hi);var ne__namespace=/*#__PURE__*/_interopNamespace(ne);var ce__namespace=/*#__PURE__*/_interopNamespace(ce);var Os__namespace=/*#__PURE__*/_interopNamespace(Os);var vs__namespace=/*#__PURE__*/_interopNamespace(vs);var js__namespace=/*#__PURE__*/_interopNamespace(js);var F=(e,n)=>()=>(e&&(n=e(e=0)),n);var m=F(()=>{});var C,Vn=F(()=>{m();C=class extends Error{constructor(t,i=t,o){super(i);this.code=t;this.currentRevision=o;}code;currentRevision;name="UiRuntimeError"};});function Lt(e){return Zs.test(e)||Qs.test(e)}function ye(){throw new C("INPUT_INVALID","JSON value is not projection-safe")}function ia(e){let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function Mt(e,n,t,i,o,r){if(n>i&&ye(),e===null||typeof e=="string"||typeof e=="boolean")return typeof e=="string"&&(ea.test(e)||ta.test(e)&&!sa(o,r)||na.test(e))&&ye(),e;if(typeof e=="number")return Number.isFinite(e)||ye(),e;(typeof e!="object"||e===void 0||typeof e=="function"||typeof e=="bigint")&&ye();let s=e;t.has(s)&&ye(),t.add(s);try{if(Array.isArray(e))return e.map(c=>Mt(c,n+1,t,i,o,r));ia(s)||ye();let a={};for(let[c,d]of Object.entries(e))Lt(c)&&ye(),a[c]=Mt(d,n+1,t,i,[...o,c],r);return a}finally{t.delete(s);}}function Ae(e,n=0,t=[]){(!Number.isInteger(n)||n<0||n>ra)&&ye(),(!Array.isArray(t)||t.some(o=>typeof o!="string"))&&ye();let i=Mt(e,0,new Set,oa+n,[],t);return (i===null||Array.isArray(i)||typeof i!="object")&&ye(),i}function nn(e,n){if(!e||!n)return false;let t=e.split("."),i=n.split(".");return t.length>=i.length&&i.every((o,r)=>t[r]===o)}function sa(e,n){if(e.length===0)return false;let t=e.join(".");return n.some(i=>nn(t,i))}function tn(e){try{let n=JSON.stringify(e);return n===void 0&&ye(),n}catch{ye();}}function Ot(e){return Array.isArray(e)?e.map(Ot):e!==null&&typeof e=="object"?Object.fromEntries(Object.keys(e).sort().map(n=>[n,Ot(e[n])])):e}function te(e){return tn(Ot(e))}function Rt(e){return Buffer.byteLength(e,"utf8")}var Zs,Qs,ea,na,ta,oa,ra,Re=F(()=>{m();Vn();Zs=/(?:proof|token|secret|password|cookie|authorization|private[_-]?key|stack|exception|plugin[_-]?text)/i,Qs=/(?:url|uri|endpoint|path|file(?:name|path)?|cwd|shell|directory|dir|folder)$/i,ea=/<\/?[A-Za-z][^>]*>/,na=/^(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)/,ta=/^(?:https?|file|ftp|ws|wss):\/\//i;oa=8,ra=4;});var Ji=F(()=>{m();Re();});var Bn,wt=F(()=>{m();Bn=["text/plain","application/json"];});var Wi=F(()=>{m();wt();});function on(e){return ca.has(e)||da.test(e)||pa.test(e)}var Ki,ca,da,pa,Hn,gn,Pe,Ct,Ut,kt,xt,vt,Ge=F(()=>{m();Ki=["__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"],ca=new Set(Ki),da=/(?:proof|token|secret|password|cookie|authorization|private[_-]?key|stack|exception|plugin[_-]?text)/i,pa=/(?:url|uri|endpoint|path|file(?:name|path)?|cwd|shell|directory|dir|folder)$/i;Hn=/^[A-Za-z0-9_]+$/,gn=/^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)*$/,Pe=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,Ct=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/,Ut=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,kt=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/,xt=["blue","violet","emerald","amber","rose","sky","slate","indigo"],vt=["inline","panel"];});function Ft(e){return typeof e=="string"&&Bn.includes(e)}var Xi=F(()=>{m();wt();Ge();});function zn(e){if(!jt(e))return false;let n=Object.keys(e);return !(n.some(t=>t!=="in"&&t!=="out")||n.length===0||Object.hasOwn(e,"in")&&!la(e.in)||Object.hasOwn(e,"out")&&!ua(e.out))}function la(e){return jt(e)?Object.keys(e).every(t=>t==="mediaType"||t==="required")&&Object.hasOwn(e,"mediaType")&&Ft(e.mediaType)&&(!Object.hasOwn(e,"required")||typeof e.required=="boolean"):false}function ua(e){return jt(e)?Object.keys(e).every(t=>t==="mediaType"||t==="range")&&Object.hasOwn(e,"mediaType")&&Ft(e.mediaType)&&(!Object.hasOwn(e,"range")||typeof e.range=="boolean"):false}function jt(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}var Vt=F(()=>{m();Wi();Xi();new TextDecoder("utf-8",{fatal:true,ignoreBOM:true});});function Gn(e){return fa.includes(e)}function Jn(e){return Number.isSafeInteger(e)&&e>=$n.min&&e<=$n.max}var fa,$n,Yi,Bt=F(()=>{m();fa=[5,15,30,60],$n=Object.freeze({min:15e3,max:6e5,default:3e5}),Yi=1;});function Kn(e){return Number.isSafeInteger(e)&&e>=Wn.min&&e<=Wn.max}function Xn(e){return ya.includes(e)}var Wn,qi,ya,Ht=F(()=>{m();Wn=Object.freeze({min:6e4,max:18e5,default:6e5}),qi=1,ya=["start","status","cancel"];});function le(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(o=>o.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=Ae(t);return Hi.createHash("sha256").update(te(i)).digest("hex")}function $t(e){return `${e.id}\0${e.version}`}function Ie(e){if(!/^\d+$/.test(String(e.version))||e.version<1||e.id.length<1||e.id.length>128)throw new C("DEFINITION_UNSUPPORTED","UI definition is invalid");if(e.sourceHash!==void 0&&(typeof e.sourceHash!="string"||!Ia.test(e.sourceHash)))throw new C("DEFINITION_UNSUPPORTED","UI definition source hash is invalid");if(!/^[0-9a-f]{64}$/.test(e.hash)||le(e)!==e.hash)throw new C("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=>!ma(i)))throw new C("DEFINITION_UNSUPPORTED","UI action declaration is invalid");if(t.confirmation!==void 0&&t.confirmation!=="none"&&t.confirmation!=="native")throw new C("DEFINITION_UNSUPPORTED","UI action confirmation is invalid");if(t.inputKeys&&(!Array.isArray(t.inputKeys)||t.inputKeys.some(i=>typeof i!="string"||!i)))throw new C("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 C("DEFINITION_UNSUPPORTED","UI action data input declaration is invalid");if(t.resultProjection&&zt(t.resultProjection),t.schedule!==void 0&&(!Gn(t.schedule.everyMinutes)||!Jn(t.schedule.timeoutMs)))throw new C("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 C("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 C("DEFINITION_UNSUPPORTED","UI action job control declaration is invalid");if(t.content!==void 0&&!zn(t.content))throw new C("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 C("DEFINITION_UNSUPPORTED","UI action environment declaration is invalid")}if(e.renderer!==void 0&&(!e.renderer||e.renderer.length>128))throw new C("DEFINITION_UNSUPPORTED","UI definition renderer is invalid");if(e.surfaces&&(!Array.isArray(e.surfaces)||e.surfaces.some(n=>!n||n.length>64)))throw new C("DEFINITION_UNSUPPORTED","UI definition surfaces are invalid");if(e.usage!==void 0&&e.usage!=="card"&&e.usage!=="window")throw new C("DEFINITION_UNSUPPORTED","UI definition usage is invalid");if(e.detailPanel!==void 0&&typeof e.detailPanel!="boolean")throw new C("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 C("DEFINITION_UNSUPPORTED","UI definition displayModes are invalid");if(e.usage==="card"&&e.displayModes!==void 0)throw new C("DEFINITION_UNSUPPORTED","Card definitions cannot declare displayModes");if(e.usage==="window"&&e.detailPanel!==void 0)throw new C("DEFINITION_UNSUPPORTED","Window definitions cannot declare detailPanel");if(e.stateProjection&&zt(e.stateProjection),e.summaryProjection){zt(e.summaryProjection);let n=new Set(e.stateProjection?.allow??[]);if(e.summaryProjection.allow.some(t=>!n.has(t)))throw new C("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(o=>!["readTool","actionTool","hostTools","agentAccess"].includes(o)))throw new C("DEFINITION_UNSUPPORTED","UI legacy metadata is invalid");let n=new Set;for(let[o,r]of [["readTool",e.legacy.readTool],["actionTool",e.legacy.actionTool]])if(r!==void 0){if(ga(r,o==="readTool"),n.has(r.name))throw new C("DEFINITION_UNSUPPORTED","UI legacy tool names collide");n.add(r.name);}let t=e.legacy.hostTools;if(t!==void 0){if(!t||typeof t!="object"||Array.isArray(t))throw new C("DEFINITION_UNSUPPORTED","UI legacy host tools are invalid");let o={"doc.open":"crewx_app_html_viewer_open","pty.connect":"crewx_app_terminal_connect"};for(let[r,s]of Object.entries(t)){if(!Object.hasOwn(o,r)||o[r]!==s||typeof s!="string"||!/^[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(s)||n.has(s))throw new C("DEFINITION_UNSUPPORTED","UI legacy host tools are invalid");n.add(s);}}let i=e.legacy.agentAccess;if(i!==void 0&&(!i||typeof i!="object"||Array.isArray(i)||Object.entries(i).some(([o,r])=>!o||!Object.hasOwn(e.actions,o)||r!=="allowed"&&r!=="denied")))throw new C("DEFINITION_UNSUPPORTED","UI legacy agent access is invalid");if(e.legacy.actionTool!==void 0&&(!i||Object.keys(i).length===0))throw new C("DEFINITION_UNSUPPORTED","UI legacy action tool requires its complete agent access map")}if(e.downloads!==void 0&&e.downloads!==true)throw new C("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=>nn(t,i))))throw new C("DEFINITION_UNSUPPORTED","UI definition dataPaths are invalid")}}function ga(e,n){if(!e||typeof e!="object"||Array.isArray(e))throw new C("DEFINITION_UNSUPPORTED","UI legacy tool metadata is invalid");let t=e,i=["name","description","inputSchema","textFallback","visibility"],o=Object.hasOwn(t,"fixedResult");if(Object.keys(t).some(r=>!i.includes(r)&&!(n&&r==="fixedResult"))||i.some(r=>!Object.hasOwn(t,r))||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(r=>r!=="model"&&r!=="app")||new Set(t.visibility).size!==t.visibility.length)throw new C("DEFINITION_UNSUPPORTED","UI legacy tool metadata is invalid");try{let r=Ae(t.inputSchema);if(r.type!==void 0&&r.type!=="object")throw new Error("schema type");if(o){if(!n)throw new Error("fixed result location");let s=t.fixedResult;if(!s||typeof s!="object"||Array.isArray(s))throw new Error("fixed result");let a=s;if(Object.keys(a).sort().join(",")!=="argsPolicy,structuredContent"||a.argsPolicy!=="empty-only"&&a.argsPolicy!=="ignore"||!a.structuredContent||typeof a.structuredContent!="object"||Array.isArray(a.structuredContent))throw new Error("fixed result");let c=Ae(a.structuredContent);if(Rt(tn(c))>4*1024)throw new Error("fixed result size")}}catch{throw new C("DEFINITION_UNSUPPORTED","UI legacy tool metadata is not projection-safe")}}function zt(e){if(!Array.isArray(e.allow)||e.allow.some(n=>!/^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)*$/.test(n)))throw new C("DEFINITION_UNSUPPORTED","UI projection policy is invalid")}function ma(e){return e.length>0&&e.length<=128&&e!=="*"&&e!=="all"&&!/[/*]/.test(e)}var Ia,Je=F(()=>{m();Re();Vn();Vt();Bt();Ht();Ia=/^[0-9a-f]{64}$/;});var $,we,Gt=F(()=>{m();$="dist/tools.json",we="dist/main.mjs";});var je,Jt=F(()=>{m();je="window";});function Zi(e){if(!Array.isArray(e)||e.length===0)return false;let n=new Set;for(let t of e){if(!ha.some(i=>i===t)||n.has(t))return false;n.add(t);}return true}var ha,Qi=F(()=>{m();ha=["CREWX_APP_INSTANCE_ID","CREWX_THREAD_ID"];});function J(e){throw new Wt(e)}function Ra(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 wa(e,n){let t=Object.getOwnPropertyDescriptor(e,n);return (!t||!("value"in t))&&J("CSP_ORIGIN_INVALID"),t.value}function Yn(e,n){if(!Object.prototype.hasOwnProperty.call(e,n))return [];let t=wa(e,n);Array.isArray(t)||J("CSP_ORIGIN_INVALID"),Reflect.ownKeys(t).some(r=>typeof r!="string"||r!=="length"&&!/^(?:0|[1-9][0-9]*)$/.test(r))&&J("CSP_ORIGIN_INVALID");let o=[];for(let r=0;r<t.length;r+=1)(!Object.prototype.hasOwnProperty.call(t,r)||typeof t[r]!="string")&&J("CSP_ORIGIN_INVALID"),o.push(t[r]);return Object.keys(t).length!==t.length&&J("CSP_ORIGIN_INVALID"),o}function Ca(e){let n;try{n=JSON.stringify(e);}catch{J("CSP_ORIGIN_INVALID");}return n===void 0&&J("CSP_ORIGIN_INVALID"),new TextEncoder().encode(n).byteLength}function to(e,n){/\s|\\/u.test(e)&&J("CSP_ORIGIN_INVALID");let t=Da.exec(e);t||J("CSP_ORIGIN_INVALID");let i=t[1].toLowerCase(),o=t[2];(o.includes("@")||o.includes("%")||o.includes("*"))&&J("CSP_ORIGIN_INVALID"),(o.startsWith("[")?Sa:Ma).test(o)||J("CSP_ORIGIN_INVALID"),i==="wss"&&n!=="connectDomains"&&J("CSP_ORIGIN_INVALID");let s;try{s=new URL(e);}catch{J("CSP_ORIGIN_INVALID");}(s.protocol!==`${i}:`||s.username!==""||s.password!==""||s.search!==""||s.hash!=="")&&J("CSP_ORIGIN_INVALID");let a=s.hostname.toLowerCase();if((!a||a.includes("%"))&&J("CSP_ORIGIN_INVALID"),!a.startsWith("[")){let d=a.endsWith(".")?a.slice(0,-1):a;(d.length===0||d.length>253)&&J("CSP_ORIGIN_INVALID"),d.split(".").some(p=>p.length>63||!Oa.test(p))&&J("CSP_ORIGIN_INVALID");}let c=s.origin;return (c==="null"||!c.startsWith(`${i}://`))&&J("CSP_ORIGIN_INVALID"),{origin:c,hostname:a}}function Ua(e){let n=e.split(".").map(Number);return ((n[0]*256+n[1])*256+n[2])*256+n[3]}function io(e,n,t){let i=4294967295<<32-t>>>0;return (e&i)===(n&i)}function so(e){let n=Ua(e);return io(n,3221225472,24)?n!==3221225481&&n!==3221225482:La.some(([t,i])=>io(n,t,i))}function ka(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((r,s)=>r<<16n|BigInt(Number.parseInt(s,16)),0n)}function xa(e){let n=ka(e),t=Number(n>>112n),i=Number(n>>96n&0xffffn);if(n>>32n===0xffffn){let o=Number(n&0xffffffffn);return so([o>>>24&255,o>>>16&255,o>>>8&255,o&255].join("."))}return t<8192||t>16383||t===8193&&i<=511||t===8193&&i===3512||t===8194||t===16383&&i<=4095}function va(e,n){let t=e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e,i=net.isIP(t);if(i===4)return so(t);if(i===6)return xa(t);let o=e.toLowerCase().replace(/\.$/,"");return !o||!o.includes(".")||n.has(o)?true:Na.some(r=>o===r||o.endsWith(`.${r}`))}function oo(e){return Object.freeze([...new Set(e.map(n=>n.origin))].sort())}function ro(e){return JSON.stringify({baseUriDomains:[],connectDomains:e.connectDomains,declared:e.declared,frameDomains:e.frameDomains,resourceDomains:[]})}function ao(e,n={}){if(e===void 0){let y=ro({declared:false,connectDomains:[],frameDomains:[]});return Object.freeze({declared:false,connectDomains:Object.freeze([]),frameDomains:Object.freeze([]),resourceDomains:Object.freeze([]),baseUriDomains:Object.freeze([]),cspHash:Hi.createHash("sha256").update(y,"utf8").digest("hex")})}Ra(e)||J("CSP_ORIGIN_INVALID");let t=Reflect.ownKeys(e);t.some(y=>typeof y!="string")&&J("CSP_ORIGIN_INVALID"),t.some(y=>!Pa.has(y))&&J("CSP_AXIS_UNKNOWN");let i=Yn(e,"connectDomains"),o=Yn(e,"frameDomains"),r=Yn(e,"resourceDomains"),s=Yn(e,"baseUriDomains");(r.length>0||s.length>0)&&J("CSP_AXIS_UNSUPPORTED"),(Ca(e)>Ea||i.length>no||o.length>no||i.length+o.length>Ta||[...i,...o].some(y=>new TextEncoder().encode(y).byteLength>ba))&&J("CSP_LIMIT_EXCEEDED");let c=i.map(y=>to(y,"connectDomains")),d=o.map(y=>to(y,"frameDomains")),l=new Set((n.runtimeHostnames??[]).map(y=>y.toLowerCase().replace(/\.$/,"")));[...c,...d].some(y=>va(y.hostname,l))&&J("CSP_ORIGIN_FORBIDDEN");let p={declared:true,connectDomains:oo(c),frameDomains:oo(d)},u=ro(p);return Object.freeze({...p,resourceDomains:Object.freeze([]),baseUriDomains:Object.freeze([]),cspHash:Hi.createHash("sha256").update(u,"utf8").digest("hex")})}var Ea,no,Ta,ba,Pa,Na,Da,Sa,Ma,Oa,La,Wt,co=F(()=>{m();Ea=4096,no=16,Ta=32,ba=512,Pa=new Set(["connectDomains","frameDomains","resourceDomains","baseUriDomains"]),Na=["localhost","local","internal","home.arpa","test","example","invalid","onion","lan","corp","home","intranet","private","localdomain"],Da=/^(https|wss):\/\/([^/?#]+)$/i,Sa=/^\[[^\]]+\](?::[0-9]+)?$/,Ma=/^[^:\[\]]+(?::[0-9]+)?$/,Oa=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/,La=[[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]],Wt=class extends Error{constructor(t){super(t);this.code=t;}code;name="UiPluginCspNormalizationError"};});function hn(e,n){return n===void 0||n===""?e:e===""?n:n.startsWith("[")?`${e}${n}`:`${e}.${n}`}function f(e,n=e,t,i){throw new ae(e,n,t,i)}function z(e,n){try{return n()}catch(t){throw t instanceof ae?t.withPathPrefix(e):t}}function G(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 R(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function gc(e,n){let t={};for(let[i,o]of Object.entries(e))n.includes(i)||(t[i]=o);return t}function K(e,n,t=[]){let i=new Set([...n,...t]),o=Object.keys(e).find(s=>!i.has(s));o!==void 0&&f("MANIFEST_INVALID","MANIFEST_INVALID",o,"unknown-key");let r=n.find(s=>!R(e,s));r!==void 0&&f("MANIFEST_INVALID","MANIFEST_INVALID",r,"missing-key");}function et(e,n=false,t=false,i=false){return Ba.test(e)||!i&&za.test(e)||Ha.test(e)||t&&po.test(e)||$a.test(e)&&!(n&&/^\s*data:/i.test(e)&&!po.test(e))}function Qn(e,n=new Set,t=0,i=false,o=false,r=""){if(typeof e=="string"){et(e,i,o)&&f("UNSAFE_VALUE","UNSAFE_VALUE",r,"unsafe-value");return}if(!(e===null||typeof e!="object")){(t>8||n.has(e))&&f("MANIFEST_INVALID","MANIFEST_INVALID",r),n.add(e);try{if(Array.isArray(e)){e.forEach((s,a)=>Qn(s,n,t+1,!1,!1,hn(r,`[${a}]`)));return}G(e)||f("MANIFEST_INVALID","MANIFEST_INVALID",r);for(let[s,a]of Object.entries(e))Qn(a,n,t+1,i&&t===0&&(s==="name"||s==="description"),o,hn(r,s));}finally{n.delete(e);}}}function Ne(e,n){let t=e[n];return typeof t!="string"&&f("MANIFEST_INVALID"),t}function me(e,n,t){let i=e[n];return (!Number.isSafeInteger(i)||i<t)&&f("MANIFEST_INVALID"),i}function Kt(e){return Va.test(e)||f("MANIFEST_INVALID"),e}function rn(e){return ja.test(e)||f("TOKEN_INVALID"),e}function mc(e){return Po.test(e)||f("MANIFEST_INVALID"),e}function hc(e){G(e)||f("MANIFEST_INVALID");let n={};for(let[t,i]of Object.entries(e)){let o=mc(t);G(i)||f("MANIFEST_INVALID");let r=i.type;if(r==="text"){K(i,["type","maxLength"]),n[o]={type:r,maxLength:me(i,"maxLength",1)};continue}if(r==="text-list"){K(i,["type","max","itemMaxLength"]),n[o]={type:r,max:me(i,"max",0),itemMaxLength:me(i,"itemMaxLength",1)};continue}if(r==="step-list"){K(i,["type","min","max","labelMaxLength","detailMaxLength"]);let s=me(i,"min",0),a=me(i,"max",1);s>a&&f("MANIFEST_INVALID"),n[o]={type:r,min:s,max:a,labelMaxLength:me(i,"labelMaxLength",1),detailMaxLength:me(i,"detailMaxLength",1)};continue}typeof r=="string"&&f("SCHEMA_TYPE_UNSUPPORTED"),f("MANIFEST_INVALID");}return n}function _c(e,n,t){let i=e[n];(!i||i.type!==t)&&f("MANIFEST_INVALID");}function qn(e,n,t){let i=Ne(e,"field");return Po.test(i)||f("MANIFEST_INVALID"),_c(n,i,t),i}function Ec(e,n){G(e)||f("MANIFEST_INVALID");let t=e.primitive;switch(typeof t!="string"&&f("MANIFEST_INVALID"),Ic.includes(t)||f("PRIMITIVE_UNKNOWN"),t){case "card-shell":return K(e,["primitive"]),{primitive:t};case "meta-banner":return K(e,["primitive","badgeToken","noticeToken"]),{primitive:t,badgeToken:rn(Ne(e,"badgeToken")),noticeToken:rn(Ne(e,"noticeToken"))};case "heading":return K(e,["primitive","field"]),{primitive:t,field:qn(e,n,"text")};case "labeled-text":return K(e,["primitive","titleToken","field","variant"]),e.variant!=="callout"&&f("MANIFEST_INVALID"),{primitive:t,titleToken:rn(Ne(e,"titleToken")),field:qn(e,n,"text"),variant:"callout"};case "step-flow":return K(e,["primitive","titleToken","field"]),{primitive:t,titleToken:rn(Ne(e,"titleToken")),field:qn(e,n,"step-list")};case "text-list":{K(e,["primitive","titleToken","field"],["emptyToken","hideWhenEmpty"]);let i={primitive:t,titleToken:rn(Ne(e,"titleToken")),field:qn(e,n,"text-list")};return R(e,"emptyToken")&&(i.emptyToken=rn(Ne(e,"emptyToken"))),R(e,"hideWhenEmpty")&&(typeof e.hideWhenEmpty!="boolean"&&f("MANIFEST_INVALID"),i.hideWhenEmpty=e.hideWhenEmpty),i}}return f("MANIFEST_INVALID")}function Tc(e,n){return Array.isArray(e)||f("MANIFEST_INVALID"),e.map(t=>Ec(t,n))}function Y(e="v2 manifest exceeds a contract limit",n,t){return f("LIMIT_EXCEEDED",e,n,t)}function ge(e="initial state is not projection-safe"){return f("INITIAL_STATE_INVALID",e)}function lo(e,n){return (typeof e!="string"||e.length===0||e.length>4096||e.trim().length===0||pc.test(e)||lc.test(e))&&f("MANIFEST_INVALID",`${n} is invalid`),(et(e,true,true)||Ga.test(e)||Ja.test(e)||Wa.test(e))&&f("UNSAFE_VALUE",`${n} contains an unsafe value`),e}function Xt(e,n){return (typeof e!="string"||!Pe.test(e))&&f("MANIFEST_INVALID",`${n} is invalid`),e}function bc(e){return (typeof e!="string"||!Ct.test(e)||e==="*"||e==="all")&&f("MANIFEST_INVALID","action capability is invalid"),e}function No(e){return (typeof e!="string"||!dc.test(e))&&f("MANIFEST_INVALID","resource hash is invalid"),e}function Yt(e,n=new Set,t=0,i=""){if(typeof e=="string"){e.length>4096&&Y("v2 manifest string is too long",i,"string-too-long");return}if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){Number.isFinite(e)||f("MANIFEST_INVALID","v2 manifest contains a non-finite number",i,"non-finite-number");return}(e===void 0||typeof e=="function"||typeof e=="bigint")&&f("MANIFEST_INVALID","v2 manifest contains a non-JSON value",i,"non-json-value"),typeof e!="object"&&f("MANIFEST_INVALID","MANIFEST_INVALID",i),t>8&&Y("v2 manifest nesting is too deep",i,"too-deep"),n.has(e)&&f("MANIFEST_INVALID","v2 manifest contains a cycle",i,"cycle"),n.add(e);try{if(Array.isArray(e)){e.length>128&&Y("v2 manifest array is too long",i,"array-too-long"),e.forEach((o,r)=>Yt(o,n,t+1,hn(i,`[${r}]`)));return}G(e)||f("MANIFEST_INVALID","v2 manifest contains a non-plain object",i,"non-plain-object");for(let[o,r]of Object.entries(e))Yt(r,n,t+1,hn(i,o));}finally{n.delete(e);}}}function Do(e){return (typeof e!="string"||e.length>4096||!gn.test(e))&&(typeof e=="string"&&e.length>4096&&Y("projection path is too long"),f("MANIFEST_INVALID","projection paths must be canonical exact paths")),e.split(".").some(t=>on(t))&&f("MANIFEST_INVALID","projection paths cannot address reserved state keys"),e}function qt(e){G(e)||f("MANIFEST_INVALID","projection policy must be an object"),K(e,["allow"]),Array.isArray(e.allow)||f("MANIFEST_INVALID","projection allow must be an array"),e.allow.length>128&&Y("projection allowlist is too long");let n=[],t=new Set;for(let i of e.allow){let o=Do(i);t.has(o)&&f("MANIFEST_INVALID","projection allowlist contains a duplicate path"),t.add(o),n.push(o);}return {allow:n}}function Pc(e,n){if(e===void 0)return;Array.isArray(e)||f("MANIFEST_INVALID","dataPaths must be an array"),e.length>uc&&Y("dataPaths exceed the v2 limit");let t=[],i=new Set;for(let o of e){let r=Do(o);i.has(r)&&f("MANIFEST_INVALID","dataPaths contain a duplicate path"),n.some(s=>nn(r,s))||f("MANIFEST_INVALID","dataPaths must be projection-allowed"),i.add(r),t.push(r);}return t}function Nc(e){Array.isArray(e)||f("MANIFEST_INVALID","deviceFeatures must be an array",void 0,"array"),e.length>fc&&f("MANIFEST_INVALID","deviceFeatures allow at most 16 names",void 0,"too-many-items");let n=[],t=new Set;for(let[i,o]of e.entries()){let r=`[${i}]`;typeof o!="string"&&f("MANIFEST_INVALID","a device feature name must be a string",r,"string"),o.length===0&&f("MANIFEST_INVALID","a device feature name must not be empty",r,"empty"),o.length>yc&&f("MANIFEST_INVALID","a device feature name is at most 32 characters",r,"too-long"),Ac.test(o)||f("MANIFEST_INVALID","a device feature name starts with a lowercase letter and holds only letters and digits",r,"format"),t.has(o)&&f("MANIFEST_INVALID","deviceFeatures contain a duplicate name",r,"duplicate-item"),t.add(o),n.push(o);}return n}function Dc(e){if(e!==false)return e!==true&&f("MANIFEST_INVALID","downloads must be true or false",void 0,"boolean"),true}function Sc(e){return typeof e!="boolean"&&f("MANIFEST_INVALID","desktopOnly must be true or false",void 0,"boolean"),e}function Mc(e){return (!G(e)||e.view!==true||Object.keys(e).some(n=>n!=="view"&&n!=="entry"))&&f("MANIFEST_INVALID",'share must be { "view": true } or { "view": true, "entry": "<path>" }',void 0,"share-shape"),R(e,"entry")?{view:true,entry:Lc(e.entry)}:{view:true}}function Lc(e){typeof e!="string"&&f("MANIFEST_INVALID","share.entry must be a string","entry","entry-shape");let n=(i,o)=>f("MANIFEST_INVALID",`share.entry ${o}`,"entry",i);e.length===0&&n("empty","must not be empty"),e.length>uo&&n("too-long",`must be at most ${uo} characters`),e.startsWith("/")&&n("absolute","must be relative to the App folder");let t=e.split("/");t.length>fo&&n("too-many-segments",`must have at most ${fo} 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'),Oc.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 Rc(e){return (!G(e)||Object.keys(e).length!==1||typeof e.root!="string")&&f("MANIFEST_INVALID",'files must be exactly { "root": "<workspace folder>" }',void 0,"files-shape"),{root:xc(e.root)}}function xc(e){let n=e.normalize("NFC"),t=(r,s)=>f("MANIFEST_INVALID",`files.root ${s}`,"root",r);n.length===0&&t("empty","must not be empty"),kc.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>yo&&t("too-long",`must be at most ${yo} characters`);let i=n.split("/"),o=i[0].toLowerCase().replace(/[. ]+$/,"");Uc.includes(o)&&t("reserved-folder","must not start in an App code folder or a tool folder"),i.length<wc&&t("too-shallow","must name a folder inside a top-level folder, such as docs/trips"),i.length>Ao&&t("too-many-segments",`must have at most ${Ao} segments`);for(let r of i)r.length===0&&t("empty-segment","must not contain an empty segment"),(r==="."||r==="..")&&t("dot-segment",'must not contain "." or ".." segments'),Array.from(r).length>Io&&t("segment-too-long",`segments must be at most ${Io} characters`),Cc.test(r)||t("segment-shape",'segments must start with a letter or digit and contain only letters, digits, combining marks, "_" or "-"');return n}function sn(e,n,t=Number.MAX_SAFE_INTEGER){return (!Number.isSafeInteger(e)||e<0||e>t)&&f("MANIFEST_INVALID",`${n} is invalid`),e}function go(e,n){return (typeof e!="number"||!Number.isFinite(e))&&f("MANIFEST_INVALID",`${n} is invalid`),e}function Zt(e,n=0,t=new Set){if(typeof e=="string")return (e.length>4096||et(e))&&f("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)||f("MANIFEST_INVALID","schema enum contains a non-finite number"),e;(n>8||typeof e!="object"||e===void 0)&&Y("schema enum is too deep"),t.has(e)&&f("MANIFEST_INVALID","schema enum contains a cycle"),t.add(e);try{if(Array.isArray(e))return e.length>128&&Y("schema enum array is too long"),e.map(o=>Zt(o,n+1,t));G(e)||f("MANIFEST_INVALID","schema enum contains a non-plain object");let i={};for(let[o,r]of Object.entries(e))on(o)&&f("MANIFEST_INVALID","schema enum contains a reserved key"),i[o]=Zt(r,n+1,t);return i}finally{t.delete(e);}}function vc(e,n){if(e===void 0)return;Array.isArray(e)||f("MANIFEST_INVALID","schema required must be an array"),e.length>64&&Y("schema required list is too long");let t=[],i=new Set;for(let o of e)(typeof o!="string"||!gn.test(o))&&f("MANIFEST_INVALID","schema required contains an invalid key"),o.length>4096&&Y("schema required key is too long"),i.has(o)&&f("MANIFEST_INVALID","schema required contains a duplicate key"),n&&!Object.prototype.hasOwnProperty.call(n,o)&&f("MANIFEST_INVALID","schema required references an undeclared property"),i.add(o),t.push(o);return t}function Fc(e,n){let t=n?gn:Hn;return e.length>4096&&Y("schema property name is too long"),(!t.test(e)||e.split(".").some(i=>on(i)))&&f("MANIFEST_INVALID","schema property name is invalid"),e}function Qt(e,n=0,t=false){G(e)||f("MANIFEST_INVALID","action inputSchema must be an object"),n>8&&Y("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"&&f("SCHEMA_TYPE_UNSUPPORTED","action inputSchema type is unsupported"),f("MANIFEST_INVALID","action inputSchema type is required"));let o=["type","enum"];i==="string"&&o.push("minLength","maxLength"),i==="array"&&o.push("minItems","maxItems","items"),i==="object"&&o.push("minProperties","maxProperties","properties","required","additionalProperties"),(i==="number"||i==="integer")&&o.push("minimum","maximum"),K(e,["type"],o.filter(a=>a!=="type"));let r={type:i};if(R(e,"enum")&&(Array.isArray(e.enum)||f("MANIFEST_INVALID","schema enum must be an array"),e.enum.length>128&&Y("schema enum is too long"),r.enum=e.enum.map(a=>Zt(a))),i==="string"&&(R(e,"minLength")&&(r.minLength=sn(e.minLength,"schema minLength",4096)),R(e,"maxLength")&&(r.maxLength=sn(e.maxLength,"schema maxLength",4096)),r.minLength!==void 0&&r.maxLength!==void 0&&r.minLength>r.maxLength&&f("MANIFEST_INVALID","schema string length bounds are inverted")),(i==="number"||i==="integer")&&(R(e,"minimum")&&(r.minimum=go(e.minimum,"schema minimum")),R(e,"maximum")&&(r.maximum=go(e.maximum,"schema maximum")),r.minimum!==void 0&&r.maximum!==void 0&&r.minimum>r.maximum&&f("MANIFEST_INVALID","schema numeric bounds are inverted")),i==="array"&&(R(e,"minItems")&&(r.minItems=sn(e.minItems,"schema minItems",128)),R(e,"maxItems")&&(r.maxItems=sn(e.maxItems,"schema maxItems",128)),r.minItems!==void 0&&r.maxItems!==void 0&&r.minItems>r.maxItems&&f("MANIFEST_INVALID","schema array length bounds are inverted"),R(e,"items")&&(r.items=Qt(e.items,n+1,false))),i==="object"){let a;if(R(e,"properties")){G(e.properties)||f("MANIFEST_INVALID","schema properties must be an object");let d=Object.entries(e.properties);d.length>64&&Y("schema properties are too many"),a={};for(let[l,p]of d){let u=Fc(l,t);a[u]=Qt(p,n+1,false);}r.properties=a;}R(e,"minProperties")&&(r.minProperties=sn(e.minProperties,"schema minProperties",64)),R(e,"maxProperties")&&(r.maxProperties=sn(e.maxProperties,"schema maxProperties",64)),r.minProperties!==void 0&&r.maxProperties!==void 0&&r.minProperties>r.maxProperties&&f("MANIFEST_INVALID","schema object property bounds are inverted");let c=vc(e.required,a);c!==void 0&&(r.required=c),R(e,"additionalProperties")&&(e.additionalProperties!==false&&f("MANIFEST_INVALID","schema additionalProperties must be false"),r.additionalProperties=false);}let s=JSON.stringify(r);return (s===void 0||Buffer.byteLength(s,"utf8")>2097152)&&Y("action inputSchema subtree is too large"),r}function jc(e){let n=Qt(e,0,true);return (n.type!=="object"||!n.properties)&&f("MANIFEST_INVALID","action inputSchema must declare object properties"),n}function Vc(e){if(G(e)||f("MANIFEST_INVALID","action backend must be an object"),e.type==="core"){K(e,ic);let n=e.handler;return (typeof n!="string"||!Ut.test(n))&&f("MANIFEST_INVALID","core backend handler is invalid"),{type:"core",handler:n}}if(e.type==="skill"&&R(e,"entry"))return K(e,sc),e.entry!==we&&f("MANIFEST_INVALID",`skill backend entry must be ${we}`),{type:"skill",entry:we};if(e.type==="skill"){K(e,oc,rc),(!Array.isArray(e.command)||e.command.length===0||e.command.length>16)&&f("MANIFEST_INVALID","skill backend command is invalid");let n=[];for(let i of e.command)(typeof i!="string"||i.length===0||i.length>256||!kt.test(i))&&f("MANIFEST_INVALID","skill backend command token is invalid"),n.push(i);let t=R(e,"env")?Gc(e.env):void 0;return {type:"skill",command:n,...t===void 0?{}:{env:t}}}f("MANIFEST_INVALID","action backend type is unsupported");}function Bc(e){G(e)||f("MANIFEST_INVALID","action must be an object"),K(e,qa,Za),R(e,"_meta")&&z("_meta",()=>So(e._meta));let n=z("actionId",()=>Xt(e.actionId,"actionId"));Lt(n)&&f("MANIFEST_INVALID",`actionId "${n}" is not projection-safe`,"actionId");let t=z("capability",()=>bc(e.capability)),i=e.mutation;typeof i!="boolean"&&f("MANIFEST_INVALID","action mutation must be boolean","mutation");let o=z("inputSchema",()=>jc(e.inputSchema)),r;if(R(e,"dataInputs")){Array.isArray(e.dataInputs)||f("MANIFEST_INVALID","action dataInputs must be an array","dataInputs");let y=o.properties,g=new Set,_=[];for(let E of e.dataInputs)(typeof E!="string"||!R(y,E)||g.has(E))&&f("MANIFEST_INVALID","action dataInputs must be unique declared properties","dataInputs"),g.add(E),_.push(E);r=_;}let s=z("resultProjection",()=>qt(e.resultProjection)),a=z("backend",()=>Vc(e.backend)),c;R(e,"content")&&((a.type!=="skill"||!zn(e.content))&&f("MANIFEST_INVALID","action content declaration is invalid","content"),c=Jc(e.content));let d;if(R(e,"confirmation")){let y=e.confirmation;y!=="none"&&y!=="native"&&f("MANIFEST_INVALID","action confirmation is invalid","confirmation"),d=y;}let l;R(e,"schedule")&&(l=z("schedule",()=>$c(e.schedule,{backend:a,inputSchema:o,hasContent:c!==void 0,hasDataInputs:r!==void 0,confirmation:d})));let p;R(e,"job")&&(l!==void 0&&f("MANIFEST_INVALID","an action is either the scheduled run or a job, not both","job"),p=z("job",()=>zc(e.job,{backend:a,inputSchema:o,hasContent:c!==void 0,hasDataInputs:r!==void 0,confirmation:d})));let u;return R(e,"jobAccess")&&(p!==void 0&&f("MANIFEST_INVALID","an action is either the job or a job control, not both","jobAccess"),u=z("jobAccess",()=>Hc(e.jobAccess,{backend:a,hasContent:c!==void 0}))),{actionId:n,capability:t,mutation:i,inputSchema:o,resultProjection:s,backend:a,...c===void 0?{}:{content:c},...r===void 0?{}:{dataInputs:r},...d===void 0?{}:{confirmation:d},...l===void 0?{}:{schedule:l},...p===void 0?{}:{job:p},...u===void 0?{}:{jobAccess:u}}}function Hc(e,n){return (n.backend.type!=="skill"||!("entry"in n.backend)||n.backend.entry!==we)&&f("MANIFEST_INVALID","jobAccess needs a tool-mode action","jobAccess"),n.hasContent&&f("MANIFEST_INVALID","a job control action takes no content","jobAccess"),(!Array.isArray(e)||e.length===0)&&f("MANIFEST_INVALID","jobAccess must list at least one operation","jobAccess"),(new Set(e).size!==e.length||!e.every(Xn))&&f("MANIFEST_INVALID","jobAccess must name each operation once: start, status or cancel","jobAccess"),Object.freeze([...e])}function zc(e,n){(n.backend.type!=="skill"||!("entry"in n.backend)||n.backend.entry!==we)&&f("MANIFEST_INVALID","job needs a tool-mode action","job"),(n.hasContent||n.hasDataInputs||n.confirmation!==void 0&&n.confirmation!=="none")&&f("MANIFEST_INVALID","a job action takes no content, dataInputs or native confirmation","job"),(n.inputSchema.required??[]).length>0&&f("MANIFEST_INVALID","a job action input must accept {}","inputSchema.required"),G(e)||f("MANIFEST_INVALID","job must be an object","job"),K(e,[],nc);let t=R(e,"deadlineMs")?e.deadlineMs:Wn.default;return Kn(t)||f("MANIFEST_INVALID","job deadlineMs is invalid","job.deadlineMs"),{deadlineMs:t}}function $c(e,n){(n.backend.type!=="skill"||!("entry"in n.backend)||n.backend.entry!==we)&&f("MANIFEST_INVALID","schedule needs a tool-mode action","schedule"),(n.hasContent||n.hasDataInputs||n.confirmation!==void 0&&n.confirmation!=="none")&&f("MANIFEST_INVALID","a scheduled action takes no content, dataInputs or native confirmation","schedule"),(n.inputSchema.required??[]).length>0&&f("MANIFEST_INVALID","a scheduled action input must accept {}","inputSchema.required"),G(e)||f("MANIFEST_INVALID","schedule must be an object","schedule"),K(e,Qa,ec),Gn(e.everyMinutes)||f("MANIFEST_INVALID","schedule everyMinutes is invalid","schedule.everyMinutes");let t=R(e,"timeoutMs")?e.timeoutMs:$n.default;return Jn(t)||f("MANIFEST_INVALID","schedule timeoutMs is invalid","schedule.timeoutMs"),{everyMinutes:e.everyMinutes,timeoutMs:t}}function Gc(e){return Zi(e)||f("MANIFEST_INVALID","skill backend env is invalid"),Object.freeze([...e])}function Jc(e){return Object.freeze({...e.in===void 0?{}:{in:Object.freeze({...e.in})},...e.out===void 0?{}:{out:Object.freeze({...e.out})}})}function Wc(e){return G(e)||f("INITIAL_STATE_INVALID","initialState must be an object"),K(e,ac,cc),e.path!=="ui/state.json"&&f("MANIFEST_INVALID","initialState path is not fixed"),R(e,"hash")?{path:"ui/state.json",hash:No(e.hash)}:{path:"ui/state.json"}}function Kc(e){let n=["wasm","terminal","htmlDocuments","appBrowser"];return (!G(e)||Object.keys(e).length===0||Object.keys(e).some(t=>!n.includes(t)||e[t]!==true))&&f("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 Xc(e,n){let t;try{t=ao(e);}catch(i){let o=i!==null&&typeof i=="object"&&"code"in i&&typeof i.code=="string"?i.code:"CSP_ORIGIN_INVALID";return f("MANIFEST_INVALID",o,void 0,o.toLowerCase().replace(/_/g,"-"))}if(t.frameDomains.length>0&&f("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&&f("MANIFEST_INVALID","runtime.terminal cannot be combined with csp.connectDomains","connectDomains","terminal-with-connect-domains"),Object.freeze({connectDomains:t.connectDomains})}function Yc(e,n){Qn(G(e)?gc(e,["csp","downloads","files","share"]):e,new Set,0,true,true),Yt(e),G(e)||f("MANIFEST_INVALID"),K(e,Xa,Ya),R(e,"_meta")&&z("_meta",()=>So(e._meta)),e.manifestVersion!==2&&f("MANIFEST_INVALID");let t;R(e,"runtime")&&(t=z("runtime",()=>Kc(e.runtime)));let i;R(e,"csp")&&(i=z("csp",()=>Xc(e.csp,t)));let o=z("pluginId",()=>Xt(e.pluginId,"pluginId")),r=z("definitionId",()=>Xt(e.definitionId,"definitionId")),s=z("version",()=>me(e,"version",1)),a=z("name",()=>lo(e.name,"name")),c=z("description",()=>lo(e.description,"description")),d;R(e,"icon")&&((typeof e.icon!="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(e.icon))&&f("MANIFEST_INVALID","icon is invalid","icon"),d=e.icon);let l;R(e,"tone")&&((typeof e.tone!="string"||!xt.includes(e.tone))&&f("MANIFEST_INVALID","tone is invalid","tone"),l=e.tone),e.entry!=="ui/index.html"&&f("MANIFEST_INVALID","entry path is not fixed","entry","fixed-value");let p;R(e,"entryHash")&&(p=z("entryHash",()=>No(e.entryHash)));let u;R(e,"initialState")&&(u=z("initialState",()=>Wc(e.initialState)));let y;R(e,"usage")&&(e.usage!=="card"&&e.usage!=="window"&&f("MANIFEST_INVALID","usage is invalid","usage"),y=e.usage);let g;R(e,"detailPanel")&&(typeof e.detailPanel!="boolean"&&f("MANIFEST_INVALID","detailPanel is invalid","detailPanel"),g=e.detailPanel);let _;if(R(e,"displayModes")){((y??je)!==je||!Array.isArray(e.displayModes)||e.displayModes.length===0)&&f("MANIFEST_INVALID","displayModes are only valid for window Apps","displayModes");let v=new Set(["inline","floating","focused"]);(new Set(e.displayModes).size!==e.displayModes.length||e.displayModes.some(pe=>typeof pe!="string"||!v.has(pe)))&&f("MANIFEST_INVALID","displayModes are invalid","displayModes"),_=e.displayModes;}(y??je)===je&&g!==void 0&&f("MANIFEST_INVALID","detailPanel is card-only","detailPanel");let E=n.mode??"local";E!=="local"&&E!=="installed"&&E!=="published"&&f("MANIFEST_INVALID","manifest mode is invalid"),E!=="local"&&p===void 0&&f("MANIFEST_INVALID","installed manifests require entryHash","entryHash","required-when-installed"),E!=="local"&&u!==void 0&&u.hash===void 0&&f("MANIFEST_INVALID","installed manifests require initialState.hash","initialState.hash","required-when-installed"),(!Array.isArray(e.surfaces)||e.surfaces.length===0)&&f("MANIFEST_INVALID","surfaces are invalid","surfaces"),e.surfaces.length>2&&Y("surfaces exceed the v2 limit","surfaces","too-many-items");let U=[],k=new Set;for(let v of e.surfaces)(typeof v!="string"||!vt.includes(v))&&f("MANIFEST_INVALID","surface is unsupported","surfaces"),k.has(v)&&f("MANIFEST_INVALID","surfaces contain a duplicate","surfaces","duplicate-item"),k.add(v),U.push(v);G(e.size)||f("MANIFEST_INVALID","size must be an object","size"),z("size",()=>K(e.size,["height"]));let P=z("size",()=>me(e.size,"height",1));P>720&&Y("size.height exceeds the v2 limit","size.height","too-large");let w=z("stateProjection",()=>qt(e.stateProjection)),B=e.summaryProjection===void 0?void 0:z("summaryProjection",()=>qt(e.summaryProjection));B!==void 0&&B.allow.some(v=>!w.allow.includes(v))&&f("MANIFEST_INVALID","summaryProjection must be a subset of stateProjection.allow","summaryProjection");let N=z("dataPaths",()=>Pc(e.dataPaths,w.allow)),D=R(e,"deviceFeatures")?z("deviceFeatures",()=>Nc(e.deviceFeatures)):void 0,O=R(e,"downloads")?z("downloads",()=>Dc(e.downloads)):void 0,I=R(e,"share")?z("share",()=>Mc(e.share)):void 0,A=R(e,"files")?z("files",()=>Rc(e.files)):void 0,h=R(e,"desktopOnly")?z("desktopOnly",()=>Sc(e.desktopOnly)):void 0;Array.isArray(e.actions)||f("MANIFEST_INVALID","actions must be an array","actions"),e.actions.length>32&&Y("actions exceed the v2 limit","actions","too-many-items");let T=[],V=new Set,x=0,X=0;for(let[v,pe]of e.actions.entries()){let be=`actions[${v}]`,Le=z(be,()=>Bc(pe));if(V.has(Le.actionId)&&f("MANIFEST_INVALID","actions contain a duplicate actionId",`${be}.actionId`,"duplicate-item"),Le.schedule!==void 0&&(x+=1,x>Yi&&f("MANIFEST_INVALID","an App declares at most one scheduled action",`${be}.schedule`,"duplicate-item")),Le.job!==void 0&&(X+=1,X>qi&&f("MANIFEST_INVALID","an App declares at most one job action",`${be}.job`,"duplicate-item")),Le.backend.type==="core"&&Le.backend.handler==="state.set"){Le.mutation||f("MANIFEST_INVALID","state.set actions must be mutations",`${be}.mutation`);for(let qs of Object.keys(Le.inputSchema.properties))w.allow.includes(qs)||f("MANIFEST_INVALID","state.set input paths must be projection-allowed",`${be}.inputSchema.properties`);}V.add(Le.actionId),T.push(Le);}return {manifestVersion:2,pluginId:o,definitionId:r,version:s,name:a,description:c,...d===void 0?{}:{icon:d},...l===void 0?{}:{tone:l},entry:"ui/index.html",...p===void 0?{}:{entryHash:p},...t===void 0?{}:{runtime:t},...i===void 0?{}:{csp:i},...u===void 0?{}:{initialState:u},...y===void 0?{}:{usage:y},...g===void 0?{}:{detailPanel:g},..._===void 0?{}:{displayModes:_},surfaces:U,size:{height:P},stateProjection:w,...B===void 0?{}:{summaryProjection:B},...N===void 0?{}:{dataPaths:N},...D===void 0?{}:{deviceFeatures:D},...O===void 0?{}:{downloads:O},...I===void 0?{}:{share:I},...A===void 0?{}:{files:A},...h===void 0?{}:{desktopOnly:h},actions:T}}function So(e){G(e)||f("MANIFEST_INVALID","_meta must be an object");let n=JSON.stringify(e);(n===void 0||Buffer.byteLength(n,"utf8")>tc)&&Y("_meta exceeds the 4 KiB limit",void 0,"meta-too-large");}function qc(e){let n={},t={};for(let r of e.actions){n[r.actionId]={capabilities:[r.capability],inputKeys:Object.keys(r.inputSchema.properties??{}),...r.dataInputs===void 0?{}:{dataInputs:r.dataInputs},resultProjection:r.resultProjection,...r.confirmation===void 0?{}:{confirmation:r.confirmation},...r.content===void 0?{}:{content:r.content},...r.schedule===void 0?{}:{schedule:r.schedule},...r.job===void 0?{}:{job:r.job},...r.jobAccess===void 0?{}:{jobAccess:r.jobAccess},...r.backend.type!=="skill"||r.backend.env===void 0?{}:{env:r.backend.env}};let s=r.backend.type==="skill"||r.backend.type==="core"&&r.backend.handler==="state.set";t[r.actionId]={actionId:r.actionId,mutation:r.mutation,backend:r.backend,launchPolicy:s?"allowed":"denied",...s?{}:{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},o={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:o}}function ei(e,n,t,i,o,r){if(typeof e=="string"){let s=o.length>0&&r.some(a=>nn(o.join("."),a));return (e.length>4096||et(e,false,false,s))&&ge("state contains an unsafe string"),e}if(e===null||typeof e=="boolean")return e;if(typeof e=="number")return Number.isFinite(e)||ge("state contains a non-finite number"),e;(e===void 0||typeof e!="object"||typeof e=="function"||typeof e=="bigint")&&ge("state contains a non-JSON value"),t>8&&ge("state is too deep"),n.has(e)&&ge("state contains a cycle"),n.add(e);try{let s;if(Array.isArray(e))e.length>128&&ge("state array is too long"),s=e.map(c=>ei(c,n,t+1,2097152,o,r));else {G(e)||ge("state contains a non-plain object");let c={};for(let[d,l]of Object.entries(e))(d.length>4096||!Hn.test(d)||on(d))&&(d.length>4096&&ge("state key is too long"),ge("state contains a reserved or invalid key")),c[d]=ei(l,n,t+1,2097152,[...o,d],r);s=c;}let a=JSON.stringify(s);return (a===void 0||Buffer.byteLength(a,"utf8")>i)&&ge("state subtree is too large"),s}finally{n.delete(e);}}function ti(e,n=[]){G(e)||ge("initial state must be a JSON object");let t=ei(e,new Set,0,2097152,[],n);return (t===null||Array.isArray(t)||typeof t!="object")&&ge(),t}function Zc(e,n={}){Qn(e),G(e)||f("MANIFEST_INVALID"),K(e,Ka),e.manifestVersion!==1&&f("MANIFEST_INVALID");let t=Kt(Ne(e,"pluginId")),i=Kt(Ne(e,"definitionId")),o=me(e,"version",1),r=me(e,"primitiveSet",1),s=n.supportedPrimitiveSet??Fa;(!Number.isSafeInteger(s)||s<1)&&f("MANIFEST_INVALID"),r>s&&f("PRIMITIVE_SET_UNSUPPORTED"),G(e.activation)||f("MANIFEST_INVALID"),K(e.activation,["kind","language"]),e.activation.kind!=="fenced-code"&&f("MANIFEST_INVALID");let a=Kt(Ne(e.activation,"language")),c=hc(e.schema),d=Tc(e.layout,c);return {manifestVersion:1,pluginId:t,definitionId:i,version:o,primitiveSet:r,activation:{kind:"fenced-code",language:a},schema:c,layout:d}}function Qc(e,n={}){return G(e)||f("MANIFEST_INVALID"),Object.hasOwn(e,"lineage")&&f("MANIFEST_INVALID","lineage is only allowed in product bundle indexes"),e.manifestVersion===2?Yc(e,n):Zc(e,n)}function Ke(e,n={}){try{return Qc(e,n)}catch(t){if(t instanceof ae)throw t;return f("MANIFEST_INVALID")}}function _n(e,n={}){let t=Ke(e,n);return t.manifestVersion===2?qc(t):t}var Fa,ja,Va,Po,Ba,Ha,za,$a,po,Ga,Ja,Wa,Ka,Xa,Ya,qa,Za,Qa,ec,nc,tc,ic,oc,rc,sc,ac,cc,dc,pc,lc,uc,fc,yc,Ac,Ic,ae,uo,fo,Oc,yo,wc,Ao,Io,Cc,Uc,kc,ii=F(()=>{m();Jt();Re();Vt();Qi();Gt();Bt();Ht();co();Ge();Fa=1,ja=/^[a-z][a-zA-Z0-9]*(\.[a-zA-Z0-9]+)+$/,Va=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,Po=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,Ba=/<\/?[A-Za-z][^>]*>/,Ha=/^(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)/,za=/^(?:https?|file|ftp|ws|wss):\/\//i,$a=/^\s*(?:javascript|data):/i,po=/data:[^,\s]*,/i,Ga=/(?:https?|file|ftp|ws|wss):\/\//i,Ja=/javascript:/i,Wa=/(?:^[\s]*|[\s"'(=])(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)(?=[^\s"'<>])[^\s"'<>]*/,Ka=["manifestVersion","pluginId","definitionId","version","primitiveSet","activation","schema","layout"],Xa=["manifestVersion","pluginId","definitionId","version","name","description","entry","surfaces","size","stateProjection","actions"],Ya=["_meta","icon","tone","entryHash","runtime","csp","initialState","usage","detailPanel","displayModes","summaryProjection","dataPaths","focusedAiDataPaths","deviceFeatures","downloads","share","files","desktopOnly"],qa=["actionId","capability","mutation","inputSchema","resultProjection","backend"],Za=["confirmation","dataInputs","content","schedule","job","jobAccess","_meta"],Qa=["everyMinutes"],ec=["timeoutMs"],nc=["deadlineMs"],tc=4*1024,ic=["type","handler"],oc=["type","command"],rc=["env"],sc=["type","entry"],ac=["path"],cc=["hash"],dc=/^[0-9a-f]{64}$/,pc=/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/,lc=/[\r\n]/,uc=16,fc=16,yc=32,Ac=/^[a-z][A-Za-z0-9]{0,31}$/,Ic=["card-shell","meta-banner","heading","labeled-text","step-flow","text-list"],ae=class e extends Error{constructor(t,i=t,o,r){super(i);this.code=t;this.path=o;this.rule=r;}code;path;rule;name="UiPluginValidationError";withPathPrefix(t){return new e(this.code,this.message,hn(t,this.path),this.rule)}};uo=200,fo=3,Oc=/^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/;yo=200,wc=2,Ao=4,Io=100,Cc=/^[\p{L}\p{N}][\p{L}\p{N}\p{M}_-]*$/u,Uc=[".git",".crewx","node_modules","apps","skills"],kc=/[\u0000-\u001f\u007f-\u009f\\:<>"|?*]/;});function Co(e){return typeof e=="string"&&e.length<=nd&&ed.test(e)}function j(e,n,t,i,o){throw new Se(e,{path:n,rule:t,...i===void 0?{}:{message:i},...o===void 0?{}:{file:o}})}function ie(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 q(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function _e(e){let n=`_meta["${Ve}"]`;return e===void 0||e===""?n:e.startsWith("[")?`${n}${e}`:`${n}.${e}`}function rd(e){return e.toLowerCase().replace(/_/g,"-")}function sd(e){if(e===void 0||e==="")return "";let n=/^([^.[]+)(.*)$/.exec(e);if(!n)return _e(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 _e("definitionVersion");case "definitionId":return _e("definitionId");default:return _e(`${t}${i}`)}}function Uo(e,n,t){return {path:t(e.path),rule:e.rule??rd(e.code),...e.message!==e.code?{message:e.message}:{},file:n}}function ko(e){return JSON.parse(JSON.stringify(e))}function si(e,n,t=0,i=new Set){if(typeof e=="string"){e.length>4096&&j("LIMIT_EXCEEDED",n,"string-too-long"),(td.test(e)||id.test(e)||od.test(e))&&j("UNSAFE_VALUE",n,"unsafe-value");return}if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){Number.isFinite(e)||j("MANIFEST_INVALID",n,"non-finite-number");return}typeof e!="object"&&j("MANIFEST_INVALID",n,"non-json-value"),t>8&&j("LIMIT_EXCEEDED",n,"too-deep"),i.has(e)&&j("MANIFEST_INVALID",n,"cycle"),i.add(e);try{if(Array.isArray(e)){e.length>128&&j("LIMIT_EXCEEDED",n,"array-too-long"),e.forEach((o,r)=>si(o,`${n}[${r}]`,t+1,i));return}ie(e)||j("MANIFEST_INVALID",n,"non-plain-object");for(let[o,r]of Object.entries(e))si(r,n===""?o:`${n}.${o}`,t+1,i);}finally{i.delete(e);}}}function he(e,n){return (typeof e!="string"||e.length===0)&&j("MANIFEST_INVALID",n,"string"),e}function cn(e,n){return ie(e)||j("MANIFEST_INVALID",n,"object"),e}function ad(e,n){Array.isArray(e)||j("MANIFEST_INVALID",n,"array"),e.forEach((t,i)=>he(t,`${n}[${i}]`));}function cd(e,n){typeof e!="boolean"&&j("MANIFEST_INVALID",n,"boolean");}function En(e,n,t,i){for(let o of Object.keys(e))!t.includes(o)&&!i.includes(o)&&j("MANIFEST_INVALID",`${n}.${o}`,"unknown-key");for(let o of t)q(e,o)||j("MANIFEST_INVALID",`${n}.${o}`,"missing-key");}function dd(e,n){if(e!=="icon")switch(si(n,e),e){case "long_description":case "homepage":case "documentation":case "support":case "license":he(n,e);return;case "author":{let t=cn(n,e);En(t,e,["name"],["email","url"]);for(let i of Object.keys(t))he(t[i],`${e}.${i}`);return}case "repository":{let t=cn(n,e);En(t,e,[],["type","url"]);for(let i of Object.keys(t))he(t[i],`${e}.${i}`);return}case "icons":{Array.isArray(n)||j("MANIFEST_INVALID",e,"array"),n.forEach((t,i)=>{let o=`${e}[${i}]`,r=cn(t,o);En(r,o,["src","size"],["theme"]),he(r.src,`${o}.src`),he(r.size,`${o}.size`),q(r,"theme")&&he(r.theme,`${o}.theme`);});return}case "screenshots":case "keywords":case "privacy_policies":ad(n,e);return;case "tools":{Array.isArray(n)||j("MANIFEST_INVALID",e,"array"),n.forEach((t,i)=>{let o=`${e}[${i}]`,r=cn(t,o);En(r,o,["name"],["description"]),he(r.name,`${o}.name`),q(r,"description")&&he(r.description,`${o}.description`);});return}case "prompts":{Array.isArray(n)||j("MANIFEST_INVALID",e,"array"),n.forEach((t,i)=>{let o=`${e}[${i}]`,r=cn(t,o);En(r,o,["name","text"],["description","arguments"]),he(r.name,`${o}.name`),he(r.text,`${o}.text`);});return}case "tools_generated":case "prompts_generated":cd(n,e);return;case "localization":case "compatibility":case "user_config":cn(n,e);return;default:j("MANIFEST_INVALID",e,"unknown-key");}}function nt(e){return typeof e=="string"&&Pe.test(e)?e:void 0}function xo(e){return Number.isSafeInteger(e)&&e>=1?e:void 0}function pd(e){let n=nt(e.name);if(n===void 0)return;let t=e._meta,i=ie(t)?t[Ve]:void 0,o=ie(i)?i:{},r=q(o,"definitionId")?nt(o.definitionId):n,s=q(o,"definitionVersion")?xo(o.definitionVersion):1;return {pluginId:n,...r===void 0?{}:{definitionId:r},...s===void 0?{}:{definitionVersion:s}}}function ld(e){let n=nt(e.pluginId);if(n===void 0)return;let t=nt(e.definitionId),i=xo(e.version);return {pluginId:n,...t===void 0?{}:{definitionId:t},...i===void 0?{}:{definitionVersion:i}}}function di(e){try{let n=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e));if(!ie(n))return !1;let t=n._meta;return ie(t)&&q(t,Ve)}catch{return false}}function ud(e,n){if(e===de)return n.builtinOnly===true;let t=n._meta,i=ie(t)?t[Ve]:void 0;return ie(i)&&i.builtinOnly===true}function fd(e,n){q(e,"server")&&j("MANIFEST_INVALID","server","server-unsupported","phase 1 runs CrewX-owned Apps only");for(let a of Object.keys(e))ai.includes(a)||j("MANIFEST_INVALID",a,"unknown-key");for(let a of ci)q(e,a)||j("MANIFEST_INVALID",a,"missing-key");e.manifest_version!==oi&&j("MANIFEST_INVALID","manifest_version","unsupported-version",`manifest_version must be "${oi}"`),Co(e.version)||j("MANIFEST_INVALID","version","semver","version must be a semver.org version such as 0.1.0");let t=e._meta;ie(t)||j("MANIFEST_INVALID","_meta","object"),q(t,Ve)||j("MANIFEST_INVALID",_e(),"missing-key");let i=t[Ve];ie(i)||j("MANIFEST_INVALID",_e(),"object");for(let a of Object.keys(i))ri.includes(a)||wo.includes(a)||j("MANIFEST_INVALID",_e(a),"unknown-key");for(let a of ri)a==="actions"&&n!==void 0||q(i,a)||j("MANIFEST_INVALID",_e(a),"missing-key");if(n!==void 0&&q(i,"actions")&&j("MANIFEST_INVALID",_e("actions"),"two-truths",`actions are declared in both ${W} and ${$}; a server.ts App keeps them in the tools file only`),yd(i.actions),q(i,"definitionVersion")){let a=i.definitionVersion;(!Number.isSafeInteger(a)||a<1)&&j("MANIFEST_INVALID",_e("definitionVersion"),"positive-integer");}let o={};for(let a of Ro)q(e,a)&&(dd(a,e[a]),o[a]=ko(e[a]));let r={};for(let[a,c]of Object.entries(t))a!==Ve&&(r[a]=c);let s={manifestVersion:2,pluginId:e.name,definitionId:q(i,"definitionId")?i.definitionId:e.name,version:q(i,"definitionVersion")?i.definitionVersion:1,name:e.display_name,description:e.description};for(let[a,c]of Object.entries(i))a==="definitionId"||a==="definitionVersion"||(s[a]=c);return n!==void 0&&(s.actions=n.map(a=>({...a,backend:{type:"skill",entry:we}}))),Object.keys(r).length>0&&(s._meta=r),{v2Input:s,...Object.keys(r).length>0?{vendorMeta:r}:{},passthrough:o}}function yd(e){Array.isArray(e)&&e.forEach((n,t)=>{let i=ie(n)?n.backend:void 0;ie(i)&&q(i,"entry")&&j("MANIFEST_INVALID",_e(`actions[${t}].backend.entry`),"entry-not-authorable",`an action in ${W} cannot name an entry; a server.ts App declares its actions in ${$}`);});}function Ad(e,n,t){ie(e)||j("MANIFEST_INVALID","","not-object","manifest.json must be a JSON object",W);let i;try{i=fd(e,t);}catch(s){throw s instanceof Se?new Se(s.code,{...s.reason,file:W}):s}let o;try{let s=Ke(i.v2Input,{mode:n.mode??"local"});s.manifestVersion!==2&&j("MANIFEST_INVALID","","v2-required"),o=s;}catch(s){throw s instanceof ae?new Se(s.code,Uo(s,W,sd)):s}let r=e.tools;if(Array.isArray(r)){let s=new Set(o.actions.map(a=>a.actionId));r.forEach((a,c)=>{let d=a.name;if(!s.has(d))throw new Se("MANIFEST_INVALID",{path:`tools[${c}].name`,rule:"tool-not-action",message:"every tools[].name must be an action id",file:W})});}return {file:W,manifest:o,v2Input:i.v2Input,releaseVersion:e.version,...Object.keys(i.passthrough).length>0?{mcpb:i.passthrough}:{}}}function Id(e,n){try{let t=Ke(e,{mode:n.mode??"local"});if(t.manifestVersion!==2)throw new Se("MANIFEST_INVALID",{path:"manifestVersion",rule:"v2-required",message:"a workspace App requires manifestVersion 2",file:de});return {file:de,manifest:t,v2Input:e}}catch(t){throw t instanceof ae?new Se(t.code,Uo(t,de,i=>i??"")):t}}function dn(e){return le(_n(e).definition)}function Oo(e){let{entryHash:n,initialState:t,...i}=e,o={...i};return t!==void 0&&(o.initialState={path:t.path}),ko(o)}function gd(e,n){let t=Oo(e),i=Oo(n);return [...new Set([...Object.keys(t),...Object.keys(i)])].sort().filter(r=>te(t[r]??null)!==te(i[r]??null))}function md(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 hd(e,n){let t=gd(e,n),i=md(e,n),o="";try{let r=dn(e),s=dn(n);i=i||r!==s,o=` (definition hash ${r.slice(0,12)} vs ${s.slice(0,12)})`;}catch{i=true;}t.length===0&&!i||j("MANIFEST_DUAL_MISMATCH","","dual-manifest-mismatch",`${W} and ${de} normalize to different definitions${o}`+(t.length>0?`; differing fields: ${t.join(", ")}`:""));}function De(e,n,t="MANIFEST_INVALID",i){return {code:t,reason:{path:e,rule:n,...i===void 0?{}:{message:i},file:$},files:[]}}function Lo(e){return {...De("","tools-needs-manifest-json","MANIFEST_INVALID",`${$} is read with ${W} only`),files:e}}function _d(e,n){if(e.byteLength>n)return {failure:De("","file-too-large","LIMIT_EXCEEDED")};let t;try{t=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e));}catch{return {failure:De("","invalid-json")}}if(!ie(t))return {failure:De("","not-object","MANIFEST_INVALID",`${$} must be a JSON object`)};for(let o of Object.keys(t))if(o!=="schemaVersion"&&o!=="actions")return {failure:De(o,"unknown-key")};for(let o of ["schemaVersion","actions"])if(!q(t,o))return {failure:De(o,"missing-key")};if(t.schemaVersion!==1)return {failure:De("schemaVersion","unsupported-version","MANIFEST_INVALID",`schemaVersion must be ${1}`)};let i=t.actions;if(!Array.isArray(i))return {failure:De("actions","array")};for(let[o,r]of i.entries()){if(!ie(r))return {failure:De(`actions[${o}]`,"object")};if(q(r,"backend"))return {failure:De(`actions[${o}].backend`,"tools-backend","MANIFEST_INVALID",`an action in ${$} cannot carry a backend`)}}return {actions:i}}function Ed(e,n){let t=n.maxBytes??262144,i=[],o=new TextDecoder("utf-8",{fatal:true});for(let r of Q){let s=e[r];if(s===void 0)continue;if(s.byteLength>t)return {parsed:i,failure:{code:"LIMIT_EXCEEDED",reason:{path:"",rule:"file-too-large",file:r},files:[r]}};let a;try{a=JSON.parse(o.decode(s));}catch{return {parsed:i,failure:{code:"MANIFEST_INVALID",reason:{path:"",rule:"invalid-json",file:r},files:[r]}}}if(!ie(a))return {parsed:i,failure:{code:"MANIFEST_INVALID",reason:{path:"",rule:"not-object",message:`${r} must be a JSON object`,file:r},files:[r]}};i.push({file:r,raw:a});}return {parsed:i}}function He(e,n={}){let{parsed:t,failure:i}=Ed(e,n),o=Q.filter(y=>e[y]!==void 0);if(i!==void 0)return {ok:false,rejection:i,parseFailure:true,builtinOnly:false};let r=e[$],s=r===void 0?void 0:_d(r,n.maxBytes??262144);if(t.length===0)return {ok:false,rejection:s===void 0?{code:"MANIFEST_INVALID",reason:{path:"",rule:"no-manifest-file",message:"neither manifest.json nor ui-plugin.json is present"},files:[]}:Lo(o),parseFailure:true,builtinOnly:false};let a=t[0],c=a.file===W?pd(a.raw):ld(a.raw),d=t.some(y=>ud(y.file,y.raw)),l;if(s!==void 0){let y=t.some(g=>g.file===W)?s.failure:Lo(o);if(y!==void 0)return {ok:false,rejection:y,parseFailure:false,...c===void 0?{}:{identity:c},builtinOnly:d};l=s.actions;}let p=[];try{for(let y of t)p.push(y.file===W?Ad(y.raw,n,l):Id(y.raw,n));p.length===2&&hd(p[0].manifest,p[1].manifest);}catch(y){if(y instanceof Se)return {ok:false,rejection:{code:y.code,reason:y.reason,files:y.code==="MANIFEST_DUAL_MISMATCH"?[...Q]:y.reason.file===void 0||y.reason.file===$?o:[y.reason.file]},parseFailure:false,...c===void 0?{}:{identity:c},builtinOnly:d};throw y}let u=p[0];return {ok:true,...u,identity:c??{pluginId:u.manifest.pluginId},files:o}}var W,de,Q,oi,Ve,ai,ci,Ro,ri,wo,ed,nd,td,id,od,Se,tt=F(()=>{m();Je();Re();Gt();Ge();ii();W="manifest.json",de="ui-plugin.json",Q=[W,de],oi="0.3",Ve="dev.crewx",ai=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"]),ci=Object.freeze(["manifest_version","name","display_name","version","description","_meta"]),Ro=Object.freeze(ai.filter(e=>e!=="server"&&!ci.includes(e))),ri=Object.freeze(["entry","surfaces","size","stateProjection","actions"]),wo=Object.freeze(["definitionId","definitionVersion","icon","tone","entryHash","runtime","initialState","usage","detailPanel","displayModes","summaryProjection","dataPaths","focusedAiDataPaths","csp","deviceFeatures","downloads","share","files","desktopOnly"]),ed=/^(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-]+)*))?$/,nd=256,td=/<\/?[A-Za-z][^>]*>/,id=/^\s*javascript:/i,od=/data:[^,\s]*,/i;Se=class extends Error{constructor(t,i){super(`${t}: ${i.path||"<file>"} (${i.rule})`);this.code=t;this.reason=i;}code;reason};});function zo(e){if(e===void 0)return {kind:"none"};if(typeof e!="string")return {kind:"invalid",reason:"bad-path"};if(Pd.test(e))return {kind:"url",declared:e};if(!Sd(e))return {kind:"invalid",reason:"bad-path",declared:e};let n=e.lastIndexOf("."),t=n<0?void 0:Td.get(e.slice(n+1).toLowerCase());return t===void 0?{kind:"invalid",reason:"bad-type",declared:e}:{kind:"file",path:e,contentType:t}}function Sd(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 Tn(e,n){let t=zo(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:[pi(t.reason,t.declared)]};let i=await n(t.path);if(typeof i=="string")return {diagnostics:[pi(i,t.path)]};let o=$o(t.contentType,i);if(!o.ok)return {diagnostics:[pi(o.reason,t.path)]};let r={path:t.path,contentType:t.contentType,byteLength:i.byteLength,bytes:i},s=o.square===false?[{code:"ICON_NOT_SQUARE",severity:"warning",declared:t.path}]:[];return {file:r,diagnostics:s}}function pi(e,n){return {code:"ICON_INVALID",severity:"error",reason:e,...n===void 0?{}:{declared:n}}}function $o(e,n){if(n.byteLength>262144)return {ok:false,reason:"too-large"};if(e==="image/png")return !Vo(n,Nd)||vd(n,12,16)!=="IHDR"||n.byteLength<24?{ok:false,reason:"bytes-mismatch"}:{ok:true,square:jo(Bo(n,16),Bo(n,20))};if(e==="image/jpeg"){if(!Vo(n,Dd))return {ok:false,reason:"bytes-mismatch"};let t=kd(n);return {ok:true,square:t===void 0?void 0:jo(t.width,t.height)}}return Md(n)}function Md(e){let n;try{n=bd.decode(e);}catch{return {ok:false,reason:"bytes-mismatch"}}return Cd(n)?{ok:false,reason:"unsafe-svg"}:Od.test(n)?{ok:true,square:Ud(n)}:{ok:false,reason:"bytes-mismatch"}}function Cd(e){if(Ld.some(n=>n.test(e)))return true;for(let n of e.matchAll(Rd))if(!(n[1]??n[2]??n[3]??"").startsWith("#"))return true;for(let n of e.matchAll(wd))if(vo.lastIndex=n.index??0,!vo.test(e))return true;return false}function Ud(e){let n=/<svg\b[^>]*>/i.exec(e)?.[0];if(n===void 0)return;let t=Go(n,"viewBox");if(t!==void 0){let r=t.trim().split(/[\s,]+/).map(Number);return r.length===4&&r.every(Number.isFinite)?r[2]===r[3]:void 0}let i=Fo(n,"width"),o=Fo(n,"height");return i===void 0||o===void 0?void 0:i===o}function Go(e,n){let t=new RegExp(`\\s${n}\\s*=\\s*(?:"([^"]*)"|'([^']*)')`).exec(e);return t?.[1]??t?.[2]}function Fo(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 kd(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(xd(t))return n+9>e.byteLength?void 0:{height:Ho(e,n+5),width:Ho(e,n+7)};n+=2+i;}}function xd(e){return e>=192&&e<=207&&e!==196&&e!==200&&e!==204}function jo(e,n){if(!(e<=0||n<=0))return e===n}function Vo(e,n){return e.byteLength>=n.length&&n.every((t,i)=>e[i]===t)}function vd(e,n,t){return String.fromCharCode(...e.subarray(n,t))}function Bo(e,n){return (e[n]<<24|e[n+1]<<16|e[n+2]<<8|e[n+3])>>>0}function Ho(e,n){return e[n]<<8|e[n+1]}var Td,bd,Pd,Nd,Dd,Od,Ld,Rd,wd,vo,li=F(()=>{m();Td=new Map([["svg","image/svg+xml"],["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"]]),bd=new TextDecoder("utf-8",{fatal:true}),Pd=/^[A-Za-z][A-Za-z0-9+.-]*:/,Nd=[137,80,78,71,13,10,26,10],Dd=[255,216,255];Od=/^\s*(?:<\?[\s\S]*?\?>\s*|<!--[\s\S]*?-->\s*)*<svg(?=[\s/>])/,Ld=[/<script/i,/[\s"'/]on[a-z]+\s*=/i,/<foreignobject/i,/<!doctype/i,/<!entity/i,/<(?:iframe|embed|object)\b/i,/@import/i],Rd=/(?:^|[\s"'/])(?:xlink:)?href\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+))/gi,wd=/url\(/gi,vo=/url\(\s*["']?#/iy;});var ui=F(()=>{m();Ji();tt();li();ii();Ge();});function S(e,n=e){throw new Me(e,n)}var Me,ot=F(()=>{m();Me=class extends Error{constructor(t,i=t){super(i);this.code=t;}code;name="McpAppContractError"};});var ir=F(()=>{m();});var or=F(()=>{m();Je();Re();ot();ir();});function sr(e,n){return rr.add(e),n!==void 0&&Xd.set(e,n),e}function pn(e){return e!==null&&typeof e=="object"&&rr.has(e)}var rr,Xd,rt=F(()=>{m();rr=new WeakSet,Xd=new WeakMap;});function Dn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function yi(e,n,t=[]){let i=new Set([...n,...t]),o=Object.keys(e);return n.every(r=>Object.hasOwn(e,r))&&o.every(r=>i.has(r))}function dr(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let n of Object.values(e))dr(n);return Object.freeze(e)}function oe(e){throw new Oe("LINEAGE_INVALID",e)}function tp(e){throw new Oe("LINEAGE_STALE",e)}function pr(e){if(!Dn(e)||!yi(e,Zd,Qd)||!Dn(e.actions))return oe("Lineage definition shape is invalid");for(let n of Object.values(e.actions))if(!Dn(n)||!yi(n,ep,np))return oe("Lineage action definition shape is invalid");return e}function ip(e){if(!Dn(e)||!yi(e,Yd,qd))return oe("Lineage entry shape is invalid");if(!Number.isSafeInteger(e.version)||e.version<1||typeof e.hash!="string"||!ar.test(e.hash))return oe("Lineage entry identity is invalid");if(e.sourceHash!==void 0&&(typeof e.sourceHash!="string"||!ar.test(e.sourceHash)))return oe("Lineage source hash is invalid");if(e.compat!==void 0&&e.compat!=="break")return oe("Lineage compatibility marker is invalid");let n=pr(e.definition);if(n.version!==e.version)return oe("Lineage version does not match its definition");if(e.sourceHash!==void 0&&n.sourceHash!==e.sourceHash)return oe("Lineage source hash does not match its definition");let t;try{t=le(n),Ie({...n,hash:e.hash});}catch{return oe("Lineage definition is invalid")}return t!==e.hash?oe("Lineage definition hash does not match"):dr({version:e.version,hash:e.hash,definition:n,...e.sourceHash===void 0?{}:{sourceHash:e.sourceHash},...e.compat===void 0?{}:{compat:e.compat}})}function cr(e){return e.stateProjection?.allow??[]}function op(e,n){let t=[],i=new Set(cr(n));cr(e).some(a=>!i.has(a))&&t.push("S1_STATE_PROJECTION");let o=new Set(n.dataPaths??[]);(e.dataPaths??[]).some(a=>!o.has(a))&&t.push("S2_DATA_PATHS");for(let[a,c]of Object.entries(e.actions)){let d=n.actions[a];if(d&&(c.confirmation??"native")==="native"&&(d.confirmation??"native")!=="native"){t.push("S3_ACTION_CONFIRMATION");break}}Object.keys(e.legacy?.agentAccess??{}).some(a=>!Object.hasOwn(n.actions,a))&&t.push("S4_LEGACY_AGENT_ACTIONS");let s=e.summaryProjection?.allow;if(s!==void 0){let a=new Set(n.summaryProjection?.allow??[]);s.some(c=>!a.has(c))&&t.push("S5_SUMMARY_PROJECTION");}return t}function rp(e,n){return te(e)===te(n)}function Ai(e,n){if(!Array.isArray(e)||e.length===0)return oe("Definition lineage is missing");if(!Dn(n)||typeof n.hash!="string")return oe("Current definition is invalid");let t,i;try{let{hash:a,...c}=n;i=pr(c),t={...i,hash:a},Ie(t);}catch{return oe("Current definition is invalid")}let o=e.map(ip),r=o[0].definition.id;if(o.some(a=>a.definition.id!==r))return oe("Lineage definition ids do not match");if(o.some((a,c)=>c>0&&a.version<=o[c-1].version))return oe("Lineage generations are not in increasing version order");if(o.some((a,c)=>o.findIndex(d=>d.hash===a.hash)!==c))return oe("Lineage contains a duplicate hash");let s=o[o.length-1];if(s.version!==t.version||s.hash!==t.hash||s.definition.id!==t.id||!rp(s.definition,i))return tp("The last lineage generation does not match the current package");if(t.legacy!==void 0){let a=new Set(Object.keys(t.actions)),c=new Set;for(let l of o)if(l.sourceHash===void 0)for(let p of Object.keys(l.definition.actions))a.has(p)&&c.add(p);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 Oe("LINEAGE_INVALID",`Lineage compatibility failed: ${l}`,[l])}}for(let a=0;a<o.length-1;a+=1){if(o.slice(a,-1).some(l=>l.compat==="break"))continue;let d=op(o[a].definition,t);if(d.length>0)throw new Oe("LINEAGE_INVALID",`Lineage compatibility failed: ${d.join(", ")}`,d)}return Object.freeze({entries:Object.freeze(o),current:t})}var Oe,ar,Yd,qd,Zd,Qd,ep,np,Ii=F(()=>{m();Je();Re();Oe=class extends Error{constructor(t,i=t,o=[]){super(i);this.code=t;this.violations=o;}code;violations;name="UiDefinitionLineageError"},ar=/^[0-9a-f]{64}$/,Yd=["version","hash","definition"],qd=["sourceHash","compat"],Zd=["id","version","actions"],Qd=["sourceHash","usage","detailPanel","displayModes","renderer","surfaces","stateProjection","dataPaths","summaryProjection","downloads","legacy"],ep=["capabilities"],np=["inputKeys","dataInputs","confirmation","resultProjection","content","env","schedule","job","jobAccess"];});var lr,ur,fr,yr,Ar=F(()=>{m();lr="text/html;profile=mcp-app",ur=["crewx_app_terminal_connect","crewx_app_html_viewer_open","crewx_app_browser","crewx_files_list","crewx_files_read","crewx_files_write","crewx_docs_share"],fr=["crewx_listWorkspaces","crewx_queryAgent","crewx_executeAgent","crewx_getTaskResult","crewx_listTasks","crewx_listAgents","callBrowser","openTab","listTabs","closeTab"],yr="text/html";});function Sn(e){return typeof e=="string"&&sp.includes(e)}function st(e,n){return e==="card"&&n?.type==="core"&&Sn(n.handler)}var sp,at=F(()=>{m();sp=Object.freeze(["card.secret-env"]);});function Ir(e,n=[],t){if(e.content!==void 0||e.confirmation!=="none")return "denied";let i=ap();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"&&Sn(e.backend.handler)||e.backend?.type==="skill"?"approval_required":e.backend===void 0&&n.includes(e.actionId)?"allowed":"denied"}function ap(e){return;}var gr=F(()=>{m();Je();rt();at();});function Ip(e){return Ln.has(e)&&(e.initialState===void 0||Ln.has(e.initialState))}function Tr(e,n,t,i){let o=i===void 0?void 0:Object.freeze({hash:i.hash,bytes:Object.freeze(i.bytes)}),r=Object.freeze({mimeType:yr,entryHash:e,html:n,bytes:Object.freeze(t),...o===void 0?{}:{initialState:o}});return o!==void 0&&Ln.add(o),Ln.add(r),r}function gp(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:ue}),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:ue}),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:ue}),n}function mp(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:ue},{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:{...gi}},required:["ref"],additionalProperties:false},textFallback:"A markdown file of this App is read through this App.",visibility:Object.freeze(["app"]),kind:"host",resourceBinding:ue},{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:{...gi},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:ue}),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:{...gi}},required:["ref"],additionalProperties:false},textFallback:"The Host share sheet opens for a markdown file of this App.",visibility:Object.freeze(["app"]),kind:"host",resourceBinding:ue}),n}function ze(e,n,t){return (typeof e!="string"||!_r.test(e))&&S(n,`${t} must be a safe identifier`),e}function Mn(e,n,t){let i=e??t;return (typeof i!="string"||i.trim().length===0||i.length>pp)&&S("TOOL_INVALID",`${n} must be a meaningful description`),i}function hi(e){return (typeof e!="string"||e.length===0||e.length>ln||!/<html(?:\s|>)/i.test(e)||!/<\/html\s*>/i.test(e))&&S("HTML_INVALID","MCP App HTML must be a non-empty HTML document"),e}function On(e,n=0){try{let t=Ae(e,n);return t.type!==void 0&&t.type!=="object"&&S("TOOL_INVALID","MCP App inputSchema must describe an object"),t}catch(t){if(t instanceof Me)throw t;S("TOOL_INVALID","MCP App inputSchema must be projection-safe JSON");}}function hp(e){return (typeof e!="string"||e.trim().length===0||e.length>lp)&&S("TOOL_INVALID","MCP App tools require a meaningful text fallback"),e}function _p(e){e===void 0&&S("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)&&S("TOOL_INVALID","MCP App tool visibility must contain model and/or app once"),n}function Pr(e){return (typeof e!="string"||!Er.test(e))&&S("RESOURCE_URI_INVALID","MCP App resource URI is not a registered ui:// URI"),e}function Nr(e){let n=ze(e.appId,"APP_ID_INVALID","Local App id"),t=Mn(e.name,"Local App name",n),i=Mn(e.description,"Local App description",`${t} interactive view`),o=lt(e.definition),r=hi(e.html),s=ct(e.entryHash,"Local App entry hash"),a=e.entryBytes===void 0?Array.from(new TextEncoder().encode(r)):pt(e.entryBytes,"Local App entry bytes");(dt(a)!==s||Mr(a)!==r)&&S("HTML_INVALID","Local App entry bytes do not match the HTML hash");let c=Ep(e),d=[];Array.isArray(e.actions)||S("TOOL_INVALID","Local App actions must be an array");for(let P of e.actions){let w=ze(P.actionId,"TOOL_ID_INVALID","Local App action id");(d.includes(w)||!Object.prototype.hasOwnProperty.call(o.actions,w))&&S("TOOL_INVALID",`Local App action is not declared by the UI definition: ${w}`),d.push(w);}let l=ze(e.readToolName,"TOOL_ID_INVALID","Local App read tool name"),p=e.actionToolName===void 0?void 0:ze(e.actionToolName,"TOOL_ID_INVALID","Local App action tool name");d.length===0&&p!==void 0&&S("TOOL_INVALID","A static local App cannot register an action tool"),d.length>0&&p===void 0&&S("TOOL_INVALID","A stateful local App requires an action tool name"),p!==void 0&&p===l&&S("TOOL_ID_CONFLICT",`Local App read and action tools share a name: ${l}`);let u=[...gp(e.runtime),...mp(e.hostTools)];u.some(P=>P.name===l||P.name===p)&&S("TOOL_ID_CONFLICT","Local App read or action tool conflicts with a requested Host capability");let y={name:l,description:`${t} current state`,inputSchema:Ap,textFallback:`${t} current state is available through its open instance.`,visibility:Object.freeze(["model","app"]),kind:"read",resourceBinding:ue},g=[Object.freeze(y)];if(g.push(...u.map(P=>Object.freeze(P))),p!==void 0){let P={name:p,description:`${t} actions`,inputSchema:_i(e.actions),textFallback:`${t} action requests are handled by the open App instance.`,visibility:Object.freeze(["app"]),kind:"action",resourceBinding:ue,actionIds:Object.freeze([...d])};g.push(Object.freeze(P));}let _=[],E=new Set(g.map(P=>P.name));if(p!==void 0)for(let P of e.actions){let w=`${p}__${P.actionId}`;if(w.length>128||!_r.test(w)){_.push(Object.freeze({toolName:w,actionId:P.actionId,reason:"name_too_long"}));continue}if(E.has(w)){_.push(Object.freeze({toolName:w,actionId:P.actionId,reason:"name_collision"}));continue}let B=Ir({actionId:P.actionId,confirmation:o.actions[P.actionId]?.confirmation,content:o.actions[P.actionId]?.content,backend:P.backend},e.modelActions),N=Object.freeze([...Dp(B,o.usage,P.backend)]),D={name:w,description:`${w} action`,inputSchema:On(P.inputSchema),textFallback:`${w} action requests are handled by the open App instance.`,visibility:N,kind:"action",resourceBinding:ue,actionId:P.actionId,actionIds:Object.freeze([P.actionId]),_meta:Object.freeze({ui:Object.freeze({visibility:N})})};g.push(Object.freeze(D)),E.add(w);}let U=Tr(s,r,a,c===void 0?void 0:{hash:c.hash,bytes:[...c.bytes]}),k={appId:n,name:t,description:i,...e.icon===void 0?{}:{icon:Or(e.icon)},...e.tone===void 0?{}:{tone:Lr(e.tone)},builtinOnly:false,definition:o,...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:ue,resource:U,tools:Object.freeze(g),toolDiagnostics:Object.freeze(_)};return ee(k)}function Dr(e={}){return new mi(e)}function _i(e){if(e.length===0)return On({type:"object",properties:{},additionalProperties:false});let n=e.map(i=>i.actionId),t=new Map;for(let i of e)t.set(i.actionId,On(i.inputSchema));return On(Tp(n,t),br)}function Ep(e){let n=e.definition.dataPaths??[];if(e.initialStateBytes===void 0){e.initialStateHash!==void 0&&S("STATE_INVALID","Initial state hash has no bytes"),e.initialState!==void 0&&Ae(e.initialState,0,n);return}e.initialStateHash===void 0&&S("STATE_INVALID","Initial state bytes require a hash");let t=ct(e.initialStateHash,"Initial state hash"),i=pt(e.initialStateBytes,"Initial state bytes");dt(i)!==t&&S("STATE_INVALID","Initial state bytes do not match the hash");let o;try{let r=new TextDecoder("utf-8",{fatal:!0}).decode(Uint8Array.from(i));o=Ae(JSON.parse(r),0,n);}catch{S("STATE_INVALID","Initial state bytes are not projection-safe JSON");}return e.initialState!==void 0&&te(o)!==te(Ae(e.initialState,0,n))&&S("STATE_INVALID","Initial state bytes do not match the state value"),{hash:t,bytes:Object.freeze([...i])}}function Tp(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 bp(e){let n=Rn(e),t=ze(n.appId,"APP_ID_INVALID","MCP App id"),i=hi(n.html);Pr(n.uiUri);let o=n.definition===void 0?void 0:lt(n.definition),r=e.provenance;r!==void 0&&(!pn(r)||r.appId!==t||r.definitionId!==o?.id||r.version!==o?.version||r.definitionHash!==o?.hash)&&S("TOOL_INVALID","Product App built-in registration provenance is not verified");let s=Object.freeze(n.tools.map(d=>ee(Rn(d)))),a=ee({...n,appId:t,html:i,...o===void 0?{}:{definition:o},...r===void 0?{}:{provenance:r},tools:s}),c=ee({uri:a.uiUri,mimeType:lr,text:i,...a.csp===void 0?{}:{_meta:{ui:{csp:a.csp}}}});return ee({appId:t,name:a.name,description:a.description,...a.icon===void 0?{}:{icon:a.icon},...a.tone===void 0?{}:{tone:a.tone},builtinOnly:a.builtinOnly,uiUri:a.uiUri,...o===void 0?{}:{definition:o},resourceBinding:Object.freeze({kind:"mcp",uri:a.uiUri}),resource:c,tools:s,descriptor:a})}function Pp(e){(e.resourceBinding.kind!=="instance"||e.builtinOnly!==false)&&S("STATE_INVALID","Local App registration binding is invalid"),Object.prototype.hasOwnProperty.call(e,"uiUri")&&S("STATE_INVALID","Local App registration cannot contain uiUri");let n=ze(e.appId,"APP_ID_INVALID","Local App id"),t=lt(e.definition),i=e.provenance;i!==void 0&&(!pn(i)||i.appId!==n||i.definitionId!==t.id||i.version!==t.version||i.definitionHash!==t.hash)&&S("TOOL_INVALID","Product App local registration provenance is not verified");let o=Np(e.resource),r=e.tools.map(a=>{ze(a.name,"TOOL_ID_INVALID","Local App tool name"),Mn(a.description,"Local App tool description","Local App tool"),hp(a.textFallback);let c=On(a.inputSchema,a.kind==="action"&&!("actionId"in a)?br:0);if((a.resourceBinding.kind!=="instance"||Object.prototype.hasOwnProperty.call(a,"resourceUri"))&&S("TOOL_INVALID","Local App tools cannot carry an MCP resource URI"),a.kind==="host")return (!yp.has(a.name)||a.visibility.length!==1||a.visibility[0]!=="app"||Object.prototype.hasOwnProperty.call(a,"actionId"))&&S("TOOL_INVALID","Local App Host tools must use an allow-listed name and app-only visibility"),ee({...a,inputSchema:c,visibility:Object.freeze(["app"])});if(a.kind==="action"){if("actionId"in a){let l=ze(a.actionId,"TOOL_ID_INVALID","Local App action id");Object.prototype.hasOwnProperty.call(t.actions,l)||S("TOOL_INVALID","Local App action tool references an undeclared action");let p=_p(a._meta.ui.visibility);return JSON.stringify(p)!==JSON.stringify(a.visibility)&&S("TOOL_INVALID","Local App action metadata visibility must match the tool visibility"),ee({...a,actionId:l,actionIds:Object.freeze([l]),inputSchema:c,visibility:p,_meta:{ui:{visibility:p}}})}let d=[...a.actionIds];return (d.length===0||d.some(l=>!Object.prototype.hasOwnProperty.call(t.actions,l)))&&S("TOOL_INVALID","Local App action tool references an undeclared action"),ee({...a,inputSchema:c,actionIds:Object.freeze(d)})}return ee({...a,inputSchema:c})}),s=ee({appId:n,name:Mn(e.name,"Local App name",e.appId),description:Mn(e.description,"Local App description",e.name),...e.icon===void 0?{}:{icon:Or(e.icon)},...e.tone===void 0?{}:{tone:Lr(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:ue,resource:o,tools:Object.freeze(r),toolDiagnostics:Object.freeze([...e.toolDiagnostics??[]])});return mr.has(e)?e:(mr.add(s),s)}function Np(e){let n=hi(e.html),t=ct(e.entryHash,"Local App entry hash");if(Ip(e))return e;let i=pt(e.bytes,"Local App entry bytes");(dt(i)!==t||Mr(i)!==n)&&S("HTML_INVALID","Local App entry bytes do not match the HTML hash");let o=e.initialState===void 0?void 0:{hash:ct(e.initialState.hash,"Initial state hash"),bytes:pt(e.initialState.bytes,"Initial state bytes")};return o&&dt(o.bytes)!==o.hash&&S("STATE_INVALID","Initial state bytes do not match the hash"),Tr(t,n,i,o)}function Dp(e,n,t){if(st(n,t))return ["model"];let i=t?.type==="core"&&Sn(t.handler);return e==="denied"||i?["app"]:["model","app"]}function Sp(e){return ee({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:Sr(e.definition),...e.provenance===void 0?{}:{provenance:e.provenance},entryHash:e.resource.entryHash,resourceBinding:ue,tools:e.tools})}function Mp(e){return ee({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:Sr(e.definition)},resourceBinding:Object.freeze({kind:"mcp",uri:e.uiUri}),tools:e.tools})}function lt(e){try{if(Object.isFrozen(e))return Ie(e),ee(e);let n=Rn(e);return Ie(n),ee(n)}catch(n){if(n instanceof Me)throw n;S("STATE_INVALID","UI definition is not a valid immutable definition");}}function Sr(e){return ee({id:e.id,version:e.version,hash:e.hash})}function Op(e){return e!==null&&typeof e=="object"&&typeof e.id=="string"&&Number.isSafeInteger(e.version)&&typeof e.hash=="string"}function hr(e,n,t){return `${e}\0${n}\0${t}`}function ct(e,n){return (typeof e!="string"||!dp.test(e))&&S("SERIALIZATION_INVALID",`${n} is invalid`),e}function dt(e){return Hi.createHash("sha256").update(Uint8Array.from(e)).digest("hex")}function pt(e,n){return (!Array.isArray(e)||e.some(t=>!Number.isInteger(t)||t<0||t>255))&&S("SERIALIZATION_INVALID",`${n} is invalid`),[...e]}function Mr(e){try{return new TextDecoder("utf-8",{fatal:!0}).decode(Uint8Array.from(e))}catch{S("SERIALIZATION_INVALID","UTF-8 bytes are invalid");}}function Or(e){return (typeof e!="string"||!up.test(e))&&S("TOOL_INVALID","MCP App icon is invalid"),e}function Lr(e){return (typeof e!="string"||!fp.has(e))&&S("TOOL_INVALID","MCP App tone is invalid"),e}function Rn(e,n=new Map){if(e===null||typeof e!="object")return e;let t=e;if(n.has(t)&&S("SERIALIZATION_INVALID","MCP App value contains a cycle"),Array.isArray(e)){let r=[];n.set(t,r);for(let s of e)r.push(Rn(s,n));return n.delete(t),r}let i;try{i=Object.getPrototypeOf(e);}catch{S("SERIALIZATION_INVALID","MCP App value cannot be cloned");}i!==Object.prototype&&i!==null&&S("SERIALIZATION_INVALID","MCP App value must be plain JSON");let o={};n.set(t,o);for(let[r,s]of Object.entries(e))Object.defineProperty(o,r,{configurable:true,enumerable:true,value:Rn(s,n),writable:true});return n.delete(t),o}function ee(e,n=new Set){if(e===null||typeof e!="object"||n.has(e)||Ln.has(e))return e;n.add(e);for(let t of Object.values(e))ee(t,n);return Object.freeze(e),e}var _r,Er,dp,ln,pp,lp,up,fp,yp,ue,Ap,Ln,mr,gi,br,mi,ut=F(()=>{m();or();Je();Re();rt();ot();Ii();Ar();gr();at();_r=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,Er=/^ui:\/\/crewx\/([A-Za-z][A-Za-z0-9._-]{0,127})\/([0-9a-f]{12})$/,dp=/^[0-9a-f]{64}$/,ln=8*1024*1024,pp=8*1024,lp=16*1024,up=/^[a-z][a-z0-9-]{0,63}$/,fp=new Set(["blue","violet","emerald","amber","rose","sky","slate","indigo"]),yp=new Set(ur),new Set(fr),ue=Object.freeze({kind:"instance"}),Ap=Object.freeze({type:"object",properties:Object.freeze({}),additionalProperties:false}),Ln=new WeakSet,mr=new WeakSet;gi={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.'};br=4;mi=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=[],o=[],r=[],s=new Set,a=new Set;for(let p of t?.listMcpApps()??[]){let u=bp(p);s.has(u.appId)&&S("APP_ID_CONFLICT",`MCP App id is already registered: ${u.appId}`),s.add(u.appId);let y=u.tools;for(let g of y)a.has(g.name)&&S("TOOL_ID_CONFLICT",`MCP App tool name is already registered: ${g.name}`),a.add(g.name),this.mcpToolByName.set(g.name,g),r.push(g);this.mcpResources.set(u.resource.uri,u.resource),i.push(u),o.push(u.descriptor);}let c=(n.localApps??n.locals??[]).map(Pp),d=new Set(c.flatMap(p=>p.tools.filter(u=>!(u.kind==="action"&&"actionId"in u)).map(u=>u.name))),l=[];for(let p of c){let u=p;s.has(u.appId)&&S("APP_ID_CONFLICT",`MCP App id is already registered: ${u.appId}`),s.add(u.appId);let y=[],g=[...u.toolDiagnostics??[]];for(let _ of u.tools){if(a.has(_.name)){if(_.kind==="host"&&this.localToolByName.get(_.name)?.kind==="host"){y.push(_);continue}if(_.kind==="action"&&"actionId"in _){g.push(Object.freeze({toolName:_.name,actionId:_.actionId,reason:"name_collision"}));continue}S("TOOL_ID_CONFLICT",`MCP App tool name is already registered: ${_.name}`);}if(_.kind==="action"&&"actionId"in _&&d.has(_.name)){g.push(Object.freeze({toolName:_.name,actionId:_.actionId,reason:"name_collision"}));continue}a.add(_.name),this.localToolByName.set(_.name,_),y.push(_);}(y.length!==u.tools.length||g.length!==(u.toolDiagnostics?.length??0))&&(u=ee({...u,tools:Object.freeze(y),toolDiagnostics:Object.freeze(g)})),l.push(u),this.localById.set(u.appId,u);}for(let p of i)this.registrationById.set(p.appId,p),this.launcherById.set(p.appId,Mp(p)),p.definition&&this.addDefinition(p.definition);for(let p of l)this.registrationById.set(p.appId,p),this.launcherById.set(p.appId,Sp(p)),this.addDefinition(p.definition);for(let p of n.definitions??[])this.addDefinition(p);for(let p of n.handlers??[])this.addHandler(p);this.builtinApps=Object.freeze(i),this.localApps=Object.freeze(l),this.builtinDescriptors=Object.freeze(o),this.builtinTools=Object.freeze(r);}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"||!Er.test(n)?null:this.mcpResources.get(n)??null}requireMcpAppResource(n){Pr(n);let t=this.mcpResources.get(n);return t||S("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,o=pn(i)&&i.launcher===false;return t?.definition?.usage!=="card"&&!o}))}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(!Op(n))return null;let t=this.definitionByKey.get($t(n));if(!t||t.hash!==n.hash)return null;try{return le(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(hr(n,t,i))??null}addDefinition(n){let t=lt(n),i=$t(t),o=this.definitionByKey.get(i);o&&o.hash!==t.hash&&S("STATE_INVALID",`UI definition generation conflicts: ${i}`),o||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")&&S("STATE_INVALID","UI action handler registration is invalid");let t=hr(n.definitionId,n.version,n.actionId);this.handlerByKey.has(t)&&S("TOOL_INVALID",`Duplicate UI action handler registration: ${t}`),this.handlerByKey.set(t,Object.freeze({...n}));}};});function Lp(e,n){let t=Nr({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(o=>({actionId:o.actionId,inputSchema:o.inputSchema,backend:o.backend})),...{}});return e.provenance===void 0?t:Object.freeze({...t,provenance:e.provenance})}function Rr(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=Lp(e);Dr({localApps:[t],definitions:[e.definition]});}var wr=F(()=>{m();ut();});function Rp(e){if(e===null||typeof e!="object"||!(Cr in e))throw new TypeError("scanCache must be created by createWorkspaceAppScanCache");return e[Cr]}function Ur(e,n){let t=Rp(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 Cr,kr=F(()=>{m();Cr=Symbol("crewx.workspace-app-scan-cache.state");});function fe(e){let n=typeof e=="object"&&e!==null&&"code"in e?String(e.code):"";return n==="ENOENT"?new M("NOT_FOUND"):n==="ELOOP"?new M("PATH_ESCAPED"):n==="EFBIG"||n==="EOVERFLOW"?new M("LIMIT_EXCEEDED"):n==="EACCES"||n==="EPERM"||n==="ENOTDIR"?new M("READ_DENIED"):new M("READ_DENIED")}function kp(e){if(typeof e!="string"||e.length===0||!ce.isAbsolute(e))throw new M("READ_DENIED")}function Ei(e){if(typeof e!="string"||ce.isAbsolute(e)||/[\\\u0000]/.test(e))throw new M("PATH_ESCAPED");if(e==="")return [];let n=e.split("/");if(n.some(t=>t.length===0||t==="."||t===".."))throw new M("PATH_ESCAPED");return n}function It(e,n){let t=ce.relative(e,n);return t===""||t!==".."&&!t.startsWith(`..${ce.sep}`)&&!ce.isAbsolute(t)}function fn(e){return {dev:e.dev,ino:e.ino,size:e.size,mtimeNs:e.mtimeNs,ctimeNs:e.ctimeNs}}function Ni(e,n){return e.dev===n.dev&&e.ino===n.ino}function Di(e,n){return Ni(e,n)&&e.size===n.size&&e.mtimeNs===n.mtimeNs&&e.ctimeNs===n.ctimeNs}async function ft(e){kp(e);let n,t;try{n=await promises.realpath(e),t=await promises.stat(n,{bigint:!0});}catch(i){throw fe(i)}if(!t.isDirectory())throw new M("READ_DENIED");return {realRoot:n,identity:fn(t)}}async function Fr(e,n,t){if(t.length<2||t[0]!=="apps"&&t[0]!=="skills")return;let i,o;try{if(i=ce.resolve(e,t[0],t[1]),o=await promises.realpath(i),!(await promises.stat(o,{bigint:!0})).isDirectory())throw new M("READ_DENIED")}catch(r){throw r instanceof M?r:fe(r)}if(!It(n,o))throw new M("PATH_ESCAPED");return o}async function yt(e,n,t,i){let o,r,s;try{o=await promises.lstat(e,{bigint:!0}),r=await promises.realpath(e),s=await promises.stat(r,{bigint:!0});}catch(a){throw fe(a)}if(!It(n,r)||t!==void 0&&!It(t,r))throw new M("PATH_ESCAPED");if(!o.isFile()||!s.isFile())throw new M("READ_DENIED");if(!Ni(i,o)||!Ni(i,s)||i.dev!==s.dev)throw new M("PATH_ESCAPED")}async function un(e,n){let t,i;try{t=await promises.realpath(e),i=await promises.stat(t,{bigint:!0});}catch{throw new M("PATH_ESCAPED")}if(t!==n.realRoot||!Di(n.identity,fn(i)))throw new M("PATH_ESCAPED")}function xp(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 M,Pi,Up,vr,gt,jr,Mi=F(()=>{m();M=class extends Error{constructor(t){super(t);this.code=t;}code;name="AppDiscoveryFsError"},Pi=ne.constants.O_NOFOLLOW,Up=ne.constants.O_NONBLOCK,vr=ne.constants.O_RDONLY|(Pi??0)|(Up??0);gt=class{async getRootIdentity(n){let t=await ft(n);return await un(n,t),{dev:t.identity.dev,ino:t.identity.ino,realPath:t.realRoot}}async listDirectory(n,t){let i=Ei(t),o=await ft(n),r=ce.resolve(n,...i),s,a;try{s=await promises.realpath(r),a=await promises.stat(s,{bigint:!0});}catch(c){let d=fe(c);if(d.code==="NOT_FOUND")return [];throw d}if(!It(o.realRoot,s)||!a.isDirectory())throw new M("PATH_ESCAPED");try{let c=await promises.readdir(s,{withFileTypes:!0,encoding:"utf8"});return await un(n,o),c.map(xp)}catch(c){let d=fe(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 M("READ_DENIED");if(Pi===void 0)throw new M("UNSUPPORTED");let o=Ei(t),r=await ft(n),s=ce.resolve(n,...o),a=ce.relative(n,s);if(a===".."||a.startsWith(`..${ce.sep}`)||ce.isAbsolute(a))throw new M("PATH_ESCAPED");let c;try{c=await promises.open(s,vr);}catch(d){throw fe(d)}try{let d;try{let g=await c.stat({bigint:!0});d=fn(g);}catch(g){throw fe(g)}if(d.size>BigInt(i))throw new M("LIMIT_EXCEEDED");if(d.size>BigInt(Number.MAX_SAFE_INTEGER))throw new M("LIMIT_EXCEEDED");await un(n,r);let l=await Fr(n,r.realRoot,o);await yt(s,r.realRoot,l,d);let p=new Uint8Array(new ArrayBuffer(Number(d.size))),u=0;for(;u<p.byteLength;){let g;try{g=(await c.read(p,u,p.byteLength-u,u)).bytesRead;}catch(_){throw fe(_)}if(g<=0)throw new M("IDENTITY_CHANGED");u+=g;}let y;try{let g=await c.stat({bigint:!0});y=fn(g);}catch(g){throw fe(g)}if(!Di(d,y))throw new M("IDENTITY_CHANGED");return await yt(s,r.realRoot,l,y),await un(n,r),new Uint8Array(p)}finally{await c.close().catch(()=>{});}}async fingerprintVerifiedFile(n,t,i){if(!Number.isSafeInteger(i)||i<0)throw new M("READ_DENIED");if(Pi===void 0)throw new M("UNSUPPORTED");let o=Ei(t),r=await ft(n),s=ce.resolve(n,...o),a=ce.relative(n,s);if(a===".."||a.startsWith(`..${ce.sep}`)||ce.isAbsolute(a))throw new M("PATH_ESCAPED");let c;try{c=await promises.open(s,vr);}catch(d){throw fe(d)}try{let d;try{let u=await c.stat({bigint:!0});d=fn(u);}catch(u){throw fe(u)}if(d.size>BigInt(i)||d.size>BigInt(Number.MAX_SAFE_INTEGER))throw new M("LIMIT_EXCEEDED");await un(n,r);let l=await Fr(n,r.realRoot,o);await yt(s,r.realRoot,l,d);let p;try{let u=await c.stat({bigint:!0});p=fn(u);}catch(u){throw fe(u)}if(!Di(d,p))throw new M("IDENTITY_CHANGED");return await yt(s,r.realRoot,l,p),await un(n,r),{...p,candidateRealPath:l??r.realRoot}}catch(d){throw d instanceof M?d:fe(d)}finally{await c.close().catch(()=>{});}}async readFileVerified(n,t,i){return this.readVerifiedFile(n,t,i)}},jr=new gt;});function kn(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 Br(e){return typeof e=="string"&&Pe.test(e)?e:void 0}function zp(e){return e.length>0&&e!=="."&&e!==".."&&!/[\\/\u0000]/.test(e)}function Ye(e,n){let t=new TextEncoder().encode(e),i=new TextEncoder().encode(n),o=Math.min(t.byteLength,i.byteLength);for(let r=0;r<o;r+=1){let s=t[r]-i[r];if(s!==0)return s}return t.byteLength-i.byteLength}function $p(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 o=n.isFile;return typeof o=="function"&&o.call(e)?{name:n.name,kind:"file"}:{name:n.name,kind:"other"}}function Gp(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 Jp(e){return Bp.decode(e)}function Wp(e){return JSON.parse(Jp(e))}function Hr(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 Kp(e){if(e instanceof M)return Hr(e.code);if(e!==null&&typeof e=="object"&&"code"in e){let n=e.code;if(typeof n=="string")return Hr(n)}}function Ue(e,n){let t=n();return Number.isFinite(t)&&Number.isFinite(e)&&t-e<=5e3}function Xp(e){if(typeof e.readVerifiedFile=="function")return e.readVerifiedFile;if(typeof e.readFileVerified=="function")return e.readFileVerified}function Yp(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 zr(e,n,t,i){let o=Xp(e);if(!o)throw new M("READ_DENIED");return Gp(await o.call(e,n,t,i))}async function Ri(e,n,t){let i=Yp(e);if(!i)throw new M("READ_DENIED");let o=await i.call(e,n,t);if(!Array.isArray(o))throw new M("READ_DENIED");return o.map($p).filter(r=>r!==null)}function qp(e,n,t,i){return Object.freeze({code:e,...{},source:n,relativePath:t})}function Zp(e){if(!kn(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,o)=>{if(!Array.isArray(i))throw new TypeError("productBundle.reservedIds."+o+" must be an array");let r=[];for(let s=0;s<i.length;s+=1){let a=i[s];if(typeof a!="string"||a.length===0)throw new TypeError("productBundle.reservedIds."+o+" must contain non-empty strings");r.push(a);}return Object.freeze([...new Set(r)].sort(Ye))};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 Qp(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 ht(e){return Object.freeze({appIds:Object.freeze([...new Set(e.map(n=>n.appId))].sort(Ye)),definitionIds:Object.freeze([...new Set(e.map(n=>n.definition.id))].sort(Ye))})}function mt(e,n){let t=Object.keys(e).sort(Ye),i=[...n].sort(Ye);return t.length===i.length&&t.every((o,r)=>o===i[r])}function $r(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 el(e){let n;try{n=Wp(e);}catch{return}if(!kn(n)||!mt(n,["version","packages"])||n.version!==1||!Array.isArray(n.packages)||n.packages.length>wi)return;let t=new Set,i=new Set,o=0,r=[];for(let s of n.packages){if(!kn(s))return;let a=["packageDir","appId","definition","files"],c=Object.hasOwn(s,"lineage"),d=Object.hasOwn(s,"launcher"),l=[...c?["lineage"]:[],...d?["launcher"]:[]];if(!mt(s,[...a,...l])||d&&s.launcher!==false)return;let p=$r(s.packageDir),u=Br(s.appId);if(!p||p.length!==2||p[0]!=="apps"||!zp(p[1])||!u||t.has(s.packageDir)||!kn(s.definition)||!mt(s.definition,["id","version","hash"]))return;let y=Br(s.definition.id),g=s.definition.version,_=s.definition.hash;if(!y||!Number.isSafeInteger(g)||g<1||typeof _!="string"||!Li.test(_)||!Array.isArray(s.files)||s.files.length<2||s.files.length>Ci)return;let E=new Set,U=[];for(let k of s.files){if(!kn(k)||!mt(k,["path","sha256"]))return;let P=$r(k.path);if(!P||typeof k.sha256!="string"||!Li.test(k.sha256))return;let w=P.join("/"),B=`${s.packageDir}/${w}`;if(E.has(w)||i.has(B))return;E.add(w),i.add(B),U.push(Object.freeze({path:w,sha256:k.sha256}));}if(!Q.some(k=>E.has(k))||!E.has("ui/index.html")||(o+=U.length,o>Fp))return;t.add(s.packageDir),r.push(Object.freeze({packageDir:s.packageDir,...d?{launcher:false}:{},appId:u,definition:Object.freeze({id:y,version:g,hash:_}),lineage:Array.isArray(s.lineage)?s.lineage:[],files:Object.freeze(U.sort((k,P)=>Ye(k.path,P.path)))}));}return Object.freeze({version:1,packages:Object.freeze(r)})}function Xe(e){let n=Kp(e);return n==="PATH_ESCAPED"||n==="IDENTITY_CHANGED"||n==="TOCTOU"?"PATH_ESCAPED":n==="LIMIT_EXCEEDED"?"LIMIT_EXCEEDED":"BUNDLE_INTEGRITY"}async function nl(e,n,t,i,o){let r=[],s=async(a,c)=>{if(!Ue(i,o))throw new M("LIMIT_EXCEEDED");if(c>2)throw new M("LIMIT_EXCEEDED");let d=await Ri(e,n,a);for(let l of d){if(typeof l.name!="string"||l.name.length===0||l.name==="."||l.name===".."||/[\\/\u0000]/.test(l.name))throw new M("PATH_ESCAPED");let p=`${a}/${l.name}`;if(l.kind==="file"){if(r.push(p.slice(t.length+1)),r.length>Ci)throw new M("LIMIT_EXCEEDED")}else if(l.kind==="directory")await s(p,c+1);else throw l.kind==="symlink"?new M("PATH_ESCAPED"):new M("READ_DENIED")}};return await s(t,0),r.sort(Ye)}function tl(e){return Q.includes(e)?262144:e==="ui/index.html"?ln:e==="ui/state.json"?2097152:e.startsWith("ui/assets/")?Vp:jp}async function Gr(e,n,t,i){if(e===void 0)return {packages:[],diagnostics:[],incomplete:false,reservedIds:Hp};let o=Zp(e.reservedIds),r=[],s=(I,A,h)=>qp(I,"bundled",A),a=(I=[],A=false,h)=>({...h===void 0?{}:{indexHash:h},packages:I,diagnostics:r,incomplete:A,reservedIds:o});if(typeof e.root!="string"||e.root.length===0||typeof e.expectedIndexHash!="string"||!Li.test(e.expectedIndexHash))return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a();let c;try{c=await zr(n,e.root,"bundle-index.json",vp);}catch(I){return r.push(s(Xe(I),"bundle-index.json")),a()}let d=Hi.createHash("sha256").update(c).digest("hex");if(d!==e.expectedIndexHash)return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a();let l=el(c);if(l===void 0)return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a();if(!Qp(ht(l.packages),o))return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a([],false,d);if(!Ue(t,i))return r.push(s("LIMIT_EXCEEDED","bundle-index.json")),a(l.packages.map(I=>({indexEntry:I,failureCode:"LIMIT_EXCEEDED"})),true,d);let p;try{p=await Ri(n,e.root,"");}catch(I){return r.push(s(Xe(I),"bundle-index.json")),a(l.packages.map(A=>({indexEntry:A,failureCode:Xe(I)})),false,d)}if(!Ue(t,i))return r.push(s("LIMIT_EXCEEDED","bundle-index.json")),a(l.packages.map(I=>({indexEntry:I,failureCode:"LIMIT_EXCEEDED"})),true,d);let u=p.find(I=>I.name==="bundle-index.json"&&I.kind==="file"),y=p.find(I=>I.name==="apps"&&I.kind==="directory"),g=I=>l.packages.map(A=>({indexEntry:A,failureCode:I}));if(!u)return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a(g("BUNDLE_INTEGRITY"),false,d);let _=p.filter(I=>I.name!=="bundle-index.json"&&I.name!=="apps");if(_.length>0){let I=_.some(A=>A.kind==="symlink")?"PATH_ESCAPED":"BUNDLE_INTEGRITY";return r.push(s(I,"bundle-index.json")),a(g("BUNDLE_INTEGRITY"),false,d)}if(p.some(I=>I.name==="apps"&&I.kind!=="directory"))return r.push(s("PATH_ESCAPED","apps")),a(g("PATH_ESCAPED"),false,d);let E=[];if(y)try{E=await Ri(n,e.root,"apps");}catch(I){return r.push(s(Xe(I),"apps")),a(g(Xe(I)),false,d)}if(!Ue(t,i)||E.length>wi)return r.push(s("LIMIT_EXCEEDED","apps")),a(g("LIMIT_EXCEEDED"),true,d);let U=new Map(l.packages.map(I=>[I.packageDir.slice(5),I])),k=E.filter(I=>!U.has(I.name));for(let I of k)r.push(s(I.kind==="symlink"?"PATH_ESCAPED":"BUNDLE_INTEGRITY",`apps/${I.name}`));if(k.length>0){let I=k.some(A=>A.kind==="symlink")?"PATH_ESCAPED":"BUNDLE_INTEGRITY";return a(g(I),false,d)}let P=new Set,w=new Map,B=new Map;for(let I of l.packages){let A=w.get(I.appId)??[];A.push(I),w.set(I.appId,A);let h=`${I.definition.id}\0${String(I.definition.version)}`,T=B.get(h)??[];T.push(I),B.set(h,T);}for(let I of [...w.values(),...B.values()])if(I.length>1)for(let A of I)P.add(A);let N=[],D=c.byteLength,O=false;for(let I of l.packages){if(!Ue(t,i)){O=true,N.push({indexEntry:I,failureCode:"LIMIT_EXCEEDED"});continue}let A;try{let V=I.lineage[I.lineage.length-1];if(!V)throw new Oe("LINEAGE_INVALID","Definition lineage is missing");if(V.definition.id!==I.definition.id||V.version!==I.definition.version||V.hash!==I.definition.hash)throw new Oe("LINEAGE_STALE","Last lineage generation does not match bundle identity");A=Ai(I.lineage,{...V.definition,hash:V.hash}).entries;}catch(V){let x=V instanceof Oe?V.code:"LINEAGE_INVALID";r.push(s(x,I.packageDir)),N.push({indexEntry:I,failureCode:x});continue}let h=E.find(V=>V.name===I.packageDir.slice(5));if(!y||!h){N.push({indexEntry:I,failureCode:"BUNDLE_INTEGRITY"});continue}if(h.kind!=="directory"){N.push({indexEntry:I,failureCode:h.kind==="symlink"?"PATH_ESCAPED":"BUNDLE_INTEGRITY"});continue}let T;try{let V=await nl(n,e.root,I.packageDir,t,i);if(!Ue(t,i)){O=!0,N.push({indexEntry:I,failureCode:"LIMIT_EXCEEDED"});continue}let x=I.files.map(v=>v.path);if(V.length!==x.length||V.some((v,pe)=>v!==x[pe])){N.push({indexEntry:I,failureCode:"BUNDLE_INTEGRITY"});continue}T=new Map;let X;for(let v of I.files){if(!Ue(t,i)){X="LIMIT_EXCEEDED",O=!0;break}if(D>=Oi){X="LIMIT_EXCEEDED";break}let pe;try{pe=await zr(n,e.root,`${I.packageDir}/${v.path}`,tl(v.path));}catch(be){X=Xe(be);break}if(!Ue(t,i)){X="LIMIT_EXCEEDED",O=!0;break}if(D+pe.byteLength>Oi){D=Oi,X="LIMIT_EXCEEDED";break}if(D+=pe.byteLength,Hi.createHash("sha256").update(pe).digest("hex")!==v.sha256){X="BUNDLE_INTEGRITY";break}T.set(v.path,pe);}if(X!==void 0){N.push({indexEntry:I,failureCode:X});continue}}catch(V){Ue(t,i)||(O=true),N.push({indexEntry:I,failureCode:Xe(V)});continue}N.push({indexEntry:I,lineage:A,files:T,...P.has(I)?{failureCode:"DUPLICATE_ID"}:{}});}return a(N,O,d)}var vp,wi,Ci,Fp,jp,Vp,Oi,Li,Bp,Hp,Ui=F(()=>{m();Ii();Ge();tt();ut();Mi();vp=256*1024,wi=64,Ci=128,Fp=wi*Ci,jp=2*1024*1024,Vp=8*1024*1024,Oi=32*1024*1024,Li=/^[0-9a-f]{64}$/,Bp=new TextDecoder("utf-8",{fatal:true}),Hp=Object.freeze({appIds:Object.freeze([]),definitionIds:Object.freeze([])});});function ol(e){if(typeof e!="string"||!Pe.test(e))throw new TypeError("pluginId must be a safe UI plugin identifier");let n=`${ki}${e}`.length+7<=128?e:`hash_${Hi.createHash("sha256").update(e,"utf8").digest("hex")}`;return {read:`${ki}${n}_read`,action:`${ki}${n}_action`}}function Wr(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 sl(e,n){return n.length===0||n==="."||n===".."||/[\\/\u0000]/.test(n)?e==="skills"?"skills":"apps":`${e==="skills"?"skills":"apps"}/${n}`}function al(e){return e.length>0&&e!=="."&&e!==".."&&!/[\\/\u0000]/.test(e)}function vn(e,n){let t=new TextEncoder().encode(e),i=new TextEncoder().encode(n),o=Math.min(t.byteLength,i.byteLength);for(let r=0;r<o;r+=1){let s=t[r]-i[r];if(s!==0)return s}return t.byteLength-i.byteLength}function os(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 o=n.isFile;return typeof o=="function"&&o.call(e)?{name:n.name,kind:"file"}:{name:n.name,kind:"other"}}function cl(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 rs(e){return rl.decode(e)}function dl(e){return JSON.parse(rs(e))}function pl(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 _t(e,n,t,i,o){let r={code:e,...i===void 0?{}:{pluginId:i},source:n,relativePath:t,...o?.reason===void 0?{}:{reason:Object.freeze({...o.reason})},...o?.files===void 0?{}:{files:Object.freeze([...o.files])}};return Object.freeze(r)}function Kr(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 re(e){if(e instanceof M)return Kr(e.code);if(e!==null&&typeof e=="object"&&"code"in e){let n=e.code;if(typeof n=="string")return Kr(n)}}function Ze(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 Xr(e){return {reason:e.reason,...e.code==="MANIFEST_DUAL_MISMATCH"?{files:e.files}:{}}}function Yr(e){return e==="MANIFEST_DUAL_MISMATCH"?e:ss(e)}function ll(e){return ss(e.code)}function ss(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 as("UiPluginValidationError",e)}}function as(e,n){throw new Error(`Unmapped ${e} code: ${String(n)}`)}function cs(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 as("McpAppContractError",e)}}function ke(e,n){let t=n();return Number.isFinite(t)&&Number.isFinite(e)&&t-e<=5e3}function ul(e){return {pluginId:e.appId,definitionKey:`${e.definition.id}\0${String(e.definition.version)}`}}function fl(e,n){let t=n.get("package.json");if(t!==void 0)try{let o=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(t));if(Wr(o)){let r=o.bin,s=typeof r=="string"?r:Wr(r)?Object.values(r).find(a=>typeof a=="string"):void 0;for(let a of [s,o.main]){if(typeof a!="string")continue;let c=yl(a);if(c&&n.has(c))return c}}}catch{}return [`${e.slice(e.lastIndexOf("/")+1)}.js`,"index.js","main.js"].find(o=>n.has(o))}function yl(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 Al(){return globalThis.performance?.now()??Date.now()}function qe(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let n of Object.values(e))qe(n);return Object.freeze(e)}function qr(e){return Object.freeze(Array.from(e))}async function Fn(e,n,t,i){if(n.pinnedFiles!==void 0){let a=n.pinnedFiles.get(t);if(a===void 0)throw new M("NOT_FOUND");if(a.byteLength>i)throw new M("LIMIT_EXCEEDED");return new Uint8Array(a)}let o=`${n.relativePath}/${t}`,r=n.scanContext,s=e.fingerprintVerifiedFile;if(r===void 0||!r.cacheable||typeof s!="function")return ns(e,n.root,o,i);try{let a=r.priorFingerprints.get(o)??await s.call(e,r.workspaceRoot,o,i);r.candidateRealPath=a.candidateRealPath;let c=await ns(e,n.root,o,i),d=await s.call(e,r.workspaceRoot,o,i);return r.candidateRealPath=d.candidateRealPath,ps(a,d)&&d.size===BigInt(c.byteLength)&&!ls(d,r.scanStartedAtNs)?r.files.set(o,{relativePath:o,byteLimit:i,fingerprint:d}):r.cacheable=!1,c}catch(a){let c=!t.includes("/")&&re(a)==="NOT_FOUND"&&r.directoryListings.some(l=>l.relativePath===n.relativePath&&!Et(l.key,t)),d=t===$&&re(a)==="NOT_FOUND"&&gl(r.directoryListings,n.relativePath);throw !c&&!d&&(r.cacheable=false),a}}async function Il(e,n,t){if(n.pinnedFiles!==void 0)return {iconDiagnostics:[]};let i=await Tn(t,async r=>{try{return await Fn(e,n,r,262144)}catch(s){let a=re(s);return a==="NOT_FOUND"?"missing":a==="LIMIT_EXCEEDED"?"too-large":"bad-path"}}),o=i.file;return {...o===void 0?{}:{iconFile:{path:o.path,sha256:Hi.createHash("sha256").update(o.bytes).digest("hex"),contentType:o.contentType,byteLength:o.byteLength}},iconDiagnostics:i.diagnostics}}function gl(e,n){let t=e.find(o=>o.relativePath===n);if(t===void 0)return false;if(!Et(t.key,"dist"))return true;let i=e.find(o=>o.relativePath===`${n}/dist`);return i!==void 0&&!Et(i.key,"tools.json")}function ds(e,n){return JSON.stringify([e.realPath,n.source,n.relativePath])}async function hl(e,n,t,i,o,r,s,a){let c=e.fingerprintVerifiedFile,d=ds(t,i),l=o.candidates.get(d),p=i.relativePath,u;try{u=await es(e,n,p);}catch(O){if(re(O)!=="NOT_FOUND")throw O}let y=u===void 0?void 0:{relativePath:p,key:u};if(y!==void 0&&(i.source==="apps"||i.source==="skills")&&!Q.some(O=>Et(y.key,O)))return ke(s,a)?l!==void 0&&l.candidate===void 0&&l.candidateRealPath===void 0&&l.files.length===0&&l.directoryListings.length===1&&l.directoryListings[0]?.relativePath===y.relativePath&&l.directoryListings[0]?.key===y.key&&(i.source==="apps"?l.diagnostic?.code==="MANIFEST_MISSING":l.diagnostic===void 0)&&typeof c=="function"?{memo:l}:typeof c!="function"?{}:{context:{state:o,cacheKey:d,workspaceRoot:n,scanStartedAtNs:r,directoryListings:Object.freeze([y]),priorFingerprints:new Map,files:new Map,cacheable:true}}:{timeLimitReached:true};let g=async O=>{if(O==="")return y;let I=`${i.relativePath}${O}`;try{let A=await es(e,n,I);return A===void 0?void 0:{relativePath:I,key:A}}catch(A){if(re(A)==="NOT_FOUND")return;throw A}},_=await Promise.all(Zr.map(g)),E=await Promise.all(ml.map(g));if(!ke(s,a))return {timeLimitReached:true};let U=typeof c=="function"&&_.every(O=>O!==void 0),k=_.filter(O=>O!==void 0),P=[...k,...E.filter(O=>O!==void 0)],w=new Map,B=l!==void 0&&U,N;if(l!==void 0&&typeof c=="function"){let O=await Promise.all(l.files.map(async I=>{if(!ke(s,a))return {kind:"time",file:I};try{let A=await c.call(e,n,I.relativePath,I.byteLimit);return {kind:"fingerprint",file:I,current:A}}catch(A){return re(A)==="NOT_FOUND"?{kind:"missing",file:I}:{kind:"error",file:I,error:A}}}));if(O.some(I=>I.kind==="time"))return {timeLimitReached:true};for(let I of O){if(I.kind==="error")throw I.error;if(I.kind==="missing"){B=false;continue}if(I.kind!=="fingerprint")continue;let{file:A,current:h}=I;w.set(A.relativePath,h),N??=h.candidateRealPath,(h.candidateRealPath!==l.candidateRealPath||!ps(h,A.fingerprint)||ls(h,r))&&(B=false);}}let D=l!==void 0&&l.directoryListings.length===P.length&&l.directoryListings.every((O,I)=>O.relativePath===P[I]?.relativePath&&O.key===P[I]?.key);return l!==void 0&&U&&D&&B&&N===l.candidateRealPath?{memo:l}:!U||k.length!==Zr.length?{}:{context:{state:o,cacheKey:d,workspaceRoot:n,scanStartedAtNs:r,directoryListings:Object.freeze(P),priorFingerprints:w,files:new Map,...N===void 0?{}:{candidateRealPath:N},cacheable:true}}}function Et(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 es(e,n,t){let i=us(e);if(typeof i!="function")return;let o=await i.call(e,n,t);if(!Array.isArray(o)||o.some(s=>typeof s=="string"))return;let r=o.map(os);if(!r.some(s=>s===null))return JSON.stringify(r.slice().sort((s,a)=>vn(s.name,a.name)||vn(s.kind,a.kind)).map(s=>[s.name,s.kind]))}function ps(e,n){return e.dev===n.dev&&e.ino===n.ino&&e.size===n.size&&e.mtimeNs===n.mtimeNs&&e.ctimeNs===n.ctimeNs}function ls(e,n){let t=e.mtimeNs-n;return t>=-Qr&&t<=Qr}function xi(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,o=t||i;if(n===void 0||!n.cacheable||n.candidateRealPath===void 0&&!o||n.files.size===0&&!o)return;let r=Object.freeze({...!o&&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,r);}function _l(e,n,t){let i=Hi.createHash("sha256"),o=new TextEncoder().encode(te(e)),r=s=>{let a=new Uint8Array(8);new DataView(a.buffer).setBigUint64(0,BigInt(s)),i.update(a);};return r(o.byteLength),i.update(o),r(n.byteLength),i.update(n),r(t.byteLength),i.update(t),i.digest("hex")}function El(e,n){let t={...e.definition,sourceHash:n},i;try{i=le(t);}catch(r){throw r instanceof C&&r.code==="INPUT_INVALID"?new ae("MANIFEST_INVALID","normalized definition is invalid"):r}let o={...t,hash:i};try{Ie(o);}catch{throw new ae("MANIFEST_INVALID","normalized definition is invalid")}return o}function Tl(e,n){return e.actions.some(t=>t.backend.type==="core"&&t.backend.handler!=="state.set"&&!st(n,t.backend))}function bl(e){if(typeof e.readVerifiedFile=="function")return e.readVerifiedFile;if(typeof e.readFileVerified=="function")return e.readFileVerified}function us(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 ns(e,n,t,i){let o=bl(e);if(!o)throw new M("READ_DENIED");return cl(await o.call(e,n,t,i))}async function Pl(e,n,t){let i=us(e);if(!i)throw new M("READ_DENIED");let o=await i.call(e,n,t);if(!Array.isArray(o))throw new M("READ_DENIED");return o.map(os).filter(r=>r!==null)}function Nl(e){let n=[];for(let t of [e.reserved,e.builtin])t&&n.push(t);return e.builtins&&"listMcpApps"in e.builtins?n.push(ts(e.builtins)):e.builtins&&n.push(e.builtins),e.builtinCatalog&&n.push(ts(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 ts(e){let n=[],t=[],i=[];for(let o of e.listMcpApps())typeof o.appId=="string"&&n.push(o.appId),o.definition&&typeof o.definition.id=="string"&&t.push(o.definition.id);for(let o of e.listMcpAppTools())typeof o.name=="string"&&i.push(o.name);return {appIds:n,definitionIds:t,toolNames:i}}function Ee(e,n){e.diagnostic||(e.diagnostic=_t(n,e.source,e.relativePath,e.identity?.pluginId));}function Dl(e,n){let t=new Set,i=new Map;for(let r of e){let s=r.identity?.pluginId;if(s===void 0)continue;let a=i.get(s)??[];a.push(r),i.set(s,a);}for(let r of i.values()){if(r.length<2)continue;let s=r.filter(c=>c.provenance!==void 0);if(s.length>0){let c=r.find(d=>n.has(d));if(c){for(let d of s)t.add(d);for(let d of r)d!==c&&d.provenance===void 0&&Ee(d,"RESERVED_ID");continue}for(let d of r)d.provenance===void 0&&Ee(d,"RESERVED_ID");if(s.length>1)for(let d of s)Ee(d,"DUPLICATE_ID");continue}let a=r.filter(c=>c.source==="apps");if(a.length>1){for(let c of a)Ee(c,"DUPLICATE_ID");for(let c of r.filter(d=>d.source==="skills"))Ee(c,"DUPLICATE_ID");}else for(let c of r.filter(d=>d.source==="skills"))Ee(c,"DUPLICATE_ID");}let o=new Map;for(let r of e){if(r.diagnostic?.code==="RESERVED_ID"||t.has(r)||r.provenance===void 0&&!n.has(r)&&i.get(r.identity?.pluginId??"")?.some(c=>c.provenance!==void 0))continue;let s=r.identity?.definitionKey;if(s===void 0)continue;let a=o.get(s)??[];a.push(r),o.set(s,a);}for(let r of o.values())if(r.length>1)for(let s of r)Ee(s,"DUPLICATE_ID");return t}function Sl(e,n,t){let i=new Set,o=new Set,r=new Set,s=new Set([...t.appIds,...n.productBundleReservationMetadata?.reservedAppIds??[]]),a=new Set([...t.definitionIds,...n.productBundleReservationMetadata?.reservedDefinitionIds??[]]);for(let l of Nl(n)){for(let p of l.appIds??[])typeof p=="string"&&i.add(p);for(let p of l.definitionIds??[])typeof p=="string"&&o.add(p);for(let p of l.toolNames??[])typeof p=="string"&&r.add(p);}for(let l of e){let p=l.candidate;if(!p)continue;if(i.has(p.pluginId)||o.has(p.definitionId)){Ee(l,"RESERVED_ID");continue}[p.toolNames.read,p.toolNames.action].filter(y=>y!==void 0).some(y=>r.has(y))&&Ee(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 p=l.candidate;if(!(!p||l.diagnostic||l.source!=="apps"||l.provenance!==void 0)&&e.filter(u=>u.source==="apps"&&u.identity?.pluginId===p.pluginId).length===1&&c.some(u=>u.pluginId===p.pluginId)&&!(a.has(p.definitionId)&&!c.some(u=>u.pluginId===p.pluginId&&u.definitionId===p.definitionId))&&!c.some(u=>u.pluginId!==p.pluginId&&u.definitionId===p.definitionId)&&!e.some(u=>u.identity?.pluginId!==p.pluginId&&u.identity?.definitionKey===`${p.definitionId}\0${p.version}`&&u.diagnostic?.code!=="RESERVED_ID"))try{Rr(p),d.add(l);}catch(u){Ee(l,u instanceof Me?cs(u.code):"EXEC_DENIED");}}for(let l of e){let p=l.candidate;p&&l.provenance===void 0&&!d.has(l)&&(s.has(p.pluginId)||a.has(p.definitionId))&&Ee(l,"RESERVED_ID");}return d}function Ml(e){return [...e].sort((n,t)=>{let i=Jr.indexOf(n.source)-Jr.indexOf(t.source);return i!==0?i:vn(n.relativePath,t.relativePath)})}function H(e,n,t){e.diagnostic=_t(n,e.source,e.relativePath,e.identity?.pluginId,t);}async function is(e,n,t){let i=He(t,{mode:"local"});if(!i.ok&&i.parseFailure){H(n,Yr(i.rejection.code),Xr(i.rejection));return}let o=pl(i.identity);if(n.bundleIdentity===void 0)n.identity=o;else if(o?.pluginId!==n.bundleIdentity.appId||o.definitionKey!==`${n.bundleIdentity.definitionId}\0${String(n.bundleIdentity.version)}`){H(n,"BUNDLE_INTEGRITY");return}if(!i.ok&&i.builtinOnly){H(n,"RESERVED_ID");return}if(!i.ok){H(n,Yr(i.rejection.code),Xr(i.rejection));return}let r=i.manifest,s={pluginId:r.pluginId,definitionKey:`${r.definitionId}\0${String(r.version)}`};if(n.bundleIdentity===void 0&&(n.identity=s),r.actions.length>0)try{_i(r.actions.map(x=>({actionId:x.actionId,inputSchema:x.inputSchema})));}catch(x){if(x instanceof Me){H(n,cs(x.code));return}throw x}let a;try{a=await Fn(e,n,"ui/index.html",ln);}catch(x){H(n,Ze(re(x),"entry"));return}if(a.byteLength>ln){H(n,"LIMIT_EXCEEDED");return}let c;try{c=rs(a);}catch{H(n,"ENTRY_INVALID");return}if(a.byteLength===0||c.length===0){H(n,"ENTRY_INVALID");return}let d=Hi.createHash("sha256").update(a).digest("hex");if(r.entryHash!==void 0&&r.entryHash!==d){H(n,"ENTRY_INVALID");return}let l={},p,u;if(r.initialState!==void 0){try{p=await Fn(e,n,"ui/state.json",2097152);}catch(x){H(n,Ze(re(x),"initial"));return}if(p.byteLength>2097152){H(n,"LIMIT_EXCEEDED");return}try{let x=dl(p),X=r.dataPaths??[],v=ti(x,X);l=Ae(v,0,X),tn(l);}catch{H(n,"INITIAL_STATE_INVALID");return}if(u=Hi.createHash("sha256").update(p).digest("hex"),r.initialState.hash!==void 0&&r.initialState.hash!==u){H(n,"INITIAL_STATE_INVALID");return}}let y={...r,entryHash:d,...r.initialState===void 0?{}:{initialState:{path:"ui/state.json",hash:u}}},g=_n(y),_=_l(y,a,p??new Uint8Array),E;try{E=El(g,_);}catch(x){if(x instanceof ae){H(n,ll(x));return}throw x}let U;if(n.bundleLineage!==void 0){let x=n.bundleLineage[n.bundleLineage.length-1];if(!x){H(n,"LINEAGE_INVALID");return}let{legacy:X,...v}=x.definition,{hash:pe,...be}=E;if(te(v)!==te(be)){H(n,"LINEAGE_STALE");return}if(X!==void 0&&(E={...E,legacy:X}),X!==void 0)try{E={...E,hash:le(E)},Ie(E);}catch{H(n,"LINEAGE_INVALID");return}U=n.bundleLineage;}if(n.bundleIdentity!==void 0&&n.bundleIdentity.appId!==r.pluginId){H(n,"BUNDLE_INTEGRITY");return}if(n.bundleIdentity!==void 0&&(n.bundleIdentity.definitionId!==E.id||n.bundleIdentity.version!==E.version||n.bundleIdentity.definitionHash!==E.hash)){H(n,"LINEAGE_STALE");return}let k=await Il(e,n,i.mcpb?.icon),P=ol(r.pluginId),w=r.actions.length===0?{read:P.read}:P,B=qe(g),N=qe(y),D=qe(E),O=qe({...g.handlers}),I=qr(a),A=p===void 0?void 0:qr(p),h=Object.freeze({...n.provenance===void 0?{}:{provenance:n.provenance},entry:Object.freeze({path:"ui/index.html",hash:d,bytes:I}),...A===void 0?{}:{initialState:Object.freeze({path:"ui/state.json",hash:u,bytes:A})}}),T={appId:r.pluginId,pluginId:r.pluginId,definitionId:r.definitionId,version:r.version,...i.releaseVersion===void 0?{}:{releaseVersion:i.releaseVersion},manifestFile:i.file,...i.mcpb===void 0?{}:{mcpb:qe(i.mcpb)},relativePath:n.relativePath,manifest:N,normalized:B,name:r.name,description:r.description,...r.icon===void 0?{}:{icon:r.icon},...r.tone===void 0?{}:{tone:r.tone},...k.iconFile===void 0?{}:{iconFile:Object.freeze({...k.iconFile})},...k.iconDiagnostics.length===0?{}:{iconDiagnostics:Object.freeze([...k.iconDiagnostics])},definition:D,handlers:O,resources:h,html:c,entryBytes:I,entryHash:d,initialState:qe(l),...A===void 0?{}:{initialStateBytes:A},...u===void 0?{}:{initialStateHash:u},sourceHash:_,toolNames:Object.freeze(w)},V=n.provenance===void 0?{...T,source:n.source}:{...T,provenance:n.provenance,lineage:U??[]};n.candidate=Object.freeze(V),Tl(r,E.usage)&&H(n,"EXEC_DENIED");}async function fs(e,n){let t={};for(let i of Q)try{t[i]=await Fn(e,n,i,262144);}catch(o){if(re(o)==="NOT_FOUND")continue;return {files:t,failure:Ze(re(o),"manifest")}}if(t[W]!==void 0)try{t[$]=await Fn(e,n,$,262144);}catch(i){if(re(i)!=="NOT_FOUND")return {files:t,failure:Ze(re(i),"manifest")}}return {files:t}}function vi(e){return Q.some(n=>e[n]!==void 0)}async function Ol(e,n){let{files:t,failure:i}=await fs(e,n);if(i!==void 0){H(n,i);return}let o=t[W];return o!==void 0&&!di(o)&&(delete t[W],delete t[$]),vi(t)?t:void 0}function Ll(e,n,t,i=il,o=false,r=new Set){let s=Ml(e),a=Dl(s,r),c=Object.freeze(s.filter(u=>u.candidate!==void 0&&u.diagnostic===void 0&&!a.has(u)).map(u=>u.candidate)),d=Object.freeze(s.filter(u=>u.diagnostic!==void 0).map(u=>u.diagnostic)),l=o?Object.freeze({...t===void 0?{}:{indexHash:t},candidates:Object.freeze(s.filter(u=>u.source==="bundled"&&u.diagnostic===void 0&&t!==void 0&&u.candidate?.provenance?.indexHash===t).map(u=>u.candidate)),diagnostics:Object.freeze(d.filter(u=>u.source==="bundled").map(u=>Object.freeze({...u}))),reservedAppIds:Object.freeze([...i.appIds]),reservedDefinitionIds:Object.freeze([...i.definitionIds])}):void 0,p={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(p,"candidates",{configurable:false,enumerable:false,get:()=>c}),Object.freeze(p)}function Rl(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 wl(e,n){if(Rl(e))return {fs:e,options:{}};let t=e??n??{};return {fs:t.filesystem??t.fileSystem??t.fs??jr,options:t}}async function ys(e,n,t){if(typeof e!="string"||e.length===0)throw new TypeError("workspaceRoot must be explicit");let{fs:i,options:o}=wl(n,t),r=o.clock??Al,s=r(),a=await Gr(o.productBundle,i,s,r),c=r(),d=BigInt(Date.now())*1000000n,l=[],p=0,u,y=false,g,_;if(o.scanCache!==void 0&&typeof i.getRootIdentity=="function"&&typeof i.fingerprintVerifiedFile=="function")try{_=await i.getRootIdentity(e),g=Ur(o.scanCache,_),g.scanStartedAtNs=d;}catch(N){if(re(N)!=="NOT_FOUND")throw N}let E=g!==void 0&&o.productBundle===void 0&&a.packages.length===0&&a.diagnostics.length===0,U=new Set,k=true;l.push(...a.diagnostics.map(N=>({source:N.source,root:o.productBundle?.root??e,name:"",relativePath:N.relativePath,diagnostic:N})));let P=a.reservedIds;a.incomplete&&(u="time_limit");for(let N of a.packages){if(!ke(c,r)){y=true,u="time_limit";break}let D=N.indexEntry,O=D.packageDir,I=N.files===void 0?void 0:fl(O,N.files),A=a.indexHash===void 0?void 0:sr(Object.freeze({kind:"bundled",launcher:D.launcher!==false,indexHash:a.indexHash,packageDir:O,appId:D.appId,definitionId:D.definition.id,version:D.definition.version,definitionHash:D.definition.hash,files:D.files}),I),h={source:"bundled",root:o.productBundle?.root??e,name:O.slice(5),relativePath:O,...A===void 0?{}:{provenance:A},...N.files===void 0?{}:{pinnedFiles:N.files},...N.lineage===void 0?{}:{bundleLineage:N.lineage},bundleIdentity:{appId:D.appId,definitionId:D.definition.id,version:D.definition.version,definitionHash:D.definition.hash},identity:ul(D)};if(l.push(h),p+=1,N.failureCode!==void 0){H(h,N.failureCode);continue}if(N.files?.has($)===true){H(h,"EXEC_DENIED",{reason:{path:"",rule:"bundled-tool-mode-unsupported",file:$}});continue}let T={};for(let V of Q){let x=N.files?.get(V);x!==void 0&&(T[V]=x);}if(!vi(T)){H(h,"BUNDLE_INTEGRITY");continue}if(await is(i,h,T),!ke(c,r)){y=true,u="time_limit";break}}let w=[{source:"apps",directory:"apps"},{source:"skills",directory:"skills"}];e:for(let N of w){let{source:D,directory:O}=N,I;try{I=await Pl(i,e,O);}catch(h){if(re(h)==="NOT_FOUND")continue;E=false,k=false,l.push({source:D,root:e,name:"",relativePath:D,diagnostic:_t(Ze(re(h),"manifest"),D,D)});continue}let A=I.filter(h=>h.kind==="directory"||h.kind==="symlink").filter(h=>al(h.name)).map(h=>({source:D,root:e,name:h.name,relativePath:sl(D,h.name)})).sort((h,T)=>vn(h.relativePath,T.relativePath));for(let h of A){let T={...h};if(l.push(T),_!==void 0?U.add(ds(_,T)):E=false,!ke(c,r)){y=true,u="time_limit";break e}let V;if(g!==void 0&&_!==void 0){try{let v=await hl(i,e,_,T,g,d,c,r);if(v.timeLimitReached){y=!0,u="time_limit";break e}T.scanContext=v.context,V=v.memo;}catch(v){E=false,H(T,Ze(re(v),"manifest"));continue}V===void 0&&(E=false);}if(V!==void 0){if(T.candidate=V.candidate,T.diagnostic=V.diagnostic,T.identity=V.identity,D==="skills"&&V.candidate===void 0&&V.diagnostic===void 0)continue;if(p>=64){H(T,"LIMIT_EXCEEDED");continue}if(h.relativePath.split("/").length-1>2){H(T,"LIMIT_EXCEEDED");continue}if(p+=1,!ke(c,r)){y=true,u="time_limit";break e}continue}let x;if(D==="skills"&&(x=await Ol(i,T),x===void 0)){T.diagnostic===void 0&&xi(T);continue}if(p>=64){H(T,"LIMIT_EXCEEDED");continue}if(h.relativePath.split("/").length-1>2){H(T,"LIMIT_EXCEEDED");continue}if(!ke(c,r)){y=true,u="time_limit";break e}if(p+=1,x===void 0){let v=await fs(i,T);if(v.failure!==void 0||!vi(v.files)){H(T,v.failure??Ze("NOT_FOUND","manifest")),xi(T);continue}x=v.files;}if(await is(i,T,x),xi(T),!ke(c,r)){y=true,u="time_limit";break e}}}if(g!==void 0&&_!==void 0){let N=[...U].sort(vn),D=g.lastCandidateKeys,O=D!==void 0&&D.length===N.length&&D.every((A,h)=>A===N[h]);if(E=E&&O,k&&!y&&u===void 0)for(let A of g.candidates.keys())try{JSON.parse(A)[0]===_.realPath&&!U.has(A)&&g.candidates.delete(A);}catch{g.candidates.delete(A);}let I=[...g.candidates.keys()].filter(A=>{try{return JSON.parse(A)[0]===_.realPath}catch{return false}});E=E&&I.length===U.size&&I.every(A=>U.has(A))&&!y&&u===void 0,g.lastCandidateScanUnchanged=E,k&&!y&&u===void 0&&(g.lastCandidateKeys=Object.freeze(N));}y&&l.push({source:"apps",root:e,name:"",relativePath:"apps",diagnostic:_t("DISCOVERY_TIME_LIMIT","apps","apps")});let B=Sl(l,o,P);return Ll(l,u,a.indexHash,P,o.productBundle!==void 0,B)}var il,ki,Jr,rl,Zr,ml,Qr,As=F(()=>{m();Je();Vn();Re();ui();li();Ge();ut();wr();at();ot();kr();Mi();rt();Ui();Ui();il=ht([]),ki="crewx_local_app_";Jr=["bundled","apps","skills"],rl=new TextDecoder("utf-8",{fatal:true});Zr=["","/ui"],ml=["/dist"],Qr=2000000000n;});m();ui();m();Jt();m();var Wo="SKILL.md",Hd=/^---\s*\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;function Ko(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function zd(e){return e.isDirectory()||e.isSymbolicLink()}function Qo(e){try{return ne.existsSync(e)&&ne.statSync(e).isDirectory()}catch{return false}}function fi(e){let n;try{n=ne.readFileSync(e,"utf8");}catch{return {frontmatter:{},readable:false,valid:false,hasFrontmatter:false}}let t=n.match(Hd);if(!t)return {frontmatter:{},readable:true,valid:true,hasFrontmatter:false};try{let i=Os.load(t[1]??"");if(!Ko(i))return {frontmatter:{},readable:!0,valid:!1,hasFrontmatter:!0};let o=Ko(i.metadata)?i.metadata:void 0;return {frontmatter:{...typeof i.name=="string"?{name:i.name}:{},...typeof(o?.version??i.version)=="string"?{version:o?.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 $d(e){return [ce.join(e,Wo),ce.join(e,"skill",Wo)]}function Xo(e,n){if(!Qo(e))return null;for(let t of $d(e)){if(!ne.existsSync(t))continue;let o=fi(t).frontmatter;return {name:o.name??n,...o.version===void 0?{}:{version:o.version},...o.description===void 0?{}:{description:o.description},skillMdPath:t,dir:e}}return null}function Yo(e){try{return ne.readdirSync(e,{withFileTypes:!0}).filter(zd)}catch{return []}}function qo(e,n,t){!e||n.has(e.name)||(n.add(e.name),t.push(e));}function er(e){let n=[],t=new Set;for(let i of e)if(Qo(i))for(let o of Yo(i)){if(o.name.startsWith("@")){let r=ce.join(i,o.name);for(let s of Yo(r))qo(Xo(ce.join(r,s.name),s.name),t,n);continue}qo(Xo(ce.join(i,o.name),o.name),t,n);}return n.sort((i,o)=>i.name.localeCompare(o.name))}m();tt();var Gd=/^[A-Za-z0-9_$.[\]"-]{0,200}$/,Jd=/^[a-z][a-z0-9-]{0,63}$/,Wd="<unknown>";function Kd(e){return typeof e=="string"&&(Q.includes(e)||e===$)}function nr(e){if(typeof e!="object"||e===null)return;let{file:n,path:t,rule:i}=e;if(!(typeof i!="string"||!Jd.test(i)))return {...Kd(n)?{file:n}:{},path:typeof t=="string"&&Gd.test(t)?t:Wd,rule:i}}function tr(e){if(!Array.isArray(e))return;let n=Q.filter(t=>e.includes(t));return n.length>0?n:void 0}As();var Ul=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/;function Pt(e){let n="screenHash"in e?e.screenHash:void 0,i=("skillHash"in e?e.skillHash:void 0)??(e.relativePath!==void 0&&e.fileBytes!==void 0?kl(e.relativePath,e.fileBytes):void 0);if(n!==void 0&&i!==void 0){let o=JSON.stringify({screenHash:n,skillHash:i});return Hi.createHash("sha256").update(o,"utf8").digest("hex")}if(n!==void 0)return n;if(i!==void 0)return i;throw new TypeError("App definition hash input must contain a screenHash or skill bytes")}function kl(e,n){let t=new TextEncoder().encode(Nt(e)),i=xl(n),o=new Uint8Array(t.byteLength+1+i.byteLength);return o.set(t,0),o[t.byteLength]=0,o.set(i,t.byteLength+1),Hi.createHash("sha256").update(o).digest("hex")}function xl(e){if(typeof e=="string")return new TextEncoder().encode(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("fileBytes must be UTF-8 text or bytes")}function Nt(e){if(typeof e!="string"||e.length===0||ce.isAbsolute(e)||/[\\\u0000]/.test(e))throw new TypeError("relative path must be package-relative");let n=e.split("/").filter(t=>t.length>0&&t!==".").join("/");if(!n||n.split("/").some(t=>t===".."))throw new TypeError("relative path must stay inside the package");return n}function Tt(e,n){let t=new TextEncoder().encode(e),i=new TextEncoder().encode(n),o=Math.min(t.byteLength,i.byteLength);for(let r=0;r<o;r+=1){let s=t[r]-i[r];if(s!==0)return s}return t.byteLength-i.byteLength}function ms(e,n){let t=ce.relative(e,n).split(ce.sep).join("/");return !t||t===".."||t.startsWith("../")||ce.isAbsolute(t)?null:Nt(t)}function vl(e){return e==="apps"||e.startsWith("apps/")?"apps":e==="skills"||e.startsWith("skills/")?"skills":e==="node_modules"||e.startsWith("node_modules/")?"node_modules":null}function hs(e){return Object.freeze({packageRoot:e})}function Fl(e){return Object.freeze({id:e.definition.id,version:e.definition.version,hash:e.definition.hash,usage:e.definition.usage??je,...e.definition.detailPanel===void 0?{}:{detailPanel:e.definition.detailPanel},...e.definition.displayModes===void 0?{}:{displayModes:e.definition.displayModes},...e.definition.summaryProjection===void 0?{}:{summaryProjection:e.definition.summaryProjection}})}function _s(e){return {capabilities:Object.freeze([...e]),origin:"local",ownership:"unknown",shareability:"unknown",sharingAvailability:"unavailable"}}function jl(e,n){let t=e.candidate,i=t.provenance!==void 0,o=n&&!i?["screen","skill"]:["screen"],r=Fl(t),s=Pt(n?{screenHash:r.hash,skillHash:n.skillHash}:{screenHash:r.hash}),a=t.description||n?.skill.description||"",c=t.releaseVersion??String(t.version),d={appId:t.pluginId,name:t.name,description:a,version:c,..._s(o),definition:r,...n===void 0||i?{}:{skillName:n.skill.name},...i?{provenance:t.provenance}:{localDefinitionRef:hs(e.packageRoot)},definitionHash:s,...t.manifest.csp===void 0?{}:{connectDomains:Object.freeze([...t.manifest.csp.connectDomains])}};return {...i?{}:{packageRoot:e.packageRoot},source:i?"bundled":t.source,appId:d.appId,capabilities:o,summary:Object.freeze(d)}}function Vl(e){let n=Bl(e.skill.name),t={appId:n,name:e.skill.name,description:e.skill.description??"",...e.skill.version===void 0?{}:{version:e.skill.version},..._s(["skill"]),skillName:e.skill.name,localDefinitionRef:hs(e.packageRoot),definitionHash:Pt({skillHash:e.skillHash})};return {packageRoot:e.packageRoot,source:e.source,appId:n,capabilities:["skill"],summary:Object.freeze(t)}}function Bl(e){return `skill.${e.replace(/^@/,"").replace(/\//g,".").replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,122)||"unnamed"}`}function Z(e,n,t,i,o){let r=nr(o?.reason),s=tr(o?.files);return Object.freeze({code:e,source:n,relativePath:Hl(t),...i===void 0?{}:{appId:i},...r===void 0?{}:{reason:r},...s===void 0?{}:{files:s}})}function Hl(e){if(typeof e!="string"||e.length===0||ce.isAbsolute(e)||/[\\\u0000]/.test(e))return "<unknown>";let n=e.split("/").filter(t=>t.length>0&&t!==".").join("/");return n.split("/").some(t=>t==="..")?"<unknown>":n}function Es(e){return Z(e.code,e.source,e.relativePath,e.pluginId,e)}function zl(e,n){let t=ms(e,n.dir);if(!t)return {diagnostic:Z("PATH_ESCAPED","node_modules","node_modules")};let i=vl(t);if(!i)return {diagnostic:Z("PATH_ESCAPED","node_modules",t)};let o=fi(n.skillMdPath);if(!o.readable)return {diagnostic:Z("SKILL_READ_FAILED",i,t)};if(!o.valid)return {diagnostic:Z("SKILL_INVALID",i,t)};let r=$l(n.dir,n.skillMdPath);if(!r)return {diagnostic:Z("PATH_ESCAPED",i,t)};try{let s=new Uint8Array(ne.readFileSync(n.skillMdPath));return {skill:n,packageRoot:t,relativeSkillPath:r,skillHash:Pt({relativePath:r,fileBytes:s}),source:i}}catch{return {diagnostic:Z("SKILL_READ_FAILED",i,t)}}}function $l(e,n){let t=ce.relative(e,n).split(ce.sep).join("/");try{return Nt(t)}catch{return null}}function Gl(e){if(!Ul.test(e.appId))return {diagnostic:Z("BUILTIN_INVALID","builtin",`builtin/${e.appId||"unknown"}`)};let n=e.definition===void 0?void 0:{id:e.definition.id,version:e.definition.version,hash:e.definition.hash,usage:e.definition.usage??je,...e.definition.detailPanel===void 0?{}:{detailPanel:e.definition.detailPanel},...e.definition.displayModes===void 0?{}:{displayModes:e.definition.displayModes},...e.definition.summaryProjection===void 0?{}:{summaryProjection:e.definition.summaryProjection}},t=n?.hash??Hi.createHash("sha256").update(JSON.stringify({appId:e.appId,name:e.name,description:e.description}),"utf8").digest("hex"),i={appId:e.appId,name:e.name,description:e.description,...n===void 0?{}:{version:String(n.version),definition:n},capabilities:["screen"],origin:"builtin",ownership:"unknown",shareability:"forbidden",sharingAvailability:"unavailable",definitionHash:t};return {source:"builtin",appId:e.appId,summary:Object.freeze(i)}}function Jl(e){return e.builtinCatalog}function Wl(e){let n=e.packageRoot??e.relativePath??e.packageRootPath;if(n===void 0)return null;try{return Nt(n)}catch{return null}}function Kl(e){let n=e.marketplaceContentId;return typeof n=="string"&&n.length>0?n:void 0}function Xl(e,n,t){let i=n.installed??[],o=new Map;for(let s of i){let a=Wl(s);if(!a){t.push(Z("INSTALLED_IDENTITY_MISMATCH","installed","installed"));continue}let c=o.get(a);if(c&&JSON.stringify(c)!==JSON.stringify(s)){t.push(Z("INSTALLED_IDENTITY_MISMATCH","installed",a));continue}o.set(a,s);}let r=new Map;for(let s of e)s.packageRoot!==void 0&&r.set(s.packageRoot,s);for(let[s,a]of o){let c=r.get(s);if(!c){t.push(Z("INSTALLED_MISSING","installed",s,a.appId));continue}let d=Kl(a);if(!d){t.push(Z("INSTALLED_CONTENT_ID_MISSING","installed",s,a.appId));continue}if(a.appId!==void 0&&a.appId!==c.appId||a.definitionHash!==void 0&&a.definitionHash!==c.summary.definitionHash){t.push(Z("INSTALLED_IDENTITY_MISMATCH","installed",s,a.appId));continue}let l={...c.summary,origin:"installed",...a.slug===void 0?{}:{slug:a.slug},marketplaceContentId:d},p=e.indexOf(c);p>=0&&(e[p]={...c,summary:Object.freeze(l)});}}function Yl(e,n){let t=new Map;for(let o of e){let r=t.get(o.appId)??[];r.push(o),t.set(o.appId,r);}let i=new Set;for(let o of t.values()){if(o.length<2)continue;let r=o.some(s=>s.source==="builtin")?"builtin":o.some(s=>s.source==="bundled")?"bundled":void 0;if(r==="bundled"){let s=o.filter(a=>a.source==="apps"&&a.summary.definition!==void 0);if(s.length===1){for(let a of o)a.source==="bundled"?i.add(a):a!==s[0]&&(i.add(a),n.push(Z("RESERVED_ID",a.source,bt(a),a.appId)));continue}}if(r!==void 0){let s=o.filter(a=>a.source===r);for(let a of o.filter(c=>c.source!==r))i.add(a),n.push(Z("RESERVED_ID",a.source,bt(a),a.appId));if(s.length>1)for(let a of s)i.add(a),n.push(Z("DUPLICATE_ID",a.source,bt(a),a.appId));continue}for(let s of o)i.add(s),n.push(Z("DUPLICATE_ID",s.source,bt(s),s.appId));}return e.filter(o=>!i.has(o))}function bt(e){return e.packageRoot??e.summary.provenance?.packageDir??`builtin/${e.appId}`}function ql(e,n){return e.filter(t=>!(t.code==="MANIFEST_MISSING"&&n.has(t.relativePath))).map(Es)}function Zl(e){return e.filesystem}function Ql(e,n){let t=Zl(e),i=e.registeredProductBundle;return {...t===void 0?{}:{filesystem:t},...e.productBundle===void 0?{}:{productBundle:e.productBundle},...n===void 0?{}:{builtinCatalog:n},...i===void 0?{}:{productBundleReservationMetadata:i}}}async function Ts(e,n={}){if(typeof e!="string"||e.length===0)throw new TypeError("workspaceRoot must be explicit");if(n.productBundle!==void 0&&n.registeredProductBundle!==void 0)throw new TypeError("registeredProductBundle cannot be combined with product bundle discovery");let t=Jl(n),i=await ys(e,Ql(n,t)),o=n.registeredProductBundle??i.productBundleSnapshotMetadata,r=[ce.join(e,"skills"),ce.join(e,"node_modules"),ce.join(e,"apps")],s=[],a=[],c=[],d=new Set;for(let A of r)for(let h of er([A])){let T=ms(e,h.dir);(T===null||!d.has(T))&&(c.push(h),T!==null&&d.add(T));}for(let A of c){let h=zl(e,A);"diagnostic"in h?s.push(h.diagnostic):a.push(h);}let l=new Map,p=n.registeredProductBundle?.indexHash,u=(n.registeredProductBundle?.candidates??[]).filter(A=>p!==void 0&&A.provenance?.indexHash===p),y=[...new Set([...i.apps??i.candidates??[],...i.productBundleSnapshotMetadata?.candidates??[]]),...u],g=new Set(u),_=new Set(p===void 0?[]:(t?.listMcpApps()??[]).filter(A=>A.provenance?.indexHash===p).map(A=>A.appId));for(let A of y){if(g.has(A)&&A.provenance?.indexHash===p&&_.has(A.appId))continue;let h=A.provenance===void 0?`workspace\0${A.relativePath}`:`bundled\0${A.provenance.indexHash}\0${A.provenance.packageDir}`;l.set(h,{candidate:A,packageRoot:A.relativePath});}let E=new Map(a.map(A=>[A.packageRoot,A])),U=[];for(let A of l.values()){let h=A.candidate.provenance===void 0?E.get(A.packageRoot):void 0,T=jl(A,h);U.push({...T.packageRoot===void 0?{}:{packageRoot:T.packageRoot},source:T.source,appId:T.appId,summary:T.summary});}let k=new Set([...l.values()].filter(A=>A.candidate.provenance===void 0).map(A=>A.packageRoot)),P=o===void 0?new Set:new Set(i.diagnostics.filter(A=>A.code==="RESERVED_ID"&&A.source!=="bundled").map(A=>A.relativePath)),w=new Set(o?.reservedAppIds??[]);for(let A of a){let h=Vl(A);if(!(k.has(A.packageRoot)||P.has(A.packageRoot))){if(w.has(h.appId)){s.push(Z("RESERVED_ID",A.source,A.packageRoot,h.appId));continue}U.push({packageRoot:h.packageRoot,source:h.source,appId:h.appId,summary:h.summary});}}let B=[...ql(i.diagnostics,new Set(a.map(A=>A.packageRoot))),...s,...n.registeredProductBundle?.diagnostics.filter(A=>A.source==="bundled").map(Es)??[]],N=[];if(t)for(let A of t.listMcpApps()){let h=Gl(A);"diagnostic"in h?B.push(h.diagnostic):N.push(h);}let D=Yl([...U,...N],B);Xl(D,n,B);let O=D.map(A=>A.summary).sort((A,h)=>Tt(A.appId,h.appId)),I=[...B].sort((A,h)=>Tt(A.relativePath,h.relativePath)||Tt(A.code,h.code)||Tt(A.appId??"",h.appId??""));return Object.freeze({items:Object.freeze(O),diagnostics:Object.freeze(I)})}m();m();m();function eu(e){let n=o=>o.replace(/[.+^${}()|[\]\\]/g,"\\$&"),i=e.split("/").map(o=>o==="**"?".*":o.split("*").map(n).join("[^/]*"));return new RegExp(`^${i.join("\\/")}$`)}function yn(e,n){try{return eu(n).test(e)}catch{return false}}function Dt(e,...n){let t=e.split("/");if(t.length<n.length)return false;let i=t.length-n.length;return n.every((o,r)=>yn(t[i+r],o))}function nu(e,n){return e.split("/").some(t=>yn(t,n))}var bs=[{label:".env*",test:e=>yn(e,".env*")},{label:".git/",test:(e,n,t)=>t&&e===".git"},{label:"memory/",test:(e,n,t)=>t&&e==="memory"},{label:"*.key",test:e=>yn(e,"*.key")},{label:"*.pem",test:e=>yn(e,"*.pem")},{label:"auth.json",test:e=>e==="auth.json"},{label:"node_modules/",test:(e,n,t)=>t&&e==="node_modules"},{label:"conversations/",test:(e,n,t)=>t&&e==="conversations"},{label:".crewx/threads/",test:(e,n,t)=>t&&Dt(n,".crewx","threads")},{label:".crewx/crewx.db",test:(e,n,t)=>!t&&Dt(n,".crewx","crewx.db")},{label:".crewx/*.log",test:(e,n,t)=>!t&&Dt(n,".crewx","*.log")},{label:".crewx/publish/",test:(e,n,t)=>t&&Dt(n,".crewx","publish")},{label:".crewx/",test:(e,n)=>nu(n,".crewx")}];function An(e,n,t){for(let i of bs)if(i.test(e,n,t))return i.label;return null}m();var xe=class extends Error{constructor(t,i){super(`publish: [${t}]${i?` ${i}`:""}`);this.code=t;}code;name="PublishError"};function b(e,n){return new xe(e,n)}function Ps(e,n){if(!n||/[\\\u0000]/.test(n)||ce__namespace.posix.isAbsolute(n)||n.split("/").some(y=>!y||y==="."||y===".."))throw b("PACKAGE_PATH_TRAVERSAL","package root must be a safe workspace-relative path");let t=ce__namespace.resolve(e),i=ce__namespace.resolve(t,...n.split("/"));if(!i.startsWith(`${t}${ce__namespace.sep}`))throw b("PACKAGE_PATH_TRAVERSAL","package root escaped the workspace");function o(y,g){let _;try{_=ne__namespace.lstatSync(y);}catch{throw b("PACKAGE_FILE_INVALID",`package directory is missing: ${g}`)}if(_.isSymbolicLink())throw b("PACKAGE_SYMLINK",`symlink is not publishable: ${g}`);if(!_.isDirectory())throw b("PACKAGE_FILE_INVALID",`not a package directory: ${g}`)}o(t,".");let r=t,s="",a=null;for(let y of n.split("/"))r=ce__namespace.join(r,y),s=s?`${s}/${y}`:y,o(r,s),a??=An(y,s,true);let c=[],d=[];function l(y,g){o(y,g);let _=ne__namespace.readdirSync(y,{withFileTypes:true});for(let E of _){let U=`${g}/${E.name}`,k=ce__namespace.join(y,E.name);if(E.isSymbolicLink())throw b("PACKAGE_SYMLINK",`symlink is not publishable: ${U}`);let P=An(E.name,U,E.isDirectory());P?d.push({path:U,rule:P}):E.isDirectory()?l(k,U):E.isFile()&&c.push(U);}}a?d.push({path:n,rule:a}):l(i,n);let p=new TextEncoder,u=(y,g)=>Buffer.compare(p.encode(y),p.encode(g));return c.sort(u),d.sort((y,g)=>u(y.path,g.path)),{included:c,excluded:d}}function Ns(e){let n=[],t=[];function i(o,r,s){let a;try{a=ne__namespace.readdirSync(o,{withFileTypes:!0});}catch{return}a.sort((c,d)=>c.name.localeCompare(d.name));for(let c of a){let d=r?`${r}/${c.name}`:c.name,l=ce__namespace.join(o,c.name);if(c.isSymbolicLink()){let p;try{p=ne__namespace.statSync(l);}catch{t.push({path:d,rule:"symlink"});continue}if(p.isDirectory()){t.push({path:d,rule:s??"symlink-dir"});continue}let u=s??An(c.name,d,false);u?t.push({path:d,rule:u}):t.push({path:d,rule:"symlink"});continue}if(c.isDirectory()){let p=s??An(c.name,d,true);i(l,d,p);continue}if(c.isFile()){let p=s??An(c.name,d,false);p?t.push({path:d,rule:p}):n.push(d);}}}return i(e,"",null),n.sort(),t.sort((o,r)=>o.path<r.path?-1:o.path>r.path?1:0),{included:n,excluded:t}}m();var tu=[{rule:"token-prefix",regex:/\b(?:sk-|ghp_|xoxb-)[A-Za-z0-9_-]{10,}/},{rule:"private-key",regex:/-----BEGIN [A-Z ]*PRIVATE KEY-----/},{rule:"aws-access-key",regex:/\bAKIA[0-9A-Z]{16}\b/}];function iu(e){return e.includes(0)}function Bi(e,n,t){let i=[];for(let o of n){let r=ce__namespace.join(e,o),s;try{let c=t?.get(o);s=c===void 0?ne__namespace.readFileSync(r):Buffer.from(c);}catch{continue}if(iu(s))continue;s.toString("utf8").split(/\r\n|\r|\n/).forEach((c,d)=>{for(let{rule:l,regex:p}of tu)p.test(c)&&i.push({path:o,line:d+1,rule:l});});}return i}m();var Ms=/^[a-z0-9-]+$/,ou=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/,ru=/^[A-Za-z_][A-Za-z0-9_]*$/;function su(e){let n=ce__namespace.join(e,"crewx.yaml");if(!ne__namespace.existsSync(n))return {};let t;try{t=Os__namespace.load(ne__namespace.readFileSync(n,"utf8"));}catch{return {}}if(!t||typeof t!="object")return {};let i=t.metadata;if(!i||typeof i!="object")return {};let o=i;return {name:typeof o.name=="string"?o.name:void 0,version:typeof o.version=="string"?o.version:void 0,description:typeof o.description=="string"?o.description:void 0,requiredEnv:o.requiredEnv,crewxMinVersion:typeof o.crewxMinVersion=="string"?o.crewxMinVersion:void 0}}function au(e){return Hi__namespace.createHash("sha256").update(e).digest("hex")}function Ls(e){let n;try{n=ne__namespace.lstatSync(e);}catch{throw b("PACKAGE_FILE_INVALID",`file is not readable: ${ce__namespace.basename(e)}`)}if(n.isSymbolicLink())throw b("PACKAGE_SYMLINK","symlink content is not publishable");if(!n.isFile())throw b("PACKAGE_FILE_INVALID","only regular files are publishable");return Hi__namespace.createHash("sha256").update(new Uint8Array(ne__namespace.readFileSync(e))).digest("hex")}function cu(e,n){let t=new TextEncoder().encode(e),i=new TextEncoder().encode(n),o=Math.min(t.byteLength,i.byteLength);for(let r=0;r<o;r+=1){let s=t[r]-i[r];if(s!==0)return s}return t.byteLength-i.byteLength}function Rs(e){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||ce__namespace.posix.isAbsolute(e)||e.split("/").some(n=>n===".."||n.length===0))throw b("PACKAGE_PATH_TRAVERSAL","manifest file path must be a non-empty POSIX relative path")}function du(e){if(!/^(?:apps|skills)\/[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(e))throw b("APP_PACKAGE_ROOT_INVALID","packageRoot must be apps/<safe-id> or skills/<safe-id>")}function ws(e){if(!ou.test(e))throw new Error(`publish: invalid version "${e}" \u2014 must be semver (e.g. 1.0.0)`)}function Cs(e,n,t={}){let i=su(e),o=i.name??ce__namespace.basename(e);if(!Ms.test(o))throw new Error(`publish: invalid name "${o}" \u2014 must match ${Ms} (lowercase letters, numbers, hyphen only)`);let r=t.version??i.version;if(!r)throw new Error("publish: version is required \u2014 set crewx.yaml metadata.version or pass opts.version");ws(r);let s=Array.isArray(i.requiredEnv)?i.requiredEnv:[],a=[];for(let l of s){if(typeof l!="string"||!ru.test(l))throw new Error(`publish: requiredEnv must contain names only (no values), got "${String(l)}"`);a.push(l);}let c=n.map(l=>(Rs(l),{path:l,sha256:Ls(ce__namespace.join(e,l))})).sort((l,p)=>l.path<p.path?-1:l.path>p.path?1:0),d={name:o,version:r,type:"template",description:i.description??"",files:c,requiredEnv:a};return i.crewxMinVersion&&(d.crewxMinVersion=i.crewxMinVersion),d}function pu(e){let n=e.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"");if(!n)throw b("APP_PACKAGE_ROOT_INVALID","appId cannot produce a marketplace name");return n}function Us(e,n){if(du(n.packageRoot),!n.version)throw new Error("publish: version is required for App publishing \u2014 pass opts.version");if(ws(n.version),typeof n.description!="string")throw new Error("publish: App description must be a string");let t=[...new Set(n.capabilities)].sort();if(t.length===0||t.some(s=>s!=="screen"&&s!=="skill"))throw new Error("publish: App capabilities must contain screen or skill");let i=`${n.packageRoot}/`;if(t.includes("screen")){if(typeof n.definitionId!="string"||n.definitionId.length===0)throw b("APP_UI_MANIFEST_INVALID","screen App manifests require definitionId");let s=n.includedFiles.includes(`${i}manifest.json`),a=n.includedFiles.includes(`${i}ui-plugin.json`);if(!s&&!a)throw b("APP_UI_MANIFEST_INVALID","screen App is missing manifest.json or ui-plugin.json");if(s&&!a)throw b("APP_UI_MANIFEST_INVALID","a manifest.json App must also ship a generated ui-plugin.json");if(!n.includedFiles.includes(`${i}ui/index.html`))throw b("APP_UI_MANIFEST_INVALID","screen App is missing ui/index.html")}if(t.includes("skill")&&!n.includedFiles.includes(`${i}SKILL.md`))throw b("APP_SKILL_MISSING","skill capability requires package-root SKILL.md");let o=new Set,r=n.includedFiles.map(s=>{if(Rs(s),!s.startsWith(i))throw b("PACKAGE_PATH_TRAVERSAL","App manifest file is outside packageRoot");let a=n.generatedFiles?.get(s);return a!==void 0&&o.add(s),{path:s,sha256:a===void 0?Ls(ce__namespace.join(e,s)):au(a),...a===void 0?{}:{generated:true}}}).sort((s,a)=>cu(s.path,a.path));if(o.size>0&&(o.size!==1||!o.has(`${i}ui-plugin.json`)))throw new Error("publish: only the generated ui-plugin.json may be present in an App package");return {manifestVersion:1,name:pu(n.appId),version:n.version,type:"app",description:n.description,appId:n.appId,...n.definitionId===void 0?{}:{definitionId:n.definitionId},...n.definitionHash===void 0?{}:{definitionHash:n.definitionHash},capabilities:t,packageRoot:n.packageRoot,files:r,requiredEnv:[]}}m();function ks(e){return Hi__namespace.createHash("sha256").update(e).digest("hex")}function Vs(e,n){if(typeof n!="string"||n.length===0||n.includes("\\")||n.includes("\0")||ce__namespace.posix.isAbsolute(n)||n.split("/").some(o=>o===".."||o.length===0))throw b("PACKAGE_PATH_TRAVERSAL","archive paths must be non-empty POSIX relative paths");let t=ce__namespace.resolve(e),i=ce__namespace.resolve(t,...n.split("/"));if(i!==t&&!i.startsWith(`${t}${ce__namespace.sep}`))throw b("PACKAGE_PATH_TRAVERSAL","archive path escaped its root");return i}function xs(e,n){let t=Vs(e,n),i;try{i=ne__namespace.lstatSync(t);}catch{throw b("PACKAGE_FILE_INVALID","manifest file is missing")}if(i.isSymbolicLink())throw b("PACKAGE_SYMLINK","symlink content is not publishable");if(!i.isFile())throw b("PACKAGE_FILE_INVALID","only regular files are publishable");return new Uint8Array(ne__namespace.readFileSync(t))}async function Bs(e,n,t={}){let i=ce__namespace.join(e,".crewx","publish");ne__namespace.mkdirSync(i,{recursive:true});let o=ce__namespace.join(i,`${n.name}-${n.version}.tgz`),r=ce__namespace.join(i,`.${n.name}-${n.version}.${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}.tmp.tgz`),s=ne__namespace.mkdtempSync(ce__namespace.join(vs__namespace.tmpdir(),"crewx-publish-"));try{let a=new Set,c=[];for(let d of n.files){if(a.has(d.path))throw b("PACKAGE_PATH_TRAVERSAL","manifest contains duplicate file paths");a.add(d.path);let l=t.generatedFiles?.get(d.path);if(d.generated===!0&&l===void 0)throw b("PACKAGE_GENERATED_FILE_MISSING","generated manifest file bytes are missing");if(t.sourceFileHashes?.has(d.path)){let y=xs(e,d.path);if(t.sourceFileHashes.get(d.path)!==ks(y))throw b("PACKAGE_STAGED_BYTES_MISMATCH","workspace source changed before staging")}let p=l??xs(e,d.path);if(ks(p)!==d.sha256)throw b("PACKAGE_STAGED_BYTES_MISMATCH",`staged bytes differ for ${d.path}`);let u=Vs(s,d.path);ne__namespace.mkdirSync(ce__namespace.dirname(u),{recursive:!0}),ne__namespace.writeFileSync(u,new Uint8Array(p)),c.push(d.path);}ne__namespace.writeFileSync(ce__namespace.join(s,"manifest.json"),JSON.stringify(n,null,2)),await js__namespace.create({gzip:!0,file:r,cwd:s,portable:!0,noMtime:!0},["manifest.json",...c]),ne__namespace.renameSync(r,o);}finally{try{ne__namespace.rmSync(r,{force:!0});}catch{}ne__namespace.rmSync(s,{recursive:true,force:true});}return o}m();m();var In="/api/v1";var fu=201,yu=200,Au=409,zi=401,Hs={APP_NAME_CONFLICT:"APP_NAME_CONFLICT",CONTENT_SUSPENDED:"PUBLISH_CONTENT_SUSPENDED",CONTENT_REJECTED:"CONTENT_REJECTED",APP_VERSION_MUST_INCREASE:"APP_VERSION_MUST_INCREASE",APP_VERSION_INVALID:"APP_VERSION_INVALID"};function Iu(){return process.env.WI013_FAKE_UPLOAD==="1"}function gu(e){let n=zlib.gunzipSync(new Uint8Array(e)),t=zlib.gzipSync(new Uint8Array(n),{level:1});if(Buffer.compare(new Uint8Array(t),new Uint8Array(e))===0)throw new Error("publish: [E_MALFORMED] Re-gzipped upload bytes are identical to the original \u2014 tamper is a no-op");return t}function mu(e){return e.replace(/\/+$/,"")}async function jn(e){try{return await e.json()}catch{return null}}function zs(e,n,t){let i=e;if(!i||i.success!==true||i.data===void 0)throw new Error(`publish: [E_MALFORMED] ${n} response envelope is malformed (expected { success: true, data }) \u2014 HTTP ${t}`);return i.data}function hu(e){if(!e||typeof e!="object"||Array.isArray(e))return;let n=e;if(typeof n.contentId=="string"&&n.contentId.length>0)return n.contentId;if(!n.data||typeof n.data!="object"||Array.isArray(n.data))return;let t=n.data;return typeof t.contentId=="string"&&t.contentId.length>0?t.contentId:void 0}function _u(e){if(!e||typeof e!="object"||Array.isArray(e))return;let n=e;if(typeof n.slug=="string"&&n.slug.length>0)return n.slug;if(!n.data||typeof n.data!="object"||Array.isArray(n.data))return;let t=n.data;return typeof t.slug=="string"&&t.slug.length>0?t.slug:void 0}function $s(e,n){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e,i=t.data&&typeof t.data=="object"&&!Array.isArray(t.data)?t.data:void 0,o=[t.code,t.message,i?.code,i?.message];for(let r of o){if(typeof r!="string"||!Object.prototype.hasOwnProperty.call(Hs,r))continue;let s=r,a=s==="APP_NAME_CONFLICT"?`marketplace name is already in use: ${n}`:void 0;return b(Hs[s],a)}}async function Eu(e){if(!e.baseUrl.trim())throw new Error("publish: [E_ENV_MISSING] Marketplace base URL is required");if(!e.accessToken.trim())throw new Error("publish: [E_AUTH_EXPIRED] A valid bearer token is required");let n=mu(e.baseUrl),t=e.accessPolicy??"private",i=e.manifest.name,o=e.manifest.type==="app"?e.manifest:void 0,r=o!==void 0,s=o?.appId,a;try{a=await fetch(`${n}${In}/publisher/items`,{method:"POST",headers:{Authorization:`Bearer ${e.accessToken}`,"Content-Type":"application/json"},body:JSON.stringify({slug:i,displayName:i,description:e.manifest.description,type:e.manifest.type,version:e.manifest.version,accessPolicy:t,...s===void 0?{}:{appId:s}})});}catch{throw new Error("publish: [E_NETWORK] Submit request failed (network)")}let c=await jn(a),d=hu(c),l=_u(c),p=r&&l!==void 0?l:i,u;if(a.status===fu)u="created";else if(r&&a.status===yu){if(d===void 0)throw b("PUBLISH_CONTENT_ID_MISSING","App republish did not return an opaque contentId");u="existing";}else if(a.status===Au){if(r)throw $s(c,i)??b("APP_NAME_CONFLICT",`marketplace name is already in use: ${i}`);u="existing";}else throw a.status===zi?new Error("publish: [E_AUTH_EXPIRED] Authentication is expired or missing \u2014 please log in again (HTTP 401)"):new Error(`publish: [E_HTTP] Submit request failed \u2014 HTTP ${a.status}`);let y="not-needed",g=null;if(u==="existing"&&!r){let D;try{D=await fetch(`${n}${In}/publisher/items`,{method:"GET",headers:{Authorization:`Bearer ${e.accessToken}`}});}catch{throw new Error("publish: [E_NETWORK] Publisher items request failed (network)")}let O=await jn(D);if(D.status!==200)throw new Error(`publish: [E_HTTP] Publisher items request failed \u2014 HTTP ${D.status}`);let A=zs(O,"publisher items",D.status)?.items;if(!Array.isArray(A))throw new Error(`publish: [E_MALFORMED] Publisher items response is malformed (expected data.items[]) \u2014 HTTP ${D.status}`);let h=A.find(T=>!T||typeof T!="object"?false:T.slug===i);if(!h||typeof h.version!="string")throw new Error(`publish: [E_MALFORMED] Publisher items response does not contain slug "${i}" \u2014 HTTP ${D.status}`);if(g=h.version,g!==e.manifest.version){let T;try{T=await fetch(`${n}${In}/publisher/items/${encodeURIComponent(i)}`,{method:"PUT",headers:{Authorization:`Bearer ${e.accessToken}`,"Content-Type":"application/json"},body:JSON.stringify({version:e.manifest.version})});}catch{throw new Error("publish: [E_NETWORK] Version update request failed (network)")}if(!T.ok)throw await jn(T),T.status===zi?new Error(`publish: [E_AUTH_EXPIRED] Authentication is expired or missing \u2014 please log in again (HTTP ${T.status})`):T.status===403?new Error(`publish: [E_FORBIDDEN] Version update is forbidden; only the item owner can update an existing item (HTTP ${T.status})`):new Error(`publish: [E_HTTP] Version update failed \u2014 HTTP ${T.status}`);y="applied";}}let _=ne__namespace.readFileSync(e.tgzPath),E=Iu()?gu(_):_,U=new FormData;U.set("archive",new Blob([new Uint8Array(E)],{type:"application/gzip"}),`${p}-${e.manifest.version}.tgz`);let k=r&&d!==void 0?d:i,P;try{P=await fetch(`${n}${In}/publisher/items/${encodeURIComponent(k)}/upload`,{method:"POST",headers:{Authorization:`Bearer ${e.accessToken}`},body:U});}catch{throw new Error("publish: [E_NETWORK] Upload request failed (network)")}if(P.status===zi)throw new Error("publish: [E_AUTH_EXPIRED] Authentication is expired or missing \u2014 please log in again (HTTP 401)");if(!P.ok){let D=await jn(P);if(r){let O=$s(D,p);if(O)throw O}throw new Error(`publish: [E_HTTP] Upload request failed \u2014 HTTP ${P.status}`)}let w=await jn(P),B=zs(w,"upload",P.status),N=typeof B.contentId=="string"&&B.contentId.length>0?B.contentId:d;if(r&&N===void 0)throw b("PUBLISH_CONTENT_ID_MISSING","App upload did not return an opaque contentId");return {slug:p,version:e.manifest.version,...N===void 0?{}:{contentId:N},artifactChecksum:B.artifactChecksum,artifactSizeBytes:B.artifactSizeBytes,submitOutcome:u,versionUpdate:y,serverVersionBefore:g}}var Tu=1e4,bu=100*1024*1024;function $i(e){return Hi__namespace.createHash("sha256").update(e).digest("hex")}function Pu(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function $e(e,n){if(!n||n.includes("\\")||n.includes("\0")||ce__namespace.posix.isAbsolute(n)||n.split("/").some(r=>r===".."||r.length===0))throw b("PACKAGE_PATH_TRAVERSAL","workspace file path is not a safe relative path");let t=ce__namespace.resolve(e,...n.split("/")),i=ce__namespace.resolve(e);if(t!==i&&!t.startsWith(`${i}${ce__namespace.sep}`))throw b("PACKAGE_PATH_TRAVERSAL","workspace file path escaped the workspace root");let o;try{o=ne__namespace.lstatSync(t);}catch{throw b("PACKAGE_FILE_INVALID",`workspace file is missing: ${n}`)}if(o.isSymbolicLink())throw b("PACKAGE_SYMLINK",`symlink is not publishable: ${n}`);if(!o.isFile())throw b("PACKAGE_FILE_INVALID",`not a regular file: ${n}`);return new Uint8Array(ne__namespace.readFileSync(t))}async function Nu(e,n,t){let i=`${n}/${W}`;if(!t.includes(i))return [];let o={[W]:$e(e,i)},r=`${n}/${$}`;t.includes(r)&&(o[$]=$e(e,r));let s=He(o,{mode:"local"});if(!s.ok)return [];let{diagnostics:a}=await Tn(s.mcpb?.icon,async d=>{let l=`${n}/${d}`;return t.includes(l)?$e(e,l):"missing"}),c=a.find(d=>d.code==="ICON_INVALID");if(c!==void 0)throw b("ICON_INVALID",`${c.reason??"invalid"} at ${c.declared??"icon"}`);return a.flatMap(d=>d.code==="ICON_INVALID"?[]:[{code:d.code,path:d.declared??"icon"}])}function Js(e,n,t){let i=e??n;if(!Number.isSafeInteger(i)||i<=0)throw new xe("PACKAGE_SIZE_LIMIT",`${t} must be a positive integer`);return i}function Ks(e,n,t,i){let o=Js(t.maxFileCount??t.maxFiles,Tu,"max file count"),r=Js(t.maxTotalBytes??t.maxBytes,bu,"max total bytes");if(n.length>o)throw new xe("PACKAGE_SIZE_LIMIT",`package exceeds file count limit (${o})`);let s=0;for(let a of n){let c=i?.get(a);if(c!==void 0?s+=c.byteLength:s+=$e(e,a).byteLength,s>r)throw new xe("PACKAGE_SIZE_LIMIT",`package exceeds byte limit (${r})`)}}function Du(e){return e.appId!==void 0||e.expectedDefinitionHash!==void 0}function Su(e){let n=e.appId!==void 0,t=e.expectedDefinitionHash!==void 0;if(!n&&t)throw b("APP_ID_REQUIRED","appId is required with expectedDefinitionHash");if(n&&!t)throw b("APP_DEFINITION_HASH_REQUIRED","expectedDefinitionHash is required with appId");if(!n||!t)throw b("APP_ID_REQUIRED")}function Mu(e,n){let t=e.filter(i=>i.appId===n);if(t.length===0)throw b("APP_NOT_FOUND",`no publishable App matches ${n}`);if(t.length!==1)throw b("APP_AMBIGUOUS",`more than one App matches ${n}`);return t[0]}function Ou(e){let n=e.localDefinitionRef?.packageRoot;if(!n||!/^(?:apps|skills)\/[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(n))throw b("APP_PACKAGE_ROOT_INVALID","selected App is not rooted in apps/<safe-id> or skills/<safe-id>");return n}function Gi(e){let{path:n,rule:t}=e.reason;return `${e.code} at ${n===""?"<file>":n} (${t})`+(e.files.length>0?` [${e.files.join(", ")}]`:"")}function Lu(e,n,t){let i=He({[de]:t},{mode:"published"});if(!i.ok)throw b("APP_UI_MANIFEST_INVALID",`generated ${de} does not read: ${Gi(i.rejection)}`);if(dn(i.manifest)!==dn(n))throw b("APP_UI_MANIFEST_INVALID",`generated ${de} normalizes to a different definition hash than the source`);let o=e[W];if(o===void 0)return;let r=e[$],s=He({[W]:o,[de]:t,...r===void 0?{}:{[$]:r}},{mode:"local"});if(!s.ok)throw b("APP_UI_MANIFEST_INVALID",Gi(s.rejection))}function Ru(e,n,t,i){let o={};for(let y of Q){let g=`${t}/${y}`;i.includes(g)&&(o[y]=$e(e,g));}let r=`${t}/${$}`;if(o[W]!==void 0&&i.includes(r)&&(o[$]=$e(e,r)),Object.keys(o).length===0)throw b("APP_UI_MANIFEST_INVALID","selected screen App has no package manifest.json or ui-plugin.json");let s=He(o,{mode:"local"});if(!s.ok)throw b("APP_UI_MANIFEST_INVALID",Gi(s.rejection));if(s.manifest.pluginId!==n.appId)throw b("APP_DEFINITION_CONFLICT",`${s.file} identity no longer matches the selected App`);let a=o[de],c=a===void 0?void 0:$i(a),d=`${t}/ui/index.html`;if(!i.includes(d))throw b("APP_UI_MANIFEST_INVALID","screen entry is outside package scope");let l=$i($e(e,d)),p=JSON.parse(JSON.stringify(s.v2Input));if(p.entryHash=l,Object.prototype.hasOwnProperty.call(p,"initialState")){let y=p.initialState;if(!Pu(y)||y.path!=="ui/state.json")throw b("APP_INITIAL_STATE_OUT_OF_SCOPE","initialState must reference ui/state.json inside the package");let g=`${t}/ui/state.json`;if(!i.includes(g))throw b("APP_INITIAL_STATE_OUT_OF_SCOPE","initialState reference is outside the selected package");let _=$e(e,g);p.initialState={...y,hash:$i(_)};}let u;try{let y=Ke(p,{mode:"published"});u=new Uint8Array(Buffer.from(JSON.stringify(y),"utf8"));}catch(y){throw y instanceof ae?b("APP_UI_MANIFEST_INVALID",y.code):b("APP_UI_MANIFEST_INVALID")}return Lu(o,s.manifest,u),{bytes:u,...c===void 0?{}:{legacySourceHash:c}}}async function wu(e,n){let{included:t,excluded:i}=Ns(e);Ks(e,t,n);let o=Cs(e,t,{version:n.version}),r=Bi(e,t);return {plan:{manifest:o,included:t,excluded:i,secretFindings:r},archiveOptions:{}}}async function Cu(e,n){Su(n);let t=await Ts(e),i=Mu(t.items,n.appId);if(i.definitionHash!==n.expectedDefinitionHash)throw b("APP_DEFINITION_CONFLICT",`definitionHash changed for ${n.appId}`);let o=Ou(i),{included:r,excluded:s}=Ps(e,o),a=await Nu(e,o,r),c=new Map,d=new Map;if(i.capabilities.includes("screen")){let y=Ru(e,i,o,r),g=`${o}/${de}`;if(c.set(g,y.bytes),y.legacySourceHash!==void 0)d.set(g,y.legacySourceHash);else {r.push(g);let _=new TextEncoder;r.sort((E,U)=>Buffer.compare(_.encode(E),_.encode(U)));}}if(i.capabilities.includes("skill")&&!r.includes(`${o}/SKILL.md`))throw b("APP_SKILL_MISSING","skill capability requires package-root SKILL.md");Ks(e,r,n,c);let l={appId:i.appId,version:n.version??"",description:i.description,capabilities:i.capabilities,packageRoot:o,...i.definition?.id===void 0?{}:{definitionId:i.definition.id},definitionHash:i.definitionHash,includedFiles:r,generatedFiles:c},p=Us(e,l),u=Bi(e,r,c);return {plan:{manifest:p,included:r,excluded:s,secretFindings:u,warnings:a},archiveOptions:{generatedFiles:c,sourceFileHashes:d}}}async function Xs(e,n){let t=ce__namespace.resolve(e);if(Du(n))return Cu(t,n);if(n.expectedDefinitionHash!==void 0)throw b("APP_ID_REQUIRED");return wu(t,n)}async function GI(e,n={}){return (await Xs(e,n)).plan}function Uu(e){let n=e.map(t=>`${t.path}:${t.line} (${t.rule})`).join(", ");throw new xe("PUBLISH_SECRET_FINDINGS",`aborted \u2014 secret findings must be resolved before packing: ${n}`)}async function Ys(e,n={}){let t=ce__namespace.resolve(e),i=await Xs(t,n);i.plan.secretFindings.length>0&&Uu(i.plan.secretFindings);let o=await Bs(t,i.plan.manifest,i.archiveOptions);return {manifest:i.plan.manifest,tgzPath:o}}async function JI(e,n={}){return Ys(e,n)}async function WI(e,n){let t=await Ys(e,n);if(t.manifest.type!=="app")throw new Error("publish: App pack unexpectedly produced a template manifest");return t}
2
- exports.DEFAULT_PUBLISH_MAX_BYTES=bu;exports.DEFAULT_PUBLISH_MAX_FILES=Tu;exports.EXCLUDE_RULES=bs;exports.MARKETPLACE_API_PREFIX=In;exports.PublishError=xe;exports.packApp=WI;exports.packPublish=Ys;exports.packTemplate=JI;exports.planPublish=GI;exports.uploadToMarketplace=Eu;
1
+ 'use strict';var zi=require('crypto'),net=require('net'),ne=require('fs'),promises=require('fs/promises'),de=require('path'),Rs=require('js-yaml'),Fs=require('os'),Bs=require('tar'),zlib=require('zlib');function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var zi__namespace=/*#__PURE__*/_interopNamespace(zi);var ne__namespace=/*#__PURE__*/_interopNamespace(ne);var de__namespace=/*#__PURE__*/_interopNamespace(de);var Rs__namespace=/*#__PURE__*/_interopNamespace(Rs);var Fs__namespace=/*#__PURE__*/_interopNamespace(Fs);var Bs__namespace=/*#__PURE__*/_interopNamespace(Bs);var j=(e,n)=>()=>(e&&(n=e(e=0)),n);var m=j(()=>{});var w,Hn=j(()=>{m();w=class extends Error{constructor(t,i=t,o){super(i);this.code=t;this.currentRevision=o;}code;currentRevision;name="UiRuntimeError"};});function wt(e){return ea.test(e)||na.test(e)}function Ae(){throw new w("INPUT_INVALID","JSON value is not projection-safe")}function ra(e){let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function Ot(e,n,t,i,o,r){if(n>i&&Ae(),e===null||typeof e=="string"||typeof e=="boolean")return typeof e=="string"&&(ta.test(e)||oa.test(e)&&!ca(o,r)||ia.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 s=e;t.has(s)&&Ae(),t.add(s);try{if(Array.isArray(e))return e.map(c=>Ot(c,n+1,t,i,o,r));ra(s)||Ae();let a={};for(let[c,d]of Object.entries(e))wt(c)&&Ae(),a[c]=Ot(d,n+1,t,i,[...o,c],r);return a}finally{t.delete(s);}}function Ie(e,n=0,t=[]){(!Number.isInteger(n)||n<0||n>aa)&&Ae(),(!Array.isArray(t)||t.some(o=>typeof o!="string"))&&Ae();let i=Ot(e,0,new Set,sa+n,[],t);return (i===null||Array.isArray(i)||typeof i!="object")&&Ae(),i}function tn(e,n){if(!e||!n)return false;let t=e.split("."),i=n.split(".");return t.length>=i.length&&i.every((o,r)=>t[r]===o)}function ca(e,n){if(e.length===0)return false;let t=e.join(".");return n.some(i=>tn(t,i))}function on(e){try{let n=JSON.stringify(e);return n===void 0&&Ae(),n}catch{Ae();}}function Rt(e){return Array.isArray(e)?e.map(Rt):e!==null&&typeof e=="object"?Object.fromEntries(Object.keys(e).sort().map(n=>[n,Rt(e[n])])):e}function te(e){return on(Rt(e))}function Ct(e){return Buffer.byteLength(e,"utf8")}var ea,na,ta,ia,oa,sa,aa,Ce=j(()=>{m();Hn();ea=/(?:proof|token|secret|password|cookie|authorization|private[_-]?key|stack|exception|plugin[_-]?text)/i,na=/(?:url|uri|endpoint|path|file(?:name|path)?|cwd|shell|directory|dir|folder)$/i,ta=/<\/?[A-Za-z][^>]*>/,ia=/^(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)/,oa=/^(?:https?|file|ftp|ws|wss):\/\//i;sa=8,aa=4;});var Wi=j(()=>{m();Ce();});var zn,Ut=j(()=>{m();zn=["text/plain","application/json"];});var Ki=j(()=>{m();Ut();});function rn(e){return pa.has(e)||la.test(e)||ua.test(e)}var Xi,pa,la,ua,$n,hn,Se,kt,xt,vt,jt,Ft,Je=j(()=>{m();Xi=["__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"],pa=new Set(Xi),la=/(?:proof|token|secret|password|cookie|authorization|private[_-]?key|stack|exception|plugin[_-]?text)/i,ua=/(?:url|uri|endpoint|path|file(?:name|path)?|cwd|shell|directory|dir|folder)$/i;$n=/^[A-Za-z0-9_]+$/,hn=/^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)*$/,Se=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,kt=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/,xt=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,vt=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/,jt=["blue","violet","emerald","amber","rose","sky","slate","indigo"],Ft=["inline","panel"];});function Vt(e){return typeof e=="string"&&zn.includes(e)}var Yi=j(()=>{m();Ut();Je();});function Gn(e){if(!Bt(e))return false;let n=Object.keys(e);return !(n.some(t=>t!=="in"&&t!=="out")||n.length===0||Object.hasOwn(e,"in")&&!fa(e.in)||Object.hasOwn(e,"out")&&!ya(e.out))}function fa(e){return Bt(e)?Object.keys(e).every(t=>t==="mediaType"||t==="required")&&Object.hasOwn(e,"mediaType")&&Vt(e.mediaType)&&(!Object.hasOwn(e,"required")||typeof e.required=="boolean"):false}function ya(e){return Bt(e)?Object.keys(e).every(t=>t==="mediaType"||t==="range")&&Object.hasOwn(e,"mediaType")&&Vt(e.mediaType)&&(!Object.hasOwn(e,"range")||typeof e.range=="boolean"):false}function Bt(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}var Ht=j(()=>{m();Ki();Yi();new TextDecoder("utf-8",{fatal:true,ignoreBOM:true});});function Wn(e){return Aa.includes(e)}function Kn(e){return Number.isSafeInteger(e)&&e>=Jn.min&&e<=Jn.max}var Aa,Jn,qi,zt=j(()=>{m();Aa=[5,15,30,60],Jn=Object.freeze({min:15e3,max:6e5,default:3e5}),qi=1;});function Yn(e){return Number.isSafeInteger(e)&&e>=Xn.min&&e<=Xn.max}function qn(e){return Ia.includes(e)}var Xn,Zi,Ia,$t=j(()=>{m();Xn=Object.freeze({min:6e4,max:18e5,default:6e5}),Zi=1,Ia=["start","status","cancel"];});function ue(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(o=>o.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=Ie(t);return zi.createHash("sha256").update(te(i)).digest("hex")}function Jt(e){return `${e.id}\0${e.version}`}function ge(e){if(!/^\d+$/.test(String(e.version))||e.version<1||e.id.length<1||e.id.length>128)throw new w("DEFINITION_UNSUPPORTED","UI definition is invalid");if(e.sourceHash!==void 0&&(typeof e.sourceHash!="string"||!ma.test(e.sourceHash)))throw new w("DEFINITION_UNSUPPORTED","UI definition source hash is invalid");if(!/^[0-9a-f]{64}$/.test(e.hash)||ue(e)!==e.hash)throw new w("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=>!_a(i)))throw new w("DEFINITION_UNSUPPORTED","UI action declaration is invalid");if(t.confirmation!==void 0&&t.confirmation!=="none"&&t.confirmation!=="native")throw new w("DEFINITION_UNSUPPORTED","UI action confirmation is invalid");if(t.mutation!==void 0&&typeof t.mutation!="boolean")throw new w("DEFINITION_UNSUPPORTED","UI action mutation policy is invalid");if(t.inputKeys&&(!Array.isArray(t.inputKeys)||t.inputKeys.some(i=>typeof i!="string"||!i)))throw new w("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 w("DEFINITION_UNSUPPORTED","UI action data input declaration is invalid");if(t.resultProjection&&Gt(t.resultProjection),t.schedule!==void 0&&(!Wn(t.schedule.everyMinutes)||!Kn(t.schedule.timeoutMs)))throw new w("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")||!Yn(t.job.deadlineMs)))throw new w("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(qn)||t.job!==void 0))throw new w("DEFINITION_UNSUPPORTED","UI action job control declaration is invalid");if(t.content!==void 0&&!Gn(t.content))throw new w("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 w("DEFINITION_UNSUPPORTED","UI action environment declaration is invalid")}if(e.renderer!==void 0&&(!e.renderer||e.renderer.length>128))throw new w("DEFINITION_UNSUPPORTED","UI definition renderer is invalid");if(e.surfaces&&(!Array.isArray(e.surfaces)||e.surfaces.some(n=>!n||n.length>64)))throw new w("DEFINITION_UNSUPPORTED","UI definition surfaces are invalid");if(e.usage!==void 0&&e.usage!=="card"&&e.usage!=="window")throw new w("DEFINITION_UNSUPPORTED","UI definition usage is invalid");if(e.detailPanel!==void 0&&typeof e.detailPanel!="boolean")throw new w("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 w("DEFINITION_UNSUPPORTED","UI definition displayModes are invalid");if(e.usage==="card"&&e.displayModes!==void 0)throw new w("DEFINITION_UNSUPPORTED","Card definitions cannot declare displayModes");if(e.usage==="window"&&e.detailPanel!==void 0)throw new w("DEFINITION_UNSUPPORTED","Window definitions cannot declare detailPanel");if(e.stateProjection&&Gt(e.stateProjection),e.summaryProjection){Gt(e.summaryProjection);let n=new Set(e.stateProjection?.allow??[]);if(e.summaryProjection.allow.some(t=>!n.has(t)))throw new w("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(o=>!["readTool","actionTool","hostTools","agentAccess"].includes(o)))throw new w("DEFINITION_UNSUPPORTED","UI legacy metadata is invalid");let n=new Set;for(let[o,r]of [["readTool",e.legacy.readTool],["actionTool",e.legacy.actionTool]])if(r!==void 0){if(ha(r,o==="readTool"),n.has(r.name))throw new w("DEFINITION_UNSUPPORTED","UI legacy tool names collide");n.add(r.name);}let t=e.legacy.hostTools;if(t!==void 0){if(!t||typeof t!="object"||Array.isArray(t))throw new w("DEFINITION_UNSUPPORTED","UI legacy host tools are invalid");let o={"doc.open":"crewx_app_html_viewer_open","pty.connect":"crewx_app_terminal_connect"};for(let[r,s]of Object.entries(t)){if(!Object.hasOwn(o,r)||o[r]!==s||typeof s!="string"||!/^[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(s)||n.has(s))throw new w("DEFINITION_UNSUPPORTED","UI legacy host tools are invalid");n.add(s);}}let i=e.legacy.agentAccess;if(i!==void 0&&(!i||typeof i!="object"||Array.isArray(i)||Object.entries(i).some(([o,r])=>!o||!Object.hasOwn(e.actions,o)||r!=="allowed"&&r!=="denied")))throw new w("DEFINITION_UNSUPPORTED","UI legacy agent access is invalid");if(e.legacy.actionTool!==void 0&&(!i||Object.keys(i).length===0))throw new w("DEFINITION_UNSUPPORTED","UI legacy action tool requires its complete agent access map")}if(e.downloads!==void 0&&e.downloads!==true)throw new w("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=>tn(t,i))))throw new w("DEFINITION_UNSUPPORTED","UI definition dataPaths are invalid")}}function ha(e,n){if(!e||typeof e!="object"||Array.isArray(e))throw new w("DEFINITION_UNSUPPORTED","UI legacy tool metadata is invalid");let t=e,i=["name","description","inputSchema","textFallback","visibility"],o=Object.hasOwn(t,"fixedResult");if(Object.keys(t).some(r=>!i.includes(r)&&!(n&&r==="fixedResult"))||i.some(r=>!Object.hasOwn(t,r))||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(r=>r!=="model"&&r!=="app")||new Set(t.visibility).size!==t.visibility.length)throw new w("DEFINITION_UNSUPPORTED","UI legacy tool metadata is invalid");try{let r=Ie(t.inputSchema);if(r.type!==void 0&&r.type!=="object")throw new Error("schema type");if(o){if(!n)throw new Error("fixed result location");let s=t.fixedResult;if(!s||typeof s!="object"||Array.isArray(s))throw new Error("fixed result");let a=s;if(Object.keys(a).sort().join(",")!=="argsPolicy,structuredContent"||a.argsPolicy!=="empty-only"&&a.argsPolicy!=="ignore"||!a.structuredContent||typeof a.structuredContent!="object"||Array.isArray(a.structuredContent))throw new Error("fixed result");let c=Ie(a.structuredContent);if(Ct(on(c))>4*1024)throw new Error("fixed result size")}}catch{throw new w("DEFINITION_UNSUPPORTED","UI legacy tool metadata is not projection-safe")}}function Gt(e){if(!Array.isArray(e.allow)||e.allow.some(n=>!/^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)*$/.test(n)))throw new w("DEFINITION_UNSUPPORTED","UI projection policy is invalid")}function _a(e){return e.length>0&&e.length<=128&&e!=="*"&&e!=="all"&&!/[/*]/.test(e)}var ma,We=j(()=>{m();Ce();Hn();Ht();zt();$t();ma=/^[0-9a-f]{64}$/;});var $,Ue,Wt=j(()=>{m();$="dist/tools.json",Ue="dist/main.mjs";});var Me,Qi,ie,sn=j(()=>{m();Me="view.call",Qi="crewxImage",ie="window";});function eo(e){if(!Array.isArray(e)||e.length===0)return false;let n=new Set;for(let t of e){if(!Ea.some(i=>i===t)||n.has(t))return false;n.add(t);}return true}var Ea,no=j(()=>{m();Ea=["CREWX_APP_INSTANCE_ID","CREWX_THREAD_ID"];});function J(e){throw new Kt(e)}function Ca(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 Ua(e,n){let t=Object.getOwnPropertyDescriptor(e,n);return (!t||!("value"in t))&&J("CSP_ORIGIN_INVALID"),t.value}function Zn(e,n){if(!Object.prototype.hasOwnProperty.call(e,n))return [];let t=Ua(e,n);Array.isArray(t)||J("CSP_ORIGIN_INVALID"),Reflect.ownKeys(t).some(r=>typeof r!="string"||r!=="length"&&!/^(?:0|[1-9][0-9]*)$/.test(r))&&J("CSP_ORIGIN_INVALID");let o=[];for(let r=0;r<t.length;r+=1)(!Object.prototype.hasOwnProperty.call(t,r)||typeof t[r]!="string")&&J("CSP_ORIGIN_INVALID"),o.push(t[r]);return Object.keys(t).length!==t.length&&J("CSP_ORIGIN_INVALID"),o}function ka(e){let n;try{n=JSON.stringify(e);}catch{J("CSP_ORIGIN_INVALID");}return n===void 0&&J("CSP_ORIGIN_INVALID"),new TextEncoder().encode(n).byteLength}function oo(e,n){/\s|\\/u.test(e)&&J("CSP_ORIGIN_INVALID");let t=Ma.exec(e);t||J("CSP_ORIGIN_INVALID");let i=t[1].toLowerCase(),o=t[2];(o.includes("@")||o.includes("%")||o.includes("*"))&&J("CSP_ORIGIN_INVALID"),(o.startsWith("[")?La:Oa).test(o)||J("CSP_ORIGIN_INVALID"),i==="wss"&&n!=="connectDomains"&&J("CSP_ORIGIN_INVALID");let s;try{s=new URL(e);}catch{J("CSP_ORIGIN_INVALID");}(s.protocol!==`${i}:`||s.username!==""||s.password!==""||s.search!==""||s.hash!=="")&&J("CSP_ORIGIN_INVALID");let a=s.hostname.toLowerCase();if((!a||a.includes("%"))&&J("CSP_ORIGIN_INVALID"),!a.startsWith("[")){let d=a.endsWith(".")?a.slice(0,-1):a;(d.length===0||d.length>253)&&J("CSP_ORIGIN_INVALID"),d.split(".").some(p=>p.length>63||!Ra.test(p))&&J("CSP_ORIGIN_INVALID");}let c=s.origin;return (c==="null"||!c.startsWith(`${i}://`))&&J("CSP_ORIGIN_INVALID"),{origin:c,hostname:a}}function xa(e){let n=e.split(".").map(Number);return ((n[0]*256+n[1])*256+n[2])*256+n[3]}function ro(e,n,t){let i=4294967295<<32-t>>>0;return (e&i)===(n&i)}function co(e){let n=xa(e);return ro(n,3221225472,24)?n!==3221225481&&n!==3221225482:wa.some(([t,i])=>ro(n,t,i))}function va(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((r,s)=>r<<16n|BigInt(Number.parseInt(s,16)),0n)}function ja(e){let n=va(e),t=Number(n>>112n),i=Number(n>>96n&0xffffn);if(n>>32n===0xffffn){let o=Number(n&0xffffffffn);return co([o>>>24&255,o>>>16&255,o>>>8&255,o&255].join("."))}return t<8192||t>16383||t===8193&&i<=511||t===8193&&i===3512||t===8194||t===16383&&i<=4095}function Fa(e,n){let t=e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e,i=net.isIP(t);if(i===4)return co(t);if(i===6)return ja(t);let o=e.toLowerCase().replace(/\.$/,"");return !o||!o.includes(".")||n.has(o)?true:Sa.some(r=>o===r||o.endsWith(`.${r}`))}function so(e){return Object.freeze([...new Set(e.map(n=>n.origin))].sort())}function ao(e){return JSON.stringify({baseUriDomains:[],connectDomains:e.connectDomains,declared:e.declared,frameDomains:e.frameDomains,resourceDomains:[]})}function po(e,n={}){if(e===void 0){let y=ao({declared:false,connectDomains:[],frameDomains:[]});return Object.freeze({declared:false,connectDomains:Object.freeze([]),frameDomains:Object.freeze([]),resourceDomains:Object.freeze([]),baseUriDomains:Object.freeze([]),cspHash:zi.createHash("sha256").update(y,"utf8").digest("hex")})}Ca(e)||J("CSP_ORIGIN_INVALID");let t=Reflect.ownKeys(e);t.some(y=>typeof y!="string")&&J("CSP_ORIGIN_INVALID"),t.some(y=>!Da.has(y))&&J("CSP_AXIS_UNKNOWN");let i=Zn(e,"connectDomains"),o=Zn(e,"frameDomains"),r=Zn(e,"resourceDomains"),s=Zn(e,"baseUriDomains");(r.length>0||s.length>0)&&J("CSP_AXIS_UNSUPPORTED"),(ka(e)>ba||i.length>io||o.length>io||i.length+o.length>Pa||[...i,...o].some(y=>new TextEncoder().encode(y).byteLength>Na))&&J("CSP_LIMIT_EXCEEDED");let c=i.map(y=>oo(y,"connectDomains")),d=o.map(y=>oo(y,"frameDomains")),l=new Set((n.runtimeHostnames??[]).map(y=>y.toLowerCase().replace(/\.$/,"")));[...c,...d].some(y=>Fa(y.hostname,l))&&J("CSP_ORIGIN_FORBIDDEN");let p={declared:true,connectDomains:so(c),frameDomains:so(d)},f=ao(p);return Object.freeze({...p,resourceDomains:Object.freeze([]),baseUriDomains:Object.freeze([]),cspHash:zi.createHash("sha256").update(f,"utf8").digest("hex")})}var ba,io,Pa,Na,Da,Sa,Ma,La,Oa,Ra,wa,Kt,lo=j(()=>{m();ba=4096,io=16,Pa=32,Na=512,Da=new Set(["connectDomains","frameDomains","resourceDomains","baseUriDomains"]),Sa=["localhost","local","internal","home.arpa","test","example","invalid","onion","lan","corp","home","intranet","private","localdomain"],Ma=/^(https|wss):\/\/([^/?#]+)$/i,La=/^\[[^\]]+\](?::[0-9]+)?$/,Oa=/^[^:\[\]]+(?::[0-9]+)?$/,Ra=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/,wa=[[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]],Kt=class extends Error{constructor(t){super(t);this.code=t;}code;name="UiPluginCspNormalizationError"};});function En(e,n){return n===void 0||n===""?e:e===""?n:n.startsWith("[")?`${e}${n}`:`${e}.${n}`}function u(e,n=e,t,i){throw new ce(e,n,t,i)}function z(e,n){try{return n()}catch(t){throw t instanceof ce?t.withPathPrefix(e):t}}function G(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 R(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function hc(e,n){let t={};for(let[i,o]of Object.entries(e))n.includes(i)||(t[i]=o);return t}function K(e,n,t=[]){let i=new Set([...n,...t]),o=Object.keys(e).find(s=>!i.has(s));o!==void 0&&u("MANIFEST_INVALID","MANIFEST_INVALID",o,"unknown-key");let r=n.find(s=>!R(e,s));r!==void 0&&u("MANIFEST_INVALID","MANIFEST_INVALID",r,"missing-key");}function tt(e,n=false,t=false,i=false){return za.test(e)||!i&&Ga.test(e)||$a.test(e)||t&&uo.test(e)||Ja.test(e)&&!(n&&/^\s*data:/i.test(e)&&!uo.test(e))}function nt(e,n=new Set,t=0,i=false,o=false,r=""){if(typeof e=="string"){tt(e,i,o)&&u("UNSAFE_VALUE","UNSAFE_VALUE",r,"unsafe-value");return}if(!(e===null||typeof e!="object")){(t>8||n.has(e))&&u("MANIFEST_INVALID","MANIFEST_INVALID",r),n.add(e);try{if(Array.isArray(e)){e.forEach((s,a)=>nt(s,n,t+1,!1,!1,En(r,`[${a}]`)));return}G(e)||u("MANIFEST_INVALID","MANIFEST_INVALID",r);for(let[s,a]of Object.entries(e))nt(a,n,t+1,i&&t===0&&(s==="name"||s==="description"),o,En(r,s));}finally{n.delete(e);}}}function Le(e,n){let t=e[n];return typeof t!="string"&&u("MANIFEST_INVALID"),t}function _e(e,n,t){let i=e[n];return (!Number.isSafeInteger(i)||i<t)&&u("MANIFEST_INVALID"),i}function Xt(e){return Ha.test(e)||u("MANIFEST_INVALID"),e}function an(e){return Ba.test(e)||u("TOKEN_INVALID"),e}function _c(e){return Do.test(e)||u("MANIFEST_INVALID"),e}function Ec(e){G(e)||u("MANIFEST_INVALID");let n={};for(let[t,i]of Object.entries(e)){let o=_c(t);G(i)||u("MANIFEST_INVALID");let r=i.type;if(r==="text"){K(i,["type","maxLength"]),n[o]={type:r,maxLength:_e(i,"maxLength",1)};continue}if(r==="text-list"){K(i,["type","max","itemMaxLength"]),n[o]={type:r,max:_e(i,"max",0),itemMaxLength:_e(i,"itemMaxLength",1)};continue}if(r==="step-list"){K(i,["type","min","max","labelMaxLength","detailMaxLength"]);let s=_e(i,"min",0),a=_e(i,"max",1);s>a&&u("MANIFEST_INVALID"),n[o]={type:r,min:s,max:a,labelMaxLength:_e(i,"labelMaxLength",1),detailMaxLength:_e(i,"detailMaxLength",1)};continue}typeof r=="string"&&u("SCHEMA_TYPE_UNSUPPORTED"),u("MANIFEST_INVALID");}return n}function Tc(e,n,t){let i=e[n];(!i||i.type!==t)&&u("MANIFEST_INVALID");}function Qn(e,n,t){let i=Le(e,"field");return Do.test(i)||u("MANIFEST_INVALID"),Tc(n,i,t),i}function bc(e,n){G(e)||u("MANIFEST_INVALID");let t=e.primitive;switch(typeof t!="string"&&u("MANIFEST_INVALID"),mc.includes(t)||u("PRIMITIVE_UNKNOWN"),t){case "card-shell":return K(e,["primitive"]),{primitive:t};case "meta-banner":return K(e,["primitive","badgeToken","noticeToken"]),{primitive:t,badgeToken:an(Le(e,"badgeToken")),noticeToken:an(Le(e,"noticeToken"))};case "heading":return K(e,["primitive","field"]),{primitive:t,field:Qn(e,n,"text")};case "labeled-text":return K(e,["primitive","titleToken","field","variant"]),e.variant!=="callout"&&u("MANIFEST_INVALID"),{primitive:t,titleToken:an(Le(e,"titleToken")),field:Qn(e,n,"text"),variant:"callout"};case "step-flow":return K(e,["primitive","titleToken","field"]),{primitive:t,titleToken:an(Le(e,"titleToken")),field:Qn(e,n,"step-list")};case "text-list":{K(e,["primitive","titleToken","field"],["emptyToken","hideWhenEmpty"]);let i={primitive:t,titleToken:an(Le(e,"titleToken")),field:Qn(e,n,"text-list")};return R(e,"emptyToken")&&(i.emptyToken=an(Le(e,"emptyToken"))),R(e,"hideWhenEmpty")&&(typeof e.hideWhenEmpty!="boolean"&&u("MANIFEST_INVALID"),i.hideWhenEmpty=e.hideWhenEmpty),i}}return u("MANIFEST_INVALID")}function Pc(e,n){return Array.isArray(e)||u("MANIFEST_INVALID"),e.map(t=>bc(t,n))}function Y(e="v2 manifest exceeds a contract limit",n,t){return u("LIMIT_EXCEEDED",e,n,t)}function me(e="initial state is not projection-safe"){return u("INITIAL_STATE_INVALID",e)}function fo(e,n){return (typeof e!="string"||e.length===0||e.length>4096||e.trim().length===0||uc.test(e)||fc.test(e))&&u("MANIFEST_INVALID",`${n} is invalid`),(tt(e,true,true)||Wa.test(e)||Ka.test(e)||Xa.test(e))&&u("UNSAFE_VALUE",`${n} contains an unsafe value`),e}function Yt(e,n){return (typeof e!="string"||!Se.test(e))&&u("MANIFEST_INVALID",`${n} is invalid`),e}function Nc(e){return (typeof e!="string"||!kt.test(e)||e==="*"||e==="all")&&u("MANIFEST_INVALID","action capability is invalid"),e}function So(e){return (typeof e!="string"||!lc.test(e))&&u("MANIFEST_INVALID","resource hash is invalid"),e}function qt(e,n=new Set,t=0,i=""){if(typeof e=="string"){e.length>4096&&Y("v2 manifest string is too long",i,"string-too-long");return}if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){Number.isFinite(e)||u("MANIFEST_INVALID","v2 manifest contains a non-finite number",i,"non-finite-number");return}(e===void 0||typeof e=="function"||typeof e=="bigint")&&u("MANIFEST_INVALID","v2 manifest contains a non-JSON value",i,"non-json-value"),typeof e!="object"&&u("MANIFEST_INVALID","MANIFEST_INVALID",i),t>8&&Y("v2 manifest nesting is too deep",i,"too-deep"),n.has(e)&&u("MANIFEST_INVALID","v2 manifest contains a cycle",i,"cycle"),n.add(e);try{if(Array.isArray(e)){e.length>128&&Y("v2 manifest array is too long",i,"array-too-long"),e.forEach((o,r)=>qt(o,n,t+1,En(i,`[${r}]`)));return}G(e)||u("MANIFEST_INVALID","v2 manifest contains a non-plain object",i,"non-plain-object");for(let[o,r]of Object.entries(e))qt(r,n,t+1,En(i,o));}finally{n.delete(e);}}}function Mo(e){return (typeof e!="string"||e.length>4096||!hn.test(e))&&(typeof e=="string"&&e.length>4096&&Y("projection path is too long"),u("MANIFEST_INVALID","projection paths must be canonical exact paths")),e.split(".").some(t=>rn(t)||t===Qi)&&u("MANIFEST_INVALID","projection paths cannot address reserved state keys"),e}function Zt(e){G(e)||u("MANIFEST_INVALID","projection policy must be an object"),K(e,["allow"]),Array.isArray(e.allow)||u("MANIFEST_INVALID","projection allow must be an array"),e.allow.length>128&&Y("projection allowlist is too long");let n=[],t=new Set;for(let i of e.allow){let o=Mo(i);t.has(o)&&u("MANIFEST_INVALID","projection allowlist contains a duplicate path"),t.add(o),n.push(o);}return {allow:n}}function Dc(e,n){if(e===void 0)return;Array.isArray(e)||u("MANIFEST_INVALID","dataPaths must be an array"),e.length>yc&&Y("dataPaths exceed the v2 limit");let t=[],i=new Set;for(let o of e){let r=Mo(o);i.has(r)&&u("MANIFEST_INVALID","dataPaths contain a duplicate path"),n.some(s=>tn(r,s))||u("MANIFEST_INVALID","dataPaths must be projection-allowed"),i.add(r),t.push(r);}return t}function Sc(e){Array.isArray(e)||u("MANIFEST_INVALID","deviceFeatures must be an array",void 0,"array"),e.length>Ac&&u("MANIFEST_INVALID","deviceFeatures allow at most 16 names",void 0,"too-many-items");let n=[],t=new Set;for(let[i,o]of e.entries()){let r=`[${i}]`;typeof o!="string"&&u("MANIFEST_INVALID","a device feature name must be a string",r,"string"),o.length===0&&u("MANIFEST_INVALID","a device feature name must not be empty",r,"empty"),o.length>Ic&&u("MANIFEST_INVALID","a device feature name is at most 32 characters",r,"too-long"),gc.test(o)||u("MANIFEST_INVALID","a device feature name starts with a lowercase letter and holds only letters and digits",r,"format"),t.has(o)&&u("MANIFEST_INVALID","deviceFeatures contain a duplicate name",r,"duplicate-item"),t.add(o),n.push(o);}return n}function Mc(e){if(e!==false)return e!==true&&u("MANIFEST_INVALID","downloads must be true or false",void 0,"boolean"),true}function Lc(e){return typeof e!="boolean"&&u("MANIFEST_INVALID","desktopOnly must be true or false",void 0,"boolean"),e}function Oc(e){return (!G(e)||e.view!==true||Object.keys(e).some(n=>n!=="view"&&n!=="entry"))&&u("MANIFEST_INVALID",'share must be { "view": true } or { "view": true, "entry": "<path>" }',void 0,"share-shape"),R(e,"entry")?{view:true,entry:wc(e.entry)}:{view:true}}function wc(e){typeof e!="string"&&u("MANIFEST_INVALID","share.entry must be a string","entry","entry-shape");let n=(i,o)=>u("MANIFEST_INVALID",`share.entry ${o}`,"entry",i);e.length===0&&n("empty","must not be empty"),e.length>yo&&n("too-long",`must be at most ${yo} characters`),e.startsWith("/")&&n("absolute","must be relative to the App folder");let t=e.split("/");t.length>Ao&&n("too-many-segments",`must have at most ${Ao} 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'),Rc.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 Cc(e){return (!G(e)||Object.keys(e).length!==1||typeof e.root!="string")&&u("MANIFEST_INVALID",'files must be exactly { "root": "<workspace folder>" }',void 0,"files-shape"),{root:jc(e.root)}}function jc(e){let n=e.normalize("NFC"),t=(r,s)=>u("MANIFEST_INVALID",`files.root ${s}`,"root",r);n.length===0&&t("empty","must not be empty"),vc.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>Io&&t("too-long",`must be at most ${Io} characters`);let i=n.split("/"),o=i[0].toLowerCase().replace(/[. ]+$/,"");xc.includes(o)&&t("reserved-folder","must not start in an App code folder or a tool folder"),i.length<Uc&&t("too-shallow","must name a folder inside a top-level folder, such as docs/trips"),i.length>go&&t("too-many-segments",`must have at most ${go} segments`);for(let r of i)r.length===0&&t("empty-segment","must not contain an empty segment"),(r==="."||r==="..")&&t("dot-segment",'must not contain "." or ".." segments'),Array.from(r).length>mo&&t("segment-too-long",`segments must be at most ${mo} characters`),kc.test(r)||t("segment-shape",'segments must start with a letter or digit and contain only letters, digits, combining marks, "_" or "-"');return n}function cn(e,n,t=Number.MAX_SAFE_INTEGER){return (!Number.isSafeInteger(e)||e<0||e>t)&&u("MANIFEST_INVALID",`${n} is invalid`),e}function ho(e,n){return (typeof e!="number"||!Number.isFinite(e))&&u("MANIFEST_INVALID",`${n} is invalid`),e}function Qt(e,n=0,t=new Set){if(typeof e=="string")return (e.length>4096||tt(e))&&u("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)||u("MANIFEST_INVALID","schema enum contains a non-finite number"),e;(n>8||typeof e!="object"||e===void 0)&&Y("schema enum is too deep"),t.has(e)&&u("MANIFEST_INVALID","schema enum contains a cycle"),t.add(e);try{if(Array.isArray(e))return e.length>128&&Y("schema enum array is too long"),e.map(o=>Qt(o,n+1,t));G(e)||u("MANIFEST_INVALID","schema enum contains a non-plain object");let i={};for(let[o,r]of Object.entries(e))rn(o)&&u("MANIFEST_INVALID","schema enum contains a reserved key"),i[o]=Qt(r,n+1,t);return i}finally{t.delete(e);}}function Fc(e,n){if(e===void 0)return;Array.isArray(e)||u("MANIFEST_INVALID","schema required must be an array"),e.length>64&&Y("schema required list is too long");let t=[],i=new Set;for(let o of e)(typeof o!="string"||!hn.test(o))&&u("MANIFEST_INVALID","schema required contains an invalid key"),o.length>4096&&Y("schema required key is too long"),i.has(o)&&u("MANIFEST_INVALID","schema required contains a duplicate key"),n&&!Object.prototype.hasOwnProperty.call(n,o)&&u("MANIFEST_INVALID","schema required references an undeclared property"),i.add(o),t.push(o);return t}function Vc(e,n){let t=n?hn:$n;return e.length>4096&&Y("schema property name is too long"),(!t.test(e)||e.split(".").some(i=>rn(i)))&&u("MANIFEST_INVALID","schema property name is invalid"),e}function ei(e,n=0,t=false){G(e)||u("MANIFEST_INVALID","action inputSchema must be an object"),n>8&&Y("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"&&u("SCHEMA_TYPE_UNSUPPORTED","action inputSchema type is unsupported"),u("MANIFEST_INVALID","action inputSchema type is required"));let o=["type","enum"];i==="string"&&o.push("minLength","maxLength"),i==="array"&&o.push("minItems","maxItems","items"),i==="object"&&o.push("minProperties","maxProperties","properties","required","additionalProperties"),(i==="number"||i==="integer")&&o.push("minimum","maximum"),K(e,["type"],o.filter(a=>a!=="type"));let r={type:i};if(R(e,"enum")&&(Array.isArray(e.enum)||u("MANIFEST_INVALID","schema enum must be an array"),e.enum.length>128&&Y("schema enum is too long"),r.enum=e.enum.map(a=>Qt(a))),i==="string"&&(R(e,"minLength")&&(r.minLength=cn(e.minLength,"schema minLength",4096)),R(e,"maxLength")&&(r.maxLength=cn(e.maxLength,"schema maxLength",4096)),r.minLength!==void 0&&r.maxLength!==void 0&&r.minLength>r.maxLength&&u("MANIFEST_INVALID","schema string length bounds are inverted")),(i==="number"||i==="integer")&&(R(e,"minimum")&&(r.minimum=ho(e.minimum,"schema minimum")),R(e,"maximum")&&(r.maximum=ho(e.maximum,"schema maximum")),r.minimum!==void 0&&r.maximum!==void 0&&r.minimum>r.maximum&&u("MANIFEST_INVALID","schema numeric bounds are inverted")),i==="array"&&(R(e,"minItems")&&(r.minItems=cn(e.minItems,"schema minItems",128)),R(e,"maxItems")&&(r.maxItems=cn(e.maxItems,"schema maxItems",128)),r.minItems!==void 0&&r.maxItems!==void 0&&r.minItems>r.maxItems&&u("MANIFEST_INVALID","schema array length bounds are inverted"),R(e,"items")&&(r.items=ei(e.items,n+1,false))),i==="object"){let a;if(R(e,"properties")){G(e.properties)||u("MANIFEST_INVALID","schema properties must be an object");let d=Object.entries(e.properties);d.length>64&&Y("schema properties are too many"),a={};for(let[l,p]of d){let f=Vc(l,t);a[f]=ei(p,n+1,false);}r.properties=a;}R(e,"minProperties")&&(r.minProperties=cn(e.minProperties,"schema minProperties",64)),R(e,"maxProperties")&&(r.maxProperties=cn(e.maxProperties,"schema maxProperties",64)),r.minProperties!==void 0&&r.maxProperties!==void 0&&r.minProperties>r.maxProperties&&u("MANIFEST_INVALID","schema object property bounds are inverted");let c=Fc(e.required,a);c!==void 0&&(r.required=c),R(e,"additionalProperties")&&(e.additionalProperties!==false&&u("MANIFEST_INVALID","schema additionalProperties must be false"),r.additionalProperties=false);}let s=JSON.stringify(r);return (s===void 0||Buffer.byteLength(s,"utf8")>2097152)&&Y("action inputSchema subtree is too large"),r}function Bc(e){let n=ei(e,0,true);return (n.type!=="object"||!n.properties)&&u("MANIFEST_INVALID","action inputSchema must declare object properties"),n}function Hc(e){if(G(e)||u("MANIFEST_INVALID","action backend must be an object"),e.type==="core"){K(e,rc);let n=e.handler;return (typeof n!="string"||!xt.test(n))&&u("MANIFEST_INVALID","core backend handler is invalid"),{type:"core",handler:n}}if(e.type==="skill"&&R(e,"entry"))return K(e,cc),e.entry!==Ue&&u("MANIFEST_INVALID",`skill backend entry must be ${Ue}`),{type:"skill",entry:Ue};if(e.type==="skill"){K(e,sc,ac),(!Array.isArray(e.command)||e.command.length===0||e.command.length>16)&&u("MANIFEST_INVALID","skill backend command is invalid");let n=[];for(let i of e.command)(typeof i!="string"||i.length===0||i.length>256||!vt.test(i))&&u("MANIFEST_INVALID","skill backend command token is invalid"),n.push(i);let t=R(e,"env")?Kc(e.env):void 0;return {type:"skill",command:n,...t===void 0?{}:{env:t}}}u("MANIFEST_INVALID","action backend type is unsupported");}function zc(e){G(e)||u("MANIFEST_INVALID","action must be an object"),K(e,Qa,ec),R(e,"_meta")&&z("_meta",()=>Lo(e._meta));let n=z("actionId",()=>Yt(e.actionId,"actionId"));wt(n)&&u("MANIFEST_INVALID",`actionId "${n}" is not projection-safe`,"actionId");let t=z("capability",()=>Nc(e.capability)),i=e.mutation;typeof i!="boolean"&&u("MANIFEST_INVALID","action mutation must be boolean","mutation");let o=z("inputSchema",()=>Bc(e.inputSchema)),r;if(R(e,"dataInputs")){Array.isArray(e.dataInputs)||u("MANIFEST_INVALID","action dataInputs must be an array","dataInputs");let y=o.properties,g=new Set,_=[];for(let E of e.dataInputs)(typeof E!="string"||!R(y,E)||g.has(E))&&u("MANIFEST_INVALID","action dataInputs must be unique declared properties","dataInputs"),g.add(E),_.push(E);r=_;}let s=z("resultProjection",()=>Zt(e.resultProjection)),a=z("backend",()=>Hc(e.backend)),c;R(e,"content")&&((a.type!=="skill"||!Gn(e.content))&&u("MANIFEST_INVALID","action content declaration is invalid","content"),c=Xc(e.content));let d;if(R(e,"confirmation")){let y=e.confirmation;y!=="none"&&y!=="native"&&u("MANIFEST_INVALID","action confirmation is invalid","confirmation"),d=y;}let l;R(e,"schedule")&&(l=z("schedule",()=>Wc(e.schedule,{backend:a,inputSchema:o,hasContent:c!==void 0,hasDataInputs:r!==void 0,confirmation:d})));let p;R(e,"job")&&(l!==void 0&&u("MANIFEST_INVALID","an action is either the scheduled run or a job, not both","job"),p=z("job",()=>Jc(e.job,{backend:a,inputSchema:o,hasContent:c!==void 0,hasDataInputs:r!==void 0,confirmation:d})));let f;return R(e,"jobAccess")&&(p!==void 0&&u("MANIFEST_INVALID","an action is either the job or a job control, not both","jobAccess"),f=z("jobAccess",()=>Gc(e.jobAccess,{backend:a,hasContent:c!==void 0}))),{actionId:n,capability:t,mutation:i,inputSchema:o,resultProjection:s,backend:a,...c===void 0?{}:{content:c},...r===void 0?{}:{dataInputs:r},...d===void 0?{}:{confirmation:d},...l===void 0?{}:{schedule:l},...p===void 0?{}:{job:p},...f===void 0?{}:{jobAccess:f}}}function $c(e,n,t){e.backend.type!=="core"||e.backend.handler!==Me||((n??ie)!==ie&&u("MANIFEST_INVALID","view.call is only available to screen Apps",`${t}.backend.handler`),e.mutation!==false&&u("MANIFEST_INVALID","view.call must be read-only",`${t}.mutation`),e.confirmation!=="none"&&u("MANIFEST_INVALID","view.call requires confirmation none",`${t}.confirmation`),(e.content!==void 0||e.schedule!==void 0||e.job!==void 0||e.jobAccess!==void 0)&&u("MANIFEST_INVALID","view.call cannot declare content, jobs, or schedules",t),e.resultProjection===void 0&&u("MANIFEST_INVALID","view.call requires resultProjection",`${t}.resultProjection`));}function Gc(e,n){return (n.backend.type!=="skill"||!("entry"in n.backend)||n.backend.entry!==Ue)&&u("MANIFEST_INVALID","jobAccess needs a tool-mode action","jobAccess"),n.hasContent&&u("MANIFEST_INVALID","a job control action takes no content","jobAccess"),(!Array.isArray(e)||e.length===0)&&u("MANIFEST_INVALID","jobAccess must list at least one operation","jobAccess"),(new Set(e).size!==e.length||!e.every(qn))&&u("MANIFEST_INVALID","jobAccess must name each operation once: start, status or cancel","jobAccess"),Object.freeze([...e])}function Jc(e,n){(n.backend.type!=="skill"||!("entry"in n.backend)||n.backend.entry!==Ue)&&u("MANIFEST_INVALID","job needs a tool-mode action","job"),(n.hasContent||n.hasDataInputs||n.confirmation!==void 0&&n.confirmation!=="none")&&u("MANIFEST_INVALID","a job action takes no content, dataInputs or native confirmation","job"),(n.inputSchema.required??[]).length>0&&u("MANIFEST_INVALID","a job action input must accept {}","inputSchema.required"),G(e)||u("MANIFEST_INVALID","job must be an object","job"),K(e,[],ic);let t=R(e,"deadlineMs")?e.deadlineMs:Xn.default;return Yn(t)||u("MANIFEST_INVALID","job deadlineMs is invalid","job.deadlineMs"),{deadlineMs:t}}function Wc(e,n){(n.backend.type!=="skill"||!("entry"in n.backend)||n.backend.entry!==Ue)&&u("MANIFEST_INVALID","schedule needs a tool-mode action","schedule"),(n.hasContent||n.hasDataInputs||n.confirmation!==void 0&&n.confirmation!=="none")&&u("MANIFEST_INVALID","a scheduled action takes no content, dataInputs or native confirmation","schedule"),(n.inputSchema.required??[]).length>0&&u("MANIFEST_INVALID","a scheduled action input must accept {}","inputSchema.required"),G(e)||u("MANIFEST_INVALID","schedule must be an object","schedule"),K(e,nc,tc),Wn(e.everyMinutes)||u("MANIFEST_INVALID","schedule everyMinutes is invalid","schedule.everyMinutes");let t=R(e,"timeoutMs")?e.timeoutMs:Jn.default;return Kn(t)||u("MANIFEST_INVALID","schedule timeoutMs is invalid","schedule.timeoutMs"),{everyMinutes:e.everyMinutes,timeoutMs:t}}function Kc(e){return eo(e)||u("MANIFEST_INVALID","skill backend env is invalid"),Object.freeze([...e])}function Xc(e){return Object.freeze({...e.in===void 0?{}:{in:Object.freeze({...e.in})},...e.out===void 0?{}:{out:Object.freeze({...e.out})}})}function Yc(e){return G(e)||u("INITIAL_STATE_INVALID","initialState must be an object"),K(e,dc,pc),e.path!=="ui/state.json"&&u("MANIFEST_INVALID","initialState path is not fixed"),R(e,"hash")?{path:"ui/state.json",hash:So(e.hash)}:{path:"ui/state.json"}}function qc(e){let n=["wasm","terminal","htmlDocuments","appBrowser"];return (!G(e)||Object.keys(e).length===0||Object.keys(e).some(t=>!n.includes(t)||e[t]!==true))&&u("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 Zc(e,n){let t;try{t=po(e);}catch(i){let o=i!==null&&typeof i=="object"&&"code"in i&&typeof i.code=="string"?i.code:"CSP_ORIGIN_INVALID";return u("MANIFEST_INVALID",o,void 0,o.toLowerCase().replace(/_/g,"-"))}if(t.frameDomains.length>0&&u("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&&u("MANIFEST_INVALID","runtime.terminal cannot be combined with csp.connectDomains","connectDomains","terminal-with-connect-domains"),Object.freeze({connectDomains:t.connectDomains})}function Qc(e,n){nt(G(e)?hc(e,["csp","downloads","files","share"]):e,new Set,0,true,true),qt(e),G(e)||u("MANIFEST_INVALID"),K(e,qa,Za),R(e,"_meta")&&z("_meta",()=>Lo(e._meta)),e.manifestVersion!==2&&u("MANIFEST_INVALID");let t;R(e,"runtime")&&(t=z("runtime",()=>qc(e.runtime)));let i;R(e,"csp")&&(i=z("csp",()=>Zc(e.csp,t)));let o=z("pluginId",()=>Yt(e.pluginId,"pluginId")),r=z("definitionId",()=>Yt(e.definitionId,"definitionId")),s=z("version",()=>_e(e,"version",1)),a=z("name",()=>fo(e.name,"name")),c=z("description",()=>fo(e.description,"description")),d;R(e,"icon")&&((typeof e.icon!="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(e.icon))&&u("MANIFEST_INVALID","icon is invalid","icon"),d=e.icon);let l;R(e,"tone")&&((typeof e.tone!="string"||!jt.includes(e.tone))&&u("MANIFEST_INVALID","tone is invalid","tone"),l=e.tone),e.entry!=="ui/index.html"&&u("MANIFEST_INVALID","entry path is not fixed","entry","fixed-value");let p;R(e,"entryHash")&&(p=z("entryHash",()=>So(e.entryHash)));let f;R(e,"initialState")&&(f=z("initialState",()=>Yc(e.initialState)));let y;R(e,"usage")&&(e.usage!=="card"&&e.usage!=="window"&&u("MANIFEST_INVALID","usage is invalid","usage"),y=e.usage);let g;R(e,"detailPanel")&&(typeof e.detailPanel!="boolean"&&u("MANIFEST_INVALID","detailPanel is invalid","detailPanel"),g=e.detailPanel);let _;if(R(e,"displayModes")){((y??ie)!==ie||!Array.isArray(e.displayModes)||e.displayModes.length===0)&&u("MANIFEST_INVALID","displayModes are only valid for window Apps","displayModes");let v=new Set(["inline","floating","focused"]);(new Set(e.displayModes).size!==e.displayModes.length||e.displayModes.some(le=>typeof le!="string"||!v.has(le)))&&u("MANIFEST_INVALID","displayModes are invalid","displayModes"),_=e.displayModes;}(y??ie)===ie&&g!==void 0&&u("MANIFEST_INVALID","detailPanel is card-only","detailPanel");let E=n.mode??"local";E!=="local"&&E!=="installed"&&E!=="published"&&u("MANIFEST_INVALID","manifest mode is invalid"),E!=="local"&&p===void 0&&u("MANIFEST_INVALID","installed manifests require entryHash","entryHash","required-when-installed"),E!=="local"&&f!==void 0&&f.hash===void 0&&u("MANIFEST_INVALID","installed manifests require initialState.hash","initialState.hash","required-when-installed"),(!Array.isArray(e.surfaces)||e.surfaces.length===0)&&u("MANIFEST_INVALID","surfaces are invalid","surfaces"),e.surfaces.length>2&&Y("surfaces exceed the v2 limit","surfaces","too-many-items");let U=[],k=new Set;for(let v of e.surfaces)(typeof v!="string"||!Ft.includes(v))&&u("MANIFEST_INVALID","surface is unsupported","surfaces"),k.has(v)&&u("MANIFEST_INVALID","surfaces contain a duplicate","surfaces","duplicate-item"),k.add(v),U.push(v);G(e.size)||u("MANIFEST_INVALID","size must be an object","size"),z("size",()=>K(e.size,["height"]));let T=z("size",()=>_e(e.size,"height",1));T>720&&Y("size.height exceeds the v2 limit","size.height","too-large");let C=z("stateProjection",()=>Zt(e.stateProjection)),B=e.summaryProjection===void 0?void 0:z("summaryProjection",()=>Zt(e.summaryProjection));B!==void 0&&B.allow.some(v=>!C.allow.includes(v))&&u("MANIFEST_INVALID","summaryProjection must be a subset of stateProjection.allow","summaryProjection");let N=z("dataPaths",()=>Dc(e.dataPaths,C.allow)),D=R(e,"deviceFeatures")?z("deviceFeatures",()=>Sc(e.deviceFeatures)):void 0,L=R(e,"downloads")?z("downloads",()=>Mc(e.downloads)):void 0,I=R(e,"share")?z("share",()=>Oc(e.share)):void 0,A=R(e,"files")?z("files",()=>Cc(e.files)):void 0,h=R(e,"desktopOnly")?z("desktopOnly",()=>Lc(e.desktopOnly)):void 0;Array.isArray(e.actions)||u("MANIFEST_INVALID","actions must be an array","actions"),e.actions.length>32&&Y("actions exceed the v2 limit","actions","too-many-items");let b=[],V=new Set,x=0,X=0;for(let[v,le]of e.actions.entries()){let he=`actions[${v}]`,De=z(he,()=>zc(le));if($c(De,y,he),V.has(De.actionId)&&u("MANIFEST_INVALID","actions contain a duplicate actionId",`${he}.actionId`,"duplicate-item"),De.schedule!==void 0&&(x+=1,x>qi&&u("MANIFEST_INVALID","an App declares at most one scheduled action",`${he}.schedule`,"duplicate-item")),De.job!==void 0&&(X+=1,X>Zi&&u("MANIFEST_INVALID","an App declares at most one job action",`${he}.job`,"duplicate-item")),De.backend.type==="core"&&De.backend.handler==="state.set"){De.mutation||u("MANIFEST_INVALID","state.set actions must be mutations",`${he}.mutation`);for(let Qs of Object.keys(De.inputSchema.properties))C.allow.includes(Qs)||u("MANIFEST_INVALID","state.set input paths must be projection-allowed",`${he}.inputSchema.properties`);}V.add(De.actionId),b.push(De);}return {manifestVersion:2,pluginId:o,definitionId:r,version:s,name:a,description:c,...d===void 0?{}:{icon:d},...l===void 0?{}:{tone:l},entry:"ui/index.html",...p===void 0?{}:{entryHash:p},...t===void 0?{}:{runtime:t},...i===void 0?{}:{csp:i},...f===void 0?{}:{initialState:f},...y===void 0?{}:{usage:y},...g===void 0?{}:{detailPanel:g},..._===void 0?{}:{displayModes:_},surfaces:U,size:{height:T},stateProjection:C,...B===void 0?{}:{summaryProjection:B},...N===void 0?{}:{dataPaths:N},...D===void 0?{}:{deviceFeatures:D},...L===void 0?{}:{downloads:L},...I===void 0?{}:{share:I},...A===void 0?{}:{files:A},...h===void 0?{}:{desktopOnly:h},actions:b}}function Lo(e){G(e)||u("MANIFEST_INVALID","_meta must be an object");let n=JSON.stringify(e);(n===void 0||Buffer.byteLength(n,"utf8")>oc)&&Y("_meta exceeds the 4 KiB limit",void 0,"meta-too-large");}function ed(e){let n={},t={};for(let r of e.actions){n[r.actionId]={capabilities:[r.capability],inputKeys:Object.keys(r.inputSchema.properties??{}),...r.backend.type==="core"&&r.backend.handler===Me?{mutation:r.mutation}:{},...r.dataInputs===void 0?{}:{dataInputs:r.dataInputs},resultProjection:r.resultProjection,...r.confirmation===void 0?{}:{confirmation:r.confirmation},...r.content===void 0?{}:{content:r.content},...r.schedule===void 0?{}:{schedule:r.schedule},...r.job===void 0?{}:{job:r.job},...r.jobAccess===void 0?{}:{jobAccess:r.jobAccess},...r.backend.type!=="skill"||r.backend.env===void 0?{}:{env:r.backend.env}};let s=r.backend.type==="skill"||r.backend.type==="core"&&(r.backend.handler==="state.set"||r.backend.handler===Me);t[r.actionId]={actionId:r.actionId,mutation:r.mutation,backend:r.backend,launchPolicy:s?"allowed":"denied",...s?{}:{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},o={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:o}}function ni(e,n,t,i,o,r){if(typeof e=="string"){let s=o.length>0&&r.some(a=>tn(o.join("."),a));return (e.length>4096||tt(e,false,false,s))&&me("state contains an unsafe string"),e}if(e===null||typeof e=="boolean")return e;if(typeof e=="number")return Number.isFinite(e)||me("state contains a non-finite number"),e;(e===void 0||typeof e!="object"||typeof e=="function"||typeof e=="bigint")&&me("state contains a non-JSON value"),t>8&&me("state is too deep"),n.has(e)&&me("state contains a cycle"),n.add(e);try{let s;if(Array.isArray(e))e.length>128&&me("state array is too long"),s=e.map(c=>ni(c,n,t+1,2097152,o,r));else {G(e)||me("state contains a non-plain object");let c={};for(let[d,l]of Object.entries(e))(d.length>4096||!$n.test(d)||rn(d))&&(d.length>4096&&me("state key is too long"),me("state contains a reserved or invalid key")),c[d]=ni(l,n,t+1,2097152,[...o,d],r);s=c;}let a=JSON.stringify(s);return (a===void 0||Buffer.byteLength(a,"utf8")>i)&&me("state subtree is too large"),s}finally{n.delete(e);}}function ii(e,n=[]){G(e)||me("initial state must be a JSON object");let t=ni(e,new Set,0,2097152,[],n);return (t===null||Array.isArray(t)||typeof t!="object")&&me(),t}function nd(e,n={}){nt(e),G(e)||u("MANIFEST_INVALID"),K(e,Ya),e.manifestVersion!==1&&u("MANIFEST_INVALID");let t=Xt(Le(e,"pluginId")),i=Xt(Le(e,"definitionId")),o=_e(e,"version",1),r=_e(e,"primitiveSet",1),s=n.supportedPrimitiveSet??Va;(!Number.isSafeInteger(s)||s<1)&&u("MANIFEST_INVALID"),r>s&&u("PRIMITIVE_SET_UNSUPPORTED"),G(e.activation)||u("MANIFEST_INVALID"),K(e.activation,["kind","language"]),e.activation.kind!=="fenced-code"&&u("MANIFEST_INVALID");let a=Xt(Le(e.activation,"language")),c=Ec(e.schema),d=Pc(e.layout,c);return {manifestVersion:1,pluginId:t,definitionId:i,version:o,primitiveSet:r,activation:{kind:"fenced-code",language:a},schema:c,layout:d}}function td(e,n={}){return G(e)||u("MANIFEST_INVALID"),Object.hasOwn(e,"lineage")&&u("MANIFEST_INVALID","lineage is only allowed in product bundle indexes"),e.manifestVersion===2?Qc(e,n):nd(e,n)}function Xe(e,n={}){try{return td(e,n)}catch(t){if(t instanceof ce)throw t;return u("MANIFEST_INVALID")}}function Tn(e,n={}){let t=Xe(e,n);return t.manifestVersion===2?ed(t):t}var Va,Ba,Ha,Do,za,$a,Ga,Ja,uo,Wa,Ka,Xa,Ya,qa,Za,Qa,ec,nc,tc,ic,oc,rc,sc,ac,cc,dc,pc,lc,uc,fc,yc,Ac,Ic,gc,mc,ce,yo,Ao,Rc,Io,Uc,go,mo,kc,xc,vc,oi=j(()=>{m();sn();Ce();Ht();no();Wt();zt();$t();lo();Je();Va=1,Ba=/^[a-z][a-zA-Z0-9]*(\.[a-zA-Z0-9]+)+$/,Ha=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,Do=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,za=/<\/?[A-Za-z][^>]*>/,$a=/^(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)/,Ga=/^(?:https?|file|ftp|ws|wss):\/\//i,Ja=/^\s*(?:javascript|data):/i,uo=/data:[^,\s]*,/i,Wa=/(?:https?|file|ftp|ws|wss):\/\//i,Ka=/javascript:/i,Xa=/(?:^[\s]*|[\s"'(=])(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)(?=[^\s"'<>])[^\s"'<>]*/,Ya=["manifestVersion","pluginId","definitionId","version","primitiveSet","activation","schema","layout"],qa=["manifestVersion","pluginId","definitionId","version","name","description","entry","surfaces","size","stateProjection","actions"],Za=["_meta","icon","tone","entryHash","runtime","csp","initialState","usage","detailPanel","displayModes","summaryProjection","dataPaths","focusedAiDataPaths","deviceFeatures","downloads","share","files","desktopOnly"],Qa=["actionId","capability","mutation","inputSchema","resultProjection","backend"],ec=["confirmation","dataInputs","content","schedule","job","jobAccess","_meta"],nc=["everyMinutes"],tc=["timeoutMs"],ic=["deadlineMs"],oc=4*1024,rc=["type","handler"],sc=["type","command"],ac=["env"],cc=["type","entry"],dc=["path"],pc=["hash"],lc=/^[0-9a-f]{64}$/,uc=/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/,fc=/[\r\n]/,yc=16,Ac=16,Ic=32,gc=/^[a-z][A-Za-z0-9]{0,31}$/,mc=["card-shell","meta-banner","heading","labeled-text","step-flow","text-list"],ce=class e extends Error{constructor(t,i=t,o,r){super(i);this.code=t;this.path=o;this.rule=r;}code;path;rule;name="UiPluginValidationError";withPathPrefix(t){return new e(this.code,this.message,En(t,this.path),this.rule)}};yo=200,Ao=3,Rc=/^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/;Io=200,Uc=2,go=4,mo=100,kc=/^[\p{L}\p{N}][\p{L}\p{N}\p{M}_-]*$/u,xc=[".git",".crewx","node_modules","apps","skills"],vc=/[\u0000-\u001f\u007f-\u009f\\:<>"|?*]/;});function ko(e){return typeof e=="string"&&e.length<=od&&id.test(e)}function F(e,n,t,i,o){throw new Oe(e,{path:n,rule:t,...i===void 0?{}:{message:i},...o===void 0?{}:{file:o}})}function oe(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 q(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function be(e){let n=`_meta["${Be}"]`;return e===void 0||e===""?n:e.startsWith("[")?`${n}${e}`:`${n}.${e}`}function cd(e){return e.toLowerCase().replace(/_/g,"-")}function dd(e){if(e===void 0||e==="")return "";let n=/^([^.[]+)(.*)$/.exec(e);if(!n)return be(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 be("definitionVersion");case "definitionId":return be("definitionId");default:return be(`${t}${i}`)}}function xo(e,n,t){return {path:t(e.path),rule:e.rule??cd(e.code),...e.message!==e.code?{message:e.message}:{},file:n}}function vo(e){return JSON.parse(JSON.stringify(e))}function ai(e,n,t=0,i=new Set){if(typeof e=="string"){e.length>4096&&F("LIMIT_EXCEEDED",n,"string-too-long"),(rd.test(e)||sd.test(e)||ad.test(e))&&F("UNSAFE_VALUE",n,"unsafe-value");return}if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){Number.isFinite(e)||F("MANIFEST_INVALID",n,"non-finite-number");return}typeof e!="object"&&F("MANIFEST_INVALID",n,"non-json-value"),t>8&&F("LIMIT_EXCEEDED",n,"too-deep"),i.has(e)&&F("MANIFEST_INVALID",n,"cycle"),i.add(e);try{if(Array.isArray(e)){e.length>128&&F("LIMIT_EXCEEDED",n,"array-too-long"),e.forEach((o,r)=>ai(o,`${n}[${r}]`,t+1,i));return}oe(e)||F("MANIFEST_INVALID",n,"non-plain-object");for(let[o,r]of Object.entries(e))ai(r,n===""?o:`${n}.${o}`,t+1,i);}finally{i.delete(e);}}}function Ee(e,n){return (typeof e!="string"||e.length===0)&&F("MANIFEST_INVALID",n,"string"),e}function pn(e,n){return oe(e)||F("MANIFEST_INVALID",n,"object"),e}function pd(e,n){Array.isArray(e)||F("MANIFEST_INVALID",n,"array"),e.forEach((t,i)=>Ee(t,`${n}[${i}]`));}function ld(e,n){typeof e!="boolean"&&F("MANIFEST_INVALID",n,"boolean");}function bn(e,n,t,i){for(let o of Object.keys(e))!t.includes(o)&&!i.includes(o)&&F("MANIFEST_INVALID",`${n}.${o}`,"unknown-key");for(let o of t)q(e,o)||F("MANIFEST_INVALID",`${n}.${o}`,"missing-key");}function ud(e,n){if(e!=="icon")switch(ai(n,e),e){case "long_description":case "homepage":case "documentation":case "support":case "license":Ee(n,e);return;case "author":{let t=pn(n,e);bn(t,e,["name"],["email","url"]);for(let i of Object.keys(t))Ee(t[i],`${e}.${i}`);return}case "repository":{let t=pn(n,e);bn(t,e,[],["type","url"]);for(let i of Object.keys(t))Ee(t[i],`${e}.${i}`);return}case "icons":{Array.isArray(n)||F("MANIFEST_INVALID",e,"array"),n.forEach((t,i)=>{let o=`${e}[${i}]`,r=pn(t,o);bn(r,o,["src","size"],["theme"]),Ee(r.src,`${o}.src`),Ee(r.size,`${o}.size`),q(r,"theme")&&Ee(r.theme,`${o}.theme`);});return}case "screenshots":case "keywords":case "privacy_policies":pd(n,e);return;case "tools":{Array.isArray(n)||F("MANIFEST_INVALID",e,"array"),n.forEach((t,i)=>{let o=`${e}[${i}]`,r=pn(t,o);bn(r,o,["name"],["description"]),Ee(r.name,`${o}.name`),q(r,"description")&&Ee(r.description,`${o}.description`);});return}case "prompts":{Array.isArray(n)||F("MANIFEST_INVALID",e,"array"),n.forEach((t,i)=>{let o=`${e}[${i}]`,r=pn(t,o);bn(r,o,["name","text"],["description","arguments"]),Ee(r.name,`${o}.name`),Ee(r.text,`${o}.text`);});return}case "tools_generated":case "prompts_generated":ld(n,e);return;case "localization":case "compatibility":case "user_config":pn(n,e);return;default:F("MANIFEST_INVALID",e,"unknown-key");}}function it(e){return typeof e=="string"&&Se.test(e)?e:void 0}function jo(e){return Number.isSafeInteger(e)&&e>=1?e:void 0}function fd(e){let n=it(e.name);if(n===void 0)return;let t=e._meta,i=oe(t)?t[Be]:void 0,o=oe(i)?i:{},r=q(o,"definitionId")?it(o.definitionId):n,s=q(o,"definitionVersion")?jo(o.definitionVersion):1;return {pluginId:n,...r===void 0?{}:{definitionId:r},...s===void 0?{}:{definitionVersion:s}}}function yd(e){let n=it(e.pluginId);if(n===void 0)return;let t=it(e.definitionId),i=jo(e.version);return {pluginId:n,...t===void 0?{}:{definitionId:t},...i===void 0?{}:{definitionVersion:i}}}function pi(e){try{let n=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e));if(!oe(n))return !1;let t=n._meta;return oe(t)&&q(t,Be)}catch{return false}}function Ad(e,n){if(e===pe)return n.builtinOnly===true;let t=n._meta,i=oe(t)?t[Be]:void 0;return oe(i)&&i.builtinOnly===true}function Id(e,n){q(e,"server")&&F("MANIFEST_INVALID","server","server-unsupported","phase 1 runs CrewX-owned Apps only");for(let a of Object.keys(e))ci.includes(a)||F("MANIFEST_INVALID",a,"unknown-key");for(let a of di)q(e,a)||F("MANIFEST_INVALID",a,"missing-key");e.manifest_version!==ri&&F("MANIFEST_INVALID","manifest_version","unsupported-version",`manifest_version must be "${ri}"`),ko(e.version)||F("MANIFEST_INVALID","version","semver","version must be a semver.org version such as 0.1.0");let t=e._meta;oe(t)||F("MANIFEST_INVALID","_meta","object"),q(t,Be)||F("MANIFEST_INVALID",be(),"missing-key");let i=t[Be];oe(i)||F("MANIFEST_INVALID",be(),"object");for(let a of Object.keys(i))si.includes(a)||Uo.includes(a)||F("MANIFEST_INVALID",be(a),"unknown-key");for(let a of si)a==="actions"&&n!==void 0||q(i,a)||F("MANIFEST_INVALID",be(a),"missing-key");if(n!==void 0&&q(i,"actions")&&F("MANIFEST_INVALID",be("actions"),"two-truths",`actions are declared in both ${W} and ${$}; a server.ts App keeps them in the tools file only`),gd(i.actions),q(i,"definitionVersion")){let a=i.definitionVersion;(!Number.isSafeInteger(a)||a<1)&&F("MANIFEST_INVALID",be("definitionVersion"),"positive-integer");}let o={};for(let a of Co)q(e,a)&&(ud(a,e[a]),o[a]=vo(e[a]));let r={};for(let[a,c]of Object.entries(t))a!==Be&&(r[a]=c);let s={manifestVersion:2,pluginId:e.name,definitionId:q(i,"definitionId")?i.definitionId:e.name,version:q(i,"definitionVersion")?i.definitionVersion:1,name:e.display_name,description:e.description};for(let[a,c]of Object.entries(i))a==="definitionId"||a==="definitionVersion"||(s[a]=c);return n!==void 0&&(s.actions=n.map(a=>{let{viewCall:c,...d}=a;return {...d,backend:c===true?{type:"core",handler:"view.call"}:{type:"skill",entry:Ue}}})),Object.keys(r).length>0&&(s._meta=r),{v2Input:s,...Object.keys(r).length>0?{vendorMeta:r}:{},passthrough:o}}function gd(e){Array.isArray(e)&&e.forEach((n,t)=>{let i=oe(n)?n.backend:void 0;oe(i)&&q(i,"entry")&&F("MANIFEST_INVALID",be(`actions[${t}].backend.entry`),"entry-not-authorable",`an action in ${W} cannot name an entry; a server.ts App declares its actions in ${$}`);});}function md(e,n,t){oe(e)||F("MANIFEST_INVALID","","not-object","manifest.json must be a JSON object",W);let i;try{i=Id(e,t);}catch(s){throw s instanceof Oe?new Oe(s.code,{...s.reason,file:W}):s}let o;try{let s=Xe(i.v2Input,{mode:n.mode??"local"});s.manifestVersion!==2&&F("MANIFEST_INVALID","","v2-required"),o=s;}catch(s){throw s instanceof ce?new Oe(s.code,xo(s,W,dd)):s}let r=e.tools;if(Array.isArray(r)){let s=new Set(o.actions.map(a=>a.actionId));r.forEach((a,c)=>{let d=a.name;if(!s.has(d))throw new Oe("MANIFEST_INVALID",{path:`tools[${c}].name`,rule:"tool-not-action",message:"every tools[].name must be an action id",file:W})});}return {file:W,manifest:o,v2Input:i.v2Input,releaseVersion:e.version,...Object.keys(i.passthrough).length>0?{mcpb:i.passthrough}:{}}}function hd(e,n){try{let t=Xe(e,{mode:n.mode??"local"});if(t.manifestVersion!==2)throw new Oe("MANIFEST_INVALID",{path:"manifestVersion",rule:"v2-required",message:"a workspace App requires manifestVersion 2",file:pe});return {file:pe,manifest:t,v2Input:e}}catch(t){throw t instanceof ce?new Oe(t.code,xo(t,pe,i=>i??"")):t}}function ln(e){return ue(Tn(e).definition)}function Ro(e){let{entryHash:n,initialState:t,...i}=e,o={...i};return t!==void 0&&(o.initialState={path:t.path}),vo(o)}function _d(e,n){let t=Ro(e),i=Ro(n);return [...new Set([...Object.keys(t),...Object.keys(i)])].sort().filter(r=>te(t[r]??null)!==te(i[r]??null))}function Ed(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 Td(e,n){let t=_d(e,n),i=Ed(e,n),o="";try{let r=ln(e),s=ln(n);i=i||r!==s,o=` (definition hash ${r.slice(0,12)} vs ${s.slice(0,12)})`;}catch{i=true;}t.length===0&&!i||F("MANIFEST_DUAL_MISMATCH","","dual-manifest-mismatch",`${W} and ${pe} normalize to different definitions${o}`+(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:$},files:[]}}function wo(e){return {...Te("","tools-needs-manifest-json","MANIFEST_INVALID",`${$} is read with ${W} only`),files:e}}function bd(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(!oe(t))return {failure:Te("","not-object","MANIFEST_INVALID",`${$} must be a JSON object`)};for(let o of Object.keys(t))if(o!=="schemaVersion"&&o!=="actions")return {failure:Te(o,"unknown-key")};for(let o of ["schemaVersion","actions"])if(!q(t,o))return {failure:Te(o,"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[o,r]of i.entries()){if(!oe(r))return {failure:Te(`actions[${o}]`,"object")};if(q(r,"backend"))return {failure:Te(`actions[${o}].backend`,"tools-backend","MANIFEST_INVALID",`an action in ${$} cannot carry a backend`)};if(q(r,"viewCall")&&r.viewCall!==true)return {failure:Te(`actions[${o}].viewCall`,"view-call-marker","MANIFEST_INVALID","viewCall must be the exact marker true")}}return {actions:i}}function Pd(e,n){let t=n.maxBytes??262144,i=[],o=new TextDecoder("utf-8",{fatal:true});for(let r of Q){let s=e[r];if(s===void 0)continue;if(s.byteLength>t)return {parsed:i,failure:{code:"LIMIT_EXCEEDED",reason:{path:"",rule:"file-too-large",file:r},files:[r]}};let a;try{a=JSON.parse(o.decode(s));}catch{return {parsed:i,failure:{code:"MANIFEST_INVALID",reason:{path:"",rule:"invalid-json",file:r},files:[r]}}}if(!oe(a))return {parsed:i,failure:{code:"MANIFEST_INVALID",reason:{path:"",rule:"not-object",message:`${r} must be a JSON object`,file:r},files:[r]}};i.push({file:r,raw:a});}return {parsed:i}}function ze(e,n={}){let{parsed:t,failure:i}=Pd(e,n),o=Q.filter(y=>e[y]!==void 0);if(i!==void 0)return {ok:false,rejection:i,parseFailure:true,builtinOnly:false};let r=e[$],s=r===void 0?void 0:bd(r,n.maxBytes??262144);if(t.length===0)return {ok:false,rejection:s===void 0?{code:"MANIFEST_INVALID",reason:{path:"",rule:"no-manifest-file",message:"neither manifest.json nor ui-plugin.json is present"},files:[]}:wo(o),parseFailure:true,builtinOnly:false};let a=t[0],c=a.file===W?fd(a.raw):yd(a.raw),d=t.some(y=>Ad(y.file,y.raw)),l;if(s!==void 0){let y=t.some(g=>g.file===W)?s.failure:wo(o);if(y!==void 0)return {ok:false,rejection:y,parseFailure:false,...c===void 0?{}:{identity:c},builtinOnly:d};l=s.actions;}let p=[];try{for(let y of t)p.push(y.file===W?md(y.raw,n,l):hd(y.raw,n));p.length===2&&Td(p[0].manifest,p[1].manifest);}catch(y){if(y instanceof Oe)return {ok:false,rejection:{code:y.code,reason:y.reason,files:y.code==="MANIFEST_DUAL_MISMATCH"?[...Q]:y.reason.file===void 0||y.reason.file===$?o:[y.reason.file]},parseFailure:false,...c===void 0?{}:{identity:c},builtinOnly:d};throw y}let f=p[0];return {ok:true,...f,identity:c??{pluginId:f.manifest.pluginId},files:o}}var W,pe,Q,ri,Be,ci,di,Co,si,Uo,id,od,rd,sd,ad,Oe,ot=j(()=>{m();We();Ce();Wt();Je();oi();W="manifest.json",pe="ui-plugin.json",Q=[W,pe],ri="0.3",Be="dev.crewx",ci=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"]),di=Object.freeze(["manifest_version","name","display_name","version","description","_meta"]),Co=Object.freeze(ci.filter(e=>e!=="server"&&!di.includes(e))),si=Object.freeze(["entry","surfaces","size","stateProjection","actions"]),Uo=Object.freeze(["definitionId","definitionVersion","icon","tone","entryHash","runtime","initialState","usage","detailPanel","displayModes","summaryProjection","dataPaths","focusedAiDataPaths","csp","deviceFeatures","downloads","share","files","desktopOnly"]),id=/^(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-]+)*))?$/,od=256,rd=/<\/?[A-Za-z][^>]*>/,sd=/^\s*javascript:/i,ad=/data:[^,\s]*,/i;Oe=class extends Error{constructor(t,i){super(`${t}: ${i.path||"<file>"} (${i.rule})`);this.code=t;this.reason=i;}code;reason};});function Go(e){if(e===void 0)return {kind:"none"};if(typeof e!="string")return {kind:"invalid",reason:"bad-path"};if(Sd.test(e))return {kind:"url",declared:e};if(!Od(e))return {kind:"invalid",reason:"bad-path",declared:e};let n=e.lastIndexOf("."),t=n<0?void 0:Nd.get(e.slice(n+1).toLowerCase());return t===void 0?{kind:"invalid",reason:"bad-type",declared:e}:{kind:"file",path:e,contentType:t}}function Od(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 Pn(e,n){let t=Go(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:[li(t.reason,t.declared)]};let i=await n(t.path);if(typeof i=="string")return {diagnostics:[li(i,t.path)]};let o=Jo(t.contentType,i);if(!o.ok)return {diagnostics:[li(o.reason,t.path)]};let r={path:t.path,contentType:t.contentType,byteLength:i.byteLength,bytes:i},s=o.square===false?[{code:"ICON_NOT_SQUARE",severity:"warning",declared:t.path}]:[];return {file:r,diagnostics:s}}function li(e,n){return {code:"ICON_INVALID",severity:"error",reason:e,...n===void 0?{}:{declared:n}}}function Jo(e,n){if(n.byteLength>262144)return {ok:false,reason:"too-large"};if(e==="image/png")return !Ho(n,Md)||Vd(n,12,16)!=="IHDR"||n.byteLength<24?{ok:false,reason:"bytes-mismatch"}:{ok:true,square:Bo(zo(n,16),zo(n,20))};if(e==="image/jpeg"){if(!Ho(n,Ld))return {ok:false,reason:"bytes-mismatch"};let t=jd(n);return {ok:true,square:t===void 0?void 0:Bo(t.width,t.height)}}return Rd(n)}function Rd(e){let n;try{n=Dd.decode(e);}catch{return {ok:false,reason:"bytes-mismatch"}}return xd(n)?{ok:false,reason:"unsafe-svg"}:wd.test(n)?{ok:true,square:vd(n)}:{ok:false,reason:"bytes-mismatch"}}function xd(e){if(Cd.some(n=>n.test(e)))return true;for(let n of e.matchAll(Ud))if(!(n[1]??n[2]??n[3]??"").startsWith("#"))return true;for(let n of e.matchAll(kd))if(Fo.lastIndex=n.index??0,!Fo.test(e))return true;return false}function vd(e){let n=/<svg\b[^>]*>/i.exec(e)?.[0];if(n===void 0)return;let t=Wo(n,"viewBox");if(t!==void 0){let r=t.trim().split(/[\s,]+/).map(Number);return r.length===4&&r.every(Number.isFinite)?r[2]===r[3]:void 0}let i=Vo(n,"width"),o=Vo(n,"height");return i===void 0||o===void 0?void 0:i===o}function Wo(e,n){let t=new RegExp(`\\s${n}\\s*=\\s*(?:"([^"]*)"|'([^']*)')`).exec(e);return t?.[1]??t?.[2]}function Vo(e,n){let t=Wo(e,n),i=t===void 0?null:/^\s*(\d+(?:\.\d+)?)(?:px)?\s*$/.exec(t);return i===null?void 0:Number(i[1])}function jd(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(Fd(t))return n+9>e.byteLength?void 0:{height:$o(e,n+5),width:$o(e,n+7)};n+=2+i;}}function Fd(e){return e>=192&&e<=207&&e!==196&&e!==200&&e!==204}function Bo(e,n){if(!(e<=0||n<=0))return e===n}function Ho(e,n){return e.byteLength>=n.length&&n.every((t,i)=>e[i]===t)}function Vd(e,n,t){return String.fromCharCode(...e.subarray(n,t))}function zo(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 Nd,Dd,Sd,Md,Ld,wd,Cd,Ud,kd,Fo,ui=j(()=>{m();Nd=new Map([["svg","image/svg+xml"],["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"]]),Dd=new TextDecoder("utf-8",{fatal:true}),Sd=/^[A-Za-z][A-Za-z0-9+.-]*:/,Md=[137,80,78,71,13,10,26,10],Ld=[255,216,255];wd=/^\s*(?:<\?[\s\S]*?\?>\s*|<!--[\s\S]*?-->\s*)*<svg(?=[\s/>])/,Cd=[/<script/i,/[\s"'/]on[a-z]+\s*=/i,/<foreignobject/i,/<!doctype/i,/<!entity/i,/<(?:iframe|embed|object)\b/i,/@import/i],Ud=/(?:^|[\s"'/])(?:xlink:)?href\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+))/gi,kd=/url\(/gi,Fo=/url\(\s*["']?#/iy;});var fi=j(()=>{m();Wi();ot();ui();oi();Je();});function S(e,n=e){throw new Re(e,n)}var Re,st=j(()=>{m();Re=class extends Error{constructor(t,i=t){super(i);this.code=t;}code;name="McpAppContractError"};});var rr=j(()=>{m();});var sr=j(()=>{m();We();Ce();st();rr();});function cr(e,n){return ar.add(e),n!==void 0&&Zd.set(e,n),e}function un(e){return e!==null&&typeof e=="object"&&ar.has(e)}var ar,Zd,at=j(()=>{m();ar=new WeakSet,Zd=new WeakMap;});function Mn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Ai(e,n,t=[]){let i=new Set([...n,...t]),o=Object.keys(e);return n.every(r=>Object.hasOwn(e,r))&&o.every(r=>i.has(r))}function lr(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let n of Object.values(e))lr(n);return Object.freeze(e)}function re(e){throw new we("LINEAGE_INVALID",e)}function rp(e){throw new we("LINEAGE_STALE",e)}function ur(e){if(!Mn(e)||!Ai(e,np,tp)||!Mn(e.actions))return re("Lineage definition shape is invalid");for(let n of Object.values(e.actions))if(!Mn(n)||!Ai(n,ip,op))return re("Lineage action definition shape is invalid");return e}function sp(e){if(!Mn(e)||!Ai(e,Qd,ep))return re("Lineage entry shape is invalid");if(!Number.isSafeInteger(e.version)||e.version<1||typeof e.hash!="string"||!dr.test(e.hash))return re("Lineage entry identity is invalid");if(e.sourceHash!==void 0&&(typeof e.sourceHash!="string"||!dr.test(e.sourceHash)))return re("Lineage source hash is invalid");if(e.compat!==void 0&&e.compat!=="break")return re("Lineage compatibility marker is invalid");let n=ur(e.definition);if(n.version!==e.version)return re("Lineage version does not match its definition");if(e.sourceHash!==void 0&&n.sourceHash!==e.sourceHash)return re("Lineage source hash does not match its definition");let t;try{t=ue(n),ge({...n,hash:e.hash});}catch{return re("Lineage definition is invalid")}return t!==e.hash?re("Lineage definition hash does not match"):lr({version:e.version,hash:e.hash,definition:n,...e.sourceHash===void 0?{}:{sourceHash:e.sourceHash},...e.compat===void 0?{}:{compat:e.compat}})}function pr(e){return e.stateProjection?.allow??[]}function ap(e,n){let t=[],i=new Set(pr(n));pr(e).some(a=>!i.has(a))&&t.push("S1_STATE_PROJECTION");let o=new Set(n.dataPaths??[]);(e.dataPaths??[]).some(a=>!o.has(a))&&t.push("S2_DATA_PATHS");for(let[a,c]of Object.entries(e.actions)){let d=n.actions[a];if(d&&(c.confirmation??"native")==="native"&&(d.confirmation??"native")!=="native"){t.push("S3_ACTION_CONFIRMATION");break}}Object.keys(e.legacy?.agentAccess??{}).some(a=>!Object.hasOwn(n.actions,a))&&t.push("S4_LEGACY_AGENT_ACTIONS");let s=e.summaryProjection?.allow;if(s!==void 0){let a=new Set(n.summaryProjection?.allow??[]);s.some(c=>!a.has(c))&&t.push("S5_SUMMARY_PROJECTION");}return t}function cp(e,n){return te(e)===te(n)}function Ii(e,n){if(!Array.isArray(e)||e.length===0)return re("Definition lineage is missing");if(!Mn(n)||typeof n.hash!="string")return re("Current definition is invalid");let t,i;try{let{hash:a,...c}=n;i=ur(c),t={...i,hash:a},ge(t);}catch{return re("Current definition is invalid")}let o=e.map(sp),r=o[0].definition.id;if(o.some(a=>a.definition.id!==r))return re("Lineage definition ids do not match");if(o.some((a,c)=>c>0&&a.version<=o[c-1].version))return re("Lineage generations are not in increasing version order");if(o.some((a,c)=>o.findIndex(d=>d.hash===a.hash)!==c))return re("Lineage contains a duplicate hash");let s=o[o.length-1];if(s.version!==t.version||s.hash!==t.hash||s.definition.id!==t.id||!cp(s.definition,i))return rp("The last lineage generation does not match the current package");if(t.legacy!==void 0){let a=new Set(Object.keys(t.actions)),c=new Set;for(let l of o)if(l.sourceHash===void 0)for(let p of Object.keys(l.definition.actions))a.has(p)&&c.add(p);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 we("LINEAGE_INVALID",`Lineage compatibility failed: ${l}`,[l])}}for(let a=0;a<o.length-1;a+=1){if(o.slice(a,-1).some(l=>l.compat==="break"))continue;let d=ap(o[a].definition,t);if(d.length>0)throw new we("LINEAGE_INVALID",`Lineage compatibility failed: ${d.join(", ")}`,d)}return Object.freeze({entries:Object.freeze(o),current:t})}var we,dr,Qd,ep,np,tp,ip,op,gi=j(()=>{m();We();Ce();we=class extends Error{constructor(t,i=t,o=[]){super(i);this.code=t;this.violations=o;}code;violations;name="UiDefinitionLineageError"},dr=/^[0-9a-f]{64}$/,Qd=["version","hash","definition"],ep=["sourceHash","compat"],np=["id","version","actions"],tp=["sourceHash","usage","detailPanel","displayModes","renderer","surfaces","stateProjection","dataPaths","summaryProjection","downloads","legacy"],ip=["capabilities"],op=["inputKeys","dataInputs","confirmation","resultProjection","content","env","schedule","job","jobAccess"];});var fr,yr,Ar,Ir,gr=j(()=>{m();fr="text/html;profile=mcp-app",yr=["crewx_app_terminal_connect","crewx_app_html_viewer_open","crewx_app_browser","crewx_files_list","crewx_files_read","crewx_files_write","crewx_docs_share"],Ar=["crewx_listWorkspaces","crewx_queryAgent","crewx_executeAgent","crewx_getTaskResult","crewx_listTasks","crewx_listAgents","callBrowser","openTab","listTabs","closeTab"],Ir="text/html";});function Ln(e){return typeof e=="string"&&dp.includes(e)}function ct(e,n){return e==="card"&&n?.type==="core"&&Ln(n.handler)}var dp,dt=j(()=>{m();dp=Object.freeze(["card.secret-env"]);});function mr(e,n=[],t){if(e.content!==void 0||e.confirmation!=="none")return "denied";let i=pp();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===Me?(e.usage??ie)===ie&&e.mutation===false&&e.resultProjection!==void 0&&Array.isArray(e.resultProjection.allow)&&e.env===void 0&&e.job===void 0&&e.jobAccess===void 0&&e.schedule===void 0?"allowed":"denied":e.backend?.type==="core"&&e.backend.handler==="state.set"?"allowed":e.backend?.type==="core"&&Ln(e.backend.handler)||e.backend?.type==="skill"?"approval_required":e.backend===void 0&&n.includes(e.actionId)?"allowed":"denied"}function pp(e){return;}var hr=j(()=>{m();sn();We();at();dt();});function hp(e){return wn.has(e)&&(e.initialState===void 0||wn.has(e.initialState))}function Pr(e,n,t,i){let o=i===void 0?void 0:Object.freeze({hash:i.hash,bytes:Object.freeze(i.bytes)}),r=Object.freeze({mimeType:Ir,entryHash:e,html:n,bytes:Object.freeze(t),...o===void 0?{}:{initialState:o}});return o!==void 0&&wn.add(o),wn.add(r),r}function _p(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:fe}),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:fe}),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:fe}),n}function Ep(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:fe},{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:{...mi}},required:["ref"],additionalProperties:false},textFallback:"A markdown file of this App is read through this App.",visibility:Object.freeze(["app"]),kind:"host",resourceBinding:fe},{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:{...mi},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:fe}),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:{...mi}},required:["ref"],additionalProperties:false},textFallback:"The Host share sheet opens for a markdown file of this App.",visibility:Object.freeze(["app"]),kind:"host",resourceBinding:fe}),n}function $e(e,n,t){return (typeof e!="string"||!Tr.test(e))&&S(n,`${t} must be a safe identifier`),e}function On(e,n,t){let i=e??t;return (typeof i!="string"||i.trim().length===0||i.length>fp)&&S("TOOL_INVALID",`${n} must be a meaningful description`),i}function _i(e){return (typeof e!="string"||e.length===0||e.length>fn||!/<html(?:\s|>)/i.test(e)||!/<\/html\s*>/i.test(e))&&S("HTML_INVALID","MCP App HTML must be a non-empty HTML document"),e}function Rn(e,n=0){try{let t=Ie(e,n);return t.type!==void 0&&t.type!=="object"&&S("TOOL_INVALID","MCP App inputSchema must describe an object"),t}catch(t){if(t instanceof Re)throw t;S("TOOL_INVALID","MCP App inputSchema must be projection-safe JSON");}}function Tp(e){return (typeof e!="string"||e.trim().length===0||e.length>yp)&&S("TOOL_INVALID","MCP App tools require a meaningful text fallback"),e}function bp(e){e===void 0&&S("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)&&S("TOOL_INVALID","MCP App tool visibility must contain model and/or app once"),n}function Dr(e){return (typeof e!="string"||!br.test(e))&&S("RESOURCE_URI_INVALID","MCP App resource URI is not a registered ui:// URI"),e}function Sr(e){let n=$e(e.appId,"APP_ID_INVALID","Local App id"),t=On(e.name,"Local App name",n),i=On(e.description,"Local App description",`${t} interactive view`),o=ft(e.definition),r=_i(e.html),s=pt(e.entryHash,"Local App entry hash"),a=e.entryBytes===void 0?Array.from(new TextEncoder().encode(r)):ut(e.entryBytes,"Local App entry bytes");(lt(a)!==s||Or(a)!==r)&&S("HTML_INVALID","Local App entry bytes do not match the HTML hash");let c=Pp(e),d=[];Array.isArray(e.actions)||S("TOOL_INVALID","Local App actions must be an array");for(let T of e.actions){let C=$e(T.actionId,"TOOL_ID_INVALID","Local App action id");(d.includes(C)||!Object.prototype.hasOwnProperty.call(o.actions,C))&&S("TOOL_INVALID",`Local App action is not declared by the UI definition: ${C}`),d.push(C);}let l=$e(e.readToolName,"TOOL_ID_INVALID","Local App read tool name"),p=e.actionToolName===void 0?void 0:$e(e.actionToolName,"TOOL_ID_INVALID","Local App action tool name");d.length===0&&p!==void 0&&S("TOOL_INVALID","A static local App cannot register an action tool"),d.length>0&&p===void 0&&S("TOOL_INVALID","A stateful local App requires an action tool name"),p!==void 0&&p===l&&S("TOOL_ID_CONFLICT",`Local App read and action tools share a name: ${l}`);let f=[..._p(e.runtime),...Ep(e.hostTools)];f.some(T=>T.name===l||T.name===p)&&S("TOOL_ID_CONFLICT","Local App read or action tool conflicts with a requested Host capability");let y={name:l,description:`${t} current state`,inputSchema:mp,textFallback:`${t} current state is available through its open instance.`,visibility:Object.freeze(["model","app"]),kind:"read",resourceBinding:fe},g=[Object.freeze(y)];if(g.push(...f.map(T=>Object.freeze(T))),p!==void 0){let T={name:p,description:`${t} actions`,inputSchema:Ei(e.actions),textFallback:`${t} action requests are handled by the open App instance.`,visibility:Object.freeze(["app"]),kind:"action",resourceBinding:fe,actionIds:Object.freeze([...d])};g.push(Object.freeze(T));}let _=[],E=new Set(g.map(T=>T.name));if(p!==void 0)for(let T of e.actions){let C=`${p}__${T.actionId}`;if(C.length>128||!Tr.test(C)){_.push(Object.freeze({toolName:C,actionId:T.actionId,reason:"name_too_long"}));continue}if(E.has(C)){_.push(Object.freeze({toolName:C,actionId:T.actionId,reason:"name_collision"}));continue}let B=mr({actionId:T.actionId,confirmation:o.actions[T.actionId]?.confirmation,content:o.actions[T.actionId]?.content,usage:o.usage,mutation:o.actions[T.actionId]?.mutation,resultProjection:o.actions[T.actionId]?.resultProjection,env:o.actions[T.actionId]?.env,job:o.actions[T.actionId]?.job,jobAccess:o.actions[T.actionId]?.jobAccess,schedule:o.actions[T.actionId]?.schedule,backend:T.backend},e.modelActions),N=Object.freeze([...Lp(B,o.usage,T.backend)]),D={name:C,description:`${C} action`,inputSchema:Rn(T.inputSchema),textFallback:`${C} action requests are handled by the open App instance.`,visibility:N,kind:"action",resourceBinding:fe,actionId:T.actionId,actionIds:Object.freeze([T.actionId]),_meta:Object.freeze({ui:Object.freeze({visibility:N})})};g.push(Object.freeze(D)),E.add(C);}let U=Pr(s,r,a,c===void 0?void 0:{hash:c.hash,bytes:[...c.bytes]}),k={appId:n,name:t,description:i,...e.icon===void 0?{}:{icon:Rr(e.icon)},...e.tone===void 0?{}:{tone:wr(e.tone)},builtinOnly:false,definition:o,...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:fe,resource:U,tools:Object.freeze(g),toolDiagnostics:Object.freeze(_)};return ee(k)}function Mr(e={}){return new hi(e)}function Ei(e){if(e.length===0)return Rn({type:"object",properties:{},additionalProperties:false});let n=e.map(i=>i.actionId),t=new Map;for(let i of e)t.set(i.actionId,Rn(i.inputSchema));return Rn(Np(n,t),Nr)}function Pp(e){let n=e.definition.dataPaths??[];if(e.initialStateBytes===void 0){e.initialStateHash!==void 0&&S("STATE_INVALID","Initial state hash has no bytes"),e.initialState!==void 0&&Ie(e.initialState,0,n);return}e.initialStateHash===void 0&&S("STATE_INVALID","Initial state bytes require a hash");let t=pt(e.initialStateHash,"Initial state hash"),i=ut(e.initialStateBytes,"Initial state bytes");lt(i)!==t&&S("STATE_INVALID","Initial state bytes do not match the hash");let o;try{let r=new TextDecoder("utf-8",{fatal:!0}).decode(Uint8Array.from(i));o=Ie(JSON.parse(r),0,n);}catch{S("STATE_INVALID","Initial state bytes are not projection-safe JSON");}return e.initialState!==void 0&&te(o)!==te(Ie(e.initialState,0,n))&&S("STATE_INVALID","Initial state bytes do not match the state value"),{hash:t,bytes:Object.freeze([...i])}}function Np(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 Dp(e){let n=Cn(e),t=$e(n.appId,"APP_ID_INVALID","MCP App id"),i=_i(n.html);Dr(n.uiUri);let o=n.definition===void 0?void 0:ft(n.definition),r=e.provenance;r!==void 0&&(!un(r)||r.appId!==t||r.definitionId!==o?.id||r.version!==o?.version||r.definitionHash!==o?.hash)&&S("TOOL_INVALID","Product App built-in registration provenance is not verified");let s=Object.freeze(n.tools.map(d=>ee(Cn(d)))),a=ee({...n,appId:t,html:i,...o===void 0?{}:{definition:o},...r===void 0?{}:{provenance:r},tools:s}),c=ee({uri:a.uiUri,mimeType:fr,text:i,...a.csp===void 0?{}:{_meta:{ui:{csp:a.csp}}}});return ee({appId:t,name:a.name,description:a.description,...a.icon===void 0?{}:{icon:a.icon},...a.tone===void 0?{}:{tone:a.tone},builtinOnly:a.builtinOnly,uiUri:a.uiUri,...o===void 0?{}:{definition:o},resourceBinding:Object.freeze({kind:"mcp",uri:a.uiUri}),resource:c,tools:s,descriptor:a})}function Sp(e){(e.resourceBinding.kind!=="instance"||e.builtinOnly!==false)&&S("STATE_INVALID","Local App registration binding is invalid"),Object.prototype.hasOwnProperty.call(e,"uiUri")&&S("STATE_INVALID","Local App registration cannot contain uiUri");let n=$e(e.appId,"APP_ID_INVALID","Local App id"),t=ft(e.definition),i=e.provenance;i!==void 0&&(!un(i)||i.appId!==n||i.definitionId!==t.id||i.version!==t.version||i.definitionHash!==t.hash)&&S("TOOL_INVALID","Product App local registration provenance is not verified");let o=Mp(e.resource),r=e.tools.map(a=>{$e(a.name,"TOOL_ID_INVALID","Local App tool name"),On(a.description,"Local App tool description","Local App tool"),Tp(a.textFallback);let c=Rn(a.inputSchema,a.kind==="action"&&!("actionId"in a)?Nr:0);if((a.resourceBinding.kind!=="instance"||Object.prototype.hasOwnProperty.call(a,"resourceUri"))&&S("TOOL_INVALID","Local App tools cannot carry an MCP resource URI"),a.kind==="host")return (!gp.has(a.name)||a.visibility.length!==1||a.visibility[0]!=="app"||Object.prototype.hasOwnProperty.call(a,"actionId"))&&S("TOOL_INVALID","Local App Host tools must use an allow-listed name and app-only visibility"),ee({...a,inputSchema:c,visibility:Object.freeze(["app"])});if(a.kind==="action"){if("actionId"in a){let l=$e(a.actionId,"TOOL_ID_INVALID","Local App action id");Object.prototype.hasOwnProperty.call(t.actions,l)||S("TOOL_INVALID","Local App action tool references an undeclared action");let p=bp(a._meta.ui.visibility);return JSON.stringify(p)!==JSON.stringify(a.visibility)&&S("TOOL_INVALID","Local App action metadata visibility must match the tool visibility"),ee({...a,actionId:l,actionIds:Object.freeze([l]),inputSchema:c,visibility:p,_meta:{ui:{visibility:p}}})}let d=[...a.actionIds];return (d.length===0||d.some(l=>!Object.prototype.hasOwnProperty.call(t.actions,l)))&&S("TOOL_INVALID","Local App action tool references an undeclared action"),ee({...a,inputSchema:c,actionIds:Object.freeze(d)})}return ee({...a,inputSchema:c})}),s=ee({appId:n,name:On(e.name,"Local App name",e.appId),description:On(e.description,"Local App description",e.name),...e.icon===void 0?{}:{icon:Rr(e.icon)},...e.tone===void 0?{}:{tone:wr(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:fe,resource:o,tools:Object.freeze(r),toolDiagnostics:Object.freeze([...e.toolDiagnostics??[]])});return _r.has(e)?e:(_r.add(s),s)}function Mp(e){let n=_i(e.html),t=pt(e.entryHash,"Local App entry hash");if(hp(e))return e;let i=ut(e.bytes,"Local App entry bytes");(lt(i)!==t||Or(i)!==n)&&S("HTML_INVALID","Local App entry bytes do not match the HTML hash");let o=e.initialState===void 0?void 0:{hash:pt(e.initialState.hash,"Initial state hash"),bytes:ut(e.initialState.bytes,"Initial state bytes")};return o&&lt(o.bytes)!==o.hash&&S("STATE_INVALID","Initial state bytes do not match the hash"),Pr(t,n,i,o)}function Lp(e,n,t){if(ct(n,t))return ["model"];if(t?.type==="core"&&t.handler===Me)return ["model"];let i=t?.type==="core"&&Ln(t.handler);return e==="denied"||i?["app"]:["model","app"]}function Op(e){return ee({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:Lr(e.definition),...e.provenance===void 0?{}:{provenance:e.provenance},entryHash:e.resource.entryHash,resourceBinding:fe,tools:e.tools})}function Rp(e){return ee({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:Lr(e.definition)},resourceBinding:Object.freeze({kind:"mcp",uri:e.uiUri}),tools:e.tools})}function ft(e){try{if(Object.isFrozen(e))return ge(e),ee(e);let n=Cn(e);return ge(n),ee(n)}catch(n){if(n instanceof Re)throw n;S("STATE_INVALID","UI definition is not a valid immutable definition");}}function Lr(e){return ee({id:e.id,version:e.version,hash:e.hash})}function wp(e){return e!==null&&typeof e=="object"&&typeof e.id=="string"&&Number.isSafeInteger(e.version)&&typeof e.hash=="string"}function Er(e,n,t){return `${e}\0${n}\0${t}`}function pt(e,n){return (typeof e!="string"||!up.test(e))&&S("SERIALIZATION_INVALID",`${n} is invalid`),e}function lt(e){return zi.createHash("sha256").update(Uint8Array.from(e)).digest("hex")}function ut(e,n){return (!Array.isArray(e)||e.some(t=>!Number.isInteger(t)||t<0||t>255))&&S("SERIALIZATION_INVALID",`${n} is invalid`),[...e]}function Or(e){try{return new TextDecoder("utf-8",{fatal:!0}).decode(Uint8Array.from(e))}catch{S("SERIALIZATION_INVALID","UTF-8 bytes are invalid");}}function Rr(e){return (typeof e!="string"||!Ap.test(e))&&S("TOOL_INVALID","MCP App icon is invalid"),e}function wr(e){return (typeof e!="string"||!Ip.has(e))&&S("TOOL_INVALID","MCP App tone is invalid"),e}function Cn(e,n=new Map){if(e===null||typeof e!="object")return e;let t=e;if(n.has(t)&&S("SERIALIZATION_INVALID","MCP App value contains a cycle"),Array.isArray(e)){let r=[];n.set(t,r);for(let s of e)r.push(Cn(s,n));return n.delete(t),r}let i;try{i=Object.getPrototypeOf(e);}catch{S("SERIALIZATION_INVALID","MCP App value cannot be cloned");}i!==Object.prototype&&i!==null&&S("SERIALIZATION_INVALID","MCP App value must be plain JSON");let o={};n.set(t,o);for(let[r,s]of Object.entries(e))Object.defineProperty(o,r,{configurable:true,enumerable:true,value:Cn(s,n),writable:true});return n.delete(t),o}function ee(e,n=new Set){if(e===null||typeof e!="object"||n.has(e)||wn.has(e))return e;n.add(e);for(let t of Object.values(e))ee(t,n);return Object.freeze(e),e}var Tr,br,up,fn,fp,yp,Ap,Ip,gp,fe,mp,wn,_r,mi,Nr,hi,yt=j(()=>{m();sr();We();Ce();at();st();gi();gr();sn();hr();dt();Tr=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,br=/^ui:\/\/crewx\/([A-Za-z][A-Za-z0-9._-]{0,127})\/([0-9a-f]{12})$/,up=/^[0-9a-f]{64}$/,fn=8*1024*1024,fp=8*1024,yp=16*1024,Ap=/^[a-z][a-z0-9-]{0,63}$/,Ip=new Set(["blue","violet","emerald","amber","rose","sky","slate","indigo"]),gp=new Set(yr),new Set(Ar),fe=Object.freeze({kind:"instance"}),mp=Object.freeze({type:"object",properties:Object.freeze({}),additionalProperties:false}),wn=new WeakSet,_r=new WeakSet;mi={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.'};Nr=4;hi=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=[],o=[],r=[],s=new Set,a=new Set;for(let p of t?.listMcpApps()??[]){let f=Dp(p);s.has(f.appId)&&S("APP_ID_CONFLICT",`MCP App id is already registered: ${f.appId}`),s.add(f.appId);let y=f.tools;for(let g of y)a.has(g.name)&&S("TOOL_ID_CONFLICT",`MCP App tool name is already registered: ${g.name}`),a.add(g.name),this.mcpToolByName.set(g.name,g),r.push(g);this.mcpResources.set(f.resource.uri,f.resource),i.push(f),o.push(f.descriptor);}let c=(n.localApps??n.locals??[]).map(Sp),d=new Set(c.flatMap(p=>p.tools.filter(f=>!(f.kind==="action"&&"actionId"in f)).map(f=>f.name))),l=[];for(let p of c){let f=p;s.has(f.appId)&&S("APP_ID_CONFLICT",`MCP App id is already registered: ${f.appId}`),s.add(f.appId);let y=[],g=[...f.toolDiagnostics??[]];for(let _ of f.tools){if(a.has(_.name)){if(_.kind==="host"&&this.localToolByName.get(_.name)?.kind==="host"){y.push(_);continue}if(_.kind==="action"&&"actionId"in _){g.push(Object.freeze({toolName:_.name,actionId:_.actionId,reason:"name_collision"}));continue}S("TOOL_ID_CONFLICT",`MCP App tool name is already registered: ${_.name}`);}if(_.kind==="action"&&"actionId"in _&&d.has(_.name)){g.push(Object.freeze({toolName:_.name,actionId:_.actionId,reason:"name_collision"}));continue}a.add(_.name),this.localToolByName.set(_.name,_),y.push(_);}(y.length!==f.tools.length||g.length!==(f.toolDiagnostics?.length??0))&&(f=ee({...f,tools:Object.freeze(y),toolDiagnostics:Object.freeze(g)})),l.push(f),this.localById.set(f.appId,f);}for(let p of i)this.registrationById.set(p.appId,p),this.launcherById.set(p.appId,Rp(p)),p.definition&&this.addDefinition(p.definition);for(let p of l)this.registrationById.set(p.appId,p),this.launcherById.set(p.appId,Op(p)),this.addDefinition(p.definition);for(let p of n.definitions??[])this.addDefinition(p);for(let p of n.handlers??[])this.addHandler(p);this.builtinApps=Object.freeze(i),this.localApps=Object.freeze(l),this.builtinDescriptors=Object.freeze(o),this.builtinTools=Object.freeze(r);}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"||!br.test(n)?null:this.mcpResources.get(n)??null}requireMcpAppResource(n){Dr(n);let t=this.mcpResources.get(n);return t||S("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,o=un(i)&&i.launcher===false;return t?.definition?.usage!=="card"&&!o}))}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(!wp(n))return null;let t=this.definitionByKey.get(Jt(n));if(!t||t.hash!==n.hash)return null;try{return ue(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(Er(n,t,i))??null}addDefinition(n){let t=ft(n),i=Jt(t),o=this.definitionByKey.get(i);o&&o.hash!==t.hash&&S("STATE_INVALID",`UI definition generation conflicts: ${i}`),o||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")&&S("STATE_INVALID","UI action handler registration is invalid");let t=Er(n.definitionId,n.version,n.actionId);this.handlerByKey.has(t)&&S("TOOL_INVALID",`Duplicate UI action handler registration: ${t}`),this.handlerByKey.set(t,Object.freeze({...n}));}};});function Cp(e,n){let t=Sr({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(o=>({actionId:o.actionId,inputSchema:o.inputSchema,backend:o.backend})),...{}});return e.provenance===void 0?t:Object.freeze({...t,provenance:e.provenance})}function Cr(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=Cp(e);Mr({localApps:[t],definitions:[e.definition]});}var Ur=j(()=>{m();yt();});function Up(e){if(e===null||typeof e!="object"||!(kr in e))throw new TypeError("scanCache must be created by createWorkspaceAppScanCache");return e[kr]}function xr(e,n){let t=Up(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 kr,vr=j(()=>{m();kr=Symbol("crewx.workspace-app-scan-cache.state");});function ye(e){let n=typeof e=="object"&&e!==null&&"code"in e?String(e.code):"";return n==="ENOENT"?new M("NOT_FOUND"):n==="ELOOP"?new M("PATH_ESCAPED"):n==="EFBIG"||n==="EOVERFLOW"?new M("LIMIT_EXCEEDED"):n==="EACCES"||n==="EPERM"||n==="ENOTDIR"?new M("READ_DENIED"):new M("READ_DENIED")}function jp(e){if(typeof e!="string"||e.length===0||!de.isAbsolute(e))throw new M("READ_DENIED")}function Ti(e){if(typeof e!="string"||de.isAbsolute(e)||/[\\\u0000]/.test(e))throw new M("PATH_ESCAPED");if(e==="")return [];let n=e.split("/");if(n.some(t=>t.length===0||t==="."||t===".."))throw new M("PATH_ESCAPED");return n}function mt(e,n){let t=de.relative(e,n);return t===""||t!==".."&&!t.startsWith(`..${de.sep}`)&&!de.isAbsolute(t)}function An(e){return {dev:e.dev,ino:e.ino,size:e.size,mtimeNs:e.mtimeNs,ctimeNs:e.ctimeNs}}function Di(e,n){return e.dev===n.dev&&e.ino===n.ino}function Si(e,n){return Di(e,n)&&e.size===n.size&&e.mtimeNs===n.mtimeNs&&e.ctimeNs===n.ctimeNs}async function At(e){jp(e);let n,t;try{n=await promises.realpath(e),t=await promises.stat(n,{bigint:!0});}catch(i){throw ye(i)}if(!t.isDirectory())throw new M("READ_DENIED");return {realRoot:n,identity:An(t)}}async function Vr(e,n,t){if(t.length<2||t[0]!=="apps"&&t[0]!=="skills")return;let i,o;try{if(i=de.resolve(e,t[0],t[1]),o=await promises.realpath(i),!(await promises.stat(o,{bigint:!0})).isDirectory())throw new M("READ_DENIED")}catch(r){throw r instanceof M?r:ye(r)}if(!mt(n,o))throw new M("PATH_ESCAPED");return o}async function It(e,n,t,i){let o,r,s;try{o=await promises.lstat(e,{bigint:!0}),r=await promises.realpath(e),s=await promises.stat(r,{bigint:!0});}catch(a){throw ye(a)}if(!mt(n,r)||t!==void 0&&!mt(t,r))throw new M("PATH_ESCAPED");if(!o.isFile()||!s.isFile())throw new M("READ_DENIED");if(!Di(i,o)||!Di(i,s)||i.dev!==s.dev)throw new M("PATH_ESCAPED")}async function yn(e,n){let t,i;try{t=await promises.realpath(e),i=await promises.stat(t,{bigint:!0});}catch{throw new M("PATH_ESCAPED")}if(t!==n.realRoot||!Si(n.identity,An(i)))throw new M("PATH_ESCAPED")}function Fp(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 M,Ni,vp,Fr,ht,Br,Li=j(()=>{m();M=class extends Error{constructor(t){super(t);this.code=t;}code;name="AppDiscoveryFsError"},Ni=ne.constants.O_NOFOLLOW,vp=ne.constants.O_NONBLOCK,Fr=ne.constants.O_RDONLY|(Ni??0)|(vp??0);ht=class{async getRootIdentity(n){let t=await At(n);return await yn(n,t),{dev:t.identity.dev,ino:t.identity.ino,realPath:t.realRoot}}async listDirectory(n,t){let i=Ti(t),o=await At(n),r=de.resolve(n,...i),s,a;try{s=await promises.realpath(r),a=await promises.stat(s,{bigint:!0});}catch(c){let d=ye(c);if(d.code==="NOT_FOUND")return [];throw d}if(!mt(o.realRoot,s)||!a.isDirectory())throw new M("PATH_ESCAPED");try{let c=await promises.readdir(s,{withFileTypes:!0,encoding:"utf8"});return await yn(n,o),c.map(Fp)}catch(c){let d=ye(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 M("READ_DENIED");if(Ni===void 0)throw new M("UNSUPPORTED");let o=Ti(t),r=await At(n),s=de.resolve(n,...o),a=de.relative(n,s);if(a===".."||a.startsWith(`..${de.sep}`)||de.isAbsolute(a))throw new M("PATH_ESCAPED");let c;try{c=await promises.open(s,Fr);}catch(d){throw ye(d)}try{let d;try{let g=await c.stat({bigint:!0});d=An(g);}catch(g){throw ye(g)}if(d.size>BigInt(i))throw new M("LIMIT_EXCEEDED");if(d.size>BigInt(Number.MAX_SAFE_INTEGER))throw new M("LIMIT_EXCEEDED");await yn(n,r);let l=await Vr(n,r.realRoot,o);await It(s,r.realRoot,l,d);let p=new Uint8Array(new ArrayBuffer(Number(d.size))),f=0;for(;f<p.byteLength;){let g;try{g=(await c.read(p,f,p.byteLength-f,f)).bytesRead;}catch(_){throw ye(_)}if(g<=0)throw new M("IDENTITY_CHANGED");f+=g;}let y;try{let g=await c.stat({bigint:!0});y=An(g);}catch(g){throw ye(g)}if(!Si(d,y))throw new M("IDENTITY_CHANGED");return await It(s,r.realRoot,l,y),await yn(n,r),new Uint8Array(p)}finally{await c.close().catch(()=>{});}}async fingerprintVerifiedFile(n,t,i){if(!Number.isSafeInteger(i)||i<0)throw new M("READ_DENIED");if(Ni===void 0)throw new M("UNSUPPORTED");let o=Ti(t),r=await At(n),s=de.resolve(n,...o),a=de.relative(n,s);if(a===".."||a.startsWith(`..${de.sep}`)||de.isAbsolute(a))throw new M("PATH_ESCAPED");let c;try{c=await promises.open(s,Fr);}catch(d){throw ye(d)}try{let d;try{let f=await c.stat({bigint:!0});d=An(f);}catch(f){throw ye(f)}if(d.size>BigInt(i)||d.size>BigInt(Number.MAX_SAFE_INTEGER))throw new M("LIMIT_EXCEEDED");await yn(n,r);let l=await Vr(n,r.realRoot,o);await It(s,r.realRoot,l,d);let p;try{let f=await c.stat({bigint:!0});p=An(f);}catch(f){throw ye(f)}if(!Si(d,p))throw new M("IDENTITY_CHANGED");return await It(s,r.realRoot,l,p),await yn(n,r),{...p,candidateRealPath:l??r.realRoot}}catch(d){throw d instanceof M?d:ye(d)}finally{await c.close().catch(()=>{});}}async readFileVerified(n,t,i){return this.readVerifiedFile(n,t,i)}},Br=new ht;});function vn(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 zr(e){return typeof e=="string"&&Se.test(e)?e:void 0}function Jp(e){return e.length>0&&e!=="."&&e!==".."&&!/[\\/\u0000]/.test(e)}function qe(e,n){let t=new TextEncoder().encode(e),i=new TextEncoder().encode(n),o=Math.min(t.byteLength,i.byteLength);for(let r=0;r<o;r+=1){let s=t[r]-i[r];if(s!==0)return s}return t.byteLength-i.byteLength}function Wp(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 o=n.isFile;return typeof o=="function"&&o.call(e)?{name:n.name,kind:"file"}:{name:n.name,kind:"other"}}function Kp(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 Xp(e){return $p.decode(e)}function Yp(e){return JSON.parse(Xp(e))}function $r(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 qp(e){if(e instanceof M)return $r(e.code);if(e!==null&&typeof e=="object"&&"code"in e){let n=e.code;if(typeof n=="string")return $r(n)}}function xe(e,n){let t=n();return Number.isFinite(t)&&Number.isFinite(e)&&t-e<=5e3}function Zp(e){if(typeof e.readVerifiedFile=="function")return e.readVerifiedFile;if(typeof e.readFileVerified=="function")return e.readFileVerified}function Qp(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 Gr(e,n,t,i){let o=Zp(e);if(!o)throw new M("READ_DENIED");return Kp(await o.call(e,n,t,i))}async function wi(e,n,t){let i=Qp(e);if(!i)throw new M("READ_DENIED");let o=await i.call(e,n,t);if(!Array.isArray(o))throw new M("READ_DENIED");return o.map(Wp).filter(r=>r!==null)}function el(e,n,t,i){return Object.freeze({code:e,...{},source:n,relativePath:t})}function nl(e){if(!vn(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,o)=>{if(!Array.isArray(i))throw new TypeError("productBundle.reservedIds."+o+" must be an array");let r=[];for(let s=0;s<i.length;s+=1){let a=i[s];if(typeof a!="string"||a.length===0)throw new TypeError("productBundle.reservedIds."+o+" must contain non-empty strings");r.push(a);}return Object.freeze([...new Set(r)].sort(qe))};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 tl(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 Et(e){return Object.freeze({appIds:Object.freeze([...new Set(e.map(n=>n.appId))].sort(qe)),definitionIds:Object.freeze([...new Set(e.map(n=>n.definition.id))].sort(qe))})}function _t(e,n){let t=Object.keys(e).sort(qe),i=[...n].sort(qe);return t.length===i.length&&t.every((o,r)=>o===i[r])}function Jr(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 il(e){let n;try{n=Yp(e);}catch{return}if(!vn(n)||!_t(n,["version","packages"])||n.version!==1||!Array.isArray(n.packages)||n.packages.length>Ci)return;let t=new Set,i=new Set,o=0,r=[];for(let s of n.packages){if(!vn(s))return;let a=["packageDir","appId","definition","files"],c=Object.hasOwn(s,"lineage"),d=Object.hasOwn(s,"launcher"),l=[...c?["lineage"]:[],...d?["launcher"]:[]];if(!_t(s,[...a,...l])||d&&s.launcher!==false)return;let p=Jr(s.packageDir),f=zr(s.appId);if(!p||p.length!==2||p[0]!=="apps"||!Jp(p[1])||!f||t.has(s.packageDir)||!vn(s.definition)||!_t(s.definition,["id","version","hash"]))return;let y=zr(s.definition.id),g=s.definition.version,_=s.definition.hash;if(!y||!Number.isSafeInteger(g)||g<1||typeof _!="string"||!Ri.test(_)||!Array.isArray(s.files)||s.files.length<2||s.files.length>Ui)return;let E=new Set,U=[];for(let k of s.files){if(!vn(k)||!_t(k,["path","sha256"]))return;let T=Jr(k.path);if(!T||typeof k.sha256!="string"||!Ri.test(k.sha256))return;let C=T.join("/"),B=`${s.packageDir}/${C}`;if(E.has(C)||i.has(B))return;E.add(C),i.add(B),U.push(Object.freeze({path:C,sha256:k.sha256}));}if(!Q.some(k=>E.has(k))||!E.has("ui/index.html")||(o+=U.length,o>Bp))return;t.add(s.packageDir),r.push(Object.freeze({packageDir:s.packageDir,...d?{launcher:false}:{},appId:f,definition:Object.freeze({id:y,version:g,hash:_}),lineage:Array.isArray(s.lineage)?s.lineage:[],files:Object.freeze(U.sort((k,T)=>qe(k.path,T.path)))}));}return Object.freeze({version:1,packages:Object.freeze(r)})}function Ye(e){let n=qp(e);return n==="PATH_ESCAPED"||n==="IDENTITY_CHANGED"||n==="TOCTOU"?"PATH_ESCAPED":n==="LIMIT_EXCEEDED"?"LIMIT_EXCEEDED":"BUNDLE_INTEGRITY"}async function ol(e,n,t,i,o){let r=[],s=async(a,c)=>{if(!xe(i,o))throw new M("LIMIT_EXCEEDED");if(c>2)throw new M("LIMIT_EXCEEDED");let d=await wi(e,n,a);for(let l of d){if(typeof l.name!="string"||l.name.length===0||l.name==="."||l.name===".."||/[\\/\u0000]/.test(l.name))throw new M("PATH_ESCAPED");let p=`${a}/${l.name}`;if(l.kind==="file"){if(r.push(p.slice(t.length+1)),r.length>Ui)throw new M("LIMIT_EXCEEDED")}else if(l.kind==="directory")await s(p,c+1);else throw l.kind==="symlink"?new M("PATH_ESCAPED"):new M("READ_DENIED")}};return await s(t,0),r.sort(qe)}function rl(e){return Q.includes(e)?262144:e==="ui/index.html"?fn:e==="ui/state.json"?2097152:e.startsWith("ui/assets/")?zp:Hp}async function Wr(e,n,t,i){if(e===void 0)return {packages:[],diagnostics:[],incomplete:false,reservedIds:Gp};let o=nl(e.reservedIds),r=[],s=(I,A,h)=>el(I,"bundled",A),a=(I=[],A=false,h)=>({...h===void 0?{}:{indexHash:h},packages:I,diagnostics:r,incomplete:A,reservedIds:o});if(typeof e.root!="string"||e.root.length===0||typeof e.expectedIndexHash!="string"||!Ri.test(e.expectedIndexHash))return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a();let c;try{c=await Gr(n,e.root,"bundle-index.json",Vp);}catch(I){return r.push(s(Ye(I),"bundle-index.json")),a()}let d=zi.createHash("sha256").update(c).digest("hex");if(d!==e.expectedIndexHash)return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a();let l=il(c);if(l===void 0)return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a();if(!tl(Et(l.packages),o))return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a([],false,d);if(!xe(t,i))return r.push(s("LIMIT_EXCEEDED","bundle-index.json")),a(l.packages.map(I=>({indexEntry:I,failureCode:"LIMIT_EXCEEDED"})),true,d);let p;try{p=await wi(n,e.root,"");}catch(I){return r.push(s(Ye(I),"bundle-index.json")),a(l.packages.map(A=>({indexEntry:A,failureCode:Ye(I)})),false,d)}if(!xe(t,i))return r.push(s("LIMIT_EXCEEDED","bundle-index.json")),a(l.packages.map(I=>({indexEntry:I,failureCode:"LIMIT_EXCEEDED"})),true,d);let f=p.find(I=>I.name==="bundle-index.json"&&I.kind==="file"),y=p.find(I=>I.name==="apps"&&I.kind==="directory"),g=I=>l.packages.map(A=>({indexEntry:A,failureCode:I}));if(!f)return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a(g("BUNDLE_INTEGRITY"),false,d);let _=p.filter(I=>I.name!=="bundle-index.json"&&I.name!=="apps");if(_.length>0){let I=_.some(A=>A.kind==="symlink")?"PATH_ESCAPED":"BUNDLE_INTEGRITY";return r.push(s(I,"bundle-index.json")),a(g("BUNDLE_INTEGRITY"),false,d)}if(p.some(I=>I.name==="apps"&&I.kind!=="directory"))return r.push(s("PATH_ESCAPED","apps")),a(g("PATH_ESCAPED"),false,d);let E=[];if(y)try{E=await wi(n,e.root,"apps");}catch(I){return r.push(s(Ye(I),"apps")),a(g(Ye(I)),false,d)}if(!xe(t,i)||E.length>Ci)return r.push(s("LIMIT_EXCEEDED","apps")),a(g("LIMIT_EXCEEDED"),true,d);let U=new Map(l.packages.map(I=>[I.packageDir.slice(5),I])),k=E.filter(I=>!U.has(I.name));for(let I of k)r.push(s(I.kind==="symlink"?"PATH_ESCAPED":"BUNDLE_INTEGRITY",`apps/${I.name}`));if(k.length>0){let I=k.some(A=>A.kind==="symlink")?"PATH_ESCAPED":"BUNDLE_INTEGRITY";return a(g(I),false,d)}let T=new Set,C=new Map,B=new Map;for(let I of l.packages){let A=C.get(I.appId)??[];A.push(I),C.set(I.appId,A);let h=`${I.definition.id}\0${String(I.definition.version)}`,b=B.get(h)??[];b.push(I),B.set(h,b);}for(let I of [...C.values(),...B.values()])if(I.length>1)for(let A of I)T.add(A);let N=[],D=c.byteLength,L=false;for(let I of l.packages){if(!xe(t,i)){L=true,N.push({indexEntry:I,failureCode:"LIMIT_EXCEEDED"});continue}let A;try{let V=I.lineage[I.lineage.length-1];if(!V)throw new we("LINEAGE_INVALID","Definition lineage is missing");if(V.definition.id!==I.definition.id||V.version!==I.definition.version||V.hash!==I.definition.hash)throw new we("LINEAGE_STALE","Last lineage generation does not match bundle identity");A=Ii(I.lineage,{...V.definition,hash:V.hash}).entries;}catch(V){let x=V instanceof we?V.code:"LINEAGE_INVALID";r.push(s(x,I.packageDir)),N.push({indexEntry:I,failureCode:x});continue}let h=E.find(V=>V.name===I.packageDir.slice(5));if(!y||!h){N.push({indexEntry:I,failureCode:"BUNDLE_INTEGRITY"});continue}if(h.kind!=="directory"){N.push({indexEntry:I,failureCode:h.kind==="symlink"?"PATH_ESCAPED":"BUNDLE_INTEGRITY"});continue}let b;try{let V=await ol(n,e.root,I.packageDir,t,i);if(!xe(t,i)){L=!0,N.push({indexEntry:I,failureCode:"LIMIT_EXCEEDED"});continue}let x=I.files.map(v=>v.path);if(V.length!==x.length||V.some((v,le)=>v!==x[le])){N.push({indexEntry:I,failureCode:"BUNDLE_INTEGRITY"});continue}b=new Map;let X;for(let v of I.files){if(!xe(t,i)){X="LIMIT_EXCEEDED",L=!0;break}if(D>=Oi){X="LIMIT_EXCEEDED";break}let le;try{le=await Gr(n,e.root,`${I.packageDir}/${v.path}`,rl(v.path));}catch(he){X=Ye(he);break}if(!xe(t,i)){X="LIMIT_EXCEEDED",L=!0;break}if(D+le.byteLength>Oi){D=Oi,X="LIMIT_EXCEEDED";break}if(D+=le.byteLength,zi.createHash("sha256").update(le).digest("hex")!==v.sha256){X="BUNDLE_INTEGRITY";break}b.set(v.path,le);}if(X!==void 0){N.push({indexEntry:I,failureCode:X});continue}}catch(V){xe(t,i)||(L=true),N.push({indexEntry:I,failureCode:Ye(V)});continue}N.push({indexEntry:I,lineage:A,files:b,...T.has(I)?{failureCode:"DUPLICATE_ID"}:{}});}return a(N,L,d)}var Vp,Ci,Ui,Bp,Hp,zp,Oi,Ri,$p,Gp,ki=j(()=>{m();gi();Je();ot();yt();Li();Vp=256*1024,Ci=64,Ui=128,Bp=Ci*Ui,Hp=2*1024*1024,zp=8*1024*1024,Oi=32*1024*1024,Ri=/^[0-9a-f]{64}$/,$p=new TextDecoder("utf-8",{fatal:true}),Gp=Object.freeze({appIds:Object.freeze([]),definitionIds:Object.freeze([])});});function al(e){if(typeof e!="string"||!Se.test(e))throw new TypeError("pluginId must be a safe UI plugin identifier");let n=`${xi}${e}`.length+7<=128?e:`hash_${zi.createHash("sha256").update(e,"utf8").digest("hex")}`;return {read:`${xi}${n}_read`,action:`${xi}${n}_action`}}function Xr(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 dl(e,n){return n.length===0||n==="."||n===".."||/[\\/\u0000]/.test(n)?e==="skills"?"skills":"apps":`${e==="skills"?"skills":"apps"}/${n}`}function pl(e){return e.length>0&&e!=="."&&e!==".."&&!/[\\/\u0000]/.test(e)}function Fn(e,n){let t=new TextEncoder().encode(e),i=new TextEncoder().encode(n),o=Math.min(t.byteLength,i.byteLength);for(let r=0;r<o;r+=1){let s=t[r]-i[r];if(s!==0)return s}return t.byteLength-i.byteLength}function ss(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 o=n.isFile;return typeof o=="function"&&o.call(e)?{name:n.name,kind:"file"}:{name:n.name,kind:"other"}}function ll(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 as(e){return cl.decode(e)}function ul(e){return JSON.parse(as(e))}function fl(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 Tt(e,n,t,i,o){let r={code:e,...i===void 0?{}:{pluginId:i},source:n,relativePath:t,...o?.reason===void 0?{}:{reason:Object.freeze({...o.reason})},...o?.files===void 0?{}:{files:Object.freeze([...o.files])}};return Object.freeze(r)}function Yr(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 se(e){if(e instanceof M)return Yr(e.code);if(e!==null&&typeof e=="object"&&"code"in e){let n=e.code;if(typeof n=="string")return Yr(n)}}function Qe(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 qr(e){return {reason:e.reason,...e.code==="MANIFEST_DUAL_MISMATCH"?{files:e.files}:{}}}function Zr(e){return e==="MANIFEST_DUAL_MISMATCH"?e:cs(e)}function yl(e){return cs(e.code)}function cs(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 ds("UiPluginValidationError",e)}}function ds(e,n){throw new Error(`Unmapped ${e} code: ${String(n)}`)}function ps(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 ds("McpAppContractError",e)}}function ve(e,n){let t=n();return Number.isFinite(t)&&Number.isFinite(e)&&t-e<=5e3}function Al(e){return {pluginId:e.appId,definitionKey:`${e.definition.id}\0${String(e.definition.version)}`}}function Il(e,n){let t=n.get("package.json");if(t!==void 0)try{let o=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(t));if(Xr(o)){let r=o.bin,s=typeof r=="string"?r:Xr(r)?Object.values(r).find(a=>typeof a=="string"):void 0;for(let a of [s,o.main]){if(typeof a!="string")continue;let c=gl(a);if(c&&n.has(c))return c}}}catch{}return [`${e.slice(e.lastIndexOf("/")+1)}.js`,"index.js","main.js"].find(o=>n.has(o))}function gl(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 ml(){return globalThis.performance?.now()??Date.now()}function Ze(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let n of Object.values(e))Ze(n);return Object.freeze(e)}function Qr(e){return Object.freeze(Array.from(e))}async function Vn(e,n,t,i){if(n.pinnedFiles!==void 0){let a=n.pinnedFiles.get(t);if(a===void 0)throw new M("NOT_FOUND");if(a.byteLength>i)throw new M("LIMIT_EXCEEDED");return new Uint8Array(a)}let o=`${n.relativePath}/${t}`,r=n.scanContext,s=e.fingerprintVerifiedFile;if(r===void 0||!r.cacheable||typeof s!="function")return is(e,n.root,o,i);try{let a=r.priorFingerprints.get(o)??await s.call(e,r.workspaceRoot,o,i);r.candidateRealPath=a.candidateRealPath;let c=await is(e,n.root,o,i),d=await s.call(e,r.workspaceRoot,o,i);return r.candidateRealPath=d.candidateRealPath,us(a,d)&&d.size===BigInt(c.byteLength)&&!fs(d,r.scanStartedAtNs)?r.files.set(o,{relativePath:o,byteLimit:i,fingerprint:d}):r.cacheable=!1,c}catch(a){let c=!t.includes("/")&&se(a)==="NOT_FOUND"&&r.directoryListings.some(l=>l.relativePath===n.relativePath&&!bt(l.key,t)),d=t===$&&se(a)==="NOT_FOUND"&&_l(r.directoryListings,n.relativePath);throw !c&&!d&&(r.cacheable=false),a}}async function hl(e,n,t){if(n.pinnedFiles!==void 0)return {iconDiagnostics:[]};let i=await Pn(t,async r=>{try{return await Vn(e,n,r,262144)}catch(s){let a=se(s);return a==="NOT_FOUND"?"missing":a==="LIMIT_EXCEEDED"?"too-large":"bad-path"}}),o=i.file;return {...o===void 0?{}:{iconFile:{path:o.path,sha256:zi.createHash("sha256").update(o.bytes).digest("hex"),contentType:o.contentType,byteLength:o.byteLength}},iconDiagnostics:i.diagnostics}}function _l(e,n){let t=e.find(o=>o.relativePath===n);if(t===void 0)return false;if(!bt(t.key,"dist"))return true;let i=e.find(o=>o.relativePath===`${n}/dist`);return i!==void 0&&!bt(i.key,"tools.json")}function ls(e,n){return JSON.stringify([e.realPath,n.source,n.relativePath])}async function Tl(e,n,t,i,o,r,s,a){let c=e.fingerprintVerifiedFile,d=ls(t,i),l=o.candidates.get(d),p=i.relativePath,f;try{f=await ts(e,n,p);}catch(L){if(se(L)!=="NOT_FOUND")throw L}let y=f===void 0?void 0:{relativePath:p,key:f};if(y!==void 0&&(i.source==="apps"||i.source==="skills")&&!Q.some(L=>bt(y.key,L)))return ve(s,a)?l!==void 0&&l.candidate===void 0&&l.candidateRealPath===void 0&&l.files.length===0&&l.directoryListings.length===1&&l.directoryListings[0]?.relativePath===y.relativePath&&l.directoryListings[0]?.key===y.key&&(i.source==="apps"?l.diagnostic?.code==="MANIFEST_MISSING":l.diagnostic===void 0)&&typeof c=="function"?{memo:l}:typeof c!="function"?{}:{context:{state:o,cacheKey:d,workspaceRoot:n,scanStartedAtNs:r,directoryListings:Object.freeze([y]),priorFingerprints:new Map,files:new Map,cacheable:true}}:{timeLimitReached:true};let g=async L=>{if(L==="")return y;let I=`${i.relativePath}${L}`;try{let A=await ts(e,n,I);return A===void 0?void 0:{relativePath:I,key:A}}catch(A){if(se(A)==="NOT_FOUND")return;throw A}},_=await Promise.all(es.map(g)),E=await Promise.all(El.map(g));if(!ve(s,a))return {timeLimitReached:true};let U=typeof c=="function"&&_.every(L=>L!==void 0),k=_.filter(L=>L!==void 0),T=[...k,...E.filter(L=>L!==void 0)],C=new Map,B=l!==void 0&&U,N;if(l!==void 0&&typeof c=="function"){let L=await Promise.all(l.files.map(async I=>{if(!ve(s,a))return {kind:"time",file:I};try{let A=await c.call(e,n,I.relativePath,I.byteLimit);return {kind:"fingerprint",file:I,current:A}}catch(A){return se(A)==="NOT_FOUND"?{kind:"missing",file:I}:{kind:"error",file:I,error:A}}}));if(L.some(I=>I.kind==="time"))return {timeLimitReached:true};for(let I of L){if(I.kind==="error")throw I.error;if(I.kind==="missing"){B=false;continue}if(I.kind!=="fingerprint")continue;let{file:A,current:h}=I;C.set(A.relativePath,h),N??=h.candidateRealPath,(h.candidateRealPath!==l.candidateRealPath||!us(h,A.fingerprint)||fs(h,r))&&(B=false);}}let D=l!==void 0&&l.directoryListings.length===T.length&&l.directoryListings.every((L,I)=>L.relativePath===T[I]?.relativePath&&L.key===T[I]?.key);return l!==void 0&&U&&D&&B&&N===l.candidateRealPath?{memo:l}:!U||k.length!==es.length?{}:{context:{state:o,cacheKey:d,workspaceRoot:n,scanStartedAtNs:r,directoryListings:Object.freeze(T),priorFingerprints:C,files:new Map,...N===void 0?{}:{candidateRealPath:N},cacheable:true}}}function bt(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 ts(e,n,t){let i=ys(e);if(typeof i!="function")return;let o=await i.call(e,n,t);if(!Array.isArray(o)||o.some(s=>typeof s=="string"))return;let r=o.map(ss);if(!r.some(s=>s===null))return JSON.stringify(r.slice().sort((s,a)=>Fn(s.name,a.name)||Fn(s.kind,a.kind)).map(s=>[s.name,s.kind]))}function us(e,n){return e.dev===n.dev&&e.ino===n.ino&&e.size===n.size&&e.mtimeNs===n.mtimeNs&&e.ctimeNs===n.ctimeNs}function fs(e,n){let t=e.mtimeNs-n;return t>=-ns&&t<=ns}function vi(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,o=t||i;if(n===void 0||!n.cacheable||n.candidateRealPath===void 0&&!o||n.files.size===0&&!o)return;let r=Object.freeze({...!o&&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,r);}function bl(e,n,t){let i=zi.createHash("sha256"),o=new TextEncoder().encode(te(e)),r=s=>{let a=new Uint8Array(8);new DataView(a.buffer).setBigUint64(0,BigInt(s)),i.update(a);};return r(o.byteLength),i.update(o),r(n.byteLength),i.update(n),r(t.byteLength),i.update(t),i.digest("hex")}function Pl(e,n){let t={...e.definition,sourceHash:n},i;try{i=ue(t);}catch(r){throw r instanceof w&&r.code==="INPUT_INVALID"?new ce("MANIFEST_INVALID","normalized definition is invalid"):r}let o={...t,hash:i};try{ge(o);}catch{throw new ce("MANIFEST_INVALID","normalized definition is invalid")}return o}function Nl(e,n){return e.actions.some(t=>t.backend.type==="core"&&t.backend.handler!=="state.set"&&!(t.backend.handler===Me&&(n??ie)===ie)&&!ct(n,t.backend))}function Dl(e){if(typeof e.readVerifiedFile=="function")return e.readVerifiedFile;if(typeof e.readFileVerified=="function")return e.readFileVerified}function ys(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 is(e,n,t,i){let o=Dl(e);if(!o)throw new M("READ_DENIED");return ll(await o.call(e,n,t,i))}async function Sl(e,n,t){let i=ys(e);if(!i)throw new M("READ_DENIED");let o=await i.call(e,n,t);if(!Array.isArray(o))throw new M("READ_DENIED");return o.map(ss).filter(r=>r!==null)}function Ml(e){let n=[];for(let t of [e.reserved,e.builtin])t&&n.push(t);return e.builtins&&"listMcpApps"in e.builtins?n.push(os(e.builtins)):e.builtins&&n.push(e.builtins),e.builtinCatalog&&n.push(os(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 os(e){let n=[],t=[],i=[];for(let o of e.listMcpApps())typeof o.appId=="string"&&n.push(o.appId),o.definition&&typeof o.definition.id=="string"&&t.push(o.definition.id);for(let o of e.listMcpAppTools())typeof o.name=="string"&&i.push(o.name);return {appIds:n,definitionIds:t,toolNames:i}}function Pe(e,n){e.diagnostic||(e.diagnostic=Tt(n,e.source,e.relativePath,e.identity?.pluginId));}function Ll(e,n){let t=new Set,i=new Map;for(let r of e){let s=r.identity?.pluginId;if(s===void 0)continue;let a=i.get(s)??[];a.push(r),i.set(s,a);}for(let r of i.values()){if(r.length<2)continue;let s=r.filter(c=>c.provenance!==void 0);if(s.length>0){let c=r.find(d=>n.has(d));if(c){for(let d of s)t.add(d);for(let d of r)d!==c&&d.provenance===void 0&&Pe(d,"RESERVED_ID");continue}for(let d of r)d.provenance===void 0&&Pe(d,"RESERVED_ID");if(s.length>1)for(let d of s)Pe(d,"DUPLICATE_ID");continue}let a=r.filter(c=>c.source==="apps");if(a.length>1){for(let c of a)Pe(c,"DUPLICATE_ID");for(let c of r.filter(d=>d.source==="skills"))Pe(c,"DUPLICATE_ID");}else for(let c of r.filter(d=>d.source==="skills"))Pe(c,"DUPLICATE_ID");}let o=new Map;for(let r of e){if(r.diagnostic?.code==="RESERVED_ID"||t.has(r)||r.provenance===void 0&&!n.has(r)&&i.get(r.identity?.pluginId??"")?.some(c=>c.provenance!==void 0))continue;let s=r.identity?.definitionKey;if(s===void 0)continue;let a=o.get(s)??[];a.push(r),o.set(s,a);}for(let r of o.values())if(r.length>1)for(let s of r)Pe(s,"DUPLICATE_ID");return t}function Ol(e,n,t){let i=new Set,o=new Set,r=new Set,s=new Set([...t.appIds,...n.productBundleReservationMetadata?.reservedAppIds??[]]),a=new Set([...t.definitionIds,...n.productBundleReservationMetadata?.reservedDefinitionIds??[]]);for(let l of Ml(n)){for(let p of l.appIds??[])typeof p=="string"&&i.add(p);for(let p of l.definitionIds??[])typeof p=="string"&&o.add(p);for(let p of l.toolNames??[])typeof p=="string"&&r.add(p);}for(let l of e){let p=l.candidate;if(!p)continue;if(i.has(p.pluginId)||o.has(p.definitionId)){Pe(l,"RESERVED_ID");continue}[p.toolNames.read,p.toolNames.action].filter(y=>y!==void 0).some(y=>r.has(y))&&Pe(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 p=l.candidate;if(!(!p||l.diagnostic||l.source!=="apps"||l.provenance!==void 0)&&e.filter(f=>f.source==="apps"&&f.identity?.pluginId===p.pluginId).length===1&&c.some(f=>f.pluginId===p.pluginId)&&!(a.has(p.definitionId)&&!c.some(f=>f.pluginId===p.pluginId&&f.definitionId===p.definitionId))&&!c.some(f=>f.pluginId!==p.pluginId&&f.definitionId===p.definitionId)&&!e.some(f=>f.identity?.pluginId!==p.pluginId&&f.identity?.definitionKey===`${p.definitionId}\0${p.version}`&&f.diagnostic?.code!=="RESERVED_ID"))try{Cr(p),d.add(l);}catch(f){Pe(l,f instanceof Re?ps(f.code):"EXEC_DENIED");}}for(let l of e){let p=l.candidate;p&&l.provenance===void 0&&!d.has(l)&&(s.has(p.pluginId)||a.has(p.definitionId))&&Pe(l,"RESERVED_ID");}return d}function Rl(e){return [...e].sort((n,t)=>{let i=Kr.indexOf(n.source)-Kr.indexOf(t.source);return i!==0?i:Fn(n.relativePath,t.relativePath)})}function H(e,n,t){e.diagnostic=Tt(n,e.source,e.relativePath,e.identity?.pluginId,t);}async function rs(e,n,t){let i=ze(t,{mode:"local"});if(!i.ok&&i.parseFailure){H(n,Zr(i.rejection.code),qr(i.rejection));return}let o=fl(i.identity);if(n.bundleIdentity===void 0)n.identity=o;else if(o?.pluginId!==n.bundleIdentity.appId||o.definitionKey!==`${n.bundleIdentity.definitionId}\0${String(n.bundleIdentity.version)}`){H(n,"BUNDLE_INTEGRITY");return}if(!i.ok&&i.builtinOnly){H(n,"RESERVED_ID");return}if(!i.ok){H(n,Zr(i.rejection.code),qr(i.rejection));return}let r=i.manifest,s={pluginId:r.pluginId,definitionKey:`${r.definitionId}\0${String(r.version)}`};if(n.bundleIdentity===void 0&&(n.identity=s),r.actions.length>0)try{Ei(r.actions.map(x=>({actionId:x.actionId,inputSchema:x.inputSchema})));}catch(x){if(x instanceof Re){H(n,ps(x.code));return}throw x}let a;try{a=await Vn(e,n,"ui/index.html",fn);}catch(x){H(n,Qe(se(x),"entry"));return}if(a.byteLength>fn){H(n,"LIMIT_EXCEEDED");return}let c;try{c=as(a);}catch{H(n,"ENTRY_INVALID");return}if(a.byteLength===0||c.length===0){H(n,"ENTRY_INVALID");return}let d=zi.createHash("sha256").update(a).digest("hex");if(r.entryHash!==void 0&&r.entryHash!==d){H(n,"ENTRY_INVALID");return}let l={},p,f;if(r.initialState!==void 0){try{p=await Vn(e,n,"ui/state.json",2097152);}catch(x){H(n,Qe(se(x),"initial"));return}if(p.byteLength>2097152){H(n,"LIMIT_EXCEEDED");return}try{let x=ul(p),X=r.dataPaths??[],v=ii(x,X);l=Ie(v,0,X),on(l);}catch{H(n,"INITIAL_STATE_INVALID");return}if(f=zi.createHash("sha256").update(p).digest("hex"),r.initialState.hash!==void 0&&r.initialState.hash!==f){H(n,"INITIAL_STATE_INVALID");return}}let y={...r,entryHash:d,...r.initialState===void 0?{}:{initialState:{path:"ui/state.json",hash:f}}},g=Tn(y),_=bl(y,a,p??new Uint8Array),E;try{E=Pl(g,_);}catch(x){if(x instanceof ce){H(n,yl(x));return}throw x}let U;if(n.bundleLineage!==void 0){let x=n.bundleLineage[n.bundleLineage.length-1];if(!x){H(n,"LINEAGE_INVALID");return}let{legacy:X,...v}=x.definition,{hash:le,...he}=E;if(te(v)!==te(he)){H(n,"LINEAGE_STALE");return}if(X!==void 0&&(E={...E,legacy:X}),X!==void 0)try{E={...E,hash:ue(E)},ge(E);}catch{H(n,"LINEAGE_INVALID");return}U=n.bundleLineage;}if(n.bundleIdentity!==void 0&&n.bundleIdentity.appId!==r.pluginId){H(n,"BUNDLE_INTEGRITY");return}if(n.bundleIdentity!==void 0&&(n.bundleIdentity.definitionId!==E.id||n.bundleIdentity.version!==E.version||n.bundleIdentity.definitionHash!==E.hash)){H(n,"LINEAGE_STALE");return}let k=await hl(e,n,i.mcpb?.icon),T=al(r.pluginId),C=r.actions.length===0?{read:T.read}:T,B=Ze(g),N=Ze(y),D=Ze(E),L=Ze({...g.handlers}),I=Qr(a),A=p===void 0?void 0:Qr(p),h=Object.freeze({...n.provenance===void 0?{}:{provenance:n.provenance},entry:Object.freeze({path:"ui/index.html",hash:d,bytes:I}),...A===void 0?{}:{initialState:Object.freeze({path:"ui/state.json",hash:f,bytes:A})}}),b={appId:r.pluginId,pluginId:r.pluginId,definitionId:r.definitionId,version:r.version,...i.releaseVersion===void 0?{}:{releaseVersion:i.releaseVersion},manifestFile:i.file,...i.mcpb===void 0?{}:{mcpb:Ze(i.mcpb)},relativePath:n.relativePath,manifest:N,normalized:B,name:r.name,description:r.description,...r.icon===void 0?{}:{icon:r.icon},...r.tone===void 0?{}:{tone:r.tone},...k.iconFile===void 0?{}:{iconFile:Object.freeze({...k.iconFile})},...k.iconDiagnostics.length===0?{}:{iconDiagnostics:Object.freeze([...k.iconDiagnostics])},definition:D,handlers:L,resources:h,html:c,entryBytes:I,entryHash:d,initialState:Ze(l),...A===void 0?{}:{initialStateBytes:A},...f===void 0?{}:{initialStateHash:f},sourceHash:_,toolNames:Object.freeze(C)},V=n.provenance===void 0?{...b,source:n.source}:{...b,provenance:n.provenance,lineage:U??[]};n.candidate=Object.freeze(V),Nl(r,E.usage)&&H(n,"EXEC_DENIED");}async function As(e,n){let t={};for(let i of Q)try{t[i]=await Vn(e,n,i,262144);}catch(o){if(se(o)==="NOT_FOUND")continue;return {files:t,failure:Qe(se(o),"manifest")}}if(t[W]!==void 0)try{t[$]=await Vn(e,n,$,262144);}catch(i){if(se(i)!=="NOT_FOUND")return {files:t,failure:Qe(se(i),"manifest")}}return {files:t}}function ji(e){return Q.some(n=>e[n]!==void 0)}async function wl(e,n){let{files:t,failure:i}=await As(e,n);if(i!==void 0){H(n,i);return}let o=t[W];return o!==void 0&&!pi(o)&&(delete t[W],delete t[$]),ji(t)?t:void 0}function Cl(e,n,t,i=sl,o=false,r=new Set){let s=Rl(e),a=Ll(s,r),c=Object.freeze(s.filter(f=>f.candidate!==void 0&&f.diagnostic===void 0&&!a.has(f)).map(f=>f.candidate)),d=Object.freeze(s.filter(f=>f.diagnostic!==void 0).map(f=>f.diagnostic)),l=o?Object.freeze({...t===void 0?{}:{indexHash:t},candidates:Object.freeze(s.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,p={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(p,"candidates",{configurable:false,enumerable:false,get:()=>c}),Object.freeze(p)}function Ul(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 kl(e,n){if(Ul(e))return {fs:e,options:{}};let t=e??n??{};return {fs:t.filesystem??t.fileSystem??t.fs??Br,options:t}}async function Is(e,n,t){if(typeof e!="string"||e.length===0)throw new TypeError("workspaceRoot must be explicit");let{fs:i,options:o}=kl(n,t),r=o.clock??ml,s=r(),a=await Wr(o.productBundle,i,s,r),c=r(),d=BigInt(Date.now())*1000000n,l=[],p=0,f,y=false,g,_;if(o.scanCache!==void 0&&typeof i.getRootIdentity=="function"&&typeof i.fingerprintVerifiedFile=="function")try{_=await i.getRootIdentity(e),g=xr(o.scanCache,_),g.scanStartedAtNs=d;}catch(N){if(se(N)!=="NOT_FOUND")throw N}let E=g!==void 0&&o.productBundle===void 0&&a.packages.length===0&&a.diagnostics.length===0,U=new Set,k=true;l.push(...a.diagnostics.map(N=>({source:N.source,root:o.productBundle?.root??e,name:"",relativePath:N.relativePath,diagnostic:N})));let T=a.reservedIds;a.incomplete&&(f="time_limit");for(let N of a.packages){if(!ve(c,r)){y=true,f="time_limit";break}let D=N.indexEntry,L=D.packageDir,I=N.files===void 0?void 0:Il(L,N.files),A=a.indexHash===void 0?void 0:cr(Object.freeze({kind:"bundled",launcher:D.launcher!==false,indexHash:a.indexHash,packageDir:L,appId:D.appId,definitionId:D.definition.id,version:D.definition.version,definitionHash:D.definition.hash,files:D.files}),I),h={source:"bundled",root:o.productBundle?.root??e,name:L.slice(5),relativePath:L,...A===void 0?{}:{provenance:A},...N.files===void 0?{}:{pinnedFiles:N.files},...N.lineage===void 0?{}:{bundleLineage:N.lineage},bundleIdentity:{appId:D.appId,definitionId:D.definition.id,version:D.definition.version,definitionHash:D.definition.hash},identity:Al(D)};if(l.push(h),p+=1,N.failureCode!==void 0){H(h,N.failureCode);continue}if(N.files?.has($)===true){H(h,"EXEC_DENIED",{reason:{path:"",rule:"bundled-tool-mode-unsupported",file:$}});continue}let b={};for(let V of Q){let x=N.files?.get(V);x!==void 0&&(b[V]=x);}if(!ji(b)){H(h,"BUNDLE_INTEGRITY");continue}if(await rs(i,h,b),!ve(c,r)){y=true,f="time_limit";break}}let C=[{source:"apps",directory:"apps"},{source:"skills",directory:"skills"}];e:for(let N of C){let{source:D,directory:L}=N,I;try{I=await Sl(i,e,L);}catch(h){if(se(h)==="NOT_FOUND")continue;E=false,k=false,l.push({source:D,root:e,name:"",relativePath:D,diagnostic:Tt(Qe(se(h),"manifest"),D,D)});continue}let A=I.filter(h=>h.kind==="directory"||h.kind==="symlink").filter(h=>pl(h.name)).map(h=>({source:D,root:e,name:h.name,relativePath:dl(D,h.name)})).sort((h,b)=>Fn(h.relativePath,b.relativePath));for(let h of A){let b={...h};if(l.push(b),_!==void 0?U.add(ls(_,b)):E=false,!ve(c,r)){y=true,f="time_limit";break e}let V;if(g!==void 0&&_!==void 0){try{let v=await Tl(i,e,_,b,g,d,c,r);if(v.timeLimitReached){y=!0,f="time_limit";break e}b.scanContext=v.context,V=v.memo;}catch(v){E=false,H(b,Qe(se(v),"manifest"));continue}V===void 0&&(E=false);}if(V!==void 0){if(b.candidate=V.candidate,b.diagnostic=V.diagnostic,b.identity=V.identity,D==="skills"&&V.candidate===void 0&&V.diagnostic===void 0)continue;if(p>=64){H(b,"LIMIT_EXCEEDED");continue}if(h.relativePath.split("/").length-1>2){H(b,"LIMIT_EXCEEDED");continue}if(p+=1,!ve(c,r)){y=true,f="time_limit";break e}continue}let x;if(D==="skills"&&(x=await wl(i,b),x===void 0)){b.diagnostic===void 0&&vi(b);continue}if(p>=64){H(b,"LIMIT_EXCEEDED");continue}if(h.relativePath.split("/").length-1>2){H(b,"LIMIT_EXCEEDED");continue}if(!ve(c,r)){y=true,f="time_limit";break e}if(p+=1,x===void 0){let v=await As(i,b);if(v.failure!==void 0||!ji(v.files)){H(b,v.failure??Qe("NOT_FOUND","manifest")),vi(b);continue}x=v.files;}if(await rs(i,b,x),vi(b),!ve(c,r)){y=true,f="time_limit";break e}}}if(g!==void 0&&_!==void 0){let N=[...U].sort(Fn),D=g.lastCandidateKeys,L=D!==void 0&&D.length===N.length&&D.every((A,h)=>A===N[h]);if(E=E&&L,k&&!y&&f===void 0)for(let A of g.candidates.keys())try{JSON.parse(A)[0]===_.realPath&&!U.has(A)&&g.candidates.delete(A);}catch{g.candidates.delete(A);}let I=[...g.candidates.keys()].filter(A=>{try{return JSON.parse(A)[0]===_.realPath}catch{return false}});E=E&&I.length===U.size&&I.every(A=>U.has(A))&&!y&&f===void 0,g.lastCandidateScanUnchanged=E,k&&!y&&f===void 0&&(g.lastCandidateKeys=Object.freeze(N));}y&&l.push({source:"apps",root:e,name:"",relativePath:"apps",diagnostic:Tt("DISCOVERY_TIME_LIMIT","apps","apps")});let B=Ol(l,o,T);return Cl(l,f,a.indexHash,T,o.productBundle!==void 0,B)}var sl,xi,Kr,cl,es,El,ns,gs=j(()=>{m();We();Hn();Ce();sn();fi();ui();Je();yt();Ur();dt();st();vr();Li();at();ki();ki();sl=Et([]),xi="crewx_local_app_";Kr=["bundled","apps","skills"],cl=new TextDecoder("utf-8",{fatal:true});es=["","/ui"],El=["/dist"],ns=2000000000n;});m();fi();m();sn();m();var Xo="SKILL.md",Gd=/^---\s*\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;function Yo(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function Jd(e){return e.isDirectory()||e.isSymbolicLink()}function nr(e){try{return ne.existsSync(e)&&ne.statSync(e).isDirectory()}catch{return false}}function yi(e){let n;try{n=ne.readFileSync(e,"utf8");}catch{return {frontmatter:{},readable:false,valid:false,hasFrontmatter:false}}let t=n.match(Gd);if(!t)return {frontmatter:{},readable:true,valid:true,hasFrontmatter:false};try{let i=Rs.load(t[1]??"");if(!Yo(i))return {frontmatter:{},readable:!0,valid:!1,hasFrontmatter:!0};let o=Yo(i.metadata)?i.metadata:void 0;return {frontmatter:{...typeof i.name=="string"?{name:i.name}:{},...typeof(o?.version??i.version)=="string"?{version:o?.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 Wd(e){return [de.join(e,Xo),de.join(e,"skill",Xo)]}function qo(e,n){if(!nr(e))return null;for(let t of Wd(e)){if(!ne.existsSync(t))continue;let o=yi(t).frontmatter;return {name:o.name??n,...o.version===void 0?{}:{version:o.version},...o.description===void 0?{}:{description:o.description},skillMdPath:t,dir:e}}return null}function Zo(e){try{return ne.readdirSync(e,{withFileTypes:!0}).filter(Jd)}catch{return []}}function Qo(e,n,t){!e||n.has(e.name)||(n.add(e.name),t.push(e));}function tr(e){let n=[],t=new Set;for(let i of e)if(nr(i))for(let o of Zo(i)){if(o.name.startsWith("@")){let r=de.join(i,o.name);for(let s of Zo(r))Qo(qo(de.join(r,s.name),s.name),t,n);continue}Qo(qo(de.join(i,o.name),o.name),t,n);}return n.sort((i,o)=>i.name.localeCompare(o.name))}m();ot();var Kd=/^[A-Za-z0-9_$.[\]"-]{0,200}$/,Xd=/^[a-z][a-z0-9-]{0,63}$/,Yd="<unknown>";function qd(e){return typeof e=="string"&&(Q.includes(e)||e===$)}function ir(e){if(typeof e!="object"||e===null)return;let{file:n,path:t,rule:i}=e;if(!(typeof i!="string"||!Xd.test(i)))return {...qd(n)?{file:n}:{},path:typeof t=="string"&&Kd.test(t)?t:Yd,rule:i}}function or(e){if(!Array.isArray(e))return;let n=Q.filter(t=>e.includes(t));return n.length>0?n:void 0}gs();var vl=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/;function Dt(e){let n="screenHash"in e?e.screenHash:void 0,i=("skillHash"in e?e.skillHash:void 0)??(e.relativePath!==void 0&&e.fileBytes!==void 0?jl(e.relativePath,e.fileBytes):void 0);if(n!==void 0&&i!==void 0){let o=JSON.stringify({screenHash:n,skillHash:i});return zi.createHash("sha256").update(o,"utf8").digest("hex")}if(n!==void 0)return n;if(i!==void 0)return i;throw new TypeError("App definition hash input must contain a screenHash or skill bytes")}function jl(e,n){let t=new TextEncoder().encode(St(e)),i=Fl(n),o=new Uint8Array(t.byteLength+1+i.byteLength);return o.set(t,0),o[t.byteLength]=0,o.set(i,t.byteLength+1),zi.createHash("sha256").update(o).digest("hex")}function Fl(e){if(typeof e=="string")return new TextEncoder().encode(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("fileBytes must be UTF-8 text or bytes")}function St(e){if(typeof e!="string"||e.length===0||de.isAbsolute(e)||/[\\\u0000]/.test(e))throw new TypeError("relative path must be package-relative");let n=e.split("/").filter(t=>t.length>0&&t!==".").join("/");if(!n||n.split("/").some(t=>t===".."))throw new TypeError("relative path must stay inside the package");return n}function Pt(e,n){let t=new TextEncoder().encode(e),i=new TextEncoder().encode(n),o=Math.min(t.byteLength,i.byteLength);for(let r=0;r<o;r+=1){let s=t[r]-i[r];if(s!==0)return s}return t.byteLength-i.byteLength}function _s(e,n){let t=de.relative(e,n).split(de.sep).join("/");return !t||t===".."||t.startsWith("../")||de.isAbsolute(t)?null:St(t)}function Vl(e){return e==="apps"||e.startsWith("apps/")?"apps":e==="skills"||e.startsWith("skills/")?"skills":e==="node_modules"||e.startsWith("node_modules/")?"node_modules":null}function Es(e){return Object.freeze({packageRoot:e})}function Bl(e){return Object.freeze({id:e.definition.id,version:e.definition.version,hash:e.definition.hash,usage:e.definition.usage??ie,...e.definition.detailPanel===void 0?{}:{detailPanel:e.definition.detailPanel},...e.definition.displayModes===void 0?{}:{displayModes:e.definition.displayModes},...e.definition.summaryProjection===void 0?{}:{summaryProjection:e.definition.summaryProjection}})}function Ts(e){return {capabilities:Object.freeze([...e]),origin:"local",ownership:"unknown",shareability:"unknown",sharingAvailability:"unavailable"}}function Hl(e,n){let t=e.candidate,i=t.provenance!==void 0,o=n&&!i?["screen","skill"]:["screen"],r=Bl(t),s=Dt(n?{screenHash:r.hash,skillHash:n.skillHash}:{screenHash:r.hash}),a=t.description||n?.skill.description||"",c=t.releaseVersion??String(t.version),d={appId:t.pluginId,name:t.name,description:a,version:c,...Ts(o),definition:r,...n===void 0||i?{}:{skillName:n.skill.name},...i?{provenance:t.provenance}:{localDefinitionRef:Es(e.packageRoot)},definitionHash:s,...t.manifest.csp===void 0?{}:{connectDomains:Object.freeze([...t.manifest.csp.connectDomains])}};return {...i?{}:{packageRoot:e.packageRoot},source:i?"bundled":t.source,appId:d.appId,capabilities:o,summary:Object.freeze(d)}}function zl(e){let n=$l(e.skill.name),t={appId:n,name:e.skill.name,description:e.skill.description??"",...e.skill.version===void 0?{}:{version:e.skill.version},...Ts(["skill"]),skillName:e.skill.name,localDefinitionRef:Es(e.packageRoot),definitionHash:Dt({skillHash:e.skillHash})};return {packageRoot:e.packageRoot,source:e.source,appId:n,capabilities:["skill"],summary:Object.freeze(t)}}function $l(e){return `skill.${e.replace(/^@/,"").replace(/\//g,".").replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,122)||"unnamed"}`}function Z(e,n,t,i,o){let r=ir(o?.reason),s=or(o?.files);return Object.freeze({code:e,source:n,relativePath:Gl(t),...i===void 0?{}:{appId:i},...r===void 0?{}:{reason:r},...s===void 0?{}:{files:s}})}function Gl(e){if(typeof e!="string"||e.length===0||de.isAbsolute(e)||/[\\\u0000]/.test(e))return "<unknown>";let n=e.split("/").filter(t=>t.length>0&&t!==".").join("/");return n.split("/").some(t=>t==="..")?"<unknown>":n}function bs(e){return Z(e.code,e.source,e.relativePath,e.pluginId,e)}function Jl(e,n){let t=_s(e,n.dir);if(!t)return {diagnostic:Z("PATH_ESCAPED","node_modules","node_modules")};let i=Vl(t);if(!i)return {diagnostic:Z("PATH_ESCAPED","node_modules",t)};let o=yi(n.skillMdPath);if(!o.readable)return {diagnostic:Z("SKILL_READ_FAILED",i,t)};if(!o.valid)return {diagnostic:Z("SKILL_INVALID",i,t)};let r=Wl(n.dir,n.skillMdPath);if(!r)return {diagnostic:Z("PATH_ESCAPED",i,t)};try{let s=new Uint8Array(ne.readFileSync(n.skillMdPath));return {skill:n,packageRoot:t,relativeSkillPath:r,skillHash:Dt({relativePath:r,fileBytes:s}),source:i}}catch{return {diagnostic:Z("SKILL_READ_FAILED",i,t)}}}function Wl(e,n){let t=de.relative(e,n).split(de.sep).join("/");try{return St(t)}catch{return null}}function Kl(e){if(!vl.test(e.appId))return {diagnostic:Z("BUILTIN_INVALID","builtin",`builtin/${e.appId||"unknown"}`)};let n=e.definition===void 0?void 0:{id:e.definition.id,version:e.definition.version,hash:e.definition.hash,usage:e.definition.usage??ie,...e.definition.detailPanel===void 0?{}:{detailPanel:e.definition.detailPanel},...e.definition.displayModes===void 0?{}:{displayModes:e.definition.displayModes},...e.definition.summaryProjection===void 0?{}:{summaryProjection:e.definition.summaryProjection}},t=n?.hash??zi.createHash("sha256").update(JSON.stringify({appId:e.appId,name:e.name,description:e.description}),"utf8").digest("hex"),i={appId:e.appId,name:e.name,description:e.description,...n===void 0?{}:{version:String(n.version),definition:n},capabilities:["screen"],origin:"builtin",ownership:"unknown",shareability:"forbidden",sharingAvailability:"unavailable",definitionHash:t};return {source:"builtin",appId:e.appId,summary:Object.freeze(i)}}function Xl(e){return e.builtinCatalog}function Yl(e){let n=e.packageRoot??e.relativePath??e.packageRootPath;if(n===void 0)return null;try{return St(n)}catch{return null}}function ql(e){let n=e.marketplaceContentId;return typeof n=="string"&&n.length>0?n:void 0}function Zl(e,n,t){let i=n.installed??[],o=new Map;for(let s of i){let a=Yl(s);if(!a){t.push(Z("INSTALLED_IDENTITY_MISMATCH","installed","installed"));continue}let c=o.get(a);if(c&&JSON.stringify(c)!==JSON.stringify(s)){t.push(Z("INSTALLED_IDENTITY_MISMATCH","installed",a));continue}o.set(a,s);}let r=new Map;for(let s of e)s.packageRoot!==void 0&&r.set(s.packageRoot,s);for(let[s,a]of o){let c=r.get(s);if(!c){t.push(Z("INSTALLED_MISSING","installed",s,a.appId));continue}let d=ql(a);if(!d){t.push(Z("INSTALLED_CONTENT_ID_MISSING","installed",s,a.appId));continue}if(a.appId!==void 0&&a.appId!==c.appId||a.definitionHash!==void 0&&a.definitionHash!==c.summary.definitionHash){t.push(Z("INSTALLED_IDENTITY_MISMATCH","installed",s,a.appId));continue}let l={...c.summary,origin:"installed",...a.slug===void 0?{}:{slug:a.slug},marketplaceContentId:d},p=e.indexOf(c);p>=0&&(e[p]={...c,summary:Object.freeze(l)});}}function Ql(e,n){let t=new Map;for(let o of e){let r=t.get(o.appId)??[];r.push(o),t.set(o.appId,r);}let i=new Set;for(let o of t.values()){if(o.length<2)continue;let r=o.some(s=>s.source==="builtin")?"builtin":o.some(s=>s.source==="bundled")?"bundled":void 0;if(r==="bundled"){let s=o.filter(a=>a.source==="apps"&&a.summary.definition!==void 0);if(s.length===1){for(let a of o)a.source==="bundled"?i.add(a):a!==s[0]&&(i.add(a),n.push(Z("RESERVED_ID",a.source,Nt(a),a.appId)));continue}}if(r!==void 0){let s=o.filter(a=>a.source===r);for(let a of o.filter(c=>c.source!==r))i.add(a),n.push(Z("RESERVED_ID",a.source,Nt(a),a.appId));if(s.length>1)for(let a of s)i.add(a),n.push(Z("DUPLICATE_ID",a.source,Nt(a),a.appId));continue}for(let s of o)i.add(s),n.push(Z("DUPLICATE_ID",s.source,Nt(s),s.appId));}return e.filter(o=>!i.has(o))}function Nt(e){return e.packageRoot??e.summary.provenance?.packageDir??`builtin/${e.appId}`}function eu(e,n){return e.filter(t=>!(t.code==="MANIFEST_MISSING"&&n.has(t.relativePath))).map(bs)}function nu(e){return e.filesystem}function tu(e,n){let t=nu(e),i=e.registeredProductBundle;return {...t===void 0?{}:{filesystem:t},...e.productBundle===void 0?{}:{productBundle:e.productBundle},...n===void 0?{}:{builtinCatalog:n},...i===void 0?{}:{productBundleReservationMetadata:i}}}async function Ps(e,n={}){if(typeof e!="string"||e.length===0)throw new TypeError("workspaceRoot must be explicit");if(n.productBundle!==void 0&&n.registeredProductBundle!==void 0)throw new TypeError("registeredProductBundle cannot be combined with product bundle discovery");let t=Xl(n),i=await Is(e,tu(n,t)),o=n.registeredProductBundle??i.productBundleSnapshotMetadata,r=[de.join(e,"skills"),de.join(e,"node_modules"),de.join(e,"apps")],s=[],a=[],c=[],d=new Set;for(let A of r)for(let h of tr([A])){let b=_s(e,h.dir);(b===null||!d.has(b))&&(c.push(h),b!==null&&d.add(b));}for(let A of c){let h=Jl(e,A);"diagnostic"in h?s.push(h.diagnostic):a.push(h);}let l=new Map,p=n.registeredProductBundle?.indexHash,f=(n.registeredProductBundle?.candidates??[]).filter(A=>p!==void 0&&A.provenance?.indexHash===p),y=[...new Set([...i.apps??i.candidates??[],...i.productBundleSnapshotMetadata?.candidates??[]]),...f],g=new Set(f),_=new Set(p===void 0?[]:(t?.listMcpApps()??[]).filter(A=>A.provenance?.indexHash===p).map(A=>A.appId));for(let A of y){if(g.has(A)&&A.provenance?.indexHash===p&&_.has(A.appId))continue;let h=A.provenance===void 0?`workspace\0${A.relativePath}`:`bundled\0${A.provenance.indexHash}\0${A.provenance.packageDir}`;l.set(h,{candidate:A,packageRoot:A.relativePath});}let E=new Map(a.map(A=>[A.packageRoot,A])),U=[];for(let A of l.values()){let h=A.candidate.provenance===void 0?E.get(A.packageRoot):void 0,b=Hl(A,h);U.push({...b.packageRoot===void 0?{}:{packageRoot:b.packageRoot},source:b.source,appId:b.appId,summary:b.summary});}let k=new Set([...l.values()].filter(A=>A.candidate.provenance===void 0).map(A=>A.packageRoot)),T=o===void 0?new Set:new Set(i.diagnostics.filter(A=>A.code==="RESERVED_ID"&&A.source!=="bundled").map(A=>A.relativePath)),C=new Set(o?.reservedAppIds??[]);for(let A of a){let h=zl(A);if(!(k.has(A.packageRoot)||T.has(A.packageRoot))){if(C.has(h.appId)){s.push(Z("RESERVED_ID",A.source,A.packageRoot,h.appId));continue}U.push({packageRoot:h.packageRoot,source:h.source,appId:h.appId,summary:h.summary});}}let B=[...eu(i.diagnostics,new Set(a.map(A=>A.packageRoot))),...s,...n.registeredProductBundle?.diagnostics.filter(A=>A.source==="bundled").map(bs)??[]],N=[];if(t)for(let A of t.listMcpApps()){let h=Kl(A);"diagnostic"in h?B.push(h.diagnostic):N.push(h);}let D=Ql([...U,...N],B);Zl(D,n,B);let L=D.map(A=>A.summary).sort((A,h)=>Pt(A.appId,h.appId)),I=[...B].sort((A,h)=>Pt(A.relativePath,h.relativePath)||Pt(A.code,h.code)||Pt(A.appId??"",h.appId??""));return Object.freeze({items:Object.freeze(L),diagnostics:Object.freeze(I)})}m();m();m();function iu(e){let n=o=>o.replace(/[.+^${}()|[\]\\]/g,"\\$&"),i=e.split("/").map(o=>o==="**"?".*":o.split("*").map(n).join("[^/]*"));return new RegExp(`^${i.join("\\/")}$`)}function In(e,n){try{return iu(n).test(e)}catch{return false}}function Mt(e,...n){let t=e.split("/");if(t.length<n.length)return false;let i=t.length-n.length;return n.every((o,r)=>In(t[i+r],o))}function ou(e,n){return e.split("/").some(t=>In(t,n))}var Ns=[{label:".env*",test:e=>In(e,".env*")},{label:".git/",test:(e,n,t)=>t&&e===".git"},{label:"memory/",test:(e,n,t)=>t&&e==="memory"},{label:"*.key",test:e=>In(e,"*.key")},{label:"*.pem",test:e=>In(e,"*.pem")},{label:"auth.json",test:e=>e==="auth.json"},{label:"node_modules/",test:(e,n,t)=>t&&e==="node_modules"},{label:"conversations/",test:(e,n,t)=>t&&e==="conversations"},{label:".crewx/threads/",test:(e,n,t)=>t&&Mt(n,".crewx","threads")},{label:".crewx/crewx.db",test:(e,n,t)=>!t&&Mt(n,".crewx","crewx.db")},{label:".crewx/*.log",test:(e,n,t)=>!t&&Mt(n,".crewx","*.log")},{label:".crewx/publish/",test:(e,n,t)=>t&&Mt(n,".crewx","publish")},{label:".crewx/",test:(e,n)=>ou(n,".crewx")}];function gn(e,n,t){for(let i of Ns)if(i.test(e,n,t))return i.label;return null}m();var je=class extends Error{constructor(t,i){super(`publish: [${t}]${i?` ${i}`:""}`);this.code=t;}code;name="PublishError"};function P(e,n){return new je(e,n)}function Ds(e,n){if(!n||/[\\\u0000]/.test(n)||de__namespace.posix.isAbsolute(n)||n.split("/").some(y=>!y||y==="."||y===".."))throw P("PACKAGE_PATH_TRAVERSAL","package root must be a safe workspace-relative path");let t=de__namespace.resolve(e),i=de__namespace.resolve(t,...n.split("/"));if(!i.startsWith(`${t}${de__namespace.sep}`))throw P("PACKAGE_PATH_TRAVERSAL","package root escaped the workspace");function o(y,g){let _;try{_=ne__namespace.lstatSync(y);}catch{throw P("PACKAGE_FILE_INVALID",`package directory is missing: ${g}`)}if(_.isSymbolicLink())throw P("PACKAGE_SYMLINK",`symlink is not publishable: ${g}`);if(!_.isDirectory())throw P("PACKAGE_FILE_INVALID",`not a package directory: ${g}`)}o(t,".");let r=t,s="",a=null;for(let y of n.split("/"))r=de__namespace.join(r,y),s=s?`${s}/${y}`:y,o(r,s),a??=gn(y,s,true);let c=[],d=[];function l(y,g){o(y,g);let _=ne__namespace.readdirSync(y,{withFileTypes:true});for(let E of _){let U=`${g}/${E.name}`,k=de__namespace.join(y,E.name);if(E.isSymbolicLink())throw P("PACKAGE_SYMLINK",`symlink is not publishable: ${U}`);let T=gn(E.name,U,E.isDirectory());T?d.push({path:U,rule:T}):E.isDirectory()?l(k,U):E.isFile()&&c.push(U);}}a?d.push({path:n,rule:a}):l(i,n);let p=new TextEncoder,f=(y,g)=>Buffer.compare(p.encode(y),p.encode(g));return c.sort(f),d.sort((y,g)=>f(y.path,g.path)),{included:c,excluded:d}}function Ss(e){let n=[],t=[];function i(o,r,s){let a;try{a=ne__namespace.readdirSync(o,{withFileTypes:!0});}catch{return}a.sort((c,d)=>c.name.localeCompare(d.name));for(let c of a){let d=r?`${r}/${c.name}`:c.name,l=de__namespace.join(o,c.name);if(c.isSymbolicLink()){let p;try{p=ne__namespace.statSync(l);}catch{t.push({path:d,rule:"symlink"});continue}if(p.isDirectory()){t.push({path:d,rule:s??"symlink-dir"});continue}let f=s??gn(c.name,d,false);f?t.push({path:d,rule:f}):t.push({path:d,rule:"symlink"});continue}if(c.isDirectory()){let p=s??gn(c.name,d,true);i(l,d,p);continue}if(c.isFile()){let p=s??gn(c.name,d,false);p?t.push({path:d,rule:p}):n.push(d);}}}return i(e,"",null),n.sort(),t.sort((o,r)=>o.path<r.path?-1:o.path>r.path?1:0),{included:n,excluded:t}}m();var ru=[{rule:"token-prefix",regex:/\b(?:sk-|ghp_|xoxb-)[A-Za-z0-9_-]{10,}/},{rule:"private-key",regex:/-----BEGIN [A-Z ]*PRIVATE KEY-----/},{rule:"aws-access-key",regex:/\bAKIA[0-9A-Z]{16}\b/}];function su(e){return e.includes(0)}function Hi(e,n,t){let i=[];for(let o of n){let r=de__namespace.join(e,o),s;try{let c=t?.get(o);s=c===void 0?ne__namespace.readFileSync(r):Buffer.from(c);}catch{continue}if(su(s))continue;s.toString("utf8").split(/\r\n|\r|\n/).forEach((c,d)=>{for(let{rule:l,regex:p}of ru)p.test(c)&&i.push({path:o,line:d+1,rule:l});});}return i}m();var Os=/^[a-z0-9-]+$/,au=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/,cu=/^[A-Za-z_][A-Za-z0-9_]*$/;function du(e){let n=de__namespace.join(e,"crewx.yaml");if(!ne__namespace.existsSync(n))return {};let t;try{t=Rs__namespace.load(ne__namespace.readFileSync(n,"utf8"));}catch{return {}}if(!t||typeof t!="object")return {};let i=t.metadata;if(!i||typeof i!="object")return {};let o=i;return {name:typeof o.name=="string"?o.name:void 0,version:typeof o.version=="string"?o.version:void 0,description:typeof o.description=="string"?o.description:void 0,requiredEnv:o.requiredEnv,crewxMinVersion:typeof o.crewxMinVersion=="string"?o.crewxMinVersion:void 0}}function pu(e){return zi__namespace.createHash("sha256").update(e).digest("hex")}function ws(e){let n;try{n=ne__namespace.lstatSync(e);}catch{throw P("PACKAGE_FILE_INVALID",`file is not readable: ${de__namespace.basename(e)}`)}if(n.isSymbolicLink())throw P("PACKAGE_SYMLINK","symlink content is not publishable");if(!n.isFile())throw P("PACKAGE_FILE_INVALID","only regular files are publishable");return zi__namespace.createHash("sha256").update(new Uint8Array(ne__namespace.readFileSync(e))).digest("hex")}function lu(e,n){let t=new TextEncoder().encode(e),i=new TextEncoder().encode(n),o=Math.min(t.byteLength,i.byteLength);for(let r=0;r<o;r+=1){let s=t[r]-i[r];if(s!==0)return s}return t.byteLength-i.byteLength}function Cs(e){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||de__namespace.posix.isAbsolute(e)||e.split("/").some(n=>n===".."||n.length===0))throw P("PACKAGE_PATH_TRAVERSAL","manifest file path must be a non-empty POSIX relative path")}function uu(e){if(!/^(?:apps|skills)\/[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(e))throw P("APP_PACKAGE_ROOT_INVALID","packageRoot must be apps/<safe-id> or skills/<safe-id>")}function Us(e){if(!au.test(e))throw new Error(`publish: invalid version "${e}" \u2014 must be semver (e.g. 1.0.0)`)}function ks(e,n,t={}){let i=du(e),o=i.name??de__namespace.basename(e);if(!Os.test(o))throw new Error(`publish: invalid name "${o}" \u2014 must match ${Os} (lowercase letters, numbers, hyphen only)`);let r=t.version??i.version;if(!r)throw new Error("publish: version is required \u2014 set crewx.yaml metadata.version or pass opts.version");Us(r);let s=Array.isArray(i.requiredEnv)?i.requiredEnv:[],a=[];for(let l of s){if(typeof l!="string"||!cu.test(l))throw new Error(`publish: requiredEnv must contain names only (no values), got "${String(l)}"`);a.push(l);}let c=n.map(l=>(Cs(l),{path:l,sha256:ws(de__namespace.join(e,l))})).sort((l,p)=>l.path<p.path?-1:l.path>p.path?1:0),d={name:o,version:r,type:"template",description:i.description??"",files:c,requiredEnv:a};return i.crewxMinVersion&&(d.crewxMinVersion=i.crewxMinVersion),d}function fu(e){let n=e.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"");if(!n)throw P("APP_PACKAGE_ROOT_INVALID","appId cannot produce a marketplace name");return n}function xs(e,n){if(uu(n.packageRoot),!n.version)throw new Error("publish: version is required for App publishing \u2014 pass opts.version");if(Us(n.version),typeof n.description!="string")throw new Error("publish: App description must be a string");let t=[...new Set(n.capabilities)].sort();if(t.length===0||t.some(s=>s!=="screen"&&s!=="skill"))throw new Error("publish: App capabilities must contain screen or skill");let i=`${n.packageRoot}/`;if(t.includes("screen")){if(typeof n.definitionId!="string"||n.definitionId.length===0)throw P("APP_UI_MANIFEST_INVALID","screen App manifests require definitionId");let s=n.includedFiles.includes(`${i}manifest.json`),a=n.includedFiles.includes(`${i}ui-plugin.json`);if(!s&&!a)throw P("APP_UI_MANIFEST_INVALID","screen App is missing manifest.json or ui-plugin.json");if(s&&!a)throw P("APP_UI_MANIFEST_INVALID","a manifest.json App must also ship a generated ui-plugin.json");if(!n.includedFiles.includes(`${i}ui/index.html`))throw P("APP_UI_MANIFEST_INVALID","screen App is missing ui/index.html")}if(t.includes("skill")&&!n.includedFiles.includes(`${i}SKILL.md`))throw P("APP_SKILL_MISSING","skill capability requires package-root SKILL.md");let o=new Set,r=n.includedFiles.map(s=>{if(Cs(s),!s.startsWith(i))throw P("PACKAGE_PATH_TRAVERSAL","App manifest file is outside packageRoot");let a=n.generatedFiles?.get(s);return a!==void 0&&o.add(s),{path:s,sha256:a===void 0?ws(de__namespace.join(e,s)):pu(a),...a===void 0?{}:{generated:true}}}).sort((s,a)=>lu(s.path,a.path));if(o.size>0&&(o.size!==1||!o.has(`${i}ui-plugin.json`)))throw new Error("publish: only the generated ui-plugin.json may be present in an App package");return {manifestVersion:1,name:fu(n.appId),version:n.version,type:"app",description:n.description,appId:n.appId,...n.definitionId===void 0?{}:{definitionId:n.definitionId},...n.definitionHash===void 0?{}:{definitionHash:n.definitionHash},capabilities:t,packageRoot:n.packageRoot,files:r,requiredEnv:[]}}m();function vs(e){return zi__namespace.createHash("sha256").update(e).digest("hex")}function Hs(e,n){if(typeof n!="string"||n.length===0||n.includes("\\")||n.includes("\0")||de__namespace.posix.isAbsolute(n)||n.split("/").some(o=>o===".."||o.length===0))throw P("PACKAGE_PATH_TRAVERSAL","archive paths must be non-empty POSIX relative paths");let t=de__namespace.resolve(e),i=de__namespace.resolve(t,...n.split("/"));if(i!==t&&!i.startsWith(`${t}${de__namespace.sep}`))throw P("PACKAGE_PATH_TRAVERSAL","archive path escaped its root");return i}function js(e,n){let t=Hs(e,n),i;try{i=ne__namespace.lstatSync(t);}catch{throw P("PACKAGE_FILE_INVALID","manifest file is missing")}if(i.isSymbolicLink())throw P("PACKAGE_SYMLINK","symlink content is not publishable");if(!i.isFile())throw P("PACKAGE_FILE_INVALID","only regular files are publishable");return new Uint8Array(ne__namespace.readFileSync(t))}async function zs(e,n,t={}){let i=de__namespace.join(e,".crewx","publish");ne__namespace.mkdirSync(i,{recursive:true});let o=de__namespace.join(i,`${n.name}-${n.version}.tgz`),r=de__namespace.join(i,`.${n.name}-${n.version}.${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}.tmp.tgz`),s=ne__namespace.mkdtempSync(de__namespace.join(Fs__namespace.tmpdir(),"crewx-publish-"));try{let a=new Set,c=[];for(let d of n.files){if(a.has(d.path))throw P("PACKAGE_PATH_TRAVERSAL","manifest contains duplicate file paths");a.add(d.path);let l=t.generatedFiles?.get(d.path);if(d.generated===!0&&l===void 0)throw P("PACKAGE_GENERATED_FILE_MISSING","generated manifest file bytes are missing");if(t.sourceFileHashes?.has(d.path)){let y=js(e,d.path);if(t.sourceFileHashes.get(d.path)!==vs(y))throw P("PACKAGE_STAGED_BYTES_MISMATCH","workspace source changed before staging")}let p=l??js(e,d.path);if(vs(p)!==d.sha256)throw P("PACKAGE_STAGED_BYTES_MISMATCH",`staged bytes differ for ${d.path}`);let f=Hs(s,d.path);ne__namespace.mkdirSync(de__namespace.dirname(f),{recursive:!0}),ne__namespace.writeFileSync(f,new Uint8Array(p)),c.push(d.path);}ne__namespace.writeFileSync(de__namespace.join(s,"manifest.json"),JSON.stringify(n,null,2)),await Bs__namespace.create({gzip:!0,file:r,cwd:s,portable:!0,noMtime:!0},["manifest.json",...c]),ne__namespace.renameSync(r,o);}finally{try{ne__namespace.rmSync(r,{force:!0});}catch{}ne__namespace.rmSync(s,{recursive:true,force:true});}return o}m();m();var mn="/api/v1";var Iu=201,gu=200,mu=409,$i=401,$s={APP_NAME_CONFLICT:"APP_NAME_CONFLICT",CONTENT_SUSPENDED:"PUBLISH_CONTENT_SUSPENDED",CONTENT_REJECTED:"CONTENT_REJECTED",APP_VERSION_MUST_INCREASE:"APP_VERSION_MUST_INCREASE",APP_VERSION_INVALID:"APP_VERSION_INVALID"};function hu(){return process.env.WI013_FAKE_UPLOAD==="1"}function _u(e){let n=zlib.gunzipSync(new Uint8Array(e)),t=zlib.gzipSync(new Uint8Array(n),{level:1});if(Buffer.compare(new Uint8Array(t),new Uint8Array(e))===0)throw new Error("publish: [E_MALFORMED] Re-gzipped upload bytes are identical to the original \u2014 tamper is a no-op");return t}function Eu(e){return e.replace(/\/+$/,"")}async function Bn(e){try{return await e.json()}catch{return null}}function Gs(e,n,t){let i=e;if(!i||i.success!==true||i.data===void 0)throw new Error(`publish: [E_MALFORMED] ${n} response envelope is malformed (expected { success: true, data }) \u2014 HTTP ${t}`);return i.data}function Tu(e){if(!e||typeof e!="object"||Array.isArray(e))return;let n=e;if(typeof n.contentId=="string"&&n.contentId.length>0)return n.contentId;if(!n.data||typeof n.data!="object"||Array.isArray(n.data))return;let t=n.data;return typeof t.contentId=="string"&&t.contentId.length>0?t.contentId:void 0}function bu(e){if(!e||typeof e!="object"||Array.isArray(e))return;let n=e;if(typeof n.slug=="string"&&n.slug.length>0)return n.slug;if(!n.data||typeof n.data!="object"||Array.isArray(n.data))return;let t=n.data;return typeof t.slug=="string"&&t.slug.length>0?t.slug:void 0}function Js(e,n){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e,i=t.data&&typeof t.data=="object"&&!Array.isArray(t.data)?t.data:void 0,o=[t.code,t.message,i?.code,i?.message];for(let r of o){if(typeof r!="string"||!Object.prototype.hasOwnProperty.call($s,r))continue;let s=r,a=s==="APP_NAME_CONFLICT"?`marketplace name is already in use: ${n}`:void 0;return P($s[s],a)}}async function Pu(e){if(!e.baseUrl.trim())throw new Error("publish: [E_ENV_MISSING] Marketplace base URL is required");if(!e.accessToken.trim())throw new Error("publish: [E_AUTH_EXPIRED] A valid bearer token is required");let n=Eu(e.baseUrl),t=e.accessPolicy??"private",i=e.manifest.name,o=e.manifest.type==="app"?e.manifest:void 0,r=o!==void 0,s=o?.appId,a;try{a=await fetch(`${n}${mn}/publisher/items`,{method:"POST",headers:{Authorization:`Bearer ${e.accessToken}`,"Content-Type":"application/json"},body:JSON.stringify({slug:i,displayName:i,description:e.manifest.description,type:e.manifest.type,version:e.manifest.version,accessPolicy:t,...s===void 0?{}:{appId:s}})});}catch{throw new Error("publish: [E_NETWORK] Submit request failed (network)")}let c=await Bn(a),d=Tu(c),l=bu(c),p=r&&l!==void 0?l:i,f;if(a.status===Iu)f="created";else if(r&&a.status===gu){if(d===void 0)throw P("PUBLISH_CONTENT_ID_MISSING","App republish did not return an opaque contentId");f="existing";}else if(a.status===mu){if(r)throw Js(c,i)??P("APP_NAME_CONFLICT",`marketplace name is already in use: ${i}`);f="existing";}else throw a.status===$i?new Error("publish: [E_AUTH_EXPIRED] Authentication is expired or missing \u2014 please log in again (HTTP 401)"):new Error(`publish: [E_HTTP] Submit request failed \u2014 HTTP ${a.status}`);let y="not-needed",g=null;if(f==="existing"&&!r){let D;try{D=await fetch(`${n}${mn}/publisher/items`,{method:"GET",headers:{Authorization:`Bearer ${e.accessToken}`}});}catch{throw new Error("publish: [E_NETWORK] Publisher items request failed (network)")}let L=await Bn(D);if(D.status!==200)throw new Error(`publish: [E_HTTP] Publisher items request failed \u2014 HTTP ${D.status}`);let A=Gs(L,"publisher items",D.status)?.items;if(!Array.isArray(A))throw new Error(`publish: [E_MALFORMED] Publisher items response is malformed (expected data.items[]) \u2014 HTTP ${D.status}`);let h=A.find(b=>!b||typeof b!="object"?false:b.slug===i);if(!h||typeof h.version!="string")throw new Error(`publish: [E_MALFORMED] Publisher items response does not contain slug "${i}" \u2014 HTTP ${D.status}`);if(g=h.version,g!==e.manifest.version){let b;try{b=await fetch(`${n}${mn}/publisher/items/${encodeURIComponent(i)}`,{method:"PUT",headers:{Authorization:`Bearer ${e.accessToken}`,"Content-Type":"application/json"},body:JSON.stringify({version:e.manifest.version})});}catch{throw new Error("publish: [E_NETWORK] Version update request failed (network)")}if(!b.ok)throw await Bn(b),b.status===$i?new Error(`publish: [E_AUTH_EXPIRED] Authentication is expired or missing \u2014 please log in again (HTTP ${b.status})`):b.status===403?new Error(`publish: [E_FORBIDDEN] Version update is forbidden; only the item owner can update an existing item (HTTP ${b.status})`):new Error(`publish: [E_HTTP] Version update failed \u2014 HTTP ${b.status}`);y="applied";}}let _=ne__namespace.readFileSync(e.tgzPath),E=hu()?_u(_):_,U=new FormData;U.set("archive",new Blob([new Uint8Array(E)],{type:"application/gzip"}),`${p}-${e.manifest.version}.tgz`);let k=r&&d!==void 0?d:i,T;try{T=await fetch(`${n}${mn}/publisher/items/${encodeURIComponent(k)}/upload`,{method:"POST",headers:{Authorization:`Bearer ${e.accessToken}`},body:U});}catch{throw new Error("publish: [E_NETWORK] Upload request failed (network)")}if(T.status===$i)throw new Error("publish: [E_AUTH_EXPIRED] Authentication is expired or missing \u2014 please log in again (HTTP 401)");if(!T.ok){let D=await Bn(T);if(r){let L=Js(D,p);if(L)throw L}throw new Error(`publish: [E_HTTP] Upload request failed \u2014 HTTP ${T.status}`)}let C=await Bn(T),B=Gs(C,"upload",T.status),N=typeof B.contentId=="string"&&B.contentId.length>0?B.contentId:d;if(r&&N===void 0)throw P("PUBLISH_CONTENT_ID_MISSING","App upload did not return an opaque contentId");return {slug:p,version:e.manifest.version,...N===void 0?{}:{contentId:N},artifactChecksum:B.artifactChecksum,artifactSizeBytes:B.artifactSizeBytes,submitOutcome:f,versionUpdate:y,serverVersionBefore:g}}var Nu=1e4,Du=100*1024*1024;function Gi(e){return zi__namespace.createHash("sha256").update(e).digest("hex")}function Su(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function Ge(e,n){if(!n||n.includes("\\")||n.includes("\0")||de__namespace.posix.isAbsolute(n)||n.split("/").some(r=>r===".."||r.length===0))throw P("PACKAGE_PATH_TRAVERSAL","workspace file path is not a safe relative path");let t=de__namespace.resolve(e,...n.split("/")),i=de__namespace.resolve(e);if(t!==i&&!t.startsWith(`${i}${de__namespace.sep}`))throw P("PACKAGE_PATH_TRAVERSAL","workspace file path escaped the workspace root");let o;try{o=ne__namespace.lstatSync(t);}catch{throw P("PACKAGE_FILE_INVALID",`workspace file is missing: ${n}`)}if(o.isSymbolicLink())throw P("PACKAGE_SYMLINK",`symlink is not publishable: ${n}`);if(!o.isFile())throw P("PACKAGE_FILE_INVALID",`not a regular file: ${n}`);return new Uint8Array(ne__namespace.readFileSync(t))}async function Mu(e,n,t){let i=`${n}/${W}`;if(!t.includes(i))return [];let o={[W]:Ge(e,i)},r=`${n}/${$}`;t.includes(r)&&(o[$]=Ge(e,r));let s=ze(o,{mode:"local"});if(!s.ok)return [];let{diagnostics:a}=await Pn(s.mcpb?.icon,async d=>{let l=`${n}/${d}`;return t.includes(l)?Ge(e,l):"missing"}),c=a.find(d=>d.code==="ICON_INVALID");if(c!==void 0)throw P("ICON_INVALID",`${c.reason??"invalid"} at ${c.declared??"icon"}`);return a.flatMap(d=>d.code==="ICON_INVALID"?[]:[{code:d.code,path:d.declared??"icon"}])}function Ks(e,n,t){let i=e??n;if(!Number.isSafeInteger(i)||i<=0)throw new je("PACKAGE_SIZE_LIMIT",`${t} must be a positive integer`);return i}function Ys(e,n,t,i){let o=Ks(t.maxFileCount??t.maxFiles,Nu,"max file count"),r=Ks(t.maxTotalBytes??t.maxBytes,Du,"max total bytes");if(n.length>o)throw new je("PACKAGE_SIZE_LIMIT",`package exceeds file count limit (${o})`);let s=0;for(let a of n){let c=i?.get(a);if(c!==void 0?s+=c.byteLength:s+=Ge(e,a).byteLength,s>r)throw new je("PACKAGE_SIZE_LIMIT",`package exceeds byte limit (${r})`)}}function Lu(e){return e.appId!==void 0||e.expectedDefinitionHash!==void 0}function Ou(e){let n=e.appId!==void 0,t=e.expectedDefinitionHash!==void 0;if(!n&&t)throw P("APP_ID_REQUIRED","appId is required with expectedDefinitionHash");if(n&&!t)throw P("APP_DEFINITION_HASH_REQUIRED","expectedDefinitionHash is required with appId");if(!n||!t)throw P("APP_ID_REQUIRED")}function Ru(e,n){let t=e.filter(i=>i.appId===n);if(t.length===0)throw P("APP_NOT_FOUND",`no publishable App matches ${n}`);if(t.length!==1)throw P("APP_AMBIGUOUS",`more than one App matches ${n}`);return t[0]}function wu(e){let n=e.localDefinitionRef?.packageRoot;if(!n||!/^(?:apps|skills)\/[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(n))throw P("APP_PACKAGE_ROOT_INVALID","selected App is not rooted in apps/<safe-id> or skills/<safe-id>");return n}function Ji(e){let{path:n,rule:t}=e.reason;return `${e.code} at ${n===""?"<file>":n} (${t})`+(e.files.length>0?` [${e.files.join(", ")}]`:"")}function Cu(e,n,t){let i=ze({[pe]:t},{mode:"published"});if(!i.ok)throw P("APP_UI_MANIFEST_INVALID",`generated ${pe} does not read: ${Ji(i.rejection)}`);if(ln(i.manifest)!==ln(n))throw P("APP_UI_MANIFEST_INVALID",`generated ${pe} normalizes to a different definition hash than the source`);let o=e[W];if(o===void 0)return;let r=e[$],s=ze({[W]:o,[pe]:t,...r===void 0?{}:{[$]:r}},{mode:"local"});if(!s.ok)throw P("APP_UI_MANIFEST_INVALID",Ji(s.rejection))}function Uu(e,n,t,i){let o={};for(let y of Q){let g=`${t}/${y}`;i.includes(g)&&(o[y]=Ge(e,g));}let r=`${t}/${$}`;if(o[W]!==void 0&&i.includes(r)&&(o[$]=Ge(e,r)),Object.keys(o).length===0)throw P("APP_UI_MANIFEST_INVALID","selected screen App has no package manifest.json or ui-plugin.json");let s=ze(o,{mode:"local"});if(!s.ok)throw P("APP_UI_MANIFEST_INVALID",Ji(s.rejection));if(s.manifest.pluginId!==n.appId)throw P("APP_DEFINITION_CONFLICT",`${s.file} identity no longer matches the selected App`);let a=o[pe],c=a===void 0?void 0:Gi(a),d=`${t}/ui/index.html`;if(!i.includes(d))throw P("APP_UI_MANIFEST_INVALID","screen entry is outside package scope");let l=Gi(Ge(e,d)),p=JSON.parse(JSON.stringify(s.v2Input));if(p.entryHash=l,Object.prototype.hasOwnProperty.call(p,"initialState")){let y=p.initialState;if(!Su(y)||y.path!=="ui/state.json")throw P("APP_INITIAL_STATE_OUT_OF_SCOPE","initialState must reference ui/state.json inside the package");let g=`${t}/ui/state.json`;if(!i.includes(g))throw P("APP_INITIAL_STATE_OUT_OF_SCOPE","initialState reference is outside the selected package");let _=Ge(e,g);p.initialState={...y,hash:Gi(_)};}let f;try{let y=Xe(p,{mode:"published"});f=new Uint8Array(Buffer.from(JSON.stringify(y),"utf8"));}catch(y){throw y instanceof ce?P("APP_UI_MANIFEST_INVALID",y.code):P("APP_UI_MANIFEST_INVALID")}return Cu(o,s.manifest,f),{bytes:f,...c===void 0?{}:{legacySourceHash:c}}}async function ku(e,n){let{included:t,excluded:i}=Ss(e);Ys(e,t,n);let o=ks(e,t,{version:n.version}),r=Hi(e,t);return {plan:{manifest:o,included:t,excluded:i,secretFindings:r},archiveOptions:{}}}async function xu(e,n){Ou(n);let t=await Ps(e),i=Ru(t.items,n.appId);if(i.definitionHash!==n.expectedDefinitionHash)throw P("APP_DEFINITION_CONFLICT",`definitionHash changed for ${n.appId}`);let o=wu(i),{included:r,excluded:s}=Ds(e,o),a=await Mu(e,o,r),c=new Map,d=new Map;if(i.capabilities.includes("screen")){let y=Uu(e,i,o,r),g=`${o}/${pe}`;if(c.set(g,y.bytes),y.legacySourceHash!==void 0)d.set(g,y.legacySourceHash);else {r.push(g);let _=new TextEncoder;r.sort((E,U)=>Buffer.compare(_.encode(E),_.encode(U)));}}if(i.capabilities.includes("skill")&&!r.includes(`${o}/SKILL.md`))throw P("APP_SKILL_MISSING","skill capability requires package-root SKILL.md");Ys(e,r,n,c);let l={appId:i.appId,version:n.version??"",description:i.description,capabilities:i.capabilities,packageRoot:o,...i.definition?.id===void 0?{}:{definitionId:i.definition.id},definitionHash:i.definitionHash,includedFiles:r,generatedFiles:c},p=xs(e,l),f=Hi(e,r,c);return {plan:{manifest:p,included:r,excluded:s,secretFindings:f,warnings:a},archiveOptions:{generatedFiles:c,sourceFileHashes:d}}}async function qs(e,n){let t=de__namespace.resolve(e);if(Lu(n))return xu(t,n);if(n.expectedDefinitionHash!==void 0)throw P("APP_ID_REQUIRED");return ku(t,n)}async function qI(e,n={}){return (await qs(e,n)).plan}function vu(e){let n=e.map(t=>`${t.path}:${t.line} (${t.rule})`).join(", ");throw new je("PUBLISH_SECRET_FINDINGS",`aborted \u2014 secret findings must be resolved before packing: ${n}`)}async function Zs(e,n={}){let t=de__namespace.resolve(e),i=await qs(t,n);i.plan.secretFindings.length>0&&vu(i.plan.secretFindings);let o=await zs(t,i.plan.manifest,i.archiveOptions);return {manifest:i.plan.manifest,tgzPath:o}}async function ZI(e,n={}){return Zs(e,n)}async function QI(e,n){let t=await Zs(e,n);if(t.manifest.type!=="app")throw new Error("publish: App pack unexpectedly produced a template manifest");return t}
2
+ exports.DEFAULT_PUBLISH_MAX_BYTES=Du;exports.DEFAULT_PUBLISH_MAX_FILES=Nu;exports.EXCLUDE_RULES=Ns;exports.MARKETPLACE_API_PREFIX=mn;exports.PublishError=je;exports.packApp=QI;exports.packPublish=Zs;exports.packTemplate=ZI;exports.planPublish=qI;exports.uploadToMarketplace=Pu;