@crewx/sdk 0.9.0-rc.170 → 0.9.0-rc.171

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 k=(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=k(()=>{});var R,bn=k(()=>{g();R=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 R("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,Ee=k(()=>{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=k(()=>{g();Pn=["text/plain","application/json"];});var Ti=k(()=>{g();ut();});function ze(e){return Yr.has(e)||qr.test(e)||Zr.test(e)}var Ei,Yr,qr,Zr,Sn,nn,Ie,ft,yt,At,It,gt,Ue=k(()=>{g();Ei=["__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(Ei),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_]+)*$/,Ie=/^[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=k(()=>{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=k(()=>{g();Ti();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,Tt=k(()=>{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 kn(e){return ts.includes(e)}var Un,bi,ts,Et=k(()=>{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.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.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 R("DEFINITION_UNSUPPORTED","UI definition is invalid");if(e.sourceHash!==void 0&&(typeof e.sourceHash!="string"||!os.test(e.sourceHash)))throw new R("DEFINITION_UNSUPPORTED","UI definition source hash is invalid");if(!/^[0-9a-f]{64}$/.test(e.hash)||ie(e)!==e.hash)throw new R("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 R("DEFINITION_UNSUPPORTED","UI action declaration is invalid");if(t.confirmation!==void 0&&t.confirmation!=="none"&&t.confirmation!=="native")throw new R("DEFINITION_UNSUPPORTED","UI action confirmation is invalid");if(t.inputKeys&&(!Array.isArray(t.inputKeys)||t.inputKeys.some(i=>typeof i!="string"||!i)))throw new R("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 R("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 R("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 R("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 R("DEFINITION_UNSUPPORTED","UI action job control declaration is invalid");if(t.content!==void 0&&!Mn(t.content))throw new R("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 R("DEFINITION_UNSUPPORTED","UI action environment declaration is invalid")}if(e.renderer!==void 0&&(!e.renderer||e.renderer.length>128))throw new R("DEFINITION_UNSUPPORTED","UI definition renderer is invalid");if(e.surfaces&&(!Array.isArray(e.surfaces)||e.surfaces.some(n=>!n||n.length>64)))throw new R("DEFINITION_UNSUPPORTED","UI definition surfaces are invalid");if(e.usage!==void 0&&e.usage!=="card"&&e.usage!=="window")throw new R("DEFINITION_UNSUPPORTED","UI definition usage is invalid");if(e.detailPanel!==void 0&&typeof e.detailPanel!="boolean")throw new R("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 R("DEFINITION_UNSUPPORTED","UI definition displayModes are invalid");if(e.usage==="card"&&e.displayModes!==void 0)throw new R("DEFINITION_UNSUPPORTED","Card definitions cannot declare displayModes");if(e.usage==="window"&&e.detailPanel!==void 0)throw new R("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 R("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 R("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 R("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 R("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 R("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 R("DEFINITION_UNSUPPORTED","UI legacy agent access is invalid");if(e.legacy.actionTool!==void 0&&(!i||Object.keys(i).length===0))throw new R("DEFINITION_UNSUPPORTED","UI legacy action tool requires its complete agent access map")}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 R("DEFINITION_UNSUPPORTED","UI definition dataPaths are invalid")}}function rs(e,n){if(!e||typeof e!="object"||Array.isArray(e))throw new R("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 R("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 R("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 R("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=k(()=>{g();Ee();bn();_t();Tt();Et();os=/^[0-9a-f]{64}$/;});var Pi=k(()=>{g();Ee();});var Y,De,bt=k(()=>{g();Y="dist/tools.json",De="dist/main.mjs";});var tn,Si=k(()=>{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=k(()=>{g();as=["CREWX_APP_INSTANCE_ID","CREWX_THREAD_ID"];});function F(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))&&F("CSP_ORIGIN_INVALID"),t.value}function wn(e,n){if(!Object.prototype.hasOwnProperty.call(e,n))return [];let t=_s(e,n);Array.isArray(t)||F("CSP_ORIGIN_INVALID"),Reflect.ownKeys(t).some(o=>typeof o!="string"||o!=="length"&&!/^(?:0|[1-9][0-9]*)$/.test(o))&&F("CSP_ORIGIN_INVALID");let r=[];for(let o=0;o<t.length;o+=1)(!Object.prototype.hasOwnProperty.call(t,o)||typeof t[o]!="string")&&F("CSP_ORIGIN_INVALID"),r.push(t[o]);return Object.keys(t).length!==t.length&&F("CSP_ORIGIN_INVALID"),r}function Ts(e){let n;try{n=JSON.stringify(e);}catch{F("CSP_ORIGIN_INVALID");}return n===void 0&&F("CSP_ORIGIN_INVALID"),new TextEncoder().encode(n).byteLength}function Ui(e,n){/\s|\\/u.test(e)&&F("CSP_ORIGIN_INVALID");let t=ys.exec(e);t||F("CSP_ORIGIN_INVALID");let i=t[1].toLowerCase(),r=t[2];(r.includes("@")||r.includes("%")||r.includes("*"))&&F("CSP_ORIGIN_INVALID"),(r.startsWith("[")?As:Is).test(r)||F("CSP_ORIGIN_INVALID"),i==="wss"&&n!=="connectDomains"&&F("CSP_ORIGIN_INVALID");let a;try{a=new URL(e);}catch{F("CSP_ORIGIN_INVALID");}(a.protocol!==`${i}:`||a.username!==""||a.password!==""||a.search!==""||a.hash!=="")&&F("CSP_ORIGIN_INVALID");let s=a.hostname.toLowerCase();if((!s||s.includes("%"))&&F("CSP_ORIGIN_INVALID"),!s.startsWith("[")){let d=s.endsWith(".")?s.slice(0,-1):s;(d.length===0||d.length>253)&&F("CSP_ORIGIN_INVALID"),d.split(".").some(l=>l.length>63||!gs.test(l))&&F("CSP_ORIGIN_INVALID");}let c=a.origin;return (c==="null"||!c.startsWith(`${i}://`))&&F("CSP_ORIGIN_INVALID"),{origin:c,hostname:s}}function Es(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=Es(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 ki(e){return Object.freeze([...new Set(e.map(n=>n.origin))].sort())}function wi(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=wi({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)||F("CSP_ORIGIN_INVALID");let t=Reflect.ownKeys(e);t.some(A=>typeof A!="string")&&F("CSP_ORIGIN_INVALID"),t.some(A=>!us.has(A))&&F("CSP_AXIS_UNKNOWN");let i=wn(e,"connectDomains"),r=wn(e,"frameDomains"),o=wn(e,"resourceDomains"),a=wn(e,"baseUriDomains");(o.length>0||a.length>0)&&F("CSP_AXIS_UNSUPPORTED"),(Ts(e)>ds||i.length>Ri||r.length>Ri||i.length+r.length>ps||[...i,...r].some(A=>new TextEncoder().encode(A).byteLength>ls))&&F("CSP_LIMIT_EXCEEDED");let c=i.map(A=>Ui(A,"connectDomains")),d=r.map(A=>Ui(A,"frameDomains")),p=new Set((n.runtimeHostnames??[]).map(A=>A.toLowerCase().replace(/\.$/,"")));[...c,...d].some(A=>bs(A.hostname,p))&&F("CSP_ORIGIN_FORBIDDEN");let l={declared:true,connectDomains:ki(c),frameDomains:ki(d)},f=wi(l);return Object.freeze({...l,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=k(()=>{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 u(e,n=e,t,i){throw new oe(e,n,t,i)}function V(e,n){try{return n()}catch(t){throw t instanceof oe?t.withPathPrefix(e):t}}function B(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 L(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function ta(e,n){let t={};for(let[i,r]of Object.entries(e))i!==n&&(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&&u("MANIFEST_INVALID","MANIFEST_INVALID",r,"unknown-key");let o=n.find(a=>!L(e,a));o!==void 0&&u("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)&&u("UNSAFE_VALUE","UNSAFE_VALUE",o,"unsafe-value");return}if(!(e===null||typeof e!="object")){(t>8||n.has(e))&&u("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}B(e)||u("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 ge(e,n){let t=e[n];return typeof t!="string"&&u("MANIFEST_INVALID"),t}function le(e,n,t){let i=e[n];return (!Number.isSafeInteger(i)||i<t)&&u("MANIFEST_INVALID"),i}function St(e){return Ms.test(e)||u("MANIFEST_INVALID"),e}function Je(e){return Ss.test(e)||u("TOKEN_INVALID"),e}function ia(e){return Xi.test(e)||u("MANIFEST_INVALID"),e}function oa(e){B(e)||u("MANIFEST_INVALID");let n={};for(let[t,i]of Object.entries(e)){let r=ia(t);B(i)||u("MANIFEST_INVALID");let o=i.type;if(o==="text"){J(i,["type","maxLength"]),n[r]={type:o,maxLength:le(i,"maxLength",1)};continue}if(o==="text-list"){J(i,["type","max","itemMaxLength"]),n[r]={type:o,max:le(i,"max",0),itemMaxLength:le(i,"itemMaxLength",1)};continue}if(o==="step-list"){J(i,["type","min","max","labelMaxLength","detailMaxLength"]);let a=le(i,"min",0),s=le(i,"max",1);a>s&&u("MANIFEST_INVALID"),n[r]={type:o,min:a,max:s,labelMaxLength:le(i,"labelMaxLength",1),detailMaxLength:le(i,"detailMaxLength",1)};continue}typeof o=="string"&&u("SCHEMA_TYPE_UNSUPPORTED"),u("MANIFEST_INVALID");}return n}function ra(e,n,t){let i=e[n];(!i||i.type!==t)&&u("MANIFEST_INVALID");}function xn(e,n,t){let i=ge(e,"field");return Xi.test(i)||u("MANIFEST_INVALID"),ra(n,i,t),i}function sa(e,n){B(e)||u("MANIFEST_INVALID");let t=e.primitive;switch(typeof t!="string"&&u("MANIFEST_INVALID"),na.includes(t)||u("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(ge(e,"badgeToken")),noticeToken:Je(ge(e,"noticeToken"))};case "heading":return J(e,["primitive","field"]),{primitive:t,field:xn(e,n,"text")};case "labeled-text":return J(e,["primitive","titleToken","field","variant"]),e.variant!=="callout"&&u("MANIFEST_INVALID"),{primitive:t,titleToken:Je(ge(e,"titleToken")),field:xn(e,n,"text"),variant:"callout"};case "step-flow":return J(e,["primitive","titleToken","field"]),{primitive:t,titleToken:Je(ge(e,"titleToken")),field:xn(e,n,"step-list")};case "text-list":{J(e,["primitive","titleToken","field"],["emptyToken","hideWhenEmpty"]);let i={primitive:t,titleToken:Je(ge(e,"titleToken")),field:xn(e,n,"text-list")};return L(e,"emptyToken")&&(i.emptyToken=Je(ge(e,"emptyToken"))),L(e,"hideWhenEmpty")&&(typeof e.hideWhenEmpty!="boolean"&&u("MANIFEST_INVALID"),i.hideWhenEmpty=e.hideWhenEmpty),i}}return u("MANIFEST_INVALID")}function aa(e,n){return Array.isArray(e)||u("MANIFEST_INVALID"),e.map(t=>sa(t,n))}function $(e="v2 manifest exceeds a contract limit",n,t){return u("LIMIT_EXCEEDED",e,n,t)}function de(e="initial state is not projection-safe"){return u("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))&&u("MANIFEST_INVALID",`${n} is invalid`),(Vn(e,true,true)||Cs.test(e)||ks.test(e)||ws.test(e))&&u("UNSAFE_VALUE",`${n} contains an unsafe value`),e}function Mt(e,n){return (typeof e!="string"||!Ie.test(e))&&u("MANIFEST_INVALID",`${n} is invalid`),e}function ca(e){return (typeof e!="string"||!ft.test(e)||e==="*"||e==="all")&&u("MANIFEST_INVALID","action capability is invalid"),e}function Ki(e){return (typeof e!="string"||!qs.test(e))&&u("MANIFEST_INVALID","resource hash is invalid"),e}function Ot(e,n=new Set,t=0,i=""){if(typeof e=="string"){e.length>4096&&$("v2 manifest string is too long",i,"string-too-long");return}if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){Number.isFinite(e)||u("MANIFEST_INVALID","v2 manifest contains a non-finite number",i,"non-finite-number");return}(e===void 0||typeof e=="function"||typeof e=="bigint")&&u("MANIFEST_INVALID","v2 manifest contains a non-JSON value",i,"non-json-value"),typeof e!="object"&&u("MANIFEST_INVALID","MANIFEST_INVALID",i),t>8&&$("v2 manifest nesting is too deep",i,"too-deep"),n.has(e)&&u("MANIFEST_INVALID","v2 manifest contains a cycle",i,"cycle"),n.add(e);try{if(Array.isArray(e)){e.length>128&&$("v2 manifest array is too long",i,"array-too-long"),e.forEach((r,o)=>Ot(r,n,t+1,rn(i,`[${o}]`)));return}B(e)||u("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&&$("projection path is too long"),u("MANIFEST_INVALID","projection paths must be canonical exact paths")),e.split(".").some(t=>ze(t))&&u("MANIFEST_INVALID","projection paths cannot address reserved state keys"),e}function Lt(e){B(e)||u("MANIFEST_INVALID","projection policy must be an object"),J(e,["allow"]),Array.isArray(e.allow)||u("MANIFEST_INVALID","projection allow must be an array"),e.allow.length>128&&$("projection allowlist is too long");let n=[],t=new Set;for(let i of e.allow){let r=Yi(i);t.has(r)&&u("MANIFEST_INVALID","projection allowlist contains a duplicate path"),t.add(r),n.push(r);}return {allow:n}}function da(e,n){if(e===void 0)return;Array.isArray(e)||u("MANIFEST_INVALID","dataPaths must be an array"),e.length>ea&&$("dataPaths exceed the v2 limit");let t=[],i=new Set;for(let r of e){let o=Yi(r);i.has(o)&&u("MANIFEST_INVALID","dataPaths contain a duplicate path"),n.some(a=>Be(o,a))||u("MANIFEST_INVALID","dataPaths must be projection-allowed"),i.add(o),t.push(o);}return t}function Ge(e,n,t=Number.MAX_SAFE_INTEGER){return (!Number.isSafeInteger(e)||e<0||e>t)&&u("MANIFEST_INVALID",`${n} is invalid`),e}function Bi(e,n){return (typeof e!="number"||!Number.isFinite(e))&&u("MANIFEST_INVALID",`${n} is invalid`),e}function Rt(e,n=0,t=new Set){if(typeof e=="string")return (e.length>4096||Vn(e))&&u("UNSAFE_VALUE","schema enum contains an unsafe string"),e;if(e===null||typeof e=="boolean")return e;if(typeof e=="number")return Number.isFinite(e)||u("MANIFEST_INVALID","schema enum contains a non-finite number"),e;(n>8||typeof e!="object"||e===void 0)&&$("schema enum is too deep"),t.has(e)&&u("MANIFEST_INVALID","schema enum contains a cycle"),t.add(e);try{if(Array.isArray(e))return e.length>128&&$("schema enum array is too long"),e.map(r=>Rt(r,n+1,t));B(e)||u("MANIFEST_INVALID","schema enum contains a non-plain object");let i={};for(let[r,o]of Object.entries(e))ze(r)&&u("MANIFEST_INVALID","schema enum contains a reserved key"),i[r]=Rt(o,n+1,t);return i}finally{t.delete(e);}}function pa(e,n){if(e===void 0)return;Array.isArray(e)||u("MANIFEST_INVALID","schema required must be an array"),e.length>64&&$("schema required list is too long");let t=[],i=new Set;for(let r of e)(typeof r!="string"||!nn.test(r))&&u("MANIFEST_INVALID","schema required contains an invalid key"),r.length>4096&&$("schema required key is too long"),i.has(r)&&u("MANIFEST_INVALID","schema required contains a duplicate key"),n&&!Object.prototype.hasOwnProperty.call(n,r)&&u("MANIFEST_INVALID","schema required references an undeclared property"),i.add(r),t.push(r);return t}function la(e,n){let t=n?nn:Sn;return e.length>4096&&$("schema property name is too long"),(!t.test(e)||e.split(".").some(i=>ze(i)))&&u("MANIFEST_INVALID","schema property name is invalid"),e}function Ut(e,n=0,t=false){B(e)||u("MANIFEST_INVALID","action inputSchema must be an object"),n>8&&$("action inputSchema is too deep");let i=e.type;i!=="object"&&i!=="string"&&i!=="number"&&i!=="integer"&&i!=="boolean"&&i!=="array"&&i!=="null"&&(typeof i=="string"&&u("SCHEMA_TYPE_UNSUPPORTED","action inputSchema type is unsupported"),u("MANIFEST_INVALID","action inputSchema type is required"));let 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(L(e,"enum")&&(Array.isArray(e.enum)||u("MANIFEST_INVALID","schema enum must be an array"),e.enum.length>128&&$("schema enum is too long"),o.enum=e.enum.map(s=>Rt(s))),i==="string"&&(L(e,"minLength")&&(o.minLength=Ge(e.minLength,"schema minLength",4096)),L(e,"maxLength")&&(o.maxLength=Ge(e.maxLength,"schema maxLength",4096)),o.minLength!==void 0&&o.maxLength!==void 0&&o.minLength>o.maxLength&&u("MANIFEST_INVALID","schema string length bounds are inverted")),(i==="number"||i==="integer")&&(L(e,"minimum")&&(o.minimum=Bi(e.minimum,"schema minimum")),L(e,"maximum")&&(o.maximum=Bi(e.maximum,"schema maximum")),o.minimum!==void 0&&o.maximum!==void 0&&o.minimum>o.maximum&&u("MANIFEST_INVALID","schema numeric bounds are inverted")),i==="array"&&(L(e,"minItems")&&(o.minItems=Ge(e.minItems,"schema minItems",128)),L(e,"maxItems")&&(o.maxItems=Ge(e.maxItems,"schema maxItems",128)),o.minItems!==void 0&&o.maxItems!==void 0&&o.minItems>o.maxItems&&u("MANIFEST_INVALID","schema array length bounds are inverted"),L(e,"items")&&(o.items=Ut(e.items,n+1,false))),i==="object"){let s;if(L(e,"properties")){B(e.properties)||u("MANIFEST_INVALID","schema properties must be an object");let d=Object.entries(e.properties);d.length>64&&$("schema properties are too many"),s={};for(let[p,l]of d){let f=la(p,t);s[f]=Ut(l,n+1,false);}o.properties=s;}L(e,"minProperties")&&(o.minProperties=Ge(e.minProperties,"schema minProperties",64)),L(e,"maxProperties")&&(o.maxProperties=Ge(e.maxProperties,"schema maxProperties",64)),o.minProperties!==void 0&&o.maxProperties!==void 0&&o.minProperties>o.maxProperties&&u("MANIFEST_INVALID","schema object property bounds are inverted");let c=pa(e.required,s);c!==void 0&&(o.required=c),L(e,"additionalProperties")&&(e.additionalProperties!==false&&u("MANIFEST_INVALID","schema additionalProperties must be false"),o.additionalProperties=false);}let a=JSON.stringify(o);return (a===void 0||Buffer.byteLength(a,"utf8")>2097152)&&$("action inputSchema subtree is too large"),o}function ua(e){let n=Ut(e,0,true);return (n.type!=="object"||!n.properties)&&u("MANIFEST_INVALID","action inputSchema must declare object properties"),n}function fa(e){if(B(e)||u("MANIFEST_INVALID","action backend must be an object"),e.type==="core"){J(e,Gs);let n=e.handler;return (typeof n!="string"||!yt.test(n))&&u("MANIFEST_INVALID","core backend handler is invalid"),{type:"core",handler:n}}if(e.type==="skill"&&L(e,"entry"))return J(e,Xs),e.entry!==De&&u("MANIFEST_INVALID",`skill backend entry must be ${De}`),{type:"skill",entry:De};if(e.type==="skill"){J(e,$s,Ws),(!Array.isArray(e.command)||e.command.length===0||e.command.length>16)&&u("MANIFEST_INVALID","skill backend command is invalid");let n=[];for(let i of e.command)(typeof i!="string"||i.length===0||i.length>256||!At.test(i))&&u("MANIFEST_INVALID","skill backend command token is invalid"),n.push(i);let t=L(e,"env")?ma(e.env):void 0;return {type:"skill",command:n,...t===void 0?{}:{env:t}}}u("MANIFEST_INVALID","action backend type is unsupported");}function ya(e){B(e)||u("MANIFEST_INVALID","action must be an object"),J(e,Vs,Fs),L(e,"_meta")&&V("_meta",()=>qi(e._meta));let n=V("actionId",()=>Mt(e.actionId,"actionId"));pt(n)&&u("MANIFEST_INVALID",`actionId "${n}" is not projection-safe`,"actionId");let t=V("capability",()=>ca(e.capability)),i=e.mutation;typeof i!="boolean"&&u("MANIFEST_INVALID","action mutation must be boolean","mutation");let r=V("inputSchema",()=>ua(e.inputSchema)),o;if(L(e,"dataInputs")){Array.isArray(e.dataInputs)||u("MANIFEST_INVALID","action dataInputs must be an array","dataInputs");let A=r.properties,I=new Set,_=[];for(let D of e.dataInputs)(typeof D!="string"||!L(A,D)||I.has(D))&&u("MANIFEST_INVALID","action dataInputs must be unique declared properties","dataInputs"),I.add(D),_.push(D);o=_;}let a=V("resultProjection",()=>Lt(e.resultProjection)),s=V("backend",()=>fa(e.backend)),c;L(e,"content")&&((s.type!=="skill"||!Mn(e.content))&&u("MANIFEST_INVALID","action content declaration is invalid","content"),c=ha(e.content));let d;if(L(e,"confirmation")){let A=e.confirmation;A!=="none"&&A!=="native"&&u("MANIFEST_INVALID","action confirmation is invalid","confirmation"),d=A;}let p;L(e,"schedule")&&(p=V("schedule",()=>ga(e.schedule,{backend:s,inputSchema:r,hasContent:c!==void 0,hasDataInputs:o!==void 0,confirmation:d})));let l;L(e,"job")&&(p!==void 0&&u("MANIFEST_INVALID","an action is either the scheduled run or a job, not both","job"),l=V("job",()=>Ia(e.job,{backend:s,inputSchema:r,hasContent:c!==void 0,hasDataInputs:o!==void 0,confirmation:d})));let f;return L(e,"jobAccess")&&(l!==void 0&&u("MANIFEST_INVALID","an action is either the job or a job control, not both","jobAccess"),f=V("jobAccess",()=>Aa(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},...p===void 0?{}:{schedule:p},...l===void 0?{}:{job:l},...f===void 0?{}:{jobAccess:f}}}function Aa(e,n){return (n.backend.type!=="skill"||!("entry"in n.backend)||n.backend.entry!==De)&&u("MANIFEST_INVALID","jobAccess needs a tool-mode action","jobAccess"),n.hasContent&&u("MANIFEST_INVALID","a job control action takes no content","jobAccess"),(!Array.isArray(e)||e.length===0)&&u("MANIFEST_INVALID","jobAccess must list at least one operation","jobAccess"),(new Set(e).size!==e.length||!e.every(kn))&&u("MANIFEST_INVALID","jobAccess must name each operation once: start, status or cancel","jobAccess"),Object.freeze([...e])}function Ia(e,n){(n.backend.type!=="skill"||!("entry"in n.backend)||n.backend.entry!==De)&&u("MANIFEST_INVALID","job needs a tool-mode action","job"),(n.hasContent||n.hasDataInputs||n.confirmation!==void 0&&n.confirmation!=="none")&&u("MANIFEST_INVALID","a job action takes no content, dataInputs or native confirmation","job"),(n.inputSchema.required??[]).length>0&&u("MANIFEST_INVALID","a job action input must accept {}","inputSchema.required"),B(e)||u("MANIFEST_INVALID","job must be an object","job"),J(e,[],zs);let t=L(e,"deadlineMs")?e.deadlineMs:Un.default;return Cn(t)||u("MANIFEST_INVALID","job deadlineMs is invalid","job.deadlineMs"),{deadlineMs:t}}function ga(e,n){(n.backend.type!=="skill"||!("entry"in n.backend)||n.backend.entry!==De)&&u("MANIFEST_INVALID","schedule needs a tool-mode action","schedule"),(n.hasContent||n.hasDataInputs||n.confirmation!==void 0&&n.confirmation!=="none")&&u("MANIFEST_INVALID","a scheduled action takes no content, dataInputs or native confirmation","schedule"),(n.inputSchema.required??[]).length>0&&u("MANIFEST_INVALID","a scheduled action input must accept {}","inputSchema.required"),B(e)||u("MANIFEST_INVALID","schedule must be an object","schedule"),J(e,Bs,Hs),Ln(e.everyMinutes)||u("MANIFEST_INVALID","schedule everyMinutes is invalid","schedule.everyMinutes");let t=L(e,"timeoutMs")?e.timeoutMs:On.default;return Rn(t)||u("MANIFEST_INVALID","schedule timeoutMs is invalid","schedule.timeoutMs"),{everyMinutes:e.everyMinutes,timeoutMs:t}}function ma(e){return Mi(e)||u("MANIFEST_INVALID","skill backend env is invalid"),Object.freeze([...e])}function ha(e){return Object.freeze({...e.in===void 0?{}:{in:Object.freeze({...e.in})},...e.out===void 0?{}:{out:Object.freeze({...e.out})}})}function _a(e){return B(e)||u("INITIAL_STATE_INVALID","initialState must be an object"),J(e,Ks,Ys),e.path!=="ui/state.json"&&u("MANIFEST_INVALID","initialState path is not fixed"),L(e,"hash")?{path:"ui/state.json",hash:Ki(e.hash)}:{path:"ui/state.json"}}function Ta(e){let n=["wasm","terminal","htmlDocuments"];return (!B(e)||Object.keys(e).length===0||Object.keys(e).some(t=>!n.includes(t)||e[t]!==true))&&u("MANIFEST_INVALID","runtime must contain only known capability flags set to true"),{...e.wasm===true?{wasm:true}:{},...e.terminal===true?{terminal:true}:{},...e.htmlDocuments===true?{htmlDocuments:true}:{}}}function Ea(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 u("MANIFEST_INVALID",r,void 0,r.toLowerCase().replace(/_/g,"-"))}if(t.frameDomains.length>0&&u("MANIFEST_INVALID","external origins in csp are not enabled in this rollout",void 0,"csp-not-enabled"),t.connectDomains.length!==0)return n?.terminal===true&&u("MANIFEST_INVALID","runtime.terminal cannot be combined with csp.connectDomains","connectDomains","terminal-with-connect-domains"),Object.freeze({connectDomains:t.connectDomains})}function Da(e,n){vn(B(e)&&L(e,"csp")?ta(e,"csp"):e,new Set,0,true,true),Ot(e),B(e)||u("MANIFEST_INVALID"),J(e,js,vs),L(e,"_meta")&&V("_meta",()=>qi(e._meta)),e.manifestVersion!==2&&u("MANIFEST_INVALID");let t;L(e,"runtime")&&(t=V("runtime",()=>Ta(e.runtime)));let i;L(e,"csp")&&(i=V("csp",()=>Ea(e.csp,t)));let r=V("pluginId",()=>Mt(e.pluginId,"pluginId")),o=V("definitionId",()=>Mt(e.definitionId,"definitionId")),a=V("version",()=>le(e,"version",1)),s=V("name",()=>Fi(e.name,"name")),c=V("description",()=>Fi(e.description,"description")),d;L(e,"icon")&&((typeof e.icon!="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(e.icon))&&u("MANIFEST_INVALID","icon is invalid","icon"),d=e.icon);let p;L(e,"tone")&&((typeof e.tone!="string"||!It.includes(e.tone))&&u("MANIFEST_INVALID","tone is invalid","tone"),p=e.tone),e.entry!=="ui/index.html"&&u("MANIFEST_INVALID","entry path is not fixed","entry","fixed-value");let l;L(e,"entryHash")&&(l=V("entryHash",()=>Ki(e.entryHash)));let f;L(e,"initialState")&&(f=V("initialState",()=>_a(e.initialState)));let A;L(e,"usage")&&(e.usage!=="card"&&e.usage!=="window"&&u("MANIFEST_INVALID","usage is invalid","usage"),A=e.usage);let I;L(e,"detailPanel")&&(typeof e.detailPanel!="boolean"&&u("MANIFEST_INVALID","detailPanel is invalid","detailPanel"),I=e.detailPanel);let _;if(L(e,"displayModes")){((A??tn)!==tn||!Array.isArray(e.displayModes)||e.displayModes.length===0)&&u("MANIFEST_INVALID","displayModes are only valid for window Apps","displayModes");let h=new Set(["inline","floating","focused"]);(new Set(e.displayModes).size!==e.displayModes.length||e.displayModes.some(M=>typeof M!="string"||!h.has(M)))&&u("MANIFEST_INVALID","displayModes are invalid","displayModes"),_=e.displayModes;}(A??tn)===tn&&I!==void 0&&u("MANIFEST_INVALID","detailPanel is card-only","detailPanel");let D=n.mode??"local";D!=="local"&&D!=="installed"&&D!=="published"&&u("MANIFEST_INVALID","manifest mode is invalid"),D!=="local"&&l===void 0&&u("MANIFEST_INVALID","installed manifests require entryHash","entryHash","required-when-installed"),D!=="local"&&f!==void 0&&f.hash===void 0&&u("MANIFEST_INVALID","installed manifests require initialState.hash","initialState.hash","required-when-installed"),(!Array.isArray(e.surfaces)||e.surfaces.length===0)&&u("MANIFEST_INVALID","surfaces are invalid","surfaces"),e.surfaces.length>2&&$("surfaces exceed the v2 limit","surfaces","too-many-items");let H=[],j=new Set;for(let h of e.surfaces)(typeof h!="string"||!gt.includes(h))&&u("MANIFEST_INVALID","surface is unsupported","surfaces"),j.has(h)&&u("MANIFEST_INVALID","surfaces contain a duplicate","surfaces","duplicate-item"),j.add(h),H.push(h);B(e.size)||u("MANIFEST_INVALID","size must be an object","size"),V("size",()=>J(e.size,["height"]));let b=V("size",()=>le(e.size,"height",1));b>720&&$("size.height exceeds the v2 limit","size.height","too-large");let C=V("stateProjection",()=>Lt(e.stateProjection)),G=e.summaryProjection===void 0?void 0:V("summaryProjection",()=>Lt(e.summaryProjection));G!==void 0&&G.allow.some(h=>!C.allow.includes(h))&&u("MANIFEST_INVALID","summaryProjection must be a subset of stateProjection.allow","summaryProjection");let N=V("dataPaths",()=>da(e.dataPaths,C.allow));Array.isArray(e.actions)||u("MANIFEST_INVALID","actions must be an array","actions"),e.actions.length>32&&$("actions exceed the v2 limit","actions","too-many-items");let O=[],S=new Set,y=0,m=0;for(let[h,M]of e.actions.entries()){let U=`actions[${h}]`,P=V(U,()=>ya(M));if(S.has(P.actionId)&&u("MANIFEST_INVALID","actions contain a duplicate actionId",`${U}.actionId`,"duplicate-item"),P.schedule!==void 0&&(y+=1,y>Ni&&u("MANIFEST_INVALID","an App declares at most one scheduled action",`${U}.schedule`,"duplicate-item")),P.job!==void 0&&(m+=1,m>bi&&u("MANIFEST_INVALID","an App declares at most one job action",`${U}.job`,"duplicate-item")),P.backend.type==="core"&&P.backend.handler==="state.set"){P.mutation||u("MANIFEST_INVALID","state.set actions must be mutations",`${U}.mutation`);for(let W of Object.keys(P.inputSchema.properties))C.allow.includes(W)||u("MANIFEST_INVALID","state.set input paths must be projection-allowed",`${U}.inputSchema.properties`);}S.add(P.actionId),O.push(P);}return {manifestVersion:2,pluginId:r,definitionId:o,version:a,name:s,description:c,...d===void 0?{}:{icon:d},...p===void 0?{}:{tone:p},entry:"ui/index.html",...l===void 0?{}:{entryHash:l},...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},..._===void 0?{}:{displayModes:_},surfaces:H,size:{height:b},stateProjection:C,...G===void 0?{}:{summaryProjection:G},...N===void 0?{}:{dataPaths:N},actions:O}}function qi(e){B(e)||u("MANIFEST_INVALID","_meta must be an object");let n=JSON.stringify(e);(n===void 0||Buffer.byteLength(n,"utf8")>Js)&&$("_meta exceeds the 4 KiB limit",void 0,"meta-too-large");}function Na(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},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 {B(e)||de("state contains a non-plain object");let c={};for(let[d,p]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(p,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 wt(e,n=[]){B(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 ba(e,n={}){vn(e),B(e)||u("MANIFEST_INVALID"),J(e,xs),e.manifestVersion!==1&&u("MANIFEST_INVALID");let t=St(ge(e,"pluginId")),i=St(ge(e,"definitionId")),r=le(e,"version",1),o=le(e,"primitiveSet",1),a=n.supportedPrimitiveSet??Ps;(!Number.isSafeInteger(a)||a<1)&&u("MANIFEST_INVALID"),o>a&&u("PRIMITIVE_SET_UNSUPPORTED"),B(e.activation)||u("MANIFEST_INVALID"),J(e.activation,["kind","language"]),e.activation.kind!=="fenced-code"&&u("MANIFEST_INVALID");let s=St(ge(e.activation,"language")),c=oa(e.schema),d=aa(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 Pa(e,n={}){return B(e)||u("MANIFEST_INVALID"),Object.hasOwn(e,"lineage")&&u("MANIFEST_INVALID","lineage is only allowed in product bundle indexes"),e.manifestVersion===2?Da(e,n):ba(e,n)}function sn(e,n={}){try{return Pa(e,n)}catch(t){if(t instanceof oe)throw t;return u("MANIFEST_INVALID")}}function an(e,n={}){let t=sn(e,n);return t.manifestVersion===2?Na(t):t}var Ps,Ss,Ms,Xi,Os,Ls,Rs,Us,Vi,Cs,ks,ws,xs,js,vs,Vs,Fs,Bs,Hs,zs,Js,Gs,$s,Ws,Xs,Ks,Ys,qs,Zs,Qs,ea,na,oe,xt=k(()=>{g();Si();Ee();_t();Oi();bt();Tt();Et();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,ks=/javascript:/i,ws=/(?:^[\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"],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=["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<=Ma&&Sa.test(e)}function w(e,n,t,i,r){throw new he(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["${Me}"]`;return e===void 0||e===""?n:e.startsWith("[")?`${n}${e}`:`${n}.${e}`}function Ua(e){return e.toLowerCase().replace(/_/g,"-")}function Ca(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??Ua(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&&w("LIMIT_EXCEEDED",n,"string-too-long"),(Oa.test(e)||La.test(e)||Ra.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 ue(e,n){return (typeof e!="string"||e.length===0)&&w("MANIFEST_INVALID",n,"string"),e}function We(e,n){return Q(e)||w("MANIFEST_INVALID",n,"object"),e}function ka(e,n){Array.isArray(e)||w("MANIFEST_INVALID",n,"array"),e.forEach((t,i)=>ue(t,`${n}[${i}]`));}function wa(e,n){typeof e!="boolean"&&w("MANIFEST_INVALID",n,"boolean");}function cn(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 xa(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)||w("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":ka(n,e);return;case "tools":{Array.isArray(n)||w("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)||w("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":wa(n,e);return;case "localization":case "compatibility":case "user_config":We(n,e);return;default:w("MANIFEST_INVALID",e,"unknown-key");}}function Fn(e){return typeof e=="string"&&Ie.test(e)?e:void 0}function so(e){return Number.isSafeInteger(e)&&e>=1?e:void 0}function ja(e){let n=Fn(e.name);if(n===void 0)return;let t=e._meta,i=Q(t)?t[Me]: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 va(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,Me)}catch{return false}}function Va(e,n){if(e===we)return n.builtinOnly===true;let t=n._meta,i=Q(t)?t[Me]:void 0;return Q(i)&&i.builtinOnly===true}function Fa(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}"`),io(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,Me)||w("MANIFEST_INVALID",fe(),"missing-key");let i=t[Me];Q(i)||w("MANIFEST_INVALID",fe(),"object");for(let s of Object.keys(i))vt.includes(s)||to.includes(s)||w("MANIFEST_INVALID",fe(s),"unknown-key");for(let s of vt)s==="actions"&&n!==void 0||X(i,s)||w("MANIFEST_INVALID",fe(s),"missing-key");if(n!==void 0&&X(i,"actions")&&w("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`),Ba(i.actions),X(i,"definitionVersion")){let s=i.definitionVersion;(!Number.isSafeInteger(s)||s<1)&&w("MANIFEST_INVALID",fe("definitionVersion"),"positive-integer");}let r={};for(let s of no)X(e,s)&&(xa(s,e[s]),r[s]=ro(e[s]));let o={};for(let[s,c]of Object.entries(t))s!==Me&&(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:De}}))),Object.keys(o).length>0&&(a._meta=o),{v2Input:a,...Object.keys(o).length>0?{vendorMeta:o}:{},passthrough:r}}function Ba(e){Array.isArray(e)&&e.forEach((n,t)=>{let i=Q(n)?n.backend:void 0;Q(i)&&X(i,"entry")&&w("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 Ha(e,n,t){Q(e)||w("MANIFEST_INVALID","","not-object","manifest.json must be a JSON object",K);let i;try{i=Fa(e,t);}catch(a){throw a instanceof he?new he(a.code,{...a.reason,file:K}):a}let r;try{let a=sn(i.v2Input,{mode:n.mode??"local"});a.manifestVersion!==2&&w("MANIFEST_INVALID","","v2-required"),r=a;}catch(a){throw a instanceof oe?new he(a.code,oo(a,K,Ca)):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 he("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 za(e,n){try{let t=sn(e,{mode:n.mode??"local"});if(t.manifestVersion!==2)throw new he("MANIFEST_INVALID",{path:"manifestVersion",rule:"v2-required",message:"a workspace App requires manifestVersion 2",file:we});return {file:we,manifest:t,v2Input:e}}catch(t){throw t instanceof oe?new he(t.code,oo(t,we,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 Ja(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 Ga(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 $a(e,n){let t=Ja(e,n),i=Ga(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 ${we} normalize to different definitions${r}`+(t.length>0?`; differing fields: ${t.join(", ")}`:""));}function me(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 {...me("","tools-needs-manifest-json","MANIFEST_INVALID",`${Y} is read with ${K} only`),files:e}}function Wa(e,n){if(e.byteLength>n)return {failure:me("","file-too-large","LIMIT_EXCEEDED")};let t;try{t=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e));}catch{return {failure:me("","invalid-json")}}if(!Q(t))return {failure:me("","not-object","MANIFEST_INVALID",`${Y} must be a JSON object`)};for(let r of Object.keys(t))if(r!=="schemaVersion"&&r!=="actions")return {failure:me(r,"unknown-key")};for(let r of ["schemaVersion","actions"])if(!X(t,r))return {failure:me(r,"missing-key")};if(t.schemaVersion!==1)return {failure:me("schemaVersion","unsupported-version","MANIFEST_INVALID",`schemaVersion must be ${1}`)};let i=t.actions;if(!Array.isArray(i))return {failure:me("actions","array")};for(let[r,o]of i.entries()){if(!Q(o))return {failure:me(`actions[${r}]`,"object")};if(X(o,"backend"))return {failure:me(`actions[${r}].backend`,"tools-backend","MANIFEST_INVALID",`an action in ${Y} cannot carry a backend`)}}return {actions:i}}function Xa(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}=Xa(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:Wa(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?ja(s.raw):va(s.raw),d=t.some(A=>Va(A.file,A.raw)),p;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};p=a.actions;}let l=[];try{for(let A of t)l.push(A.file===K?Ha(A.raw,n,p):za(A.raw,n));l.length===2&&$a(l[0].manifest,l[1].manifest);}catch(A){if(A instanceof he)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=l[0];return {ok:true,...f,identity:c??{pluginId:f.manifest.pluginId},files:r}}var K,we,pe,jt,Me,Bt,Ht,no,vt,to,Sa,Ma,Oa,La,Ra,he,Gt=k(()=>{g();Ce();Ee();bt();Ue();xt();K="manifest.json",we="ui-plugin.json",pe=[K,we],jt="0.3",Me="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"]),Sa=/^(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-]+)*))?$/,Ma=256,Oa=/<\/?[A-Za-z][^>]*>/,La=/^\s*javascript:/i,Ra=/data:[^,\s]*,/i;he=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(qa.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:Ka.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=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,Za)||pc(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,Qa))return {ok:false,reason:"bytes-mismatch"};let t=cc(n);return {ok:true,square:t===void 0?void 0:po(t.width,t.height)}}return nc(n)}function nc(e){let n;try{n=Ya.decode(e);}catch{return {ok:false,reason:"bytes-mismatch"}}return sc(n)?{ok:false,reason:"unsafe-svg"}:tc.test(n)?{ok:true,square:ac(n)}:{ok:false,reason:"bytes-mismatch"}}function sc(e){if(ic.some(n=>n.test(e)))return true;for(let n of e.matchAll(oc))if(!(n[1]??n[2]??n[3]??"").startsWith("#"))return true;for(let n of e.matchAll(rc))if(ao.lastIndex=n.index??0,!ao.test(e))return true;return false}function ac(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 cc(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(dc(t))return n+9>e.byteLength?void 0:{height:fo(e,n+5),width:fo(e,n+7)};n+=2+i;}}function dc(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 pc(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 Ka,Ya,qa,Za,Qa,tc,ic,oc,rc,ao,Xt=k(()=>{g();Ka=new Map([["svg","image/svg+xml"],["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"]]),Ya=new TextDecoder("utf-8",{fatal:true}),qa=/^[A-Za-z][A-Za-z0-9+.-]*:/,Za=[137,80,78,71,13,10,26,10],Qa=[255,216,255];tc=/^\s*(?:<\?[\s\S]*?\?>\s*|<!--[\s\S]*?-->\s*)*<svg(?=[\s/>])/,ic=[/<script/i,/[\s"'/]on[a-z]+\s*=/i,/<foreignobject/i,/<!doctype/i,/<!entity/i,/<(?:iframe|embed|object)\b/i,/@import/i],oc=/(?:^|[\s"'/])(?:xlink:)?href\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+))/gi,rc=/url\(/gi,ao=/url\(\s*["']?#/iy;});var mo=k(()=>{g();Pi();Gt();Xt();xt();Ue();});function E(e,n=e){throw new _e(e,n)}var _e,Hn=k(()=>{g();_e=class extends Error{constructor(t,i=t){super(i);this.code=t;}code;name="McpAppContractError"};});var ho=k(()=>{g();});var _o=k(()=>{g();Ce();Ee();Hn();ho();});function Eo(e,n){return To.add(e),n!==void 0&&lc.set(e,n),e}function Xe(e){return e!==null&&typeof e=="object"&&To.has(e)}var To,lc,zn=k(()=>{g();To=new WeakSet,lc=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 mc(e){throw new Te("LINEAGE_STALE",e)}function Po(e){if(!ln(e)||!Kt(e,yc,Ac)||!ln(e.actions))return ee("Lineage definition shape is invalid");for(let n of Object.values(e.actions))if(!ln(n)||!Kt(n,Ic,gc))return ee("Lineage action definition shape is invalid");return e}function hc(e){if(!ln(e)||!Kt(e,uc,fc))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 _c(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 Tc(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(hc),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||!Tc(a.definition,i))return mc("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 p of r)if(p.sourceHash===void 0)for(let l of Object.keys(p.definition.actions))s.has(l)&&c.add(l);let d=Object.keys(t.legacy.agentAccess??{});if(d.length!==c.size||d.some(p=>!c.has(p))){let p="S4_LEGACY_AGENT_ACCESS_COMPLETE";throw new Te("LINEAGE_INVALID",`Lineage compatibility failed: ${p}`,[p])}}for(let s=0;s<r.length-1;s+=1){if(r.slice(s,-1).some(p=>p.compat==="break"))continue;let d=_c(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,uc,fc,yc,Ac,Ic,gc,qt=k(()=>{g();Ce();Ee();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}$/,uc=["version","hash","definition"],fc=["sourceHash","compat"],yc=["id","version","actions"],Ac=["sourceHash","usage","detailPanel","displayModes","renderer","surfaces","stateProjection","dataPaths","summaryProjection","legacy"],Ic=["capabilities"],gc=["inputKeys","dataInputs","confirmation","resultProjection","content","env","schedule","job","jobAccess"];});var So,Mo,Oo,Lo,Ro=k(()=>{g();So="text/html;profile=mcp-app",Mo=["crewx_app_terminal_connect","crewx_app_html_viewer_open"],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"&&Ec.includes(e)}function Jn(e,n){return e==="card"&&n?.type==="core"&&un(n.handler)}var Ec,Gn=k(()=>{g();Ec=Object.freeze(["card.secret-env"]);});function Uo(e,n=[],t){if(e.content!==void 0||e.confirmation!=="none")return "denied";let i=Dc();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 Dc(e){return;}var Co=k(()=>{g();Ce();zn();Gn();});function Uc(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 Cc(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:Le}),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:Le}),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>Pc)&&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 _e)throw t;E("TOOL_INVALID","MCP App inputSchema must be projection-safe JSON");}}function kc(e){return (typeof e!="string"||e.trim().length===0||e.length>Sc)&&E("TOOL_INVALID","MCP App tools require a meaningful text fallback"),e}function wc(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=xc(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 p=Re(e.readToolName,"TOOL_ID_INVALID","Local App read tool name"),l=e.actionToolName===void 0?void 0:Re(e.actionToolName,"TOOL_ID_INVALID","Local App action tool name");d.length===0&&l!==void 0&&E("TOOL_INVALID","A static local App cannot register an action tool"),d.length>0&&l===void 0&&E("TOOL_INVALID","A stateful local App requires an action tool name"),l!==void 0&&l===p&&E("TOOL_ID_CONFLICT",`Local App read and action tools share a name: ${p}`);let f=Cc(e.runtime);f.some(b=>b.name===p||b.name===l)&&E("TOOL_ID_CONFLICT","Local App read or action tool conflicts with a requested Host capability");let A={name:p,description:`${t} current state`,inputSchema:Rc,textFallback:`${t} current state is available through its open instance.`,visibility:Object.freeze(["model","app"]),kind:"read",resourceBinding:Le},I=[Object.freeze(A)];if(I.push(...f.map(b=>Object.freeze(b))),l!==void 0){let b={name:l,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:Le,actionIds:Object.freeze([...d])};I.push(Object.freeze(b));}let _=[],D=new Set(I.map(b=>b.name));if(l!==void 0)for(let b of e.actions){let C=`${l}__${b.actionId}`;if(C.length>128||!xo.test(C)){_.push(Object.freeze({toolName:C,actionId:b.actionId,reason:"name_too_long"}));continue}if(D.has(C)){_.push(Object.freeze({toolName:C,actionId:b.actionId,reason:"name_collision"}));continue}let G=Uo({actionId:b.actionId,confirmation:r.actions[b.actionId]?.confirmation,content:r.actions[b.actionId]?.content,backend:b.backend},e.modelActions),N=Object.freeze([...Bc(G,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:N,kind:"action",resourceBinding:Le,actionId:b.actionId,actionIds:Object.freeze([b.actionId]),_meta:Object.freeze({ui:Object.freeze({visibility:N})})};I.push(Object.freeze(O)),D.add(C);}let H=vo(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:Go(e.icon)},...e.tone===void 0?{}:{tone:$o(e.tone)},builtinOnly:false,definition:r,...e.runtime===void 0?{}:{runtime:Object.freeze({...e.runtime})},resourceBinding:Le,resource:H,tools:Object.freeze(I),toolDiagnostics:Object.freeze(_)};return q(j)}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(jc(n,t),Vo)}function xc(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 jc(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 vc(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 Vc(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=Fc(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"),kc(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 (!Lc.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 p=Re(s.actionId,"TOOL_ID_INVALID","Local App action id");Object.prototype.hasOwnProperty.call(t.actions,p)||E("TOOL_INVALID","Local App action tool references an undeclared action");let l=wc(s._meta.ui.visibility);return JSON.stringify(l)!==JSON.stringify(s.visibility)&&E("TOOL_INVALID","Local App action metadata visibility must match the tool visibility"),q({...s,actionId:p,actionIds:Object.freeze([p]),inputSchema:c,visibility:l,_meta:{ui:{visibility:l}}})}let d=[...s.actionIds];return (d.length===0||d.some(p=>!Object.prototype.hasOwnProperty.call(t.actions,p)))&&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})},...i===void 0?{}:{provenance:i},resourceBinding:Le,resource:r,tools:Object.freeze(o),toolDiagnostics:Object.freeze([...e.toolDiagnostics??[]])});return ko.has(e)?e:(ko.add(a),a)}function Fc(e){let n=Qt(e.html),t=$n(e.entryHash,"Local App entry hash");if(Uc(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 Bc(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 Hc(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:Le,tools:e.tools})}function zc(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 _e)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 Jc(e){return e!==null&&typeof e=="object"&&typeof e.id=="string"&&Number.isSafeInteger(e.version)&&typeof e.hash=="string"}function wo(e,n,t){return `${e}\0${n}\0${t}`}function $n(e,n){return (typeof e!="string"||!bc.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"||!Mc.test(e))&&E("TOOL_INVALID","MCP App icon is invalid"),e}function $o(e){return (typeof e!="string"||!Oc.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,bc,Ke,Pc,Sc,Mc,Oc,Lc,Le,Rc,An,ko,Vo,Zt,Yn=k(()=>{g();_o();Ce();Ee();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})$/,bc=/^[0-9a-f]{64}$/,Ke=8*1024*1024,Pc=8*1024,Sc=16*1024,Mc=/^[a-z][a-z0-9-]{0,63}$/,Oc=new Set(["blue","violet","emerald","amber","rose","sky","slate","indigo"]),Lc=new Set(Mo),new Set(Oo),Le=Object.freeze({kind:"instance"}),Rc=Object.freeze({type:"object",properties:Object.freeze({}),additionalProperties:false}),An=new WeakSet,ko=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 l of t?.listMcpApps()??[]){let f=vc(l);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(Vc),d=new Set(c.flatMap(l=>l.tools.filter(f=>!(f.kind==="action"&&"actionId"in f)).map(f=>f.name))),p=[];for(let l of c){let f=l;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 _ of f.tools){if(s.has(_.name)){if(_.kind==="host"&&this.localToolByName.get(_.name)?.kind==="host"){A.push(_);continue}if(_.kind==="action"&&"actionId"in _){I.push(Object.freeze({toolName:_.name,actionId:_.actionId,reason:"name_collision"}));continue}E("TOOL_ID_CONFLICT",`MCP App tool name is already registered: ${_.name}`);}if(_.kind==="action"&&"actionId"in _&&d.has(_.name)){I.push(Object.freeze({toolName:_.name,actionId:_.actionId,reason:"name_collision"}));continue}s.add(_.name),this.localToolByName.set(_.name,_),A.push(_);}(A.length!==f.tools.length||I.length!==(f.toolDiagnostics?.length??0))&&(f=q({...f,tools:Object.freeze(A),toolDiagnostics:Object.freeze(I)})),p.push(f),this.localById.set(f.appId,f);}for(let l of i)this.registrationById.set(l.appId,l),this.launcherById.set(l.appId,zc(l)),l.definition&&this.addDefinition(l.definition);for(let l of p)this.registrationById.set(l.appId,l),this.launcherById.set(l.appId,Hc(l)),this.addDefinition(l.definition);for(let l of n.definitions??[])this.addDefinition(l);for(let l of n.handlers??[])this.addHandler(l);this.builtinApps=Object.freeze(i),this.localApps=Object.freeze(p),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(!Jc(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(wo(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=wo(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 Gc(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},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=Gc(e);Ho({localApps:[t],definitions:[e.definition]});}var Xo=k(()=>{g();Yn();});function Ko(){return Object.freeze({[ni]:{candidates:new Map,assetCatalogs:new Map,preparedCandidates:new Map}})}function $c(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=$c(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=k(()=>{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 T("NOT_FOUND"):n==="ELOOP"?new T("PATH_ESCAPED"):n==="EFBIG"||n==="EOVERFLOW"?new T("LIMIT_EXCEEDED"):n==="EACCES"||n==="EPERM"||n==="ENOTDIR"?new T("READ_DENIED"):new T("READ_DENIED")}function Yc(e){if(typeof e!="string"||e.length===0||!path.isAbsolute(e))throw new T("READ_DENIED")}function ti(e){if(typeof e!="string"||path.isAbsolute(e)||/[\\\u0000]/.test(e))throw new T("PATH_ESCAPED");if(e==="")return [];let n=e.split("/");if(n.some(t=>t.length===0||t==="."||t===".."))throw new T("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){Yc(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 T("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 T("READ_DENIED")}catch(o){throw o instanceof T?o:re(o)}if(!et(n,r))throw new T("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 T("PATH_ESCAPED");if(!r.isFile()||!a.isFile())throw new T("READ_DENIED");if(!si(i,r)||!si(i,a)||i.dev!==a.dev)throw new T("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 T("PATH_ESCAPED")}if(t!==n.realRoot||!ai(n.identity,qe(i)))throw new T("PATH_ESCAPED")}function qc(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 T,ri,Kc,Qo,Ze,nt,nr,tr,di=k(()=>{g();T=class extends Error{constructor(t){super(t);this.code=t;}code;name="AppDiscoveryFsError"},ri=fs$1.constants.O_NOFOLLOW,Kc=fs$1.constants.O_NONBLOCK,Qo=fs$1.constants.O_RDONLY|(ri??0)|(Kc??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 T("PATH_ESCAPED");try{let c=await promises.readdir(a,{withFileTypes:!0,encoding:"utf8"});return await Ye(n,r),c.map(qc)}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 T("READ_DENIED");if(ri===void 0)throw new T("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 T("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 T("LIMIT_EXCEEDED");if(d.size>BigInt(Number.MAX_SAFE_INTEGER))throw new T("LIMIT_EXCEEDED");await Ye(n,o);let p=await er(n,o.realRoot,r);await Zn(a,o.realRoot,p,d);let l=new Uint8Array(new ArrayBuffer(Number(d.size))),f=0;for(;f<l.byteLength;){let I;try{I=(await c.read(l,f,l.byteLength-f,f)).bytesRead;}catch(_){throw re(_)}if(I<=0)throw new T("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 T("IDENTITY_CHANGED");return await Zn(a,o.realRoot,p,A),await Ye(n,o),new Uint8Array(l)}finally{await c.close().catch(()=>{});}}async fingerprintVerifiedFile(n,t,i){if(!Number.isSafeInteger(i)||i<0)throw new T("READ_DENIED");if(ri===void 0)throw new T("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 T("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 T("LIMIT_EXCEEDED");await Ye(n,o);let p=await er(n,o.realRoot,r);await Zn(a,o.realRoot,p,d);let l;try{let f=await c.stat({bigint:!0});l=qe(f);}catch(f){throw re(f)}if(!ai(d,l))throw new T("IDENTITY_CHANGED");return await Zn(a,o.realRoot,p,l),await Ye(n,o),{...l,candidateRealPath:p??o.realRoot}}catch(d){throw d instanceof T?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"&&Ie.test(e)?e:void 0}function od(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 rd(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 sd(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 ad(e){return td.decode(e)}function cd(e){return JSON.parse(ad(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 dd(e){if(e instanceof T)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 be(e,n){let t=n();return Number.isFinite(t)&&Number.isFinite(e)&&t-e<=5e3}function pd(e){if(typeof e.readVerifiedFile=="function")return e.readVerifiedFile;if(typeof e.readFileVerified=="function")return e.readFileVerified}function ld(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=pd(e);if(!r)throw new T("READ_DENIED");return sd(await r.call(e,n,t,i))}async function ui(e,n,t){let i=ld(e);if(!i)throw new T("READ_DENIED");let r=await i.call(e,n,t);if(!Array.isArray(r))throw new T("READ_DENIED");return r.map(rd).filter(o=>o!==null)}function ud(e,n,t,i){return Object.freeze({code:e,...{},source:n,relativePath:t})}function fd(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 yd(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(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 Ad(e){let n;try{n=cd(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"),p=[...c?["lineage"]:[],...d?["launcher"]:[]];if(!tt(a,[...s,...p])||d&&a.launcher!==false)return;let l=ar(a.packageDir),f=or(a.appId);if(!l||l.length!==2||l[0]!=="apps"||!od(l[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,_=a.definition.hash;if(!A||!Number.isSafeInteger(I)||I<1||typeof _!="string"||!li.test(_)||!Array.isArray(a.files)||a.files.length<2||a.files.length>yi)return;let D=new Set,H=[];for(let j of a.files){if(!_n(j)||!tt(j,["path","sha256"]))return;let b=ar(j.path);if(!b||typeof j.sha256!="string"||!li.test(j.sha256))return;let C=b.join("/"),G=`${a.packageDir}/${C}`;if(D.has(C)||i.has(G))return;D.add(C),i.add(G),H.push(Object.freeze({path:C,sha256:j.sha256}));}if(!pe.some(j=>D.has(j))||!D.has("ui/index.html")||(r+=H.length,r>Qc))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:_}),lineage:Array.isArray(a.lineage)?a.lineage:[],files:Object.freeze(H.sort((j,b)=>je(j.path,b.path)))}));}return Object.freeze({version:1,packages:Object.freeze(o)})}function xe(e){let n=dd(e);return n==="PATH_ESCAPED"||n==="IDENTITY_CHANGED"||n==="TOCTOU"?"PATH_ESCAPED":n==="LIMIT_EXCEEDED"?"LIMIT_EXCEEDED":"BUNDLE_INTEGRITY"}async function Id(e,n,t,i,r){let o=[],a=async(s,c)=>{if(!be(i,r))throw new T("LIMIT_EXCEEDED");if(c>2)throw new T("LIMIT_EXCEEDED");let d=await ui(e,n,s);for(let p of d){if(typeof p.name!="string"||p.name.length===0||p.name==="."||p.name===".."||/[\\/\u0000]/.test(p.name))throw new T("PATH_ESCAPED");let l=`${s}/${p.name}`;if(p.kind==="file"){if(o.push(l.slice(t.length+1)),o.length>yi)throw new T("LIMIT_EXCEEDED")}else if(p.kind==="directory")await a(l,c+1);else throw p.kind==="symlink"?new T("PATH_ESCAPED"):new T("READ_DENIED")}};return await a(t,0),o.sort(je)}function gd(e){return pe.includes(e)?262144:e==="ui/index.html"?Ke:e==="ui/state.json"?2097152:e.startsWith("ui/assets/")?nd:ed}async function cr(e,n,t,i){if(e===void 0)return {packages:[],diagnostics:[],incomplete:false,reservedIds:id};let r=fd(e.reservedIds),o=[],a=(y,m,h)=>ud(y,"bundled",m),s=(y=[],m=false,h)=>({...h===void 0?{}:{indexHash:h},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",Zc);}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 p=Ad(c);if(p===void 0)return o.push(a("BUNDLE_INTEGRITY","bundle-index.json")),s();if(!yd(Tn(p.packages),r))return o.push(a("BUNDLE_INTEGRITY","bundle-index.json")),s([],false,d);if(!be(t,i))return o.push(a("LIMIT_EXCEEDED","bundle-index.json")),s(p.packages.map(y=>({indexEntry:y,failureCode:"LIMIT_EXCEEDED"})),true,d);let l;try{l=await ui(n,e.root,"");}catch(y){return o.push(a(xe(y),"bundle-index.json")),s(p.packages.map(m=>({indexEntry:m,failureCode:xe(y)})),false,d)}if(!be(t,i))return o.push(a("LIMIT_EXCEEDED","bundle-index.json")),s(p.packages.map(y=>({indexEntry:y,failureCode:"LIMIT_EXCEEDED"})),true,d);let f=l.find(y=>y.name==="bundle-index.json"&&y.kind==="file"),A=l.find(y=>y.name==="apps"&&y.kind==="directory"),I=y=>p.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 _=l.filter(y=>y.name!=="bundle-index.json"&&y.name!=="apps");if(_.length>0){let y=_.some(m=>m.kind==="symlink")?"PATH_ESCAPED":"BUNDLE_INTEGRITY";return o.push(a(y,"bundle-index.json")),s(I("BUNDLE_INTEGRITY"),false,d)}if(l.some(y=>y.name==="apps"&&y.kind!=="directory"))return o.push(a("PATH_ESCAPED","apps")),s(I("PATH_ESCAPED"),false,d);let D=[];if(A)try{D=await ui(n,e.root,"apps");}catch(y){return o.push(a(xe(y),"apps")),s(I(xe(y)),false,d)}if(!be(t,i)||D.length>fi)return o.push(a("LIMIT_EXCEEDED","apps")),s(I("LIMIT_EXCEEDED"),true,d);let H=new Map(p.packages.map(y=>[y.packageDir.slice(5),y])),j=D.filter(y=>!H.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,C=new Map,G=new Map;for(let y of p.packages){let m=C.get(y.appId)??[];m.push(y),C.set(y.appId,m);let h=`${y.definition.id}\0${String(y.definition.version)}`,M=G.get(h)??[];M.push(y),G.set(h,M);}for(let y of [...C.values(),...G.values()])if(y.length>1)for(let m of y)b.add(m);let N=[],O=c.byteLength,S=false;for(let y of p.packages){if(!be(t,i)){S=true,N.push({indexEntry:y,failureCode:"LIMIT_EXCEEDED"});continue}let m;try{let U=y.lineage[y.lineage.length-1];if(!U)throw new Te("LINEAGE_INVALID","Definition lineage is missing");if(U.definition.id!==y.definition.id||U.version!==y.definition.version||U.hash!==y.definition.hash)throw new Te("LINEAGE_STALE","Last lineage generation does not match bundle identity");m=Yt(y.lineage,{...U.definition,hash:U.hash}).entries;}catch(U){let P=U instanceof Te?U.code:"LINEAGE_INVALID";o.push(a(P,y.packageDir)),N.push({indexEntry:y,failureCode:P});continue}let h=D.find(U=>U.name===y.packageDir.slice(5));if(!A||!h){N.push({indexEntry:y,failureCode:"BUNDLE_INTEGRITY"});continue}if(h.kind!=="directory"){N.push({indexEntry:y,failureCode:h.kind==="symlink"?"PATH_ESCAPED":"BUNDLE_INTEGRITY"});continue}let M;try{let U=await Id(n,e.root,y.packageDir,t,i);if(!be(t,i)){S=!0,N.push({indexEntry:y,failureCode:"LIMIT_EXCEEDED"});continue}let P=y.files.map(z=>z.path);if(U.length!==P.length||U.some((z,Se)=>z!==P[Se])){N.push({indexEntry:y,failureCode:"BUNDLE_INTEGRITY"});continue}M=new Map;let W;for(let z of y.files){if(!be(t,i)){W="LIMIT_EXCEEDED",S=!0;break}if(O>=pi){W="LIMIT_EXCEEDED";break}let Se;try{Se=await sr(n,e.root,`${y.packageDir}/${z.path}`,gd(z.path));}catch(at){W=xe(at);break}if(!be(t,i)){W="LIMIT_EXCEEDED",S=!0;break}if(O+Se.byteLength>pi){O=pi,W="LIMIT_EXCEEDED";break}if(O+=Se.byteLength,crypto.createHash("sha256").update(Se).digest("hex")!==z.sha256){W="BUNDLE_INTEGRITY";break}M.set(z.path,Se);}if(W!==void 0){N.push({indexEntry:y,failureCode:W});continue}}catch(U){be(t,i)||(S=true),N.push({indexEntry:y,failureCode:xe(U)});continue}N.push({indexEntry:y,lineage:m,files:M,...b.has(y)?{failureCode:"DUPLICATE_ID"}:{}});}return s(N,S,d)}var Zc,fi,yi,Qc,ed,nd,pi,li,td,id,Ai=k(()=>{g();qt();Ue();Gt();Yn();di();Zc=256*1024,fi=64,yi=128,Qc=fi*yi,ed=2*1024*1024,nd=8*1024*1024,pi=32*1024*1024,li=/^[0-9a-f]{64}$/,td=new TextDecoder("utf-8",{fatal:true}),id=Object.freeze({appIds:Object.freeze([]),definitionIds:Object.freeze([])});});var Rr={};Vr(Rr,{AppDiscoveryFsError:()=>T,LOCAL_APP_TOOL_PREFIX:()=>_d,MCP_APP_WORKSPACE_TOOL_PREFIX:()=>Td,NodeAppDiscoveryFs:()=>Ze,NodeAppDiscoveryFsAdapter:()=>tr,WORKSPACE_APP_TOOL_PREFIX:()=>Qe,createWorkspaceAppScanCache:()=>Ko,defaultAppDiscoveryFs:()=>nt,defaultNodeAppDiscoveryFs:()=>nr,deriveWorkspaceAppToolName:()=>Ed,deriveWorkspaceAppToolNames:()=>mi,discoverWorkspaceAppCandidates:()=>qd,discoverWorkspaceApps:()=>hi,isWorkspacePackage:()=>hd,productAppBundleReservations:()=>Tn,scanWorkspaceApps:()=>Zd});function hd(e,n){let t=n.split("/");return t.length===2&&t[0]===e&&/^[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(t[1])}function mi(e){if(typeof e!="string"||!Ie.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 Ed(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 Nd(e,n){return n.length===0||n==="."||n===".."||/[\\/\u0000]/.test(n)?e==="skills"?"skills":"apps":`${e==="skills"?"skills":"apps"}/${n}`}function bd(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 Tr(e){if(typeof e=="string")return {name:e,kind:"directory"};if(e===null||typeof e!="object")return null;let n=e;if(typeof n.name!="string")return null;if(n.kind==="file"||n.kind==="directory"||n.kind==="symlink"||n.kind==="other")return {name:n.name,kind:n.kind};if(n.type==="file"||n.type==="directory"||n.type==="symlink"||n.type==="other")return {name:n.name,kind:n.type};let t=n.isDirectory;if(typeof t=="function"&&t.call(e))return {name:n.name,kind:"directory"};let i=n.isSymbolicLink;if(typeof i=="function"&&i.call(e))return {name:n.name,kind:"symlink"};let r=n.isFile;return typeof r=="function"&&r.call(e)?{name:n.name,kind:"file"}:{name:n.name,kind:"other"}}function Pd(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 Er(e){return Dd.decode(e)}function Sd(e){return JSON.parse(Er(e))}function Md(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 T)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 Od(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 Pe(e,n){let t=n();return Number.isFinite(t)&&Number.isFinite(e)&&t-e<=5e3}function Ld(e){return {pluginId:e.appId,definitionKey:`${e.definition.id}\0${String(e.definition.version)}`}}function Rd(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=Ud(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 Ud(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 Cd(){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 T("NOT_FOUND");if(s.byteLength>i)throw new T("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(p=>p.relativePath===n.relativePath&&!ot(p.key,t)),d=t===Y&&ne(s)==="NOT_FOUND"&&wd(o.directoryListings,n.relativePath);throw !c&&!d&&(o.cacheable=false),s}}async function kd(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 wd(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 jd(e,n,t,i,r,o,a,s){let c=e.fingerprintVerifiedFile,d=Pr(t,i),p=r.candidates.get(d),l=i.relativePath,f;try{f=await gr(e,n,l);}catch(S){if(ne(S)!=="NOT_FOUND")throw S}let A=f===void 0?void 0:{relativePath:l,key:f};if(A!==void 0&&(i.source==="apps"||i.source==="skills")&&!pe.some(S=>ot(A.key,S)))return Pe(a,s)?p!==void 0&&p.candidate===void 0&&p.candidateRealPath===void 0&&p.files.length===0&&p.directoryListings.length===1&&p.directoryListings[0]?.relativePath===A.relativePath&&p.directoryListings[0]?.key===A.key&&(i.source==="apps"?p.diagnostic?.code==="MANIFEST_MISSING":p.diagnostic===void 0)&&typeof c=="function"?{memo:p}: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}},_=await Promise.all(Ar.map(I)),D=await Promise.all(xd.map(I));if(!Pe(a,s))return {timeLimitReached:true};let H=typeof c=="function"&&_.every(S=>S!==void 0),j=_.filter(S=>S!==void 0),b=[...j,...D.filter(S=>S!==void 0)],C=new Map,G=p!==void 0&&H,N;if(p!==void 0&&typeof c=="function"){let S=await Promise.all(p.files.map(async y=>{if(!Pe(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"){G=false;continue}if(y.kind!=="fingerprint")continue;let{file:m,current:h}=y;C.set(m.relativePath,h),N??=h.candidateRealPath,(h.candidateRealPath!==p.candidateRealPath||!Sr(h,m.fingerprint)||Mr(h,o))&&(G=false);}}let O=p!==void 0&&p.directoryListings.length===b.length&&p.directoryListings.every((S,y)=>S.relativePath===b[y]?.relativePath&&S.key===b[y]?.key);return p!==void 0&&H&&O&&G&&N===p.candidateRealPath?{memo:p}:!H||j.length!==Ar.length?{}:{context:{state:r,cacheKey:d,workspaceRoot:n,scanStartedAtNs:o,directoryListings:Object.freeze(b),priorFingerprints:C,files:new Map,...N===void 0?{}:{candidateRealPath:N},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(Tr);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 vd(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 Vd(e,n){let t={...e.definition,sourceHash:n},i;try{i=ie(t);}catch(o){throw o instanceof R&&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 Fd(e,n){return e.actions.some(t=>t.backend.type==="core"&&t.backend.handler!=="state.set"&&!Jn(n,t.backend))}function Bd(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=Bd(e);if(!r)throw new T("READ_DENIED");return Pd(await r.call(e,n,t,i))}async function Hd(e,n,t){let i=Or(e);if(!i)throw new T("READ_DENIED");let r=await i.call(e,n,t);if(!Array.isArray(r))throw new T("READ_DENIED");return r.map(Tr).filter(o=>o!==null)}function zd(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 Jd(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 Gd(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 p of zd(n)){for(let l of p.appIds??[])typeof l=="string"&&i.add(l);for(let l of p.definitionIds??[])typeof l=="string"&&r.add(l);for(let l of p.toolNames??[])typeof l=="string"&&o.add(l);}for(let p of e){let l=p.candidate;if(!l)continue;if(i.has(l.pluginId)||r.has(l.definitionId)){ye(p,"RESERVED_ID");continue}[l.toolNames.read,l.toolNames.action].filter(A=>A!==void 0).some(A=>o.has(A))&&ye(p,"DUPLICATE_ID");}let c=[...e.filter(p=>p.provenance!==void 0&&p.diagnostic===void 0).flatMap(p=>p.candidate?[p.candidate]:[]),...(n.productBundleReservationMetadata?.candidates??[]).filter(p=>n.productBundleReservationMetadata?.indexHash!==void 0&&p.provenance?.indexHash===n.productBundleReservationMetadata.indexHash)],d=new Set;for(let p of e){let l=p.candidate;if(!(!l||p.diagnostic||p.source!=="apps"||p.provenance!==void 0)&&e.filter(f=>f.source==="apps"&&f.identity?.pluginId===l.pluginId).length===1&&c.some(f=>f.pluginId===l.pluginId)&&!(s.has(l.definitionId)&&!c.some(f=>f.pluginId===l.pluginId&&f.definitionId===l.definitionId))&&!c.some(f=>f.pluginId!==l.pluginId&&f.definitionId===l.definitionId)&&!e.some(f=>f.identity?.pluginId!==l.pluginId&&f.identity?.definitionKey===`${l.definitionId}\0${l.version}`&&f.diagnostic?.code!=="RESERVED_ID"))try{Wo(l),d.add(p);}catch(f){ye(p,f instanceof _e?br(f.code):"EXEC_DENIED");}}for(let p of e){let l=p.candidate;l&&p.provenance===void 0&&!d.has(p)&&(a.has(l.pluginId)||s.has(l.definitionId))&&ye(p,"RESERVED_ID");}return d}function $d(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=Md(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(P=>({actionId:P.actionId,inputSchema:P.inputSchema})));}catch(P){if(P instanceof _e){v(n,br(P.code));return}throw P}let s;try{s=await Nn(e,n,"ui/index.html",Ke);}catch(P){v(n,Ve(ne(P),"entry"));return}if(s.byteLength>Ke){v(n,"LIMIT_EXCEEDED");return}let c;try{c=Er(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 p={},l,f;if(o.initialState!==void 0){try{l=await Nn(e,n,"ui/state.json",2097152);}catch(P){v(n,Ve(ne(P),"initial"));return}if(l.byteLength>2097152){v(n,"LIMIT_EXCEEDED");return}try{let P=Sd(l),W=o.dataPaths??[],z=wt(P,W);p=ae(z,0,W),He(p);}catch{v(n,"INITIAL_STATE_INVALID");return}if(f=crypto.createHash("sha256").update(l).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),_=vd(A,s,l??new Uint8Array),D;try{D=Vd(I,_);}catch(P){if(P instanceof oe){v(n,Od(P));return}throw P}let H;if(n.bundleLineage!==void 0){let P=n.bundleLineage[n.bundleLineage.length-1];if(!P){v(n,"LINEAGE_INVALID");return}let{legacy:W,...z}=P.definition,{hash:Se,...at}=D;if(Z(z)!==Z(at)){v(n,"LINEAGE_STALE");return}if(W!==void 0&&(D={...D,legacy:W}),W!==void 0)try{D={...D,hash:ie(D)},ce(D);}catch{v(n,"LINEAGE_INVALID");return}H=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!==D.id||n.bundleIdentity.version!==D.version||n.bundleIdentity.definitionHash!==D.hash)){v(n,"LINEAGE_STALE");return}let j=await kd(e,n,i.mcpb?.icon),b=mi(o.pluginId),C=o.actions.length===0?{read:b.read}:b,G=ve(I),N=ve(A),O=ve(D),S=ve({...I.handlers}),y=yr(s),m=l===void 0?void 0:yr(l),h=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})}}),M={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:G,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:O,handlers:S,resources:h,html:c,entryBytes:y,entryHash:d,initialState:ve(p),...m===void 0?{}:{initialStateBytes:m},...f===void 0?{}:{initialStateHash:f},sourceHash:_,toolNames:Object.freeze(C)},U=n.provenance===void 0?{...M,source:n.source}:{...M,provenance:n.provenance,lineage:H??[]};n.candidate=Object.freeze(U),Fd(o,D.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 Wd(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 Xd(e,n,t,i=md,r=false,o=new Set){let a=$d(e),s=Jd(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)),p=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,l={apps:c,diagnostics:d,complete:n===void 0,...n===void 0?{}:{incompleteReason:n},...t===void 0?{}:{productBundleIndexHash:t},...p===void 0?{}:{productBundleSnapshotMetadata:p}};return Object.defineProperty(l,"candidates",{configurable:false,enumerable:false,get:()=>c}),Object.freeze(l)}function Kd(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 Yd(e,n){if(Kd(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}=Yd(n,t),o=r.clock??Cd,a=o(),s=await cr(r.productBundle,i,a,o),c=o(),d=BigInt(Date.now())*1000000n,p=[],l=0,f,A=false,I,_;if(r.scanCache!==void 0&&typeof i.getRootIdentity=="function"&&typeof i.fingerprintVerifiedFile=="function")try{_=await i.getRootIdentity(e),I=Yo(r.scanCache,_),I.scanStartedAtNs=d;}catch(N){if(ne(N)!=="NOT_FOUND")throw N}let D=I!==void 0&&r.productBundle===void 0&&s.packages.length===0&&s.diagnostics.length===0,H=new Set,j=true;p.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(!Pe(c,o)){A=true,f="time_limit";break}let O=N.indexEntry,S=O.packageDir,y=N.files===void 0?void 0:Rd(S,N.files),m=s.indexHash===void 0?void 0:Eo(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),h={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:O.appId,definitionId:O.definition.id,version:O.definition.version,definitionHash:O.definition.hash},identity:Ld(O)};if(p.push(h),l+=1,N.failureCode!==void 0){v(h,N.failureCode);continue}if(N.files?.has(Y)===true){v(h,"EXEC_DENIED",{reason:{path:"",rule:"bundled-tool-mode-unsupported",file:Y}});continue}let M={};for(let U of pe){let P=N.files?.get(U);P!==void 0&&(M[U]=P);}if(!gi(M)){v(h,"BUNDLE_INTEGRITY");continue}if(await _r(i,h,M),!Pe(c,o)){A=true,f="time_limit";break}}let C=[{source:"apps",directory:"apps"},{source:"skills",directory:"skills"}];e:for(let N of C){let{source:O,directory:S}=N,y;try{y=await Hd(i,e,S);}catch(h){if(ne(h)==="NOT_FOUND")continue;D=false,j=false,p.push({source:O,root:e,name:"",relativePath:O,diagnostic:it(Ve(ne(h),"manifest"),O,O)});continue}let m=y.filter(h=>h.kind==="directory"||h.kind==="symlink").filter(h=>bd(h.name)).map(h=>({source:O,root:e,name:h.name,relativePath:Nd(O,h.name)})).sort((h,M)=>Dn(h.relativePath,M.relativePath));for(let h of m){let M={...h};if(p.push(M),_!==void 0?H.add(Pr(_,M)):D=false,!Pe(c,o)){A=true,f="time_limit";break e}let U;if(I!==void 0&&_!==void 0){try{let z=await jd(i,e,_,M,I,d,c,o);if(z.timeLimitReached){A=!0,f="time_limit";break e}M.scanContext=z.context,U=z.memo;}catch(z){D=false,v(M,Ve(ne(z),"manifest"));continue}U===void 0&&(D=false);}if(U!==void 0){if(M.candidate=U.candidate,M.diagnostic=U.diagnostic,M.identity=U.identity,O==="skills"&&U.candidate===void 0&&U.diagnostic===void 0)continue;if(l>=64){v(M,"LIMIT_EXCEEDED");continue}if(h.relativePath.split("/").length-1>2){v(M,"LIMIT_EXCEEDED");continue}if(l+=1,!Pe(c,o)){A=true,f="time_limit";break e}continue}let P;if(O==="skills"&&(P=await Wd(i,M),P===void 0)){M.diagnostic===void 0&&Ii(M);continue}if(l>=64){v(M,"LIMIT_EXCEEDED");continue}if(h.relativePath.split("/").length-1>2){v(M,"LIMIT_EXCEEDED");continue}if(!Pe(c,o)){A=true,f="time_limit";break e}if(l+=1,P===void 0){let z=await Lr(i,M);if(z.failure!==void 0||!gi(z.files)){v(M,z.failure??Ve("NOT_FOUND","manifest")),Ii(M);continue}P=z.files;}if(await _r(i,M,P),Ii(M),!Pe(c,o)){A=true,f="time_limit";break e}}}if(I!==void 0&&_!==void 0){let N=[...H].sort(Dn),O=I.lastCandidateKeys,S=O!==void 0&&O.length===N.length&&O.every((m,h)=>m===N[h]);if(D=D&&S,j&&!A&&f===void 0)for(let m of I.candidates.keys())try{JSON.parse(m)[0]===_.realPath&&!H.has(m)&&I.candidates.delete(m);}catch{I.candidates.delete(m);}let y=[...I.candidates.keys()].filter(m=>{try{return JSON.parse(m)[0]===_.realPath}catch{return false}});D=D&&y.length===H.size&&y.every(m=>H.has(m))&&!A&&f===void 0,I.lastCandidateScanUnchanged=D,j&&!A&&f===void 0&&(I.lastCandidateKeys=Object.freeze(N));}A&&p.push({source:"apps",root:e,name:"",relativePath:"apps",diagnostic:it("DISCOVERY_TIME_LIMIT","apps","apps")});let G=Gd(p,r,b);return Xd(p,f,s.indexHash,b,r.productBundle!==void 0,G)}var md,Qe,_d,Td,dr,Dd,Ar,xd,Ir,qd,Zd,Ur=k(()=>{g();Ce();bn();Ee();mo();Xt();Ue();Yn();Xo();Gn();Hn();qo();di();zn();Ai();Ai();md=Tn([]);Qe="crewx_local_app_",_d=Qe,Td=Qe;dr=["bundled","apps","skills"],Dd=new TextDecoder("utf-8",{fatal:true});Ar=["","/ui"],xd=["/dist"],Ir=2000000000n;qd=hi,Zd=hi;});g();var Cr="SKILL.md",ip=/^---\s*\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;function kr(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function op(e){return e.isDirectory()||e.isSymbolicLink()}function jr(e){try{return fs$1.existsSync(e)&&fs$1.statSync(e).isDirectory()}catch{return false}}var rp=["index.js","main.js"];function hf(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 rp){let o=path.resolve(e,r);if(fs$1.existsSync(o))return o}}function sp(e){let n;try{n=fs$1.readFileSync(e,"utf8");}catch{return {frontmatter:{},readable:false,valid:false,hasFrontmatter:false}}let t=n.match(ip);if(!t)return {frontmatter:{},readable:true,valid:true,hasFrontmatter:false};try{let i=jsYaml.load(t[1]??"");if(!kr(i))return {frontmatter:{},readable:!0,valid:!1,hasFrontmatter:!0};let r=kr(i.metadata)?i.metadata:void 0;return {frontmatter:{...typeof i.name=="string"?{name:i.name}:{},...typeof(r?.version??i.version)=="string"?{version:r?.version??i.version}:{},...typeof i.description=="string"?{description:i.description}:{}},readable:!0,valid:!0,hasFrontmatter:!0}}catch{return {frontmatter:{},readable:true,valid:false,hasFrontmatter:true}}}function ap(e){return [path.join(e,Cr),path.join(e,"skill",Cr)]}function rt(e,n){if(!jr(e))return null;for(let t of ap(e)){if(!fs$1.existsSync(t))continue;let r=sp(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(op)}catch{return []}}function cp(e){return e.length===0||/[\\\u0000]/.test(e)?false:e.split("/").every(n=>n.length>0&&n!=="."&&n!=="..")}function wr(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))wr(rt(path.join(o,a.name),a.name),t,n);continue}wr(rt(path.join(i,r.name),r.name),t,n);}return n.sort((i,r)=>i.name.localeCompare(r.name))}function dp(e,n){if(!cp(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 _f(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 Tf=st,Ef=dp;
2
- exports.discover=st;exports.discoverBundledProductSkills=_f;exports.discoverSkills=Tf;exports.findEntrypoint=hf;exports.readSkillFrontmatter=sp;exports.resolve=dp;exports.resolveSkill=Ef;
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 k=(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=k(()=>{});var R,bn=k(()=>{g();R=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 R("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,Te=k(()=>{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=k(()=>{g();Pn=["text/plain","application/json"];});var Ei=k(()=>{g();ut();});function ze(e){return Yr.has(e)||qr.test(e)||Zr.test(e)}var Ti,Yr,qr,Zr,Sn,nn,Ie,ft,yt,At,It,gt,Ue=k(()=>{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_]+)*$/,Ie=/^[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=k(()=>{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=k(()=>{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=k(()=>{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 kn(e){return ts.includes(e)}var Un,bi,ts,Tt=k(()=>{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.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.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 R("DEFINITION_UNSUPPORTED","UI definition is invalid");if(e.sourceHash!==void 0&&(typeof e.sourceHash!="string"||!os.test(e.sourceHash)))throw new R("DEFINITION_UNSUPPORTED","UI definition source hash is invalid");if(!/^[0-9a-f]{64}$/.test(e.hash)||ie(e)!==e.hash)throw new R("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 R("DEFINITION_UNSUPPORTED","UI action declaration is invalid");if(t.confirmation!==void 0&&t.confirmation!=="none"&&t.confirmation!=="native")throw new R("DEFINITION_UNSUPPORTED","UI action confirmation is invalid");if(t.inputKeys&&(!Array.isArray(t.inputKeys)||t.inputKeys.some(i=>typeof i!="string"||!i)))throw new R("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 R("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 R("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 R("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 R("DEFINITION_UNSUPPORTED","UI action job control declaration is invalid");if(t.content!==void 0&&!Mn(t.content))throw new R("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 R("DEFINITION_UNSUPPORTED","UI action environment declaration is invalid")}if(e.renderer!==void 0&&(!e.renderer||e.renderer.length>128))throw new R("DEFINITION_UNSUPPORTED","UI definition renderer is invalid");if(e.surfaces&&(!Array.isArray(e.surfaces)||e.surfaces.some(n=>!n||n.length>64)))throw new R("DEFINITION_UNSUPPORTED","UI definition surfaces are invalid");if(e.usage!==void 0&&e.usage!=="card"&&e.usage!=="window")throw new R("DEFINITION_UNSUPPORTED","UI definition usage is invalid");if(e.detailPanel!==void 0&&typeof e.detailPanel!="boolean")throw new R("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 R("DEFINITION_UNSUPPORTED","UI definition displayModes are invalid");if(e.usage==="card"&&e.displayModes!==void 0)throw new R("DEFINITION_UNSUPPORTED","Card definitions cannot declare displayModes");if(e.usage==="window"&&e.detailPanel!==void 0)throw new R("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 R("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 R("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 R("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 R("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 R("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 R("DEFINITION_UNSUPPORTED","UI legacy agent access is invalid");if(e.legacy.actionTool!==void 0&&(!i||Object.keys(i).length===0))throw new R("DEFINITION_UNSUPPORTED","UI legacy action tool requires its complete agent access map")}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 R("DEFINITION_UNSUPPORTED","UI definition dataPaths are invalid")}}function rs(e,n){if(!e||typeof e!="object"||Array.isArray(e))throw new R("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 R("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 R("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 R("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=k(()=>{g();Te();bn();_t();Et();Tt();os=/^[0-9a-f]{64}$/;});var Pi=k(()=>{g();Te();});var Y,De,bt=k(()=>{g();Y="dist/tools.json",De="dist/main.mjs";});var tn,Si=k(()=>{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=k(()=>{g();as=["CREWX_APP_INSTANCE_ID","CREWX_THREAD_ID"];});function H(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))&&H("CSP_ORIGIN_INVALID"),t.value}function wn(e,n){if(!Object.prototype.hasOwnProperty.call(e,n))return [];let t=_s(e,n);Array.isArray(t)||H("CSP_ORIGIN_INVALID"),Reflect.ownKeys(t).some(o=>typeof o!="string"||o!=="length"&&!/^(?:0|[1-9][0-9]*)$/.test(o))&&H("CSP_ORIGIN_INVALID");let r=[];for(let o=0;o<t.length;o+=1)(!Object.prototype.hasOwnProperty.call(t,o)||typeof t[o]!="string")&&H("CSP_ORIGIN_INVALID"),r.push(t[o]);return Object.keys(t).length!==t.length&&H("CSP_ORIGIN_INVALID"),r}function Es(e){let n;try{n=JSON.stringify(e);}catch{H("CSP_ORIGIN_INVALID");}return n===void 0&&H("CSP_ORIGIN_INVALID"),new TextEncoder().encode(n).byteLength}function Ui(e,n){/\s|\\/u.test(e)&&H("CSP_ORIGIN_INVALID");let t=ys.exec(e);t||H("CSP_ORIGIN_INVALID");let i=t[1].toLowerCase(),r=t[2];(r.includes("@")||r.includes("%")||r.includes("*"))&&H("CSP_ORIGIN_INVALID"),(r.startsWith("[")?As:Is).test(r)||H("CSP_ORIGIN_INVALID"),i==="wss"&&n!=="connectDomains"&&H("CSP_ORIGIN_INVALID");let a;try{a=new URL(e);}catch{H("CSP_ORIGIN_INVALID");}(a.protocol!==`${i}:`||a.username!==""||a.password!==""||a.search!==""||a.hash!=="")&&H("CSP_ORIGIN_INVALID");let s=a.hostname.toLowerCase();if((!s||s.includes("%"))&&H("CSP_ORIGIN_INVALID"),!s.startsWith("[")){let d=s.endsWith(".")?s.slice(0,-1):s;(d.length===0||d.length>253)&&H("CSP_ORIGIN_INVALID"),d.split(".").some(u=>u.length>63||!gs.test(u))&&H("CSP_ORIGIN_INVALID");}let c=a.origin;return (c==="null"||!c.startsWith(`${i}://`))&&H("CSP_ORIGIN_INVALID"),{origin:c,hostname:s}}function 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 ki(e){return Object.freeze([...new Set(e.map(n=>n.origin))].sort())}function wi(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=wi({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)||H("CSP_ORIGIN_INVALID");let t=Reflect.ownKeys(e);t.some(A=>typeof A!="string")&&H("CSP_ORIGIN_INVALID"),t.some(A=>!us.has(A))&&H("CSP_AXIS_UNKNOWN");let i=wn(e,"connectDomains"),r=wn(e,"frameDomains"),o=wn(e,"resourceDomains"),a=wn(e,"baseUriDomains");(o.length>0||a.length>0)&&H("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))&&H("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))&&H("CSP_ORIGIN_FORBIDDEN");let u={declared:true,connectDomains:ki(c),frameDomains:ki(d)},f=wi(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=k(()=>{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 z(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;try{let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}catch{return false}}function O(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function ra(e,n){let t={};for(let[i,r]of Object.entries(e))i!==n&&(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=>!O(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}z(e)||p("MANIFEST_INVALID","MANIFEST_INVALID",o);for(let[a,s]of Object.entries(e))vn(s,n,t+1,i&&t===0&&(a==="name"||a==="description"),r,rn(o,a));}finally{n.delete(e);}}}function ge(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){z(e)||p("MANIFEST_INVALID");let n={};for(let[t,i]of Object.entries(e)){let r=sa(t);z(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=ge(e,"field");return Xi.test(i)||p("MANIFEST_INVALID"),ca(n,i,t),i}function da(e,n){z(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(ge(e,"badgeToken")),noticeToken:Je(ge(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(ge(e,"titleToken")),field:xn(e,n,"text"),variant:"callout"};case "step-flow":return G(e,["primitive","titleToken","field"]),{primitive:t,titleToken:Je(ge(e,"titleToken")),field:xn(e,n,"step-list")};case "text-list":{G(e,["primitive","titleToken","field"],["emptyToken","hideWhenEmpty"]);let i={primitive:t,titleToken:Je(ge(e,"titleToken")),field:xn(e,n,"text-list")};return O(e,"emptyToken")&&(i.emptyToken=Je(ge(e,"emptyToken"))),O(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)||ks.test(e)||ws.test(e))&&p("UNSAFE_VALUE",`${n} contains an unsafe value`),e}function Mt(e,n){return (typeof e!="string"||!Ie.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}z(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){z(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 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));z(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 ya(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 Aa(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){z(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(O(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"&&(O(e,"minLength")&&(o.minLength=Ge(e.minLength,"schema minLength",4096)),O(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")&&(O(e,"minimum")&&(o.minimum=Bi(e.minimum,"schema minimum")),O(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"&&(O(e,"minItems")&&(o.minItems=Ge(e.minItems,"schema minItems",128)),O(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"),O(e,"items")&&(o.items=Ut(e.items,n+1,false))),i==="object"){let s;if(O(e,"properties")){z(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=Aa(l,t);s[f]=Ut(u,n+1,false);}o.properties=s;}O(e,"minProperties")&&(o.minProperties=Ge(e.minProperties,"schema minProperties",64)),O(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=ya(e.required,s);c!==void 0&&(o.required=c),O(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 Ia(e){let n=Ut(e,0,true);return (n.type!=="object"||!n.properties)&&p("MANIFEST_INVALID","action inputSchema must declare object properties"),n}function ga(e){if(z(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"&&O(e,"entry"))return G(e,Xs),e.entry!==De&&p("MANIFEST_INVALID",`skill backend entry must be ${De}`),{type:"skill",entry:De};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=O(e,"env")?Ta(e.env):void 0;return {type:"skill",command:n,...t===void 0?{}:{env:t}}}p("MANIFEST_INVALID","action backend type is unsupported");}function ma(e){z(e)||p("MANIFEST_INVALID","action must be an object"),G(e,Vs,Fs),O(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",()=>Ia(e.inputSchema)),o;if(O(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"||!O(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",()=>ga(e.backend)),c;O(e,"content")&&((s.type!=="skill"||!Mn(e.content))&&p("MANIFEST_INVALID","action content declaration is invalid","content"),c=Da(e.content));let d;if(O(e,"confirmation")){let A=e.confirmation;A!=="none"&&A!=="native"&&p("MANIFEST_INVALID","action confirmation is invalid","confirmation"),d=A;}let l;O(e,"schedule")&&(l=F("schedule",()=>Ea(e.schedule,{backend:s,inputSchema:r,hasContent:c!==void 0,hasDataInputs:o!==void 0,confirmation:d})));let u;O(e,"job")&&(l!==void 0&&p("MANIFEST_INVALID","an action is either the scheduled run or a job, not both","job"),u=F("job",()=>_a(e.job,{backend:s,inputSchema:r,hasContent:c!==void 0,hasDataInputs:o!==void 0,confirmation:d})));let f;return O(e,"jobAccess")&&(u!==void 0&&p("MANIFEST_INVALID","an action is either the job or a job control, not both","jobAccess"),f=F("jobAccess",()=>ha(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 ha(e,n){return (n.backend.type!=="skill"||!("entry"in n.backend)||n.backend.entry!==De)&&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 _a(e,n){(n.backend.type!=="skill"||!("entry"in n.backend)||n.backend.entry!==De)&&p("MANIFEST_INVALID","job needs a tool-mode action","job"),(n.hasContent||n.hasDataInputs||n.confirmation!==void 0&&n.confirmation!=="none")&&p("MANIFEST_INVALID","a job action takes no content, dataInputs or native confirmation","job"),(n.inputSchema.required??[]).length>0&&p("MANIFEST_INVALID","a job action input must accept {}","inputSchema.required"),z(e)||p("MANIFEST_INVALID","job must be an object","job"),G(e,[],zs);let t=O(e,"deadlineMs")?e.deadlineMs:Un.default;return Cn(t)||p("MANIFEST_INVALID","job deadlineMs is invalid","job.deadlineMs"),{deadlineMs:t}}function Ea(e,n){(n.backend.type!=="skill"||!("entry"in n.backend)||n.backend.entry!==De)&&p("MANIFEST_INVALID","schedule needs a tool-mode action","schedule"),(n.hasContent||n.hasDataInputs||n.confirmation!==void 0&&n.confirmation!=="none")&&p("MANIFEST_INVALID","a scheduled action takes no content, dataInputs or native confirmation","schedule"),(n.inputSchema.required??[]).length>0&&p("MANIFEST_INVALID","a scheduled action input must accept {}","inputSchema.required"),z(e)||p("MANIFEST_INVALID","schedule must be an object","schedule"),G(e,Bs,Hs),Ln(e.everyMinutes)||p("MANIFEST_INVALID","schedule everyMinutes is invalid","schedule.everyMinutes");let t=O(e,"timeoutMs")?e.timeoutMs:On.default;return Rn(t)||p("MANIFEST_INVALID","schedule timeoutMs is invalid","schedule.timeoutMs"),{everyMinutes:e.everyMinutes,timeoutMs:t}}function Ta(e){return Mi(e)||p("MANIFEST_INVALID","skill backend env is invalid"),Object.freeze([...e])}function Da(e){return Object.freeze({...e.in===void 0?{}:{in:Object.freeze({...e.in})},...e.out===void 0?{}:{out:Object.freeze({...e.out})}})}function Na(e){return z(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"),O(e,"hash")?{path:"ui/state.json",hash:Ki(e.hash)}:{path:"ui/state.json"}}function ba(e){let n=["wasm","terminal","htmlDocuments"];return (!z(e)||Object.keys(e).length===0||Object.keys(e).some(t=>!n.includes(t)||e[t]!==true))&&p("MANIFEST_INVALID","runtime must contain only known capability flags set to true"),{...e.wasm===true?{wasm:true}:{},...e.terminal===true?{terminal:true}:{},...e.htmlDocuments===true?{htmlDocuments:true}:{}}}function Pa(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 Sa(e,n){vn(z(e)&&O(e,"csp")?ra(e,"csp"):e,new Set,0,true,true),Ot(e),z(e)||p("MANIFEST_INVALID"),G(e,js,vs),O(e,"_meta")&&F("_meta",()=>qi(e._meta)),e.manifestVersion!==2&&p("MANIFEST_INVALID");let t;O(e,"runtime")&&(t=F("runtime",()=>ba(e.runtime)));let i;O(e,"csp")&&(i=F("csp",()=>Pa(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;O(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;O(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;O(e,"entryHash")&&(u=F("entryHash",()=>Ki(e.entryHash)));let f;O(e,"initialState")&&(f=F("initialState",()=>Na(e.initialState)));let A;O(e,"usage")&&(e.usage!=="card"&&e.usage!=="window"&&p("MANIFEST_INVALID","usage is invalid","usage"),A=e.usage);let I;O(e,"detailPanel")&&(typeof e.detailPanel!="boolean"&&p("MANIFEST_INVALID","detailPanel is invalid","detailPanel"),I=e.detailPanel);let h;if(O(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 b=new Set(["inline","floating","focused"]);(new Set(e.displayModes).size!==e.displayModes.length||e.displayModes.some(C=>typeof C!="string"||!b.has(C)))&&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 J=[],j=new Set;for(let b of e.surfaces)(typeof b!="string"||!gt.includes(b))&&p("MANIFEST_INVALID","surface is unsupported","surfaces"),j.has(b)&&p("MANIFEST_INVALID","surfaces contain a duplicate","surfaces","duplicate-item"),j.add(b),J.push(b);z(e.size)||p("MANIFEST_INVALID","size must be an object","size"),F("size",()=>G(e.size,["height"]));let P=F("size",()=>le(e.size,"height",1));P>720&&W("size.height exceeds the v2 limit","size.height","too-large");let U=F("stateProjection",()=>Lt(e.stateProjection)),$=e.summaryProjection===void 0?void 0:F("summaryProjection",()=>Lt(e.summaryProjection));$!==void 0&&$.allow.some(b=>!U.allow.includes(b))&&p("MANIFEST_INVALID","summaryProjection must be a subset of stateProjection.allow","summaryProjection");let D=F("dataPaths",()=>ua(e.dataPaths,U.allow)),L=O(e,"deviceFeatures")?F("deviceFeatures",()=>fa(e.deviceFeatures)):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 S=[],y=new Set,m=0,N=0;for(let[b,C]of e.actions.entries()){let M=`actions[${b}]`,V=F(M,()=>ma(C));if(y.has(V.actionId)&&p("MANIFEST_INVALID","actions contain a duplicate actionId",`${M}.actionId`,"duplicate-item"),V.schedule!==void 0&&(m+=1,m>Ni&&p("MANIFEST_INVALID","an App declares at most one scheduled action",`${M}.schedule`,"duplicate-item")),V.job!==void 0&&(N+=1,N>bi&&p("MANIFEST_INVALID","an App declares at most one job action",`${M}.job`,"duplicate-item")),V.backend.type==="core"&&V.backend.handler==="state.set"){V.mutation||p("MANIFEST_INVALID","state.set actions must be mutations",`${M}.mutation`);for(let B of Object.keys(V.inputSchema.properties))U.allow.includes(B)||p("MANIFEST_INVALID","state.set input paths must be projection-allowed",`${M}.inputSchema.properties`);}y.add(V.actionId),S.push(V);}return {manifestVersion:2,pluginId:r,definitionId:o,version:a,name:s,description:c,...d===void 0?{}:{icon:d},...l===void 0?{}:{tone:l},entry:"ui/index.html",...u===void 0?{}:{entryHash:u},...t===void 0?{}:{runtime:t},...i===void 0?{}:{csp:i},...f===void 0?{}:{initialState:f},...A===void 0?{}:{usage:A},...I===void 0?{}:{detailPanel:I},...h===void 0?{}:{displayModes:h},surfaces:J,size:{height:P},stateProjection:U,...$===void 0?{}:{summaryProjection:$},...D===void 0?{}:{dataPaths:D},...L===void 0?{}:{deviceFeatures:L},actions:S}}function qi(e){z(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 Ma(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},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 {z(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 wt(e,n=[]){z(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 Oa(e,n={}){vn(e),z(e)||p("MANIFEST_INVALID"),G(e,xs),e.manifestVersion!==1&&p("MANIFEST_INVALID");let t=St(ge(e,"pluginId")),i=St(ge(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"),z(e.activation)||p("MANIFEST_INVALID"),G(e.activation,["kind","language"]),e.activation.kind!=="fenced-code"&&p("MANIFEST_INVALID");let s=St(ge(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 La(e,n={}){return z(e)||p("MANIFEST_INVALID"),Object.hasOwn(e,"lineage")&&p("MANIFEST_INVALID","lineage is only allowed in product bundle indexes"),e.manifestVersion===2?Sa(e,n):Oa(e,n)}function sn(e,n={}){try{return La(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?Ma(t):t}var Ps,Ss,Ms,Xi,Os,Ls,Rs,Us,Vi,Cs,ks,ws,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=k(()=>{g();Si();Te();_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,ks=/javascript:/i,ws=/(?:^[\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"],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<=Ua&&Ra.test(e)}function w(e,n,t,i,r){throw new he(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["${Me}"]`;return e===void 0||e===""?n:e.startsWith("[")?`${n}${e}`:`${n}.${e}`}function xa(e){return e.toLowerCase().replace(/_/g,"-")}function ja(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??xa(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&&w("LIMIT_EXCEEDED",n,"string-too-long"),(Ca.test(e)||ka.test(e)||wa.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 ue(e,n){return (typeof e!="string"||e.length===0)&&w("MANIFEST_INVALID",n,"string"),e}function We(e,n){return Q(e)||w("MANIFEST_INVALID",n,"object"),e}function va(e,n){Array.isArray(e)||w("MANIFEST_INVALID",n,"array"),e.forEach((t,i)=>ue(t,`${n}[${i}]`));}function Va(e,n){typeof e!="boolean"&&w("MANIFEST_INVALID",n,"boolean");}function cn(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 Fa(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)||w("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)||w("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)||w("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":Va(n,e);return;case "localization":case "compatibility":case "user_config":We(n,e);return;default:w("MANIFEST_INVALID",e,"unknown-key");}}function Fn(e){return typeof e=="string"&&Ie.test(e)?e:void 0}function so(e){return Number.isSafeInteger(e)&&e>=1?e:void 0}function Ba(e){let n=Fn(e.name);if(n===void 0)return;let t=e._meta,i=Q(t)?t[Me]: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 Ha(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,Me)}catch{return false}}function za(e,n){if(e===we)return n.builtinOnly===true;let t=n._meta,i=Q(t)?t[Me]:void 0;return Q(i)&&i.builtinOnly===true}function Ja(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}"`),io(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,Me)||w("MANIFEST_INVALID",fe(),"missing-key");let i=t[Me];Q(i)||w("MANIFEST_INVALID",fe(),"object");for(let s of Object.keys(i))vt.includes(s)||to.includes(s)||w("MANIFEST_INVALID",fe(s),"unknown-key");for(let s of vt)s==="actions"&&n!==void 0||X(i,s)||w("MANIFEST_INVALID",fe(s),"missing-key");if(n!==void 0&&X(i,"actions")&&w("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`),Ga(i.actions),X(i,"definitionVersion")){let s=i.definitionVersion;(!Number.isSafeInteger(s)||s<1)&&w("MANIFEST_INVALID",fe("definitionVersion"),"positive-integer");}let r={};for(let s of no)X(e,s)&&(Fa(s,e[s]),r[s]=ro(e[s]));let o={};for(let[s,c]of Object.entries(t))s!==Me&&(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:De}}))),Object.keys(o).length>0&&(a._meta=o),{v2Input:a,...Object.keys(o).length>0?{vendorMeta:o}:{},passthrough:r}}function Ga(e){Array.isArray(e)&&e.forEach((n,t)=>{let i=Q(n)?n.backend:void 0;Q(i)&&X(i,"entry")&&w("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 $a(e,n,t){Q(e)||w("MANIFEST_INVALID","","not-object","manifest.json must be a JSON object",K);let i;try{i=Ja(e,t);}catch(a){throw a instanceof he?new he(a.code,{...a.reason,file:K}):a}let r;try{let a=sn(i.v2Input,{mode:n.mode??"local"});a.manifestVersion!==2&&w("MANIFEST_INVALID","","v2-required"),r=a;}catch(a){throw a instanceof oe?new he(a.code,oo(a,K,ja)):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 he("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 Wa(e,n){try{let t=sn(e,{mode:n.mode??"local"});if(t.manifestVersion!==2)throw new he("MANIFEST_INVALID",{path:"manifestVersion",rule:"v2-required",message:"a workspace App requires manifestVersion 2",file:we});return {file:we,manifest:t,v2Input:e}}catch(t){throw t instanceof oe?new he(t.code,oo(t,we,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 Xa(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 Ka(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 Ya(e,n){let t=Xa(e,n),i=Ka(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 ${we} normalize to different definitions${r}`+(t.length>0?`; differing fields: ${t.join(", ")}`:""));}function me(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 {...me("","tools-needs-manifest-json","MANIFEST_INVALID",`${Y} is read with ${K} only`),files:e}}function qa(e,n){if(e.byteLength>n)return {failure:me("","file-too-large","LIMIT_EXCEEDED")};let t;try{t=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e));}catch{return {failure:me("","invalid-json")}}if(!Q(t))return {failure:me("","not-object","MANIFEST_INVALID",`${Y} must be a JSON object`)};for(let r of Object.keys(t))if(r!=="schemaVersion"&&r!=="actions")return {failure:me(r,"unknown-key")};for(let r of ["schemaVersion","actions"])if(!X(t,r))return {failure:me(r,"missing-key")};if(t.schemaVersion!==1)return {failure:me("schemaVersion","unsupported-version","MANIFEST_INVALID",`schemaVersion must be ${1}`)};let i=t.actions;if(!Array.isArray(i))return {failure:me("actions","array")};for(let[r,o]of i.entries()){if(!Q(o))return {failure:me(`actions[${r}]`,"object")};if(X(o,"backend"))return {failure:me(`actions[${r}].backend`,"tools-backend","MANIFEST_INVALID",`an action in ${Y} cannot carry a backend`)}}return {actions:i}}function Za(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}=Za(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:qa(o,n.maxBytes??262144);if(t.length===0)return {ok:false,rejection:a===void 0?{code:"MANIFEST_INVALID",reason:{path:"",rule:"no-manifest-file",message:"neither manifest.json nor ui-plugin.json is present"},files:[]}:eo(r),parseFailure:true,builtinOnly:false};let s=t[0],c=s.file===K?Ba(s.raw):Ha(s.raw),d=t.some(A=>za(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?$a(A.raw,n,l):Wa(A.raw,n));u.length===2&&Ya(u[0].manifest,u[1].manifest);}catch(A){if(A instanceof he)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,we,pe,jt,Me,Bt,Ht,no,vt,to,Ra,Ua,Ca,ka,wa,he,Gt=k(()=>{g();Ce();Te();bt();Ue();xt();K="manifest.json",we="ui-plugin.json",pe=[K,we],jt="0.3",Me="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"]),Ra=/^(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-]+)*))?$/,Ua=256,Ca=/<\/?[A-Za-z][^>]*>/,ka=/^\s*javascript:/i,wa=/data:[^,\s]*,/i;he=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(nc.test(e))return {kind:"url",declared:e};if(!oc(e))return {kind:"invalid",reason:"bad-path",declared:e};let n=e.lastIndexOf("."),t=n<0?void 0:Qa.get(e.slice(n+1).toLowerCase());return t===void 0?{kind:"invalid",reason:"bad-type",declared:e}:{kind:"file",path:e,contentType:t}}function oc(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,tc)||yc(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,ic))return {ok:false,reason:"bytes-mismatch"};let t=uc(n);return {ok:true,square:t===void 0?void 0:po(t.width,t.height)}}return rc(n)}function rc(e){let n;try{n=ec.decode(e);}catch{return {ok:false,reason:"bytes-mismatch"}}return pc(n)?{ok:false,reason:"unsafe-svg"}:sc.test(n)?{ok:true,square:lc(n)}:{ok:false,reason:"bytes-mismatch"}}function pc(e){if(ac.some(n=>n.test(e)))return true;for(let n of e.matchAll(cc))if(!(n[1]??n[2]??n[3]??"").startsWith("#"))return true;for(let n of e.matchAll(dc))if(ao.lastIndex=n.index??0,!ao.test(e))return true;return false}function lc(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 uc(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(fc(t))return n+9>e.byteLength?void 0:{height:fo(e,n+5),width:fo(e,n+7)};n+=2+i;}}function fc(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 yc(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 Qa,ec,nc,tc,ic,sc,ac,cc,dc,ao,Xt=k(()=>{g();Qa=new Map([["svg","image/svg+xml"],["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"]]),ec=new TextDecoder("utf-8",{fatal:true}),nc=/^[A-Za-z][A-Za-z0-9+.-]*:/,tc=[137,80,78,71,13,10,26,10],ic=[255,216,255];sc=/^\s*(?:<\?[\s\S]*?\?>\s*|<!--[\s\S]*?-->\s*)*<svg(?=[\s/>])/,ac=[/<script/i,/[\s"'/]on[a-z]+\s*=/i,/<foreignobject/i,/<!doctype/i,/<!entity/i,/<(?:iframe|embed|object)\b/i,/@import/i],cc=/(?:^|[\s"'/])(?:xlink:)?href\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+))/gi,dc=/url\(/gi,ao=/url\(\s*["']?#/iy;});var mo=k(()=>{g();Pi();Gt();Xt();xt();Ue();});function E(e,n=e){throw new _e(e,n)}var _e,Hn=k(()=>{g();_e=class extends Error{constructor(t,i=t){super(i);this.code=t;}code;name="McpAppContractError"};});var ho=k(()=>{g();});var _o=k(()=>{g();Ce();Te();Hn();ho();});function To(e,n){return Eo.add(e),n!==void 0&&Ac.set(e,n),e}function Xe(e){return e!==null&&typeof e=="object"&&Eo.has(e)}var Eo,Ac,zn=k(()=>{g();Eo=new WeakSet,Ac=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 Ee("LINEAGE_INVALID",e)}function Tc(e){throw new Ee("LINEAGE_STALE",e)}function Po(e){if(!ln(e)||!Kt(e,mc,hc)||!ln(e.actions))return ee("Lineage definition shape is invalid");for(let n of Object.values(e.actions))if(!ln(n)||!Kt(n,_c,Ec))return ee("Lineage action definition shape is invalid");return e}function Dc(e){if(!ln(e)||!Kt(e,Ic,gc))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 Nc(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 bc(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(Dc),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||!bc(a.definition,i))return Tc("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 Ee("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=Nc(r[s].definition,t);if(d.length>0)throw new Ee("LINEAGE_INVALID",`Lineage compatibility failed: ${d.join(", ")}`,d)}return Object.freeze({entries:Object.freeze(r),current:t})}var Ee,Do,Ic,gc,mc,hc,_c,Ec,qt=k(()=>{g();Ce();Te();Ee=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}$/,Ic=["version","hash","definition"],gc=["sourceHash","compat"],mc=["id","version","actions"],hc=["sourceHash","usage","detailPanel","displayModes","renderer","surfaces","stateProjection","dataPaths","summaryProjection","legacy"],_c=["capabilities"],Ec=["inputKeys","dataInputs","confirmation","resultProjection","content","env","schedule","job","jobAccess"];});var So,Mo,Oo,Lo,Ro=k(()=>{g();So="text/html;profile=mcp-app",Mo=["crewx_app_terminal_connect","crewx_app_html_viewer_open"],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"&&Pc.includes(e)}function Jn(e,n){return e==="card"&&n?.type==="core"&&un(n.handler)}var Pc,Gn=k(()=>{g();Pc=Object.freeze(["card.secret-env"]);});function Uo(e,n=[],t){if(e.content!==void 0||e.confirmation!=="none")return "denied";let i=Sc();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 Sc(e){return;}var Co=k(()=>{g();Ce();zn();Gn();});function xc(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 jc(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:Le}),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:Le}),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>Lc)&&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 _e)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>Rc)&&E("TOOL_INVALID","MCP App tools require a meaningful text fallback"),e}function Vc(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=Fc(e),d=[];Array.isArray(e.actions)||E("TOOL_INVALID","Local App actions must be an array");for(let P of e.actions){let U=Re(P.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=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=jc(e.runtime);f.some(P=>P.name===l||P.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:wc,textFallback:`${t} current state is available through its open instance.`,visibility:Object.freeze(["model","app"]),kind:"read",resourceBinding:Le},I=[Object.freeze(A)];if(I.push(...f.map(P=>Object.freeze(P))),u!==void 0){let P={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:Le,actionIds:Object.freeze([...d])};I.push(Object.freeze(P));}let h=[],T=new Set(I.map(P=>P.name));if(u!==void 0)for(let P of e.actions){let U=`${u}__${P.actionId}`;if(U.length>128||!xo.test(U)){h.push(Object.freeze({toolName:U,actionId:P.actionId,reason:"name_too_long"}));continue}if(T.has(U)){h.push(Object.freeze({toolName:U,actionId:P.actionId,reason:"name_collision"}));continue}let $=Uo({actionId:P.actionId,confirmation:r.actions[P.actionId]?.confirmation,content:r.actions[P.actionId]?.content,backend:P.backend},e.modelActions),D=Object.freeze([...Gc($,r.usage,P.backend)]),L={name:U,description:`${U} action`,inputSchema:yn(P.inputSchema),textFallback:`${U} action requests are handled by the open App instance.`,visibility:D,kind:"action",resourceBinding:Le,actionId:P.actionId,actionIds:Object.freeze([P.actionId]),_meta:Object.freeze({ui:Object.freeze({visibility:D})})};I.push(Object.freeze(L)),T.add(U);}let J=vo(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: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])},resourceBinding:Le,resource:J,tools:Object.freeze(I),toolDiagnostics:Object.freeze(h)};return q(j)}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(Bc(n,t),Vo)}function Fc(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 Bc(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 Hc(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 zc(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=Jc(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=Vc(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])},...i===void 0?{}:{provenance:i},resourceBinding:Le,resource:r,tools:Object.freeze(o),toolDiagnostics:Object.freeze([...e.toolDiagnostics??[]])});return ko.has(e)?e:(ko.add(a),a)}function Jc(e){let n=Qt(e.html),t=$n(e.entryHash,"Local App entry hash");if(xc(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 Gc(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 $c(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:Le,tools:e.tools})}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: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 _e)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 Xc(e){return e!==null&&typeof e=="object"&&typeof e.id=="string"&&Number.isSafeInteger(e.version)&&typeof e.hash=="string"}function wo(e,n,t){return `${e}\0${n}\0${t}`}function $n(e,n){return (typeof e!="string"||!Oc.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"||!Uc.test(e))&&E("TOOL_INVALID","MCP App icon is invalid"),e}function $o(e){return (typeof e!="string"||!Cc.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,Oc,Ke,Lc,Rc,Uc,Cc,kc,Le,wc,An,ko,Vo,Zt,Yn=k(()=>{g();_o();Ce();Te();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})$/,Oc=/^[0-9a-f]{64}$/,Ke=8*1024*1024,Lc=8*1024,Rc=16*1024,Uc=/^[a-z][a-z0-9-]{0,63}$/,Cc=new Set(["blue","violet","emerald","amber","rose","sky","slate","indigo"]),kc=new Set(Mo),new Set(Oo),Le=Object.freeze({kind:"instance"}),wc=Object.freeze({type:"object",properties:Object.freeze({}),additionalProperties:false}),An=new WeakSet,ko=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=Hc(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(zc),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,Wc(u)),u.definition&&this.addDefinition(u.definition);for(let u of l)this.registrationById.set(u.appId,u),this.launcherById.set(u.appId,$c(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(!Xc(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(wo(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=wo(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 Kc(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},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=Kc(e);Ho({localApps:[t],definitions:[e.definition]});}var Xo=k(()=>{g();Yn();});function Ko(){return Object.freeze({[ni]:{candidates:new Map,assetCatalogs:new Map,preparedCandidates:new Map}})}function Yc(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=Yc(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=k(()=>{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 ed(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){ed(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 nd(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,Qc,Qo,Ze,nt,nr,tr,di=k(()=>{g();_=class extends Error{constructor(t){super(t);this.code=t;}code;name="AppDiscoveryFsError"},ri=fs$1.constants.O_NOFOLLOW,Qc=fs$1.constants.O_NONBLOCK,Qo=fs$1.constants.O_RDONLY|(ri??0)|(Qc??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(nd)}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"&&Ie.test(e)?e:void 0}function cd(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 dd(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 pd(e){if(e instanceof Uint8Array)return new Uint8Array(e);if(e instanceof ArrayBuffer)return new Uint8Array(e.slice(0));if(Array.isArray(e)&&e.every(n=>Number.isInteger(n)&&n>=0&&n<=255))return Uint8Array.from(e);throw new TypeError("filesystem port returned an invalid byte array")}function ld(e){return sd.decode(e)}function ud(e){return JSON.parse(ld(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 fd(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 be(e,n){let t=n();return Number.isFinite(t)&&Number.isFinite(e)&&t-e<=5e3}function yd(e){if(typeof e.readVerifiedFile=="function")return e.readVerifiedFile;if(typeof e.readFileVerified=="function")return e.readFileVerified}function Ad(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=yd(e);if(!r)throw new _("READ_DENIED");return pd(await r.call(e,n,t,i))}async function ui(e,n,t){let i=Ad(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(dd).filter(o=>o!==null)}function Id(e,n,t,i){return Object.freeze({code:e,...{},source:n,relativePath:t})}function gd(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 md(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 hd(e){let n;try{n=ud(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"||!cd(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,J=[];for(let j of a.files){if(!_n(j)||!tt(j,["path","sha256"]))return;let P=ar(j.path);if(!P||typeof j.sha256!="string"||!li.test(j.sha256))return;let U=P.join("/"),$=`${a.packageDir}/${U}`;if(T.has(U)||i.has($))return;T.add(U),i.add($),J.push(Object.freeze({path:U,sha256:j.sha256}));}if(!pe.some(j=>T.has(j))||!T.has("ui/index.html")||(r+=J.length,r>id))return;t.add(a.packageDir),o.push(Object.freeze({packageDir:a.packageDir,...d?{launcher:false}:{},appId:f,definition:Object.freeze({id:A,version:I,hash:h}),lineage:Array.isArray(a.lineage)?a.lineage:[],files:Object.freeze(J.sort((j,P)=>je(j.path,P.path)))}));}return Object.freeze({version:1,packages:Object.freeze(o)})}function xe(e){let n=fd(e);return n==="PATH_ESCAPED"||n==="IDENTITY_CHANGED"||n==="TOCTOU"?"PATH_ESCAPED":n==="LIMIT_EXCEEDED"?"LIMIT_EXCEEDED":"BUNDLE_INTEGRITY"}async function _d(e,n,t,i,r){let o=[],a=async(s,c)=>{if(!be(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 Ed(e){return pe.includes(e)?262144:e==="ui/index.html"?Ke:e==="ui/state.json"?2097152:e.startsWith("ui/assets/")?rd:od}async function cr(e,n,t,i){if(e===void 0)return {packages:[],diagnostics:[],incomplete:false,reservedIds:ad};let r=gd(e.reservedIds),o=[],a=(y,m,N)=>Id(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",td);}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=hd(c);if(l===void 0)return o.push(a("BUNDLE_INTEGRITY","bundle-index.json")),s();if(!md(En(l.packages),r))return o.push(a("BUNDLE_INTEGRITY","bundle-index.json")),s([],false,d);if(!be(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(!be(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(!be(t,i)||T.length>fi)return o.push(a("LIMIT_EXCEEDED","apps")),s(I("LIMIT_EXCEEDED"),true,d);let J=new Map(l.packages.map(y=>[y.packageDir.slice(5),y])),j=T.filter(y=>!J.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 P=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 N=`${y.definition.id}\0${String(y.definition.version)}`,b=$.get(N)??[];b.push(y),$.set(N,b);}for(let y of [...U.values(),...$.values()])if(y.length>1)for(let m of y)P.add(m);let D=[],L=c.byteLength,S=false;for(let y of l.packages){if(!be(t,i)){S=true,D.push({indexEntry:y,failureCode:"LIMIT_EXCEEDED"});continue}let m;try{let C=y.lineage[y.lineage.length-1];if(!C)throw new Ee("LINEAGE_INVALID","Definition lineage is missing");if(C.definition.id!==y.definition.id||C.version!==y.definition.version||C.hash!==y.definition.hash)throw new Ee("LINEAGE_STALE","Last lineage generation does not match bundle identity");m=Yt(y.lineage,{...C.definition,hash:C.hash}).entries;}catch(C){let M=C instanceof Ee?C.code:"LINEAGE_INVALID";o.push(a(M,y.packageDir)),D.push({indexEntry:y,failureCode:M});continue}let N=T.find(C=>C.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 b;try{let C=await _d(n,e.root,y.packageDir,t,i);if(!be(t,i)){S=!0,D.push({indexEntry:y,failureCode:"LIMIT_EXCEEDED"});continue}let M=y.files.map(B=>B.path);if(C.length!==M.length||C.some((B,Se)=>B!==M[Se])){D.push({indexEntry:y,failureCode:"BUNDLE_INTEGRITY"});continue}b=new Map;let V;for(let B of y.files){if(!be(t,i)){V="LIMIT_EXCEEDED",S=!0;break}if(L>=pi){V="LIMIT_EXCEEDED";break}let Se;try{Se=await sr(n,e.root,`${y.packageDir}/${B.path}`,Ed(B.path));}catch(at){V=xe(at);break}if(!be(t,i)){V="LIMIT_EXCEEDED",S=!0;break}if(L+Se.byteLength>pi){L=pi,V="LIMIT_EXCEEDED";break}if(L+=Se.byteLength,crypto.createHash("sha256").update(Se).digest("hex")!==B.sha256){V="BUNDLE_INTEGRITY";break}b.set(B.path,Se);}if(V!==void 0){D.push({indexEntry:y,failureCode:V});continue}}catch(C){be(t,i)||(S=true),D.push({indexEntry:y,failureCode:xe(C)});continue}D.push({indexEntry:y,lineage:m,files:b,...P.has(y)?{failureCode:"DUPLICATE_ID"}:{}});}return s(D,S,d)}var td,fi,yi,id,od,rd,pi,li,sd,ad,Ai=k(()=>{g();qt();Ue();Gt();Yn();di();td=256*1024,fi=64,yi=128,id=fi*yi,od=2*1024*1024,rd=8*1024*1024,pi=32*1024*1024,li=/^[0-9a-f]{64}$/,sd=new TextDecoder("utf-8",{fatal:true}),ad=Object.freeze({appIds:Object.freeze([]),definitionIds:Object.freeze([])});});var Rr={};Vr(Rr,{AppDiscoveryFsError:()=>_,LOCAL_APP_TOOL_PREFIX:()=>Nd,MCP_APP_WORKSPACE_TOOL_PREFIX:()=>bd,NodeAppDiscoveryFs:()=>Ze,NodeAppDiscoveryFsAdapter:()=>tr,WORKSPACE_APP_TOOL_PREFIX:()=>Qe,createWorkspaceAppScanCache:()=>Ko,defaultAppDiscoveryFs:()=>nt,defaultNodeAppDiscoveryFs:()=>nr,deriveWorkspaceAppToolName:()=>Pd,deriveWorkspaceAppToolNames:()=>mi,discoverWorkspaceAppCandidates:()=>np,discoverWorkspaceApps:()=>hi,isWorkspacePackage:()=>Dd,productAppBundleReservations:()=>En,scanWorkspaceApps:()=>tp});function Dd(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"||!Ie.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 Pd(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 Md(e,n){return n.length===0||n==="."||n===".."||/[\\/\u0000]/.test(n)?e==="skills"?"skills":"apps":`${e==="skills"?"skills":"apps"}/${n}`}function Od(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 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 Tr(e){return Sd.decode(e)}function Rd(e){return JSON.parse(Tr(e))}function Ud(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 Cd(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 Pe(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 wd(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=xd(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 xd(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 jd(){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"&&Vd(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 Vd(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 Bd(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 Pe(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(Fd.map(I));if(!Pe(a,s))return {timeLimitReached:true};let J=typeof c=="function"&&h.every(S=>S!==void 0),j=h.filter(S=>S!==void 0),P=[...j,...T.filter(S=>S!==void 0)],U=new Map,$=l!==void 0&&J,D;if(l!==void 0&&typeof c=="function"){let S=await Promise.all(l.files.map(async y=>{if(!Pe(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;U.set(m.relativePath,N),D??=N.candidateRealPath,(N.candidateRealPath!==l.candidateRealPath||!Sr(N,m.fingerprint)||Mr(N,o))&&($=false);}}let L=l!==void 0&&l.directoryListings.length===P.length&&l.directoryListings.every((S,y)=>S.relativePath===P[y]?.relativePath&&S.key===P[y]?.key);return l!==void 0&&J&&L&&$&&D===l.candidateRealPath?{memo:l}:!J||j.length!==Ar.length?{}:{context:{state:r,cacheKey:d,workspaceRoot:n,scanStartedAtNs:o,directoryListings:Object.freeze(P),priorFingerprints:U,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 Hd(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 zd(e,n){let t={...e.definition,sourceHash:n},i;try{i=ie(t);}catch(o){throw o instanceof R&&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 Jd(e,n){return e.actions.some(t=>t.backend.type==="core"&&t.backend.handler!=="state.set"&&!Jn(n,t.backend))}function Gd(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=Gd(e);if(!r)throw new _("READ_DENIED");return Ld(await r.call(e,n,t,i))}async function $d(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 Wd(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 Xd(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 Kd(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 Wd(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 _e?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 Yd(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=Ud(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(M=>({actionId:M.actionId,inputSchema:M.inputSchema})));}catch(M){if(M instanceof _e){v(n,br(M.code));return}throw M}let s;try{s=await Nn(e,n,"ui/index.html",Ke);}catch(M){v(n,Ve(ne(M),"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(M){v(n,Ve(ne(M),"initial"));return}if(u.byteLength>2097152){v(n,"LIMIT_EXCEEDED");return}try{let M=Rd(u),V=o.dataPaths??[],B=wt(M,V);l=ae(B,0,V),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=Hd(A,s,u??new Uint8Array),T;try{T=zd(I,h);}catch(M){if(M instanceof oe){v(n,Cd(M));return}throw M}let J;if(n.bundleLineage!==void 0){let M=n.bundleLineage[n.bundleLineage.length-1];if(!M){v(n,"LINEAGE_INVALID");return}let{legacy:V,...B}=M.definition,{hash:Se,...at}=T;if(Z(B)!==Z(at)){v(n,"LINEAGE_STALE");return}if(V!==void 0&&(T={...T,legacy:V}),V!==void 0)try{T={...T,hash:ie(T)},ce(T);}catch{v(n,"LINEAGE_INVALID");return}J=n.bundleLineage;}if(n.bundleIdentity!==void 0&&n.bundleIdentity.appId!==o.pluginId){v(n,"BUNDLE_INTEGRITY");return}if(n.bundleIdentity!==void 0&&(n.bundleIdentity.definitionId!==T.id||n.bundleIdentity.version!==T.version||n.bundleIdentity.definitionHash!==T.hash)){v(n,"LINEAGE_STALE");return}let j=await vd(e,n,i.mcpb?.icon),P=mi(o.pluginId),U=o.actions.length===0?{read:P.read}:P,$=ve(I),D=ve(A),L=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})}}),b={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},...j.iconFile===void 0?{}:{iconFile:Object.freeze({...j.iconFile})},...j.iconDiagnostics.length===0?{}:{iconDiagnostics:Object.freeze([...j.iconDiagnostics])},definition:L,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(U)},C=n.provenance===void 0?{...b,source:n.source}:{...b,provenance:n.provenance,lineage:J??[]};n.candidate=Object.freeze(C),Jd(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 qd(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 Zd(e,n,t,i=Td,r=false,o=new Set){let a=Yd(e),s=Xd(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 Qd(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 ep(e,n){if(Qd(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}=ep(n,t),o=r.clock??jd,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,J=new Set,j=true;l.push(...s.diagnostics.map(D=>({source:D.source,root:r.productBundle?.root??e,name:"",relativePath:D.relativePath,diagnostic:D})));let P=s.reservedIds;s.incomplete&&(f="time_limit");for(let D of s.packages){if(!Pe(c,o)){A=true,f="time_limit";break}let L=D.indexEntry,S=L.packageDir,y=D.files===void 0?void 0:wd(S,D.files),m=s.indexHash===void 0?void 0:To(Object.freeze({kind:"bundled",launcher:L.launcher!==false,indexHash:s.indexHash,packageDir:S,appId:L.appId,definitionId:L.definition.id,version:L.definition.version,definitionHash:L.definition.hash,files:L.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:L.appId,definitionId:L.definition.id,version:L.definition.version,definitionHash:L.definition.hash},identity:kd(L)};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 b={};for(let C of pe){let M=D.files?.get(C);M!==void 0&&(b[C]=M);}if(!gi(b)){v(N,"BUNDLE_INTEGRITY");continue}if(await _r(i,N,b),!Pe(c,o)){A=true,f="time_limit";break}}let U=[{source:"apps",directory:"apps"},{source:"skills",directory:"skills"}];e:for(let D of U){let{source:L,directory:S}=D,y;try{y=await $d(i,e,S);}catch(N){if(ne(N)==="NOT_FOUND")continue;T=false,j=false,l.push({source:L,root:e,name:"",relativePath:L,diagnostic:it(Ve(ne(N),"manifest"),L,L)});continue}let m=y.filter(N=>N.kind==="directory"||N.kind==="symlink").filter(N=>Od(N.name)).map(N=>({source:L,root:e,name:N.name,relativePath:Md(L,N.name)})).sort((N,b)=>Dn(N.relativePath,b.relativePath));for(let N of m){let b={...N};if(l.push(b),h!==void 0?J.add(Pr(h,b)):T=false,!Pe(c,o)){A=true,f="time_limit";break e}let C;if(I!==void 0&&h!==void 0){try{let B=await Bd(i,e,h,b,I,d,c,o);if(B.timeLimitReached){A=!0,f="time_limit";break e}b.scanContext=B.context,C=B.memo;}catch(B){T=false,v(b,Ve(ne(B),"manifest"));continue}C===void 0&&(T=false);}if(C!==void 0){if(b.candidate=C.candidate,b.diagnostic=C.diagnostic,b.identity=C.identity,L==="skills"&&C.candidate===void 0&&C.diagnostic===void 0)continue;if(u>=64){v(b,"LIMIT_EXCEEDED");continue}if(N.relativePath.split("/").length-1>2){v(b,"LIMIT_EXCEEDED");continue}if(u+=1,!Pe(c,o)){A=true,f="time_limit";break e}continue}let M;if(L==="skills"&&(M=await qd(i,b),M===void 0)){b.diagnostic===void 0&&Ii(b);continue}if(u>=64){v(b,"LIMIT_EXCEEDED");continue}if(N.relativePath.split("/").length-1>2){v(b,"LIMIT_EXCEEDED");continue}if(!Pe(c,o)){A=true,f="time_limit";break e}if(u+=1,M===void 0){let B=await Lr(i,b);if(B.failure!==void 0||!gi(B.files)){v(b,B.failure??Ve("NOT_FOUND","manifest")),Ii(b);continue}M=B.files;}if(await _r(i,b,M),Ii(b),!Pe(c,o)){A=true,f="time_limit";break e}}}if(I!==void 0&&h!==void 0){let D=[...J].sort(Dn),L=I.lastCandidateKeys,S=L!==void 0&&L.length===D.length&&L.every((m,N)=>m===D[N]);if(T=T&&S,j&&!A&&f===void 0)for(let m of I.candidates.keys())try{JSON.parse(m)[0]===h.realPath&&!J.has(m)&&I.candidates.delete(m);}catch{I.candidates.delete(m);}let y=[...I.candidates.keys()].filter(m=>{try{return JSON.parse(m)[0]===h.realPath}catch{return false}});T=T&&y.length===J.size&&y.every(m=>J.has(m))&&!A&&f===void 0,I.lastCandidateScanUnchanged=T,j&&!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 $=Kd(l,r,P);return Zd(l,f,s.indexHash,P,r.productBundle!==void 0,$)}var Td,Qe,Nd,bd,dr,Sd,Ar,Fd,Ir,np,tp,Ur=k(()=>{g();Ce();bn();Te();mo();Xt();Ue();Yn();Xo();Gn();Hn();qo();di();zn();Ai();Ai();Td=En([]);Qe="crewx_local_app_",Nd=Qe,bd=Qe;dr=["bundled","apps","skills"],Sd=new TextDecoder("utf-8",{fatal:true});Ar=["","/ui"],Fd=["/dist"],Ir=2000000000n;np=hi,tp=hi;});g();var Cr="SKILL.md",ap=/^---\s*\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;function kr(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function cp(e){return e.isDirectory()||e.isSymbolicLink()}function jr(e){try{return fs$1.existsSync(e)&&fs$1.statSync(e).isDirectory()}catch{return false}}var dp=["index.js","main.js"];function Df(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 dp){let o=path.resolve(e,r);if(fs$1.existsSync(o))return o}}function pp(e){let n;try{n=fs$1.readFileSync(e,"utf8");}catch{return {frontmatter:{},readable:false,valid:false,hasFrontmatter:false}}let t=n.match(ap);if(!t)return {frontmatter:{},readable:true,valid:true,hasFrontmatter:false};try{let i=jsYaml.load(t[1]??"");if(!kr(i))return {frontmatter:{},readable:!0,valid:!1,hasFrontmatter:!0};let r=kr(i.metadata)?i.metadata:void 0;return {frontmatter:{...typeof i.name=="string"?{name:i.name}:{},...typeof(r?.version??i.version)=="string"?{version:r?.version??i.version}:{},...typeof i.description=="string"?{description:i.description}:{}},readable:!0,valid:!0,hasFrontmatter:!0}}catch{return {frontmatter:{},readable:true,valid:false,hasFrontmatter:true}}}function lp(e){return [path.join(e,Cr),path.join(e,"skill",Cr)]}function rt(e,n){if(!jr(e))return null;for(let t of lp(e)){if(!fs$1.existsSync(t))continue;let r=pp(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(cp)}catch{return []}}function up(e){return e.length===0||/[\\\u0000]/.test(e)?false:e.split("/").every(n=>n.length>0&&n!=="."&&n!=="..")}function wr(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))wr(rt(path.join(o,a.name),a.name),t,n);continue}wr(rt(path.join(i,r.name),r.name),t,n);}return n.sort((i,r)=>i.name.localeCompare(r.name))}function fp(e,n){if(!up(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 Nf(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 bf=st,Pf=fp;
2
+ exports.discover=st;exports.discoverBundledProductSkills=Nf;exports.discoverSkills=bf;exports.findEntrypoint=Df;exports.readSkillFrontmatter=pp;exports.resolve=fp;exports.resolveSkill=Pf;