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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- 'use strict';var crypto=require('crypto'),net=require('net'),fs$1=require('fs'),promises=require('fs/promises'),path=require('path'),jsYaml=require('js-yaml');var vr=Object.defineProperty;var w=(e,n)=>()=>(e&&(n=e(e=0)),n);var Vr=(e,n)=>{for(var t in n)vr(e,t,{get:n[t],enumerable:true});};var g=w(()=>{});var U,bn=w(()=>{g();U=class extends Error{constructor(t,i=t,r){super(i);this.code=t;this.currentRevision=r;}code;currentRevision;name="UiRuntimeError"};});function pt(e){return Fr.test(e)||Br.test(e)}function se(){throw new U("INPUT_INVALID","JSON value is not projection-safe")}function Gr(e){let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function ct(e,n,t,i,r,o){if(n>i&&se(),e===null||typeof e=="string"||typeof e=="boolean")return typeof e=="string"&&(Hr.test(e)||Jr.test(e)&&!Xr(r,o)||zr.test(e))&&se(),e;if(typeof e=="number")return Number.isFinite(e)||se(),e;(typeof e!="object"||e===void 0||typeof e=="function"||typeof e=="bigint")&&se();let a=e;t.has(a)&&se(),t.add(a);try{if(Array.isArray(e))return e.map(c=>ct(c,n+1,t,i,r,o));Gr(a)||se();let s={};for(let[c,d]of Object.entries(e))pt(c)&&se(),s[c]=ct(d,n+1,t,i,[...r,c],o);return s}finally{t.delete(a);}}function ae(e,n=0,t=[]){(!Number.isInteger(n)||n<0||n>Wr)&&se(),(!Array.isArray(t)||t.some(r=>typeof r!="string"))&&se();let i=ct(e,0,new Set,$r+n,[],t);return (i===null||Array.isArray(i)||typeof i!="object")&&se(),i}function Be(e,n){if(!e||!n)return false;let t=e.split("."),i=n.split(".");return t.length>=i.length&&i.every((r,o)=>t[o]===r)}function Xr(e,n){if(e.length===0)return false;let t=e.join(".");return n.some(i=>Be(t,i))}function He(e){try{let n=JSON.stringify(e);return n===void 0&&se(),n}catch{se();}}function dt(e){return Array.isArray(e)?e.map(dt):e!==null&&typeof e=="object"?Object.fromEntries(Object.keys(e).sort().map(n=>[n,dt(e[n])])):e}function Z(e){return He(dt(e))}function lt(e){return Buffer.byteLength(e,"utf8")}var Fr,Br,Hr,zr,Jr,$r,Wr,De=w(()=>{g();bn();Fr=/(?:proof|token|secret|password|cookie|authorization|private[_-]?key|stack|exception|plugin[_-]?text)/i,Br=/(?:url|uri|endpoint|path|file(?:name|path)?|cwd|shell|directory|dir|folder)$/i,Hr=/<\/?[A-Za-z][^>]*>/,zr=/^(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)/,Jr=/^(?:https?|file|ftp|ws|wss):\/\//i;$r=8,Wr=4;});var Pn,ut=w(()=>{g();Pn=["text/plain","application/json"];});var Ei=w(()=>{g();ut();});function ze(e){return Yr.has(e)||qr.test(e)||Zr.test(e)}var Ti,Yr,qr,Zr,Sn,nn,ge,ft,yt,At,It,gt,Ue=w(()=>{g();Ti=["__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"],Yr=new Set(Ti),qr=/(?:proof|token|secret|password|cookie|authorization|private[_-]?key|stack|exception|plugin[_-]?text)/i,Zr=/(?:url|uri|endpoint|path|file(?:name|path)?|cwd|shell|directory|dir|folder)$/i;Sn=/^[A-Za-z0-9_]+$/,nn=/^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)*$/,ge=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,ft=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/,yt=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,At=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/,It=["blue","violet","emerald","amber","rose","sky","slate","indigo"],gt=["inline","panel"];});function mt(e){return typeof e=="string"&&Pn.includes(e)}var Di=w(()=>{g();ut();Ue();});function Mn(e){if(!ht(e))return false;let n=Object.keys(e);return !(n.some(t=>t!=="in"&&t!=="out")||n.length===0||Object.hasOwn(e,"in")&&!Qr(e.in)||Object.hasOwn(e,"out")&&!es(e.out))}function Qr(e){return ht(e)?Object.keys(e).every(t=>t==="mediaType"||t==="required")&&Object.hasOwn(e,"mediaType")&&mt(e.mediaType)&&(!Object.hasOwn(e,"required")||typeof e.required=="boolean"):false}function es(e){return ht(e)?Object.keys(e).every(t=>t==="mediaType"||t==="range")&&Object.hasOwn(e,"mediaType")&&mt(e.mediaType)&&(!Object.hasOwn(e,"range")||typeof e.range=="boolean"):false}function ht(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}var _t=w(()=>{g();Ei();Di();new TextDecoder("utf-8",{fatal:true,ignoreBOM:true});});function Ln(e){return ns.includes(e)}function Rn(e){return Number.isSafeInteger(e)&&e>=On.min&&e<=On.max}var ns,On,Ni,Et=w(()=>{g();ns=[5,15,30,60],On=Object.freeze({min:15e3,max:6e5,default:3e5}),Ni=1;});function Cn(e){return Number.isSafeInteger(e)&&e>=Un.min&&e<=Un.max}function wn(e){return ts.includes(e)}var Un,bi,ts,Tt=w(()=>{g();Un=Object.freeze({min:6e4,max:18e5,default:6e5}),bi=1,ts=["start","status","cancel"];});function ie(e){let t=e.renderer!==void 0||e.surfaces!==void 0||e.stateProjection!==void 0||e.dataPaths!==void 0||e.usage!==void 0||e.detailPanel!==void 0||e.displayModes!==void 0||e.summaryProjection!==void 0||e.downloads!==void 0||e.legacy!==void 0||Object.values(e.actions).some(r=>r.resultProjection!==void 0)?{id:e.id,version:e.version,...e.renderer===void 0?{}:{renderer:e.renderer},...e.surfaces===void 0?{}:{surfaces:e.surfaces},...e.stateProjection===void 0?{}:{stateProjection:e.stateProjection},...e.dataPaths===void 0?{}:{dataPaths:e.dataPaths},...e.summaryProjection===void 0?{}:{summaryProjection:e.summaryProjection},...e.legacy===void 0?{}:{legacy:e.legacy},...e.usage===void 0?{}:{usage:e.usage},...e.detailPanel===void 0?{}:{detailPanel:e.detailPanel},...e.displayModes===void 0?{}:{displayModes:e.displayModes},...e.downloads===void 0?{}:{downloads:e.downloads},...e.sourceHash===void 0?{}:{sourceHash:e.sourceHash},actions:e.actions}:e.sourceHash===void 0?{id:e.id,version:e.version,actions:e.actions}:{id:e.id,version:e.version,sourceHash:e.sourceHash,actions:e.actions},i=ae(t);return crypto.createHash("sha256").update(Z(i)).digest("hex")}function Nt(e){return `${e.id}\0${e.version}`}function ce(e){if(!/^\d+$/.test(String(e.version))||e.version<1||e.id.length<1||e.id.length>128)throw new U("DEFINITION_UNSUPPORTED","UI definition is invalid");if(e.sourceHash!==void 0&&(typeof e.sourceHash!="string"||!os.test(e.sourceHash)))throw new U("DEFINITION_UNSUPPORTED","UI definition source hash is invalid");if(!/^[0-9a-f]{64}$/.test(e.hash)||ie(e)!==e.hash)throw new U("DEFINITION_UNSUPPORTED","UI definition hash is invalid");for(let[n,t]of Object.entries(e.actions)){if(!n||!Array.isArray(t.capabilities)||t.capabilities.some(i=>!ss(i)))throw new U("DEFINITION_UNSUPPORTED","UI action declaration is invalid");if(t.confirmation!==void 0&&t.confirmation!=="none"&&t.confirmation!=="native")throw new U("DEFINITION_UNSUPPORTED","UI action confirmation is invalid");if(t.inputKeys&&(!Array.isArray(t.inputKeys)||t.inputKeys.some(i=>typeof i!="string"||!i)))throw new U("DEFINITION_UNSUPPORTED","UI action input declaration is invalid");if(t.dataInputs!==void 0&&(!Array.isArray(t.dataInputs)||new Set(t.dataInputs).size!==t.dataInputs.length||t.dataInputs.some(i=>typeof i!="string"||!i||t.inputKeys!==void 0&&!t.inputKeys.includes(i))))throw new U("DEFINITION_UNSUPPORTED","UI action data input declaration is invalid");if(t.resultProjection&&Dt(t.resultProjection),t.schedule!==void 0&&(!Ln(t.schedule.everyMinutes)||!Rn(t.schedule.timeoutMs)))throw new U("DEFINITION_UNSUPPORTED","UI action schedule declaration is invalid");if(t.job!==void 0&&(typeof t.job!="object"||Object.keys(t.job).some(i=>i!=="deadlineMs")||!Cn(t.job.deadlineMs)))throw new U("DEFINITION_UNSUPPORTED","UI action job declaration is invalid");if(t.jobAccess!==void 0&&(!Array.isArray(t.jobAccess)||t.jobAccess.length===0||new Set(t.jobAccess).size!==t.jobAccess.length||!t.jobAccess.every(wn)||t.job!==void 0))throw new U("DEFINITION_UNSUPPORTED","UI action job control declaration is invalid");if(t.content!==void 0&&!Mn(t.content))throw new U("DEFINITION_UNSUPPORTED","UI action content declaration is invalid");if(t.env!==void 0&&(!Array.isArray(t.env)||t.env.length===0||new Set(t.env).size!==t.env.length||t.env.some(i=>i!=="CREWX_APP_INSTANCE_ID"&&i!=="CREWX_THREAD_ID")))throw new U("DEFINITION_UNSUPPORTED","UI action environment declaration is invalid")}if(e.renderer!==void 0&&(!e.renderer||e.renderer.length>128))throw new U("DEFINITION_UNSUPPORTED","UI definition renderer is invalid");if(e.surfaces&&(!Array.isArray(e.surfaces)||e.surfaces.some(n=>!n||n.length>64)))throw new U("DEFINITION_UNSUPPORTED","UI definition surfaces are invalid");if(e.usage!==void 0&&e.usage!=="card"&&e.usage!=="window")throw new U("DEFINITION_UNSUPPORTED","UI definition usage is invalid");if(e.detailPanel!==void 0&&typeof e.detailPanel!="boolean")throw new U("DEFINITION_UNSUPPORTED","UI definition detailPanel is invalid");if(e.displayModes&&(!Array.isArray(e.displayModes)||e.displayModes.length===0||new Set(e.displayModes).size!==e.displayModes.length||e.displayModes.some(n=>n!=="inline"&&n!=="floating"&&n!=="focused")))throw new U("DEFINITION_UNSUPPORTED","UI definition displayModes are invalid");if(e.usage==="card"&&e.displayModes!==void 0)throw new U("DEFINITION_UNSUPPORTED","Card definitions cannot declare displayModes");if(e.usage==="window"&&e.detailPanel!==void 0)throw new U("DEFINITION_UNSUPPORTED","Window definitions cannot declare detailPanel");if(e.stateProjection&&Dt(e.stateProjection),e.summaryProjection){Dt(e.summaryProjection);let n=new Set(e.stateProjection?.allow??[]);if(e.summaryProjection.allow.some(t=>!n.has(t)))throw new U("DEFINITION_UNSUPPORTED","UI summary projection exceeds state projection")}if(e.legacy!==void 0){if(!e.legacy||typeof e.legacy!="object"||Array.isArray(e.legacy)||Object.keys(e.legacy).some(r=>!["readTool","actionTool","hostTools","agentAccess"].includes(r)))throw new U("DEFINITION_UNSUPPORTED","UI legacy metadata is invalid");let n=new Set;for(let[r,o]of [["readTool",e.legacy.readTool],["actionTool",e.legacy.actionTool]])if(o!==void 0){if(rs(o,r==="readTool"),n.has(o.name))throw new U("DEFINITION_UNSUPPORTED","UI legacy tool names collide");n.add(o.name);}let t=e.legacy.hostTools;if(t!==void 0){if(!t||typeof t!="object"||Array.isArray(t))throw new U("DEFINITION_UNSUPPORTED","UI legacy host tools are invalid");let r={"doc.open":"crewx_app_html_viewer_open","pty.connect":"crewx_app_terminal_connect"};for(let[o,a]of Object.entries(t)){if(!Object.hasOwn(r,o)||r[o]!==a||typeof a!="string"||!/^[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(a)||n.has(a))throw new U("DEFINITION_UNSUPPORTED","UI legacy host tools are invalid");n.add(a);}}let i=e.legacy.agentAccess;if(i!==void 0&&(!i||typeof i!="object"||Array.isArray(i)||Object.entries(i).some(([r,o])=>!r||!Object.hasOwn(e.actions,r)||o!=="allowed"&&o!=="denied")))throw new U("DEFINITION_UNSUPPORTED","UI legacy agent access is invalid");if(e.legacy.actionTool!==void 0&&(!i||Object.keys(i).length===0))throw new U("DEFINITION_UNSUPPORTED","UI legacy action tool requires its complete agent access map")}if(e.downloads!==void 0&&e.downloads!==true)throw new U("DEFINITION_UNSUPPORTED","UI definition downloads is invalid");if(e.dataPaths!==void 0){let n=new Set(["__proto__","prototype","constructor"]);if(!Array.isArray(e.dataPaths)||e.dataPaths.length>16||new Set(e.dataPaths).size!==e.dataPaths.length||e.dataPaths.some(t=>typeof t!="string"||!/^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)*$/.test(t)||t.split(".").some(i=>n.has(i))||!(e.stateProjection?.allow??[]).some(i=>Be(t,i))))throw new U("DEFINITION_UNSUPPORTED","UI definition dataPaths are invalid")}}function rs(e,n){if(!e||typeof e!="object"||Array.isArray(e))throw new U("DEFINITION_UNSUPPORTED","UI legacy tool metadata is invalid");let t=e,i=["name","description","inputSchema","textFallback","visibility"],r=Object.hasOwn(t,"fixedResult");if(Object.keys(t).some(o=>!i.includes(o)&&!(n&&o==="fixedResult"))||i.some(o=>!Object.hasOwn(t,o))||typeof t.name!="string"||!/^[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(t.name)||typeof t.description!="string"||t.description.trim().length===0||t.description.length>8192||typeof t.textFallback!="string"||t.textFallback.trim().length===0||t.textFallback.length>16384||!t.inputSchema||typeof t.inputSchema!="object"||Array.isArray(t.inputSchema)||!Array.isArray(t.visibility)||t.visibility.length===0||t.visibility.some(o=>o!=="model"&&o!=="app")||new Set(t.visibility).size!==t.visibility.length)throw new U("DEFINITION_UNSUPPORTED","UI legacy tool metadata is invalid");try{let o=ae(t.inputSchema);if(o.type!==void 0&&o.type!=="object")throw new Error("schema type");if(r){if(!n)throw new Error("fixed result location");let a=t.fixedResult;if(!a||typeof a!="object"||Array.isArray(a))throw new Error("fixed result");let s=a;if(Object.keys(s).sort().join(",")!=="argsPolicy,structuredContent"||s.argsPolicy!=="empty-only"&&s.argsPolicy!=="ignore"||!s.structuredContent||typeof s.structuredContent!="object"||Array.isArray(s.structuredContent))throw new Error("fixed result");let c=ae(s.structuredContent);if(lt(He(c))>4*1024)throw new Error("fixed result size")}}catch{throw new U("DEFINITION_UNSUPPORTED","UI legacy tool metadata is not projection-safe")}}function Dt(e){if(!Array.isArray(e.allow)||e.allow.some(n=>!/^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)*$/.test(n)))throw new U("DEFINITION_UNSUPPORTED","UI projection policy is invalid")}function ss(e){return e.length>0&&e.length<=128&&e!=="*"&&e!=="all"&&!/[/*]/.test(e)}var os,Ce=w(()=>{g();De();bn();_t();Et();Tt();os=/^[0-9a-f]{64}$/;});var Pi=w(()=>{g();De();});var Y,Ne,bt=w(()=>{g();Y="dist/tools.json",Ne="dist/main.mjs";});var tn,Si=w(()=>{g();tn="window";});function Mi(e){if(!Array.isArray(e)||e.length===0)return false;let n=new Set;for(let t of e){if(!as.some(i=>i===t)||n.has(t))return false;n.add(t);}return true}var as,Oi=w(()=>{g();as=["CREWX_APP_INSTANCE_ID","CREWX_THREAD_ID"];});function B(e){throw new Pt(e)}function hs(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 _s(e,n){let t=Object.getOwnPropertyDescriptor(e,n);return (!t||!("value"in t))&&B("CSP_ORIGIN_INVALID"),t.value}function kn(e,n){if(!Object.prototype.hasOwnProperty.call(e,n))return [];let t=_s(e,n);Array.isArray(t)||B("CSP_ORIGIN_INVALID"),Reflect.ownKeys(t).some(o=>typeof o!="string"||o!=="length"&&!/^(?:0|[1-9][0-9]*)$/.test(o))&&B("CSP_ORIGIN_INVALID");let r=[];for(let o=0;o<t.length;o+=1)(!Object.prototype.hasOwnProperty.call(t,o)||typeof t[o]!="string")&&B("CSP_ORIGIN_INVALID"),r.push(t[o]);return Object.keys(t).length!==t.length&&B("CSP_ORIGIN_INVALID"),r}function Es(e){let n;try{n=JSON.stringify(e);}catch{B("CSP_ORIGIN_INVALID");}return n===void 0&&B("CSP_ORIGIN_INVALID"),new TextEncoder().encode(n).byteLength}function Ui(e,n){/\s|\\/u.test(e)&&B("CSP_ORIGIN_INVALID");let t=ys.exec(e);t||B("CSP_ORIGIN_INVALID");let i=t[1].toLowerCase(),r=t[2];(r.includes("@")||r.includes("%")||r.includes("*"))&&B("CSP_ORIGIN_INVALID"),(r.startsWith("[")?As:Is).test(r)||B("CSP_ORIGIN_INVALID"),i==="wss"&&n!=="connectDomains"&&B("CSP_ORIGIN_INVALID");let a;try{a=new URL(e);}catch{B("CSP_ORIGIN_INVALID");}(a.protocol!==`${i}:`||a.username!==""||a.password!==""||a.search!==""||a.hash!=="")&&B("CSP_ORIGIN_INVALID");let s=a.hostname.toLowerCase();if((!s||s.includes("%"))&&B("CSP_ORIGIN_INVALID"),!s.startsWith("[")){let d=s.endsWith(".")?s.slice(0,-1):s;(d.length===0||d.length>253)&&B("CSP_ORIGIN_INVALID"),d.split(".").some(u=>u.length>63||!gs.test(u))&&B("CSP_ORIGIN_INVALID");}let c=a.origin;return (c==="null"||!c.startsWith(`${i}://`))&&B("CSP_ORIGIN_INVALID"),{origin:c,hostname:s}}function Ts(e){let n=e.split(".").map(Number);return ((n[0]*256+n[1])*256+n[2])*256+n[3]}function Ci(e,n,t){let i=4294967295<<32-t>>>0;return (e&i)===(n&i)}function xi(e){let n=Ts(e);return Ci(n,3221225472,24)?n!==3221225481&&n!==3221225482:ms.some(([t,i])=>Ci(n,t,i))}function Ds(e){let n=e.indexOf("::"),t=(n<0?e:e.slice(0,n)).split(":").filter(Boolean),i=n<0?[]:e.slice(n+2).split(":").filter(Boolean);return (n<0?t:[...t,...Array(8-t.length-i.length).fill("0"),...i]).reduce((o,a)=>o<<16n|BigInt(Number.parseInt(a,16)),0n)}function Ns(e){let n=Ds(e),t=Number(n>>112n),i=Number(n>>96n&0xffffn);if(n>>32n===0xffffn){let r=Number(n&0xffffffffn);return xi([r>>>24&255,r>>>16&255,r>>>8&255,r&255].join("."))}return t<8192||t>16383||t===8193&&i<=511||t===8193&&i===3512||t===8194||t===16383&&i<=4095}function bs(e,n){let t=e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e,i=net.isIP(t);if(i===4)return xi(t);if(i===6)return Ns(t);let r=e.toLowerCase().replace(/\.$/,"");return !r||!r.includes(".")||n.has(r)?true:fs.some(o=>r===o||r.endsWith(`.${o}`))}function wi(e){return Object.freeze([...new Set(e.map(n=>n.origin))].sort())}function ki(e){return JSON.stringify({baseUriDomains:[],connectDomains:e.connectDomains,declared:e.declared,frameDomains:e.frameDomains,resourceDomains:[]})}function ji(e,n={}){if(e===void 0){let A=ki({declared:false,connectDomains:[],frameDomains:[]});return Object.freeze({declared:false,connectDomains:Object.freeze([]),frameDomains:Object.freeze([]),resourceDomains:Object.freeze([]),baseUriDomains:Object.freeze([]),cspHash:crypto.createHash("sha256").update(A,"utf8").digest("hex")})}hs(e)||B("CSP_ORIGIN_INVALID");let t=Reflect.ownKeys(e);t.some(A=>typeof A!="string")&&B("CSP_ORIGIN_INVALID"),t.some(A=>!us.has(A))&&B("CSP_AXIS_UNKNOWN");let i=kn(e,"connectDomains"),r=kn(e,"frameDomains"),o=kn(e,"resourceDomains"),a=kn(e,"baseUriDomains");(o.length>0||a.length>0)&&B("CSP_AXIS_UNSUPPORTED"),(Es(e)>ds||i.length>Ri||r.length>Ri||i.length+r.length>ps||[...i,...r].some(A=>new TextEncoder().encode(A).byteLength>ls))&&B("CSP_LIMIT_EXCEEDED");let c=i.map(A=>Ui(A,"connectDomains")),d=r.map(A=>Ui(A,"frameDomains")),l=new Set((n.runtimeHostnames??[]).map(A=>A.toLowerCase().replace(/\.$/,"")));[...c,...d].some(A=>bs(A.hostname,l))&&B("CSP_ORIGIN_FORBIDDEN");let u={declared:true,connectDomains:wi(c),frameDomains:wi(d)},f=ki(u);return Object.freeze({...u,resourceDomains:Object.freeze([]),baseUriDomains:Object.freeze([]),cspHash:crypto.createHash("sha256").update(f,"utf8").digest("hex")})}var ds,Ri,ps,ls,us,fs,ys,As,Is,gs,ms,Pt,vi=w(()=>{g();ds=4096,Ri=16,ps=32,ls=512,us=new Set(["connectDomains","frameDomains","resourceDomains","baseUriDomains"]),fs=["localhost","local","internal","home.arpa","test","example","invalid","onion","lan","corp","home","intranet","private","localdomain"],ys=/^(https|wss):\/\/([^/?#]+)$/i,As=/^\[[^\]]+\](?::[0-9]+)?$/,Is=/^[^:\[\]]+(?::[0-9]+)?$/,gs=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/,ms=[[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]],Pt=class extends Error{constructor(t){super(t);this.code=t;}code;name="UiPluginCspNormalizationError"};});function rn(e,n){return n===void 0||n===""?e:e===""?n:n.startsWith("[")?`${e}${n}`:`${e}.${n}`}function p(e,n=e,t,i){throw new oe(e,n,t,i)}function F(e,n){try{return n()}catch(t){throw t instanceof oe?t.withPathPrefix(e):t}}function H(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;try{let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}catch{return false}}function M(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function ra(e,n){let t={};for(let[i,r]of Object.entries(e))n.includes(i)||(t[i]=r);return t}function G(e,n,t=[]){let i=new Set([...n,...t]),r=Object.keys(e).find(a=>!i.has(a));r!==void 0&&p("MANIFEST_INVALID","MANIFEST_INVALID",r,"unknown-key");let o=n.find(a=>!M(e,a));o!==void 0&&p("MANIFEST_INVALID","MANIFEST_INVALID",o,"missing-key");}function Vn(e,n=false,t=false,i=false){return Os.test(e)||!i&&Rs.test(e)||Ls.test(e)||t&&Vi.test(e)||Us.test(e)&&!(n&&/^\s*data:/i.test(e)&&!Vi.test(e))}function vn(e,n=new Set,t=0,i=false,r=false,o=""){if(typeof e=="string"){Vn(e,i,r)&&p("UNSAFE_VALUE","UNSAFE_VALUE",o,"unsafe-value");return}if(!(e===null||typeof e!="object")){(t>8||n.has(e))&&p("MANIFEST_INVALID","MANIFEST_INVALID",o),n.add(e);try{if(Array.isArray(e)){e.forEach((a,s)=>vn(a,n,t+1,!1,!1,rn(o,`[${s}]`)));return}H(e)||p("MANIFEST_INVALID","MANIFEST_INVALID",o);for(let[a,s]of Object.entries(e))vn(s,n,t+1,i&&t===0&&(a==="name"||a==="description"),r,rn(o,a));}finally{n.delete(e);}}}function me(e,n){let t=e[n];return typeof t!="string"&&p("MANIFEST_INVALID"),t}function le(e,n,t){let i=e[n];return (!Number.isSafeInteger(i)||i<t)&&p("MANIFEST_INVALID"),i}function St(e){return Ms.test(e)||p("MANIFEST_INVALID"),e}function Je(e){return Ss.test(e)||p("TOKEN_INVALID"),e}function sa(e){return Xi.test(e)||p("MANIFEST_INVALID"),e}function aa(e){H(e)||p("MANIFEST_INVALID");let n={};for(let[t,i]of Object.entries(e)){let r=sa(t);H(i)||p("MANIFEST_INVALID");let o=i.type;if(o==="text"){G(i,["type","maxLength"]),n[r]={type:o,maxLength:le(i,"maxLength",1)};continue}if(o==="text-list"){G(i,["type","max","itemMaxLength"]),n[r]={type:o,max:le(i,"max",0),itemMaxLength:le(i,"itemMaxLength",1)};continue}if(o==="step-list"){G(i,["type","min","max","labelMaxLength","detailMaxLength"]);let a=le(i,"min",0),s=le(i,"max",1);a>s&&p("MANIFEST_INVALID"),n[r]={type:o,min:a,max:s,labelMaxLength:le(i,"labelMaxLength",1),detailMaxLength:le(i,"detailMaxLength",1)};continue}typeof o=="string"&&p("SCHEMA_TYPE_UNSUPPORTED"),p("MANIFEST_INVALID");}return n}function ca(e,n,t){let i=e[n];(!i||i.type!==t)&&p("MANIFEST_INVALID");}function xn(e,n,t){let i=me(e,"field");return Xi.test(i)||p("MANIFEST_INVALID"),ca(n,i,t),i}function da(e,n){H(e)||p("MANIFEST_INVALID");let t=e.primitive;switch(typeof t!="string"&&p("MANIFEST_INVALID"),oa.includes(t)||p("PRIMITIVE_UNKNOWN"),t){case "card-shell":return G(e,["primitive"]),{primitive:t};case "meta-banner":return G(e,["primitive","badgeToken","noticeToken"]),{primitive:t,badgeToken:Je(me(e,"badgeToken")),noticeToken:Je(me(e,"noticeToken"))};case "heading":return G(e,["primitive","field"]),{primitive:t,field:xn(e,n,"text")};case "labeled-text":return G(e,["primitive","titleToken","field","variant"]),e.variant!=="callout"&&p("MANIFEST_INVALID"),{primitive:t,titleToken:Je(me(e,"titleToken")),field:xn(e,n,"text"),variant:"callout"};case "step-flow":return G(e,["primitive","titleToken","field"]),{primitive:t,titleToken:Je(me(e,"titleToken")),field:xn(e,n,"step-list")};case "text-list":{G(e,["primitive","titleToken","field"],["emptyToken","hideWhenEmpty"]);let i={primitive:t,titleToken:Je(me(e,"titleToken")),field:xn(e,n,"text-list")};return M(e,"emptyToken")&&(i.emptyToken=Je(me(e,"emptyToken"))),M(e,"hideWhenEmpty")&&(typeof e.hideWhenEmpty!="boolean"&&p("MANIFEST_INVALID"),i.hideWhenEmpty=e.hideWhenEmpty),i}}return p("MANIFEST_INVALID")}function pa(e,n){return Array.isArray(e)||p("MANIFEST_INVALID"),e.map(t=>da(t,n))}function W(e="v2 manifest exceeds a contract limit",n,t){return p("LIMIT_EXCEEDED",e,n,t)}function de(e="initial state is not projection-safe"){return p("INITIAL_STATE_INVALID",e)}function Fi(e,n){return (typeof e!="string"||e.length===0||e.length>4096||e.trim().length===0||Zs.test(e)||Qs.test(e))&&p("MANIFEST_INVALID",`${n} is invalid`),(Vn(e,true,true)||Cs.test(e)||ws.test(e)||ks.test(e))&&p("UNSAFE_VALUE",`${n} contains an unsafe value`),e}function Mt(e,n){return (typeof e!="string"||!ge.test(e))&&p("MANIFEST_INVALID",`${n} is invalid`),e}function la(e){return (typeof e!="string"||!ft.test(e)||e==="*"||e==="all")&&p("MANIFEST_INVALID","action capability is invalid"),e}function Ki(e){return (typeof e!="string"||!qs.test(e))&&p("MANIFEST_INVALID","resource hash is invalid"),e}function Ot(e,n=new Set,t=0,i=""){if(typeof e=="string"){e.length>4096&&W("v2 manifest string is too long",i,"string-too-long");return}if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){Number.isFinite(e)||p("MANIFEST_INVALID","v2 manifest contains a non-finite number",i,"non-finite-number");return}(e===void 0||typeof e=="function"||typeof e=="bigint")&&p("MANIFEST_INVALID","v2 manifest contains a non-JSON value",i,"non-json-value"),typeof e!="object"&&p("MANIFEST_INVALID","MANIFEST_INVALID",i),t>8&&W("v2 manifest nesting is too deep",i,"too-deep"),n.has(e)&&p("MANIFEST_INVALID","v2 manifest contains a cycle",i,"cycle"),n.add(e);try{if(Array.isArray(e)){e.length>128&&W("v2 manifest array is too long",i,"array-too-long"),e.forEach((r,o)=>Ot(r,n,t+1,rn(i,`[${o}]`)));return}H(e)||p("MANIFEST_INVALID","v2 manifest contains a non-plain object",i,"non-plain-object");for(let[r,o]of Object.entries(e))Ot(o,n,t+1,rn(i,r));}finally{n.delete(e);}}}function Yi(e){return (typeof e!="string"||e.length>4096||!nn.test(e))&&(typeof e=="string"&&e.length>4096&&W("projection path is too long"),p("MANIFEST_INVALID","projection paths must be canonical exact paths")),e.split(".").some(t=>ze(t))&&p("MANIFEST_INVALID","projection paths cannot address reserved state keys"),e}function Lt(e){H(e)||p("MANIFEST_INVALID","projection policy must be an object"),G(e,["allow"]),Array.isArray(e.allow)||p("MANIFEST_INVALID","projection allow must be an array"),e.allow.length>128&&W("projection allowlist is too long");let n=[],t=new Set;for(let i of e.allow){let r=Yi(i);t.has(r)&&p("MANIFEST_INVALID","projection allowlist contains a duplicate path"),t.add(r),n.push(r);}return {allow:n}}function ua(e,n){if(e===void 0)return;Array.isArray(e)||p("MANIFEST_INVALID","dataPaths must be an array"),e.length>ea&&W("dataPaths exceed the v2 limit");let t=[],i=new Set;for(let r of e){let o=Yi(r);i.has(o)&&p("MANIFEST_INVALID","dataPaths contain a duplicate path"),n.some(a=>Be(o,a))||p("MANIFEST_INVALID","dataPaths must be projection-allowed"),i.add(o),t.push(o);}return t}function fa(e){Array.isArray(e)||p("MANIFEST_INVALID","deviceFeatures must be an array",void 0,"array"),e.length>na&&p("MANIFEST_INVALID","deviceFeatures allow at most 16 names",void 0,"too-many-items");let n=[],t=new Set;for(let[i,r]of e.entries()){let o=`[${i}]`;typeof r!="string"&&p("MANIFEST_INVALID","a device feature name must be a string",o,"string"),r.length===0&&p("MANIFEST_INVALID","a device feature name must not be empty",o,"empty"),r.length>ta&&p("MANIFEST_INVALID","a device feature name is at most 32 characters",o,"too-long"),ia.test(r)||p("MANIFEST_INVALID","a device feature name starts with a lowercase letter and holds only letters and digits",o,"format"),t.has(r)&&p("MANIFEST_INVALID","deviceFeatures contain a duplicate name",o,"duplicate-item"),t.add(r),n.push(r);}return n}function ya(e){if(e!==false)return e!==true&&p("MANIFEST_INVALID","downloads must be true or false",void 0,"boolean"),true}function Ge(e,n,t=Number.MAX_SAFE_INTEGER){return (!Number.isSafeInteger(e)||e<0||e>t)&&p("MANIFEST_INVALID",`${n} is invalid`),e}function Bi(e,n){return (typeof e!="number"||!Number.isFinite(e))&&p("MANIFEST_INVALID",`${n} is invalid`),e}function Rt(e,n=0,t=new Set){if(typeof e=="string")return (e.length>4096||Vn(e))&&p("UNSAFE_VALUE","schema enum contains an unsafe string"),e;if(e===null||typeof e=="boolean")return e;if(typeof e=="number")return Number.isFinite(e)||p("MANIFEST_INVALID","schema enum contains a non-finite number"),e;(n>8||typeof e!="object"||e===void 0)&&W("schema enum is too deep"),t.has(e)&&p("MANIFEST_INVALID","schema enum contains a cycle"),t.add(e);try{if(Array.isArray(e))return e.length>128&&W("schema enum array is too long"),e.map(r=>Rt(r,n+1,t));H(e)||p("MANIFEST_INVALID","schema enum contains a non-plain object");let i={};for(let[r,o]of Object.entries(e))ze(r)&&p("MANIFEST_INVALID","schema enum contains a reserved key"),i[r]=Rt(o,n+1,t);return i}finally{t.delete(e);}}function Aa(e,n){if(e===void 0)return;Array.isArray(e)||p("MANIFEST_INVALID","schema required must be an array"),e.length>64&&W("schema required list is too long");let t=[],i=new Set;for(let r of e)(typeof r!="string"||!nn.test(r))&&p("MANIFEST_INVALID","schema required contains an invalid key"),r.length>4096&&W("schema required key is too long"),i.has(r)&&p("MANIFEST_INVALID","schema required contains a duplicate key"),n&&!Object.prototype.hasOwnProperty.call(n,r)&&p("MANIFEST_INVALID","schema required references an undeclared property"),i.add(r),t.push(r);return t}function Ia(e,n){let t=n?nn:Sn;return e.length>4096&&W("schema property name is too long"),(!t.test(e)||e.split(".").some(i=>ze(i)))&&p("MANIFEST_INVALID","schema property name is invalid"),e}function Ut(e,n=0,t=false){H(e)||p("MANIFEST_INVALID","action inputSchema must be an object"),n>8&&W("action inputSchema is too deep");let i=e.type;i!=="object"&&i!=="string"&&i!=="number"&&i!=="integer"&&i!=="boolean"&&i!=="array"&&i!=="null"&&(typeof i=="string"&&p("SCHEMA_TYPE_UNSUPPORTED","action inputSchema type is unsupported"),p("MANIFEST_INVALID","action inputSchema type is required"));let r=["type","enum"];i==="string"&&r.push("minLength","maxLength"),i==="array"&&r.push("minItems","maxItems","items"),i==="object"&&r.push("minProperties","maxProperties","properties","required","additionalProperties"),(i==="number"||i==="integer")&&r.push("minimum","maximum"),G(e,["type"],r.filter(s=>s!=="type"));let o={type:i};if(M(e,"enum")&&(Array.isArray(e.enum)||p("MANIFEST_INVALID","schema enum must be an array"),e.enum.length>128&&W("schema enum is too long"),o.enum=e.enum.map(s=>Rt(s))),i==="string"&&(M(e,"minLength")&&(o.minLength=Ge(e.minLength,"schema minLength",4096)),M(e,"maxLength")&&(o.maxLength=Ge(e.maxLength,"schema maxLength",4096)),o.minLength!==void 0&&o.maxLength!==void 0&&o.minLength>o.maxLength&&p("MANIFEST_INVALID","schema string length bounds are inverted")),(i==="number"||i==="integer")&&(M(e,"minimum")&&(o.minimum=Bi(e.minimum,"schema minimum")),M(e,"maximum")&&(o.maximum=Bi(e.maximum,"schema maximum")),o.minimum!==void 0&&o.maximum!==void 0&&o.minimum>o.maximum&&p("MANIFEST_INVALID","schema numeric bounds are inverted")),i==="array"&&(M(e,"minItems")&&(o.minItems=Ge(e.minItems,"schema minItems",128)),M(e,"maxItems")&&(o.maxItems=Ge(e.maxItems,"schema maxItems",128)),o.minItems!==void 0&&o.maxItems!==void 0&&o.minItems>o.maxItems&&p("MANIFEST_INVALID","schema array length bounds are inverted"),M(e,"items")&&(o.items=Ut(e.items,n+1,false))),i==="object"){let s;if(M(e,"properties")){H(e.properties)||p("MANIFEST_INVALID","schema properties must be an object");let d=Object.entries(e.properties);d.length>64&&W("schema properties are too many"),s={};for(let[l,u]of d){let f=Ia(l,t);s[f]=Ut(u,n+1,false);}o.properties=s;}M(e,"minProperties")&&(o.minProperties=Ge(e.minProperties,"schema minProperties",64)),M(e,"maxProperties")&&(o.maxProperties=Ge(e.maxProperties,"schema maxProperties",64)),o.minProperties!==void 0&&o.maxProperties!==void 0&&o.minProperties>o.maxProperties&&p("MANIFEST_INVALID","schema object property bounds are inverted");let c=Aa(e.required,s);c!==void 0&&(o.required=c),M(e,"additionalProperties")&&(e.additionalProperties!==false&&p("MANIFEST_INVALID","schema additionalProperties must be false"),o.additionalProperties=false);}let a=JSON.stringify(o);return (a===void 0||Buffer.byteLength(a,"utf8")>2097152)&&W("action inputSchema subtree is too large"),o}function ga(e){let n=Ut(e,0,true);return (n.type!=="object"||!n.properties)&&p("MANIFEST_INVALID","action inputSchema must declare object properties"),n}function ma(e){if(H(e)||p("MANIFEST_INVALID","action backend must be an object"),e.type==="core"){G(e,Gs);let n=e.handler;return (typeof n!="string"||!yt.test(n))&&p("MANIFEST_INVALID","core backend handler is invalid"),{type:"core",handler:n}}if(e.type==="skill"&&M(e,"entry"))return G(e,Xs),e.entry!==Ne&&p("MANIFEST_INVALID",`skill backend entry must be ${Ne}`),{type:"skill",entry:Ne};if(e.type==="skill"){G(e,$s,Ws),(!Array.isArray(e.command)||e.command.length===0||e.command.length>16)&&p("MANIFEST_INVALID","skill backend command is invalid");let n=[];for(let i of e.command)(typeof i!="string"||i.length===0||i.length>256||!At.test(i))&&p("MANIFEST_INVALID","skill backend command token is invalid"),n.push(i);let t=M(e,"env")?Da(e.env):void 0;return {type:"skill",command:n,...t===void 0?{}:{env:t}}}p("MANIFEST_INVALID","action backend type is unsupported");}function ha(e){H(e)||p("MANIFEST_INVALID","action must be an object"),G(e,Vs,Fs),M(e,"_meta")&&F("_meta",()=>qi(e._meta));let n=F("actionId",()=>Mt(e.actionId,"actionId"));pt(n)&&p("MANIFEST_INVALID",`actionId "${n}" is not projection-safe`,"actionId");let t=F("capability",()=>la(e.capability)),i=e.mutation;typeof i!="boolean"&&p("MANIFEST_INVALID","action mutation must be boolean","mutation");let r=F("inputSchema",()=>ga(e.inputSchema)),o;if(M(e,"dataInputs")){Array.isArray(e.dataInputs)||p("MANIFEST_INVALID","action dataInputs must be an array","dataInputs");let A=r.properties,I=new Set,h=[];for(let T of e.dataInputs)(typeof T!="string"||!M(A,T)||I.has(T))&&p("MANIFEST_INVALID","action dataInputs must be unique declared properties","dataInputs"),I.add(T),h.push(T);o=h;}let a=F("resultProjection",()=>Lt(e.resultProjection)),s=F("backend",()=>ma(e.backend)),c;M(e,"content")&&((s.type!=="skill"||!Mn(e.content))&&p("MANIFEST_INVALID","action content declaration is invalid","content"),c=Na(e.content));let d;if(M(e,"confirmation")){let A=e.confirmation;A!=="none"&&A!=="native"&&p("MANIFEST_INVALID","action confirmation is invalid","confirmation"),d=A;}let l;M(e,"schedule")&&(l=F("schedule",()=>Ta(e.schedule,{backend:s,inputSchema:r,hasContent:c!==void 0,hasDataInputs:o!==void 0,confirmation:d})));let u;M(e,"job")&&(l!==void 0&&p("MANIFEST_INVALID","an action is either the scheduled run or a job, not both","job"),u=F("job",()=>Ea(e.job,{backend:s,inputSchema:r,hasContent:c!==void 0,hasDataInputs:o!==void 0,confirmation:d})));let f;return M(e,"jobAccess")&&(u!==void 0&&p("MANIFEST_INVALID","an action is either the job or a job control, not both","jobAccess"),f=F("jobAccess",()=>_a(e.jobAccess,{backend:s,hasContent:c!==void 0}))),{actionId:n,capability:t,mutation:i,inputSchema:r,resultProjection:a,backend:s,...c===void 0?{}:{content:c},...o===void 0?{}:{dataInputs:o},...d===void 0?{}:{confirmation:d},...l===void 0?{}:{schedule:l},...u===void 0?{}:{job:u},...f===void 0?{}:{jobAccess:f}}}function _a(e,n){return (n.backend.type!=="skill"||!("entry"in n.backend)||n.backend.entry!==Ne)&&p("MANIFEST_INVALID","jobAccess needs a tool-mode action","jobAccess"),n.hasContent&&p("MANIFEST_INVALID","a job control action takes no content","jobAccess"),(!Array.isArray(e)||e.length===0)&&p("MANIFEST_INVALID","jobAccess must list at least one operation","jobAccess"),(new Set(e).size!==e.length||!e.every(wn))&&p("MANIFEST_INVALID","jobAccess must name each operation once: start, status or cancel","jobAccess"),Object.freeze([...e])}function Ea(e,n){(n.backend.type!=="skill"||!("entry"in n.backend)||n.backend.entry!==Ne)&&p("MANIFEST_INVALID","job needs a tool-mode action","job"),(n.hasContent||n.hasDataInputs||n.confirmation!==void 0&&n.confirmation!=="none")&&p("MANIFEST_INVALID","a job action takes no content, dataInputs or native confirmation","job"),(n.inputSchema.required??[]).length>0&&p("MANIFEST_INVALID","a job action input must accept {}","inputSchema.required"),H(e)||p("MANIFEST_INVALID","job must be an object","job"),G(e,[],zs);let t=M(e,"deadlineMs")?e.deadlineMs:Un.default;return Cn(t)||p("MANIFEST_INVALID","job deadlineMs is invalid","job.deadlineMs"),{deadlineMs:t}}function Ta(e,n){(n.backend.type!=="skill"||!("entry"in n.backend)||n.backend.entry!==Ne)&&p("MANIFEST_INVALID","schedule needs a tool-mode action","schedule"),(n.hasContent||n.hasDataInputs||n.confirmation!==void 0&&n.confirmation!=="none")&&p("MANIFEST_INVALID","a scheduled action takes no content, dataInputs or native confirmation","schedule"),(n.inputSchema.required??[]).length>0&&p("MANIFEST_INVALID","a scheduled action input must accept {}","inputSchema.required"),H(e)||p("MANIFEST_INVALID","schedule must be an object","schedule"),G(e,Bs,Hs),Ln(e.everyMinutes)||p("MANIFEST_INVALID","schedule everyMinutes is invalid","schedule.everyMinutes");let t=M(e,"timeoutMs")?e.timeoutMs:On.default;return Rn(t)||p("MANIFEST_INVALID","schedule timeoutMs is invalid","schedule.timeoutMs"),{everyMinutes:e.everyMinutes,timeoutMs:t}}function Da(e){return Mi(e)||p("MANIFEST_INVALID","skill backend env is invalid"),Object.freeze([...e])}function Na(e){return Object.freeze({...e.in===void 0?{}:{in:Object.freeze({...e.in})},...e.out===void 0?{}:{out:Object.freeze({...e.out})}})}function ba(e){return H(e)||p("INITIAL_STATE_INVALID","initialState must be an object"),G(e,Ks,Ys),e.path!=="ui/state.json"&&p("MANIFEST_INVALID","initialState path is not fixed"),M(e,"hash")?{path:"ui/state.json",hash:Ki(e.hash)}:{path:"ui/state.json"}}function Pa(e){let n=["wasm","terminal","htmlDocuments","appBrowser"];return (!H(e)||Object.keys(e).length===0||Object.keys(e).some(t=>!n.includes(t)||e[t]!==true))&&p("MANIFEST_INVALID","runtime must contain only known capability flags set to true"),{...e.wasm===true?{wasm:true}:{},...e.terminal===true?{terminal:true}:{},...e.htmlDocuments===true?{htmlDocuments:true}:{},...e.appBrowser===true?{appBrowser:true}:{}}}function Sa(e,n){let t;try{t=ji(e);}catch(i){let r=i!==null&&typeof i=="object"&&"code"in i&&typeof i.code=="string"?i.code:"CSP_ORIGIN_INVALID";return p("MANIFEST_INVALID",r,void 0,r.toLowerCase().replace(/_/g,"-"))}if(t.frameDomains.length>0&&p("MANIFEST_INVALID","external origins in csp are not enabled in this rollout",void 0,"csp-not-enabled"),t.connectDomains.length!==0)return n?.terminal===true&&p("MANIFEST_INVALID","runtime.terminal cannot be combined with csp.connectDomains","connectDomains","terminal-with-connect-domains"),Object.freeze({connectDomains:t.connectDomains})}function Ma(e,n){vn(H(e)?ra(e,["csp","downloads"]):e,new Set,0,true,true),Ot(e),H(e)||p("MANIFEST_INVALID"),G(e,js,vs),M(e,"_meta")&&F("_meta",()=>qi(e._meta)),e.manifestVersion!==2&&p("MANIFEST_INVALID");let t;M(e,"runtime")&&(t=F("runtime",()=>Pa(e.runtime)));let i;M(e,"csp")&&(i=F("csp",()=>Sa(e.csp,t)));let r=F("pluginId",()=>Mt(e.pluginId,"pluginId")),o=F("definitionId",()=>Mt(e.definitionId,"definitionId")),a=F("version",()=>le(e,"version",1)),s=F("name",()=>Fi(e.name,"name")),c=F("description",()=>Fi(e.description,"description")),d;M(e,"icon")&&((typeof e.icon!="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(e.icon))&&p("MANIFEST_INVALID","icon is invalid","icon"),d=e.icon);let l;M(e,"tone")&&((typeof e.tone!="string"||!It.includes(e.tone))&&p("MANIFEST_INVALID","tone is invalid","tone"),l=e.tone),e.entry!=="ui/index.html"&&p("MANIFEST_INVALID","entry path is not fixed","entry","fixed-value");let u;M(e,"entryHash")&&(u=F("entryHash",()=>Ki(e.entryHash)));let f;M(e,"initialState")&&(f=F("initialState",()=>ba(e.initialState)));let A;M(e,"usage")&&(e.usage!=="card"&&e.usage!=="window"&&p("MANIFEST_INVALID","usage is invalid","usage"),A=e.usage);let I;M(e,"detailPanel")&&(typeof e.detailPanel!="boolean"&&p("MANIFEST_INVALID","detailPanel is invalid","detailPanel"),I=e.detailPanel);let h;if(M(e,"displayModes")){((A??tn)!==tn||!Array.isArray(e.displayModes)||e.displayModes.length===0)&&p("MANIFEST_INVALID","displayModes are only valid for window Apps","displayModes");let P=new Set(["inline","floating","focused"]);(new Set(e.displayModes).size!==e.displayModes.length||e.displayModes.some(R=>typeof R!="string"||!P.has(R)))&&p("MANIFEST_INVALID","displayModes are invalid","displayModes"),h=e.displayModes;}(A??tn)===tn&&I!==void 0&&p("MANIFEST_INVALID","detailPanel is card-only","detailPanel");let T=n.mode??"local";T!=="local"&&T!=="installed"&&T!=="published"&&p("MANIFEST_INVALID","manifest mode is invalid"),T!=="local"&&u===void 0&&p("MANIFEST_INVALID","installed manifests require entryHash","entryHash","required-when-installed"),T!=="local"&&f!==void 0&&f.hash===void 0&&p("MANIFEST_INVALID","installed manifests require initialState.hash","initialState.hash","required-when-installed"),(!Array.isArray(e.surfaces)||e.surfaces.length===0)&&p("MANIFEST_INVALID","surfaces are invalid","surfaces"),e.surfaces.length>2&&W("surfaces exceed the v2 limit","surfaces","too-many-items");let z=[],v=new Set;for(let P of e.surfaces)(typeof P!="string"||!gt.includes(P))&&p("MANIFEST_INVALID","surface is unsupported","surfaces"),v.has(P)&&p("MANIFEST_INVALID","surfaces contain a duplicate","surfaces","duplicate-item"),v.add(P),z.push(P);H(e.size)||p("MANIFEST_INVALID","size must be an object","size"),F("size",()=>G(e.size,["height"]));let b=F("size",()=>le(e.size,"height",1));b>720&&W("size.height exceeds the v2 limit","size.height","too-large");let C=F("stateProjection",()=>Lt(e.stateProjection)),$=e.summaryProjection===void 0?void 0:F("summaryProjection",()=>Lt(e.summaryProjection));$!==void 0&&$.allow.some(P=>!C.allow.includes(P))&&p("MANIFEST_INVALID","summaryProjection must be a subset of stateProjection.allow","summaryProjection");let D=F("dataPaths",()=>ua(e.dataPaths,C.allow)),O=M(e,"deviceFeatures")?F("deviceFeatures",()=>fa(e.deviceFeatures)):void 0,S=M(e,"downloads")?F("downloads",()=>ya(e.downloads)):void 0;Array.isArray(e.actions)||p("MANIFEST_INVALID","actions must be an array","actions"),e.actions.length>32&&W("actions exceed the v2 limit","actions","too-many-items");let y=[],m=new Set,N=0,L=0;for(let[P,R]of e.actions.entries()){let J=`actions[${P}]`,x=F(J,()=>ha(R));if(m.has(x.actionId)&&p("MANIFEST_INVALID","actions contain a duplicate actionId",`${J}.actionId`,"duplicate-item"),x.schedule!==void 0&&(N+=1,N>Ni&&p("MANIFEST_INVALID","an App declares at most one scheduled action",`${J}.schedule`,"duplicate-item")),x.job!==void 0&&(L+=1,L>bi&&p("MANIFEST_INVALID","an App declares at most one job action",`${J}.job`,"duplicate-item")),x.backend.type==="core"&&x.backend.handler==="state.set"){x.mutation||p("MANIFEST_INVALID","state.set actions must be mutations",`${J}.mutation`);for(let Ie of Object.keys(x.inputSchema.properties))C.allow.includes(Ie)||p("MANIFEST_INVALID","state.set input paths must be projection-allowed",`${J}.inputSchema.properties`);}m.add(x.actionId),y.push(x);}return {manifestVersion:2,pluginId:r,definitionId:o,version:a,name:s,description:c,...d===void 0?{}:{icon:d},...l===void 0?{}:{tone:l},entry:"ui/index.html",...u===void 0?{}:{entryHash:u},...t===void 0?{}:{runtime:t},...i===void 0?{}:{csp:i},...f===void 0?{}:{initialState:f},...A===void 0?{}:{usage:A},...I===void 0?{}:{detailPanel:I},...h===void 0?{}:{displayModes:h},surfaces:z,size:{height:b},stateProjection:C,...$===void 0?{}:{summaryProjection:$},...D===void 0?{}:{dataPaths:D},...O===void 0?{}:{deviceFeatures:O},...S===void 0?{}:{downloads:S},actions:y}}function qi(e){H(e)||p("MANIFEST_INVALID","_meta must be an object");let n=JSON.stringify(e);(n===void 0||Buffer.byteLength(n,"utf8")>Js)&&W("_meta exceeds the 4 KiB limit",void 0,"meta-too-large");}function Oa(e){let n={},t={};for(let o of e.actions){n[o.actionId]={capabilities:[o.capability],inputKeys:Object.keys(o.inputSchema.properties??{}),...o.dataInputs===void 0?{}:{dataInputs:o.dataInputs},resultProjection:o.resultProjection,...o.confirmation===void 0?{}:{confirmation:o.confirmation},...o.content===void 0?{}:{content:o.content},...o.schedule===void 0?{}:{schedule:o.schedule},...o.job===void 0?{}:{job:o.job},...o.jobAccess===void 0?{}:{jobAccess:o.jobAccess},...o.backend.type!=="skill"||o.backend.env===void 0?{}:{env:o.backend.env}};let a=o.backend.type==="skill"||o.backend.type==="core"&&o.backend.handler==="state.set";t[o.actionId]={actionId:o.actionId,mutation:o.mutation,backend:o.backend,launchPolicy:a?"allowed":"denied",...a?{}:{denialCode:"EXEC_DENIED"}};}let i={id:e.definitionId,version:e.version,renderer:"sandbox-html",...e.usage===void 0?{}:{usage:e.usage},...e.detailPanel===void 0?{}:{detailPanel:e.detailPanel},...e.displayModes===void 0?{}:{displayModes:e.displayModes},surfaces:e.surfaces,stateProjection:e.stateProjection,...e.summaryProjection===void 0?{}:{summaryProjection:e.summaryProjection},...e.dataPaths===void 0?{}:{dataPaths:e.dataPaths},...e.downloads===void 0?{}:{downloads:e.downloads},actions:n},r={entry:{path:"ui/index.html",...e.entryHash===void 0?{}:{hash:e.entryHash}},...e.initialState===void 0?{}:{initialState:e.initialState}};return {manifest:e,definition:i,handlers:t,resources:r}}function Ct(e,n,t,i,r,o){if(typeof e=="string"){let a=r.length>0&&o.some(s=>Be(r.join("."),s));return (e.length>4096||Vn(e,false,false,a))&&de("state contains an unsafe string"),e}if(e===null||typeof e=="boolean")return e;if(typeof e=="number")return Number.isFinite(e)||de("state contains a non-finite number"),e;(e===void 0||typeof e!="object"||typeof e=="function"||typeof e=="bigint")&&de("state contains a non-JSON value"),t>8&&de("state is too deep"),n.has(e)&&de("state contains a cycle"),n.add(e);try{let a;if(Array.isArray(e))e.length>128&&de("state array is too long"),a=e.map(c=>Ct(c,n,t+1,2097152,r,o));else {H(e)||de("state contains a non-plain object");let c={};for(let[d,l]of Object.entries(e))(d.length>4096||!Sn.test(d)||ze(d))&&(d.length>4096&&de("state key is too long"),de("state contains a reserved or invalid key")),c[d]=Ct(l,n,t+1,2097152,[...r,d],o);a=c;}let s=JSON.stringify(a);return (s===void 0||Buffer.byteLength(s,"utf8")>i)&&de("state subtree is too large"),a}finally{n.delete(e);}}function kt(e,n=[]){H(e)||de("initial state must be a JSON object");let t=Ct(e,new Set,0,2097152,[],n);return (t===null||Array.isArray(t)||typeof t!="object")&&de(),t}function La(e,n={}){vn(e),H(e)||p("MANIFEST_INVALID"),G(e,xs),e.manifestVersion!==1&&p("MANIFEST_INVALID");let t=St(me(e,"pluginId")),i=St(me(e,"definitionId")),r=le(e,"version",1),o=le(e,"primitiveSet",1),a=n.supportedPrimitiveSet??Ps;(!Number.isSafeInteger(a)||a<1)&&p("MANIFEST_INVALID"),o>a&&p("PRIMITIVE_SET_UNSUPPORTED"),H(e.activation)||p("MANIFEST_INVALID"),G(e.activation,["kind","language"]),e.activation.kind!=="fenced-code"&&p("MANIFEST_INVALID");let s=St(me(e.activation,"language")),c=aa(e.schema),d=pa(e.layout,c);return {manifestVersion:1,pluginId:t,definitionId:i,version:r,primitiveSet:o,activation:{kind:"fenced-code",language:s},schema:c,layout:d}}function Ra(e,n={}){return H(e)||p("MANIFEST_INVALID"),Object.hasOwn(e,"lineage")&&p("MANIFEST_INVALID","lineage is only allowed in product bundle indexes"),e.manifestVersion===2?Ma(e,n):La(e,n)}function sn(e,n={}){try{return Ra(e,n)}catch(t){if(t instanceof oe)throw t;return p("MANIFEST_INVALID")}}function an(e,n={}){let t=sn(e,n);return t.manifestVersion===2?Oa(t):t}var Ps,Ss,Ms,Xi,Os,Ls,Rs,Us,Vi,Cs,ws,ks,xs,js,vs,Vs,Fs,Bs,Hs,zs,Js,Gs,$s,Ws,Xs,Ks,Ys,qs,Zs,Qs,ea,na,ta,ia,oa,oe,xt=w(()=>{g();Si();De();_t();Oi();bt();Et();Tt();vi();Ue();Ps=1,Ss=/^[a-z][a-zA-Z0-9]*(\.[a-zA-Z0-9]+)+$/,Ms=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,Xi=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,Os=/<\/?[A-Za-z][^>]*>/,Ls=/^(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)/,Rs=/^(?:https?|file|ftp|ws|wss):\/\//i,Us=/^\s*(?:javascript|data):/i,Vi=/data:[^,\s]*,/i,Cs=/(?:https?|file|ftp|ws|wss):\/\//i,ws=/javascript:/i,ks=/(?:^[\s]*|[\s"'(=])(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)(?=[^\s"'<>])[^\s"'<>]*/,xs=["manifestVersion","pluginId","definitionId","version","primitiveSet","activation","schema","layout"],js=["manifestVersion","pluginId","definitionId","version","name","description","entry","surfaces","size","stateProjection","actions"],vs=["_meta","icon","tone","entryHash","runtime","csp","initialState","usage","detailPanel","displayModes","summaryProjection","dataPaths","focusedAiDataPaths","deviceFeatures","downloads"],Vs=["actionId","capability","mutation","inputSchema","resultProjection","backend"],Fs=["confirmation","dataInputs","content","schedule","job","jobAccess","_meta"],Bs=["everyMinutes"],Hs=["timeoutMs"],zs=["deadlineMs"],Js=4*1024,Gs=["type","handler"],$s=["type","command"],Ws=["env"],Xs=["type","entry"],Ks=["path"],Ys=["hash"],qs=/^[0-9a-f]{64}$/,Zs=/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/,Qs=/[\r\n]/,ea=16,na=16,ta=32,ia=/^[a-z][A-Za-z0-9]{0,31}$/,oa=["card-shell","meta-banner","heading","labeled-text","step-flow","text-list"],oe=class e extends Error{constructor(t,i=t,r,o){super(i);this.code=t;this.path=r;this.rule=o;}code;path;rule;name="UiPluginValidationError";withPathPrefix(t){return new e(this.code,this.message,rn(t,this.path),this.rule)}};});function io(e){return typeof e=="string"&&e.length<=Ca&&Ua.test(e)}function k(e,n,t,i,r){throw new _e(e,{path:n,rule:t,...i===void 0?{}:{message:i},...r===void 0?{}:{file:r}})}function Q(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 X(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function fe(e){let n=`_meta["${Oe}"]`;return e===void 0||e===""?n:e.startsWith("[")?`${n}${e}`:`${n}.${e}`}function ja(e){return e.toLowerCase().replace(/_/g,"-")}function va(e){if(e===void 0||e==="")return "";let n=/^([^.[]+)(.*)$/.exec(e);if(!n)return fe(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 fe("definitionVersion");case "definitionId":return fe("definitionId");default:return fe(`${t}${i}`)}}function oo(e,n,t){return {path:t(e.path),rule:e.rule??ja(e.code),...e.message!==e.code?{message:e.message}:{},file:n}}function ro(e){return JSON.parse(JSON.stringify(e))}function Vt(e,n,t=0,i=new Set){if(typeof e=="string"){e.length>4096&&k("LIMIT_EXCEEDED",n,"string-too-long"),(wa.test(e)||ka.test(e)||xa.test(e))&&k("UNSAFE_VALUE",n,"unsafe-value");return}if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){Number.isFinite(e)||k("MANIFEST_INVALID",n,"non-finite-number");return}typeof e!="object"&&k("MANIFEST_INVALID",n,"non-json-value"),t>8&&k("LIMIT_EXCEEDED",n,"too-deep"),i.has(e)&&k("MANIFEST_INVALID",n,"cycle"),i.add(e);try{if(Array.isArray(e)){e.length>128&&k("LIMIT_EXCEEDED",n,"array-too-long"),e.forEach((r,o)=>Vt(r,`${n}[${o}]`,t+1,i));return}Q(e)||k("MANIFEST_INVALID",n,"non-plain-object");for(let[r,o]of Object.entries(e))Vt(o,n===""?r:`${n}.${r}`,t+1,i);}finally{i.delete(e);}}}function ue(e,n){return (typeof e!="string"||e.length===0)&&k("MANIFEST_INVALID",n,"string"),e}function We(e,n){return Q(e)||k("MANIFEST_INVALID",n,"object"),e}function Va(e,n){Array.isArray(e)||k("MANIFEST_INVALID",n,"array"),e.forEach((t,i)=>ue(t,`${n}[${i}]`));}function Fa(e,n){typeof e!="boolean"&&k("MANIFEST_INVALID",n,"boolean");}function cn(e,n,t,i){for(let r of Object.keys(e))!t.includes(r)&&!i.includes(r)&&k("MANIFEST_INVALID",`${n}.${r}`,"unknown-key");for(let r of t)X(e,r)||k("MANIFEST_INVALID",`${n}.${r}`,"missing-key");}function Ba(e,n){if(e!=="icon")switch(Vt(n,e),e){case "long_description":case "homepage":case "documentation":case "support":case "license":ue(n,e);return;case "author":{let t=We(n,e);cn(t,e,["name"],["email","url"]);for(let i of Object.keys(t))ue(t[i],`${e}.${i}`);return}case "repository":{let t=We(n,e);cn(t,e,[],["type","url"]);for(let i of Object.keys(t))ue(t[i],`${e}.${i}`);return}case "icons":{Array.isArray(n)||k("MANIFEST_INVALID",e,"array"),n.forEach((t,i)=>{let r=`${e}[${i}]`,o=We(t,r);cn(o,r,["src","size"],["theme"]),ue(o.src,`${r}.src`),ue(o.size,`${r}.size`),X(o,"theme")&&ue(o.theme,`${r}.theme`);});return}case "screenshots":case "keywords":case "privacy_policies":Va(n,e);return;case "tools":{Array.isArray(n)||k("MANIFEST_INVALID",e,"array"),n.forEach((t,i)=>{let r=`${e}[${i}]`,o=We(t,r);cn(o,r,["name"],["description"]),ue(o.name,`${r}.name`),X(o,"description")&&ue(o.description,`${r}.description`);});return}case "prompts":{Array.isArray(n)||k("MANIFEST_INVALID",e,"array"),n.forEach((t,i)=>{let r=`${e}[${i}]`,o=We(t,r);cn(o,r,["name","text"],["description","arguments"]),ue(o.name,`${r}.name`),ue(o.text,`${r}.text`);});return}case "tools_generated":case "prompts_generated":Fa(n,e);return;case "localization":case "compatibility":case "user_config":We(n,e);return;default:k("MANIFEST_INVALID",e,"unknown-key");}}function Fn(e){return typeof e=="string"&&ge.test(e)?e:void 0}function so(e){return Number.isSafeInteger(e)&&e>=1?e:void 0}function Ha(e){let n=Fn(e.name);if(n===void 0)return;let t=e._meta,i=Q(t)?t[Oe]:void 0,r=Q(i)?i:{},o=X(r,"definitionId")?Fn(r.definitionId):n,a=X(r,"definitionVersion")?so(r.definitionVersion):1;return {pluginId:n,...o===void 0?{}:{definitionId:o},...a===void 0?{}:{definitionVersion:a}}}function za(e){let n=Fn(e.pluginId);if(n===void 0)return;let t=Fn(e.definitionId),i=so(e.version);return {pluginId:n,...t===void 0?{}:{definitionId:t},...i===void 0?{}:{definitionVersion:i}}}function zt(e){try{let n=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e));if(!Q(n))return !1;let t=n._meta;return Q(t)&&X(t,Oe)}catch{return false}}function Ja(e,n){if(e===ke)return n.builtinOnly===true;let t=n._meta,i=Q(t)?t[Oe]:void 0;return Q(i)&&i.builtinOnly===true}function Ga(e,n){X(e,"server")&&k("MANIFEST_INVALID","server","server-unsupported","phase 1 runs CrewX-owned Apps only");for(let s of Object.keys(e))Bt.includes(s)||k("MANIFEST_INVALID",s,"unknown-key");for(let s of Ht)X(e,s)||k("MANIFEST_INVALID",s,"missing-key");e.manifest_version!==jt&&k("MANIFEST_INVALID","manifest_version","unsupported-version",`manifest_version must be "${jt}"`),io(e.version)||k("MANIFEST_INVALID","version","semver","version must be a semver.org version such as 0.1.0");let t=e._meta;Q(t)||k("MANIFEST_INVALID","_meta","object"),X(t,Oe)||k("MANIFEST_INVALID",fe(),"missing-key");let i=t[Oe];Q(i)||k("MANIFEST_INVALID",fe(),"object");for(let s of Object.keys(i))vt.includes(s)||to.includes(s)||k("MANIFEST_INVALID",fe(s),"unknown-key");for(let s of vt)s==="actions"&&n!==void 0||X(i,s)||k("MANIFEST_INVALID",fe(s),"missing-key");if(n!==void 0&&X(i,"actions")&&k("MANIFEST_INVALID",fe("actions"),"two-truths",`actions are declared in both ${K} and ${Y}; a server.ts App keeps them in the tools file only`),$a(i.actions),X(i,"definitionVersion")){let s=i.definitionVersion;(!Number.isSafeInteger(s)||s<1)&&k("MANIFEST_INVALID",fe("definitionVersion"),"positive-integer");}let r={};for(let s of no)X(e,s)&&(Ba(s,e[s]),r[s]=ro(e[s]));let o={};for(let[s,c]of Object.entries(t))s!==Oe&&(o[s]=c);let a={manifestVersion:2,pluginId:e.name,definitionId:X(i,"definitionId")?i.definitionId:e.name,version:X(i,"definitionVersion")?i.definitionVersion:1,name:e.display_name,description:e.description};for(let[s,c]of Object.entries(i))s==="definitionId"||s==="definitionVersion"||(a[s]=c);return n!==void 0&&(a.actions=n.map(s=>({...s,backend:{type:"skill",entry:Ne}}))),Object.keys(o).length>0&&(a._meta=o),{v2Input:a,...Object.keys(o).length>0?{vendorMeta:o}:{},passthrough:r}}function $a(e){Array.isArray(e)&&e.forEach((n,t)=>{let i=Q(n)?n.backend:void 0;Q(i)&&X(i,"entry")&&k("MANIFEST_INVALID",fe(`actions[${t}].backend.entry`),"entry-not-authorable",`an action in ${K} cannot name an entry; a server.ts App declares its actions in ${Y}`);});}function Wa(e,n,t){Q(e)||k("MANIFEST_INVALID","","not-object","manifest.json must be a JSON object",K);let i;try{i=Ga(e,t);}catch(a){throw a instanceof _e?new _e(a.code,{...a.reason,file:K}):a}let r;try{let a=sn(i.v2Input,{mode:n.mode??"local"});a.manifestVersion!==2&&k("MANIFEST_INVALID","","v2-required"),r=a;}catch(a){throw a instanceof oe?new _e(a.code,oo(a,K,va)):a}let o=e.tools;if(Array.isArray(o)){let a=new Set(r.actions.map(s=>s.actionId));o.forEach((s,c)=>{let d=s.name;if(!a.has(d))throw new _e("MANIFEST_INVALID",{path:`tools[${c}].name`,rule:"tool-not-action",message:"every tools[].name must be an action id",file:K})});}return {file:K,manifest:r,v2Input:i.v2Input,releaseVersion:e.version,...Object.keys(i.passthrough).length>0?{mcpb:i.passthrough}:{}}}function Xa(e,n){try{let t=sn(e,{mode:n.mode??"local"});if(t.manifestVersion!==2)throw new _e("MANIFEST_INVALID",{path:"manifestVersion",rule:"v2-required",message:"a workspace App requires manifestVersion 2",file:ke});return {file:ke,manifest:t,v2Input:e}}catch(t){throw t instanceof oe?new _e(t.code,oo(t,ke,i=>i??"")):t}}function Ft(e){return ie(an(e).definition)}function Qi(e){let{entryHash:n,initialState:t,...i}=e,r={...i};return t!==void 0&&(r.initialState={path:t.path}),ro(r)}function Ka(e,n){let t=Qi(e),i=Qi(n);return [...new Set([...Object.keys(t),...Object.keys(i)])].sort().filter(o=>Z(t[o]??null)!==Z(i[o]??null))}function Ya(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 qa(e,n){let t=Ka(e,n),i=Ya(e,n),r="";try{let o=Ft(e),a=Ft(n);i=i||o!==a,r=` (definition hash ${o.slice(0,12)} vs ${a.slice(0,12)})`;}catch{i=true;}t.length===0&&!i||k("MANIFEST_DUAL_MISMATCH","","dual-manifest-mismatch",`${K} and ${ke} normalize to different definitions${r}`+(t.length>0?`; differing fields: ${t.join(", ")}`:""));}function he(e,n,t="MANIFEST_INVALID",i){return {code:t,reason:{path:e,rule:n,...i===void 0?{}:{message:i},file:Y},files:[]}}function eo(e){return {...he("","tools-needs-manifest-json","MANIFEST_INVALID",`${Y} is read with ${K} only`),files:e}}function Za(e,n){if(e.byteLength>n)return {failure:he("","file-too-large","LIMIT_EXCEEDED")};let t;try{t=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e));}catch{return {failure:he("","invalid-json")}}if(!Q(t))return {failure:he("","not-object","MANIFEST_INVALID",`${Y} must be a JSON object`)};for(let r of Object.keys(t))if(r!=="schemaVersion"&&r!=="actions")return {failure:he(r,"unknown-key")};for(let r of ["schemaVersion","actions"])if(!X(t,r))return {failure:he(r,"missing-key")};if(t.schemaVersion!==1)return {failure:he("schemaVersion","unsupported-version","MANIFEST_INVALID",`schemaVersion must be ${1}`)};let i=t.actions;if(!Array.isArray(i))return {failure:he("actions","array")};for(let[r,o]of i.entries()){if(!Q(o))return {failure:he(`actions[${r}]`,"object")};if(X(o,"backend"))return {failure:he(`actions[${r}].backend`,"tools-backend","MANIFEST_INVALID",`an action in ${Y} cannot carry a backend`)}}return {actions:i}}function Qa(e,n){let t=n.maxBytes??262144,i=[],r=new TextDecoder("utf-8",{fatal:true});for(let o of pe){let a=e[o];if(a===void 0)continue;if(a.byteLength>t)return {parsed:i,failure:{code:"LIMIT_EXCEEDED",reason:{path:"",rule:"file-too-large",file:o},files:[o]}};let s;try{s=JSON.parse(r.decode(a));}catch{return {parsed:i,failure:{code:"MANIFEST_INVALID",reason:{path:"",rule:"invalid-json",file:o},files:[o]}}}if(!Q(s))return {parsed:i,failure:{code:"MANIFEST_INVALID",reason:{path:"",rule:"not-object",message:`${o} must be a JSON object`,file:o},files:[o]}};i.push({file:o,raw:s});}return {parsed:i}}function Jt(e,n={}){let{parsed:t,failure:i}=Qa(e,n),r=pe.filter(A=>e[A]!==void 0);if(i!==void 0)return {ok:false,rejection:i,parseFailure:true,builtinOnly:false};let o=e[Y],a=o===void 0?void 0:Za(o,n.maxBytes??262144);if(t.length===0)return {ok:false,rejection:a===void 0?{code:"MANIFEST_INVALID",reason:{path:"",rule:"no-manifest-file",message:"neither manifest.json nor ui-plugin.json is present"},files:[]}:eo(r),parseFailure:true,builtinOnly:false};let s=t[0],c=s.file===K?Ha(s.raw):za(s.raw),d=t.some(A=>Ja(A.file,A.raw)),l;if(a!==void 0){let A=t.some(I=>I.file===K)?a.failure:eo(r);if(A!==void 0)return {ok:false,rejection:A,parseFailure:false,...c===void 0?{}:{identity:c},builtinOnly:d};l=a.actions;}let u=[];try{for(let A of t)u.push(A.file===K?Wa(A.raw,n,l):Xa(A.raw,n));u.length===2&&qa(u[0].manifest,u[1].manifest);}catch(A){if(A instanceof _e)return {ok:false,rejection:{code:A.code,reason:A.reason,files:A.code==="MANIFEST_DUAL_MISMATCH"?[...pe]:A.reason.file===void 0||A.reason.file===Y?r:[A.reason.file]},parseFailure:false,...c===void 0?{}:{identity:c},builtinOnly:d};throw A}let f=u[0];return {ok:true,...f,identity:c??{pluginId:f.manifest.pluginId},files:r}}var K,ke,pe,jt,Oe,Bt,Ht,no,vt,to,Ua,Ca,wa,ka,xa,_e,Gt=w(()=>{g();Ce();De();bt();Ue();xt();K="manifest.json",ke="ui-plugin.json",pe=[K,ke],jt="0.3",Oe="dev.crewx",Bt=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"]),Ht=Object.freeze(["manifest_version","name","display_name","version","description","_meta"]),no=Object.freeze(Bt.filter(e=>e!=="server"&&!Ht.includes(e))),vt=Object.freeze(["entry","surfaces","size","stateProjection","actions"]),to=Object.freeze(["definitionId","definitionVersion","icon","tone","entryHash","runtime","initialState","usage","detailPanel","displayModes","summaryProjection","dataPaths","focusedAiDataPaths","csp","deviceFeatures","downloads"]),Ua=/^(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-]+)*))?$/,Ca=256,wa=/<\/?[A-Za-z][^>]*>/,ka=/^\s*javascript:/i,xa=/data:[^,\s]*,/i;_e=class extends Error{constructor(t,i){super(`${t}: ${i.path||"<file>"} (${i.rule})`);this.code=t;this.reason=i;}code;reason};});function yo(e){if(e===void 0)return {kind:"none"};if(typeof e!="string")return {kind:"invalid",reason:"bad-path"};if(tc.test(e))return {kind:"url",declared:e};if(!rc(e))return {kind:"invalid",reason:"bad-path",declared:e};let n=e.lastIndexOf("."),t=n<0?void 0:ec.get(e.slice(n+1).toLowerCase());return t===void 0?{kind:"invalid",reason:"bad-type",declared:e}:{kind:"file",path:e,contentType:t}}function rc(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 Wt(e,n){let t=yo(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:[$t(t.reason,t.declared)]};let i=await n(t.path);if(typeof i=="string")return {diagnostics:[$t(i,t.path)]};let r=Ao(t.contentType,i);if(!r.ok)return {diagnostics:[$t(r.reason,t.path)]};let o={path:t.path,contentType:t.contentType,byteLength:i.byteLength,bytes:i},a=r.square===false?[{code:"ICON_NOT_SQUARE",severity:"warning",declared:t.path}]:[];return {file:o,diagnostics:a}}function $t(e,n){return {code:"ICON_INVALID",severity:"error",reason:e,...n===void 0?{}:{declared:n}}}function Ao(e,n){if(n.byteLength>262144)return {ok:false,reason:"too-large"};if(e==="image/png")return !lo(n,ic)||Ac(n,12,16)!=="IHDR"||n.byteLength<24?{ok:false,reason:"bytes-mismatch"}:{ok:true,square:po(uo(n,16),uo(n,20))};if(e==="image/jpeg"){if(!lo(n,oc))return {ok:false,reason:"bytes-mismatch"};let t=fc(n);return {ok:true,square:t===void 0?void 0:po(t.width,t.height)}}return sc(n)}function sc(e){let n;try{n=nc.decode(e);}catch{return {ok:false,reason:"bytes-mismatch"}}return lc(n)?{ok:false,reason:"unsafe-svg"}:ac.test(n)?{ok:true,square:uc(n)}:{ok:false,reason:"bytes-mismatch"}}function lc(e){if(cc.some(n=>n.test(e)))return true;for(let n of e.matchAll(dc))if(!(n[1]??n[2]??n[3]??"").startsWith("#"))return true;for(let n of e.matchAll(pc))if(ao.lastIndex=n.index??0,!ao.test(e))return true;return false}function uc(e){let n=/<svg\b[^>]*>/i.exec(e)?.[0];if(n===void 0)return;let t=Io(n,"viewBox");if(t!==void 0){let o=t.trim().split(/[\s,]+/).map(Number);return o.length===4&&o.every(Number.isFinite)?o[2]===o[3]:void 0}let i=co(n,"width"),r=co(n,"height");return i===void 0||r===void 0?void 0:i===r}function Io(e,n){let t=new RegExp(`\\s${n}\\s*=\\s*(?:"([^"]*)"|'([^']*)')`).exec(e);return t?.[1]??t?.[2]}function co(e,n){let t=Io(e,n),i=t===void 0?null:/^\s*(\d+(?:\.\d+)?)(?:px)?\s*$/.exec(t);return i===null?void 0:Number(i[1])}function fc(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(yc(t))return n+9>e.byteLength?void 0:{height:fo(e,n+5),width:fo(e,n+7)};n+=2+i;}}function yc(e){return e>=192&&e<=207&&e!==196&&e!==200&&e!==204}function po(e,n){if(!(e<=0||n<=0))return e===n}function lo(e,n){return e.byteLength>=n.length&&n.every((t,i)=>e[i]===t)}function Ac(e,n,t){return String.fromCharCode(...e.subarray(n,t))}function uo(e,n){return (e[n]<<24|e[n+1]<<16|e[n+2]<<8|e[n+3])>>>0}function fo(e,n){return e[n]<<8|e[n+1]}var ec,nc,tc,ic,oc,ac,cc,dc,pc,ao,Xt=w(()=>{g();ec=new Map([["svg","image/svg+xml"],["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"]]),nc=new TextDecoder("utf-8",{fatal:true}),tc=/^[A-Za-z][A-Za-z0-9+.-]*:/,ic=[137,80,78,71,13,10,26,10],oc=[255,216,255];ac=/^\s*(?:<\?[\s\S]*?\?>\s*|<!--[\s\S]*?-->\s*)*<svg(?=[\s/>])/,cc=[/<script/i,/[\s"'/]on[a-z]+\s*=/i,/<foreignobject/i,/<!doctype/i,/<!entity/i,/<(?:iframe|embed|object)\b/i,/@import/i],dc=/(?:^|[\s"'/])(?:xlink:)?href\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+))/gi,pc=/url\(/gi,ao=/url\(\s*["']?#/iy;});var mo=w(()=>{g();Pi();Gt();Xt();xt();Ue();});function E(e,n=e){throw new Ee(e,n)}var Ee,Hn=w(()=>{g();Ee=class extends Error{constructor(t,i=t){super(i);this.code=t;}code;name="McpAppContractError"};});var ho=w(()=>{g();});var _o=w(()=>{g();Ce();De();Hn();ho();});function To(e,n){return Eo.add(e),n!==void 0&&Ic.set(e,n),e}function Xe(e){return e!==null&&typeof e=="object"&&Eo.has(e)}var Eo,Ic,zn=w(()=>{g();Eo=new WeakSet,Ic=new WeakMap;});function ln(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Kt(e,n,t=[]){let i=new Set([...n,...t]),r=Object.keys(e);return n.every(o=>Object.hasOwn(e,o))&&r.every(o=>i.has(o))}function bo(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let n of Object.values(e))bo(n);return Object.freeze(e)}function ee(e){throw new Te("LINEAGE_INVALID",e)}function Dc(e){throw new Te("LINEAGE_STALE",e)}function Po(e){if(!ln(e)||!Kt(e,hc,_c)||!ln(e.actions))return ee("Lineage definition shape is invalid");for(let n of Object.values(e.actions))if(!ln(n)||!Kt(n,Ec,Tc))return ee("Lineage action definition shape is invalid");return e}function Nc(e){if(!ln(e)||!Kt(e,gc,mc))return ee("Lineage entry shape is invalid");if(!Number.isSafeInteger(e.version)||e.version<1||typeof e.hash!="string"||!Do.test(e.hash))return ee("Lineage entry identity is invalid");if(e.sourceHash!==void 0&&(typeof e.sourceHash!="string"||!Do.test(e.sourceHash)))return ee("Lineage source hash is invalid");if(e.compat!==void 0&&e.compat!=="break")return ee("Lineage compatibility marker is invalid");let n=Po(e.definition);if(n.version!==e.version)return ee("Lineage version does not match its definition");if(e.sourceHash!==void 0&&n.sourceHash!==e.sourceHash)return ee("Lineage source hash does not match its definition");let t;try{t=ie(n),ce({...n,hash:e.hash});}catch{return ee("Lineage definition is invalid")}return t!==e.hash?ee("Lineage definition hash does not match"):bo({version:e.version,hash:e.hash,definition:n,...e.sourceHash===void 0?{}:{sourceHash:e.sourceHash},...e.compat===void 0?{}:{compat:e.compat}})}function No(e){return e.stateProjection?.allow??[]}function bc(e,n){let t=[],i=new Set(No(n));No(e).some(s=>!i.has(s))&&t.push("S1_STATE_PROJECTION");let r=new Set(n.dataPaths??[]);(e.dataPaths??[]).some(s=>!r.has(s))&&t.push("S2_DATA_PATHS");for(let[s,c]of Object.entries(e.actions)){let d=n.actions[s];if(d&&(c.confirmation??"native")==="native"&&(d.confirmation??"native")!=="native"){t.push("S3_ACTION_CONFIRMATION");break}}Object.keys(e.legacy?.agentAccess??{}).some(s=>!Object.hasOwn(n.actions,s))&&t.push("S4_LEGACY_AGENT_ACTIONS");let a=e.summaryProjection?.allow;if(a!==void 0){let s=new Set(n.summaryProjection?.allow??[]);a.some(c=>!s.has(c))&&t.push("S5_SUMMARY_PROJECTION");}return t}function Pc(e,n){return Z(e)===Z(n)}function Yt(e,n){if(!Array.isArray(e)||e.length===0)return ee("Definition lineage is missing");if(!ln(n)||typeof n.hash!="string")return ee("Current definition is invalid");let t,i;try{let{hash:s,...c}=n;i=Po(c),t={...i,hash:s},ce(t);}catch{return ee("Current definition is invalid")}let r=e.map(Nc),o=r[0].definition.id;if(r.some(s=>s.definition.id!==o))return ee("Lineage definition ids do not match");if(r.some((s,c)=>c>0&&s.version<=r[c-1].version))return ee("Lineage generations are not in increasing version order");if(r.some((s,c)=>r.findIndex(d=>d.hash===s.hash)!==c))return ee("Lineage contains a duplicate hash");let a=r[r.length-1];if(a.version!==t.version||a.hash!==t.hash||a.definition.id!==t.id||!Pc(a.definition,i))return Dc("The last lineage generation does not match the current package");if(t.legacy!==void 0){let s=new Set(Object.keys(t.actions)),c=new Set;for(let l of r)if(l.sourceHash===void 0)for(let u of Object.keys(l.definition.actions))s.has(u)&&c.add(u);let d=Object.keys(t.legacy.agentAccess??{});if(d.length!==c.size||d.some(l=>!c.has(l))){let l="S4_LEGACY_AGENT_ACCESS_COMPLETE";throw new Te("LINEAGE_INVALID",`Lineage compatibility failed: ${l}`,[l])}}for(let s=0;s<r.length-1;s+=1){if(r.slice(s,-1).some(l=>l.compat==="break"))continue;let d=bc(r[s].definition,t);if(d.length>0)throw new Te("LINEAGE_INVALID",`Lineage compatibility failed: ${d.join(", ")}`,d)}return Object.freeze({entries:Object.freeze(r),current:t})}var Te,Do,gc,mc,hc,_c,Ec,Tc,qt=w(()=>{g();Ce();De();Te=class extends Error{constructor(t,i=t,r=[]){super(i);this.code=t;this.violations=r;}code;violations;name="UiDefinitionLineageError"},Do=/^[0-9a-f]{64}$/,gc=["version","hash","definition"],mc=["sourceHash","compat"],hc=["id","version","actions"],_c=["sourceHash","usage","detailPanel","displayModes","renderer","surfaces","stateProjection","dataPaths","summaryProjection","downloads","legacy"],Ec=["capabilities"],Tc=["inputKeys","dataInputs","confirmation","resultProjection","content","env","schedule","job","jobAccess"];});var So,Mo,Oo,Lo,Ro=w(()=>{g();So="text/html;profile=mcp-app",Mo=["crewx_app_terminal_connect","crewx_app_html_viewer_open","crewx_app_browser"],Oo=["crewx_listWorkspaces","crewx_queryAgent","crewx_executeAgent","crewx_getTaskResult","crewx_listTasks","crewx_listAgents","callBrowser","openTab","listTabs","closeTab"],Lo="text/html";});function un(e){return typeof e=="string"&&Sc.includes(e)}function Jn(e,n){return e==="card"&&n?.type==="core"&&un(n.handler)}var Sc,Gn=w(()=>{g();Sc=Object.freeze(["card.secret-env"]);});function Uo(e,n=[],t){if(e.content!==void 0||e.confirmation!=="none")return "denied";let i=Mc();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"&&un(e.backend.handler)||e.backend?.type==="skill"?"approval_required":e.backend===void 0&&n.includes(e.actionId)?"allowed":"denied"}function Mc(e){return;}var Co=w(()=>{g();Ce();zn();Gn();});function jc(e){return An.has(e)&&(e.initialState===void 0||An.has(e.initialState))}function vo(e,n,t,i){let r=i===void 0?void 0:Object.freeze({hash:i.hash,bytes:Object.freeze(i.bytes)}),o=Object.freeze({mimeType:Lo,entryHash:e,html:n,bytes:Object.freeze(t),...r===void 0?{}:{initialState:r}});return r!==void 0&&An.add(r),An.add(o),o}function vc(e){let n=[];return e?.terminal===true&&n.push({name:"crewx_app_terminal_connect",description:"Open a local-only terminal session for this App.",inputSchema:{type:"object",properties:{workspace:{type:"string"},threadId:{type:"string"},instanceId:{type:"string"}},required:["threadId","instanceId"],additionalProperties:false},textFallback:"A local terminal connection is ready for this App.",visibility:Object.freeze(["app"]),kind:"host",resourceBinding:Pe}),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:Pe}),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:Pe}),n}function Re(e,n,t){return (typeof e!="string"||!xo.test(e))&&E(n,`${t} must be a safe identifier`),e}function fn(e,n,t){let i=e??t;return (typeof i!="string"||i.trim().length===0||i.length>Rc)&&E("TOOL_INVALID",`${n} must be a meaningful description`),i}function Qt(e){return (typeof e!="string"||e.length===0||e.length>Ke||!/<html(?:\s|>)/i.test(e)||!/<\/html\s*>/i.test(e))&&E("HTML_INVALID","MCP App HTML must be a non-empty HTML document"),e}function yn(e,n=0){try{let t=ae(e,n);return t.type!==void 0&&t.type!=="object"&&E("TOOL_INVALID","MCP App inputSchema must describe an object"),t}catch(t){if(t instanceof Ee)throw t;E("TOOL_INVALID","MCP App inputSchema must be projection-safe JSON");}}function Vc(e){return (typeof e!="string"||e.trim().length===0||e.length>Uc)&&E("TOOL_INVALID","MCP App tools require a meaningful text fallback"),e}function Fc(e){e===void 0&&E("TOOL_INVALID","MCP App tool visibility is required");let n=[...e];return (n.length===0||n.some(t=>t!=="model"&&t!=="app")||new Set(n).size!==n.length)&&E("TOOL_INVALID","MCP App tool visibility must contain model and/or app once"),n}function Fo(e){return (typeof e!="string"||!jo.test(e))&&E("RESOURCE_URI_INVALID","MCP App resource URI is not a registered ui:// URI"),e}function Bo(e){let n=Re(e.appId,"APP_ID_INVALID","Local App id"),t=fn(e.name,"Local App name",n),i=fn(e.description,"Local App description",`${t} interactive view`),r=Kn(e.definition),o=Qt(e.html),a=$n(e.entryHash,"Local App entry hash"),s=e.entryBytes===void 0?Array.from(new TextEncoder().encode(o)):Xn(e.entryBytes,"Local App entry bytes");(Wn(s)!==a||Jo(s)!==o)&&E("HTML_INVALID","Local App entry bytes do not match the HTML hash");let c=Bc(e),d=[];Array.isArray(e.actions)||E("TOOL_INVALID","Local App actions must be an array");for(let b of e.actions){let C=Re(b.actionId,"TOOL_ID_INVALID","Local App action id");(d.includes(C)||!Object.prototype.hasOwnProperty.call(r.actions,C))&&E("TOOL_INVALID",`Local App action is not declared by the UI definition: ${C}`),d.push(C);}let l=Re(e.readToolName,"TOOL_ID_INVALID","Local App read tool name"),u=e.actionToolName===void 0?void 0:Re(e.actionToolName,"TOOL_ID_INVALID","Local App action tool name");d.length===0&&u!==void 0&&E("TOOL_INVALID","A static local App cannot register an action tool"),d.length>0&&u===void 0&&E("TOOL_INVALID","A stateful local App requires an action tool name"),u!==void 0&&u===l&&E("TOOL_ID_CONFLICT",`Local App read and action tools share a name: ${l}`);let f=vc(e.runtime);f.some(b=>b.name===l||b.name===u)&&E("TOOL_ID_CONFLICT","Local App read or action tool conflicts with a requested Host capability");let A={name:l,description:`${t} current state`,inputSchema:xc,textFallback:`${t} current state is available through its open instance.`,visibility:Object.freeze(["model","app"]),kind:"read",resourceBinding:Pe},I=[Object.freeze(A)];if(I.push(...f.map(b=>Object.freeze(b))),u!==void 0){let b={name:u,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:Pe,actionIds:Object.freeze([...d])};I.push(Object.freeze(b));}let h=[],T=new Set(I.map(b=>b.name));if(u!==void 0)for(let b of e.actions){let C=`${u}__${b.actionId}`;if(C.length>128||!xo.test(C)){h.push(Object.freeze({toolName:C,actionId:b.actionId,reason:"name_too_long"}));continue}if(T.has(C)){h.push(Object.freeze({toolName:C,actionId:b.actionId,reason:"name_collision"}));continue}let $=Uo({actionId:b.actionId,confirmation:r.actions[b.actionId]?.confirmation,content:r.actions[b.actionId]?.content,backend:b.backend},e.modelActions),D=Object.freeze([...$c($,r.usage,b.backend)]),O={name:C,description:`${C} action`,inputSchema:yn(b.inputSchema),textFallback:`${C} action requests are handled by the open App instance.`,visibility:D,kind:"action",resourceBinding:Pe,actionId:b.actionId,actionIds:Object.freeze([b.actionId]),_meta:Object.freeze({ui:Object.freeze({visibility:D})})};I.push(Object.freeze(O)),T.add(C);}let z=vo(a,o,s,c===void 0?void 0:{hash:c.hash,bytes:[...c.bytes]}),v={appId:n,name:t,description:i,...e.icon===void 0?{}:{icon:Go(e.icon)},...e.tone===void 0?{}:{tone:$o(e.tone)},builtinOnly:false,definition:r,...e.runtime===void 0?{}:{runtime:Object.freeze({...e.runtime})},...e.deviceFeatures===void 0?{}:{deviceFeatures:Object.freeze([...e.deviceFeatures])},...e.downloads===void 0?{}:{downloads:e.downloads},resourceBinding:Pe,resource:z,tools:Object.freeze(I),toolDiagnostics:Object.freeze(h)};return q(v)}function Ho(e={}){return new Zt(e)}function ei(e){if(e.length===0)return yn({type:"object",properties:{},additionalProperties:false});let n=e.map(i=>i.actionId),t=new Map;for(let i of e)t.set(i.actionId,yn(i.inputSchema));return yn(Hc(n,t),Vo)}function Bc(e){let n=e.definition.dataPaths??[];if(e.initialStateBytes===void 0){e.initialStateHash!==void 0&&E("STATE_INVALID","Initial state hash has no bytes"),e.initialState!==void 0&&ae(e.initialState,0,n);return}e.initialStateHash===void 0&&E("STATE_INVALID","Initial state bytes require a hash");let t=$n(e.initialStateHash,"Initial state hash"),i=Xn(e.initialStateBytes,"Initial state bytes");Wn(i)!==t&&E("STATE_INVALID","Initial state bytes do not match the hash");let r;try{let o=new TextDecoder("utf-8",{fatal:!0}).decode(Uint8Array.from(i));r=ae(JSON.parse(o),0,n);}catch{E("STATE_INVALID","Initial state bytes are not projection-safe JSON");}return e.initialState!==void 0&&Z(r)!==Z(ae(e.initialState,0,n))&&E("STATE_INVALID","Initial state bytes do not match the state value"),{hash:t,bytes:Object.freeze([...i])}}function Hc(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 zc(e){let n=In(e),t=Re(n.appId,"APP_ID_INVALID","MCP App id"),i=Qt(n.html);Fo(n.uiUri);let r=n.definition===void 0?void 0:Kn(n.definition),o=e.provenance;o!==void 0&&(!Xe(o)||o.appId!==t||o.definitionId!==r?.id||o.version!==r?.version||o.definitionHash!==r?.hash)&&E("TOOL_INVALID","Product App built-in registration provenance is not verified");let a=Object.freeze(n.tools.map(d=>q(In(d)))),s=q({...n,appId:t,html:i,...r===void 0?{}:{definition:r},...o===void 0?{}:{provenance:o},tools:a}),c=q({uri:s.uiUri,mimeType:So,text:i,...s.csp===void 0?{}:{_meta:{ui:{csp:s.csp}}}});return q({appId:t,name:s.name,description:s.description,...s.icon===void 0?{}:{icon:s.icon},...s.tone===void 0?{}:{tone:s.tone},builtinOnly:s.builtinOnly,uiUri:s.uiUri,...r===void 0?{}:{definition:r},resourceBinding:Object.freeze({kind:"mcp",uri:s.uiUri}),resource:c,tools:a,descriptor:s})}function Jc(e){(e.resourceBinding.kind!=="instance"||e.builtinOnly!==false)&&E("STATE_INVALID","Local App registration binding is invalid"),Object.prototype.hasOwnProperty.call(e,"uiUri")&&E("STATE_INVALID","Local App registration cannot contain uiUri");let n=Re(e.appId,"APP_ID_INVALID","Local App id"),t=Kn(e.definition),i=e.provenance;i!==void 0&&(!Xe(i)||i.appId!==n||i.definitionId!==t.id||i.version!==t.version||i.definitionHash!==t.hash)&&E("TOOL_INVALID","Product App local registration provenance is not verified");let r=Gc(e.resource),o=e.tools.map(s=>{Re(s.name,"TOOL_ID_INVALID","Local App tool name"),fn(s.description,"Local App tool description","Local App tool"),Vc(s.textFallback);let c=yn(s.inputSchema,s.kind==="action"&&!("actionId"in s)?Vo:0);if((s.resourceBinding.kind!=="instance"||Object.prototype.hasOwnProperty.call(s,"resourceUri"))&&E("TOOL_INVALID","Local App tools cannot carry an MCP resource URI"),s.kind==="host")return (!kc.has(s.name)||s.visibility.length!==1||s.visibility[0]!=="app"||Object.prototype.hasOwnProperty.call(s,"actionId"))&&E("TOOL_INVALID","Local App Host tools must use an allow-listed name and app-only visibility"),q({...s,inputSchema:c,visibility:Object.freeze(["app"])});if(s.kind==="action"){if("actionId"in s){let l=Re(s.actionId,"TOOL_ID_INVALID","Local App action id");Object.prototype.hasOwnProperty.call(t.actions,l)||E("TOOL_INVALID","Local App action tool references an undeclared action");let u=Fc(s._meta.ui.visibility);return JSON.stringify(u)!==JSON.stringify(s.visibility)&&E("TOOL_INVALID","Local App action metadata visibility must match the tool visibility"),q({...s,actionId:l,actionIds:Object.freeze([l]),inputSchema:c,visibility:u,_meta:{ui:{visibility:u}}})}let d=[...s.actionIds];return (d.length===0||d.some(l=>!Object.prototype.hasOwnProperty.call(t.actions,l)))&&E("TOOL_INVALID","Local App action tool references an undeclared action"),q({...s,inputSchema:c,actionIds:Object.freeze(d)})}return q({...s,inputSchema:c})}),a=q({appId:n,name:fn(e.name,"Local App name",e.appId),description:fn(e.description,"Local App description",e.name),...e.icon===void 0?{}:{icon:Go(e.icon)},...e.tone===void 0?{}:{tone:$o(e.tone)},builtinOnly:false,definition:t,...e.runtime===void 0?{}:{runtime:Object.freeze({...e.runtime})},...e.deviceFeatures===void 0?{}:{deviceFeatures:Object.freeze([...e.deviceFeatures])},...e.downloads===void 0?{}:{downloads:e.downloads},...i===void 0?{}:{provenance:i},resourceBinding:Pe,resource:r,tools:Object.freeze(o),toolDiagnostics:Object.freeze([...e.toolDiagnostics??[]])});return wo.has(e)?e:(wo.add(a),a)}function Gc(e){let n=Qt(e.html),t=$n(e.entryHash,"Local App entry hash");if(jc(e))return e;let i=Xn(e.bytes,"Local App entry bytes");(Wn(i)!==t||Jo(i)!==n)&&E("HTML_INVALID","Local App entry bytes do not match the HTML hash");let r=e.initialState===void 0?void 0:{hash:$n(e.initialState.hash,"Initial state hash"),bytes:Xn(e.initialState.bytes,"Initial state bytes")};return r&&Wn(r.bytes)!==r.hash&&E("STATE_INVALID","Initial state bytes do not match the hash"),vo(t,n,i,r)}function $c(e,n,t){if(Jn(n,t))return ["model"];let i=t?.type==="core"&&un(t.handler);return e==="denied"||i?["app"]:["model","app"]}function Wc(e){return q({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:zo(e.definition),...e.provenance===void 0?{}:{provenance:e.provenance},entryHash:e.resource.entryHash,resourceBinding:Pe,tools:e.tools})}function Xc(e){return q({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:zo(e.definition)},resourceBinding:Object.freeze({kind:"mcp",uri:e.uiUri}),tools:e.tools})}function Kn(e){try{if(Object.isFrozen(e))return ce(e),q(e);let n=In(e);return ce(n),q(n)}catch(n){if(n instanceof Ee)throw n;E("STATE_INVALID","UI definition is not a valid immutable definition");}}function zo(e){return q({id:e.id,version:e.version,hash:e.hash})}function Kc(e){return e!==null&&typeof e=="object"&&typeof e.id=="string"&&Number.isSafeInteger(e.version)&&typeof e.hash=="string"}function ko(e,n,t){return `${e}\0${n}\0${t}`}function $n(e,n){return (typeof e!="string"||!Lc.test(e))&&E("SERIALIZATION_INVALID",`${n} is invalid`),e}function Wn(e){return crypto.createHash("sha256").update(Uint8Array.from(e)).digest("hex")}function Xn(e,n){return (!Array.isArray(e)||e.some(t=>!Number.isInteger(t)||t<0||t>255))&&E("SERIALIZATION_INVALID",`${n} is invalid`),[...e]}function Jo(e){try{return new TextDecoder("utf-8",{fatal:!0}).decode(Uint8Array.from(e))}catch{E("SERIALIZATION_INVALID","UTF-8 bytes are invalid");}}function Go(e){return (typeof e!="string"||!Cc.test(e))&&E("TOOL_INVALID","MCP App icon is invalid"),e}function $o(e){return (typeof e!="string"||!wc.has(e))&&E("TOOL_INVALID","MCP App tone is invalid"),e}function In(e,n=new Map){if(e===null||typeof e!="object")return e;let t=e;if(n.has(t)&&E("SERIALIZATION_INVALID","MCP App value contains a cycle"),Array.isArray(e)){let o=[];n.set(t,o);for(let a of e)o.push(In(a,n));return n.delete(t),o}let i;try{i=Object.getPrototypeOf(e);}catch{E("SERIALIZATION_INVALID","MCP App value cannot be cloned");}i!==Object.prototype&&i!==null&&E("SERIALIZATION_INVALID","MCP App value must be plain JSON");let r={};n.set(t,r);for(let[o,a]of Object.entries(e))Object.defineProperty(r,o,{configurable:true,enumerable:true,value:In(a,n),writable:true});return n.delete(t),r}function q(e,n=new Set){if(e===null||typeof e!="object"||n.has(e)||An.has(e))return e;n.add(e);for(let t of Object.values(e))q(t,n);return Object.freeze(e),e}var xo,jo,Lc,Ke,Rc,Uc,Cc,wc,kc,Pe,xc,An,wo,Vo,Zt,Yn=w(()=>{g();_o();Ce();De();zn();Hn();qt();Ro();Co();Gn();xo=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,jo=/^ui:\/\/crewx\/([A-Za-z][A-Za-z0-9._-]{0,127})\/([0-9a-f]{12})$/,Lc=/^[0-9a-f]{64}$/,Ke=8*1024*1024,Rc=8*1024,Uc=16*1024,Cc=/^[a-z][a-z0-9-]{0,63}$/,wc=new Set(["blue","violet","emerald","amber","rose","sky","slate","indigo"]),kc=new Set(Mo),new Set(Oo),Pe=Object.freeze({kind:"instance"}),xc=Object.freeze({type:"object",properties:Object.freeze({}),additionalProperties:false}),An=new WeakSet,wo=new WeakSet;Vo=4;Zt=class{builtinApps;localApps;builtinDescriptors;builtinTools;mcpResources=new Map;localById=new Map;registrationById=new Map;launcherById=new Map;definitionByKey=new Map;handlerByKey=new Map;mcpToolByName=new Map;localToolByName=new Map;constructor(n){let t=n.builtins??n.builtin,i=[],r=[],o=[],a=new Set,s=new Set;for(let u of t?.listMcpApps()??[]){let f=zc(u);a.has(f.appId)&&E("APP_ID_CONFLICT",`MCP App id is already registered: ${f.appId}`),a.add(f.appId);let A=f.tools;for(let I of A)s.has(I.name)&&E("TOOL_ID_CONFLICT",`MCP App tool name is already registered: ${I.name}`),s.add(I.name),this.mcpToolByName.set(I.name,I),o.push(I);this.mcpResources.set(f.resource.uri,f.resource),i.push(f),r.push(f.descriptor);}let c=(n.localApps??n.locals??[]).map(Jc),d=new Set(c.flatMap(u=>u.tools.filter(f=>!(f.kind==="action"&&"actionId"in f)).map(f=>f.name))),l=[];for(let u of c){let f=u;a.has(f.appId)&&E("APP_ID_CONFLICT",`MCP App id is already registered: ${f.appId}`),a.add(f.appId);let A=[],I=[...f.toolDiagnostics??[]];for(let h of f.tools){if(s.has(h.name)){if(h.kind==="host"&&this.localToolByName.get(h.name)?.kind==="host"){A.push(h);continue}if(h.kind==="action"&&"actionId"in h){I.push(Object.freeze({toolName:h.name,actionId:h.actionId,reason:"name_collision"}));continue}E("TOOL_ID_CONFLICT",`MCP App tool name is already registered: ${h.name}`);}if(h.kind==="action"&&"actionId"in h&&d.has(h.name)){I.push(Object.freeze({toolName:h.name,actionId:h.actionId,reason:"name_collision"}));continue}s.add(h.name),this.localToolByName.set(h.name,h),A.push(h);}(A.length!==f.tools.length||I.length!==(f.toolDiagnostics?.length??0))&&(f=q({...f,tools:Object.freeze(A),toolDiagnostics:Object.freeze(I)})),l.push(f),this.localById.set(f.appId,f);}for(let u of i)this.registrationById.set(u.appId,u),this.launcherById.set(u.appId,Xc(u)),u.definition&&this.addDefinition(u.definition);for(let u of l)this.registrationById.set(u.appId,u),this.launcherById.set(u.appId,Wc(u)),this.addDefinition(u.definition);for(let u of n.definitions??[])this.addDefinition(u);for(let u of n.handlers??[])this.addHandler(u);this.builtinApps=Object.freeze(i),this.localApps=Object.freeze(l),this.builtinDescriptors=Object.freeze(r),this.builtinTools=Object.freeze(o);}getMcpApp(n){return this.builtinApps.find(t=>t.appId===n)?.descriptor??null}listMcpApps(){return this.builtinDescriptors}listMcpAppTools(){return this.builtinTools}resolveMcpAppTool(n){return this.mcpToolByName.get(n)??null}resolveMcpAppResource(n){return typeof n!="string"||!jo.test(n)?null:this.mcpResources.get(n)??null}requireMcpAppResource(n){Fo(n);let t=this.mcpResources.get(n);return t||E("RESOURCE_NOT_FOUND",`MCP App resource is not registered: ${n}`),t}listLocalMcpApps(){return this.localApps}getLocalMcpApp(n){return this.localById.get(n)??null}listLocalMcpAppTools(){return Object.freeze([...this.localToolByName.values()])}resolveLocalMcpAppTool(n){return this.localToolByName.get(n)??null}resolveLocalMcpAppResource(n,t){let i=this.localById.get(n);return !i||t!==void 0&&i.definition.hash!==t?null:i.resource}listRegistrations(){return Object.freeze([...this.builtinApps,...this.localApps])}getRegistration(n){return this.registrationById.get(n)??null}listLaunchers(){return Object.freeze([...this.launcherById.values()].filter(n=>{let t=this.registrationById.get(n.appId),i=t?"descriptor"in t?t.descriptor.provenance:t.provenance:void 0,r=Xe(i)&&i.launcher===false;return t?.definition?.usage!=="card"&&!r}))}listCardApps(){return Object.freeze([...this.launcherById.values()].filter(n=>this.registrationById.get(n.appId)?.definition?.usage==="card"))}getLauncher(n){return this.launcherById.get(n)??null}resolveDefinition(n){if(!Kc(n))return null;let t=this.definitionByKey.get(Nt(n));if(!t||t.hash!==n.hash)return null;try{return ie(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(ko(n,t,i))??null}addDefinition(n){let t=Kn(n),i=Nt(t),r=this.definitionByKey.get(i);r&&r.hash!==t.hash&&E("STATE_INVALID",`UI definition generation conflicts: ${i}`),r||this.definitionByKey.set(i,t);}addHandler(n){(!n||typeof n.definitionId!="string"||typeof n.actionId!="string"||!Number.isSafeInteger(n.version)||n.version<1||typeof n.handle!="function")&&E("STATE_INVALID","UI action handler registration is invalid");let t=ko(n.definitionId,n.version,n.actionId);this.handlerByKey.has(t)&&E("TOOL_INVALID",`Duplicate UI action handler registration: ${t}`),this.handlerByKey.set(t,Object.freeze({...n}));}};});function Yc(e){let n=Bo({appId:e.appId,name:e.name,description:e.description,...e.icon===void 0?{}:{icon:e.icon},...e.tone===void 0?{}:{tone:e.tone},...e.normalized.manifest.runtime===void 0?{}:{runtime:e.normalized.manifest.runtime},...e.normalized.manifest.deviceFeatures===void 0?{}:{deviceFeatures:e.normalized.manifest.deviceFeatures},...e.normalized.manifest.downloads===void 0?{}:{downloads:e.normalized.manifest.downloads},definition:e.definition,html:e.html,entryHash:e.entryHash,entryBytes:e.entryBytes,initialState:e.initialState,...e.initialStateHash===void 0?{}:{initialStateHash:e.initialStateHash},...e.initialStateBytes===void 0?{}:{initialStateBytes:e.initialStateBytes},readToolName:e.toolNames.read,...e.toolNames.action===void 0?{}:{actionToolName:e.toolNames.action},actions:e.normalized.manifest.actions.map(i=>({actionId:i.actionId,inputSchema:i.inputSchema,backend:i.backend}))});return e.provenance===void 0?n:Object.freeze({...n,provenance:e.provenance})}function Wo(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=Yc(e);Ho({localApps:[t],definitions:[e.definition]});}var Xo=w(()=>{g();Yn();});function Ko(){return Object.freeze({[ni]:{candidates:new Map,assetCatalogs:new Map,preparedCandidates:new Map}})}function qc(e){if(e===null||typeof e!="object"||!(ni in e))throw new TypeError("scanCache must be created by createWorkspaceAppScanCache");return e[ni]}function Yo(e,n){let t=qc(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 ni,qo=w(()=>{g();ni=Symbol("crewx.workspace-app-scan-cache.state");});function re(e){let n=typeof e=="object"&&e!==null&&"code"in e?String(e.code):"";return n==="ENOENT"?new _("NOT_FOUND"):n==="ELOOP"?new _("PATH_ESCAPED"):n==="EFBIG"||n==="EOVERFLOW"?new _("LIMIT_EXCEEDED"):n==="EACCES"||n==="EPERM"||n==="ENOTDIR"?new _("READ_DENIED"):new _("READ_DENIED")}function nd(e){if(typeof e!="string"||e.length===0||!path.isAbsolute(e))throw new _("READ_DENIED")}function ti(e){if(typeof e!="string"||path.isAbsolute(e)||/[\\\u0000]/.test(e))throw new _("PATH_ESCAPED");if(e==="")return [];let n=e.split("/");if(n.some(t=>t.length===0||t==="."||t===".."))throw new _("PATH_ESCAPED");return n}function et(e,n){let t=path.relative(e,n);return t===""||t!==".."&&!t.startsWith(`..${path.sep}`)&&!path.isAbsolute(t)}function qe(e){return {dev:e.dev,ino:e.ino,size:e.size,mtimeNs:e.mtimeNs,ctimeNs:e.ctimeNs}}function si(e,n){return e.dev===n.dev&&e.ino===n.ino}function ai(e,n){return si(e,n)&&e.size===n.size&&e.mtimeNs===n.mtimeNs&&e.ctimeNs===n.ctimeNs}async function qn(e){nd(e);let n,t;try{n=await promises.realpath(e),t=await promises.stat(n,{bigint:!0});}catch(i){throw re(i)}if(!t.isDirectory())throw new _("READ_DENIED");return {realRoot:n,identity:qe(t)}}async function er(e,n,t){if(t.length<2||t[0]!=="apps"&&t[0]!=="skills")return;let i,r;try{if(i=path.resolve(e,t[0],t[1]),r=await promises.realpath(i),!(await promises.stat(r,{bigint:!0})).isDirectory())throw new _("READ_DENIED")}catch(o){throw o instanceof _?o:re(o)}if(!et(n,r))throw new _("PATH_ESCAPED");return r}async function Zn(e,n,t,i){let r,o,a;try{r=await promises.lstat(e,{bigint:!0}),o=await promises.realpath(e),a=await promises.stat(o,{bigint:!0});}catch(s){throw re(s)}if(!et(n,o)||t!==void 0&&!et(t,o))throw new _("PATH_ESCAPED");if(!r.isFile()||!a.isFile())throw new _("READ_DENIED");if(!si(i,r)||!si(i,a)||i.dev!==a.dev)throw new _("PATH_ESCAPED")}async function Ye(e,n){let t,i;try{t=await promises.realpath(e),i=await promises.stat(t,{bigint:!0});}catch{throw new _("PATH_ESCAPED")}if(t!==n.realRoot||!ai(n.identity,qe(i)))throw new _("PATH_ESCAPED")}function td(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 _,ri,ed,Qo,Ze,nt,nr,tr,di=w(()=>{g();_=class extends Error{constructor(t){super(t);this.code=t;}code;name="AppDiscoveryFsError"},ri=fs$1.constants.O_NOFOLLOW,ed=fs$1.constants.O_NONBLOCK,Qo=fs$1.constants.O_RDONLY|(ri??0)|(ed??0);Ze=class{async getRootIdentity(n){let t=await qn(n);return await Ye(n,t),{dev:t.identity.dev,ino:t.identity.ino,realPath:t.realRoot}}async listDirectory(n,t){let i=ti(t),r=await qn(n),o=path.resolve(n,...i),a,s;try{a=await promises.realpath(o),s=await promises.stat(a,{bigint:!0});}catch(c){let d=re(c);if(d.code==="NOT_FOUND")return [];throw d}if(!et(r.realRoot,a)||!s.isDirectory())throw new _("PATH_ESCAPED");try{let c=await promises.readdir(a,{withFileTypes:!0,encoding:"utf8"});return await Ye(n,r),c.map(td)}catch(c){let d=re(c);if(d.code==="NOT_FOUND")return [];throw d}}async readdir(n,t){return this.listDirectory(n,t)}async readDirectory(n,t){return this.listDirectory(n,t)}async readVerifiedFile(n,t,i){if(!Number.isSafeInteger(i)||i<0)throw new _("READ_DENIED");if(ri===void 0)throw new _("UNSUPPORTED");let r=ti(t),o=await qn(n),a=path.resolve(n,...r),s=path.relative(n,a);if(s===".."||s.startsWith(`..${path.sep}`)||path.isAbsolute(s))throw new _("PATH_ESCAPED");let c;try{c=await promises.open(a,Qo);}catch(d){throw re(d)}try{let d;try{let I=await c.stat({bigint:!0});d=qe(I);}catch(I){throw re(I)}if(d.size>BigInt(i))throw new _("LIMIT_EXCEEDED");if(d.size>BigInt(Number.MAX_SAFE_INTEGER))throw new _("LIMIT_EXCEEDED");await Ye(n,o);let l=await er(n,o.realRoot,r);await Zn(a,o.realRoot,l,d);let u=new Uint8Array(new ArrayBuffer(Number(d.size))),f=0;for(;f<u.byteLength;){let I;try{I=(await c.read(u,f,u.byteLength-f,f)).bytesRead;}catch(h){throw re(h)}if(I<=0)throw new _("IDENTITY_CHANGED");f+=I;}let A;try{let I=await c.stat({bigint:!0});A=qe(I);}catch(I){throw re(I)}if(!ai(d,A))throw new _("IDENTITY_CHANGED");return await Zn(a,o.realRoot,l,A),await Ye(n,o),new Uint8Array(u)}finally{await c.close().catch(()=>{});}}async fingerprintVerifiedFile(n,t,i){if(!Number.isSafeInteger(i)||i<0)throw new _("READ_DENIED");if(ri===void 0)throw new _("UNSUPPORTED");let r=ti(t),o=await qn(n),a=path.resolve(n,...r),s=path.relative(n,a);if(s===".."||s.startsWith(`..${path.sep}`)||path.isAbsolute(s))throw new _("PATH_ESCAPED");let c;try{c=await promises.open(a,Qo);}catch(d){throw re(d)}try{let d;try{let f=await c.stat({bigint:!0});d=qe(f);}catch(f){throw re(f)}if(d.size>BigInt(i)||d.size>BigInt(Number.MAX_SAFE_INTEGER))throw new _("LIMIT_EXCEEDED");await Ye(n,o);let l=await er(n,o.realRoot,r);await Zn(a,o.realRoot,l,d);let u;try{let f=await c.stat({bigint:!0});u=qe(f);}catch(f){throw re(f)}if(!ai(d,u))throw new _("IDENTITY_CHANGED");return await Zn(a,o.realRoot,l,u),await Ye(n,o),{...u,candidateRealPath:l??o.realRoot}}catch(d){throw d instanceof _?d:re(d)}finally{await c.close().catch(()=>{});}}async readFileVerified(n,t,i){return this.readVerifiedFile(n,t,i)}},nt=new Ze,nr=nt,tr=Ze;});function _n(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 or(e){return typeof e=="string"&&ge.test(e)?e:void 0}function dd(e){return e.length>0&&e!=="."&&e!==".."&&!/[\\/\u0000]/.test(e)}function je(e,n){let t=new TextEncoder().encode(e),i=new TextEncoder().encode(n),r=Math.min(t.byteLength,i.byteLength);for(let o=0;o<r;o+=1){let a=t[o]-i[o];if(a!==0)return a}return t.byteLength-i.byteLength}function pd(e){if(typeof e=="string")return {name:e,kind:"directory"};if(e===null||typeof e!="object")return null;let n=e;if(typeof n.name!="string")return null;if(n.kind==="file"||n.kind==="directory"||n.kind==="symlink"||n.kind==="other")return {name:n.name,kind:n.kind};if(n.type==="file"||n.type==="directory"||n.type==="symlink"||n.type==="other")return {name:n.name,kind:n.type};let t=n.isDirectory;if(typeof t=="function"&&t.call(e))return {name:n.name,kind:"directory"};let i=n.isSymbolicLink;if(typeof i=="function"&&i.call(e))return {name:n.name,kind:"symlink"};let r=n.isFile;return typeof r=="function"&&r.call(e)?{name:n.name,kind:"file"}:{name:n.name,kind:"other"}}function ld(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 ud(e){return ad.decode(e)}function fd(e){return JSON.parse(ud(e))}function rr(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 yd(e){if(e instanceof _)return rr(e.code);if(e!==null&&typeof e=="object"&&"code"in e){let n=e.code;if(typeof n=="string")return rr(n)}}function Se(e,n){let t=n();return Number.isFinite(t)&&Number.isFinite(e)&&t-e<=5e3}function Ad(e){if(typeof e.readVerifiedFile=="function")return e.readVerifiedFile;if(typeof e.readFileVerified=="function")return e.readFileVerified}function Id(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 sr(e,n,t,i){let r=Ad(e);if(!r)throw new _("READ_DENIED");return ld(await r.call(e,n,t,i))}async function ui(e,n,t){let i=Id(e);if(!i)throw new _("READ_DENIED");let r=await i.call(e,n,t);if(!Array.isArray(r))throw new _("READ_DENIED");return r.map(pd).filter(o=>o!==null)}function gd(e,n,t,i){return Object.freeze({code:e,...{},source:n,relativePath:t})}function md(e){if(!_n(e))throw new TypeError("productBundle.reservedIds must be an object with appIds and definitionIds arrays");try{let n=Reflect.ownKeys(e);if(n.length!==2||!n.includes("appIds")||!n.includes("definitionIds"))throw new TypeError("productBundle.reservedIds must contain exactly appIds and definitionIds");let t=(i,r)=>{if(!Array.isArray(i))throw new TypeError("productBundle.reservedIds."+r+" must be an array");let o=[];for(let a=0;a<i.length;a+=1){let s=i[a];if(typeof s!="string"||s.length===0)throw new TypeError("productBundle.reservedIds."+r+" must contain non-empty strings");o.push(s);}return Object.freeze([...new Set(o)].sort(je))};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 hd(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 En(e){return Object.freeze({appIds:Object.freeze([...new Set(e.map(n=>n.appId))].sort(je)),definitionIds:Object.freeze([...new Set(e.map(n=>n.definition.id))].sort(je))})}function tt(e,n){let t=Object.keys(e).sort(je),i=[...n].sort(je);return t.length===i.length&&t.every((r,o)=>r===i[o])}function ar(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 _d(e){let n;try{n=fd(e);}catch{return}if(!_n(n)||!tt(n,["version","packages"])||n.version!==1||!Array.isArray(n.packages)||n.packages.length>fi)return;let t=new Set,i=new Set,r=0,o=[];for(let a of n.packages){if(!_n(a))return;let s=["packageDir","appId","definition","files"],c=Object.hasOwn(a,"lineage"),d=Object.hasOwn(a,"launcher"),l=[...c?["lineage"]:[],...d?["launcher"]:[]];if(!tt(a,[...s,...l])||d&&a.launcher!==false)return;let u=ar(a.packageDir),f=or(a.appId);if(!u||u.length!==2||u[0]!=="apps"||!dd(u[1])||!f||t.has(a.packageDir)||!_n(a.definition)||!tt(a.definition,["id","version","hash"]))return;let A=or(a.definition.id),I=a.definition.version,h=a.definition.hash;if(!A||!Number.isSafeInteger(I)||I<1||typeof h!="string"||!li.test(h)||!Array.isArray(a.files)||a.files.length<2||a.files.length>yi)return;let T=new Set,z=[];for(let v of a.files){if(!_n(v)||!tt(v,["path","sha256"]))return;let b=ar(v.path);if(!b||typeof v.sha256!="string"||!li.test(v.sha256))return;let C=b.join("/"),$=`${a.packageDir}/${C}`;if(T.has(C)||i.has($))return;T.add(C),i.add($),z.push(Object.freeze({path:C,sha256:v.sha256}));}if(!pe.some(v=>T.has(v))||!T.has("ui/index.html")||(r+=z.length,r>od))return;t.add(a.packageDir),o.push(Object.freeze({packageDir:a.packageDir,...d?{launcher:false}:{},appId:f,definition:Object.freeze({id:A,version:I,hash:h}),lineage:Array.isArray(a.lineage)?a.lineage:[],files:Object.freeze(z.sort((v,b)=>je(v.path,b.path)))}));}return Object.freeze({version:1,packages:Object.freeze(o)})}function xe(e){let n=yd(e);return n==="PATH_ESCAPED"||n==="IDENTITY_CHANGED"||n==="TOCTOU"?"PATH_ESCAPED":n==="LIMIT_EXCEEDED"?"LIMIT_EXCEEDED":"BUNDLE_INTEGRITY"}async function Ed(e,n,t,i,r){let o=[],a=async(s,c)=>{if(!Se(i,r))throw new _("LIMIT_EXCEEDED");if(c>2)throw new _("LIMIT_EXCEEDED");let d=await ui(e,n,s);for(let l of d){if(typeof l.name!="string"||l.name.length===0||l.name==="."||l.name===".."||/[\\/\u0000]/.test(l.name))throw new _("PATH_ESCAPED");let u=`${s}/${l.name}`;if(l.kind==="file"){if(o.push(u.slice(t.length+1)),o.length>yi)throw new _("LIMIT_EXCEEDED")}else if(l.kind==="directory")await a(u,c+1);else throw l.kind==="symlink"?new _("PATH_ESCAPED"):new _("READ_DENIED")}};return await a(t,0),o.sort(je)}function Td(e){return pe.includes(e)?262144:e==="ui/index.html"?Ke:e==="ui/state.json"?2097152:e.startsWith("ui/assets/")?sd:rd}async function cr(e,n,t,i){if(e===void 0)return {packages:[],diagnostics:[],incomplete:false,reservedIds:cd};let r=md(e.reservedIds),o=[],a=(y,m,N)=>gd(y,"bundled",m),s=(y=[],m=false,N)=>({...N===void 0?{}:{indexHash:N},packages:y,diagnostics:o,incomplete:m,reservedIds:r});if(typeof e.root!="string"||e.root.length===0||typeof e.expectedIndexHash!="string"||!li.test(e.expectedIndexHash))return o.push(a("BUNDLE_INTEGRITY","bundle-index.json")),s();let c;try{c=await sr(n,e.root,"bundle-index.json",id);}catch(y){return o.push(a(xe(y),"bundle-index.json")),s()}let d=crypto.createHash("sha256").update(c).digest("hex");if(d!==e.expectedIndexHash)return o.push(a("BUNDLE_INTEGRITY","bundle-index.json")),s();let l=_d(c);if(l===void 0)return o.push(a("BUNDLE_INTEGRITY","bundle-index.json")),s();if(!hd(En(l.packages),r))return o.push(a("BUNDLE_INTEGRITY","bundle-index.json")),s([],false,d);if(!Se(t,i))return o.push(a("LIMIT_EXCEEDED","bundle-index.json")),s(l.packages.map(y=>({indexEntry:y,failureCode:"LIMIT_EXCEEDED"})),true,d);let u;try{u=await ui(n,e.root,"");}catch(y){return o.push(a(xe(y),"bundle-index.json")),s(l.packages.map(m=>({indexEntry:m,failureCode:xe(y)})),false,d)}if(!Se(t,i))return o.push(a("LIMIT_EXCEEDED","bundle-index.json")),s(l.packages.map(y=>({indexEntry:y,failureCode:"LIMIT_EXCEEDED"})),true,d);let f=u.find(y=>y.name==="bundle-index.json"&&y.kind==="file"),A=u.find(y=>y.name==="apps"&&y.kind==="directory"),I=y=>l.packages.map(m=>({indexEntry:m,failureCode:y}));if(!f)return o.push(a("BUNDLE_INTEGRITY","bundle-index.json")),s(I("BUNDLE_INTEGRITY"),false,d);let h=u.filter(y=>y.name!=="bundle-index.json"&&y.name!=="apps");if(h.length>0){let y=h.some(m=>m.kind==="symlink")?"PATH_ESCAPED":"BUNDLE_INTEGRITY";return o.push(a(y,"bundle-index.json")),s(I("BUNDLE_INTEGRITY"),false,d)}if(u.some(y=>y.name==="apps"&&y.kind!=="directory"))return o.push(a("PATH_ESCAPED","apps")),s(I("PATH_ESCAPED"),false,d);let T=[];if(A)try{T=await ui(n,e.root,"apps");}catch(y){return o.push(a(xe(y),"apps")),s(I(xe(y)),false,d)}if(!Se(t,i)||T.length>fi)return o.push(a("LIMIT_EXCEEDED","apps")),s(I("LIMIT_EXCEEDED"),true,d);let z=new Map(l.packages.map(y=>[y.packageDir.slice(5),y])),v=T.filter(y=>!z.has(y.name));for(let y of v)o.push(a(y.kind==="symlink"?"PATH_ESCAPED":"BUNDLE_INTEGRITY",`apps/${y.name}`));if(v.length>0){let y=v.some(m=>m.kind==="symlink")?"PATH_ESCAPED":"BUNDLE_INTEGRITY";return s(I(y),false,d)}let b=new Set,C=new Map,$=new Map;for(let y of l.packages){let m=C.get(y.appId)??[];m.push(y),C.set(y.appId,m);let N=`${y.definition.id}\0${String(y.definition.version)}`,L=$.get(N)??[];L.push(y),$.set(N,L);}for(let y of [...C.values(),...$.values()])if(y.length>1)for(let m of y)b.add(m);let D=[],O=c.byteLength,S=false;for(let y of l.packages){if(!Se(t,i)){S=true,D.push({indexEntry:y,failureCode:"LIMIT_EXCEEDED"});continue}let m;try{let P=y.lineage[y.lineage.length-1];if(!P)throw new Te("LINEAGE_INVALID","Definition lineage is missing");if(P.definition.id!==y.definition.id||P.version!==y.definition.version||P.hash!==y.definition.hash)throw new Te("LINEAGE_STALE","Last lineage generation does not match bundle identity");m=Yt(y.lineage,{...P.definition,hash:P.hash}).entries;}catch(P){let R=P instanceof Te?P.code:"LINEAGE_INVALID";o.push(a(R,y.packageDir)),D.push({indexEntry:y,failureCode:R});continue}let N=T.find(P=>P.name===y.packageDir.slice(5));if(!A||!N){D.push({indexEntry:y,failureCode:"BUNDLE_INTEGRITY"});continue}if(N.kind!=="directory"){D.push({indexEntry:y,failureCode:N.kind==="symlink"?"PATH_ESCAPED":"BUNDLE_INTEGRITY"});continue}let L;try{let P=await Ed(n,e.root,y.packageDir,t,i);if(!Se(t,i)){S=!0,D.push({indexEntry:y,failureCode:"LIMIT_EXCEEDED"});continue}let R=y.files.map(x=>x.path);if(P.length!==R.length||P.some((x,Ie)=>x!==R[Ie])){D.push({indexEntry:y,failureCode:"BUNDLE_INTEGRITY"});continue}L=new Map;let J;for(let x of y.files){if(!Se(t,i)){J="LIMIT_EXCEEDED",S=!0;break}if(O>=pi){J="LIMIT_EXCEEDED";break}let Ie;try{Ie=await sr(n,e.root,`${y.packageDir}/${x.path}`,Td(x.path));}catch(at){J=xe(at);break}if(!Se(t,i)){J="LIMIT_EXCEEDED",S=!0;break}if(O+Ie.byteLength>pi){O=pi,J="LIMIT_EXCEEDED";break}if(O+=Ie.byteLength,crypto.createHash("sha256").update(Ie).digest("hex")!==x.sha256){J="BUNDLE_INTEGRITY";break}L.set(x.path,Ie);}if(J!==void 0){D.push({indexEntry:y,failureCode:J});continue}}catch(P){Se(t,i)||(S=true),D.push({indexEntry:y,failureCode:xe(P)});continue}D.push({indexEntry:y,lineage:m,files:L,...b.has(y)?{failureCode:"DUPLICATE_ID"}:{}});}return s(D,S,d)}var id,fi,yi,od,rd,sd,pi,li,ad,cd,Ai=w(()=>{g();qt();Ue();Gt();Yn();di();id=256*1024,fi=64,yi=128,od=fi*yi,rd=2*1024*1024,sd=8*1024*1024,pi=32*1024*1024,li=/^[0-9a-f]{64}$/,ad=new TextDecoder("utf-8",{fatal:true}),cd=Object.freeze({appIds:Object.freeze([]),definitionIds:Object.freeze([])});});var Rr={};Vr(Rr,{AppDiscoveryFsError:()=>_,LOCAL_APP_TOOL_PREFIX:()=>bd,MCP_APP_WORKSPACE_TOOL_PREFIX:()=>Pd,NodeAppDiscoveryFs:()=>Ze,NodeAppDiscoveryFsAdapter:()=>tr,WORKSPACE_APP_TOOL_PREFIX:()=>Qe,createWorkspaceAppScanCache:()=>Ko,defaultAppDiscoveryFs:()=>nt,defaultNodeAppDiscoveryFs:()=>nr,deriveWorkspaceAppToolName:()=>Sd,deriveWorkspaceAppToolNames:()=>mi,discoverWorkspaceAppCandidates:()=>tp,discoverWorkspaceApps:()=>hi,isWorkspacePackage:()=>Nd,productAppBundleReservations:()=>En,scanWorkspaceApps:()=>ip});function Nd(e,n){let t=n.split("/");return t.length===2&&t[0]===e&&/^[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(t[1])}function mi(e){if(typeof e!="string"||!ge.test(e))throw new TypeError("pluginId must be a safe UI plugin identifier");let n=`${Qe}${e}`.length+7<=128?e:`hash_${crypto.createHash("sha256").update(e,"utf8").digest("hex")}`;return {read:`${Qe}${n}_read`,action:`${Qe}${n}_action`}}function Sd(e,n="read"){let t=mi(e);return n==="read"?t.read:t.action}function pr(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 Od(e,n){return n.length===0||n==="."||n===".."||/[\\/\u0000]/.test(n)?e==="skills"?"skills":"apps":`${e==="skills"?"skills":"apps"}/${n}`}function Ld(e){return e.length>0&&e!=="."&&e!==".."&&!/[\\/\u0000]/.test(e)}function Dn(e,n){let t=new TextEncoder().encode(e),i=new TextEncoder().encode(n),r=Math.min(t.byteLength,i.byteLength);for(let o=0;o<r;o+=1){let a=t[o]-i[o];if(a!==0)return a}return t.byteLength-i.byteLength}function Er(e){if(typeof e=="string")return {name:e,kind:"directory"};if(e===null||typeof e!="object")return null;let n=e;if(typeof n.name!="string")return null;if(n.kind==="file"||n.kind==="directory"||n.kind==="symlink"||n.kind==="other")return {name:n.name,kind:n.kind};if(n.type==="file"||n.type==="directory"||n.type==="symlink"||n.type==="other")return {name:n.name,kind:n.type};let t=n.isDirectory;if(typeof t=="function"&&t.call(e))return {name:n.name,kind:"directory"};let i=n.isSymbolicLink;if(typeof i=="function"&&i.call(e))return {name:n.name,kind:"symlink"};let r=n.isFile;return typeof r=="function"&&r.call(e)?{name:n.name,kind:"file"}:{name:n.name,kind:"other"}}function Rd(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 Tr(e){return Md.decode(e)}function Ud(e){return JSON.parse(Tr(e))}function Cd(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 it(e,n,t,i,r){let o={code:e,...i===void 0?{}:{pluginId:i},source:n,relativePath:t,...r?.reason===void 0?{}:{reason:Object.freeze({...r.reason})},...r?.files===void 0?{}:{files:Object.freeze([...r.files])}};return Object.freeze(o)}function lr(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 ne(e){if(e instanceof _)return lr(e.code);if(e!==null&&typeof e=="object"&&"code"in e){let n=e.code;if(typeof n=="string")return lr(n)}}function Ve(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 ur(e){return {reason:e.reason,...e.code==="MANIFEST_DUAL_MISMATCH"?{files:e.files}:{}}}function fr(e){return e==="MANIFEST_DUAL_MISMATCH"?e:Dr(e)}function wd(e){return Dr(e.code)}function Dr(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 Nr("UiPluginValidationError",e)}}function Nr(e,n){throw new Error(`Unmapped ${e} code: ${String(n)}`)}function br(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 Nr("McpAppContractError",e)}}function Me(e,n){let t=n();return Number.isFinite(t)&&Number.isFinite(e)&&t-e<=5e3}function kd(e){return {pluginId:e.appId,definitionKey:`${e.definition.id}\0${String(e.definition.version)}`}}function xd(e,n){let t=n.get("package.json");if(t!==void 0)try{let r=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(t));if(pr(r)){let o=r.bin,a=typeof o=="string"?o:pr(o)?Object.values(o).find(s=>typeof s=="string"):void 0;for(let s of [a,r.main]){if(typeof s!="string")continue;let c=jd(s);if(c&&n.has(c))return c}}}catch{}return [`${e.slice(e.lastIndexOf("/")+1)}.js`,"index.js","main.js"].find(r=>n.has(r))}function jd(e){if(e.startsWith("/")||e.includes("\\")||e.includes("\0"))return;let n=e.split("/").filter(t=>t!==".");if(!(n.length===0||n.some(t=>t.length===0||t==="..")))return n.join("/")}function vd(){return globalThis.performance?.now()??Date.now()}function ve(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let n of Object.values(e))ve(n);return Object.freeze(e)}function yr(e){return Object.freeze(Array.from(e))}async function Nn(e,n,t,i){if(n.pinnedFiles!==void 0){let s=n.pinnedFiles.get(t);if(s===void 0)throw new _("NOT_FOUND");if(s.byteLength>i)throw new _("LIMIT_EXCEEDED");return new Uint8Array(s)}let r=`${n.relativePath}/${t}`,o=n.scanContext,a=e.fingerprintVerifiedFile;if(o===void 0||!o.cacheable||typeof a!="function")return mr(e,n.root,r,i);try{let s=o.priorFingerprints.get(r)??await a.call(e,o.workspaceRoot,r,i);o.candidateRealPath=s.candidateRealPath;let c=await mr(e,n.root,r,i),d=await a.call(e,o.workspaceRoot,r,i);return o.candidateRealPath=d.candidateRealPath,Sr(s,d)&&d.size===BigInt(c.byteLength)&&!Mr(d,o.scanStartedAtNs)?o.files.set(r,{relativePath:r,byteLimit:i,fingerprint:d}):o.cacheable=!1,c}catch(s){let c=!t.includes("/")&&ne(s)==="NOT_FOUND"&&o.directoryListings.some(l=>l.relativePath===n.relativePath&&!ot(l.key,t)),d=t===Y&&ne(s)==="NOT_FOUND"&&Fd(o.directoryListings,n.relativePath);throw !c&&!d&&(o.cacheable=false),s}}async function Vd(e,n,t){if(n.pinnedFiles!==void 0)return {iconDiagnostics:[]};let i=await Wt(t,async o=>{try{return await Nn(e,n,o,262144)}catch(a){let s=ne(a);return s==="NOT_FOUND"?"missing":s==="LIMIT_EXCEEDED"?"too-large":"bad-path"}}),r=i.file;return {...r===void 0?{}:{iconFile:{path:r.path,sha256:crypto.createHash("sha256").update(r.bytes).digest("hex"),contentType:r.contentType,byteLength:r.byteLength}},iconDiagnostics:i.diagnostics}}function Fd(e,n){let t=e.find(r=>r.relativePath===n);if(t===void 0)return false;if(!ot(t.key,"dist"))return true;let i=e.find(r=>r.relativePath===`${n}/dist`);return i!==void 0&&!ot(i.key,"tools.json")}function Pr(e,n){return JSON.stringify([e.realPath,n.source,n.relativePath])}async function Hd(e,n,t,i,r,o,a,s){let c=e.fingerprintVerifiedFile,d=Pr(t,i),l=r.candidates.get(d),u=i.relativePath,f;try{f=await gr(e,n,u);}catch(S){if(ne(S)!=="NOT_FOUND")throw S}let A=f===void 0?void 0:{relativePath:u,key:f};if(A!==void 0&&(i.source==="apps"||i.source==="skills")&&!pe.some(S=>ot(A.key,S)))return Me(a,s)?l!==void 0&&l.candidate===void 0&&l.candidateRealPath===void 0&&l.files.length===0&&l.directoryListings.length===1&&l.directoryListings[0]?.relativePath===A.relativePath&&l.directoryListings[0]?.key===A.key&&(i.source==="apps"?l.diagnostic?.code==="MANIFEST_MISSING":l.diagnostic===void 0)&&typeof c=="function"?{memo:l}:typeof c!="function"?{}:{context:{state:r,cacheKey:d,workspaceRoot:n,scanStartedAtNs:o,directoryListings:Object.freeze([A]),priorFingerprints:new Map,files:new Map,cacheable:true}}:{timeLimitReached:true};let I=async S=>{if(S==="")return A;let y=`${i.relativePath}${S}`;try{let m=await gr(e,n,y);return m===void 0?void 0:{relativePath:y,key:m}}catch(m){if(ne(m)==="NOT_FOUND")return;throw m}},h=await Promise.all(Ar.map(I)),T=await Promise.all(Bd.map(I));if(!Me(a,s))return {timeLimitReached:true};let z=typeof c=="function"&&h.every(S=>S!==void 0),v=h.filter(S=>S!==void 0),b=[...v,...T.filter(S=>S!==void 0)],C=new Map,$=l!==void 0&&z,D;if(l!==void 0&&typeof c=="function"){let S=await Promise.all(l.files.map(async y=>{if(!Me(a,s))return {kind:"time",file:y};try{let m=await c.call(e,n,y.relativePath,y.byteLimit);return {kind:"fingerprint",file:y,current:m}}catch(m){return ne(m)==="NOT_FOUND"?{kind:"missing",file:y}:{kind:"error",file:y,error:m}}}));if(S.some(y=>y.kind==="time"))return {timeLimitReached:true};for(let y of S){if(y.kind==="error")throw y.error;if(y.kind==="missing"){$=false;continue}if(y.kind!=="fingerprint")continue;let{file:m,current:N}=y;C.set(m.relativePath,N),D??=N.candidateRealPath,(N.candidateRealPath!==l.candidateRealPath||!Sr(N,m.fingerprint)||Mr(N,o))&&($=false);}}let O=l!==void 0&&l.directoryListings.length===b.length&&l.directoryListings.every((S,y)=>S.relativePath===b[y]?.relativePath&&S.key===b[y]?.key);return l!==void 0&&z&&O&&$&&D===l.candidateRealPath?{memo:l}:!z||v.length!==Ar.length?{}:{context:{state:r,cacheKey:d,workspaceRoot:n,scanStartedAtNs:o,directoryListings:Object.freeze(b),priorFingerprints:C,files:new Map,...D===void 0?{}:{candidateRealPath:D},cacheable:true}}}function ot(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 gr(e,n,t){let i=Or(e);if(typeof i!="function")return;let r=await i.call(e,n,t);if(!Array.isArray(r)||r.some(a=>typeof a=="string"))return;let o=r.map(Er);if(!o.some(a=>a===null))return JSON.stringify(o.slice().sort((a,s)=>Dn(a.name,s.name)||Dn(a.kind,s.kind)).map(a=>[a.name,a.kind]))}function Sr(e,n){return e.dev===n.dev&&e.ino===n.ino&&e.size===n.size&&e.mtimeNs===n.mtimeNs&&e.ctimeNs===n.ctimeNs}function Mr(e,n){let t=e.mtimeNs-n;return t>=-Ir&&t<=Ir}function Ii(e){let n=e.scanContext,t=e.source==="skills"&&e.candidate===void 0&&e.diagnostic===void 0&&n?.files.size===0,i=e.source==="apps"&&e.candidate===void 0&&e.diagnostic?.code==="MANIFEST_MISSING"&&n?.files.size===0,r=t||i;if(n===void 0||!n.cacheable||n.candidateRealPath===void 0&&!r||n.files.size===0&&!r)return;let o=Object.freeze({...!r&&n.candidateRealPath!==void 0?{candidateRealPath:n.candidateRealPath}:{},directoryListings:n.directoryListings,files:Object.freeze([...n.files.values()]),...e.candidate===void 0?{}:{candidate:e.candidate},...e.diagnostic===void 0?{}:{diagnostic:e.diagnostic},...e.identity===void 0?{}:{identity:e.identity},...e.provenance===void 0?{}:{provenance:e.provenance}});n.state.candidates.set(n.cacheKey,o);}function zd(e,n,t){let i=crypto.createHash("sha256"),r=new TextEncoder().encode(Z(e)),o=a=>{let s=new Uint8Array(8);new DataView(s.buffer).setBigUint64(0,BigInt(a)),i.update(s);};return o(r.byteLength),i.update(r),o(n.byteLength),i.update(n),o(t.byteLength),i.update(t),i.digest("hex")}function Jd(e,n){let t={...e.definition,sourceHash:n},i;try{i=ie(t);}catch(o){throw o instanceof U&&o.code==="INPUT_INVALID"?new oe("MANIFEST_INVALID","normalized definition is invalid"):o}let r={...t,hash:i};try{ce(r);}catch{throw new oe("MANIFEST_INVALID","normalized definition is invalid")}return r}function Gd(e,n){return e.actions.some(t=>t.backend.type==="core"&&t.backend.handler!=="state.set"&&!Jn(n,t.backend))}function $d(e){if(typeof e.readVerifiedFile=="function")return e.readVerifiedFile;if(typeof e.readFileVerified=="function")return e.readFileVerified}function Or(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 mr(e,n,t,i){let r=$d(e);if(!r)throw new _("READ_DENIED");return Rd(await r.call(e,n,t,i))}async function Wd(e,n,t){let i=Or(e);if(!i)throw new _("READ_DENIED");let r=await i.call(e,n,t);if(!Array.isArray(r))throw new _("READ_DENIED");return r.map(Er).filter(o=>o!==null)}function Xd(e){let n=[];for(let t of [e.reserved,e.builtin])t&&n.push(t);return e.builtins&&"listMcpApps"in e.builtins?n.push(hr(e.builtins)):e.builtins&&n.push(e.builtins),e.builtinCatalog&&n.push(hr(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 hr(e){let n=[],t=[],i=[];for(let r of e.listMcpApps())typeof r.appId=="string"&&n.push(r.appId),r.definition&&typeof r.definition.id=="string"&&t.push(r.definition.id);for(let r of e.listMcpAppTools())typeof r.name=="string"&&i.push(r.name);return {appIds:n,definitionIds:t,toolNames:i}}function ye(e,n){e.diagnostic||(e.diagnostic=it(n,e.source,e.relativePath,e.identity?.pluginId));}function Kd(e,n){let t=new Set,i=new Map;for(let o of e){let a=o.identity?.pluginId;if(a===void 0)continue;let s=i.get(a)??[];s.push(o),i.set(a,s);}for(let o of i.values()){if(o.length<2)continue;let a=o.filter(c=>c.provenance!==void 0);if(a.length>0){let c=o.find(d=>n.has(d));if(c){for(let d of a)t.add(d);for(let d of o)d!==c&&d.provenance===void 0&&ye(d,"RESERVED_ID");continue}for(let d of o)d.provenance===void 0&&ye(d,"RESERVED_ID");if(a.length>1)for(let d of a)ye(d,"DUPLICATE_ID");continue}let s=o.filter(c=>c.source==="apps");if(s.length>1){for(let c of s)ye(c,"DUPLICATE_ID");for(let c of o.filter(d=>d.source==="skills"))ye(c,"DUPLICATE_ID");}else for(let c of o.filter(d=>d.source==="skills"))ye(c,"DUPLICATE_ID");}let r=new Map;for(let o of e){if(o.diagnostic?.code==="RESERVED_ID"||t.has(o)||o.provenance===void 0&&!n.has(o)&&i.get(o.identity?.pluginId??"")?.some(c=>c.provenance!==void 0))continue;let a=o.identity?.definitionKey;if(a===void 0)continue;let s=r.get(a)??[];s.push(o),r.set(a,s);}for(let o of r.values())if(o.length>1)for(let a of o)ye(a,"DUPLICATE_ID");return t}function Yd(e,n,t){let i=new Set,r=new Set,o=new Set,a=new Set([...t.appIds,...n.productBundleReservationMetadata?.reservedAppIds??[]]),s=new Set([...t.definitionIds,...n.productBundleReservationMetadata?.reservedDefinitionIds??[]]);for(let l of Xd(n)){for(let u of l.appIds??[])typeof u=="string"&&i.add(u);for(let u of l.definitionIds??[])typeof u=="string"&&r.add(u);for(let u of l.toolNames??[])typeof u=="string"&&o.add(u);}for(let l of e){let u=l.candidate;if(!u)continue;if(i.has(u.pluginId)||r.has(u.definitionId)){ye(l,"RESERVED_ID");continue}[u.toolNames.read,u.toolNames.action].filter(A=>A!==void 0).some(A=>o.has(A))&&ye(l,"DUPLICATE_ID");}let c=[...e.filter(l=>l.provenance!==void 0&&l.diagnostic===void 0).flatMap(l=>l.candidate?[l.candidate]:[]),...(n.productBundleReservationMetadata?.candidates??[]).filter(l=>n.productBundleReservationMetadata?.indexHash!==void 0&&l.provenance?.indexHash===n.productBundleReservationMetadata.indexHash)],d=new Set;for(let l of e){let u=l.candidate;if(!(!u||l.diagnostic||l.source!=="apps"||l.provenance!==void 0)&&e.filter(f=>f.source==="apps"&&f.identity?.pluginId===u.pluginId).length===1&&c.some(f=>f.pluginId===u.pluginId)&&!(s.has(u.definitionId)&&!c.some(f=>f.pluginId===u.pluginId&&f.definitionId===u.definitionId))&&!c.some(f=>f.pluginId!==u.pluginId&&f.definitionId===u.definitionId)&&!e.some(f=>f.identity?.pluginId!==u.pluginId&&f.identity?.definitionKey===`${u.definitionId}\0${u.version}`&&f.diagnostic?.code!=="RESERVED_ID"))try{Wo(u),d.add(l);}catch(f){ye(l,f instanceof Ee?br(f.code):"EXEC_DENIED");}}for(let l of e){let u=l.candidate;u&&l.provenance===void 0&&!d.has(l)&&(a.has(u.pluginId)||s.has(u.definitionId))&&ye(l,"RESERVED_ID");}return d}function qd(e){return [...e].sort((n,t)=>{let i=dr.indexOf(n.source)-dr.indexOf(t.source);return i!==0?i:Dn(n.relativePath,t.relativePath)})}function V(e,n,t){e.diagnostic=it(n,e.source,e.relativePath,e.identity?.pluginId,t);}async function _r(e,n,t){let i=Jt(t,{mode:"local"});if(!i.ok&&i.parseFailure){V(n,fr(i.rejection.code),ur(i.rejection));return}let r=Cd(i.identity);if(n.bundleIdentity===void 0)n.identity=r;else if(r?.pluginId!==n.bundleIdentity.appId||r.definitionKey!==`${n.bundleIdentity.definitionId}\0${String(n.bundleIdentity.version)}`){V(n,"BUNDLE_INTEGRITY");return}if(!i.ok&&i.builtinOnly){V(n,"RESERVED_ID");return}if(!i.ok){V(n,fr(i.rejection.code),ur(i.rejection));return}let o=i.manifest,a={pluginId:o.pluginId,definitionKey:`${o.definitionId}\0${String(o.version)}`};if(n.bundleIdentity===void 0&&(n.identity=a),o.actions.length>0)try{ei(o.actions.map(R=>({actionId:R.actionId,inputSchema:R.inputSchema})));}catch(R){if(R instanceof Ee){V(n,br(R.code));return}throw R}let s;try{s=await Nn(e,n,"ui/index.html",Ke);}catch(R){V(n,Ve(ne(R),"entry"));return}if(s.byteLength>Ke){V(n,"LIMIT_EXCEEDED");return}let c;try{c=Tr(s);}catch{V(n,"ENTRY_INVALID");return}if(s.byteLength===0||c.length===0){V(n,"ENTRY_INVALID");return}let d=crypto.createHash("sha256").update(s).digest("hex");if(o.entryHash!==void 0&&o.entryHash!==d){V(n,"ENTRY_INVALID");return}let l={},u,f;if(o.initialState!==void 0){try{u=await Nn(e,n,"ui/state.json",2097152);}catch(R){V(n,Ve(ne(R),"initial"));return}if(u.byteLength>2097152){V(n,"LIMIT_EXCEEDED");return}try{let R=Ud(u),J=o.dataPaths??[],x=kt(R,J);l=ae(x,0,J),He(l);}catch{V(n,"INITIAL_STATE_INVALID");return}if(f=crypto.createHash("sha256").update(u).digest("hex"),o.initialState.hash!==void 0&&o.initialState.hash!==f){V(n,"INITIAL_STATE_INVALID");return}}let A={...o,entryHash:d,...o.initialState===void 0?{}:{initialState:{path:"ui/state.json",hash:f}}},I=an(A),h=zd(A,s,u??new Uint8Array),T;try{T=Jd(I,h);}catch(R){if(R instanceof oe){V(n,wd(R));return}throw R}let z;if(n.bundleLineage!==void 0){let R=n.bundleLineage[n.bundleLineage.length-1];if(!R){V(n,"LINEAGE_INVALID");return}let{legacy:J,...x}=R.definition,{hash:Ie,...at}=T;if(Z(x)!==Z(at)){V(n,"LINEAGE_STALE");return}if(J!==void 0&&(T={...T,legacy:J}),J!==void 0)try{T={...T,hash:ie(T)},ce(T);}catch{V(n,"LINEAGE_INVALID");return}z=n.bundleLineage;}if(n.bundleIdentity!==void 0&&n.bundleIdentity.appId!==o.pluginId){V(n,"BUNDLE_INTEGRITY");return}if(n.bundleIdentity!==void 0&&(n.bundleIdentity.definitionId!==T.id||n.bundleIdentity.version!==T.version||n.bundleIdentity.definitionHash!==T.hash)){V(n,"LINEAGE_STALE");return}let v=await Vd(e,n,i.mcpb?.icon),b=mi(o.pluginId),C=o.actions.length===0?{read:b.read}:b,$=ve(I),D=ve(A),O=ve(T),S=ve({...I.handlers}),y=yr(s),m=u===void 0?void 0:yr(u),N=Object.freeze({...n.provenance===void 0?{}:{provenance:n.provenance},entry:Object.freeze({path:"ui/index.html",hash:d,bytes:y}),...m===void 0?{}:{initialState:Object.freeze({path:"ui/state.json",hash:f,bytes:m})}}),L={appId:o.pluginId,pluginId:o.pluginId,definitionId:o.definitionId,version:o.version,...i.releaseVersion===void 0?{}:{releaseVersion:i.releaseVersion},manifestFile:i.file,...i.mcpb===void 0?{}:{mcpb:ve(i.mcpb)},relativePath:n.relativePath,manifest:D,normalized:$,name:o.name,description:o.description,...o.icon===void 0?{}:{icon:o.icon},...o.tone===void 0?{}:{tone:o.tone},...v.iconFile===void 0?{}:{iconFile:Object.freeze({...v.iconFile})},...v.iconDiagnostics.length===0?{}:{iconDiagnostics:Object.freeze([...v.iconDiagnostics])},definition:O,handlers:S,resources:N,html:c,entryBytes:y,entryHash:d,initialState:ve(l),...m===void 0?{}:{initialStateBytes:m},...f===void 0?{}:{initialStateHash:f},sourceHash:h,toolNames:Object.freeze(C)},P=n.provenance===void 0?{...L,source:n.source}:{...L,provenance:n.provenance,lineage:z??[]};n.candidate=Object.freeze(P),Gd(o,T.usage)&&V(n,"EXEC_DENIED");}async function Lr(e,n){let t={};for(let i of pe)try{t[i]=await Nn(e,n,i,262144);}catch(r){if(ne(r)==="NOT_FOUND")continue;return {files:t,failure:Ve(ne(r),"manifest")}}if(t[K]!==void 0)try{t[Y]=await Nn(e,n,Y,262144);}catch(i){if(ne(i)!=="NOT_FOUND")return {files:t,failure:Ve(ne(i),"manifest")}}return {files:t}}function gi(e){return pe.some(n=>e[n]!==void 0)}async function Zd(e,n){let{files:t,failure:i}=await Lr(e,n);if(i!==void 0){V(n,i);return}let r=t[K];return r!==void 0&&!zt(r)&&(delete t[K],delete t[Y]),gi(t)?t:void 0}function Qd(e,n,t,i=Dd,r=false,o=new Set){let a=qd(e),s=Kd(a,o),c=Object.freeze(a.filter(f=>f.candidate!==void 0&&f.diagnostic===void 0&&!s.has(f)).map(f=>f.candidate)),d=Object.freeze(a.filter(f=>f.diagnostic!==void 0).map(f=>f.diagnostic)),l=r?Object.freeze({...t===void 0?{}:{indexHash:t},candidates:Object.freeze(a.filter(f=>f.source==="bundled"&&f.diagnostic===void 0&&t!==void 0&&f.candidate?.provenance?.indexHash===t).map(f=>f.candidate)),diagnostics:Object.freeze(d.filter(f=>f.source==="bundled").map(f=>Object.freeze({...f}))),reservedAppIds:Object.freeze([...i.appIds]),reservedDefinitionIds:Object.freeze([...i.definitionIds])}):void 0,u={apps:c,diagnostics:d,complete:n===void 0,...n===void 0?{}:{incompleteReason:n},...t===void 0?{}:{productBundleIndexHash:t},...l===void 0?{}:{productBundleSnapshotMetadata:l}};return Object.defineProperty(u,"candidates",{configurable:false,enumerable:false,get:()=>c}),Object.freeze(u)}function ep(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 np(e,n){if(ep(e))return {fs:e,options:n??{}};let t=e??n??{};return {fs:t.filesystem??t.fileSystem??t.fs??nt,options:t}}async function hi(e,n,t){if(typeof e!="string"||e.length===0)throw new TypeError("workspaceRoot must be explicit");let{fs:i,options:r}=np(n,t),o=r.clock??vd,a=o(),s=await cr(r.productBundle,i,a,o),c=o(),d=BigInt(Date.now())*1000000n,l=[],u=0,f,A=false,I,h;if(r.scanCache!==void 0&&typeof i.getRootIdentity=="function"&&typeof i.fingerprintVerifiedFile=="function")try{h=await i.getRootIdentity(e),I=Yo(r.scanCache,h),I.scanStartedAtNs=d;}catch(D){if(ne(D)!=="NOT_FOUND")throw D}let T=I!==void 0&&r.productBundle===void 0&&s.packages.length===0&&s.diagnostics.length===0,z=new Set,v=true;l.push(...s.diagnostics.map(D=>({source:D.source,root:r.productBundle?.root??e,name:"",relativePath:D.relativePath,diagnostic:D})));let b=s.reservedIds;s.incomplete&&(f="time_limit");for(let D of s.packages){if(!Me(c,o)){A=true,f="time_limit";break}let O=D.indexEntry,S=O.packageDir,y=D.files===void 0?void 0:xd(S,D.files),m=s.indexHash===void 0?void 0:To(Object.freeze({kind:"bundled",launcher:O.launcher!==false,indexHash:s.indexHash,packageDir:S,appId:O.appId,definitionId:O.definition.id,version:O.definition.version,definitionHash:O.definition.hash,files:O.files}),y),N={source:"bundled",root:r.productBundle?.root??e,name:S.slice(5),relativePath:S,...m===void 0?{}:{provenance:m},...D.files===void 0?{}:{pinnedFiles:D.files},...D.lineage===void 0?{}:{bundleLineage:D.lineage},bundleIdentity:{appId:O.appId,definitionId:O.definition.id,version:O.definition.version,definitionHash:O.definition.hash},identity:kd(O)};if(l.push(N),u+=1,D.failureCode!==void 0){V(N,D.failureCode);continue}if(D.files?.has(Y)===true){V(N,"EXEC_DENIED",{reason:{path:"",rule:"bundled-tool-mode-unsupported",file:Y}});continue}let L={};for(let P of pe){let R=D.files?.get(P);R!==void 0&&(L[P]=R);}if(!gi(L)){V(N,"BUNDLE_INTEGRITY");continue}if(await _r(i,N,L),!Me(c,o)){A=true,f="time_limit";break}}let C=[{source:"apps",directory:"apps"},{source:"skills",directory:"skills"}];e:for(let D of C){let{source:O,directory:S}=D,y;try{y=await Wd(i,e,S);}catch(N){if(ne(N)==="NOT_FOUND")continue;T=false,v=false,l.push({source:O,root:e,name:"",relativePath:O,diagnostic:it(Ve(ne(N),"manifest"),O,O)});continue}let m=y.filter(N=>N.kind==="directory"||N.kind==="symlink").filter(N=>Ld(N.name)).map(N=>({source:O,root:e,name:N.name,relativePath:Od(O,N.name)})).sort((N,L)=>Dn(N.relativePath,L.relativePath));for(let N of m){let L={...N};if(l.push(L),h!==void 0?z.add(Pr(h,L)):T=false,!Me(c,o)){A=true,f="time_limit";break e}let P;if(I!==void 0&&h!==void 0){try{let x=await Hd(i,e,h,L,I,d,c,o);if(x.timeLimitReached){A=!0,f="time_limit";break e}L.scanContext=x.context,P=x.memo;}catch(x){T=false,V(L,Ve(ne(x),"manifest"));continue}P===void 0&&(T=false);}if(P!==void 0){if(L.candidate=P.candidate,L.diagnostic=P.diagnostic,L.identity=P.identity,O==="skills"&&P.candidate===void 0&&P.diagnostic===void 0)continue;if(u>=64){V(L,"LIMIT_EXCEEDED");continue}if(N.relativePath.split("/").length-1>2){V(L,"LIMIT_EXCEEDED");continue}if(u+=1,!Me(c,o)){A=true,f="time_limit";break e}continue}let R;if(O==="skills"&&(R=await Zd(i,L),R===void 0)){L.diagnostic===void 0&&Ii(L);continue}if(u>=64){V(L,"LIMIT_EXCEEDED");continue}if(N.relativePath.split("/").length-1>2){V(L,"LIMIT_EXCEEDED");continue}if(!Me(c,o)){A=true,f="time_limit";break e}if(u+=1,R===void 0){let x=await Lr(i,L);if(x.failure!==void 0||!gi(x.files)){V(L,x.failure??Ve("NOT_FOUND","manifest")),Ii(L);continue}R=x.files;}if(await _r(i,L,R),Ii(L),!Me(c,o)){A=true,f="time_limit";break e}}}if(I!==void 0&&h!==void 0){let D=[...z].sort(Dn),O=I.lastCandidateKeys,S=O!==void 0&&O.length===D.length&&O.every((m,N)=>m===D[N]);if(T=T&&S,v&&!A&&f===void 0)for(let m of I.candidates.keys())try{JSON.parse(m)[0]===h.realPath&&!z.has(m)&&I.candidates.delete(m);}catch{I.candidates.delete(m);}let y=[...I.candidates.keys()].filter(m=>{try{return JSON.parse(m)[0]===h.realPath}catch{return false}});T=T&&y.length===z.size&&y.every(m=>z.has(m))&&!A&&f===void 0,I.lastCandidateScanUnchanged=T,v&&!A&&f===void 0&&(I.lastCandidateKeys=Object.freeze(D));}A&&l.push({source:"apps",root:e,name:"",relativePath:"apps",diagnostic:it("DISCOVERY_TIME_LIMIT","apps","apps")});let $=Yd(l,r,b);return Qd(l,f,s.indexHash,b,r.productBundle!==void 0,$)}var Dd,Qe,bd,Pd,dr,Md,Ar,Bd,Ir,tp,ip,Ur=w(()=>{g();Ce();bn();De();mo();Xt();Ue();Yn();Xo();Gn();Hn();qo();di();zn();Ai();Ai();Dd=En([]);Qe="crewx_local_app_",bd=Qe,Pd=Qe;dr=["bundled","apps","skills"],Md=new TextDecoder("utf-8",{fatal:true});Ar=["","/ui"],Bd=["/dist"],Ir=2000000000n;tp=hi,ip=hi;});g();var Cr="SKILL.md",cp=/^---\s*\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;function wr(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function dp(e){return e.isDirectory()||e.isSymbolicLink()}function jr(e){try{return fs$1.existsSync(e)&&fs$1.statSync(e).isDirectory()}catch{return false}}var pp=["index.js","main.js"];function Nf(e,n){let t=path.join(e,"package.json");if(fs$1.existsSync(t))try{let r=JSON.parse(fs$1.readFileSync(t,"utf8"));if(r.bin){let o=typeof r.bin=="string"?r.bin:Object.values(r.bin).find(a=>typeof a=="string");if(o){let a=path.resolve(e,o);if(fs$1.existsSync(a))return a}}if(typeof r.main=="string"){let o=path.resolve(e,r.main);if(fs$1.existsSync(o))return o}}catch{}let i=path.resolve(e,`${n}.js`);if(fs$1.existsSync(i))return i;for(let r of pp){let o=path.resolve(e,r);if(fs$1.existsSync(o))return o}}function lp(e){let n;try{n=fs$1.readFileSync(e,"utf8");}catch{return {frontmatter:{},readable:false,valid:false,hasFrontmatter:false}}let t=n.match(cp);if(!t)return {frontmatter:{},readable:true,valid:true,hasFrontmatter:false};try{let i=jsYaml.load(t[1]??"");if(!wr(i))return {frontmatter:{},readable:!0,valid:!1,hasFrontmatter:!0};let r=wr(i.metadata)?i.metadata:void 0;return {frontmatter:{...typeof i.name=="string"?{name:i.name}:{},...typeof(r?.version??i.version)=="string"?{version:r?.version??i.version}:{},...typeof i.description=="string"?{description:i.description}:{}},readable:!0,valid:!0,hasFrontmatter:!0}}catch{return {frontmatter:{},readable:true,valid:false,hasFrontmatter:true}}}function up(e){return [path.join(e,Cr),path.join(e,"skill",Cr)]}function rt(e,n){if(!jr(e))return null;for(let t of up(e)){if(!fs$1.existsSync(t))continue;let r=lp(t).frontmatter;return {name:r.name??n,...r.version===void 0?{}:{version:r.version},...r.description===void 0?{}:{description:r.description},skillMdPath:t,dir:e}}return null}function _i(e){try{return fs$1.readdirSync(e,{withFileTypes:!0}).filter(dp)}catch{return []}}function fp(e){return e.length===0||/[\\\u0000]/.test(e)?false:e.split("/").every(n=>n.length>0&&n!=="."&&n!=="..")}function kr(e,n,t){!e||n.has(e.name)||(n.add(e.name),t.push(e));}function st(e){let n=[],t=new Set;for(let i of e)if(jr(i))for(let r of _i(i)){if(r.name.startsWith("@")){let o=path.join(i,r.name);for(let a of _i(o))kr(rt(path.join(o,a.name),a.name),t,n);continue}kr(rt(path.join(i,r.name),r.name),t,n);}return n.sort((i,r)=>i.name.localeCompare(r.name))}function yp(e,n){if(!fp(e))throw new Error(`Skill not found: ${e}`);for(let i of n){let r=rt(path.join(i,e),e);if(r)return r;for(let o of _i(i)){if(!o.name.startsWith("@"))continue;let a=rt(path.join(i,o.name,e),e);if(a)return a}}let t=st(n).find(i=>i.name===e);if(t)return t;throw new Error(`Skill not found: ${e}`)}async function bf(e){if(!e||e.root===null)return {skills:[],diagnostics:[]};let{discoverWorkspaceApps:n}=await Promise.resolve().then(()=>(Ur(),Rr)),t=await n(e.root,{productBundle:e}),i=[],r=new Set;for(let o of t.apps){let a=o.provenance?.kind==="bundled"?o.provenance.packageDir:void 0;if(!a)continue;let s=path.join(e.root,...a.split("/"));for(let c of st([path.dirname(s)]))path.resolve(c.dir)!==path.resolve(s)||r.has(c.name)||(r.add(c.name),i.push(c));for(let c of [path.join(s,"skill"),path.join(s,"skills")])for(let d of st([c]))r.has(d.name)||(r.add(d.name),i.push(d));}return {skills:i.sort((o,a)=>o.name.localeCompare(a.name)),diagnostics:t.diagnostics.filter(o=>o.source==="bundled")}}var Pf=st,Sf=yp;
2
- exports.discover=st;exports.discoverBundledProductSkills=bf;exports.discoverSkills=Pf;exports.findEntrypoint=Nf;exports.readSkillFrontmatter=lp;exports.resolve=yp;exports.resolveSkill=Sf;
1
+ 'use strict';var crypto=require('crypto'),net=require('net'),fs$1=require('fs'),promises=require('fs/promises'),path=require('path'),jsYaml=require('js-yaml');var Jr=Object.defineProperty;var C=(e,n)=>()=>(e&&(n=e(e=0)),n);var $r=(e,n)=>{for(var t in n)Jr(e,t,{get:n[t],enumerable:true});};var g=C(()=>{});var L,Pn=C(()=>{g();L=class extends Error{constructor(t,i=t,r){super(i);this.code=t;this.currentRevision=r;}code;currentRevision;name="UiRuntimeError"};});function pt(e){return Wr.test(e)||Xr.test(e)}function de(){throw new L("INPUT_INVALID","JSON value is not projection-safe")}function Zr(e){let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function ct(e,n,t,i,r,o){if(n>i&&de(),e===null||typeof e=="string"||typeof e=="boolean")return typeof e=="string"&&(Kr.test(e)||qr.test(e)&&!ns(r,o)||Yr.test(e))&&de(),e;if(typeof e=="number")return Number.isFinite(e)||de(),e;(typeof e!="object"||e===void 0||typeof e=="function"||typeof e=="bigint")&&de();let a=e;t.has(a)&&de(),t.add(a);try{if(Array.isArray(e))return e.map(c=>ct(c,n+1,t,i,r,o));Zr(a)||de();let s={};for(let[c,d]of Object.entries(e))pt(c)&&de(),s[c]=ct(d,n+1,t,i,[...r,c],o);return s}finally{t.delete(a);}}function pe(e,n=0,t=[]){(!Number.isInteger(n)||n<0||n>es)&&de(),(!Array.isArray(t)||t.some(r=>typeof r!="string"))&&de();let i=ct(e,0,new Set,Qr+n,[],t);return (i===null||Array.isArray(i)||typeof i!="object")&&de(),i}function He(e,n){if(!e||!n)return false;let t=e.split("."),i=n.split(".");return t.length>=i.length&&i.every((r,o)=>t[o]===r)}function ns(e,n){if(e.length===0)return false;let t=e.join(".");return n.some(i=>He(t,i))}function ze(e){try{let n=JSON.stringify(e);return n===void 0&&de(),n}catch{de();}}function dt(e){return Array.isArray(e)?e.map(dt):e!==null&&typeof e=="object"?Object.fromEntries(Object.keys(e).sort().map(n=>[n,dt(e[n])])):e}function Z(e){return ze(dt(e))}function lt(e){return Buffer.byteLength(e,"utf8")}var Wr,Xr,Kr,Yr,qr,Qr,es,be=C(()=>{g();Pn();Wr=/(?:proof|token|secret|password|cookie|authorization|private[_-]?key|stack|exception|plugin[_-]?text)/i,Xr=/(?:url|uri|endpoint|path|file(?:name|path)?|cwd|shell|directory|dir|folder)$/i,Kr=/<\/?[A-Za-z][^>]*>/,Yr=/^(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)/,qr=/^(?:https?|file|ftp|ws|wss):\/\//i;Qr=8,es=4;});var Sn,ut=C(()=>{g();Sn=["text/plain","application/json"];});var Ti=C(()=>{g();ut();});function Ge(e){return is.has(e)||os.test(e)||rs.test(e)}var Ni,is,os,rs,Mn,tn,he,ft,yt,At,It,gt,Ce=C(()=>{g();Ni=["__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"],is=new Set(Ni),os=/(?:proof|token|secret|password|cookie|authorization|private[_-]?key|stack|exception|plugin[_-]?text)/i,rs=/(?:url|uri|endpoint|path|file(?:name|path)?|cwd|shell|directory|dir|folder)$/i;Mn=/^[A-Za-z0-9_]+$/,tn=/^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)*$/,he=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,ft=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/,yt=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,At=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/,It=["blue","violet","emerald","amber","rose","sky","slate","indigo"],gt=["inline","panel"];});function mt(e){return typeof e=="string"&&Sn.includes(e)}var Di=C(()=>{g();ut();Ce();});function On(e){if(!ht(e))return false;let n=Object.keys(e);return !(n.some(t=>t!=="in"&&t!=="out")||n.length===0||Object.hasOwn(e,"in")&&!ss(e.in)||Object.hasOwn(e,"out")&&!as(e.out))}function ss(e){return ht(e)?Object.keys(e).every(t=>t==="mediaType"||t==="required")&&Object.hasOwn(e,"mediaType")&&mt(e.mediaType)&&(!Object.hasOwn(e,"required")||typeof e.required=="boolean"):false}function as(e){return ht(e)?Object.keys(e).every(t=>t==="mediaType"||t==="range")&&Object.hasOwn(e,"mediaType")&&mt(e.mediaType)&&(!Object.hasOwn(e,"range")||typeof e.range=="boolean"):false}function ht(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}var _t=C(()=>{g();Ti();Di();new TextDecoder("utf-8",{fatal:true,ignoreBOM:true});});function Rn(e){return cs.includes(e)}function Un(e){return Number.isSafeInteger(e)&&e>=Ln.min&&e<=Ln.max}var cs,Ln,bi,Et=C(()=>{g();cs=[5,15,30,60],Ln=Object.freeze({min:15e3,max:6e5,default:3e5}),bi=1;});function wn(e){return Number.isSafeInteger(e)&&e>=Cn.min&&e<=Cn.max}function kn(e){return ds.includes(e)}var Cn,Pi,ds,Tt=C(()=>{g();Cn=Object.freeze({min:6e4,max:18e5,default:6e5}),Pi=1,ds=["start","status","cancel"];});function re(e){let t=e.renderer!==void 0||e.surfaces!==void 0||e.stateProjection!==void 0||e.dataPaths!==void 0||e.usage!==void 0||e.detailPanel!==void 0||e.displayModes!==void 0||e.summaryProjection!==void 0||e.downloads!==void 0||e.legacy!==void 0||Object.values(e.actions).some(r=>r.resultProjection!==void 0)?{id:e.id,version:e.version,...e.renderer===void 0?{}:{renderer:e.renderer},...e.surfaces===void 0?{}:{surfaces:e.surfaces},...e.stateProjection===void 0?{}:{stateProjection:e.stateProjection},...e.dataPaths===void 0?{}:{dataPaths:e.dataPaths},...e.summaryProjection===void 0?{}:{summaryProjection:e.summaryProjection},...e.legacy===void 0?{}:{legacy:e.legacy},...e.usage===void 0?{}:{usage:e.usage},...e.detailPanel===void 0?{}:{detailPanel:e.detailPanel},...e.displayModes===void 0?{}:{displayModes:e.displayModes},...e.downloads===void 0?{}:{downloads:e.downloads},...e.sourceHash===void 0?{}:{sourceHash:e.sourceHash},actions:e.actions}:e.sourceHash===void 0?{id:e.id,version:e.version,actions:e.actions}:{id:e.id,version:e.version,sourceHash:e.sourceHash,actions:e.actions},i=pe(t);return crypto.createHash("sha256").update(Z(i)).digest("hex")}function Dt(e){return `${e.id}\0${e.version}`}function le(e){if(!/^\d+$/.test(String(e.version))||e.version<1||e.id.length<1||e.id.length>128)throw new L("DEFINITION_UNSUPPORTED","UI definition is invalid");if(e.sourceHash!==void 0&&(typeof e.sourceHash!="string"||!ls.test(e.sourceHash)))throw new L("DEFINITION_UNSUPPORTED","UI definition source hash is invalid");if(!/^[0-9a-f]{64}$/.test(e.hash)||re(e)!==e.hash)throw new L("DEFINITION_UNSUPPORTED","UI definition hash is invalid");for(let[n,t]of Object.entries(e.actions)){if(!n||!Array.isArray(t.capabilities)||t.capabilities.some(i=>!fs(i)))throw new L("DEFINITION_UNSUPPORTED","UI action declaration is invalid");if(t.confirmation!==void 0&&t.confirmation!=="none"&&t.confirmation!=="native")throw new L("DEFINITION_UNSUPPORTED","UI action confirmation is invalid");if(t.inputKeys&&(!Array.isArray(t.inputKeys)||t.inputKeys.some(i=>typeof i!="string"||!i)))throw new L("DEFINITION_UNSUPPORTED","UI action input declaration is invalid");if(t.dataInputs!==void 0&&(!Array.isArray(t.dataInputs)||new Set(t.dataInputs).size!==t.dataInputs.length||t.dataInputs.some(i=>typeof i!="string"||!i||t.inputKeys!==void 0&&!t.inputKeys.includes(i))))throw new L("DEFINITION_UNSUPPORTED","UI action data input declaration is invalid");if(t.resultProjection&&Nt(t.resultProjection),t.schedule!==void 0&&(!Rn(t.schedule.everyMinutes)||!Un(t.schedule.timeoutMs)))throw new L("DEFINITION_UNSUPPORTED","UI action schedule declaration is invalid");if(t.job!==void 0&&(typeof t.job!="object"||Object.keys(t.job).some(i=>i!=="deadlineMs")||!wn(t.job.deadlineMs)))throw new L("DEFINITION_UNSUPPORTED","UI action job declaration is invalid");if(t.jobAccess!==void 0&&(!Array.isArray(t.jobAccess)||t.jobAccess.length===0||new Set(t.jobAccess).size!==t.jobAccess.length||!t.jobAccess.every(kn)||t.job!==void 0))throw new L("DEFINITION_UNSUPPORTED","UI action job control declaration is invalid");if(t.content!==void 0&&!On(t.content))throw new L("DEFINITION_UNSUPPORTED","UI action content declaration is invalid");if(t.env!==void 0&&(!Array.isArray(t.env)||t.env.length===0||new Set(t.env).size!==t.env.length||t.env.some(i=>i!=="CREWX_APP_INSTANCE_ID"&&i!=="CREWX_THREAD_ID")))throw new L("DEFINITION_UNSUPPORTED","UI action environment declaration is invalid")}if(e.renderer!==void 0&&(!e.renderer||e.renderer.length>128))throw new L("DEFINITION_UNSUPPORTED","UI definition renderer is invalid");if(e.surfaces&&(!Array.isArray(e.surfaces)||e.surfaces.some(n=>!n||n.length>64)))throw new L("DEFINITION_UNSUPPORTED","UI definition surfaces are invalid");if(e.usage!==void 0&&e.usage!=="card"&&e.usage!=="window")throw new L("DEFINITION_UNSUPPORTED","UI definition usage is invalid");if(e.detailPanel!==void 0&&typeof e.detailPanel!="boolean")throw new L("DEFINITION_UNSUPPORTED","UI definition detailPanel is invalid");if(e.displayModes&&(!Array.isArray(e.displayModes)||e.displayModes.length===0||new Set(e.displayModes).size!==e.displayModes.length||e.displayModes.some(n=>n!=="inline"&&n!=="floating"&&n!=="focused")))throw new L("DEFINITION_UNSUPPORTED","UI definition displayModes are invalid");if(e.usage==="card"&&e.displayModes!==void 0)throw new L("DEFINITION_UNSUPPORTED","Card definitions cannot declare displayModes");if(e.usage==="window"&&e.detailPanel!==void 0)throw new L("DEFINITION_UNSUPPORTED","Window definitions cannot declare detailPanel");if(e.stateProjection&&Nt(e.stateProjection),e.summaryProjection){Nt(e.summaryProjection);let n=new Set(e.stateProjection?.allow??[]);if(e.summaryProjection.allow.some(t=>!n.has(t)))throw new L("DEFINITION_UNSUPPORTED","UI summary projection exceeds state projection")}if(e.legacy!==void 0){if(!e.legacy||typeof e.legacy!="object"||Array.isArray(e.legacy)||Object.keys(e.legacy).some(r=>!["readTool","actionTool","hostTools","agentAccess"].includes(r)))throw new L("DEFINITION_UNSUPPORTED","UI legacy metadata is invalid");let n=new Set;for(let[r,o]of [["readTool",e.legacy.readTool],["actionTool",e.legacy.actionTool]])if(o!==void 0){if(us(o,r==="readTool"),n.has(o.name))throw new L("DEFINITION_UNSUPPORTED","UI legacy tool names collide");n.add(o.name);}let t=e.legacy.hostTools;if(t!==void 0){if(!t||typeof t!="object"||Array.isArray(t))throw new L("DEFINITION_UNSUPPORTED","UI legacy host tools are invalid");let r={"doc.open":"crewx_app_html_viewer_open","pty.connect":"crewx_app_terminal_connect"};for(let[o,a]of Object.entries(t)){if(!Object.hasOwn(r,o)||r[o]!==a||typeof a!="string"||!/^[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(a)||n.has(a))throw new L("DEFINITION_UNSUPPORTED","UI legacy host tools are invalid");n.add(a);}}let i=e.legacy.agentAccess;if(i!==void 0&&(!i||typeof i!="object"||Array.isArray(i)||Object.entries(i).some(([r,o])=>!r||!Object.hasOwn(e.actions,r)||o!=="allowed"&&o!=="denied")))throw new L("DEFINITION_UNSUPPORTED","UI legacy agent access is invalid");if(e.legacy.actionTool!==void 0&&(!i||Object.keys(i).length===0))throw new L("DEFINITION_UNSUPPORTED","UI legacy action tool requires its complete agent access map")}if(e.downloads!==void 0&&e.downloads!==true)throw new L("DEFINITION_UNSUPPORTED","UI definition downloads is invalid");if(e.dataPaths!==void 0){let n=new Set(["__proto__","prototype","constructor"]);if(!Array.isArray(e.dataPaths)||e.dataPaths.length>16||new Set(e.dataPaths).size!==e.dataPaths.length||e.dataPaths.some(t=>typeof t!="string"||!/^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)*$/.test(t)||t.split(".").some(i=>n.has(i))||!(e.stateProjection?.allow??[]).some(i=>He(t,i))))throw new L("DEFINITION_UNSUPPORTED","UI definition dataPaths are invalid")}}function us(e,n){if(!e||typeof e!="object"||Array.isArray(e))throw new L("DEFINITION_UNSUPPORTED","UI legacy tool metadata is invalid");let t=e,i=["name","description","inputSchema","textFallback","visibility"],r=Object.hasOwn(t,"fixedResult");if(Object.keys(t).some(o=>!i.includes(o)&&!(n&&o==="fixedResult"))||i.some(o=>!Object.hasOwn(t,o))||typeof t.name!="string"||!/^[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(t.name)||typeof t.description!="string"||t.description.trim().length===0||t.description.length>8192||typeof t.textFallback!="string"||t.textFallback.trim().length===0||t.textFallback.length>16384||!t.inputSchema||typeof t.inputSchema!="object"||Array.isArray(t.inputSchema)||!Array.isArray(t.visibility)||t.visibility.length===0||t.visibility.some(o=>o!=="model"&&o!=="app")||new Set(t.visibility).size!==t.visibility.length)throw new L("DEFINITION_UNSUPPORTED","UI legacy tool metadata is invalid");try{let o=pe(t.inputSchema);if(o.type!==void 0&&o.type!=="object")throw new Error("schema type");if(r){if(!n)throw new Error("fixed result location");let a=t.fixedResult;if(!a||typeof a!="object"||Array.isArray(a))throw new Error("fixed result");let s=a;if(Object.keys(s).sort().join(",")!=="argsPolicy,structuredContent"||s.argsPolicy!=="empty-only"&&s.argsPolicy!=="ignore"||!s.structuredContent||typeof s.structuredContent!="object"||Array.isArray(s.structuredContent))throw new Error("fixed result");let c=pe(s.structuredContent);if(lt(ze(c))>4*1024)throw new Error("fixed result size")}}catch{throw new L("DEFINITION_UNSUPPORTED","UI legacy tool metadata is not projection-safe")}}function Nt(e){if(!Array.isArray(e.allow)||e.allow.some(n=>!/^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)*$/.test(n)))throw new L("DEFINITION_UNSUPPORTED","UI projection policy is invalid")}function fs(e){return e.length>0&&e.length<=128&&e!=="*"&&e!=="all"&&!/[/*]/.test(e)}var ls,we=C(()=>{g();be();Pn();_t();Et();Tt();ls=/^[0-9a-f]{64}$/;});var Si=C(()=>{g();be();});var Y,Pe,bt=C(()=>{g();Y="dist/tools.json",Pe="dist/main.mjs";});var on,Mi=C(()=>{g();on="window";});function Oi(e){if(!Array.isArray(e)||e.length===0)return false;let n=new Set;for(let t of e){if(!ys.some(i=>i===t)||n.has(t))return false;n.add(t);}return true}var ys,Li=C(()=>{g();ys=["CREWX_APP_INSTANCE_ID","CREWX_THREAD_ID"];});function z(e){throw new Pt(e)}function Ps(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 Ss(e,n){let t=Object.getOwnPropertyDescriptor(e,n);return (!t||!("value"in t))&&z("CSP_ORIGIN_INVALID"),t.value}function xn(e,n){if(!Object.prototype.hasOwnProperty.call(e,n))return [];let t=Ss(e,n);Array.isArray(t)||z("CSP_ORIGIN_INVALID"),Reflect.ownKeys(t).some(o=>typeof o!="string"||o!=="length"&&!/^(?:0|[1-9][0-9]*)$/.test(o))&&z("CSP_ORIGIN_INVALID");let r=[];for(let o=0;o<t.length;o+=1)(!Object.prototype.hasOwnProperty.call(t,o)||typeof t[o]!="string")&&z("CSP_ORIGIN_INVALID"),r.push(t[o]);return Object.keys(t).length!==t.length&&z("CSP_ORIGIN_INVALID"),r}function Ms(e){let n;try{n=JSON.stringify(e);}catch{z("CSP_ORIGIN_INVALID");}return n===void 0&&z("CSP_ORIGIN_INVALID"),new TextEncoder().encode(n).byteLength}function Ci(e,n){/\s|\\/u.test(e)&&z("CSP_ORIGIN_INVALID");let t=Es.exec(e);t||z("CSP_ORIGIN_INVALID");let i=t[1].toLowerCase(),r=t[2];(r.includes("@")||r.includes("%")||r.includes("*"))&&z("CSP_ORIGIN_INVALID"),(r.startsWith("[")?Ts:Ns).test(r)||z("CSP_ORIGIN_INVALID"),i==="wss"&&n!=="connectDomains"&&z("CSP_ORIGIN_INVALID");let a;try{a=new URL(e);}catch{z("CSP_ORIGIN_INVALID");}(a.protocol!==`${i}:`||a.username!==""||a.password!==""||a.search!==""||a.hash!=="")&&z("CSP_ORIGIN_INVALID");let s=a.hostname.toLowerCase();if((!s||s.includes("%"))&&z("CSP_ORIGIN_INVALID"),!s.startsWith("[")){let d=s.endsWith(".")?s.slice(0,-1):s;(d.length===0||d.length>253)&&z("CSP_ORIGIN_INVALID"),d.split(".").some(u=>u.length>63||!Ds.test(u))&&z("CSP_ORIGIN_INVALID");}let c=a.origin;return (c==="null"||!c.startsWith(`${i}://`))&&z("CSP_ORIGIN_INVALID"),{origin:c,hostname:s}}function Os(e){let n=e.split(".").map(Number);return ((n[0]*256+n[1])*256+n[2])*256+n[3]}function wi(e,n,t){let i=4294967295<<32-t>>>0;return (e&i)===(n&i)}function ji(e){let n=Os(e);return wi(n,3221225472,24)?n!==3221225481&&n!==3221225482:bs.some(([t,i])=>wi(n,t,i))}function Ls(e){let n=e.indexOf("::"),t=(n<0?e:e.slice(0,n)).split(":").filter(Boolean),i=n<0?[]:e.slice(n+2).split(":").filter(Boolean);return (n<0?t:[...t,...Array(8-t.length-i.length).fill("0"),...i]).reduce((o,a)=>o<<16n|BigInt(Number.parseInt(a,16)),0n)}function Rs(e){let n=Ls(e),t=Number(n>>112n),i=Number(n>>96n&0xffffn);if(n>>32n===0xffffn){let r=Number(n&0xffffffffn);return ji([r>>>24&255,r>>>16&255,r>>>8&255,r&255].join("."))}return t<8192||t>16383||t===8193&&i<=511||t===8193&&i===3512||t===8194||t===16383&&i<=4095}function Us(e,n){let t=e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e,i=net.isIP(t);if(i===4)return ji(t);if(i===6)return Rs(t);let r=e.toLowerCase().replace(/\.$/,"");return !r||!r.includes(".")||n.has(r)?true:_s.some(o=>r===o||r.endsWith(`.${o}`))}function ki(e){return Object.freeze([...new Set(e.map(n=>n.origin))].sort())}function xi(e){return JSON.stringify({baseUriDomains:[],connectDomains:e.connectDomains,declared:e.declared,frameDomains:e.frameDomains,resourceDomains:[]})}function vi(e,n={}){if(e===void 0){let A=xi({declared:false,connectDomains:[],frameDomains:[]});return Object.freeze({declared:false,connectDomains:Object.freeze([]),frameDomains:Object.freeze([]),resourceDomains:Object.freeze([]),baseUriDomains:Object.freeze([]),cspHash:crypto.createHash("sha256").update(A,"utf8").digest("hex")})}Ps(e)||z("CSP_ORIGIN_INVALID");let t=Reflect.ownKeys(e);t.some(A=>typeof A!="string")&&z("CSP_ORIGIN_INVALID"),t.some(A=>!hs.has(A))&&z("CSP_AXIS_UNKNOWN");let i=xn(e,"connectDomains"),r=xn(e,"frameDomains"),o=xn(e,"resourceDomains"),a=xn(e,"baseUriDomains");(o.length>0||a.length>0)&&z("CSP_AXIS_UNSUPPORTED"),(Ms(e)>Is||i.length>Ui||r.length>Ui||i.length+r.length>gs||[...i,...r].some(A=>new TextEncoder().encode(A).byteLength>ms))&&z("CSP_LIMIT_EXCEEDED");let c=i.map(A=>Ci(A,"connectDomains")),d=r.map(A=>Ci(A,"frameDomains")),l=new Set((n.runtimeHostnames??[]).map(A=>A.toLowerCase().replace(/\.$/,"")));[...c,...d].some(A=>Us(A.hostname,l))&&z("CSP_ORIGIN_FORBIDDEN");let u={declared:true,connectDomains:ki(c),frameDomains:ki(d)},f=xi(u);return Object.freeze({...u,resourceDomains:Object.freeze([]),baseUriDomains:Object.freeze([]),cspHash:crypto.createHash("sha256").update(f,"utf8").digest("hex")})}var Is,Ui,gs,ms,hs,_s,Es,Ts,Ns,Ds,bs,Pt,Vi=C(()=>{g();Is=4096,Ui=16,gs=32,ms=512,hs=new Set(["connectDomains","frameDomains","resourceDomains","baseUriDomains"]),_s=["localhost","local","internal","home.arpa","test","example","invalid","onion","lan","corp","home","intranet","private","localdomain"],Es=/^(https|wss):\/\/([^/?#]+)$/i,Ts=/^\[[^\]]+\](?::[0-9]+)?$/,Ns=/^[^:\[\]]+(?::[0-9]+)?$/,Ds=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/,bs=[[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]],Pt=class extends Error{constructor(t){super(t);this.code=t;}code;name="UiPluginCspNormalizationError"};});function sn(e,n){return n===void 0||n===""?e:e===""?n:n.startsWith("[")?`${e}${n}`:`${e}.${n}`}function p(e,n=e,t,i){throw new se(e,n,t,i)}function V(e,n){try{return n()}catch(t){throw t instanceof se?t.withPathPrefix(e):t}}function H(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;try{let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}catch{return false}}function P(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function ua(e,n){let t={};for(let[i,r]of Object.entries(e))n.includes(i)||(t[i]=r);return t}function J(e,n,t=[]){let i=new Set([...n,...t]),r=Object.keys(e).find(a=>!i.has(a));r!==void 0&&p("MANIFEST_INVALID","MANIFEST_INVALID",r,"unknown-key");let o=n.find(a=>!P(e,a));o!==void 0&&p("MANIFEST_INVALID","MANIFEST_INVALID",o,"missing-key");}function Fn(e,n=false,t=false,i=false){return xs.test(e)||!i&&vs.test(e)||js.test(e)||t&&Fi.test(e)||Vs.test(e)&&!(n&&/^\s*data:/i.test(e)&&!Fi.test(e))}function Vn(e,n=new Set,t=0,i=false,r=false,o=""){if(typeof e=="string"){Fn(e,i,r)&&p("UNSAFE_VALUE","UNSAFE_VALUE",o,"unsafe-value");return}if(!(e===null||typeof e!="object")){(t>8||n.has(e))&&p("MANIFEST_INVALID","MANIFEST_INVALID",o),n.add(e);try{if(Array.isArray(e)){e.forEach((a,s)=>Vn(a,n,t+1,!1,!1,sn(o,`[${s}]`)));return}H(e)||p("MANIFEST_INVALID","MANIFEST_INVALID",o);for(let[a,s]of Object.entries(e))Vn(s,n,t+1,i&&t===0&&(a==="name"||a==="description"),r,sn(o,a));}finally{n.delete(e);}}}function _e(e,n){let t=e[n];return typeof t!="string"&&p("MANIFEST_INVALID"),t}function ye(e,n,t){let i=e[n];return (!Number.isSafeInteger(i)||i<t)&&p("MANIFEST_INVALID"),i}function St(e){return ks.test(e)||p("MANIFEST_INVALID"),e}function Je(e){return ws.test(e)||p("TOKEN_INVALID"),e}function fa(e){return eo.test(e)||p("MANIFEST_INVALID"),e}function ya(e){H(e)||p("MANIFEST_INVALID");let n={};for(let[t,i]of Object.entries(e)){let r=fa(t);H(i)||p("MANIFEST_INVALID");let o=i.type;if(o==="text"){J(i,["type","maxLength"]),n[r]={type:o,maxLength:ye(i,"maxLength",1)};continue}if(o==="text-list"){J(i,["type","max","itemMaxLength"]),n[r]={type:o,max:ye(i,"max",0),itemMaxLength:ye(i,"itemMaxLength",1)};continue}if(o==="step-list"){J(i,["type","min","max","labelMaxLength","detailMaxLength"]);let a=ye(i,"min",0),s=ye(i,"max",1);a>s&&p("MANIFEST_INVALID"),n[r]={type:o,min:a,max:s,labelMaxLength:ye(i,"labelMaxLength",1),detailMaxLength:ye(i,"detailMaxLength",1)};continue}typeof o=="string"&&p("SCHEMA_TYPE_UNSUPPORTED"),p("MANIFEST_INVALID");}return n}function Aa(e,n,t){let i=e[n];(!i||i.type!==t)&&p("MANIFEST_INVALID");}function jn(e,n,t){let i=_e(e,"field");return eo.test(i)||p("MANIFEST_INVALID"),Aa(n,i,t),i}function Ia(e,n){H(e)||p("MANIFEST_INVALID");let t=e.primitive;switch(typeof t!="string"&&p("MANIFEST_INVALID"),la.includes(t)||p("PRIMITIVE_UNKNOWN"),t){case "card-shell":return J(e,["primitive"]),{primitive:t};case "meta-banner":return J(e,["primitive","badgeToken","noticeToken"]),{primitive:t,badgeToken:Je(_e(e,"badgeToken")),noticeToken:Je(_e(e,"noticeToken"))};case "heading":return J(e,["primitive","field"]),{primitive:t,field:jn(e,n,"text")};case "labeled-text":return J(e,["primitive","titleToken","field","variant"]),e.variant!=="callout"&&p("MANIFEST_INVALID"),{primitive:t,titleToken:Je(_e(e,"titleToken")),field:jn(e,n,"text"),variant:"callout"};case "step-flow":return J(e,["primitive","titleToken","field"]),{primitive:t,titleToken:Je(_e(e,"titleToken")),field:jn(e,n,"step-list")};case "text-list":{J(e,["primitive","titleToken","field"],["emptyToken","hideWhenEmpty"]);let i={primitive:t,titleToken:Je(_e(e,"titleToken")),field:jn(e,n,"text-list")};return P(e,"emptyToken")&&(i.emptyToken=Je(_e(e,"emptyToken"))),P(e,"hideWhenEmpty")&&(typeof e.hideWhenEmpty!="boolean"&&p("MANIFEST_INVALID"),i.hideWhenEmpty=e.hideWhenEmpty),i}}return p("MANIFEST_INVALID")}function ga(e,n){return Array.isArray(e)||p("MANIFEST_INVALID"),e.map(t=>Ia(t,n))}function W(e="v2 manifest exceeds a contract limit",n,t){return p("LIMIT_EXCEEDED",e,n,t)}function ue(e="initial state is not projection-safe"){return p("INITIAL_STATE_INVALID",e)}function Bi(e,n){return (typeof e!="string"||e.length===0||e.length>4096||e.trim().length===0||ra.test(e)||sa.test(e))&&p("MANIFEST_INVALID",`${n} is invalid`),(Fn(e,true,true)||Fs.test(e)||Bs.test(e)||Hs.test(e))&&p("UNSAFE_VALUE",`${n} contains an unsafe value`),e}function Mt(e,n){return (typeof e!="string"||!he.test(e))&&p("MANIFEST_INVALID",`${n} is invalid`),e}function ma(e){return (typeof e!="string"||!ft.test(e)||e==="*"||e==="all")&&p("MANIFEST_INVALID","action capability is invalid"),e}function no(e){return (typeof e!="string"||!oa.test(e))&&p("MANIFEST_INVALID","resource hash is invalid"),e}function Ot(e,n=new Set,t=0,i=""){if(typeof e=="string"){e.length>4096&&W("v2 manifest string is too long",i,"string-too-long");return}if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){Number.isFinite(e)||p("MANIFEST_INVALID","v2 manifest contains a non-finite number",i,"non-finite-number");return}(e===void 0||typeof e=="function"||typeof e=="bigint")&&p("MANIFEST_INVALID","v2 manifest contains a non-JSON value",i,"non-json-value"),typeof e!="object"&&p("MANIFEST_INVALID","MANIFEST_INVALID",i),t>8&&W("v2 manifest nesting is too deep",i,"too-deep"),n.has(e)&&p("MANIFEST_INVALID","v2 manifest contains a cycle",i,"cycle"),n.add(e);try{if(Array.isArray(e)){e.length>128&&W("v2 manifest array is too long",i,"array-too-long"),e.forEach((r,o)=>Ot(r,n,t+1,sn(i,`[${o}]`)));return}H(e)||p("MANIFEST_INVALID","v2 manifest contains a non-plain object",i,"non-plain-object");for(let[r,o]of Object.entries(e))Ot(o,n,t+1,sn(i,r));}finally{n.delete(e);}}}function to(e){return (typeof e!="string"||e.length>4096||!tn.test(e))&&(typeof e=="string"&&e.length>4096&&W("projection path is too long"),p("MANIFEST_INVALID","projection paths must be canonical exact paths")),e.split(".").some(t=>Ge(t))&&p("MANIFEST_INVALID","projection paths cannot address reserved state keys"),e}function Lt(e){H(e)||p("MANIFEST_INVALID","projection policy must be an object"),J(e,["allow"]),Array.isArray(e.allow)||p("MANIFEST_INVALID","projection allow must be an array"),e.allow.length>128&&W("projection allowlist is too long");let n=[],t=new Set;for(let i of e.allow){let r=to(i);t.has(r)&&p("MANIFEST_INVALID","projection allowlist contains a duplicate path"),t.add(r),n.push(r);}return {allow:n}}function ha(e,n){if(e===void 0)return;Array.isArray(e)||p("MANIFEST_INVALID","dataPaths must be an array"),e.length>aa&&W("dataPaths exceed the v2 limit");let t=[],i=new Set;for(let r of e){let o=to(r);i.has(o)&&p("MANIFEST_INVALID","dataPaths contain a duplicate path"),n.some(a=>He(o,a))||p("MANIFEST_INVALID","dataPaths must be projection-allowed"),i.add(o),t.push(o);}return t}function _a(e){Array.isArray(e)||p("MANIFEST_INVALID","deviceFeatures must be an array",void 0,"array"),e.length>ca&&p("MANIFEST_INVALID","deviceFeatures allow at most 16 names",void 0,"too-many-items");let n=[],t=new Set;for(let[i,r]of e.entries()){let o=`[${i}]`;typeof r!="string"&&p("MANIFEST_INVALID","a device feature name must be a string",o,"string"),r.length===0&&p("MANIFEST_INVALID","a device feature name must not be empty",o,"empty"),r.length>da&&p("MANIFEST_INVALID","a device feature name is at most 32 characters",o,"too-long"),pa.test(r)||p("MANIFEST_INVALID","a device feature name starts with a lowercase letter and holds only letters and digits",o,"format"),t.has(r)&&p("MANIFEST_INVALID","deviceFeatures contain a duplicate name",o,"duplicate-item"),t.add(r),n.push(r);}return n}function Ea(e){if(e!==false)return e!==true&&p("MANIFEST_INVALID","downloads must be true or false",void 0,"boolean"),true}function Ta(e){return (!H(e)||e.view!==true||Object.keys(e).some(n=>n!=="view"&&n!=="entry"))&&p("MANIFEST_INVALID",'share must be { "view": true } or { "view": true, "entry": "<path>" }',void 0,"share-shape"),P(e,"entry")?{view:true,entry:Da(e.entry)}:{view:true}}function Da(e){typeof e!="string"&&p("MANIFEST_INVALID","share.entry must be a string","entry","entry-shape");let n=(i,r)=>p("MANIFEST_INVALID",`share.entry ${r}`,"entry",i);e.length===0&&n("empty","must not be empty"),e.length>Hi&&n("too-long",`must be at most ${Hi} characters`),e.startsWith("/")&&n("absolute","must be relative to the App folder");let t=e.split("/");t.length>zi&&n("too-many-segments",`must have at most ${zi} 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'),Na.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 ba(e){return (!H(e)||Object.keys(e).length!==1||typeof e.root!="string")&&p("MANIFEST_INVALID",'files must be exactly { "root": "<workspace folder>" }',void 0,"files-shape"),{root:La(e.root)}}function La(e){let n=e.normalize("NFC"),t=(o,a)=>p("MANIFEST_INVALID",`files.root ${a}`,"root",o);n.length===0&&t("empty","must not be empty"),Oa.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>Gi&&t("too-long",`must be at most ${Gi} characters`);let i=n.split("/"),r=i[0].toLowerCase().replace(/[. ]+$/,"");Ma.includes(r)&&t("reserved-folder","must not start in an App code folder or a tool folder"),i.length<Pa&&t("too-shallow","must name a folder inside a top-level folder, such as docs/trips"),i.length>Ji&&t("too-many-segments",`must have at most ${Ji} segments`);for(let o of i)o.length===0&&t("empty-segment","must not contain an empty segment"),(o==="."||o==="..")&&t("dot-segment",'must not contain "." or ".." segments'),Array.from(o).length>$i&&t("segment-too-long",`segments must be at most ${$i} characters`),Sa.test(o)||t("segment-shape",'segments must start with a letter or digit and contain only letters, digits, combining marks, "_" or "-"');return n}function $e(e,n,t=Number.MAX_SAFE_INTEGER){return (!Number.isSafeInteger(e)||e<0||e>t)&&p("MANIFEST_INVALID",`${n} is invalid`),e}function Wi(e,n){return (typeof e!="number"||!Number.isFinite(e))&&p("MANIFEST_INVALID",`${n} is invalid`),e}function Rt(e,n=0,t=new Set){if(typeof e=="string")return (e.length>4096||Fn(e))&&p("UNSAFE_VALUE","schema enum contains an unsafe string"),e;if(e===null||typeof e=="boolean")return e;if(typeof e=="number")return Number.isFinite(e)||p("MANIFEST_INVALID","schema enum contains a non-finite number"),e;(n>8||typeof e!="object"||e===void 0)&&W("schema enum is too deep"),t.has(e)&&p("MANIFEST_INVALID","schema enum contains a cycle"),t.add(e);try{if(Array.isArray(e))return e.length>128&&W("schema enum array is too long"),e.map(r=>Rt(r,n+1,t));H(e)||p("MANIFEST_INVALID","schema enum contains a non-plain object");let i={};for(let[r,o]of Object.entries(e))Ge(r)&&p("MANIFEST_INVALID","schema enum contains a reserved key"),i[r]=Rt(o,n+1,t);return i}finally{t.delete(e);}}function Ra(e,n){if(e===void 0)return;Array.isArray(e)||p("MANIFEST_INVALID","schema required must be an array"),e.length>64&&W("schema required list is too long");let t=[],i=new Set;for(let r of e)(typeof r!="string"||!tn.test(r))&&p("MANIFEST_INVALID","schema required contains an invalid key"),r.length>4096&&W("schema required key is too long"),i.has(r)&&p("MANIFEST_INVALID","schema required contains a duplicate key"),n&&!Object.prototype.hasOwnProperty.call(n,r)&&p("MANIFEST_INVALID","schema required references an undeclared property"),i.add(r),t.push(r);return t}function Ua(e,n){let t=n?tn:Mn;return e.length>4096&&W("schema property name is too long"),(!t.test(e)||e.split(".").some(i=>Ge(i)))&&p("MANIFEST_INVALID","schema property name is invalid"),e}function Ut(e,n=0,t=false){H(e)||p("MANIFEST_INVALID","action inputSchema must be an object"),n>8&&W("action inputSchema is too deep");let i=e.type;i!=="object"&&i!=="string"&&i!=="number"&&i!=="integer"&&i!=="boolean"&&i!=="array"&&i!=="null"&&(typeof i=="string"&&p("SCHEMA_TYPE_UNSUPPORTED","action inputSchema type is unsupported"),p("MANIFEST_INVALID","action inputSchema type is required"));let r=["type","enum"];i==="string"&&r.push("minLength","maxLength"),i==="array"&&r.push("minItems","maxItems","items"),i==="object"&&r.push("minProperties","maxProperties","properties","required","additionalProperties"),(i==="number"||i==="integer")&&r.push("minimum","maximum"),J(e,["type"],r.filter(s=>s!=="type"));let o={type:i};if(P(e,"enum")&&(Array.isArray(e.enum)||p("MANIFEST_INVALID","schema enum must be an array"),e.enum.length>128&&W("schema enum is too long"),o.enum=e.enum.map(s=>Rt(s))),i==="string"&&(P(e,"minLength")&&(o.minLength=$e(e.minLength,"schema minLength",4096)),P(e,"maxLength")&&(o.maxLength=$e(e.maxLength,"schema maxLength",4096)),o.minLength!==void 0&&o.maxLength!==void 0&&o.minLength>o.maxLength&&p("MANIFEST_INVALID","schema string length bounds are inverted")),(i==="number"||i==="integer")&&(P(e,"minimum")&&(o.minimum=Wi(e.minimum,"schema minimum")),P(e,"maximum")&&(o.maximum=Wi(e.maximum,"schema maximum")),o.minimum!==void 0&&o.maximum!==void 0&&o.minimum>o.maximum&&p("MANIFEST_INVALID","schema numeric bounds are inverted")),i==="array"&&(P(e,"minItems")&&(o.minItems=$e(e.minItems,"schema minItems",128)),P(e,"maxItems")&&(o.maxItems=$e(e.maxItems,"schema maxItems",128)),o.minItems!==void 0&&o.maxItems!==void 0&&o.minItems>o.maxItems&&p("MANIFEST_INVALID","schema array length bounds are inverted"),P(e,"items")&&(o.items=Ut(e.items,n+1,false))),i==="object"){let s;if(P(e,"properties")){H(e.properties)||p("MANIFEST_INVALID","schema properties must be an object");let d=Object.entries(e.properties);d.length>64&&W("schema properties are too many"),s={};for(let[l,u]of d){let f=Ua(l,t);s[f]=Ut(u,n+1,false);}o.properties=s;}P(e,"minProperties")&&(o.minProperties=$e(e.minProperties,"schema minProperties",64)),P(e,"maxProperties")&&(o.maxProperties=$e(e.maxProperties,"schema maxProperties",64)),o.minProperties!==void 0&&o.maxProperties!==void 0&&o.minProperties>o.maxProperties&&p("MANIFEST_INVALID","schema object property bounds are inverted");let c=Ra(e.required,s);c!==void 0&&(o.required=c),P(e,"additionalProperties")&&(e.additionalProperties!==false&&p("MANIFEST_INVALID","schema additionalProperties must be false"),o.additionalProperties=false);}let a=JSON.stringify(o);return (a===void 0||Buffer.byteLength(a,"utf8")>2097152)&&W("action inputSchema subtree is too large"),o}function Ca(e){let n=Ut(e,0,true);return (n.type!=="object"||!n.properties)&&p("MANIFEST_INVALID","action inputSchema must declare object properties"),n}function wa(e){if(H(e)||p("MANIFEST_INVALID","action backend must be an object"),e.type==="core"){J(e,Zs);let n=e.handler;return (typeof n!="string"||!yt.test(n))&&p("MANIFEST_INVALID","core backend handler is invalid"),{type:"core",handler:n}}if(e.type==="skill"&&P(e,"entry"))return J(e,na),e.entry!==Pe&&p("MANIFEST_INVALID",`skill backend entry must be ${Pe}`),{type:"skill",entry:Pe};if(e.type==="skill"){J(e,Qs,ea),(!Array.isArray(e.command)||e.command.length===0||e.command.length>16)&&p("MANIFEST_INVALID","skill backend command is invalid");let n=[];for(let i of e.command)(typeof i!="string"||i.length===0||i.length>256||!At.test(i))&&p("MANIFEST_INVALID","skill backend command token is invalid"),n.push(i);let t=P(e,"env")?Va(e.env):void 0;return {type:"skill",command:n,...t===void 0?{}:{env:t}}}p("MANIFEST_INVALID","action backend type is unsupported");}function ka(e){H(e)||p("MANIFEST_INVALID","action must be an object"),J(e,$s,Ws),P(e,"_meta")&&V("_meta",()=>io(e._meta));let n=V("actionId",()=>Mt(e.actionId,"actionId"));pt(n)&&p("MANIFEST_INVALID",`actionId "${n}" is not projection-safe`,"actionId");let t=V("capability",()=>ma(e.capability)),i=e.mutation;typeof i!="boolean"&&p("MANIFEST_INVALID","action mutation must be boolean","mutation");let r=V("inputSchema",()=>Ca(e.inputSchema)),o;if(P(e,"dataInputs")){Array.isArray(e.dataInputs)||p("MANIFEST_INVALID","action dataInputs must be an array","dataInputs");let A=r.properties,I=new Set,h=[];for(let T of e.dataInputs)(typeof T!="string"||!P(A,T)||I.has(T))&&p("MANIFEST_INVALID","action dataInputs must be unique declared properties","dataInputs"),I.add(T),h.push(T);o=h;}let a=V("resultProjection",()=>Lt(e.resultProjection)),s=V("backend",()=>wa(e.backend)),c;P(e,"content")&&((s.type!=="skill"||!On(e.content))&&p("MANIFEST_INVALID","action content declaration is invalid","content"),c=Fa(e.content));let d;if(P(e,"confirmation")){let A=e.confirmation;A!=="none"&&A!=="native"&&p("MANIFEST_INVALID","action confirmation is invalid","confirmation"),d=A;}let l;P(e,"schedule")&&(l=V("schedule",()=>va(e.schedule,{backend:s,inputSchema:r,hasContent:c!==void 0,hasDataInputs:o!==void 0,confirmation:d})));let u;P(e,"job")&&(l!==void 0&&p("MANIFEST_INVALID","an action is either the scheduled run or a job, not both","job"),u=V("job",()=>ja(e.job,{backend:s,inputSchema:r,hasContent:c!==void 0,hasDataInputs:o!==void 0,confirmation:d})));let f;return P(e,"jobAccess")&&(u!==void 0&&p("MANIFEST_INVALID","an action is either the job or a job control, not both","jobAccess"),f=V("jobAccess",()=>xa(e.jobAccess,{backend:s,hasContent:c!==void 0}))),{actionId:n,capability:t,mutation:i,inputSchema:r,resultProjection:a,backend:s,...c===void 0?{}:{content:c},...o===void 0?{}:{dataInputs:o},...d===void 0?{}:{confirmation:d},...l===void 0?{}:{schedule:l},...u===void 0?{}:{job:u},...f===void 0?{}:{jobAccess:f}}}function xa(e,n){return (n.backend.type!=="skill"||!("entry"in n.backend)||n.backend.entry!==Pe)&&p("MANIFEST_INVALID","jobAccess needs a tool-mode action","jobAccess"),n.hasContent&&p("MANIFEST_INVALID","a job control action takes no content","jobAccess"),(!Array.isArray(e)||e.length===0)&&p("MANIFEST_INVALID","jobAccess must list at least one operation","jobAccess"),(new Set(e).size!==e.length||!e.every(kn))&&p("MANIFEST_INVALID","jobAccess must name each operation once: start, status or cancel","jobAccess"),Object.freeze([...e])}function ja(e,n){(n.backend.type!=="skill"||!("entry"in n.backend)||n.backend.entry!==Pe)&&p("MANIFEST_INVALID","job needs a tool-mode action","job"),(n.hasContent||n.hasDataInputs||n.confirmation!==void 0&&n.confirmation!=="none")&&p("MANIFEST_INVALID","a job action takes no content, dataInputs or native confirmation","job"),(n.inputSchema.required??[]).length>0&&p("MANIFEST_INVALID","a job action input must accept {}","inputSchema.required"),H(e)||p("MANIFEST_INVALID","job must be an object","job"),J(e,[],Ys);let t=P(e,"deadlineMs")?e.deadlineMs:Cn.default;return wn(t)||p("MANIFEST_INVALID","job deadlineMs is invalid","job.deadlineMs"),{deadlineMs:t}}function va(e,n){(n.backend.type!=="skill"||!("entry"in n.backend)||n.backend.entry!==Pe)&&p("MANIFEST_INVALID","schedule needs a tool-mode action","schedule"),(n.hasContent||n.hasDataInputs||n.confirmation!==void 0&&n.confirmation!=="none")&&p("MANIFEST_INVALID","a scheduled action takes no content, dataInputs or native confirmation","schedule"),(n.inputSchema.required??[]).length>0&&p("MANIFEST_INVALID","a scheduled action input must accept {}","inputSchema.required"),H(e)||p("MANIFEST_INVALID","schedule must be an object","schedule"),J(e,Xs,Ks),Rn(e.everyMinutes)||p("MANIFEST_INVALID","schedule everyMinutes is invalid","schedule.everyMinutes");let t=P(e,"timeoutMs")?e.timeoutMs:Ln.default;return Un(t)||p("MANIFEST_INVALID","schedule timeoutMs is invalid","schedule.timeoutMs"),{everyMinutes:e.everyMinutes,timeoutMs:t}}function Va(e){return Oi(e)||p("MANIFEST_INVALID","skill backend env is invalid"),Object.freeze([...e])}function Fa(e){return Object.freeze({...e.in===void 0?{}:{in:Object.freeze({...e.in})},...e.out===void 0?{}:{out:Object.freeze({...e.out})}})}function Ba(e){return H(e)||p("INITIAL_STATE_INVALID","initialState must be an object"),J(e,ta,ia),e.path!=="ui/state.json"&&p("MANIFEST_INVALID","initialState path is not fixed"),P(e,"hash")?{path:"ui/state.json",hash:no(e.hash)}:{path:"ui/state.json"}}function Ha(e){let n=["wasm","terminal","htmlDocuments","appBrowser"];return (!H(e)||Object.keys(e).length===0||Object.keys(e).some(t=>!n.includes(t)||e[t]!==true))&&p("MANIFEST_INVALID","runtime must contain only known capability flags set to true"),{...e.wasm===true?{wasm:true}:{},...e.terminal===true?{terminal:true}:{},...e.htmlDocuments===true?{htmlDocuments:true}:{},...e.appBrowser===true?{appBrowser:true}:{}}}function za(e,n){let t;try{t=vi(e);}catch(i){let r=i!==null&&typeof i=="object"&&"code"in i&&typeof i.code=="string"?i.code:"CSP_ORIGIN_INVALID";return p("MANIFEST_INVALID",r,void 0,r.toLowerCase().replace(/_/g,"-"))}if(t.frameDomains.length>0&&p("MANIFEST_INVALID","external origins in csp are not enabled in this rollout",void 0,"csp-not-enabled"),t.connectDomains.length!==0)return n?.terminal===true&&p("MANIFEST_INVALID","runtime.terminal cannot be combined with csp.connectDomains","connectDomains","terminal-with-connect-domains"),Object.freeze({connectDomains:t.connectDomains})}function Ga(e,n){Vn(H(e)?ua(e,["csp","downloads","files","share"]):e,new Set,0,true,true),Ot(e),H(e)||p("MANIFEST_INVALID"),J(e,Gs,Js),P(e,"_meta")&&V("_meta",()=>io(e._meta)),e.manifestVersion!==2&&p("MANIFEST_INVALID");let t;P(e,"runtime")&&(t=V("runtime",()=>Ha(e.runtime)));let i;P(e,"csp")&&(i=V("csp",()=>za(e.csp,t)));let r=V("pluginId",()=>Mt(e.pluginId,"pluginId")),o=V("definitionId",()=>Mt(e.definitionId,"definitionId")),a=V("version",()=>ye(e,"version",1)),s=V("name",()=>Bi(e.name,"name")),c=V("description",()=>Bi(e.description,"description")),d;P(e,"icon")&&((typeof e.icon!="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(e.icon))&&p("MANIFEST_INVALID","icon is invalid","icon"),d=e.icon);let l;P(e,"tone")&&((typeof e.tone!="string"||!It.includes(e.tone))&&p("MANIFEST_INVALID","tone is invalid","tone"),l=e.tone),e.entry!=="ui/index.html"&&p("MANIFEST_INVALID","entry path is not fixed","entry","fixed-value");let u;P(e,"entryHash")&&(u=V("entryHash",()=>no(e.entryHash)));let f;P(e,"initialState")&&(f=V("initialState",()=>Ba(e.initialState)));let A;P(e,"usage")&&(e.usage!=="card"&&e.usage!=="window"&&p("MANIFEST_INVALID","usage is invalid","usage"),A=e.usage);let I;P(e,"detailPanel")&&(typeof e.detailPanel!="boolean"&&p("MANIFEST_INVALID","detailPanel is invalid","detailPanel"),I=e.detailPanel);let h;if(P(e,"displayModes")){((A??on)!==on||!Array.isArray(e.displayModes)||e.displayModes.length===0)&&p("MANIFEST_INVALID","displayModes are only valid for window Apps","displayModes");let F=new Set(["inline","floating","focused"]);(new Set(e.displayModes).size!==e.displayModes.length||e.displayModes.some(B=>typeof B!="string"||!F.has(B)))&&p("MANIFEST_INVALID","displayModes are invalid","displayModes"),h=e.displayModes;}(A??on)===on&&I!==void 0&&p("MANIFEST_INVALID","detailPanel is card-only","detailPanel");let T=n.mode??"local";T!=="local"&&T!=="installed"&&T!=="published"&&p("MANIFEST_INVALID","manifest mode is invalid"),T!=="local"&&u===void 0&&p("MANIFEST_INVALID","installed manifests require entryHash","entryHash","required-when-installed"),T!=="local"&&f!==void 0&&f.hash===void 0&&p("MANIFEST_INVALID","installed manifests require initialState.hash","initialState.hash","required-when-installed"),(!Array.isArray(e.surfaces)||e.surfaces.length===0)&&p("MANIFEST_INVALID","surfaces are invalid","surfaces"),e.surfaces.length>2&&W("surfaces exceed the v2 limit","surfaces","too-many-items");let G=[],j=new Set;for(let F of e.surfaces)(typeof F!="string"||!gt.includes(F))&&p("MANIFEST_INVALID","surface is unsupported","surfaces"),j.has(F)&&p("MANIFEST_INVALID","surfaces contain a duplicate","surfaces","duplicate-item"),j.add(F),G.push(F);H(e.size)||p("MANIFEST_INVALID","size must be an object","size"),V("size",()=>J(e.size,["height"]));let b=V("size",()=>ye(e.size,"height",1));b>720&&W("size.height exceeds the v2 limit","size.height","too-large");let U=V("stateProjection",()=>Lt(e.stateProjection)),$=e.summaryProjection===void 0?void 0:V("summaryProjection",()=>Lt(e.summaryProjection));$!==void 0&&$.allow.some(F=>!U.allow.includes(F))&&p("MANIFEST_INVALID","summaryProjection must be a subset of stateProjection.allow","summaryProjection");let N=V("dataPaths",()=>ha(e.dataPaths,U.allow)),M=P(e,"deviceFeatures")?V("deviceFeatures",()=>_a(e.deviceFeatures)):void 0,S=P(e,"downloads")?V("downloads",()=>Ea(e.downloads)):void 0,y=P(e,"share")?V("share",()=>Ta(e.share)):void 0,m=P(e,"files")?V("files",()=>ba(e.files)):void 0;Array.isArray(e.actions)||p("MANIFEST_INVALID","actions must be an array","actions"),e.actions.length>32&&W("actions exceed the v2 limit","actions","too-many-items");let D=[],O=new Set,k=0,R=0;for(let[F,B]of e.actions.entries()){let te=`actions[${F}]`,oe=V(te,()=>ka(B));if(O.has(oe.actionId)&&p("MANIFEST_INVALID","actions contain a duplicate actionId",`${te}.actionId`,"duplicate-item"),oe.schedule!==void 0&&(k+=1,k>bi&&p("MANIFEST_INVALID","an App declares at most one scheduled action",`${te}.schedule`,"duplicate-item")),oe.job!==void 0&&(R+=1,R>Pi&&p("MANIFEST_INVALID","an App declares at most one job action",`${te}.job`,"duplicate-item")),oe.backend.type==="core"&&oe.backend.handler==="state.set"){oe.mutation||p("MANIFEST_INVALID","state.set actions must be mutations",`${te}.mutation`);for(let Gr of Object.keys(oe.inputSchema.properties))U.allow.includes(Gr)||p("MANIFEST_INVALID","state.set input paths must be projection-allowed",`${te}.inputSchema.properties`);}O.add(oe.actionId),D.push(oe);}return {manifestVersion:2,pluginId:r,definitionId:o,version:a,name:s,description:c,...d===void 0?{}:{icon:d},...l===void 0?{}:{tone:l},entry:"ui/index.html",...u===void 0?{}:{entryHash:u},...t===void 0?{}:{runtime:t},...i===void 0?{}:{csp:i},...f===void 0?{}:{initialState:f},...A===void 0?{}:{usage:A},...I===void 0?{}:{detailPanel:I},...h===void 0?{}:{displayModes:h},surfaces:G,size:{height:b},stateProjection:U,...$===void 0?{}:{summaryProjection:$},...N===void 0?{}:{dataPaths:N},...M===void 0?{}:{deviceFeatures:M},...S===void 0?{}:{downloads:S},...y===void 0?{}:{share:y},...m===void 0?{}:{files:m},actions:D}}function io(e){H(e)||p("MANIFEST_INVALID","_meta must be an object");let n=JSON.stringify(e);(n===void 0||Buffer.byteLength(n,"utf8")>qs)&&W("_meta exceeds the 4 KiB limit",void 0,"meta-too-large");}function Ja(e){let n={},t={};for(let o of e.actions){n[o.actionId]={capabilities:[o.capability],inputKeys:Object.keys(o.inputSchema.properties??{}),...o.dataInputs===void 0?{}:{dataInputs:o.dataInputs},resultProjection:o.resultProjection,...o.confirmation===void 0?{}:{confirmation:o.confirmation},...o.content===void 0?{}:{content:o.content},...o.schedule===void 0?{}:{schedule:o.schedule},...o.job===void 0?{}:{job:o.job},...o.jobAccess===void 0?{}:{jobAccess:o.jobAccess},...o.backend.type!=="skill"||o.backend.env===void 0?{}:{env:o.backend.env}};let a=o.backend.type==="skill"||o.backend.type==="core"&&o.backend.handler==="state.set";t[o.actionId]={actionId:o.actionId,mutation:o.mutation,backend:o.backend,launchPolicy:a?"allowed":"denied",...a?{}:{denialCode:"EXEC_DENIED"}};}let i={id:e.definitionId,version:e.version,renderer:"sandbox-html",...e.usage===void 0?{}:{usage:e.usage},...e.detailPanel===void 0?{}:{detailPanel:e.detailPanel},...e.displayModes===void 0?{}:{displayModes:e.displayModes},surfaces:e.surfaces,stateProjection:e.stateProjection,...e.summaryProjection===void 0?{}:{summaryProjection:e.summaryProjection},...e.dataPaths===void 0?{}:{dataPaths:e.dataPaths},...e.downloads===void 0?{}:{downloads:e.downloads},actions:n},r={entry:{path:"ui/index.html",...e.entryHash===void 0?{}:{hash:e.entryHash}},...e.initialState===void 0?{}:{initialState:e.initialState}};return {manifest:e,definition:i,handlers:t,resources:r}}function Ct(e,n,t,i,r,o){if(typeof e=="string"){let a=r.length>0&&o.some(s=>He(r.join("."),s));return (e.length>4096||Fn(e,false,false,a))&&ue("state contains an unsafe string"),e}if(e===null||typeof e=="boolean")return e;if(typeof e=="number")return Number.isFinite(e)||ue("state contains a non-finite number"),e;(e===void 0||typeof e!="object"||typeof e=="function"||typeof e=="bigint")&&ue("state contains a non-JSON value"),t>8&&ue("state is too deep"),n.has(e)&&ue("state contains a cycle"),n.add(e);try{let a;if(Array.isArray(e))e.length>128&&ue("state array is too long"),a=e.map(c=>Ct(c,n,t+1,2097152,r,o));else {H(e)||ue("state contains a non-plain object");let c={};for(let[d,l]of Object.entries(e))(d.length>4096||!Mn.test(d)||Ge(d))&&(d.length>4096&&ue("state key is too long"),ue("state contains a reserved or invalid key")),c[d]=Ct(l,n,t+1,2097152,[...r,d],o);a=c;}let s=JSON.stringify(a);return (s===void 0||Buffer.byteLength(s,"utf8")>i)&&ue("state subtree is too large"),a}finally{n.delete(e);}}function kt(e,n=[]){H(e)||ue("initial state must be a JSON object");let t=Ct(e,new Set,0,2097152,[],n);return (t===null||Array.isArray(t)||typeof t!="object")&&ue(),t}function $a(e,n={}){Vn(e),H(e)||p("MANIFEST_INVALID"),J(e,zs),e.manifestVersion!==1&&p("MANIFEST_INVALID");let t=St(_e(e,"pluginId")),i=St(_e(e,"definitionId")),r=ye(e,"version",1),o=ye(e,"primitiveSet",1),a=n.supportedPrimitiveSet??Cs;(!Number.isSafeInteger(a)||a<1)&&p("MANIFEST_INVALID"),o>a&&p("PRIMITIVE_SET_UNSUPPORTED"),H(e.activation)||p("MANIFEST_INVALID"),J(e.activation,["kind","language"]),e.activation.kind!=="fenced-code"&&p("MANIFEST_INVALID");let s=St(_e(e.activation,"language")),c=ya(e.schema),d=ga(e.layout,c);return {manifestVersion:1,pluginId:t,definitionId:i,version:r,primitiveSet:o,activation:{kind:"fenced-code",language:s},schema:c,layout:d}}function Wa(e,n={}){return H(e)||p("MANIFEST_INVALID"),Object.hasOwn(e,"lineage")&&p("MANIFEST_INVALID","lineage is only allowed in product bundle indexes"),e.manifestVersion===2?Ga(e,n):$a(e,n)}function an(e,n={}){try{return Wa(e,n)}catch(t){if(t instanceof se)throw t;return p("MANIFEST_INVALID")}}function cn(e,n={}){let t=an(e,n);return t.manifestVersion===2?Ja(t):t}var Cs,ws,ks,eo,xs,js,vs,Vs,Fi,Fs,Bs,Hs,zs,Gs,Js,$s,Ws,Xs,Ks,Ys,qs,Zs,Qs,ea,na,ta,ia,oa,ra,sa,aa,ca,da,pa,la,se,Hi,zi,Na,Gi,Pa,Ji,$i,Sa,Ma,Oa,xt=C(()=>{g();Mi();be();_t();Li();bt();Et();Tt();Vi();Ce();Cs=1,ws=/^[a-z][a-zA-Z0-9]*(\.[a-zA-Z0-9]+)+$/,ks=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,eo=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,xs=/<\/?[A-Za-z][^>]*>/,js=/^(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)/,vs=/^(?:https?|file|ftp|ws|wss):\/\//i,Vs=/^\s*(?:javascript|data):/i,Fi=/data:[^,\s]*,/i,Fs=/(?:https?|file|ftp|ws|wss):\/\//i,Bs=/javascript:/i,Hs=/(?:^[\s]*|[\s"'(=])(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)(?=[^\s"'<>])[^\s"'<>]*/,zs=["manifestVersion","pluginId","definitionId","version","primitiveSet","activation","schema","layout"],Gs=["manifestVersion","pluginId","definitionId","version","name","description","entry","surfaces","size","stateProjection","actions"],Js=["_meta","icon","tone","entryHash","runtime","csp","initialState","usage","detailPanel","displayModes","summaryProjection","dataPaths","focusedAiDataPaths","deviceFeatures","downloads","share","files"],$s=["actionId","capability","mutation","inputSchema","resultProjection","backend"],Ws=["confirmation","dataInputs","content","schedule","job","jobAccess","_meta"],Xs=["everyMinutes"],Ks=["timeoutMs"],Ys=["deadlineMs"],qs=4*1024,Zs=["type","handler"],Qs=["type","command"],ea=["env"],na=["type","entry"],ta=["path"],ia=["hash"],oa=/^[0-9a-f]{64}$/,ra=/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/,sa=/[\r\n]/,aa=16,ca=16,da=32,pa=/^[a-z][A-Za-z0-9]{0,31}$/,la=["card-shell","meta-banner","heading","labeled-text","step-flow","text-list"],se=class e extends Error{constructor(t,i=t,r,o){super(i);this.code=t;this.path=r;this.rule=o;}code;path;rule;name="UiPluginValidationError";withPathPrefix(t){return new e(this.code,this.message,sn(t,this.path),this.rule)}};Hi=200,zi=3,Na=/^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/;Gi=200,Pa=2,Ji=4,$i=100,Sa=/^[\p{L}\p{N}][\p{L}\p{N}\p{M}_-]*$/u,Ma=[".git",".crewx","node_modules","apps","skills"],Oa=/[\u0000-\u001f\u007f-\u009f\\:<>"|?*]/;});function po(e){return typeof e=="string"&&e.length<=Ka&&Xa.test(e)}function w(e,n,t,i,r){throw new Te(e,{path:n,rule:t,...i===void 0?{}:{message:i},...r===void 0?{}:{file:r}})}function Q(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 X(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function Ie(e){let n=`_meta["${Le}"]`;return e===void 0||e===""?n:e.startsWith("[")?`${n}${e}`:`${n}.${e}`}function Qa(e){return e.toLowerCase().replace(/_/g,"-")}function ec(e){if(e===void 0||e==="")return "";let n=/^([^.[]+)(.*)$/.exec(e);if(!n)return Ie(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 Ie("definitionVersion");case "definitionId":return Ie("definitionId");default:return Ie(`${t}${i}`)}}function lo(e,n,t){return {path:t(e.path),rule:e.rule??Qa(e.code),...e.message!==e.code?{message:e.message}:{},file:n}}function uo(e){return JSON.parse(JSON.stringify(e))}function Vt(e,n,t=0,i=new Set){if(typeof e=="string"){e.length>4096&&w("LIMIT_EXCEEDED",n,"string-too-long"),(Ya.test(e)||qa.test(e)||Za.test(e))&&w("UNSAFE_VALUE",n,"unsafe-value");return}if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){Number.isFinite(e)||w("MANIFEST_INVALID",n,"non-finite-number");return}typeof e!="object"&&w("MANIFEST_INVALID",n,"non-json-value"),t>8&&w("LIMIT_EXCEEDED",n,"too-deep"),i.has(e)&&w("MANIFEST_INVALID",n,"cycle"),i.add(e);try{if(Array.isArray(e)){e.length>128&&w("LIMIT_EXCEEDED",n,"array-too-long"),e.forEach((r,o)=>Vt(r,`${n}[${o}]`,t+1,i));return}Q(e)||w("MANIFEST_INVALID",n,"non-plain-object");for(let[r,o]of Object.entries(e))Vt(o,n===""?r:`${n}.${r}`,t+1,i);}finally{i.delete(e);}}}function Ae(e,n){return (typeof e!="string"||e.length===0)&&w("MANIFEST_INVALID",n,"string"),e}function Xe(e,n){return Q(e)||w("MANIFEST_INVALID",n,"object"),e}function nc(e,n){Array.isArray(e)||w("MANIFEST_INVALID",n,"array"),e.forEach((t,i)=>Ae(t,`${n}[${i}]`));}function tc(e,n){typeof e!="boolean"&&w("MANIFEST_INVALID",n,"boolean");}function dn(e,n,t,i){for(let r of Object.keys(e))!t.includes(r)&&!i.includes(r)&&w("MANIFEST_INVALID",`${n}.${r}`,"unknown-key");for(let r of t)X(e,r)||w("MANIFEST_INVALID",`${n}.${r}`,"missing-key");}function ic(e,n){if(e!=="icon")switch(Vt(n,e),e){case "long_description":case "homepage":case "documentation":case "support":case "license":Ae(n,e);return;case "author":{let t=Xe(n,e);dn(t,e,["name"],["email","url"]);for(let i of Object.keys(t))Ae(t[i],`${e}.${i}`);return}case "repository":{let t=Xe(n,e);dn(t,e,[],["type","url"]);for(let i of Object.keys(t))Ae(t[i],`${e}.${i}`);return}case "icons":{Array.isArray(n)||w("MANIFEST_INVALID",e,"array"),n.forEach((t,i)=>{let r=`${e}[${i}]`,o=Xe(t,r);dn(o,r,["src","size"],["theme"]),Ae(o.src,`${r}.src`),Ae(o.size,`${r}.size`),X(o,"theme")&&Ae(o.theme,`${r}.theme`);});return}case "screenshots":case "keywords":case "privacy_policies":nc(n,e);return;case "tools":{Array.isArray(n)||w("MANIFEST_INVALID",e,"array"),n.forEach((t,i)=>{let r=`${e}[${i}]`,o=Xe(t,r);dn(o,r,["name"],["description"]),Ae(o.name,`${r}.name`),X(o,"description")&&Ae(o.description,`${r}.description`);});return}case "prompts":{Array.isArray(n)||w("MANIFEST_INVALID",e,"array"),n.forEach((t,i)=>{let r=`${e}[${i}]`,o=Xe(t,r);dn(o,r,["name","text"],["description","arguments"]),Ae(o.name,`${r}.name`),Ae(o.text,`${r}.text`);});return}case "tools_generated":case "prompts_generated":tc(n,e);return;case "localization":case "compatibility":case "user_config":Xe(n,e);return;default:w("MANIFEST_INVALID",e,"unknown-key");}}function Bn(e){return typeof e=="string"&&he.test(e)?e:void 0}function fo(e){return Number.isSafeInteger(e)&&e>=1?e:void 0}function oc(e){let n=Bn(e.name);if(n===void 0)return;let t=e._meta,i=Q(t)?t[Le]:void 0,r=Q(i)?i:{},o=X(r,"definitionId")?Bn(r.definitionId):n,a=X(r,"definitionVersion")?fo(r.definitionVersion):1;return {pluginId:n,...o===void 0?{}:{definitionId:o},...a===void 0?{}:{definitionVersion:a}}}function rc(e){let n=Bn(e.pluginId);if(n===void 0)return;let t=Bn(e.definitionId),i=fo(e.version);return {pluginId:n,...t===void 0?{}:{definitionId:t},...i===void 0?{}:{definitionVersion:i}}}function zt(e){try{let n=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e));if(!Q(n))return !1;let t=n._meta;return Q(t)&&X(t,Le)}catch{return false}}function sc(e,n){if(e===xe)return n.builtinOnly===true;let t=n._meta,i=Q(t)?t[Le]:void 0;return Q(i)&&i.builtinOnly===true}function ac(e,n){X(e,"server")&&w("MANIFEST_INVALID","server","server-unsupported","phase 1 runs CrewX-owned Apps only");for(let s of Object.keys(e))Bt.includes(s)||w("MANIFEST_INVALID",s,"unknown-key");for(let s of Ht)X(e,s)||w("MANIFEST_INVALID",s,"missing-key");e.manifest_version!==jt&&w("MANIFEST_INVALID","manifest_version","unsupported-version",`manifest_version must be "${jt}"`),po(e.version)||w("MANIFEST_INVALID","version","semver","version must be a semver.org version such as 0.1.0");let t=e._meta;Q(t)||w("MANIFEST_INVALID","_meta","object"),X(t,Le)||w("MANIFEST_INVALID",Ie(),"missing-key");let i=t[Le];Q(i)||w("MANIFEST_INVALID",Ie(),"object");for(let s of Object.keys(i))vt.includes(s)||co.includes(s)||w("MANIFEST_INVALID",Ie(s),"unknown-key");for(let s of vt)s==="actions"&&n!==void 0||X(i,s)||w("MANIFEST_INVALID",Ie(s),"missing-key");if(n!==void 0&&X(i,"actions")&&w("MANIFEST_INVALID",Ie("actions"),"two-truths",`actions are declared in both ${K} and ${Y}; a server.ts App keeps them in the tools file only`),cc(i.actions),X(i,"definitionVersion")){let s=i.definitionVersion;(!Number.isSafeInteger(s)||s<1)&&w("MANIFEST_INVALID",Ie("definitionVersion"),"positive-integer");}let r={};for(let s of ao)X(e,s)&&(ic(s,e[s]),r[s]=uo(e[s]));let o={};for(let[s,c]of Object.entries(t))s!==Le&&(o[s]=c);let a={manifestVersion:2,pluginId:e.name,definitionId:X(i,"definitionId")?i.definitionId:e.name,version:X(i,"definitionVersion")?i.definitionVersion:1,name:e.display_name,description:e.description};for(let[s,c]of Object.entries(i))s==="definitionId"||s==="definitionVersion"||(a[s]=c);return n!==void 0&&(a.actions=n.map(s=>({...s,backend:{type:"skill",entry:Pe}}))),Object.keys(o).length>0&&(a._meta=o),{v2Input:a,...Object.keys(o).length>0?{vendorMeta:o}:{},passthrough:r}}function cc(e){Array.isArray(e)&&e.forEach((n,t)=>{let i=Q(n)?n.backend:void 0;Q(i)&&X(i,"entry")&&w("MANIFEST_INVALID",Ie(`actions[${t}].backend.entry`),"entry-not-authorable",`an action in ${K} cannot name an entry; a server.ts App declares its actions in ${Y}`);});}function dc(e,n,t){Q(e)||w("MANIFEST_INVALID","","not-object","manifest.json must be a JSON object",K);let i;try{i=ac(e,t);}catch(a){throw a instanceof Te?new Te(a.code,{...a.reason,file:K}):a}let r;try{let a=an(i.v2Input,{mode:n.mode??"local"});a.manifestVersion!==2&&w("MANIFEST_INVALID","","v2-required"),r=a;}catch(a){throw a instanceof se?new Te(a.code,lo(a,K,ec)):a}let o=e.tools;if(Array.isArray(o)){let a=new Set(r.actions.map(s=>s.actionId));o.forEach((s,c)=>{let d=s.name;if(!a.has(d))throw new Te("MANIFEST_INVALID",{path:`tools[${c}].name`,rule:"tool-not-action",message:"every tools[].name must be an action id",file:K})});}return {file:K,manifest:r,v2Input:i.v2Input,releaseVersion:e.version,...Object.keys(i.passthrough).length>0?{mcpb:i.passthrough}:{}}}function pc(e,n){try{let t=an(e,{mode:n.mode??"local"});if(t.manifestVersion!==2)throw new Te("MANIFEST_INVALID",{path:"manifestVersion",rule:"v2-required",message:"a workspace App requires manifestVersion 2",file:xe});return {file:xe,manifest:t,v2Input:e}}catch(t){throw t instanceof se?new Te(t.code,lo(t,xe,i=>i??"")):t}}function Ft(e){return re(cn(e).definition)}function ro(e){let{entryHash:n,initialState:t,...i}=e,r={...i};return t!==void 0&&(r.initialState={path:t.path}),uo(r)}function lc(e,n){let t=ro(e),i=ro(n);return [...new Set([...Object.keys(t),...Object.keys(i)])].sort().filter(o=>Z(t[o]??null)!==Z(i[o]??null))}function uc(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 fc(e,n){let t=lc(e,n),i=uc(e,n),r="";try{let o=Ft(e),a=Ft(n);i=i||o!==a,r=` (definition hash ${o.slice(0,12)} vs ${a.slice(0,12)})`;}catch{i=true;}t.length===0&&!i||w("MANIFEST_DUAL_MISMATCH","","dual-manifest-mismatch",`${K} and ${xe} normalize to different definitions${r}`+(t.length>0?`; differing fields: ${t.join(", ")}`:""));}function Ee(e,n,t="MANIFEST_INVALID",i){return {code:t,reason:{path:e,rule:n,...i===void 0?{}:{message:i},file:Y},files:[]}}function so(e){return {...Ee("","tools-needs-manifest-json","MANIFEST_INVALID",`${Y} is read with ${K} only`),files:e}}function yc(e,n){if(e.byteLength>n)return {failure:Ee("","file-too-large","LIMIT_EXCEEDED")};let t;try{t=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e));}catch{return {failure:Ee("","invalid-json")}}if(!Q(t))return {failure:Ee("","not-object","MANIFEST_INVALID",`${Y} must be a JSON object`)};for(let r of Object.keys(t))if(r!=="schemaVersion"&&r!=="actions")return {failure:Ee(r,"unknown-key")};for(let r of ["schemaVersion","actions"])if(!X(t,r))return {failure:Ee(r,"missing-key")};if(t.schemaVersion!==1)return {failure:Ee("schemaVersion","unsupported-version","MANIFEST_INVALID",`schemaVersion must be ${1}`)};let i=t.actions;if(!Array.isArray(i))return {failure:Ee("actions","array")};for(let[r,o]of i.entries()){if(!Q(o))return {failure:Ee(`actions[${r}]`,"object")};if(X(o,"backend"))return {failure:Ee(`actions[${r}].backend`,"tools-backend","MANIFEST_INVALID",`an action in ${Y} cannot carry a backend`)}}return {actions:i}}function Ac(e,n){let t=n.maxBytes??262144,i=[],r=new TextDecoder("utf-8",{fatal:true});for(let o of fe){let a=e[o];if(a===void 0)continue;if(a.byteLength>t)return {parsed:i,failure:{code:"LIMIT_EXCEEDED",reason:{path:"",rule:"file-too-large",file:o},files:[o]}};let s;try{s=JSON.parse(r.decode(a));}catch{return {parsed:i,failure:{code:"MANIFEST_INVALID",reason:{path:"",rule:"invalid-json",file:o},files:[o]}}}if(!Q(s))return {parsed:i,failure:{code:"MANIFEST_INVALID",reason:{path:"",rule:"not-object",message:`${o} must be a JSON object`,file:o},files:[o]}};i.push({file:o,raw:s});}return {parsed:i}}function Gt(e,n={}){let{parsed:t,failure:i}=Ac(e,n),r=fe.filter(A=>e[A]!==void 0);if(i!==void 0)return {ok:false,rejection:i,parseFailure:true,builtinOnly:false};let o=e[Y],a=o===void 0?void 0:yc(o,n.maxBytes??262144);if(t.length===0)return {ok:false,rejection:a===void 0?{code:"MANIFEST_INVALID",reason:{path:"",rule:"no-manifest-file",message:"neither manifest.json nor ui-plugin.json is present"},files:[]}:so(r),parseFailure:true,builtinOnly:false};let s=t[0],c=s.file===K?oc(s.raw):rc(s.raw),d=t.some(A=>sc(A.file,A.raw)),l;if(a!==void 0){let A=t.some(I=>I.file===K)?a.failure:so(r);if(A!==void 0)return {ok:false,rejection:A,parseFailure:false,...c===void 0?{}:{identity:c},builtinOnly:d};l=a.actions;}let u=[];try{for(let A of t)u.push(A.file===K?dc(A.raw,n,l):pc(A.raw,n));u.length===2&&fc(u[0].manifest,u[1].manifest);}catch(A){if(A instanceof Te)return {ok:false,rejection:{code:A.code,reason:A.reason,files:A.code==="MANIFEST_DUAL_MISMATCH"?[...fe]:A.reason.file===void 0||A.reason.file===Y?r:[A.reason.file]},parseFailure:false,...c===void 0?{}:{identity:c},builtinOnly:d};throw A}let f=u[0];return {ok:true,...f,identity:c??{pluginId:f.manifest.pluginId},files:r}}var K,xe,fe,jt,Le,Bt,Ht,ao,vt,co,Xa,Ka,Ya,qa,Za,Te,Jt=C(()=>{g();we();be();bt();Ce();xt();K="manifest.json",xe="ui-plugin.json",fe=[K,xe],jt="0.3",Le="dev.crewx",Bt=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"]),Ht=Object.freeze(["manifest_version","name","display_name","version","description","_meta"]),ao=Object.freeze(Bt.filter(e=>e!=="server"&&!Ht.includes(e))),vt=Object.freeze(["entry","surfaces","size","stateProjection","actions"]),co=Object.freeze(["definitionId","definitionVersion","icon","tone","entryHash","runtime","initialState","usage","detailPanel","displayModes","summaryProjection","dataPaths","focusedAiDataPaths","csp","deviceFeatures","downloads","share","files"]),Xa=/^(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-]+)*))?$/,Ka=256,Ya=/<\/?[A-Za-z][^>]*>/,qa=/^\s*javascript:/i,Za=/data:[^,\s]*,/i;Te=class extends Error{constructor(t,i){super(`${t}: ${i.path||"<file>"} (${i.rule})`);this.code=t;this.reason=i;}code;reason};});function _o(e){if(e===void 0)return {kind:"none"};if(typeof e!="string")return {kind:"invalid",reason:"bad-path"};if(mc.test(e))return {kind:"url",declared:e};if(!Ec(e))return {kind:"invalid",reason:"bad-path",declared:e};let n=e.lastIndexOf("."),t=n<0?void 0:Ic.get(e.slice(n+1).toLowerCase());return t===void 0?{kind:"invalid",reason:"bad-type",declared:e}:{kind:"file",path:e,contentType:t}}function Ec(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 Wt(e,n){let t=_o(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:[$t(t.reason,t.declared)]};let i=await n(t.path);if(typeof i=="string")return {diagnostics:[$t(i,t.path)]};let r=Eo(t.contentType,i);if(!r.ok)return {diagnostics:[$t(r.reason,t.path)]};let o={path:t.path,contentType:t.contentType,byteLength:i.byteLength,bytes:i},a=r.square===false?[{code:"ICON_NOT_SQUARE",severity:"warning",declared:t.path}]:[];return {file:o,diagnostics:a}}function $t(e,n){return {code:"ICON_INVALID",severity:"error",reason:e,...n===void 0?{}:{declared:n}}}function Eo(e,n){if(n.byteLength>262144)return {ok:false,reason:"too-large"};if(e==="image/png")return !go(n,hc)||Rc(n,12,16)!=="IHDR"||n.byteLength<24?{ok:false,reason:"bytes-mismatch"}:{ok:true,square:Io(mo(n,16),mo(n,20))};if(e==="image/jpeg"){if(!go(n,_c))return {ok:false,reason:"bytes-mismatch"};let t=Oc(n);return {ok:true,square:t===void 0?void 0:Io(t.width,t.height)}}return Tc(n)}function Tc(e){let n;try{n=gc.decode(e);}catch{return {ok:false,reason:"bytes-mismatch"}}return Sc(n)?{ok:false,reason:"unsafe-svg"}:Nc.test(n)?{ok:true,square:Mc(n)}:{ok:false,reason:"bytes-mismatch"}}function Sc(e){if(Dc.some(n=>n.test(e)))return true;for(let n of e.matchAll(bc))if(!(n[1]??n[2]??n[3]??"").startsWith("#"))return true;for(let n of e.matchAll(Pc))if(yo.lastIndex=n.index??0,!yo.test(e))return true;return false}function Mc(e){let n=/<svg\b[^>]*>/i.exec(e)?.[0];if(n===void 0)return;let t=To(n,"viewBox");if(t!==void 0){let o=t.trim().split(/[\s,]+/).map(Number);return o.length===4&&o.every(Number.isFinite)?o[2]===o[3]:void 0}let i=Ao(n,"width"),r=Ao(n,"height");return i===void 0||r===void 0?void 0:i===r}function To(e,n){let t=new RegExp(`\\s${n}\\s*=\\s*(?:"([^"]*)"|'([^']*)')`).exec(e);return t?.[1]??t?.[2]}function Ao(e,n){let t=To(e,n),i=t===void 0?null:/^\s*(\d+(?:\.\d+)?)(?:px)?\s*$/.exec(t);return i===null?void 0:Number(i[1])}function Oc(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(Lc(t))return n+9>e.byteLength?void 0:{height:ho(e,n+5),width:ho(e,n+7)};n+=2+i;}}function Lc(e){return e>=192&&e<=207&&e!==196&&e!==200&&e!==204}function Io(e,n){if(!(e<=0||n<=0))return e===n}function go(e,n){return e.byteLength>=n.length&&n.every((t,i)=>e[i]===t)}function Rc(e,n,t){return String.fromCharCode(...e.subarray(n,t))}function mo(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 Ic,gc,mc,hc,_c,Nc,Dc,bc,Pc,yo,Xt=C(()=>{g();Ic=new Map([["svg","image/svg+xml"],["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"]]),gc=new TextDecoder("utf-8",{fatal:true}),mc=/^[A-Za-z][A-Za-z0-9+.-]*:/,hc=[137,80,78,71,13,10,26,10],_c=[255,216,255];Nc=/^\s*(?:<\?[\s\S]*?\?>\s*|<!--[\s\S]*?-->\s*)*<svg(?=[\s/>])/,Dc=[/<script/i,/[\s"'/]on[a-z]+\s*=/i,/<foreignobject/i,/<!doctype/i,/<!entity/i,/<(?:iframe|embed|object)\b/i,/@import/i],bc=/(?:^|[\s"'/])(?:xlink:)?href\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+))/gi,Pc=/url\(/gi,yo=/url\(\s*["']?#/iy;});var Do=C(()=>{g();Si();Jt();Xt();xt();Ce();});function E(e,n=e){throw new Ne(e,n)}var Ne,zn=C(()=>{g();Ne=class extends Error{constructor(t,i=t){super(i);this.code=t;}code;name="McpAppContractError"};});var bo=C(()=>{g();});var Po=C(()=>{g();we();be();zn();bo();});function Mo(e,n){return So.add(e),n!==void 0&&Uc.set(e,n),e}function Ke(e){return e!==null&&typeof e=="object"&&So.has(e)}var So,Uc,Gn=C(()=>{g();So=new WeakSet,Uc=new WeakMap;});function un(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Kt(e,n,t=[]){let i=new Set([...n,...t]),r=Object.keys(e);return n.every(o=>Object.hasOwn(e,o))&&r.every(o=>i.has(o))}function Ro(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let n of Object.values(e))Ro(n);return Object.freeze(e)}function ee(e){throw new De("LINEAGE_INVALID",e)}function Vc(e){throw new De("LINEAGE_STALE",e)}function Uo(e){if(!un(e)||!Kt(e,kc,xc)||!un(e.actions))return ee("Lineage definition shape is invalid");for(let n of Object.values(e.actions))if(!un(n)||!Kt(n,jc,vc))return ee("Lineage action definition shape is invalid");return e}function Fc(e){if(!un(e)||!Kt(e,Cc,wc))return ee("Lineage entry shape is invalid");if(!Number.isSafeInteger(e.version)||e.version<1||typeof e.hash!="string"||!Oo.test(e.hash))return ee("Lineage entry identity is invalid");if(e.sourceHash!==void 0&&(typeof e.sourceHash!="string"||!Oo.test(e.sourceHash)))return ee("Lineage source hash is invalid");if(e.compat!==void 0&&e.compat!=="break")return ee("Lineage compatibility marker is invalid");let n=Uo(e.definition);if(n.version!==e.version)return ee("Lineage version does not match its definition");if(e.sourceHash!==void 0&&n.sourceHash!==e.sourceHash)return ee("Lineage source hash does not match its definition");let t;try{t=re(n),le({...n,hash:e.hash});}catch{return ee("Lineage definition is invalid")}return t!==e.hash?ee("Lineage definition hash does not match"):Ro({version:e.version,hash:e.hash,definition:n,...e.sourceHash===void 0?{}:{sourceHash:e.sourceHash},...e.compat===void 0?{}:{compat:e.compat}})}function Lo(e){return e.stateProjection?.allow??[]}function Bc(e,n){let t=[],i=new Set(Lo(n));Lo(e).some(s=>!i.has(s))&&t.push("S1_STATE_PROJECTION");let r=new Set(n.dataPaths??[]);(e.dataPaths??[]).some(s=>!r.has(s))&&t.push("S2_DATA_PATHS");for(let[s,c]of Object.entries(e.actions)){let d=n.actions[s];if(d&&(c.confirmation??"native")==="native"&&(d.confirmation??"native")!=="native"){t.push("S3_ACTION_CONFIRMATION");break}}Object.keys(e.legacy?.agentAccess??{}).some(s=>!Object.hasOwn(n.actions,s))&&t.push("S4_LEGACY_AGENT_ACTIONS");let a=e.summaryProjection?.allow;if(a!==void 0){let s=new Set(n.summaryProjection?.allow??[]);a.some(c=>!s.has(c))&&t.push("S5_SUMMARY_PROJECTION");}return t}function Hc(e,n){return Z(e)===Z(n)}function Yt(e,n){if(!Array.isArray(e)||e.length===0)return ee("Definition lineage is missing");if(!un(n)||typeof n.hash!="string")return ee("Current definition is invalid");let t,i;try{let{hash:s,...c}=n;i=Uo(c),t={...i,hash:s},le(t);}catch{return ee("Current definition is invalid")}let r=e.map(Fc),o=r[0].definition.id;if(r.some(s=>s.definition.id!==o))return ee("Lineage definition ids do not match");if(r.some((s,c)=>c>0&&s.version<=r[c-1].version))return ee("Lineage generations are not in increasing version order");if(r.some((s,c)=>r.findIndex(d=>d.hash===s.hash)!==c))return ee("Lineage contains a duplicate hash");let a=r[r.length-1];if(a.version!==t.version||a.hash!==t.hash||a.definition.id!==t.id||!Hc(a.definition,i))return Vc("The last lineage generation does not match the current package");if(t.legacy!==void 0){let s=new Set(Object.keys(t.actions)),c=new Set;for(let l of r)if(l.sourceHash===void 0)for(let u of Object.keys(l.definition.actions))s.has(u)&&c.add(u);let d=Object.keys(t.legacy.agentAccess??{});if(d.length!==c.size||d.some(l=>!c.has(l))){let l="S4_LEGACY_AGENT_ACCESS_COMPLETE";throw new De("LINEAGE_INVALID",`Lineage compatibility failed: ${l}`,[l])}}for(let s=0;s<r.length-1;s+=1){if(r.slice(s,-1).some(l=>l.compat==="break"))continue;let d=Bc(r[s].definition,t);if(d.length>0)throw new De("LINEAGE_INVALID",`Lineage compatibility failed: ${d.join(", ")}`,d)}return Object.freeze({entries:Object.freeze(r),current:t})}var De,Oo,Cc,wc,kc,xc,jc,vc,qt=C(()=>{g();we();be();De=class extends Error{constructor(t,i=t,r=[]){super(i);this.code=t;this.violations=r;}code;violations;name="UiDefinitionLineageError"},Oo=/^[0-9a-f]{64}$/,Cc=["version","hash","definition"],wc=["sourceHash","compat"],kc=["id","version","actions"],xc=["sourceHash","usage","detailPanel","displayModes","renderer","surfaces","stateProjection","dataPaths","summaryProjection","downloads","legacy"],jc=["capabilities"],vc=["inputKeys","dataInputs","confirmation","resultProjection","content","env","schedule","job","jobAccess"];});var Co,wo,ko,xo,jo=C(()=>{g();Co="text/html;profile=mcp-app",wo=["crewx_app_terminal_connect","crewx_app_html_viewer_open","crewx_app_browser","crewx_files_list","crewx_files_read","crewx_files_write","crewx_docs_share"],ko=["crewx_listWorkspaces","crewx_queryAgent","crewx_executeAgent","crewx_getTaskResult","crewx_listTasks","crewx_listAgents","callBrowser","openTab","listTabs","closeTab"],xo="text/html";});function fn(e){return typeof e=="string"&&zc.includes(e)}function Jn(e,n){return e==="card"&&n?.type==="core"&&fn(n.handler)}var zc,$n=C(()=>{g();zc=Object.freeze(["card.secret-env"]);});function vo(e,n=[],t){if(e.content!==void 0||e.confirmation!=="none")return "denied";let i=Gc();return i&&Object.hasOwn(i,e.actionId)?i[e.actionId]:e.backend?.type==="core"&&e.backend.handler.startsWith("host.")?"denied":e.backend?.type==="core"&&e.backend.handler==="state.set"?"allowed":e.backend?.type==="core"&&fn(e.backend.handler)||e.backend?.type==="skill"?"approval_required":e.backend===void 0&&n.includes(e.actionId)?"allowed":"denied"}function Gc(e){return;}var Vo=C(()=>{g();we();Gn();$n();});function Qc(e){return In.has(e)&&(e.initialState===void 0||In.has(e.initialState))}function Go(e,n,t,i){let r=i===void 0?void 0:Object.freeze({hash:i.hash,bytes:Object.freeze(i.bytes)}),o=Object.freeze({mimeType:xo,entryHash:e,html:n,bytes:Object.freeze(t),...r===void 0?{}:{initialState:r}});return r!==void 0&&In.add(r),In.add(o),o}function ed(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:ae}),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:ae}),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:ae}),n}function nd(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:ae},{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:{...Zt}},required:["ref"],additionalProperties:false},textFallback:"A markdown file of this App is read through this App.",visibility:Object.freeze(["app"]),kind:"host",resourceBinding:ae},{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:{...Zt},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:ae}),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:{...Zt}},required:["ref"],additionalProperties:false},textFallback:"The Host share sheet opens for a markdown file of this App.",visibility:Object.freeze(["app"]),kind:"host",resourceBinding:ae}),n}function Ue(e,n,t){return (typeof e!="string"||!Ho.test(e))&&E(n,`${t} must be a safe identifier`),e}function yn(e,n,t){let i=e??t;return (typeof i!="string"||i.trim().length===0||i.length>Wc)&&E("TOOL_INVALID",`${n} must be a meaningful description`),i}function ei(e){return (typeof e!="string"||e.length===0||e.length>Ye||!/<html(?:\s|>)/i.test(e)||!/<\/html\s*>/i.test(e))&&E("HTML_INVALID","MCP App HTML must be a non-empty HTML document"),e}function An(e,n=0){try{let t=pe(e,n);return t.type!==void 0&&t.type!=="object"&&E("TOOL_INVALID","MCP App inputSchema must describe an object"),t}catch(t){if(t instanceof Ne)throw t;E("TOOL_INVALID","MCP App inputSchema must be projection-safe JSON");}}function td(e){return (typeof e!="string"||e.trim().length===0||e.length>Xc)&&E("TOOL_INVALID","MCP App tools require a meaningful text fallback"),e}function id(e){e===void 0&&E("TOOL_INVALID","MCP App tool visibility is required");let n=[...e];return (n.length===0||n.some(t=>t!=="model"&&t!=="app")||new Set(n).size!==n.length)&&E("TOOL_INVALID","MCP App tool visibility must contain model and/or app once"),n}function $o(e){return (typeof e!="string"||!zo.test(e))&&E("RESOURCE_URI_INVALID","MCP App resource URI is not a registered ui:// URI"),e}function Wo(e){let n=Ue(e.appId,"APP_ID_INVALID","Local App id"),t=yn(e.name,"Local App name",n),i=yn(e.description,"Local App description",`${t} interactive view`),r=Yn(e.definition),o=ei(e.html),a=Wn(e.entryHash,"Local App entry hash"),s=e.entryBytes===void 0?Array.from(new TextEncoder().encode(o)):Kn(e.entryBytes,"Local App entry bytes");(Xn(s)!==a||Yo(s)!==o)&&E("HTML_INVALID","Local App entry bytes do not match the HTML hash");let c=od(e),d=[];Array.isArray(e.actions)||E("TOOL_INVALID","Local App actions must be an array");for(let b of e.actions){let U=Ue(b.actionId,"TOOL_ID_INVALID","Local App action id");(d.includes(U)||!Object.prototype.hasOwnProperty.call(r.actions,U))&&E("TOOL_INVALID",`Local App action is not declared by the UI definition: ${U}`),d.push(U);}let l=Ue(e.readToolName,"TOOL_ID_INVALID","Local App read tool name"),u=e.actionToolName===void 0?void 0:Ue(e.actionToolName,"TOOL_ID_INVALID","Local App action tool name");d.length===0&&u!==void 0&&E("TOOL_INVALID","A static local App cannot register an action tool"),d.length>0&&u===void 0&&E("TOOL_INVALID","A stateful local App requires an action tool name"),u!==void 0&&u===l&&E("TOOL_ID_CONFLICT",`Local App read and action tools share a name: ${l}`);let f=[...ed(e.runtime),...nd(e.hostTools)];f.some(b=>b.name===l||b.name===u)&&E("TOOL_ID_CONFLICT","Local App read or action tool conflicts with a requested Host capability");let A={name:l,description:`${t} current state`,inputSchema:Zc,textFallback:`${t} current state is available through its open instance.`,visibility:Object.freeze(["model","app"]),kind:"read",resourceBinding:ae},I=[Object.freeze(A)];if(I.push(...f.map(b=>Object.freeze(b))),u!==void 0){let b={name:u,description:`${t} actions`,inputSchema:ni(e.actions),textFallback:`${t} action requests are handled by the open App instance.`,visibility:Object.freeze(["app"]),kind:"action",resourceBinding:ae,actionIds:Object.freeze([...d])};I.push(Object.freeze(b));}let h=[],T=new Set(I.map(b=>b.name));if(u!==void 0)for(let b of e.actions){let U=`${u}__${b.actionId}`;if(U.length>128||!Ho.test(U)){h.push(Object.freeze({toolName:U,actionId:b.actionId,reason:"name_too_long"}));continue}if(T.has(U)){h.push(Object.freeze({toolName:U,actionId:b.actionId,reason:"name_collision"}));continue}let $=vo({actionId:b.actionId,confirmation:r.actions[b.actionId]?.confirmation,content:r.actions[b.actionId]?.content,backend:b.backend},e.modelActions),N=Object.freeze([...dd($,r.usage,b.backend)]),M={name:U,description:`${U} action`,inputSchema:An(b.inputSchema),textFallback:`${U} action requests are handled by the open App instance.`,visibility:N,kind:"action",resourceBinding:ae,actionId:b.actionId,actionIds:Object.freeze([b.actionId]),_meta:Object.freeze({ui:Object.freeze({visibility:N})})};I.push(Object.freeze(M)),T.add(U);}let G=Go(a,o,s,c===void 0?void 0:{hash:c.hash,bytes:[...c.bytes]}),j={appId:n,name:t,description:i,...e.icon===void 0?{}:{icon:qo(e.icon)},...e.tone===void 0?{}:{tone:Zo(e.tone)},builtinOnly:false,definition:r,...e.runtime===void 0?{}:{runtime:Object.freeze({...e.runtime})},...e.deviceFeatures===void 0?{}:{deviceFeatures:Object.freeze([...e.deviceFeatures])},...e.downloads===void 0?{}:{downloads:e.downloads},...e.share===void 0?{}:{share:Object.freeze({...e.share})},...e.files===void 0?{}:{files:Object.freeze({...e.files})},resourceBinding:ae,resource:G,tools:Object.freeze(I),toolDiagnostics:Object.freeze(h)};return q(j)}function Xo(e={}){return new Qt(e)}function ni(e){if(e.length===0)return An({type:"object",properties:{},additionalProperties:false});let n=e.map(i=>i.actionId),t=new Map;for(let i of e)t.set(i.actionId,An(i.inputSchema));return An(rd(n,t),Jo)}function od(e){let n=e.definition.dataPaths??[];if(e.initialStateBytes===void 0){e.initialStateHash!==void 0&&E("STATE_INVALID","Initial state hash has no bytes"),e.initialState!==void 0&&pe(e.initialState,0,n);return}e.initialStateHash===void 0&&E("STATE_INVALID","Initial state bytes require a hash");let t=Wn(e.initialStateHash,"Initial state hash"),i=Kn(e.initialStateBytes,"Initial state bytes");Xn(i)!==t&&E("STATE_INVALID","Initial state bytes do not match the hash");let r;try{let o=new TextDecoder("utf-8",{fatal:!0}).decode(Uint8Array.from(i));r=pe(JSON.parse(o),0,n);}catch{E("STATE_INVALID","Initial state bytes are not projection-safe JSON");}return e.initialState!==void 0&&Z(r)!==Z(pe(e.initialState,0,n))&&E("STATE_INVALID","Initial state bytes do not match the state value"),{hash:t,bytes:Object.freeze([...i])}}function rd(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 sd(e){let n=gn(e),t=Ue(n.appId,"APP_ID_INVALID","MCP App id"),i=ei(n.html);$o(n.uiUri);let r=n.definition===void 0?void 0:Yn(n.definition),o=e.provenance;o!==void 0&&(!Ke(o)||o.appId!==t||o.definitionId!==r?.id||o.version!==r?.version||o.definitionHash!==r?.hash)&&E("TOOL_INVALID","Product App built-in registration provenance is not verified");let a=Object.freeze(n.tools.map(d=>q(gn(d)))),s=q({...n,appId:t,html:i,...r===void 0?{}:{definition:r},...o===void 0?{}:{provenance:o},tools:a}),c=q({uri:s.uiUri,mimeType:Co,text:i,...s.csp===void 0?{}:{_meta:{ui:{csp:s.csp}}}});return q({appId:t,name:s.name,description:s.description,...s.icon===void 0?{}:{icon:s.icon},...s.tone===void 0?{}:{tone:s.tone},builtinOnly:s.builtinOnly,uiUri:s.uiUri,...r===void 0?{}:{definition:r},resourceBinding:Object.freeze({kind:"mcp",uri:s.uiUri}),resource:c,tools:a,descriptor:s})}function ad(e){(e.resourceBinding.kind!=="instance"||e.builtinOnly!==false)&&E("STATE_INVALID","Local App registration binding is invalid"),Object.prototype.hasOwnProperty.call(e,"uiUri")&&E("STATE_INVALID","Local App registration cannot contain uiUri");let n=Ue(e.appId,"APP_ID_INVALID","Local App id"),t=Yn(e.definition),i=e.provenance;i!==void 0&&(!Ke(i)||i.appId!==n||i.definitionId!==t.id||i.version!==t.version||i.definitionHash!==t.hash)&&E("TOOL_INVALID","Product App local registration provenance is not verified");let r=cd(e.resource),o=e.tools.map(s=>{Ue(s.name,"TOOL_ID_INVALID","Local App tool name"),yn(s.description,"Local App tool description","Local App tool"),td(s.textFallback);let c=An(s.inputSchema,s.kind==="action"&&!("actionId"in s)?Jo:0);if((s.resourceBinding.kind!=="instance"||Object.prototype.hasOwnProperty.call(s,"resourceUri"))&&E("TOOL_INVALID","Local App tools cannot carry an MCP resource URI"),s.kind==="host")return (!qc.has(s.name)||s.visibility.length!==1||s.visibility[0]!=="app"||Object.prototype.hasOwnProperty.call(s,"actionId"))&&E("TOOL_INVALID","Local App Host tools must use an allow-listed name and app-only visibility"),q({...s,inputSchema:c,visibility:Object.freeze(["app"])});if(s.kind==="action"){if("actionId"in s){let l=Ue(s.actionId,"TOOL_ID_INVALID","Local App action id");Object.prototype.hasOwnProperty.call(t.actions,l)||E("TOOL_INVALID","Local App action tool references an undeclared action");let u=id(s._meta.ui.visibility);return JSON.stringify(u)!==JSON.stringify(s.visibility)&&E("TOOL_INVALID","Local App action metadata visibility must match the tool visibility"),q({...s,actionId:l,actionIds:Object.freeze([l]),inputSchema:c,visibility:u,_meta:{ui:{visibility:u}}})}let d=[...s.actionIds];return (d.length===0||d.some(l=>!Object.prototype.hasOwnProperty.call(t.actions,l)))&&E("TOOL_INVALID","Local App action tool references an undeclared action"),q({...s,inputSchema:c,actionIds:Object.freeze(d)})}return q({...s,inputSchema:c})}),a=q({appId:n,name:yn(e.name,"Local App name",e.appId),description:yn(e.description,"Local App description",e.name),...e.icon===void 0?{}:{icon:qo(e.icon)},...e.tone===void 0?{}:{tone:Zo(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:ae,resource:r,tools:Object.freeze(o),toolDiagnostics:Object.freeze([...e.toolDiagnostics??[]])});return Fo.has(e)?e:(Fo.add(a),a)}function cd(e){let n=ei(e.html),t=Wn(e.entryHash,"Local App entry hash");if(Qc(e))return e;let i=Kn(e.bytes,"Local App entry bytes");(Xn(i)!==t||Yo(i)!==n)&&E("HTML_INVALID","Local App entry bytes do not match the HTML hash");let r=e.initialState===void 0?void 0:{hash:Wn(e.initialState.hash,"Initial state hash"),bytes:Kn(e.initialState.bytes,"Initial state bytes")};return r&&Xn(r.bytes)!==r.hash&&E("STATE_INVALID","Initial state bytes do not match the hash"),Go(t,n,i,r)}function dd(e,n,t){if(Jn(n,t))return ["model"];let i=t?.type==="core"&&fn(t.handler);return e==="denied"||i?["app"]:["model","app"]}function pd(e){return q({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:Ko(e.definition),...e.provenance===void 0?{}:{provenance:e.provenance},entryHash:e.resource.entryHash,resourceBinding:ae,tools:e.tools})}function ld(e){return q({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:Ko(e.definition)},resourceBinding:Object.freeze({kind:"mcp",uri:e.uiUri}),tools:e.tools})}function Yn(e){try{if(Object.isFrozen(e))return le(e),q(e);let n=gn(e);return le(n),q(n)}catch(n){if(n instanceof Ne)throw n;E("STATE_INVALID","UI definition is not a valid immutable definition");}}function Ko(e){return q({id:e.id,version:e.version,hash:e.hash})}function ud(e){return e!==null&&typeof e=="object"&&typeof e.id=="string"&&Number.isSafeInteger(e.version)&&typeof e.hash=="string"}function Bo(e,n,t){return `${e}\0${n}\0${t}`}function Wn(e,n){return (typeof e!="string"||!$c.test(e))&&E("SERIALIZATION_INVALID",`${n} is invalid`),e}function Xn(e){return crypto.createHash("sha256").update(Uint8Array.from(e)).digest("hex")}function Kn(e,n){return (!Array.isArray(e)||e.some(t=>!Number.isInteger(t)||t<0||t>255))&&E("SERIALIZATION_INVALID",`${n} is invalid`),[...e]}function Yo(e){try{return new TextDecoder("utf-8",{fatal:!0}).decode(Uint8Array.from(e))}catch{E("SERIALIZATION_INVALID","UTF-8 bytes are invalid");}}function qo(e){return (typeof e!="string"||!Kc.test(e))&&E("TOOL_INVALID","MCP App icon is invalid"),e}function Zo(e){return (typeof e!="string"||!Yc.has(e))&&E("TOOL_INVALID","MCP App tone is invalid"),e}function gn(e,n=new Map){if(e===null||typeof e!="object")return e;let t=e;if(n.has(t)&&E("SERIALIZATION_INVALID","MCP App value contains a cycle"),Array.isArray(e)){let o=[];n.set(t,o);for(let a of e)o.push(gn(a,n));return n.delete(t),o}let i;try{i=Object.getPrototypeOf(e);}catch{E("SERIALIZATION_INVALID","MCP App value cannot be cloned");}i!==Object.prototype&&i!==null&&E("SERIALIZATION_INVALID","MCP App value must be plain JSON");let r={};n.set(t,r);for(let[o,a]of Object.entries(e))Object.defineProperty(r,o,{configurable:true,enumerable:true,value:gn(a,n),writable:true});return n.delete(t),r}function q(e,n=new Set){if(e===null||typeof e!="object"||n.has(e)||In.has(e))return e;n.add(e);for(let t of Object.values(e))q(t,n);return Object.freeze(e),e}var Ho,zo,$c,Ye,Wc,Xc,Kc,Yc,qc,ae,Zc,In,Fo,Zt,Jo,Qt,qn=C(()=>{g();Po();we();be();Gn();zn();qt();jo();Vo();$n();Ho=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,zo=/^ui:\/\/crewx\/([A-Za-z][A-Za-z0-9._-]{0,127})\/([0-9a-f]{12})$/,$c=/^[0-9a-f]{64}$/,Ye=8*1024*1024,Wc=8*1024,Xc=16*1024,Kc=/^[a-z][a-z0-9-]{0,63}$/,Yc=new Set(["blue","violet","emerald","amber","rose","sky","slate","indigo"]),qc=new Set(wo),new Set(ko),ae=Object.freeze({kind:"instance"}),Zc=Object.freeze({type:"object",properties:Object.freeze({}),additionalProperties:false}),In=new WeakSet,Fo=new WeakSet;Zt={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.'};Jo=4;Qt=class{builtinApps;localApps;builtinDescriptors;builtinTools;mcpResources=new Map;localById=new Map;registrationById=new Map;launcherById=new Map;definitionByKey=new Map;handlerByKey=new Map;mcpToolByName=new Map;localToolByName=new Map;constructor(n){let t=n.builtins??n.builtin,i=[],r=[],o=[],a=new Set,s=new Set;for(let u of t?.listMcpApps()??[]){let f=sd(u);a.has(f.appId)&&E("APP_ID_CONFLICT",`MCP App id is already registered: ${f.appId}`),a.add(f.appId);let A=f.tools;for(let I of A)s.has(I.name)&&E("TOOL_ID_CONFLICT",`MCP App tool name is already registered: ${I.name}`),s.add(I.name),this.mcpToolByName.set(I.name,I),o.push(I);this.mcpResources.set(f.resource.uri,f.resource),i.push(f),r.push(f.descriptor);}let c=(n.localApps??n.locals??[]).map(ad),d=new Set(c.flatMap(u=>u.tools.filter(f=>!(f.kind==="action"&&"actionId"in f)).map(f=>f.name))),l=[];for(let u of c){let f=u;a.has(f.appId)&&E("APP_ID_CONFLICT",`MCP App id is already registered: ${f.appId}`),a.add(f.appId);let A=[],I=[...f.toolDiagnostics??[]];for(let h of f.tools){if(s.has(h.name)){if(h.kind==="host"&&this.localToolByName.get(h.name)?.kind==="host"){A.push(h);continue}if(h.kind==="action"&&"actionId"in h){I.push(Object.freeze({toolName:h.name,actionId:h.actionId,reason:"name_collision"}));continue}E("TOOL_ID_CONFLICT",`MCP App tool name is already registered: ${h.name}`);}if(h.kind==="action"&&"actionId"in h&&d.has(h.name)){I.push(Object.freeze({toolName:h.name,actionId:h.actionId,reason:"name_collision"}));continue}s.add(h.name),this.localToolByName.set(h.name,h),A.push(h);}(A.length!==f.tools.length||I.length!==(f.toolDiagnostics?.length??0))&&(f=q({...f,tools:Object.freeze(A),toolDiagnostics:Object.freeze(I)})),l.push(f),this.localById.set(f.appId,f);}for(let u of i)this.registrationById.set(u.appId,u),this.launcherById.set(u.appId,ld(u)),u.definition&&this.addDefinition(u.definition);for(let u of l)this.registrationById.set(u.appId,u),this.launcherById.set(u.appId,pd(u)),this.addDefinition(u.definition);for(let u of n.definitions??[])this.addDefinition(u);for(let u of n.handlers??[])this.addHandler(u);this.builtinApps=Object.freeze(i),this.localApps=Object.freeze(l),this.builtinDescriptors=Object.freeze(r),this.builtinTools=Object.freeze(o);}getMcpApp(n){return this.builtinApps.find(t=>t.appId===n)?.descriptor??null}listMcpApps(){return this.builtinDescriptors}listMcpAppTools(){return this.builtinTools}resolveMcpAppTool(n){return this.mcpToolByName.get(n)??null}resolveMcpAppResource(n){return typeof n!="string"||!zo.test(n)?null:this.mcpResources.get(n)??null}requireMcpAppResource(n){$o(n);let t=this.mcpResources.get(n);return t||E("RESOURCE_NOT_FOUND",`MCP App resource is not registered: ${n}`),t}listLocalMcpApps(){return this.localApps}getLocalMcpApp(n){return this.localById.get(n)??null}listLocalMcpAppTools(){return Object.freeze([...this.localToolByName.values()])}resolveLocalMcpAppTool(n){return this.localToolByName.get(n)??null}resolveLocalMcpAppResource(n,t){let i=this.localById.get(n);return !i||t!==void 0&&i.definition.hash!==t?null:i.resource}listRegistrations(){return Object.freeze([...this.builtinApps,...this.localApps])}getRegistration(n){return this.registrationById.get(n)??null}listLaunchers(){return Object.freeze([...this.launcherById.values()].filter(n=>{let t=this.registrationById.get(n.appId),i=t?"descriptor"in t?t.descriptor.provenance:t.provenance:void 0,r=Ke(i)&&i.launcher===false;return t?.definition?.usage!=="card"&&!r}))}listCardApps(){return Object.freeze([...this.launcherById.values()].filter(n=>this.registrationById.get(n.appId)?.definition?.usage==="card"))}getLauncher(n){return this.launcherById.get(n)??null}resolveDefinition(n){if(!ud(n))return null;let t=this.definitionByKey.get(Dt(n));if(!t||t.hash!==n.hash)return null;try{return re(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(Bo(n,t,i))??null}addDefinition(n){let t=Yn(n),i=Dt(t),r=this.definitionByKey.get(i);r&&r.hash!==t.hash&&E("STATE_INVALID",`UI definition generation conflicts: ${i}`),r||this.definitionByKey.set(i,t);}addHandler(n){(!n||typeof n.definitionId!="string"||typeof n.actionId!="string"||!Number.isSafeInteger(n.version)||n.version<1||typeof n.handle!="function")&&E("STATE_INVALID","UI action handler registration is invalid");let t=Bo(n.definitionId,n.version,n.actionId);this.handlerByKey.has(t)&&E("TOOL_INVALID",`Duplicate UI action handler registration: ${t}`),this.handlerByKey.set(t,Object.freeze({...n}));}};});function fd(e,n){let t=Wo({appId:e.appId,name:e.name,description:e.description,...e.icon===void 0?{}:{icon:e.icon},...e.tone===void 0?{}:{tone:e.tone},...e.normalized.manifest.runtime===void 0?{}:{runtime:e.normalized.manifest.runtime},...e.normalized.manifest.deviceFeatures===void 0?{}:{deviceFeatures:e.normalized.manifest.deviceFeatures},...e.normalized.manifest.downloads===void 0?{}:{downloads:e.normalized.manifest.downloads},...e.normalized.manifest.share===void 0?{}:{share:e.normalized.manifest.share},...e.normalized.manifest.files===void 0?{}:{files:e.normalized.manifest.files},definition:e.definition,html:e.html,entryHash:e.entryHash,entryBytes:e.entryBytes,initialState:e.initialState,...e.initialStateHash===void 0?{}:{initialStateHash:e.initialStateHash},...e.initialStateBytes===void 0?{}:{initialStateBytes:e.initialStateBytes},readToolName:e.toolNames.read,...e.toolNames.action===void 0?{}:{actionToolName:e.toolNames.action},actions:e.normalized.manifest.actions.map(r=>({actionId:r.actionId,inputSchema:r.inputSchema,backend:r.backend})),...{}});return e.provenance===void 0?t:Object.freeze({...t,provenance:e.provenance})}function Qo(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=fd(e);Xo({localApps:[t],definitions:[e.definition]});}var er=C(()=>{g();qn();});function nr(){return Object.freeze({[ti]:{candidates:new Map,assetCatalogs:new Map,preparedCandidates:new Map}})}function yd(e){if(e===null||typeof e!="object"||!(ti in e))throw new TypeError("scanCache must be created by createWorkspaceAppScanCache");return e[ti]}function tr(e,n){let t=yd(e),i=t.rootIdentity;return i!==void 0&&(i.dev!==n.dev||i.ino!==n.ino||i.realPath!==n.realPath)&&(t.candidates.clear(),t.assetCatalogs.clear(),t.preparedCandidates.clear(),t.lastCandidateScanUnchanged=void 0,t.lastCandidateKeys=void 0,t.scanStartedAtNs=void 0,t.lastAssetCatalogsUnchanged=void 0,t.lastSnapshot=void 0,t.lastSnapshotBuildInputs=void 0,t.lastSnapshotCandidates=void 0,t.lastSnapshotCatalogFingerprint=void 0),t.rootIdentity=n,t}var ti,ir=C(()=>{g();ti=Symbol("crewx.workspace-app-scan-cache.state");});function ce(e){let n=typeof e=="object"&&e!==null&&"code"in e?String(e.code):"";return n==="ENOENT"?new _("NOT_FOUND"):n==="ELOOP"?new _("PATH_ESCAPED"):n==="EFBIG"||n==="EOVERFLOW"?new _("LIMIT_EXCEEDED"):n==="EACCES"||n==="EPERM"||n==="ENOTDIR"?new _("READ_DENIED"):new _("READ_DENIED")}function md(e){if(typeof e!="string"||e.length===0||!path.isAbsolute(e))throw new _("READ_DENIED")}function ii(e){if(typeof e!="string"||path.isAbsolute(e)||/[\\\u0000]/.test(e))throw new _("PATH_ESCAPED");if(e==="")return [];let n=e.split("/");if(n.some(t=>t.length===0||t==="."||t===".."))throw new _("PATH_ESCAPED");return n}function nt(e,n){let t=path.relative(e,n);return t===""||t!==".."&&!t.startsWith(`..${path.sep}`)&&!path.isAbsolute(t)}function Ze(e){return {dev:e.dev,ino:e.ino,size:e.size,mtimeNs:e.mtimeNs,ctimeNs:e.ctimeNs}}function ai(e,n){return e.dev===n.dev&&e.ino===n.ino}function ci(e,n){return ai(e,n)&&e.size===n.size&&e.mtimeNs===n.mtimeNs&&e.ctimeNs===n.ctimeNs}async function Zn(e){md(e);let n,t;try{n=await promises.realpath(e),t=await promises.stat(n,{bigint:!0});}catch(i){throw ce(i)}if(!t.isDirectory())throw new _("READ_DENIED");return {realRoot:n,identity:Ze(t)}}async function sr(e,n,t){if(t.length<2||t[0]!=="apps"&&t[0]!=="skills")return;let i,r;try{if(i=path.resolve(e,t[0],t[1]),r=await promises.realpath(i),!(await promises.stat(r,{bigint:!0})).isDirectory())throw new _("READ_DENIED")}catch(o){throw o instanceof _?o:ce(o)}if(!nt(n,r))throw new _("PATH_ESCAPED");return r}async function Qn(e,n,t,i){let r,o,a;try{r=await promises.lstat(e,{bigint:!0}),o=await promises.realpath(e),a=await promises.stat(o,{bigint:!0});}catch(s){throw ce(s)}if(!nt(n,o)||t!==void 0&&!nt(t,o))throw new _("PATH_ESCAPED");if(!r.isFile()||!a.isFile())throw new _("READ_DENIED");if(!ai(i,r)||!ai(i,a)||i.dev!==a.dev)throw new _("PATH_ESCAPED")}async function qe(e,n){let t,i;try{t=await promises.realpath(e),i=await promises.stat(t,{bigint:!0});}catch{throw new _("PATH_ESCAPED")}if(t!==n.realRoot||!ci(n.identity,Ze(i)))throw new _("PATH_ESCAPED")}function hd(e){return e.isSymbolicLink()?{name:e.name,kind:"symlink"}:e.isDirectory()?{name:e.name,kind:"directory"}:e.isFile()?{name:e.name,kind:"file"}:{name:e.name,kind:"other"}}var _,si,gd,rr,Qe,tt,ar,cr,pi=C(()=>{g();_=class extends Error{constructor(t){super(t);this.code=t;}code;name="AppDiscoveryFsError"},si=fs$1.constants.O_NOFOLLOW,gd=fs$1.constants.O_NONBLOCK,rr=fs$1.constants.O_RDONLY|(si??0)|(gd??0);Qe=class{async getRootIdentity(n){let t=await Zn(n);return await qe(n,t),{dev:t.identity.dev,ino:t.identity.ino,realPath:t.realRoot}}async listDirectory(n,t){let i=ii(t),r=await Zn(n),o=path.resolve(n,...i),a,s;try{a=await promises.realpath(o),s=await promises.stat(a,{bigint:!0});}catch(c){let d=ce(c);if(d.code==="NOT_FOUND")return [];throw d}if(!nt(r.realRoot,a)||!s.isDirectory())throw new _("PATH_ESCAPED");try{let c=await promises.readdir(a,{withFileTypes:!0,encoding:"utf8"});return await qe(n,r),c.map(hd)}catch(c){let d=ce(c);if(d.code==="NOT_FOUND")return [];throw d}}async readdir(n,t){return this.listDirectory(n,t)}async readDirectory(n,t){return this.listDirectory(n,t)}async readVerifiedFile(n,t,i){if(!Number.isSafeInteger(i)||i<0)throw new _("READ_DENIED");if(si===void 0)throw new _("UNSUPPORTED");let r=ii(t),o=await Zn(n),a=path.resolve(n,...r),s=path.relative(n,a);if(s===".."||s.startsWith(`..${path.sep}`)||path.isAbsolute(s))throw new _("PATH_ESCAPED");let c;try{c=await promises.open(a,rr);}catch(d){throw ce(d)}try{let d;try{let I=await c.stat({bigint:!0});d=Ze(I);}catch(I){throw ce(I)}if(d.size>BigInt(i))throw new _("LIMIT_EXCEEDED");if(d.size>BigInt(Number.MAX_SAFE_INTEGER))throw new _("LIMIT_EXCEEDED");await qe(n,o);let l=await sr(n,o.realRoot,r);await Qn(a,o.realRoot,l,d);let u=new Uint8Array(new ArrayBuffer(Number(d.size))),f=0;for(;f<u.byteLength;){let I;try{I=(await c.read(u,f,u.byteLength-f,f)).bytesRead;}catch(h){throw ce(h)}if(I<=0)throw new _("IDENTITY_CHANGED");f+=I;}let A;try{let I=await c.stat({bigint:!0});A=Ze(I);}catch(I){throw ce(I)}if(!ci(d,A))throw new _("IDENTITY_CHANGED");return await Qn(a,o.realRoot,l,A),await qe(n,o),new Uint8Array(u)}finally{await c.close().catch(()=>{});}}async fingerprintVerifiedFile(n,t,i){if(!Number.isSafeInteger(i)||i<0)throw new _("READ_DENIED");if(si===void 0)throw new _("UNSUPPORTED");let r=ii(t),o=await Zn(n),a=path.resolve(n,...r),s=path.relative(n,a);if(s===".."||s.startsWith(`..${path.sep}`)||path.isAbsolute(s))throw new _("PATH_ESCAPED");let c;try{c=await promises.open(a,rr);}catch(d){throw ce(d)}try{let d;try{let f=await c.stat({bigint:!0});d=Ze(f);}catch(f){throw ce(f)}if(d.size>BigInt(i)||d.size>BigInt(Number.MAX_SAFE_INTEGER))throw new _("LIMIT_EXCEEDED");await qe(n,o);let l=await sr(n,o.realRoot,r);await Qn(a,o.realRoot,l,d);let u;try{let f=await c.stat({bigint:!0});u=Ze(f);}catch(f){throw ce(f)}if(!ci(d,u))throw new _("IDENTITY_CHANGED");return await Qn(a,o.realRoot,l,u),await qe(n,o),{...u,candidateRealPath:l??o.realRoot}}catch(d){throw d instanceof _?d:ce(d)}finally{await c.close().catch(()=>{});}}async readFileVerified(n,t,i){return this.readVerifiedFile(n,t,i)}},tt=new Qe,ar=tt,cr=Qe;});function En(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;try{let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}catch{return false}}function pr(e){return typeof e=="string"&&he.test(e)?e:void 0}function Pd(e){return e.length>0&&e!=="."&&e!==".."&&!/[\\/\u0000]/.test(e)}function ve(e,n){let t=new TextEncoder().encode(e),i=new TextEncoder().encode(n),r=Math.min(t.byteLength,i.byteLength);for(let o=0;o<r;o+=1){let a=t[o]-i[o];if(a!==0)return a}return t.byteLength-i.byteLength}function Sd(e){if(typeof e=="string")return {name:e,kind:"directory"};if(e===null||typeof e!="object")return null;let n=e;if(typeof n.name!="string")return null;if(n.kind==="file"||n.kind==="directory"||n.kind==="symlink"||n.kind==="other")return {name:n.name,kind:n.kind};if(n.type==="file"||n.type==="directory"||n.type==="symlink"||n.type==="other")return {name:n.name,kind:n.type};let t=n.isDirectory;if(typeof t=="function"&&t.call(e))return {name:n.name,kind:"directory"};let i=n.isSymbolicLink;if(typeof i=="function"&&i.call(e))return {name:n.name,kind:"symlink"};let r=n.isFile;return typeof r=="function"&&r.call(e)?{name:n.name,kind:"file"}:{name:n.name,kind:"other"}}function Md(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 Od(e){return Dd.decode(e)}function Ld(e){return JSON.parse(Od(e))}function lr(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 Rd(e){if(e instanceof _)return lr(e.code);if(e!==null&&typeof e=="object"&&"code"in e){let n=e.code;if(typeof n=="string")return lr(n)}}function Me(e,n){let t=n();return Number.isFinite(t)&&Number.isFinite(e)&&t-e<=5e3}function Ud(e){if(typeof e.readVerifiedFile=="function")return e.readVerifiedFile;if(typeof e.readFileVerified=="function")return e.readFileVerified}function Cd(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 ur(e,n,t,i){let r=Ud(e);if(!r)throw new _("READ_DENIED");return Md(await r.call(e,n,t,i))}async function fi(e,n,t){let i=Cd(e);if(!i)throw new _("READ_DENIED");let r=await i.call(e,n,t);if(!Array.isArray(r))throw new _("READ_DENIED");return r.map(Sd).filter(o=>o!==null)}function wd(e,n,t,i){return Object.freeze({code:e,...{},source:n,relativePath:t})}function kd(e){if(!En(e))throw new TypeError("productBundle.reservedIds must be an object with appIds and definitionIds arrays");try{let n=Reflect.ownKeys(e);if(n.length!==2||!n.includes("appIds")||!n.includes("definitionIds"))throw new TypeError("productBundle.reservedIds must contain exactly appIds and definitionIds");let t=(i,r)=>{if(!Array.isArray(i))throw new TypeError("productBundle.reservedIds."+r+" must be an array");let o=[];for(let a=0;a<i.length;a+=1){let s=i[a];if(typeof s!="string"||s.length===0)throw new TypeError("productBundle.reservedIds."+r+" must contain non-empty strings");o.push(s);}return Object.freeze([...new Set(o)].sort(ve))};return Object.freeze({appIds:t(e.appIds,"appIds"),definitionIds:t(e.definitionIds,"definitionIds")})}catch(n){throw n instanceof TypeError?n:new TypeError("productBundle.reservedIds must be a valid reservation object")}}function xd(e,n){return e.appIds.length===n.appIds.length&&e.appIds.every((t,i)=>t===n.appIds[i])&&e.definitionIds.length===n.definitionIds.length&&e.definitionIds.every((t,i)=>t===n.definitionIds[i])}function Tn(e){return Object.freeze({appIds:Object.freeze([...new Set(e.map(n=>n.appId))].sort(ve)),definitionIds:Object.freeze([...new Set(e.map(n=>n.definition.id))].sort(ve))})}function it(e,n){let t=Object.keys(e).sort(ve),i=[...n].sort(ve);return t.length===i.length&&t.every((r,o)=>r===i[o])}function fr(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 jd(e){let n;try{n=Ld(e);}catch{return}if(!En(n)||!it(n,["version","packages"])||n.version!==1||!Array.isArray(n.packages)||n.packages.length>yi)return;let t=new Set,i=new Set,r=0,o=[];for(let a of n.packages){if(!En(a))return;let s=["packageDir","appId","definition","files"],c=Object.hasOwn(a,"lineage"),d=Object.hasOwn(a,"launcher"),l=[...c?["lineage"]:[],...d?["launcher"]:[]];if(!it(a,[...s,...l])||d&&a.launcher!==false)return;let u=fr(a.packageDir),f=pr(a.appId);if(!u||u.length!==2||u[0]!=="apps"||!Pd(u[1])||!f||t.has(a.packageDir)||!En(a.definition)||!it(a.definition,["id","version","hash"]))return;let A=pr(a.definition.id),I=a.definition.version,h=a.definition.hash;if(!A||!Number.isSafeInteger(I)||I<1||typeof h!="string"||!ui.test(h)||!Array.isArray(a.files)||a.files.length<2||a.files.length>Ai)return;let T=new Set,G=[];for(let j of a.files){if(!En(j)||!it(j,["path","sha256"]))return;let b=fr(j.path);if(!b||typeof j.sha256!="string"||!ui.test(j.sha256))return;let U=b.join("/"),$=`${a.packageDir}/${U}`;if(T.has(U)||i.has($))return;T.add(U),i.add($),G.push(Object.freeze({path:U,sha256:j.sha256}));}if(!fe.some(j=>T.has(j))||!T.has("ui/index.html")||(r+=G.length,r>Ed))return;t.add(a.packageDir),o.push(Object.freeze({packageDir:a.packageDir,...d?{launcher:false}:{},appId:f,definition:Object.freeze({id:A,version:I,hash:h}),lineage:Array.isArray(a.lineage)?a.lineage:[],files:Object.freeze(G.sort((j,b)=>ve(j.path,b.path)))}));}return Object.freeze({version:1,packages:Object.freeze(o)})}function je(e){let n=Rd(e);return n==="PATH_ESCAPED"||n==="IDENTITY_CHANGED"||n==="TOCTOU"?"PATH_ESCAPED":n==="LIMIT_EXCEEDED"?"LIMIT_EXCEEDED":"BUNDLE_INTEGRITY"}async function vd(e,n,t,i,r){let o=[],a=async(s,c)=>{if(!Me(i,r))throw new _("LIMIT_EXCEEDED");if(c>2)throw new _("LIMIT_EXCEEDED");let d=await fi(e,n,s);for(let l of d){if(typeof l.name!="string"||l.name.length===0||l.name==="."||l.name===".."||/[\\/\u0000]/.test(l.name))throw new _("PATH_ESCAPED");let u=`${s}/${l.name}`;if(l.kind==="file"){if(o.push(u.slice(t.length+1)),o.length>Ai)throw new _("LIMIT_EXCEEDED")}else if(l.kind==="directory")await a(u,c+1);else throw l.kind==="symlink"?new _("PATH_ESCAPED"):new _("READ_DENIED")}};return await a(t,0),o.sort(ve)}function Vd(e){return fe.includes(e)?262144:e==="ui/index.html"?Ye:e==="ui/state.json"?2097152:e.startsWith("ui/assets/")?Nd:Td}async function yr(e,n,t,i){if(e===void 0)return {packages:[],diagnostics:[],incomplete:false,reservedIds:bd};let r=kd(e.reservedIds),o=[],a=(y,m,D)=>wd(y,"bundled",m),s=(y=[],m=false,D)=>({...D===void 0?{}:{indexHash:D},packages:y,diagnostics:o,incomplete:m,reservedIds:r});if(typeof e.root!="string"||e.root.length===0||typeof e.expectedIndexHash!="string"||!ui.test(e.expectedIndexHash))return o.push(a("BUNDLE_INTEGRITY","bundle-index.json")),s();let c;try{c=await ur(n,e.root,"bundle-index.json",_d);}catch(y){return o.push(a(je(y),"bundle-index.json")),s()}let d=crypto.createHash("sha256").update(c).digest("hex");if(d!==e.expectedIndexHash)return o.push(a("BUNDLE_INTEGRITY","bundle-index.json")),s();let l=jd(c);if(l===void 0)return o.push(a("BUNDLE_INTEGRITY","bundle-index.json")),s();if(!xd(Tn(l.packages),r))return o.push(a("BUNDLE_INTEGRITY","bundle-index.json")),s([],false,d);if(!Me(t,i))return o.push(a("LIMIT_EXCEEDED","bundle-index.json")),s(l.packages.map(y=>({indexEntry:y,failureCode:"LIMIT_EXCEEDED"})),true,d);let u;try{u=await fi(n,e.root,"");}catch(y){return o.push(a(je(y),"bundle-index.json")),s(l.packages.map(m=>({indexEntry:m,failureCode:je(y)})),false,d)}if(!Me(t,i))return o.push(a("LIMIT_EXCEEDED","bundle-index.json")),s(l.packages.map(y=>({indexEntry:y,failureCode:"LIMIT_EXCEEDED"})),true,d);let f=u.find(y=>y.name==="bundle-index.json"&&y.kind==="file"),A=u.find(y=>y.name==="apps"&&y.kind==="directory"),I=y=>l.packages.map(m=>({indexEntry:m,failureCode:y}));if(!f)return o.push(a("BUNDLE_INTEGRITY","bundle-index.json")),s(I("BUNDLE_INTEGRITY"),false,d);let h=u.filter(y=>y.name!=="bundle-index.json"&&y.name!=="apps");if(h.length>0){let y=h.some(m=>m.kind==="symlink")?"PATH_ESCAPED":"BUNDLE_INTEGRITY";return o.push(a(y,"bundle-index.json")),s(I("BUNDLE_INTEGRITY"),false,d)}if(u.some(y=>y.name==="apps"&&y.kind!=="directory"))return o.push(a("PATH_ESCAPED","apps")),s(I("PATH_ESCAPED"),false,d);let T=[];if(A)try{T=await fi(n,e.root,"apps");}catch(y){return o.push(a(je(y),"apps")),s(I(je(y)),false,d)}if(!Me(t,i)||T.length>yi)return o.push(a("LIMIT_EXCEEDED","apps")),s(I("LIMIT_EXCEEDED"),true,d);let G=new Map(l.packages.map(y=>[y.packageDir.slice(5),y])),j=T.filter(y=>!G.has(y.name));for(let y of j)o.push(a(y.kind==="symlink"?"PATH_ESCAPED":"BUNDLE_INTEGRITY",`apps/${y.name}`));if(j.length>0){let y=j.some(m=>m.kind==="symlink")?"PATH_ESCAPED":"BUNDLE_INTEGRITY";return s(I(y),false,d)}let b=new Set,U=new Map,$=new Map;for(let y of l.packages){let m=U.get(y.appId)??[];m.push(y),U.set(y.appId,m);let D=`${y.definition.id}\0${String(y.definition.version)}`,O=$.get(D)??[];O.push(y),$.set(D,O);}for(let y of [...U.values(),...$.values()])if(y.length>1)for(let m of y)b.add(m);let N=[],M=c.byteLength,S=false;for(let y of l.packages){if(!Me(t,i)){S=true,N.push({indexEntry:y,failureCode:"LIMIT_EXCEEDED"});continue}let m;try{let k=y.lineage[y.lineage.length-1];if(!k)throw new De("LINEAGE_INVALID","Definition lineage is missing");if(k.definition.id!==y.definition.id||k.version!==y.definition.version||k.hash!==y.definition.hash)throw new De("LINEAGE_STALE","Last lineage generation does not match bundle identity");m=Yt(y.lineage,{...k.definition,hash:k.hash}).entries;}catch(k){let R=k instanceof De?k.code:"LINEAGE_INVALID";o.push(a(R,y.packageDir)),N.push({indexEntry:y,failureCode:R});continue}let D=T.find(k=>k.name===y.packageDir.slice(5));if(!A||!D){N.push({indexEntry:y,failureCode:"BUNDLE_INTEGRITY"});continue}if(D.kind!=="directory"){N.push({indexEntry:y,failureCode:D.kind==="symlink"?"PATH_ESCAPED":"BUNDLE_INTEGRITY"});continue}let O;try{let k=await vd(n,e.root,y.packageDir,t,i);if(!Me(t,i)){S=!0,N.push({indexEntry:y,failureCode:"LIMIT_EXCEEDED"});continue}let R=y.files.map(B=>B.path);if(k.length!==R.length||k.some((B,te)=>B!==R[te])){N.push({indexEntry:y,failureCode:"BUNDLE_INTEGRITY"});continue}O=new Map;let F;for(let B of y.files){if(!Me(t,i)){F="LIMIT_EXCEEDED",S=!0;break}if(M>=li){F="LIMIT_EXCEEDED";break}let te;try{te=await ur(n,e.root,`${y.packageDir}/${B.path}`,Vd(B.path));}catch(oe){F=je(oe);break}if(!Me(t,i)){F="LIMIT_EXCEEDED",S=!0;break}if(M+te.byteLength>li){M=li,F="LIMIT_EXCEEDED";break}if(M+=te.byteLength,crypto.createHash("sha256").update(te).digest("hex")!==B.sha256){F="BUNDLE_INTEGRITY";break}O.set(B.path,te);}if(F!==void 0){N.push({indexEntry:y,failureCode:F});continue}}catch(k){Me(t,i)||(S=true),N.push({indexEntry:y,failureCode:je(k)});continue}N.push({indexEntry:y,lineage:m,files:O,...b.has(y)?{failureCode:"DUPLICATE_ID"}:{}});}return s(N,S,d)}var _d,yi,Ai,Ed,Td,Nd,li,ui,Dd,bd,Ii=C(()=>{g();qt();Ce();Jt();qn();pi();_d=256*1024,yi=64,Ai=128,Ed=yi*Ai,Td=2*1024*1024,Nd=8*1024*1024,li=32*1024*1024,ui=/^[0-9a-f]{64}$/,Dd=new TextDecoder("utf-8",{fatal:true}),bd=Object.freeze({appIds:Object.freeze([]),definitionIds:Object.freeze([])});});var jr={};$r(jr,{AppDiscoveryFsError:()=>_,LOCAL_APP_TOOL_PREFIX:()=>Hd,MCP_APP_WORKSPACE_TOOL_PREFIX:()=>zd,NodeAppDiscoveryFs:()=>Qe,NodeAppDiscoveryFsAdapter:()=>cr,WORKSPACE_APP_TOOL_PREFIX:()=>en,createWorkspaceAppScanCache:()=>nr,defaultAppDiscoveryFs:()=>tt,defaultNodeAppDiscoveryFs:()=>ar,deriveWorkspaceAppToolName:()=>Gd,deriveWorkspaceAppToolNames:()=>hi,discoverWorkspaceAppCandidates:()=>hp,discoverWorkspaceApps:()=>_i,isWorkspacePackage:()=>Bd,productAppBundleReservations:()=>Tn,scanWorkspaceApps:()=>_p});function Bd(e,n){let t=n.split("/");return t.length===2&&t[0]===e&&/^[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(t[1])}function hi(e){if(typeof e!="string"||!he.test(e))throw new TypeError("pluginId must be a safe UI plugin identifier");let n=`${en}${e}`.length+7<=128?e:`hash_${crypto.createHash("sha256").update(e,"utf8").digest("hex")}`;return {read:`${en}${n}_read`,action:`${en}${n}_action`}}function Gd(e,n="read"){let t=hi(e);return n==="read"?t.read:t.action}function Ir(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 $d(e,n){return n.length===0||n==="."||n===".."||/[\\/\u0000]/.test(n)?e==="skills"?"skills":"apps":`${e==="skills"?"skills":"apps"}/${n}`}function Wd(e){return e.length>0&&e!=="."&&e!==".."&&!/[\\/\u0000]/.test(e)}function Dn(e,n){let t=new TextEncoder().encode(e),i=new TextEncoder().encode(n),r=Math.min(t.byteLength,i.byteLength);for(let o=0;o<r;o+=1){let a=t[o]-i[o];if(a!==0)return a}return t.byteLength-i.byteLength}function Sr(e){if(typeof e=="string")return {name:e,kind:"directory"};if(e===null||typeof e!="object")return null;let n=e;if(typeof n.name!="string")return null;if(n.kind==="file"||n.kind==="directory"||n.kind==="symlink"||n.kind==="other")return {name:n.name,kind:n.kind};if(n.type==="file"||n.type==="directory"||n.type==="symlink"||n.type==="other")return {name:n.name,kind:n.type};let t=n.isDirectory;if(typeof t=="function"&&t.call(e))return {name:n.name,kind:"directory"};let i=n.isSymbolicLink;if(typeof i=="function"&&i.call(e))return {name:n.name,kind:"symlink"};let r=n.isFile;return typeof r=="function"&&r.call(e)?{name:n.name,kind:"file"}:{name:n.name,kind:"other"}}function Xd(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 Mr(e){return Jd.decode(e)}function Kd(e){return JSON.parse(Mr(e))}function Yd(e){if(e===void 0)return;let n=e.definitionId!==void 0&&e.definitionVersion!==void 0?`${e.definitionId}\0${String(e.definitionVersion)}`:void 0;return {pluginId:e.pluginId,...n===void 0?{}:{definitionKey:n}}}function ot(e,n,t,i,r){let o={code:e,...i===void 0?{}:{pluginId:i},source:n,relativePath:t,...r?.reason===void 0?{}:{reason:Object.freeze({...r.reason})},...r?.files===void 0?{}:{files:Object.freeze([...r.files])}};return Object.freeze(o)}function gr(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 ne(e){if(e instanceof _)return gr(e.code);if(e!==null&&typeof e=="object"&&"code"in e){let n=e.code;if(typeof n=="string")return gr(n)}}function Fe(e,n){return e==="PATH_ESCAPED"||e==="IDENTITY_CHANGED"||e==="TOCTOU"?"PATH_ESCAPED":e==="LIMIT_EXCEEDED"?"LIMIT_EXCEEDED":n==="manifest"&&e==="NOT_FOUND"?"MANIFEST_MISSING":n==="entry"?"ENTRY_INVALID":n==="initial"?"INITIAL_STATE_INVALID":"MANIFEST_INVALID"}function mr(e){return {reason:e.reason,...e.code==="MANIFEST_DUAL_MISMATCH"?{files:e.files}:{}}}function hr(e){return e==="MANIFEST_DUAL_MISMATCH"?e:Or(e)}function qd(e){return Or(e.code)}function Or(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 Lr("UiPluginValidationError",e)}}function Lr(e,n){throw new Error(`Unmapped ${e} code: ${String(n)}`)}function Rr(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 Lr("McpAppContractError",e)}}function Oe(e,n){let t=n();return Number.isFinite(t)&&Number.isFinite(e)&&t-e<=5e3}function Zd(e){return {pluginId:e.appId,definitionKey:`${e.definition.id}\0${String(e.definition.version)}`}}function Qd(e,n){let t=n.get("package.json");if(t!==void 0)try{let r=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(t));if(Ir(r)){let o=r.bin,a=typeof o=="string"?o:Ir(o)?Object.values(o).find(s=>typeof s=="string"):void 0;for(let s of [a,r.main]){if(typeof s!="string")continue;let c=ep(s);if(c&&n.has(c))return c}}}catch{}return [`${e.slice(e.lastIndexOf("/")+1)}.js`,"index.js","main.js"].find(r=>n.has(r))}function ep(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 np(){return globalThis.performance?.now()??Date.now()}function Ve(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let n of Object.values(e))Ve(n);return Object.freeze(e)}function _r(e){return Object.freeze(Array.from(e))}async function bn(e,n,t,i){if(n.pinnedFiles!==void 0){let s=n.pinnedFiles.get(t);if(s===void 0)throw new _("NOT_FOUND");if(s.byteLength>i)throw new _("LIMIT_EXCEEDED");return new Uint8Array(s)}let r=`${n.relativePath}/${t}`,o=n.scanContext,a=e.fingerprintVerifiedFile;if(o===void 0||!o.cacheable||typeof a!="function")return Dr(e,n.root,r,i);try{let s=o.priorFingerprints.get(r)??await a.call(e,o.workspaceRoot,r,i);o.candidateRealPath=s.candidateRealPath;let c=await Dr(e,n.root,r,i),d=await a.call(e,o.workspaceRoot,r,i);return o.candidateRealPath=d.candidateRealPath,Cr(s,d)&&d.size===BigInt(c.byteLength)&&!wr(d,o.scanStartedAtNs)?o.files.set(r,{relativePath:r,byteLimit:i,fingerprint:d}):o.cacheable=!1,c}catch(s){let c=!t.includes("/")&&ne(s)==="NOT_FOUND"&&o.directoryListings.some(l=>l.relativePath===n.relativePath&&!rt(l.key,t)),d=t===Y&&ne(s)==="NOT_FOUND"&&ip(o.directoryListings,n.relativePath);throw !c&&!d&&(o.cacheable=false),s}}async function tp(e,n,t){if(n.pinnedFiles!==void 0)return {iconDiagnostics:[]};let i=await Wt(t,async o=>{try{return await bn(e,n,o,262144)}catch(a){let s=ne(a);return s==="NOT_FOUND"?"missing":s==="LIMIT_EXCEEDED"?"too-large":"bad-path"}}),r=i.file;return {...r===void 0?{}:{iconFile:{path:r.path,sha256:crypto.createHash("sha256").update(r.bytes).digest("hex"),contentType:r.contentType,byteLength:r.byteLength}},iconDiagnostics:i.diagnostics}}function ip(e,n){let t=e.find(r=>r.relativePath===n);if(t===void 0)return false;if(!rt(t.key,"dist"))return true;let i=e.find(r=>r.relativePath===`${n}/dist`);return i!==void 0&&!rt(i.key,"tools.json")}function Ur(e,n){return JSON.stringify([e.realPath,n.source,n.relativePath])}async function rp(e,n,t,i,r,o,a,s){let c=e.fingerprintVerifiedFile,d=Ur(t,i),l=r.candidates.get(d),u=i.relativePath,f;try{f=await Nr(e,n,u);}catch(S){if(ne(S)!=="NOT_FOUND")throw S}let A=f===void 0?void 0:{relativePath:u,key:f};if(A!==void 0&&(i.source==="apps"||i.source==="skills")&&!fe.some(S=>rt(A.key,S)))return Oe(a,s)?l!==void 0&&l.candidate===void 0&&l.candidateRealPath===void 0&&l.files.length===0&&l.directoryListings.length===1&&l.directoryListings[0]?.relativePath===A.relativePath&&l.directoryListings[0]?.key===A.key&&(i.source==="apps"?l.diagnostic?.code==="MANIFEST_MISSING":l.diagnostic===void 0)&&typeof c=="function"?{memo:l}:typeof c!="function"?{}:{context:{state:r,cacheKey:d,workspaceRoot:n,scanStartedAtNs:o,directoryListings:Object.freeze([A]),priorFingerprints:new Map,files:new Map,cacheable:true}}:{timeLimitReached:true};let I=async S=>{if(S==="")return A;let y=`${i.relativePath}${S}`;try{let m=await Nr(e,n,y);return m===void 0?void 0:{relativePath:y,key:m}}catch(m){if(ne(m)==="NOT_FOUND")return;throw m}},h=await Promise.all(Er.map(I)),T=await Promise.all(op.map(I));if(!Oe(a,s))return {timeLimitReached:true};let G=typeof c=="function"&&h.every(S=>S!==void 0),j=h.filter(S=>S!==void 0),b=[...j,...T.filter(S=>S!==void 0)],U=new Map,$=l!==void 0&&G,N;if(l!==void 0&&typeof c=="function"){let S=await Promise.all(l.files.map(async y=>{if(!Oe(a,s))return {kind:"time",file:y};try{let m=await c.call(e,n,y.relativePath,y.byteLimit);return {kind:"fingerprint",file:y,current:m}}catch(m){return ne(m)==="NOT_FOUND"?{kind:"missing",file:y}:{kind:"error",file:y,error:m}}}));if(S.some(y=>y.kind==="time"))return {timeLimitReached:true};for(let y of S){if(y.kind==="error")throw y.error;if(y.kind==="missing"){$=false;continue}if(y.kind!=="fingerprint")continue;let{file:m,current:D}=y;U.set(m.relativePath,D),N??=D.candidateRealPath,(D.candidateRealPath!==l.candidateRealPath||!Cr(D,m.fingerprint)||wr(D,o))&&($=false);}}let M=l!==void 0&&l.directoryListings.length===b.length&&l.directoryListings.every((S,y)=>S.relativePath===b[y]?.relativePath&&S.key===b[y]?.key);return l!==void 0&&G&&M&&$&&N===l.candidateRealPath?{memo:l}:!G||j.length!==Er.length?{}:{context:{state:r,cacheKey:d,workspaceRoot:n,scanStartedAtNs:o,directoryListings:Object.freeze(b),priorFingerprints:U,files:new Map,...N===void 0?{}:{candidateRealPath:N},cacheable:true}}}function rt(e,n){try{let t=JSON.parse(e);return Array.isArray(t)&&t.some(i=>Array.isArray(i)&&i[0]===n)}catch{return true}}async function Nr(e,n,t){let i=kr(e);if(typeof i!="function")return;let r=await i.call(e,n,t);if(!Array.isArray(r)||r.some(a=>typeof a=="string"))return;let o=r.map(Sr);if(!o.some(a=>a===null))return JSON.stringify(o.slice().sort((a,s)=>Dn(a.name,s.name)||Dn(a.kind,s.kind)).map(a=>[a.name,a.kind]))}function Cr(e,n){return e.dev===n.dev&&e.ino===n.ino&&e.size===n.size&&e.mtimeNs===n.mtimeNs&&e.ctimeNs===n.ctimeNs}function wr(e,n){let t=e.mtimeNs-n;return t>=-Tr&&t<=Tr}function gi(e){let n=e.scanContext,t=e.source==="skills"&&e.candidate===void 0&&e.diagnostic===void 0&&n?.files.size===0,i=e.source==="apps"&&e.candidate===void 0&&e.diagnostic?.code==="MANIFEST_MISSING"&&n?.files.size===0,r=t||i;if(n===void 0||!n.cacheable||n.candidateRealPath===void 0&&!r||n.files.size===0&&!r)return;let o=Object.freeze({...!r&&n.candidateRealPath!==void 0?{candidateRealPath:n.candidateRealPath}:{},directoryListings:n.directoryListings,files:Object.freeze([...n.files.values()]),...e.candidate===void 0?{}:{candidate:e.candidate},...e.diagnostic===void 0?{}:{diagnostic:e.diagnostic},...e.identity===void 0?{}:{identity:e.identity},...e.provenance===void 0?{}:{provenance:e.provenance}});n.state.candidates.set(n.cacheKey,o);}function sp(e,n,t){let i=crypto.createHash("sha256"),r=new TextEncoder().encode(Z(e)),o=a=>{let s=new Uint8Array(8);new DataView(s.buffer).setBigUint64(0,BigInt(a)),i.update(s);};return o(r.byteLength),i.update(r),o(n.byteLength),i.update(n),o(t.byteLength),i.update(t),i.digest("hex")}function ap(e,n){let t={...e.definition,sourceHash:n},i;try{i=re(t);}catch(o){throw o instanceof L&&o.code==="INPUT_INVALID"?new se("MANIFEST_INVALID","normalized definition is invalid"):o}let r={...t,hash:i};try{le(r);}catch{throw new se("MANIFEST_INVALID","normalized definition is invalid")}return r}function cp(e,n){return e.actions.some(t=>t.backend.type==="core"&&t.backend.handler!=="state.set"&&!Jn(n,t.backend))}function dp(e){if(typeof e.readVerifiedFile=="function")return e.readVerifiedFile;if(typeof e.readFileVerified=="function")return e.readFileVerified}function kr(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 Dr(e,n,t,i){let r=dp(e);if(!r)throw new _("READ_DENIED");return Xd(await r.call(e,n,t,i))}async function pp(e,n,t){let i=kr(e);if(!i)throw new _("READ_DENIED");let r=await i.call(e,n,t);if(!Array.isArray(r))throw new _("READ_DENIED");return r.map(Sr).filter(o=>o!==null)}function lp(e){let n=[];for(let t of [e.reserved,e.builtin])t&&n.push(t);return e.builtins&&"listMcpApps"in e.builtins?n.push(br(e.builtins)):e.builtins&&n.push(e.builtins),e.builtinCatalog&&n.push(br(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 br(e){let n=[],t=[],i=[];for(let r of e.listMcpApps())typeof r.appId=="string"&&n.push(r.appId),r.definition&&typeof r.definition.id=="string"&&t.push(r.definition.id);for(let r of e.listMcpAppTools())typeof r.name=="string"&&i.push(r.name);return {appIds:n,definitionIds:t,toolNames:i}}function ge(e,n){e.diagnostic||(e.diagnostic=ot(n,e.source,e.relativePath,e.identity?.pluginId));}function up(e,n){let t=new Set,i=new Map;for(let o of e){let a=o.identity?.pluginId;if(a===void 0)continue;let s=i.get(a)??[];s.push(o),i.set(a,s);}for(let o of i.values()){if(o.length<2)continue;let a=o.filter(c=>c.provenance!==void 0);if(a.length>0){let c=o.find(d=>n.has(d));if(c){for(let d of a)t.add(d);for(let d of o)d!==c&&d.provenance===void 0&&ge(d,"RESERVED_ID");continue}for(let d of o)d.provenance===void 0&&ge(d,"RESERVED_ID");if(a.length>1)for(let d of a)ge(d,"DUPLICATE_ID");continue}let s=o.filter(c=>c.source==="apps");if(s.length>1){for(let c of s)ge(c,"DUPLICATE_ID");for(let c of o.filter(d=>d.source==="skills"))ge(c,"DUPLICATE_ID");}else for(let c of o.filter(d=>d.source==="skills"))ge(c,"DUPLICATE_ID");}let r=new Map;for(let o of e){if(o.diagnostic?.code==="RESERVED_ID"||t.has(o)||o.provenance===void 0&&!n.has(o)&&i.get(o.identity?.pluginId??"")?.some(c=>c.provenance!==void 0))continue;let a=o.identity?.definitionKey;if(a===void 0)continue;let s=r.get(a)??[];s.push(o),r.set(a,s);}for(let o of r.values())if(o.length>1)for(let a of o)ge(a,"DUPLICATE_ID");return t}function fp(e,n,t){let i=new Set,r=new Set,o=new Set,a=new Set([...t.appIds,...n.productBundleReservationMetadata?.reservedAppIds??[]]),s=new Set([...t.definitionIds,...n.productBundleReservationMetadata?.reservedDefinitionIds??[]]);for(let l of lp(n)){for(let u of l.appIds??[])typeof u=="string"&&i.add(u);for(let u of l.definitionIds??[])typeof u=="string"&&r.add(u);for(let u of l.toolNames??[])typeof u=="string"&&o.add(u);}for(let l of e){let u=l.candidate;if(!u)continue;if(i.has(u.pluginId)||r.has(u.definitionId)){ge(l,"RESERVED_ID");continue}[u.toolNames.read,u.toolNames.action].filter(A=>A!==void 0).some(A=>o.has(A))&&ge(l,"DUPLICATE_ID");}let c=[...e.filter(l=>l.provenance!==void 0&&l.diagnostic===void 0).flatMap(l=>l.candidate?[l.candidate]:[]),...(n.productBundleReservationMetadata?.candidates??[]).filter(l=>n.productBundleReservationMetadata?.indexHash!==void 0&&l.provenance?.indexHash===n.productBundleReservationMetadata.indexHash)],d=new Set;for(let l of e){let u=l.candidate;if(!(!u||l.diagnostic||l.source!=="apps"||l.provenance!==void 0)&&e.filter(f=>f.source==="apps"&&f.identity?.pluginId===u.pluginId).length===1&&c.some(f=>f.pluginId===u.pluginId)&&!(s.has(u.definitionId)&&!c.some(f=>f.pluginId===u.pluginId&&f.definitionId===u.definitionId))&&!c.some(f=>f.pluginId!==u.pluginId&&f.definitionId===u.definitionId)&&!e.some(f=>f.identity?.pluginId!==u.pluginId&&f.identity?.definitionKey===`${u.definitionId}\0${u.version}`&&f.diagnostic?.code!=="RESERVED_ID"))try{Qo(u),d.add(l);}catch(f){ge(l,f instanceof Ne?Rr(f.code):"EXEC_DENIED");}}for(let l of e){let u=l.candidate;u&&l.provenance===void 0&&!d.has(l)&&(a.has(u.pluginId)||s.has(u.definitionId))&&ge(l,"RESERVED_ID");}return d}function yp(e){return [...e].sort((n,t)=>{let i=Ar.indexOf(n.source)-Ar.indexOf(t.source);return i!==0?i:Dn(n.relativePath,t.relativePath)})}function v(e,n,t){e.diagnostic=ot(n,e.source,e.relativePath,e.identity?.pluginId,t);}async function Pr(e,n,t){let i=Gt(t,{mode:"local"});if(!i.ok&&i.parseFailure){v(n,hr(i.rejection.code),mr(i.rejection));return}let r=Yd(i.identity);if(n.bundleIdentity===void 0)n.identity=r;else if(r?.pluginId!==n.bundleIdentity.appId||r.definitionKey!==`${n.bundleIdentity.definitionId}\0${String(n.bundleIdentity.version)}`){v(n,"BUNDLE_INTEGRITY");return}if(!i.ok&&i.builtinOnly){v(n,"RESERVED_ID");return}if(!i.ok){v(n,hr(i.rejection.code),mr(i.rejection));return}let o=i.manifest,a={pluginId:o.pluginId,definitionKey:`${o.definitionId}\0${String(o.version)}`};if(n.bundleIdentity===void 0&&(n.identity=a),o.actions.length>0)try{ni(o.actions.map(R=>({actionId:R.actionId,inputSchema:R.inputSchema})));}catch(R){if(R instanceof Ne){v(n,Rr(R.code));return}throw R}let s;try{s=await bn(e,n,"ui/index.html",Ye);}catch(R){v(n,Fe(ne(R),"entry"));return}if(s.byteLength>Ye){v(n,"LIMIT_EXCEEDED");return}let c;try{c=Mr(s);}catch{v(n,"ENTRY_INVALID");return}if(s.byteLength===0||c.length===0){v(n,"ENTRY_INVALID");return}let d=crypto.createHash("sha256").update(s).digest("hex");if(o.entryHash!==void 0&&o.entryHash!==d){v(n,"ENTRY_INVALID");return}let l={},u,f;if(o.initialState!==void 0){try{u=await bn(e,n,"ui/state.json",2097152);}catch(R){v(n,Fe(ne(R),"initial"));return}if(u.byteLength>2097152){v(n,"LIMIT_EXCEEDED");return}try{let R=Kd(u),F=o.dataPaths??[],B=kt(R,F);l=pe(B,0,F),ze(l);}catch{v(n,"INITIAL_STATE_INVALID");return}if(f=crypto.createHash("sha256").update(u).digest("hex"),o.initialState.hash!==void 0&&o.initialState.hash!==f){v(n,"INITIAL_STATE_INVALID");return}}let A={...o,entryHash:d,...o.initialState===void 0?{}:{initialState:{path:"ui/state.json",hash:f}}},I=cn(A),h=sp(A,s,u??new Uint8Array),T;try{T=ap(I,h);}catch(R){if(R instanceof se){v(n,qd(R));return}throw R}let G;if(n.bundleLineage!==void 0){let R=n.bundleLineage[n.bundleLineage.length-1];if(!R){v(n,"LINEAGE_INVALID");return}let{legacy:F,...B}=R.definition,{hash:te,...oe}=T;if(Z(B)!==Z(oe)){v(n,"LINEAGE_STALE");return}if(F!==void 0&&(T={...T,legacy:F}),F!==void 0)try{T={...T,hash:re(T)},le(T);}catch{v(n,"LINEAGE_INVALID");return}G=n.bundleLineage;}if(n.bundleIdentity!==void 0&&n.bundleIdentity.appId!==o.pluginId){v(n,"BUNDLE_INTEGRITY");return}if(n.bundleIdentity!==void 0&&(n.bundleIdentity.definitionId!==T.id||n.bundleIdentity.version!==T.version||n.bundleIdentity.definitionHash!==T.hash)){v(n,"LINEAGE_STALE");return}let j=await tp(e,n,i.mcpb?.icon),b=hi(o.pluginId),U=o.actions.length===0?{read:b.read}:b,$=Ve(I),N=Ve(A),M=Ve(T),S=Ve({...I.handlers}),y=_r(s),m=u===void 0?void 0:_r(u),D=Object.freeze({...n.provenance===void 0?{}:{provenance:n.provenance},entry:Object.freeze({path:"ui/index.html",hash:d,bytes:y}),...m===void 0?{}:{initialState:Object.freeze({path:"ui/state.json",hash:f,bytes:m})}}),O={appId:o.pluginId,pluginId:o.pluginId,definitionId:o.definitionId,version:o.version,...i.releaseVersion===void 0?{}:{releaseVersion:i.releaseVersion},manifestFile:i.file,...i.mcpb===void 0?{}:{mcpb:Ve(i.mcpb)},relativePath:n.relativePath,manifest:N,normalized:$,name:o.name,description:o.description,...o.icon===void 0?{}:{icon:o.icon},...o.tone===void 0?{}:{tone:o.tone},...j.iconFile===void 0?{}:{iconFile:Object.freeze({...j.iconFile})},...j.iconDiagnostics.length===0?{}:{iconDiagnostics:Object.freeze([...j.iconDiagnostics])},definition:M,handlers:S,resources:D,html:c,entryBytes:y,entryHash:d,initialState:Ve(l),...m===void 0?{}:{initialStateBytes:m},...f===void 0?{}:{initialStateHash:f},sourceHash:h,toolNames:Object.freeze(U)},k=n.provenance===void 0?{...O,source:n.source}:{...O,provenance:n.provenance,lineage:G??[]};n.candidate=Object.freeze(k),cp(o,T.usage)&&v(n,"EXEC_DENIED");}async function xr(e,n){let t={};for(let i of fe)try{t[i]=await bn(e,n,i,262144);}catch(r){if(ne(r)==="NOT_FOUND")continue;return {files:t,failure:Fe(ne(r),"manifest")}}if(t[K]!==void 0)try{t[Y]=await bn(e,n,Y,262144);}catch(i){if(ne(i)!=="NOT_FOUND")return {files:t,failure:Fe(ne(i),"manifest")}}return {files:t}}function mi(e){return fe.some(n=>e[n]!==void 0)}async function Ap(e,n){let{files:t,failure:i}=await xr(e,n);if(i!==void 0){v(n,i);return}let r=t[K];return r!==void 0&&!zt(r)&&(delete t[K],delete t[Y]),mi(t)?t:void 0}function Ip(e,n,t,i=Fd,r=false,o=new Set){let a=yp(e),s=up(a,o),c=Object.freeze(a.filter(f=>f.candidate!==void 0&&f.diagnostic===void 0&&!s.has(f)).map(f=>f.candidate)),d=Object.freeze(a.filter(f=>f.diagnostic!==void 0).map(f=>f.diagnostic)),l=r?Object.freeze({...t===void 0?{}:{indexHash:t},candidates:Object.freeze(a.filter(f=>f.source==="bundled"&&f.diagnostic===void 0&&t!==void 0&&f.candidate?.provenance?.indexHash===t).map(f=>f.candidate)),diagnostics:Object.freeze(d.filter(f=>f.source==="bundled").map(f=>Object.freeze({...f}))),reservedAppIds:Object.freeze([...i.appIds]),reservedDefinitionIds:Object.freeze([...i.definitionIds])}):void 0,u={apps:c,diagnostics:d,complete:n===void 0,...n===void 0?{}:{incompleteReason:n},...t===void 0?{}:{productBundleIndexHash:t},...l===void 0?{}:{productBundleSnapshotMetadata:l}};return Object.defineProperty(u,"candidates",{configurable:false,enumerable:false,get:()=>c}),Object.freeze(u)}function gp(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 mp(e,n){if(gp(e))return {fs:e,options:n??{}};let t=e??n??{};return {fs:t.filesystem??t.fileSystem??t.fs??tt,options:t}}async function _i(e,n,t){if(typeof e!="string"||e.length===0)throw new TypeError("workspaceRoot must be explicit");let{fs:i,options:r}=mp(n,t),o=r.clock??np,a=o(),s=await yr(r.productBundle,i,a,o),c=o(),d=BigInt(Date.now())*1000000n,l=[],u=0,f,A=false,I,h;if(r.scanCache!==void 0&&typeof i.getRootIdentity=="function"&&typeof i.fingerprintVerifiedFile=="function")try{h=await i.getRootIdentity(e),I=tr(r.scanCache,h),I.scanStartedAtNs=d;}catch(N){if(ne(N)!=="NOT_FOUND")throw N}let T=I!==void 0&&r.productBundle===void 0&&s.packages.length===0&&s.diagnostics.length===0,G=new Set,j=true;l.push(...s.diagnostics.map(N=>({source:N.source,root:r.productBundle?.root??e,name:"",relativePath:N.relativePath,diagnostic:N})));let b=s.reservedIds;s.incomplete&&(f="time_limit");for(let N of s.packages){if(!Oe(c,o)){A=true,f="time_limit";break}let M=N.indexEntry,S=M.packageDir,y=N.files===void 0?void 0:Qd(S,N.files),m=s.indexHash===void 0?void 0:Mo(Object.freeze({kind:"bundled",launcher:M.launcher!==false,indexHash:s.indexHash,packageDir:S,appId:M.appId,definitionId:M.definition.id,version:M.definition.version,definitionHash:M.definition.hash,files:M.files}),y),D={source:"bundled",root:r.productBundle?.root??e,name:S.slice(5),relativePath:S,...m===void 0?{}:{provenance:m},...N.files===void 0?{}:{pinnedFiles:N.files},...N.lineage===void 0?{}:{bundleLineage:N.lineage},bundleIdentity:{appId:M.appId,definitionId:M.definition.id,version:M.definition.version,definitionHash:M.definition.hash},identity:Zd(M)};if(l.push(D),u+=1,N.failureCode!==void 0){v(D,N.failureCode);continue}if(N.files?.has(Y)===true){v(D,"EXEC_DENIED",{reason:{path:"",rule:"bundled-tool-mode-unsupported",file:Y}});continue}let O={};for(let k of fe){let R=N.files?.get(k);R!==void 0&&(O[k]=R);}if(!mi(O)){v(D,"BUNDLE_INTEGRITY");continue}if(await Pr(i,D,O),!Oe(c,o)){A=true,f="time_limit";break}}let U=[{source:"apps",directory:"apps"},{source:"skills",directory:"skills"}];e:for(let N of U){let{source:M,directory:S}=N,y;try{y=await pp(i,e,S);}catch(D){if(ne(D)==="NOT_FOUND")continue;T=false,j=false,l.push({source:M,root:e,name:"",relativePath:M,diagnostic:ot(Fe(ne(D),"manifest"),M,M)});continue}let m=y.filter(D=>D.kind==="directory"||D.kind==="symlink").filter(D=>Wd(D.name)).map(D=>({source:M,root:e,name:D.name,relativePath:$d(M,D.name)})).sort((D,O)=>Dn(D.relativePath,O.relativePath));for(let D of m){let O={...D};if(l.push(O),h!==void 0?G.add(Ur(h,O)):T=false,!Oe(c,o)){A=true,f="time_limit";break e}let k;if(I!==void 0&&h!==void 0){try{let B=await rp(i,e,h,O,I,d,c,o);if(B.timeLimitReached){A=!0,f="time_limit";break e}O.scanContext=B.context,k=B.memo;}catch(B){T=false,v(O,Fe(ne(B),"manifest"));continue}k===void 0&&(T=false);}if(k!==void 0){if(O.candidate=k.candidate,O.diagnostic=k.diagnostic,O.identity=k.identity,M==="skills"&&k.candidate===void 0&&k.diagnostic===void 0)continue;if(u>=64){v(O,"LIMIT_EXCEEDED");continue}if(D.relativePath.split("/").length-1>2){v(O,"LIMIT_EXCEEDED");continue}if(u+=1,!Oe(c,o)){A=true,f="time_limit";break e}continue}let R;if(M==="skills"&&(R=await Ap(i,O),R===void 0)){O.diagnostic===void 0&&gi(O);continue}if(u>=64){v(O,"LIMIT_EXCEEDED");continue}if(D.relativePath.split("/").length-1>2){v(O,"LIMIT_EXCEEDED");continue}if(!Oe(c,o)){A=true,f="time_limit";break e}if(u+=1,R===void 0){let B=await xr(i,O);if(B.failure!==void 0||!mi(B.files)){v(O,B.failure??Fe("NOT_FOUND","manifest")),gi(O);continue}R=B.files;}if(await Pr(i,O,R),gi(O),!Oe(c,o)){A=true,f="time_limit";break e}}}if(I!==void 0&&h!==void 0){let N=[...G].sort(Dn),M=I.lastCandidateKeys,S=M!==void 0&&M.length===N.length&&M.every((m,D)=>m===N[D]);if(T=T&&S,j&&!A&&f===void 0)for(let m of I.candidates.keys())try{JSON.parse(m)[0]===h.realPath&&!G.has(m)&&I.candidates.delete(m);}catch{I.candidates.delete(m);}let y=[...I.candidates.keys()].filter(m=>{try{return JSON.parse(m)[0]===h.realPath}catch{return false}});T=T&&y.length===G.size&&y.every(m=>G.has(m))&&!A&&f===void 0,I.lastCandidateScanUnchanged=T,j&&!A&&f===void 0&&(I.lastCandidateKeys=Object.freeze(N));}A&&l.push({source:"apps",root:e,name:"",relativePath:"apps",diagnostic:ot("DISCOVERY_TIME_LIMIT","apps","apps")});let $=fp(l,r,b);return Ip(l,f,s.indexHash,b,r.productBundle!==void 0,$)}var Fd,en,Hd,zd,Ar,Jd,Er,op,Tr,hp,_p,vr=C(()=>{g();we();Pn();be();Do();Xt();Ce();qn();er();$n();zn();ir();pi();Gn();Ii();Ii();Fd=Tn([]);en="crewx_local_app_",Hd=en,zd=en;Ar=["bundled","apps","skills"],Jd=new TextDecoder("utf-8",{fatal:true});Er=["","/ui"],op=["/dist"],Tr=2000000000n;hp=_i,_p=_i;});g();var Vr="SKILL.md",bp=/^---\s*\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;function Fr(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function Pp(e){return e.isDirectory()||e.isSymbolicLink()}function zr(e){try{return fs$1.existsSync(e)&&fs$1.statSync(e).isDirectory()}catch{return false}}var Sp=["index.js","main.js"];function Bf(e,n){let t=path.join(e,"package.json");if(fs$1.existsSync(t))try{let r=JSON.parse(fs$1.readFileSync(t,"utf8"));if(r.bin){let o=typeof r.bin=="string"?r.bin:Object.values(r.bin).find(a=>typeof a=="string");if(o){let a=path.resolve(e,o);if(fs$1.existsSync(a))return a}}if(typeof r.main=="string"){let o=path.resolve(e,r.main);if(fs$1.existsSync(o))return o}}catch{}let i=path.resolve(e,`${n}.js`);if(fs$1.existsSync(i))return i;for(let r of Sp){let o=path.resolve(e,r);if(fs$1.existsSync(o))return o}}function Mp(e){let n;try{n=fs$1.readFileSync(e,"utf8");}catch{return {frontmatter:{},readable:false,valid:false,hasFrontmatter:false}}let t=n.match(bp);if(!t)return {frontmatter:{},readable:true,valid:true,hasFrontmatter:false};try{let i=jsYaml.load(t[1]??"");if(!Fr(i))return {frontmatter:{},readable:!0,valid:!1,hasFrontmatter:!0};let r=Fr(i.metadata)?i.metadata:void 0;return {frontmatter:{...typeof i.name=="string"?{name:i.name}:{},...typeof(r?.version??i.version)=="string"?{version:r?.version??i.version}:{},...typeof i.description=="string"?{description:i.description}:{}},readable:!0,valid:!0,hasFrontmatter:!0}}catch{return {frontmatter:{},readable:true,valid:false,hasFrontmatter:true}}}function Op(e){return [path.join(e,Vr),path.join(e,"skill",Vr)]}function st(e,n){if(!zr(e))return null;for(let t of Op(e)){if(!fs$1.existsSync(t))continue;let r=Mp(t).frontmatter;return {name:r.name??n,...r.version===void 0?{}:{version:r.version},...r.description===void 0?{}:{description:r.description},skillMdPath:t,dir:e}}return null}function Ei(e){try{return fs$1.readdirSync(e,{withFileTypes:!0}).filter(Pp)}catch{return []}}function Lp(e){return e.length===0||/[\\\u0000]/.test(e)?false:e.split("/").every(n=>n.length>0&&n!=="."&&n!=="..")}function Br(e,n,t){!e||n.has(e.name)||(n.add(e.name),t.push(e));}function at(e){let n=[],t=new Set;for(let i of e)if(zr(i))for(let r of Ei(i)){if(r.name.startsWith("@")){let o=path.join(i,r.name);for(let a of Ei(o))Br(st(path.join(o,a.name),a.name),t,n);continue}Br(st(path.join(i,r.name),r.name),t,n);}return n.sort((i,r)=>i.name.localeCompare(r.name))}function Rp(e,n){if(!Lp(e))throw new Error(`Skill not found: ${e}`);for(let i of n){let r=st(path.join(i,e),e);if(r)return r;for(let o of Ei(i)){if(!o.name.startsWith("@"))continue;let a=st(path.join(i,o.name,e),e);if(a)return a}}let t=at(n).find(i=>i.name===e);if(t)return t;throw new Error(`Skill not found: ${e}`)}async function Hf(e){if(!e||e.root===null)return {skills:[],diagnostics:[]};let{discoverWorkspaceApps:n}=await Promise.resolve().then(()=>(vr(),jr)),t=await n(e.root,{productBundle:e}),i=[],r=new Set;for(let o of t.apps){let a=o.provenance?.kind==="bundled"?o.provenance.packageDir:void 0;if(!a)continue;let s=path.join(e.root,...a.split("/"));for(let c of at([path.dirname(s)]))path.resolve(c.dir)!==path.resolve(s)||r.has(c.name)||(r.add(c.name),i.push(c));for(let c of [path.join(s,"skill"),path.join(s,"skills")])for(let d of at([c]))r.has(d.name)||(r.add(d.name),i.push(d));}return {skills:i.sort((o,a)=>o.name.localeCompare(a.name)),diagnostics:t.diagnostics.filter(o=>o.source==="bundled")}}var zf=at,Gf=Rp;
2
+ exports.discover=at;exports.discoverBundledProductSkills=Hf;exports.discoverSkills=zf;exports.findEntrypoint=Bf;exports.readSkillFrontmatter=Mp;exports.resolve=Rp;exports.resolveSkill=Gf;