@crewx/sdk 0.9.0-rc.146 → 0.9.0-rc.148

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 li=require('crypto'),net=require('net'),q=require('fs'),promises=require('fs/promises'),ie=require('path'),Ar=require('js-yaml'),Pr=require('os'),Dr=require('tar'),zlib=require('zlib');function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var li__namespace=/*#__PURE__*/_interopNamespace(li);var q__namespace=/*#__PURE__*/_interopNamespace(q);var ie__namespace=/*#__PURE__*/_interopNamespace(ie);var Ar__namespace=/*#__PURE__*/_interopNamespace(Ar);var Pr__namespace=/*#__PURE__*/_interopNamespace(Pr);var Dr__namespace=/*#__PURE__*/_interopNamespace(Dr);var v=(e,n)=>()=>(e&&(n=e(e=0)),n);var g=v(()=>{});var O,Tn=v(()=>{g();O=class extends Error{constructor(t,i=t,o){super(i);this.code=t;this.currentRevision=o;}code;currentRevision;name="UiRuntimeError"};});function ot(e){return jr.test(e)||Fr.test(e)}function ce(){throw new O("INPUT_INVALID","JSON value is not projection-safe")}function zr(e){let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function tt(e,n,t,i,o,r){if(n>i&&ce(),e===null||typeof e=="string"||typeof e=="boolean")return typeof e=="string"&&(Vr.test(e)||Hr.test(e)&&!Wr(o,r)||Br.test(e))&&ce(),e;if(typeof e=="number")return Number.isFinite(e)||ce(),e;(typeof e!="object"||e===void 0||typeof e=="function"||typeof e=="bigint")&&ce();let s=e;t.has(s)&&ce(),t.add(s);try{if(Array.isArray(e))return e.map(c=>tt(c,n+1,t,i,o,r));zr(s)||ce();let a={};for(let[c,d]of Object.entries(e))ot(c)&&ce(),a[c]=tt(d,n+1,t,i,[...o,c],r);return a}finally{t.delete(s);}}function Ee(e,n=0,t=[]){(!Number.isInteger(n)||n<0||n>Gr)&&ce(),(!Array.isArray(t)||t.some(o=>typeof o!="string"))&&ce();let i=tt(e,0,new Set,$r+n,[],t);return (i===null||Array.isArray(i)||typeof i!="object")&&ce(),i}function Ge(e,n){if(!e||!n)return false;let t=e.split("."),i=n.split(".");return t.length>=i.length&&i.every((o,r)=>t[r]===o)}function Wr(e,n){if(e.length===0)return false;let t=e.join(".");return n.some(i=>Ge(t,i))}function We(e){try{let n=JSON.stringify(e);return n===void 0&&ce(),n}catch{ce();}}function it(e){return Array.isArray(e)?e.map(it):e!==null&&typeof e=="object"?Object.fromEntries(Object.keys(e).sort().map(n=>[n,it(e[n])])):e}function oe(e){return We(it(e))}function rt(e){return Buffer.byteLength(e,"utf8")}var jr,Fr,Vr,Br,Hr,$r,Gr,Te=v(()=>{g();Tn();jr=/(?:proof|token|secret|password|cookie|authorization|private[_-]?key|stack|exception|plugin[_-]?text)/i,Fr=/(?:url|uri|endpoint|path|file(?:name|path)?|cwd|shell|directory|dir|folder)$/i,Vr=/<\/?[A-Za-z][^>]*>/,Br=/^(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)/,Hr=/^(?:https?|file|ftp|ws|wss):\/\//i;$r=8,Gr=4;});var Ai=v(()=>{g();Te();});var Pn,st=v(()=>{g();Pn=["text/plain","application/json"];});var Ii=v(()=>{g();st();});function Je(e){return Kr.has(e)||Xr.test(e)||Yr.test(e)}var gi,Kr,Xr,Yr,Nn,rn,ye,at,ct,dt,pt,lt,ke=v(()=>{g();gi=["__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"],Kr=new Set(gi),Xr=/(?:proof|token|secret|password|cookie|authorization|private[_-]?key|stack|exception|plugin[_-]?text)/i,Yr=/(?:url|uri|endpoint|path|file(?:name|path)?|cwd|shell|directory|dir|folder)$/i;Nn=/^[A-Za-z0-9_]+$/,rn=/^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)*$/,ye=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,at=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/,ct=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,dt=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/,pt=["blue","violet","emerald","amber","rose","sky","slate","indigo"],lt=["inline","panel"];});function ut(e){return typeof e=="string"&&Pn.includes(e)}var mi=v(()=>{g();st();ke();});function Dn(e){if(!ft(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")&&!Zr(e.out))}function qr(e){return ft(e)?Object.keys(e).every(t=>t==="mediaType"||t==="required")&&Object.hasOwn(e,"mediaType")&&ut(e.mediaType)&&(!Object.hasOwn(e,"required")||typeof e.required=="boolean"):false}function Zr(e){return ft(e)?Object.keys(e).every(t=>t==="mediaType"||t==="range")&&Object.hasOwn(e,"mediaType")&&ut(e.mediaType)&&(!Object.hasOwn(e,"range")||typeof e.range=="boolean"):false}function ft(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}var yt=v(()=>{g();Ii();mi();new TextDecoder("utf-8",{fatal:true,ignoreBOM:true});});function pe(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(o=>o.resultProjection!==void 0)?{id:e.id,version:e.version,...e.renderer===void 0?{}:{renderer:e.renderer},...e.surfaces===void 0?{}:{surfaces:e.surfaces},...e.stateProjection===void 0?{}:{stateProjection:e.stateProjection},...e.dataPaths===void 0?{}:{dataPaths:e.dataPaths},...e.summaryProjection===void 0?{}:{summaryProjection:e.summaryProjection},...e.legacy===void 0?{}:{legacy:e.legacy},...e.usage===void 0?{}:{usage:e.usage},...e.detailPanel===void 0?{}:{detailPanel:e.detailPanel},...e.displayModes===void 0?{}:{displayModes:e.displayModes},...e.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=Ee(t);return li.createHash("sha256").update(oe(i)).digest("hex")}function Pe(e){if(!/^\d+$/.test(String(e.version))||e.version<1||e.id.length<1||e.id.length>128)throw new O("DEFINITION_UNSUPPORTED","UI definition is invalid");if(e.sourceHash!==void 0&&(typeof e.sourceHash!="string"||!es.test(e.sourceHash)))throw new O("DEFINITION_UNSUPPORTED","UI definition source hash is invalid");if(!/^[0-9a-f]{64}$/.test(e.hash)||pe(e)!==e.hash)throw new O("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=>!ts(i)))throw new O("DEFINITION_UNSUPPORTED","UI action declaration is invalid");if(t.confirmation!==void 0&&t.confirmation!=="none"&&t.confirmation!=="native")throw new O("DEFINITION_UNSUPPORTED","UI action confirmation is invalid");if(t.inputKeys&&(!Array.isArray(t.inputKeys)||t.inputKeys.some(i=>typeof i!="string"||!i)))throw new O("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 O("DEFINITION_UNSUPPORTED","UI action data input declaration is invalid");if(t.resultProjection&&At(t.resultProjection),t.content!==void 0&&!Dn(t.content))throw new O("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 O("DEFINITION_UNSUPPORTED","UI action environment declaration is invalid")}if(e.renderer!==void 0&&(!e.renderer||e.renderer.length>128))throw new O("DEFINITION_UNSUPPORTED","UI definition renderer is invalid");if(e.surfaces&&(!Array.isArray(e.surfaces)||e.surfaces.some(n=>!n||n.length>64)))throw new O("DEFINITION_UNSUPPORTED","UI definition surfaces are invalid");if(e.usage!==void 0&&e.usage!=="card"&&e.usage!=="window")throw new O("DEFINITION_UNSUPPORTED","UI definition usage is invalid");if(e.detailPanel!==void 0&&typeof e.detailPanel!="boolean")throw new O("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 O("DEFINITION_UNSUPPORTED","UI definition displayModes are invalid");if(e.usage==="card"&&e.displayModes!==void 0)throw new O("DEFINITION_UNSUPPORTED","Card definitions cannot declare displayModes");if(e.usage==="window"&&e.detailPanel!==void 0)throw new O("DEFINITION_UNSUPPORTED","Window definitions cannot declare detailPanel");if(e.stateProjection&&At(e.stateProjection),e.summaryProjection){At(e.summaryProjection);let n=new Set(e.stateProjection?.allow??[]);if(e.summaryProjection.allow.some(t=>!n.has(t)))throw new O("DEFINITION_UNSUPPORTED","UI summary projection exceeds state projection")}if(e.legacy!==void 0){if(!e.legacy||typeof e.legacy!="object"||Array.isArray(e.legacy)||Object.keys(e.legacy).some(o=>!["readTool","actionTool","hostTools","agentAccess"].includes(o)))throw new O("DEFINITION_UNSUPPORTED","UI legacy metadata is invalid");let n=new Set;for(let[o,r]of [["readTool",e.legacy.readTool],["actionTool",e.legacy.actionTool]])if(r!==void 0){if(ns(r,o==="readTool"),n.has(r.name))throw new O("DEFINITION_UNSUPPORTED","UI legacy tool names collide");n.add(r.name);}let t=e.legacy.hostTools;if(t!==void 0){if(!t||typeof t!="object"||Array.isArray(t))throw new O("DEFINITION_UNSUPPORTED","UI legacy host tools are invalid");let o={"doc.open":"crewx_app_html_viewer_open","pty.connect":"crewx_app_terminal_connect"};for(let[r,s]of Object.entries(t)){if(!Object.hasOwn(o,r)||o[r]!==s||typeof s!="string"||!/^[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(s)||n.has(s))throw new O("DEFINITION_UNSUPPORTED","UI legacy host tools are invalid");n.add(s);}}let i=e.legacy.agentAccess;if(i!==void 0&&(!i||typeof i!="object"||Array.isArray(i)||Object.entries(i).some(([o,r])=>!o||!Object.hasOwn(e.actions,o)||r!=="allowed"&&r!=="denied")))throw new O("DEFINITION_UNSUPPORTED","UI legacy agent access is invalid");if(e.legacy.actionTool!==void 0&&(!i||Object.keys(i).length===0))throw new O("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=>Ge(t,i))))throw new O("DEFINITION_UNSUPPORTED","UI definition dataPaths are invalid")}}function ns(e,n){if(!e||typeof e!="object"||Array.isArray(e))throw new O("DEFINITION_UNSUPPORTED","UI legacy tool metadata is invalid");let t=e,i=["name","description","inputSchema","textFallback","visibility"],o=Object.hasOwn(t,"fixedResult");if(Object.keys(t).some(r=>!i.includes(r)&&!(n&&r==="fixedResult"))||i.some(r=>!Object.hasOwn(t,r))||typeof t.name!="string"||!/^[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(t.name)||typeof t.description!="string"||t.description.trim().length===0||t.description.length>8192||typeof t.textFallback!="string"||t.textFallback.trim().length===0||t.textFallback.length>16384||!t.inputSchema||typeof t.inputSchema!="object"||Array.isArray(t.inputSchema)||!Array.isArray(t.visibility)||t.visibility.length===0||t.visibility.some(r=>r!=="model"&&r!=="app")||new Set(t.visibility).size!==t.visibility.length)throw new O("DEFINITION_UNSUPPORTED","UI legacy tool metadata is invalid");try{let r=Ee(t.inputSchema);if(r.type!==void 0&&r.type!=="object")throw new Error("schema type");if(o){if(!n)throw new Error("fixed result location");let s=t.fixedResult;if(!s||typeof s!="object"||Array.isArray(s))throw new Error("fixed result");let a=s;if(Object.keys(a).sort().join(",")!=="argsPolicy,structuredContent"||a.argsPolicy!=="empty-only"&&a.argsPolicy!=="ignore"||!a.structuredContent||typeof a.structuredContent!="object"||Array.isArray(a.structuredContent))throw new Error("fixed result");let c=Ee(a.structuredContent);if(rt(We(c))>4*1024)throw new Error("fixed result size")}}catch{throw new O("DEFINITION_UNSUPPORTED","UI legacy tool metadata is not projection-safe")}}function At(e){if(!Array.isArray(e.allow)||e.allow.some(n=>!/^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)*$/.test(n)))throw new O("DEFINITION_UNSUPPORTED","UI projection policy is invalid")}function ts(e){return e.length>0&&e.length<=128&&e!=="*"&&e!=="all"&&!/[/*]/.test(e)}var es,xe=v(()=>{g();Te();Tn();yt();es=/^[0-9a-f]{64}$/;});var V,Ke,It=v(()=>{g();V="dist/tools.json",Ke="dist/main.mjs";});var Re,gt=v(()=>{g();Re="window";});function hi(e){if(!Array.isArray(e)||e.length===0)return false;let n=new Set;for(let t of e){if(!is.some(i=>i===t)||n.has(t))return false;n.add(t);}return true}var is,_i=v(()=>{g();is=["CREWX_APP_INSTANCE_ID","CREWX_THREAD_ID"];});function B(e){throw new mt(e)}function As(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 Is(e,n){let t=Object.getOwnPropertyDescriptor(e,n);return (!t||!("value"in t))&&B("CSP_ORIGIN_INVALID"),t.value}function bn(e,n){if(!Object.prototype.hasOwnProperty.call(e,n))return [];let t=Is(e,n);Array.isArray(t)||B("CSP_ORIGIN_INVALID"),Reflect.ownKeys(t).some(r=>typeof r!="string"||r!=="length"&&!/^(?:0|[1-9][0-9]*)$/.test(r))&&B("CSP_ORIGIN_INVALID");let o=[];for(let r=0;r<t.length;r+=1)(!Object.prototype.hasOwnProperty.call(t,r)||typeof t[r]!="string")&&B("CSP_ORIGIN_INVALID"),o.push(t[r]);return Object.keys(t).length!==t.length&&B("CSP_ORIGIN_INVALID"),o}function gs(e){let n;try{n=JSON.stringify(e);}catch{B("CSP_ORIGIN_INVALID");}return n===void 0&&B("CSP_ORIGIN_INVALID"),new TextEncoder().encode(n).byteLength}function Pi(e,n){/\s|\\/u.test(e)&&B("CSP_ORIGIN_INVALID");let t=ps.exec(e);t||B("CSP_ORIGIN_INVALID");let i=t[1].toLowerCase(),o=t[2];(o.includes("@")||o.includes("%")||o.includes("*"))&&B("CSP_ORIGIN_INVALID"),(o.startsWith("[")?ls:us).test(o)||B("CSP_ORIGIN_INVALID"),i==="wss"&&n!=="connectDomains"&&B("CSP_ORIGIN_INVALID");let s;try{s=new URL(e);}catch{B("CSP_ORIGIN_INVALID");}(s.protocol!==`${i}:`||s.username!==""||s.password!==""||s.search!==""||s.hash!=="")&&B("CSP_ORIGIN_INVALID");let a=s.hostname.toLowerCase();if((!a||a.includes("%"))&&B("CSP_ORIGIN_INVALID"),!a.startsWith("[")){let d=a.endsWith(".")?a.slice(0,-1):a;(d.length===0||d.length>253)&&B("CSP_ORIGIN_INVALID"),d.split(".").some(A=>A.length>63||!fs.test(A))&&B("CSP_ORIGIN_INVALID");}let c=s.origin;return (c==="null"||!c.startsWith(`${i}://`))&&B("CSP_ORIGIN_INVALID"),{origin:c,hostname:a}}function ms(e){let n=e.split(".").map(Number);return ((n[0]*256+n[1])*256+n[2])*256+n[3]}function Ni(e,n,t){let i=4294967295<<32-t>>>0;return (e&i)===(n&i)}function Si(e){let n=ms(e);return Ni(n,3221225472,24)?n!==3221225481&&n!==3221225482:ys.some(([t,i])=>Ni(n,t,i))}function hs(e){let n=e.indexOf("::"),t=(n<0?e:e.slice(0,n)).split(":").filter(Boolean),i=n<0?[]:e.slice(n+2).split(":").filter(Boolean);return (n<0?t:[...t,...Array(8-t.length-i.length).fill("0"),...i]).reduce((r,s)=>r<<16n|BigInt(Number.parseInt(s,16)),0n)}function _s(e){let n=hs(e),t=Number(n>>112n),i=Number(n>>96n&0xffffn);if(n>>32n===0xffffn){let o=Number(n&0xffffffffn);return Si([o>>>24&255,o>>>16&255,o>>>8&255,o&255].join("."))}return t<8192||t>16383||t===8193&&i<=511||t===8193&&i===3512||t===8194||t===16383&&i<=4095}function Es(e,n){let t=e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e,i=net.isIP(t);if(i===4)return Si(t);if(i===6)return _s(t);let o=e.toLowerCase().replace(/\.$/,"");return !o||!o.includes(".")||n.has(o)?true:ds.some(r=>o===r||o.endsWith(`.${r}`))}function Di(e){return Object.freeze([...new Set(e.map(n=>n.origin))].sort())}function bi(e){return JSON.stringify({baseUriDomains:[],connectDomains:e.connectDomains,declared:e.declared,frameDomains:e.frameDomains,resourceDomains:[]})}function Mi(e,n={}){if(e===void 0){let y=bi({declared:false,connectDomains:[],frameDomains:[]});return Object.freeze({declared:false,connectDomains:Object.freeze([]),frameDomains:Object.freeze([]),resourceDomains:Object.freeze([]),baseUriDomains:Object.freeze([]),cspHash:li.createHash("sha256").update(y,"utf8").digest("hex")})}As(e)||B("CSP_ORIGIN_INVALID");let t=Reflect.ownKeys(e);t.some(y=>typeof y!="string")&&B("CSP_ORIGIN_INVALID"),t.some(y=>!cs.has(y))&&B("CSP_AXIS_UNKNOWN");let i=bn(e,"connectDomains"),o=bn(e,"frameDomains"),r=bn(e,"resourceDomains"),s=bn(e,"baseUriDomains");(r.length>0||s.length>0)&&B("CSP_AXIS_UNSUPPORTED"),(gs(e)>rs||i.length>Ti||o.length>Ti||i.length+o.length>ss||[...i,...o].some(y=>new TextEncoder().encode(y).byteLength>as))&&B("CSP_LIMIT_EXCEEDED");let c=i.map(y=>Pi(y,"connectDomains")),d=o.map(y=>Pi(y,"frameDomains")),p=new Set((n.runtimeHostnames??[]).map(y=>y.toLowerCase().replace(/\.$/,"")));[...c,...d].some(y=>Es(y.hostname,p))&&B("CSP_ORIGIN_FORBIDDEN");let A={declared:true,connectDomains:Di(c),frameDomains:Di(d)},m=bi(A);return Object.freeze({...A,resourceDomains:Object.freeze([]),baseUriDomains:Object.freeze([]),cspHash:li.createHash("sha256").update(m,"utf8").digest("hex")})}var rs,Ti,ss,as,cs,ds,ps,ls,us,fs,ys,mt,Li=v(()=>{g();rs=4096,Ti=16,ss=32,as=512,cs=new Set(["connectDomains","frameDomains","resourceDomains","baseUriDomains"]),ds=["localhost","local","internal","home.arpa","test","example","invalid","onion","lan","corp","home","intranet","private","localdomain"],ps=/^(https|wss):\/\/([^/?#]+)$/i,ls=/^\[[^\]]+\](?::[0-9]+)?$/,us=/^[^:\[\]]+(?::[0-9]+)?$/,fs=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/,ys=[[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]],mt=class extends Error{constructor(t){super(t);this.code=t;}code;name="UiPluginCspNormalizationError"};});function an(e,n){return n===void 0||n===""?e:e===""?n:n.startsWith("[")?`${e}${n}`:`${e}.${n}`}function f(e,n=e,t,i){throw new ne(e,n,t,i)}function z(e,n){try{return n()}catch(t){throw t instanceof ne?t.withPathPrefix(e):t}}function $(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;try{let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}catch{return false}}function R(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function Xs(e,n){let t={};for(let[i,o]of Object.entries(e))i!==n&&(t[i]=o);return t}function W(e,n,t=[]){let i=new Set([...n,...t]),o=Object.keys(e).find(s=>!i.has(s));o!==void 0&&f("MANIFEST_INVALID","MANIFEST_INVALID",o,"unknown-key");let r=n.find(s=>!R(e,s));r!==void 0&&f("MANIFEST_INVALID","MANIFEST_INVALID",r,"missing-key");}function On(e,n=false,t=false,i=false){return Ds.test(e)||!i&&Ss.test(e)||bs.test(e)||t&&Oi.test(e)||Ms.test(e)&&!(n&&/^\s*data:/i.test(e)&&!Oi.test(e))}function Ln(e,n=new Set,t=0,i=false,o=false,r=""){if(typeof e=="string"){On(e,i,o)&&f("UNSAFE_VALUE","UNSAFE_VALUE",r,"unsafe-value");return}if(!(e===null||typeof e!="object")){(t>8||n.has(e))&&f("MANIFEST_INVALID","MANIFEST_INVALID",r),n.add(e);try{if(Array.isArray(e)){e.forEach((s,a)=>Ln(s,n,t+1,!1,!1,an(r,`[${a}]`)));return}$(e)||f("MANIFEST_INVALID","MANIFEST_INVALID",r);for(let[s,a]of Object.entries(e))Ln(a,n,t+1,i&&t===0&&(s==="name"||s==="description"),o,an(r,s));}finally{n.delete(e);}}}function Ae(e,n){let t=e[n];return typeof t!="string"&&f("MANIFEST_INVALID"),t}function le(e,n,t){let i=e[n];return (!Number.isSafeInteger(i)||i<t)&&f("MANIFEST_INVALID"),i}function ht(e){return Ns.test(e)||f("MANIFEST_INVALID"),e}function Xe(e){return Ps.test(e)||f("TOKEN_INVALID"),e}function Ys(e){return Fi.test(e)||f("MANIFEST_INVALID"),e}function qs(e){$(e)||f("MANIFEST_INVALID");let n={};for(let[t,i]of Object.entries(e)){let o=Ys(t);$(i)||f("MANIFEST_INVALID");let r=i.type;if(r==="text"){W(i,["type","maxLength"]),n[o]={type:r,maxLength:le(i,"maxLength",1)};continue}if(r==="text-list"){W(i,["type","max","itemMaxLength"]),n[o]={type:r,max:le(i,"max",0),itemMaxLength:le(i,"itemMaxLength",1)};continue}if(r==="step-list"){W(i,["type","min","max","labelMaxLength","detailMaxLength"]);let s=le(i,"min",0),a=le(i,"max",1);s>a&&f("MANIFEST_INVALID"),n[o]={type:r,min:s,max:a,labelMaxLength:le(i,"labelMaxLength",1),detailMaxLength:le(i,"detailMaxLength",1)};continue}typeof r=="string"&&f("SCHEMA_TYPE_UNSUPPORTED"),f("MANIFEST_INVALID");}return n}function Zs(e,n,t){let i=e[n];(!i||i.type!==t)&&f("MANIFEST_INVALID");}function Sn(e,n,t){let i=Ae(e,"field");return Fi.test(i)||f("MANIFEST_INVALID"),Zs(n,i,t),i}function Qs(e,n){$(e)||f("MANIFEST_INVALID");let t=e.primitive;switch(typeof t!="string"&&f("MANIFEST_INVALID"),Ks.includes(t)||f("PRIMITIVE_UNKNOWN"),t){case "card-shell":return W(e,["primitive"]),{primitive:t};case "meta-banner":return W(e,["primitive","badgeToken","noticeToken"]),{primitive:t,badgeToken:Xe(Ae(e,"badgeToken")),noticeToken:Xe(Ae(e,"noticeToken"))};case "heading":return W(e,["primitive","field"]),{primitive:t,field:Sn(e,n,"text")};case "labeled-text":return W(e,["primitive","titleToken","field","variant"]),e.variant!=="callout"&&f("MANIFEST_INVALID"),{primitive:t,titleToken:Xe(Ae(e,"titleToken")),field:Sn(e,n,"text"),variant:"callout"};case "step-flow":return W(e,["primitive","titleToken","field"]),{primitive:t,titleToken:Xe(Ae(e,"titleToken")),field:Sn(e,n,"step-list")};case "text-list":{W(e,["primitive","titleToken","field"],["emptyToken","hideWhenEmpty"]);let i={primitive:t,titleToken:Xe(Ae(e,"titleToken")),field:Sn(e,n,"text-list")};return R(e,"emptyToken")&&(i.emptyToken=Xe(Ae(e,"emptyToken"))),R(e,"hideWhenEmpty")&&(typeof e.hideWhenEmpty!="boolean"&&f("MANIFEST_INVALID"),i.hideWhenEmpty=e.hideWhenEmpty),i}}return f("MANIFEST_INVALID")}function ea(e,n){return Array.isArray(e)||f("MANIFEST_INVALID"),e.map(t=>Qs(t,n))}function J(e="v2 manifest exceeds a contract limit",n,t){return f("LIMIT_EXCEEDED",e,n,t)}function de(e="initial state is not projection-safe"){return f("INITIAL_STATE_INVALID",e)}function Ri(e,n){return (typeof e!="string"||e.length===0||e.length>4096||e.trim().length===0||Gs.test(e)||Ws.test(e))&&f("MANIFEST_INVALID",`${n} is invalid`),(On(e,true,true)||Ls.test(e)||Os.test(e)||Rs.test(e))&&f("UNSAFE_VALUE",`${n} contains an unsafe value`),e}function _t(e,n){return (typeof e!="string"||!ye.test(e))&&f("MANIFEST_INVALID",`${n} is invalid`),e}function na(e){return (typeof e!="string"||!at.test(e)||e==="*"||e==="all")&&f("MANIFEST_INVALID","action capability is invalid"),e}function Vi(e){return (typeof e!="string"||!$s.test(e))&&f("MANIFEST_INVALID","resource hash is invalid"),e}function Et(e,n=new Set,t=0,i=""){if(typeof e=="string"){e.length>4096&&J("v2 manifest string is too long",i,"string-too-long");return}if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){Number.isFinite(e)||f("MANIFEST_INVALID","v2 manifest contains a non-finite number",i,"non-finite-number");return}(e===void 0||typeof e=="function"||typeof e=="bigint")&&f("MANIFEST_INVALID","v2 manifest contains a non-JSON value",i,"non-json-value"),typeof e!="object"&&f("MANIFEST_INVALID","MANIFEST_INVALID",i),t>8&&J("v2 manifest nesting is too deep",i,"too-deep"),n.has(e)&&f("MANIFEST_INVALID","v2 manifest contains a cycle",i,"cycle"),n.add(e);try{if(Array.isArray(e)){e.length>128&&J("v2 manifest array is too long",i,"array-too-long"),e.forEach((o,r)=>Et(o,n,t+1,an(i,`[${r}]`)));return}$(e)||f("MANIFEST_INVALID","v2 manifest contains a non-plain object",i,"non-plain-object");for(let[o,r]of Object.entries(e))Et(r,n,t+1,an(i,o));}finally{n.delete(e);}}}function Bi(e){return (typeof e!="string"||e.length>4096||!rn.test(e))&&(typeof e=="string"&&e.length>4096&&J("projection path is too long"),f("MANIFEST_INVALID","projection paths must be canonical exact paths")),e.split(".").some(t=>Je(t))&&f("MANIFEST_INVALID","projection paths cannot address reserved state keys"),e}function Tt(e){$(e)||f("MANIFEST_INVALID","projection policy must be an object"),W(e,["allow"]),Array.isArray(e.allow)||f("MANIFEST_INVALID","projection allow must be an array"),e.allow.length>128&&J("projection allowlist is too long");let n=[],t=new Set;for(let i of e.allow){let o=Bi(i);t.has(o)&&f("MANIFEST_INVALID","projection allowlist contains a duplicate path"),t.add(o),n.push(o);}return {allow:n}}function ta(e,n){if(e===void 0)return;Array.isArray(e)||f("MANIFEST_INVALID","dataPaths must be an array"),e.length>Js&&J("dataPaths exceed the v2 limit");let t=[],i=new Set;for(let o of e){let r=Bi(o);i.has(r)&&f("MANIFEST_INVALID","dataPaths contain a duplicate path"),n.some(s=>Ge(r,s))||f("MANIFEST_INVALID","dataPaths must be projection-allowed"),i.add(r),t.push(r);}return t}function Ye(e,n,t=Number.MAX_SAFE_INTEGER){return (!Number.isSafeInteger(e)||e<0||e>t)&&f("MANIFEST_INVALID",`${n} is invalid`),e}function wi(e,n){return (typeof e!="number"||!Number.isFinite(e))&&f("MANIFEST_INVALID",`${n} is invalid`),e}function Pt(e,n=0,t=new Set){if(typeof e=="string")return (e.length>4096||On(e))&&f("UNSAFE_VALUE","schema enum contains an unsafe string"),e;if(e===null||typeof e=="boolean")return e;if(typeof e=="number")return Number.isFinite(e)||f("MANIFEST_INVALID","schema enum contains a non-finite number"),e;(n>8||typeof e!="object"||e===void 0)&&J("schema enum is too deep"),t.has(e)&&f("MANIFEST_INVALID","schema enum contains a cycle"),t.add(e);try{if(Array.isArray(e))return e.length>128&&J("schema enum array is too long"),e.map(o=>Pt(o,n+1,t));$(e)||f("MANIFEST_INVALID","schema enum contains a non-plain object");let i={};for(let[o,r]of Object.entries(e))Je(o)&&f("MANIFEST_INVALID","schema enum contains a reserved key"),i[o]=Pt(r,n+1,t);return i}finally{t.delete(e);}}function ia(e,n){if(e===void 0)return;Array.isArray(e)||f("MANIFEST_INVALID","schema required must be an array"),e.length>64&&J("schema required list is too long");let t=[],i=new Set;for(let o of e)(typeof o!="string"||!rn.test(o))&&f("MANIFEST_INVALID","schema required contains an invalid key"),o.length>4096&&J("schema required key is too long"),i.has(o)&&f("MANIFEST_INVALID","schema required contains a duplicate key"),n&&!Object.prototype.hasOwnProperty.call(n,o)&&f("MANIFEST_INVALID","schema required references an undeclared property"),i.add(o),t.push(o);return t}function oa(e,n){let t=n?rn:Nn;return e.length>4096&&J("schema property name is too long"),(!t.test(e)||e.split(".").some(i=>Je(i)))&&f("MANIFEST_INVALID","schema property name is invalid"),e}function Nt(e,n=0,t=false){$(e)||f("MANIFEST_INVALID","action inputSchema must be an object"),n>8&&J("action inputSchema is too deep");let i=e.type;i!=="object"&&i!=="string"&&i!=="number"&&i!=="integer"&&i!=="boolean"&&i!=="array"&&i!=="null"&&(typeof i=="string"&&f("SCHEMA_TYPE_UNSUPPORTED","action inputSchema type is unsupported"),f("MANIFEST_INVALID","action inputSchema type is required"));let o=["type","enum"];i==="string"&&o.push("minLength","maxLength"),i==="array"&&o.push("minItems","maxItems","items"),i==="object"&&o.push("minProperties","maxProperties","properties","required","additionalProperties"),(i==="number"||i==="integer")&&o.push("minimum","maximum"),W(e,["type"],o.filter(a=>a!=="type"));let r={type:i};if(R(e,"enum")&&(Array.isArray(e.enum)||f("MANIFEST_INVALID","schema enum must be an array"),e.enum.length>128&&J("schema enum is too long"),r.enum=e.enum.map(a=>Pt(a))),i==="string"&&(R(e,"minLength")&&(r.minLength=Ye(e.minLength,"schema minLength",4096)),R(e,"maxLength")&&(r.maxLength=Ye(e.maxLength,"schema maxLength",4096)),r.minLength!==void 0&&r.maxLength!==void 0&&r.minLength>r.maxLength&&f("MANIFEST_INVALID","schema string length bounds are inverted")),(i==="number"||i==="integer")&&(R(e,"minimum")&&(r.minimum=wi(e.minimum,"schema minimum")),R(e,"maximum")&&(r.maximum=wi(e.maximum,"schema maximum")),r.minimum!==void 0&&r.maximum!==void 0&&r.minimum>r.maximum&&f("MANIFEST_INVALID","schema numeric bounds are inverted")),i==="array"&&(R(e,"minItems")&&(r.minItems=Ye(e.minItems,"schema minItems",128)),R(e,"maxItems")&&(r.maxItems=Ye(e.maxItems,"schema maxItems",128)),r.minItems!==void 0&&r.maxItems!==void 0&&r.minItems>r.maxItems&&f("MANIFEST_INVALID","schema array length bounds are inverted"),R(e,"items")&&(r.items=Nt(e.items,n+1,false))),i==="object"){let a;if(R(e,"properties")){$(e.properties)||f("MANIFEST_INVALID","schema properties must be an object");let d=Object.entries(e.properties);d.length>64&&J("schema properties are too many"),a={};for(let[p,A]of d){let m=oa(p,t);a[m]=Nt(A,n+1,false);}r.properties=a;}R(e,"minProperties")&&(r.minProperties=Ye(e.minProperties,"schema minProperties",64)),R(e,"maxProperties")&&(r.maxProperties=Ye(e.maxProperties,"schema maxProperties",64)),r.minProperties!==void 0&&r.maxProperties!==void 0&&r.minProperties>r.maxProperties&&f("MANIFEST_INVALID","schema object property bounds are inverted");let c=ia(e.required,a);c!==void 0&&(r.required=c),R(e,"additionalProperties")&&(e.additionalProperties!==false&&f("MANIFEST_INVALID","schema additionalProperties must be false"),r.additionalProperties=false);}let s=JSON.stringify(r);return (s===void 0||Buffer.byteLength(s,"utf8")>65536)&&J("action inputSchema subtree is too large"),r}function ra(e){let n=Nt(e,0,true);return (n.type!=="object"||!n.properties)&&f("MANIFEST_INVALID","action inputSchema must declare object properties"),n}function sa(e){if($(e)||f("MANIFEST_INVALID","action backend must be an object"),e.type==="core"){W(e,js);let n=e.handler;return (typeof n!="string"||!ct.test(n))&&f("MANIFEST_INVALID","core backend handler is invalid"),{type:"core",handler:n}}if(e.type==="skill"&&R(e,"entry"))return W(e,Bs),e.entry!==Ke&&f("MANIFEST_INVALID",`skill backend entry must be ${Ke}`),{type:"skill",entry:Ke};if(e.type==="skill"){W(e,Fs,Vs),(!Array.isArray(e.command)||e.command.length===0||e.command.length>16)&&f("MANIFEST_INVALID","skill backend command is invalid");let n=[];for(let i of e.command)(typeof i!="string"||i.length===0||i.length>256||!dt.test(i))&&f("MANIFEST_INVALID","skill backend command token is invalid"),n.push(i);let t=R(e,"env")?ca(e.env):void 0;return {type:"skill",command:n,...t===void 0?{}:{env:t}}}f("MANIFEST_INVALID","action backend type is unsupported");}function aa(e){$(e)||f("MANIFEST_INVALID","action must be an object"),W(e,ks,xs),R(e,"_meta")&&z("_meta",()=>Hi(e._meta));let n=z("actionId",()=>_t(e.actionId,"actionId"));ot(n)&&f("MANIFEST_INVALID",`actionId "${n}" is not projection-safe`,"actionId");let t=z("capability",()=>na(e.capability)),i=e.mutation;typeof i!="boolean"&&f("MANIFEST_INVALID","action mutation must be boolean","mutation");let o=z("inputSchema",()=>ra(e.inputSchema)),r;if(R(e,"dataInputs")){Array.isArray(e.dataInputs)||f("MANIFEST_INVALID","action dataInputs must be an array","dataInputs");let p=o.properties,A=new Set,m=[];for(let y of e.dataInputs)(typeof y!="string"||!R(p,y)||A.has(y))&&f("MANIFEST_INVALID","action dataInputs must be unique declared properties","dataInputs"),A.add(y),m.push(y);r=m;}let s=z("resultProjection",()=>Tt(e.resultProjection)),a=z("backend",()=>sa(e.backend)),c;R(e,"content")&&((a.type!=="skill"||!Dn(e.content))&&f("MANIFEST_INVALID","action content declaration is invalid","content"),c=da(e.content));let d;if(R(e,"confirmation")){let p=e.confirmation;p!=="none"&&p!=="native"&&f("MANIFEST_INVALID","action confirmation is invalid","confirmation"),d=p;}return {actionId:n,capability:t,mutation:i,inputSchema:o,resultProjection:s,backend:a,...c===void 0?{}:{content:c},...r===void 0?{}:{dataInputs:r},...d===void 0?{}:{confirmation:d}}}function ca(e){return hi(e)||f("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 pa(e){return $(e)||f("INITIAL_STATE_INVALID","initialState must be an object"),W(e,Hs,zs),e.path!=="ui/state.json"&&f("MANIFEST_INVALID","initialState path is not fixed"),R(e,"hash")?{path:"ui/state.json",hash:Vi(e.hash)}:{path:"ui/state.json"}}function la(e){let n=["wasm","terminal","htmlDocuments"];return (!$(e)||Object.keys(e).length===0||Object.keys(e).some(t=>!n.includes(t)||e[t]!==true))&&f("MANIFEST_INVALID","runtime must contain only known capability flags set to true"),{...e.wasm===true?{wasm:true}:{},...e.terminal===true?{terminal:true}:{},...e.htmlDocuments===true?{htmlDocuments:true}:{}}}function ua(e,n){let t;try{t=Mi(e);}catch(i){let o=i!==null&&typeof i=="object"&&"code"in i&&typeof i.code=="string"?i.code:"CSP_ORIGIN_INVALID";return f("MANIFEST_INVALID",o,void 0,o.toLowerCase().replace(/_/g,"-"))}if(t.frameDomains.length>0&&f("MANIFEST_INVALID","external origins in csp are not enabled in this rollout",void 0,"csp-not-enabled"),t.connectDomains.length!==0)return n?.terminal===true&&f("MANIFEST_INVALID","runtime.terminal cannot be combined with csp.connectDomains","connectDomains","terminal-with-connect-domains"),Object.freeze({connectDomains:t.connectDomains})}function fa(e,n){Ln($(e)&&R(e,"csp")?Xs(e,"csp"):e,new Set,0,true,true),Et(e),$(e)||f("MANIFEST_INVALID"),W(e,Us,Cs),R(e,"_meta")&&z("_meta",()=>Hi(e._meta)),e.manifestVersion!==2&&f("MANIFEST_INVALID");let t;R(e,"runtime")&&(t=z("runtime",()=>la(e.runtime)));let i;R(e,"csp")&&(i=z("csp",()=>ua(e.csp,t)));let o=z("pluginId",()=>_t(e.pluginId,"pluginId")),r=z("definitionId",()=>_t(e.definitionId,"definitionId")),s=z("version",()=>le(e,"version",1)),a=z("name",()=>Ri(e.name,"name")),c=z("description",()=>Ri(e.description,"description")),d;R(e,"icon")&&((typeof e.icon!="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(e.icon))&&f("MANIFEST_INVALID","icon is invalid","icon"),d=e.icon);let p;R(e,"tone")&&((typeof e.tone!="string"||!pt.includes(e.tone))&&f("MANIFEST_INVALID","tone is invalid","tone"),p=e.tone),e.entry!=="ui/index.html"&&f("MANIFEST_INVALID","entry path is not fixed","entry","fixed-value");let A;R(e,"entryHash")&&(A=z("entryHash",()=>Vi(e.entryHash)));let m;R(e,"initialState")&&(m=z("initialState",()=>pa(e.initialState)));let y;R(e,"usage")&&(e.usage!=="card"&&e.usage!=="window"&&f("MANIFEST_INVALID","usage is invalid","usage"),y=e.usage);let h;R(e,"detailPanel")&&(typeof e.detailPanel!="boolean"&&f("MANIFEST_INVALID","detailPanel is invalid","detailPanel"),h=e.detailPanel);let L;if(R(e,"displayModes")){((y??Re)!==Re||!Array.isArray(e.displayModes)||e.displayModes.length===0)&&f("MANIFEST_INVALID","displayModes are only valid for window Apps","displayModes");let l=new Set(["inline","floating","focused"]);(new Set(e.displayModes).size!==e.displayModes.length||e.displayModes.some(u=>typeof u!="string"||!l.has(u)))&&f("MANIFEST_INVALID","displayModes are invalid","displayModes"),L=e.displayModes;}(y??Re)===Re&&h!==void 0&&f("MANIFEST_INVALID","detailPanel is card-only","detailPanel");let S=n.mode??"local";S!=="local"&&S!=="installed"&&S!=="published"&&f("MANIFEST_INVALID","manifest mode is invalid"),S!=="local"&&A===void 0&&f("MANIFEST_INVALID","installed manifests require entryHash","entryHash","required-when-installed"),S!=="local"&&m!==void 0&&m.hash===void 0&&f("MANIFEST_INVALID","installed manifests require initialState.hash","initialState.hash","required-when-installed"),(!Array.isArray(e.surfaces)||e.surfaces.length===0)&&f("MANIFEST_INVALID","surfaces are invalid","surfaces"),e.surfaces.length>2&&J("surfaces exceed the v2 limit","surfaces","too-many-items");let j=[],C=new Set;for(let l of e.surfaces)(typeof l!="string"||!lt.includes(l))&&f("MANIFEST_INVALID","surface is unsupported","surfaces"),C.has(l)&&f("MANIFEST_INVALID","surfaces contain a duplicate","surfaces","duplicate-item"),C.add(l),j.push(l);$(e.size)||f("MANIFEST_INVALID","size must be an object","size"),z("size",()=>W(e.size,["height"]));let x=z("size",()=>le(e.size,"height",1));x>720&&J("size.height exceeds the v2 limit","size.height","too-large");let F=z("stateProjection",()=>Tt(e.stateProjection)),E=e.summaryProjection===void 0?void 0:z("summaryProjection",()=>Tt(e.summaryProjection));E!==void 0&&E.allow.some(l=>!F.allow.includes(l))&&f("MANIFEST_INVALID","summaryProjection must be a subset of stateProjection.allow","summaryProjection");let T=z("dataPaths",()=>ta(e.dataPaths,F.allow));Array.isArray(e.actions)||f("MANIFEST_INVALID","actions must be an array","actions"),e.actions.length>32&&J("actions exceed the v2 limit","actions","too-many-items");let U=[],D=new Set;for(let[l,u]of e.actions.entries()){let I=`actions[${l}]`,P=z(I,()=>aa(u));if(D.has(P.actionId)&&f("MANIFEST_INVALID","actions contain a duplicate actionId",`${I}.actionId`,"duplicate-item"),P.backend.type==="core"&&P.backend.handler==="state.set"){P.mutation||f("MANIFEST_INVALID","state.set actions must be mutations",`${I}.mutation`);for(let b of Object.keys(P.inputSchema.properties))F.allow.includes(b)||f("MANIFEST_INVALID","state.set input paths must be projection-allowed",`${I}.inputSchema.properties`);}D.add(P.actionId),U.push(P);}return {manifestVersion:2,pluginId:o,definitionId:r,version:s,name:a,description:c,...d===void 0?{}:{icon:d},...p===void 0?{}:{tone:p},entry:"ui/index.html",...A===void 0?{}:{entryHash:A},...t===void 0?{}:{runtime:t},...i===void 0?{}:{csp:i},...m===void 0?{}:{initialState:m},...y===void 0?{}:{usage:y},...h===void 0?{}:{detailPanel:h},...L===void 0?{}:{displayModes:L},surfaces:j,size:{height:x},stateProjection:F,...E===void 0?{}:{summaryProjection:E},...T===void 0?{}:{dataPaths:T},actions:U}}function Hi(e){$(e)||f("MANIFEST_INVALID","_meta must be an object");let n=JSON.stringify(e);(n===void 0||Buffer.byteLength(n,"utf8")>vs)&&J("_meta exceeds the 4 KiB limit",void 0,"meta-too-large");}function ya(e){let n={},t={};for(let r of e.actions){n[r.actionId]={capabilities:[r.capability],inputKeys:Object.keys(r.inputSchema.properties??{}),...r.dataInputs===void 0?{}:{dataInputs:r.dataInputs},resultProjection:r.resultProjection,...r.confirmation===void 0?{}:{confirmation:r.confirmation},...r.content===void 0?{}:{content:r.content},...r.backend.type!=="skill"||r.backend.env===void 0?{}:{env:r.backend.env}};let s=r.backend.type==="skill"||r.backend.type==="core"&&r.backend.handler==="state.set";t[r.actionId]={actionId:r.actionId,mutation:r.mutation,backend:r.backend,launchPolicy:s?"allowed":"denied",...s?{}:{denialCode:"EXEC_DENIED"}};}let i={id:e.definitionId,version:e.version,renderer:"sandbox-html",...e.usage===void 0?{}:{usage:e.usage},...e.detailPanel===void 0?{}:{detailPanel:e.detailPanel},...e.displayModes===void 0?{}:{displayModes:e.displayModes},surfaces:e.surfaces,stateProjection:e.stateProjection,...e.summaryProjection===void 0?{}:{summaryProjection:e.summaryProjection},...e.dataPaths===void 0?{}:{dataPaths:e.dataPaths},actions:n},o={entry:{path:"ui/index.html",...e.entryHash===void 0?{}:{hash:e.entryHash}},...e.initialState===void 0?{}:{initialState:e.initialState}};return {manifest:e,definition:i,handlers:t,resources:o}}function Dt(e,n,t,i,o,r){if(typeof e=="string"){let s=o.length>0&&r.some(a=>Ge(o.join("."),a));return (e.length>4096||On(e,false,false,s))&&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 s;if(Array.isArray(e))e.length>128&&de("state array is too long"),s=e.map(c=>Dt(c,n,t+1,65536,o,r));else {$(e)||de("state contains a non-plain object");let c={};for(let[d,p]of Object.entries(e))(d.length>4096||!Nn.test(d)||Je(d))&&(d.length>4096&&de("state key is too long"),de("state contains a reserved or invalid key")),c[d]=Dt(p,n,t+1,65536,[...o,d],r);s=c;}let a=JSON.stringify(s);return (a===void 0||Buffer.byteLength(a,"utf8")>i)&&de("state subtree is too large"),s}finally{n.delete(e);}}function St(e,n=[]){$(e)||de("initial state must be a JSON object");let t=Dt(e,new Set,0,65536,[],n);return (t===null||Array.isArray(t)||typeof t!="object")&&de(),t}function Aa(e,n={}){Ln(e),$(e)||f("MANIFEST_INVALID"),W(e,ws),e.manifestVersion!==1&&f("MANIFEST_INVALID");let t=ht(Ae(e,"pluginId")),i=ht(Ae(e,"definitionId")),o=le(e,"version",1),r=le(e,"primitiveSet",1),s=n.supportedPrimitiveSet??Ts;(!Number.isSafeInteger(s)||s<1)&&f("MANIFEST_INVALID"),r>s&&f("PRIMITIVE_SET_UNSUPPORTED"),$(e.activation)||f("MANIFEST_INVALID"),W(e.activation,["kind","language"]),e.activation.kind!=="fenced-code"&&f("MANIFEST_INVALID");let a=ht(Ae(e.activation,"language")),c=qs(e.schema),d=ea(e.layout,c);return {manifestVersion:1,pluginId:t,definitionId:i,version:o,primitiveSet:r,activation:{kind:"fenced-code",language:a},schema:c,layout:d}}function Ia(e,n={}){return $(e)||f("MANIFEST_INVALID"),Object.hasOwn(e,"lineage")&&f("MANIFEST_INVALID","lineage is only allowed in product bundle indexes"),e.manifestVersion===2?fa(e,n):Aa(e,n)}function je(e,n={}){try{return Ia(e,n)}catch(t){if(t instanceof ne)throw t;return f("MANIFEST_INVALID")}}function cn(e,n={}){let t=je(e,n);return t.manifestVersion===2?ya(t):t}var Ts,Ps,Ns,Fi,Ds,bs,Ss,Ms,Oi,Ls,Os,Rs,ws,Us,Cs,ks,xs,vs,js,Fs,Vs,Bs,Hs,zs,$s,Gs,Ws,Js,Ks,ne,Mt=v(()=>{g();gt();Te();yt();_i();It();Li();ke();Ts=1,Ps=/^[a-z][a-zA-Z0-9]*(\.[a-zA-Z0-9]+)+$/,Ns=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,Fi=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,Ds=/<\/?[A-Za-z][^>]*>/,bs=/^(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)/,Ss=/^(?:https?|file|ftp|ws|wss):\/\//i,Ms=/^\s*(?:javascript|data):/i,Oi=/data:[^,\s]*,/i,Ls=/(?:https?|file|ftp|ws|wss):\/\//i,Os=/javascript:/i,Rs=/(?:^[\s]*|[\s"'(=])(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)(?=[^\s"'<>])[^\s"'<>]*/,ws=["manifestVersion","pluginId","definitionId","version","primitiveSet","activation","schema","layout"],Us=["manifestVersion","pluginId","definitionId","version","name","description","entry","surfaces","size","stateProjection","actions"],Cs=["_meta","icon","tone","entryHash","runtime","csp","initialState","usage","detailPanel","displayModes","summaryProjection","dataPaths","focusedAiDataPaths"],ks=["actionId","capability","mutation","inputSchema","resultProjection","backend"],xs=["confirmation","dataInputs","content","_meta"],vs=4*1024,js=["type","handler"],Fs=["type","command"],Vs=["env"],Bs=["type","entry"],Hs=["path"],zs=["hash"],$s=/^[0-9a-f]{64}$/,Gs=/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/,Ws=/[\r\n]/,Js=16,Ks=["card-shell","meta-banner","heading","labeled-text","step-flow","text-list"],ne=class e extends Error{constructor(t,i=t,o,r){super(i);this.code=t;this.path=o;this.rule=r;}code;path;rule;name="UiPluginValidationError";withPathPrefix(t){return new e(this.code,this.message,an(t,this.path),this.rule)}};});function Ki(e){return typeof e=="string"&&e.length<=ma&&ga.test(e)}function w(e,n,t,i,o){throw new ge(e,{path:n,rule:t,...i===void 0?{}:{message:i},...o===void 0?{}:{file:o}})}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 K(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function fe(e){let n=`_meta["${we}"]`;return e===void 0||e===""?n:e.startsWith("[")?`${n}${e}`:`${n}.${e}`}function Ta(e){return e.toLowerCase().replace(/_/g,"-")}function Pa(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 Xi(e,n,t){return {path:t(e.path),rule:e.rule??Ta(e.code),...e.message!==e.code?{message:e.message}:{},file:n}}function Yi(e){return JSON.parse(JSON.stringify(e))}function Rt(e,n,t=0,i=new Set){if(typeof e=="string"){e.length>4096&&w("LIMIT_EXCEEDED",n,"string-too-long"),(ha.test(e)||_a.test(e)||Ea.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((o,r)=>Rt(o,`${n}[${r}]`,t+1,i));return}Z(e)||w("MANIFEST_INVALID",n,"non-plain-object");for(let[o,r]of Object.entries(e))Rt(r,n===""?o:`${n}.${o}`,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 Ze(e,n){return Z(e)||w("MANIFEST_INVALID",n,"object"),e}function Na(e,n){Array.isArray(e)||w("MANIFEST_INVALID",n,"array"),e.forEach((t,i)=>ue(t,`${n}[${i}]`));}function Da(e,n){typeof e!="boolean"&&w("MANIFEST_INVALID",n,"boolean");}function dn(e,n,t,i){for(let o of Object.keys(e))!t.includes(o)&&!i.includes(o)&&w("MANIFEST_INVALID",`${n}.${o}`,"unknown-key");for(let o of t)K(e,o)||w("MANIFEST_INVALID",`${n}.${o}`,"missing-key");}function ba(e,n){switch(Rt(n,e),e){case "long_description":case "homepage":case "documentation":case "support":case "icon":case "license":ue(n,e);return;case "author":{let t=Ze(n,e);dn(t,e,["name"],["email","url"]);for(let i of Object.keys(t))ue(t[i],`${e}.${i}`);return}case "repository":{let t=Ze(n,e);dn(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 o=`${e}[${i}]`,r=Ze(t,o);dn(r,o,["src","size"],["theme"]),ue(r.src,`${o}.src`),ue(r.size,`${o}.size`),K(r,"theme")&&ue(r.theme,`${o}.theme`);});return}case "screenshots":case "keywords":case "privacy_policies":Na(n,e);return;case "tools":{Array.isArray(n)||w("MANIFEST_INVALID",e,"array"),n.forEach((t,i)=>{let o=`${e}[${i}]`,r=Ze(t,o);dn(r,o,["name"],["description"]),ue(r.name,`${o}.name`),K(r,"description")&&ue(r.description,`${o}.description`);});return}case "prompts":{Array.isArray(n)||w("MANIFEST_INVALID",e,"array"),n.forEach((t,i)=>{let o=`${e}[${i}]`,r=Ze(t,o);dn(r,o,["name","text"],["description","arguments"]),ue(r.name,`${o}.name`),ue(r.text,`${o}.text`);});return}case "tools_generated":case "prompts_generated":Da(n,e);return;case "localization":case "compatibility":case "user_config":Ze(n,e);return;default:w("MANIFEST_INVALID",e,"unknown-key");}}function Rn(e){return typeof e=="string"&&ye.test(e)?e:void 0}function qi(e){return Number.isSafeInteger(e)&&e>=1?e:void 0}function Sa(e){let n=Rn(e.name);if(n===void 0)return;let t=e._meta,i=Z(t)?t[we]:void 0,o=Z(i)?i:{},r=K(o,"definitionId")?Rn(o.definitionId):n,s=K(o,"definitionVersion")?qi(o.definitionVersion):1;return {pluginId:n,...r===void 0?{}:{definitionId:r},...s===void 0?{}:{definitionVersion:s}}}function Ma(e){let n=Rn(e.pluginId);if(n===void 0)return;let t=Rn(e.definitionId),i=qi(e.version);return {pluginId:n,...t===void 0?{}:{definitionId:t},...i===void 0?{}:{definitionVersion:i}}}function Ct(e){try{let n=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e));if(!Z(n))return !1;let t=n._meta;return Z(t)&&K(t,we)}catch{return false}}function La(e,n){if(e===re)return n.builtinOnly===true;let t=n._meta,i=Z(t)?t[we]:void 0;return Z(i)&&i.builtinOnly===true}function Oa(e,n){K(e,"server")&&w("MANIFEST_INVALID","server","server-unsupported","phase 1 runs CrewX-owned Apps only");for(let a of Object.keys(e))wt.includes(a)||w("MANIFEST_INVALID",a,"unknown-key");for(let a of Ut)K(e,a)||w("MANIFEST_INVALID",a,"missing-key");e.manifest_version!==Lt&&w("MANIFEST_INVALID","manifest_version","unsupported-version",`manifest_version must be "${Lt}"`),Ki(e.version)||w("MANIFEST_INVALID","version","semver","version must be a semver.org version such as 0.1.0");let t=e._meta;Z(t)||w("MANIFEST_INVALID","_meta","object"),K(t,we)||w("MANIFEST_INVALID",fe(),"missing-key");let i=t[we];Z(i)||w("MANIFEST_INVALID",fe(),"object");for(let a of Object.keys(i))Ot.includes(a)||Ji.includes(a)||w("MANIFEST_INVALID",fe(a),"unknown-key");for(let a of Ot)a==="actions"&&n!==void 0||K(i,a)||w("MANIFEST_INVALID",fe(a),"missing-key");if(n!==void 0&&K(i,"actions")&&w("MANIFEST_INVALID",fe("actions"),"two-truths",`actions are declared in both ${G} and ${V}; a server.ts App keeps them in the tools file only`),Ra(i.actions),K(i,"definitionVersion")){let a=i.definitionVersion;(!Number.isSafeInteger(a)||a<1)&&w("MANIFEST_INVALID",fe("definitionVersion"),"positive-integer");}let o={};for(let a of Wi)K(e,a)&&(ba(a,e[a]),o[a]=Yi(e[a]));let r={};for(let[a,c]of Object.entries(t))a!==we&&(r[a]=c);let s={manifestVersion:2,pluginId:e.name,definitionId:K(i,"definitionId")?i.definitionId:e.name,version:K(i,"definitionVersion")?i.definitionVersion:1,name:e.display_name,description:e.description};for(let[a,c]of Object.entries(i))a==="definitionId"||a==="definitionVersion"||(s[a]=c);return n!==void 0&&(s.actions=n.map(a=>({...a,backend:{type:"skill",entry:Ke}}))),Object.keys(r).length>0&&(s._meta=r),{v2Input:s,...Object.keys(r).length>0?{vendorMeta:r}:{},passthrough:o}}function Ra(e){Array.isArray(e)&&e.forEach((n,t)=>{let i=Z(n)?n.backend:void 0;Z(i)&&K(i,"entry")&&w("MANIFEST_INVALID",fe(`actions[${t}].backend.entry`),"entry-not-authorable",`an action in ${G} cannot name an entry; a server.ts App declares its actions in ${V}`);});}function wa(e,n,t){Z(e)||w("MANIFEST_INVALID","","not-object","manifest.json must be a JSON object",G);let i;try{i=Oa(e,t);}catch(s){throw s instanceof ge?new ge(s.code,{...s.reason,file:G}):s}let o;try{let s=je(i.v2Input,{mode:n.mode??"local"});s.manifestVersion!==2&&w("MANIFEST_INVALID","","v2-required"),o=s;}catch(s){throw s instanceof ne?new ge(s.code,Xi(s,G,Pa)):s}let r=e.tools;if(Array.isArray(r)){let s=new Set(o.actions.map(a=>a.actionId));r.forEach((a,c)=>{let d=a.name;if(!s.has(d))throw new ge("MANIFEST_INVALID",{path:`tools[${c}].name`,rule:"tool-not-action",message:"every tools[].name must be an action id",file:G})});}return {file:G,manifest:o,v2Input:i.v2Input,releaseVersion:e.version,...Object.keys(i.passthrough).length>0?{mcpb:i.passthrough}:{}}}function Ua(e,n){try{let t=je(e,{mode:n.mode??"local"});if(t.manifestVersion!==2)throw new ge("MANIFEST_INVALID",{path:"manifestVersion",rule:"v2-required",message:"a workspace App requires manifestVersion 2",file:re});return {file:re,manifest:t,v2Input:e}}catch(t){throw t instanceof ne?new ge(t.code,Xi(t,re,i=>i??"")):t}}function Qe(e){return pe(cn(e).definition)}function $i(e){let{entryHash:n,initialState:t,...i}=e,o={...i};return t!==void 0&&(o.initialState={path:t.path}),Yi(o)}function Ca(e,n){let t=$i(e),i=$i(n);return [...new Set([...Object.keys(t),...Object.keys(i)])].sort().filter(r=>oe(t[r]??null)!==oe(i[r]??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 xa(e,n){let t=Ca(e,n),i=ka(e,n),o="";try{let r=Qe(e),s=Qe(n);i=i||r!==s,o=` (definition hash ${r.slice(0,12)} vs ${s.slice(0,12)})`;}catch{i=true;}t.length===0&&!i||w("MANIFEST_DUAL_MISMATCH","","dual-manifest-mismatch",`${G} and ${re} normalize to different definitions${o}`+(t.length>0?`; differing fields: ${t.join(", ")}`:""));}function Ie(e,n,t="MANIFEST_INVALID",i){return {code:t,reason:{path:e,rule:n,...i===void 0?{}:{message:i},file:V},files:[]}}function Gi(e){return {...Ie("","tools-needs-manifest-json","MANIFEST_INVALID",`${V} is read with ${G} only`),files:e}}function va(e,n){if(e.byteLength>n)return {failure:Ie("","file-too-large","LIMIT_EXCEEDED")};let t;try{t=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e));}catch{return {failure:Ie("","invalid-json")}}if(!Z(t))return {failure:Ie("","not-object","MANIFEST_INVALID",`${V} must be a JSON object`)};for(let o of Object.keys(t))if(o!=="schemaVersion"&&o!=="actions")return {failure:Ie(o,"unknown-key")};for(let o of ["schemaVersion","actions"])if(!K(t,o))return {failure:Ie(o,"missing-key")};if(t.schemaVersion!==1)return {failure:Ie("schemaVersion","unsupported-version","MANIFEST_INVALID",`schemaVersion must be ${1}`)};let i=t.actions;if(!Array.isArray(i))return {failure:Ie("actions","array")};for(let[o,r]of i.entries()){if(!Z(r))return {failure:Ie(`actions[${o}]`,"object")};if(K(r,"backend"))return {failure:Ie(`actions[${o}].backend`,"tools-backend","MANIFEST_INVALID",`an action in ${V} cannot carry a backend`)}}return {actions:i}}function ja(e,n){let t=n.maxBytes??262144,i=[],o=new TextDecoder("utf-8",{fatal:true});for(let r of X){let s=e[r];if(s===void 0)continue;if(s.byteLength>t)return {parsed:i,failure:{code:"LIMIT_EXCEEDED",reason:{path:"",rule:"file-too-large",file:r},files:[r]}};let a;try{a=JSON.parse(o.decode(s));}catch{return {parsed:i,failure:{code:"MANIFEST_INVALID",reason:{path:"",rule:"invalid-json",file:r},files:[r]}}}if(!Z(a))return {parsed:i,failure:{code:"MANIFEST_INVALID",reason:{path:"",rule:"not-object",message:`${r} must be a JSON object`,file:r},files:[r]}};i.push({file:r,raw:a});}return {parsed:i}}function Fe(e,n={}){let{parsed:t,failure:i}=ja(e,n),o=X.filter(y=>e[y]!==void 0);if(i!==void 0)return {ok:false,rejection:i,parseFailure:true,builtinOnly:false};let r=e[V],s=r===void 0?void 0:va(r,n.maxBytes??262144);if(t.length===0)return {ok:false,rejection:s===void 0?{code:"MANIFEST_INVALID",reason:{path:"",rule:"no-manifest-file",message:"neither manifest.json nor ui-plugin.json is present"},files:[]}:Gi(o),parseFailure:true,builtinOnly:false};let a=t[0],c=a.file===G?Sa(a.raw):Ma(a.raw),d=t.some(y=>La(y.file,y.raw)),p;if(s!==void 0){let y=t.some(h=>h.file===G)?s.failure:Gi(o);if(y!==void 0)return {ok:false,rejection:y,parseFailure:false,...c===void 0?{}:{identity:c},builtinOnly:d};p=s.actions;}let A=[];try{for(let y of t)A.push(y.file===G?wa(y.raw,n,p):Ua(y.raw,n));A.length===2&&xa(A[0].manifest,A[1].manifest);}catch(y){if(y instanceof ge)return {ok:false,rejection:{code:y.code,reason:y.reason,files:y.code==="MANIFEST_DUAL_MISMATCH"?[...X]:y.reason.file===void 0||y.reason.file===V?o:[y.reason.file]},parseFailure:false,...c===void 0?{}:{identity:c},builtinOnly:d};throw y}let m=A[0];return {ok:true,...m,identity:c??{pluginId:m.manifest.pluginId},files:o}}var G,re,X,Lt,we,wt,Ut,Wi,Ot,Ji,ga,ma,ha,_a,Ea,ge,wn=v(()=>{g();xe();Te();It();ke();Mt();G="manifest.json",re="ui-plugin.json",X=[G,re],Lt="0.3",we="dev.crewx",wt=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"]),Ut=Object.freeze(["manifest_version","name","display_name","version","description","_meta"]),Wi=Object.freeze(wt.filter(e=>e!=="server"&&!Ut.includes(e))),Ot=Object.freeze(["entry","surfaces","size","stateProjection","actions"]),Ji=Object.freeze(["definitionId","definitionVersion","icon","tone","entryHash","runtime","initialState","usage","detailPanel","displayModes","summaryProjection","dataPaths","focusedAiDataPaths","csp"]),ga=/^(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,ha=/<\/?[A-Za-z][^>]*>/,_a=/^\s*javascript:/i,Ea=/data:[^,\s]*,/i;ge=class extends Error{constructor(t,i){super(`${t}: ${i.path||"<file>"} (${i.rule})`);this.code=t;this.reason=i;}code;reason};});var kt=v(()=>{g();Ai();wn();Mt();ke();});function Cn(e,n=e){throw new Ce(e,n)}var Ce,kn=v(()=>{g();Ce=class extends Error{constructor(t,i=t){super(i);this.code=t;}code;name="McpAppContractError"};});var co=v(()=>{g();});var po=v(()=>{g();xe();Te();kn();co();});function lo(e,n){return Ya.add(e),n!==void 0&&qa.set(e,n),e}var Ya,qa,xn=v(()=>{g();Ya=new WeakSet,qa=new WeakMap;});function fn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function vt(e,n,t=[]){let i=new Set([...n,...t]),o=Object.keys(e);return n.every(r=>Object.hasOwn(e,r))&&o.every(r=>i.has(r))}function yo(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let n of Object.values(e))yo(n);return Object.freeze(e)}function Q(e){throw new me("LINEAGE_INVALID",e)}function oc(e){throw new me("LINEAGE_STALE",e)}function Ao(e){if(!fn(e)||!vt(e,ec,nc)||!fn(e.actions))return Q("Lineage definition shape is invalid");for(let n of Object.values(e.actions))if(!fn(n)||!vt(n,tc,ic))return Q("Lineage action definition shape is invalid");return e}function rc(e){if(!fn(e)||!vt(e,Za,Qa))return Q("Lineage entry shape is invalid");if(!Number.isSafeInteger(e.version)||e.version<1||typeof e.hash!="string"||!uo.test(e.hash))return Q("Lineage entry identity is invalid");if(e.sourceHash!==void 0&&(typeof e.sourceHash!="string"||!uo.test(e.sourceHash)))return Q("Lineage source hash is invalid");if(e.compat!==void 0&&e.compat!=="break")return Q("Lineage compatibility marker is invalid");let n=Ao(e.definition);if(n.version!==e.version)return Q("Lineage version does not match its definition");if(e.sourceHash!==void 0&&n.sourceHash!==e.sourceHash)return Q("Lineage source hash does not match its definition");let t;try{t=pe(n),Pe({...n,hash:e.hash});}catch{return Q("Lineage definition is invalid")}return t!==e.hash?Q("Lineage definition hash does not match"):yo({version:e.version,hash:e.hash,definition:n,...e.sourceHash===void 0?{}:{sourceHash:e.sourceHash},...e.compat===void 0?{}:{compat:e.compat}})}function fo(e){return e.stateProjection?.allow??[]}function sc(e,n){let t=[],i=new Set(fo(n));fo(e).some(a=>!i.has(a))&&t.push("S1_STATE_PROJECTION");let o=new Set(n.dataPaths??[]);(e.dataPaths??[]).some(a=>!o.has(a))&&t.push("S2_DATA_PATHS");for(let[a,c]of Object.entries(e.actions)){let d=n.actions[a];if(d&&(c.confirmation??"native")==="native"&&(d.confirmation??"native")!=="native"){t.push("S3_ACTION_CONFIRMATION");break}}Object.keys(e.legacy?.agentAccess??{}).some(a=>!Object.hasOwn(n.actions,a))&&t.push("S4_LEGACY_AGENT_ACTIONS");let s=e.summaryProjection?.allow;if(s!==void 0){let a=new Set(n.summaryProjection?.allow??[]);s.some(c=>!a.has(c))&&t.push("S5_SUMMARY_PROJECTION");}return t}function ac(e,n){return oe(e)===oe(n)}function jt(e,n){if(!Array.isArray(e)||e.length===0)return Q("Definition lineage is missing");if(!fn(n)||typeof n.hash!="string")return Q("Current definition is invalid");let t,i;try{let{hash:a,...c}=n;i=Ao(c),t={...i,hash:a},Pe(t);}catch{return Q("Current definition is invalid")}let o=e.map(rc),r=o[0].definition.id;if(o.some(a=>a.definition.id!==r))return Q("Lineage definition ids do not match");if(o.some((a,c)=>c>0&&a.version<=o[c-1].version))return Q("Lineage generations are not in increasing version order");if(o.some((a,c)=>o.findIndex(d=>d.hash===a.hash)!==c))return Q("Lineage contains a duplicate hash");let s=o[o.length-1];if(s.version!==t.version||s.hash!==t.hash||s.definition.id!==t.id||!ac(s.definition,i))return oc("The last lineage generation does not match the current package");if(t.legacy!==void 0){let a=new Set(Object.keys(t.actions)),c=new Set;for(let p of o)if(p.sourceHash===void 0)for(let A of Object.keys(p.definition.actions))a.has(A)&&c.add(A);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 me("LINEAGE_INVALID",`Lineage compatibility failed: ${p}`,[p])}}for(let a=0;a<o.length-1;a+=1){if(o.slice(a,-1).some(p=>p.compat==="break"))continue;let d=sc(o[a].definition,t);if(d.length>0)throw new me("LINEAGE_INVALID",`Lineage compatibility failed: ${d.join(", ")}`,d)}return Object.freeze({entries:Object.freeze(o),current:t})}var me,uo,Za,Qa,ec,nc,tc,ic,Ft=v(()=>{g();xe();Te();me=class extends Error{constructor(t,i=t,o=[]){super(i);this.code=t;this.violations=o;}code;violations;name="UiDefinitionLineageError"},uo=/^[0-9a-f]{64}$/,Za=["version","hash","definition"],Qa=["sourceHash","compat"],ec=["id","version","actions"],nc=["sourceHash","usage","detailPanel","displayModes","renderer","surfaces","stateProjection","dataPaths","summaryProjection","legacy"],tc=["capabilities"],ic=["inputKeys","dataInputs","confirmation","resultProjection","content","env"];});var Io,go,mo=v(()=>{g();Io=["crewx_app_terminal_connect","crewx_app_html_viewer_open"],go=["crewx_listWorkspaces","crewx_queryAgent","crewx_executeAgent","crewx_getTaskResult","crewx_listTasks","crewx_listAgents","callBrowser","openTab","listTabs","closeTab"];});var ho=v(()=>{g();xe();xn();});function Vt(e,n=0){try{let t=Ee(e,n);return t.type!==void 0&&t.type!=="object"&&Cn("TOOL_INVALID","MCP App inputSchema must describe an object"),t}catch(t){if(t instanceof Ce)throw t;Cn("TOOL_INVALID","MCP App inputSchema must be projection-safe JSON");}}function _o(e){if(e.length===0)return Vt({type:"object",properties:{},additionalProperties:false});let n=e.map(i=>i.actionId),t=new Map;for(let i of e)t.set(i.actionId,Vt(i.inputSchema));return Vt(pc(n,t),dc)}function pc(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})}var yn,dc,Bt=v(()=>{g();po();xe();Te();xn();kn();Ft();mo();ho();yn=8*1024*1024,new Set(Io),new Set(go),dc=4;});function lc(e){if(e===null||typeof e!="object"||!(Eo in e))throw new TypeError("scanCache must be created by createWorkspaceAppScanCache");return e[Eo]}function To(e,n){let t=lc(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.lastCandidateScanUnchanged=void 0,t.lastCandidateKeys=void 0,t.scanStartedAtNs=void 0,t.lastAssetCatalogsUnchanged=void 0,t.lastSnapshot=void 0,t.lastSnapshotBuildInputs=void 0),t.rootIdentity=n,t}var Eo,Po=v(()=>{g();Eo=Symbol("crewx.workspace-app-scan-cache.state");});function ae(e){let n=typeof e=="object"&&e!==null&&"code"in e?String(e.code):"";return n==="ENOENT"?new N("NOT_FOUND"):n==="ELOOP"?new N("PATH_ESCAPED"):n==="EFBIG"||n==="EOVERFLOW"?new N("LIMIT_EXCEEDED"):n==="EACCES"||n==="EPERM"||n==="ENOTDIR"?new N("READ_DENIED"):new N("READ_DENIED")}function Ac(e){if(typeof e!="string"||e.length===0||!ie.isAbsolute(e))throw new N("READ_DENIED")}function Ht(e){if(typeof e!="string"||ie.isAbsolute(e)||/[\\\u0000]/.test(e))throw new N("PATH_ESCAPED");if(e==="")return [];let n=e.split("/");if(n.some(t=>t.length===0||t==="."||t===".."))throw new N("PATH_ESCAPED");return n}function Vn(e,n){let t=ie.relative(e,n);return t===""||t!==".."&&!t.startsWith(`..${ie.sep}`)&&!ie.isAbsolute(t)}function nn(e){return {dev:e.dev,ino:e.ino,size:e.size,mtimeNs:e.mtimeNs,ctimeNs:e.ctimeNs}}function Wt(e,n){return e.dev===n.dev&&e.ino===n.ino}function Jt(e,n){return Wt(e,n)&&e.size===n.size&&e.mtimeNs===n.mtimeNs&&e.ctimeNs===n.ctimeNs}async function vn(e){Ac(e);let n,t;try{n=await promises.realpath(e),t=await promises.stat(n,{bigint:!0});}catch(i){throw ae(i)}if(!t.isDirectory())throw new N("READ_DENIED");return {realRoot:n,identity:nn(t)}}async function bo(e,n,t){if(t.length<2||t[0]!=="apps"&&t[0]!=="skills")return;let i,o;try{if(i=ie.resolve(e,t[0],t[1]),o=await promises.realpath(i),!(await promises.stat(o,{bigint:!0})).isDirectory())throw new N("READ_DENIED")}catch(r){throw r instanceof N?r:ae(r)}if(!Vn(n,o))throw new N("PATH_ESCAPED");return o}async function jn(e,n,t,i){let o,r,s;try{o=await promises.lstat(e,{bigint:!0}),r=await promises.realpath(e),s=await promises.stat(r,{bigint:!0});}catch(a){throw ae(a)}if(!Vn(n,r)||t!==void 0&&!Vn(t,r))throw new N("PATH_ESCAPED");if(!o.isFile()||!s.isFile())throw new N("READ_DENIED");if(!Wt(i,o)||!Wt(i,s)||i.dev!==s.dev)throw new N("PATH_ESCAPED")}async function en(e,n){let t,i;try{t=await promises.realpath(e),i=await promises.stat(t,{bigint:!0});}catch{throw new N("PATH_ESCAPED")}if(t!==n.realRoot||!Jt(n.identity,nn(i)))throw new N("PATH_ESCAPED")}function Ic(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 N,Gt,yc,Do,Bn,So,Xt=v(()=>{g();N=class extends Error{constructor(t){super(t);this.code=t;}code;name="AppDiscoveryFsError"},Gt=q.constants.O_NOFOLLOW,yc=q.constants.O_NONBLOCK,Do=q.constants.O_RDONLY|(Gt??0)|(yc??0);Bn=class{async getRootIdentity(n){let t=await vn(n);return await en(n,t),{dev:t.identity.dev,ino:t.identity.ino,realPath:t.realRoot}}async listDirectory(n,t){let i=Ht(t),o=await vn(n),r=ie.resolve(n,...i),s,a;try{s=await promises.realpath(r),a=await promises.stat(s,{bigint:!0});}catch(c){let d=ae(c);if(d.code==="NOT_FOUND")return [];throw d}if(!Vn(o.realRoot,s)||!a.isDirectory())throw new N("PATH_ESCAPED");try{let c=await promises.readdir(s,{withFileTypes:!0,encoding:"utf8"});return await en(n,o),c.map(Ic)}catch(c){let d=ae(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 N("READ_DENIED");if(Gt===void 0)throw new N("UNSUPPORTED");let o=Ht(t),r=await vn(n),s=ie.resolve(n,...o),a=ie.relative(n,s);if(a===".."||a.startsWith(`..${ie.sep}`)||ie.isAbsolute(a))throw new N("PATH_ESCAPED");let c;try{c=await promises.open(s,Do);}catch(d){throw ae(d)}try{let d;try{let h=await c.stat({bigint:!0});d=nn(h);}catch(h){throw ae(h)}if(d.size>BigInt(i))throw new N("LIMIT_EXCEEDED");if(d.size>BigInt(Number.MAX_SAFE_INTEGER))throw new N("LIMIT_EXCEEDED");await en(n,r);let p=await bo(n,r.realRoot,o);await jn(s,r.realRoot,p,d);let A=new Uint8Array(new ArrayBuffer(Number(d.size))),m=0;for(;m<A.byteLength;){let h;try{h=(await c.read(A,m,A.byteLength-m,m)).bytesRead;}catch(L){throw ae(L)}if(h<=0)throw new N("IDENTITY_CHANGED");m+=h;}let y;try{let h=await c.stat({bigint:!0});y=nn(h);}catch(h){throw ae(h)}if(!Jt(d,y))throw new N("IDENTITY_CHANGED");return await jn(s,r.realRoot,p,y),await en(n,r),new Uint8Array(A)}finally{await c.close().catch(()=>{});}}async fingerprintVerifiedFile(n,t,i){if(!Number.isSafeInteger(i)||i<0)throw new N("READ_DENIED");if(Gt===void 0)throw new N("UNSUPPORTED");let o=Ht(t),r=await vn(n),s=ie.resolve(n,...o),a=ie.relative(n,s);if(a===".."||a.startsWith(`..${ie.sep}`)||ie.isAbsolute(a))throw new N("PATH_ESCAPED");let c;try{c=await promises.open(s,Do);}catch(d){throw ae(d)}try{let d;try{let m=await c.stat({bigint:!0});d=nn(m);}catch(m){throw ae(m)}if(d.size>BigInt(i)||d.size>BigInt(Number.MAX_SAFE_INTEGER))throw new N("LIMIT_EXCEEDED");await en(n,r);let p=await bo(n,r.realRoot,o);await jn(s,r.realRoot,p,d);let A;try{let m=await c.stat({bigint:!0});A=nn(m);}catch(m){throw ae(m)}if(!Jt(d,A))throw new N("IDENTITY_CHANGED");return await jn(s,r.realRoot,p,A),await en(n,r),{...A,candidateRealPath:p??r.realRoot}}catch(d){throw d instanceof N?d:ae(d)}finally{await c.close().catch(()=>{});}}async readFileVerified(n,t,i){return this.readVerifiedFile(n,t,i)}},So=new Bn;});function mn(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 Lo(e){return typeof e=="string"&&ye.test(e)?e:void 0}function Pc(e){return e.length>0&&e!=="."&&e!==".."&&!/[\\/\u0000]/.test(e)}function Be(e,n){let t=new TextEncoder().encode(e),i=new TextEncoder().encode(n),o=Math.min(t.byteLength,i.byteLength);for(let r=0;r<o;r+=1){let s=t[r]-i[r];if(s!==0)return s}return t.byteLength-i.byteLength}function Nc(e){if(typeof e=="string")return {name:e,kind:"directory"};if(e===null||typeof e!="object")return null;let n=e;if(typeof n.name!="string")return null;if(n.kind==="file"||n.kind==="directory"||n.kind==="symlink"||n.kind==="other")return {name:n.name,kind:n.kind};if(n.type==="file"||n.type==="directory"||n.type==="symlink"||n.type==="other")return {name:n.name,kind:n.type};let t=n.isDirectory;if(typeof t=="function"&&t.call(e))return {name:n.name,kind:"directory"};let i=n.isSymbolicLink;if(typeof i=="function"&&i.call(e))return {name:n.name,kind:"symlink"};let o=n.isFile;return typeof o=="function"&&o.call(e)?{name:n.name,kind:"file"}:{name:n.name,kind:"other"}}function Dc(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 bc(e){return Ec.decode(e)}function Sc(e){return JSON.parse(bc(e))}function Oo(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 Mc(e){if(e instanceof N)return Oo(e.code);if(e!==null&&typeof e=="object"&&"code"in e){let n=e.code;if(typeof n=="string")return Oo(n)}}function De(e,n){let t=n();return Number.isFinite(t)&&Number.isFinite(e)&&t-e<=5e3}function Lc(e){if(typeof e.readVerifiedFile=="function")return e.readVerifiedFile;if(typeof e.readFileVerified=="function")return e.readFileVerified}function Oc(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 Ro(e,n,t,i){let o=Lc(e);if(!o)throw new N("READ_DENIED");return Dc(await o.call(e,n,t,i))}async function Zt(e,n,t){let i=Oc(e);if(!i)throw new N("READ_DENIED");let o=await i.call(e,n,t);if(!Array.isArray(o))throw new N("READ_DENIED");return o.map(Nc).filter(r=>r!==null)}function Rc(e,n,t,i){return Object.freeze({code:e,...{},source:n,relativePath:t})}function wc(e){if(!mn(e))throw new TypeError("productBundle.reservedIds must be an object with appIds and definitionIds arrays");try{let n=Reflect.ownKeys(e);if(n.length!==2||!n.includes("appIds")||!n.includes("definitionIds"))throw new TypeError("productBundle.reservedIds must contain exactly appIds and definitionIds");let t=(i,o)=>{if(!Array.isArray(i))throw new TypeError("productBundle.reservedIds."+o+" must be an array");let r=[];for(let s=0;s<i.length;s+=1){let a=i[s];if(typeof a!="string"||a.length===0)throw new TypeError("productBundle.reservedIds."+o+" must contain non-empty strings");r.push(a);}return Object.freeze([...new Set(r)].sort(Be))};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 Uc(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 zn(e){return Object.freeze({appIds:Object.freeze([...new Set(e.map(n=>n.appId))].sort(Be)),definitionIds:Object.freeze([...new Set(e.map(n=>n.definition.id))].sort(Be))})}function Hn(e,n){let t=Object.keys(e).sort(Be),i=[...n].sort(Be);return t.length===i.length&&t.every((o,r)=>o===i[r])}function wo(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 Cc(e){let n;try{n=Sc(e);}catch{return}if(!mn(n)||!Hn(n,["version","packages"])||n.version!==1||!Array.isArray(n.packages)||n.packages.length>Qt)return;let t=new Set,i=new Set,o=0,r=[];for(let s of n.packages){if(!mn(s))return;let a=["packageDir","appId","definition","files"],c=Object.hasOwn(s,"lineage"),d=Object.hasOwn(s,"launcher"),p=[...c?["lineage"]:[],...d?["launcher"]:[]];if(!Hn(s,[...a,...p])||d&&s.launcher!==false)return;let A=wo(s.packageDir),m=Lo(s.appId);if(!A||A.length!==2||A[0]!=="apps"||!Pc(A[1])||!m||t.has(s.packageDir)||!mn(s.definition)||!Hn(s.definition,["id","version","hash"]))return;let y=Lo(s.definition.id),h=s.definition.version,L=s.definition.hash;if(!y||!Number.isSafeInteger(h)||h<1||typeof L!="string"||!qt.test(L)||!Array.isArray(s.files)||s.files.length<2||s.files.length>ei)return;let S=new Set,j=[];for(let C of s.files){if(!mn(C)||!Hn(C,["path","sha256"]))return;let x=wo(C.path);if(!x||typeof C.sha256!="string"||!qt.test(C.sha256))return;let F=x.join("/"),E=`${s.packageDir}/${F}`;if(S.has(F)||i.has(E))return;S.add(F),i.add(E),j.push(Object.freeze({path:F,sha256:C.sha256}));}if(!X.some(C=>S.has(C))||!S.has("ui/index.html")||(o+=j.length,o>mc))return;t.add(s.packageDir),r.push(Object.freeze({packageDir:s.packageDir,...d?{launcher:false}:{},appId:m,definition:Object.freeze({id:y,version:h,hash:L}),lineage:Array.isArray(s.lineage)?s.lineage:[],files:Object.freeze(j.sort((C,x)=>Be(C.path,x.path)))}));}return Object.freeze({version:1,packages:Object.freeze(r)})}function Ve(e){let n=Mc(e);return n==="PATH_ESCAPED"||n==="IDENTITY_CHANGED"||n==="TOCTOU"?"PATH_ESCAPED":n==="LIMIT_EXCEEDED"?"LIMIT_EXCEEDED":"BUNDLE_INTEGRITY"}async function kc(e,n,t,i,o){let r=[],s=async(a,c)=>{if(!De(i,o))throw new N("LIMIT_EXCEEDED");if(c>2)throw new N("LIMIT_EXCEEDED");let d=await Zt(e,n,a);for(let p of d){if(typeof p.name!="string"||p.name.length===0||p.name==="."||p.name===".."||/[\\/\u0000]/.test(p.name))throw new N("PATH_ESCAPED");let A=`${a}/${p.name}`;if(p.kind==="file"){if(r.push(A.slice(t.length+1)),r.length>ei)throw new N("LIMIT_EXCEEDED")}else if(p.kind==="directory")await s(A,c+1);else throw p.kind==="symlink"?new N("PATH_ESCAPED"):new N("READ_DENIED")}};return await s(t,0),r.sort(Be)}function xc(e){return X.includes(e)?262144:e==="ui/index.html"?yn:e==="ui/state.json"?65536:e.startsWith("ui/assets/")?_c:hc}async function Uo(e,n,t,i){if(e===void 0)return {packages:[],diagnostics:[],incomplete:false,reservedIds:Tc};let o=wc(e.reservedIds),r=[],s=(l,u,I)=>Rc(l,"bundled",u),a=(l=[],u=false,I)=>({...I===void 0?{}:{indexHash:I},packages:l,diagnostics:r,incomplete:u,reservedIds:o});if(typeof e.root!="string"||e.root.length===0||typeof e.expectedIndexHash!="string"||!qt.test(e.expectedIndexHash))return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a();let c;try{c=await Ro(n,e.root,"bundle-index.json",gc);}catch(l){return r.push(s(Ve(l),"bundle-index.json")),a()}let d=li.createHash("sha256").update(c).digest("hex");if(d!==e.expectedIndexHash)return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a();let p=Cc(c);if(p===void 0)return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a();if(!Uc(zn(p.packages),o))return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a([],false,d);if(!De(t,i))return r.push(s("LIMIT_EXCEEDED","bundle-index.json")),a(p.packages.map(l=>({indexEntry:l,failureCode:"LIMIT_EXCEEDED"})),true,d);let A;try{A=await Zt(n,e.root,"");}catch(l){return r.push(s(Ve(l),"bundle-index.json")),a(p.packages.map(u=>({indexEntry:u,failureCode:Ve(l)})),false,d)}if(!De(t,i))return r.push(s("LIMIT_EXCEEDED","bundle-index.json")),a(p.packages.map(l=>({indexEntry:l,failureCode:"LIMIT_EXCEEDED"})),true,d);let m=A.find(l=>l.name==="bundle-index.json"&&l.kind==="file"),y=A.find(l=>l.name==="apps"&&l.kind==="directory"),h=l=>p.packages.map(u=>({indexEntry:u,failureCode:l}));if(!m)return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a(h("BUNDLE_INTEGRITY"),false,d);let L=A.filter(l=>l.name!=="bundle-index.json"&&l.name!=="apps");if(L.length>0){let l=L.some(u=>u.kind==="symlink")?"PATH_ESCAPED":"BUNDLE_INTEGRITY";return r.push(s(l,"bundle-index.json")),a(h("BUNDLE_INTEGRITY"),false,d)}if(A.some(l=>l.name==="apps"&&l.kind!=="directory"))return r.push(s("PATH_ESCAPED","apps")),a(h("PATH_ESCAPED"),false,d);let S=[];if(y)try{S=await Zt(n,e.root,"apps");}catch(l){return r.push(s(Ve(l),"apps")),a(h(Ve(l)),false,d)}if(!De(t,i)||S.length>Qt)return r.push(s("LIMIT_EXCEEDED","apps")),a(h("LIMIT_EXCEEDED"),true,d);let j=new Map(p.packages.map(l=>[l.packageDir.slice(5),l])),C=S.filter(l=>!j.has(l.name));for(let l of C)r.push(s(l.kind==="symlink"?"PATH_ESCAPED":"BUNDLE_INTEGRITY",`apps/${l.name}`));if(C.length>0){let l=C.some(u=>u.kind==="symlink")?"PATH_ESCAPED":"BUNDLE_INTEGRITY";return a(h(l),false,d)}let x=new Set,F=new Map,E=new Map;for(let l of p.packages){let u=F.get(l.appId)??[];u.push(l),F.set(l.appId,u);let I=`${l.definition.id}\0${String(l.definition.version)}`,P=E.get(I)??[];P.push(l),E.set(I,P);}for(let l of [...F.values(),...E.values()])if(l.length>1)for(let u of l)x.add(u);let T=[],U=c.byteLength,D=false;for(let l of p.packages){if(!De(t,i)){D=true,T.push({indexEntry:l,failureCode:"LIMIT_EXCEEDED"});continue}let u;try{let b=l.lineage[l.lineage.length-1];if(!b)throw new me("LINEAGE_INVALID","Definition lineage is missing");if(b.definition.id!==l.definition.id||b.version!==l.definition.version||b.hash!==l.definition.hash)throw new me("LINEAGE_STALE","Last lineage generation does not match bundle identity");u=jt(l.lineage,{...b.definition,hash:b.hash}).entries;}catch(b){let se=b instanceof me?b.code:"LINEAGE_INVALID";r.push(s(se,l.packageDir)),T.push({indexEntry:l,failureCode:se});continue}let I=S.find(b=>b.name===l.packageDir.slice(5));if(!y||!I){T.push({indexEntry:l,failureCode:"BUNDLE_INTEGRITY"});continue}if(I.kind!=="directory"){T.push({indexEntry:l,failureCode:I.kind==="symlink"?"PATH_ESCAPED":"BUNDLE_INTEGRITY"});continue}let P;try{let b=await kc(n,e.root,l.packageDir,t,i);if(!De(t,i)){D=!0,T.push({indexEntry:l,failureCode:"LIMIT_EXCEEDED"});continue}let se=l.files.map(he=>he.path);if(b.length!==se.length||b.some((he,_e)=>he!==se[_e])){T.push({indexEntry:l,failureCode:"BUNDLE_INTEGRITY"});continue}P=new Map;let H;for(let he of l.files){if(!De(t,i)){H="LIMIT_EXCEEDED",D=!0;break}if(U>=Yt){H="LIMIT_EXCEEDED";break}let _e;try{_e=await Ro(n,e.root,`${l.packageDir}/${he.path}`,xc(he.path));}catch(vr){H=Ve(vr);break}if(!De(t,i)){H="LIMIT_EXCEEDED",D=!0;break}if(U+_e.byteLength>Yt){U=Yt,H="LIMIT_EXCEEDED";break}if(U+=_e.byteLength,li.createHash("sha256").update(_e).digest("hex")!==he.sha256){H="BUNDLE_INTEGRITY";break}P.set(he.path,_e);}if(H!==void 0){T.push({indexEntry:l,failureCode:H});continue}}catch(b){De(t,i)||(D=true),T.push({indexEntry:l,failureCode:Ve(b)});continue}T.push({indexEntry:l,lineage:u,files:P,...x.has(l)?{failureCode:"DUPLICATE_ID"}:{}});}return a(T,D,d)}var gc,Qt,ei,mc,hc,_c,Yt,qt,Ec,Tc,ni=v(()=>{g();Ft();ke();wn();Bt();Xt();gc=256*1024,Qt=64,ei=128,mc=Qt*ei,hc=2*1024*1024,_c=8*1024*1024,Yt=32*1024*1024,qt=/^[0-9a-f]{64}$/,Ec=new TextDecoder("utf-8",{fatal:true}),Tc=Object.freeze({appIds:Object.freeze([]),definitionIds:Object.freeze([])});});function jc(e){if(typeof e!="string"||!ye.test(e))throw new TypeError("pluginId must be a safe UI plugin identifier");let n=`${ti}${e}`.length+7<=128?e:`hash_${li.createHash("sha256").update(e,"utf8").digest("hex")}`;return {read:`${ti}${n}_read`,action:`${ti}${n}_action`}}function ko(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 Vc(e,n){return n.length===0||n==="."||n===".."||/[\\/\u0000]/.test(n)?e==="skills"?"skills":"apps":`${e==="skills"?"skills":"apps"}/${n}`}function Bc(e){return e.length>0&&e!=="."&&e!==".."&&!/[\\/\u0000]/.test(e)}function hn(e,n){let t=new TextEncoder().encode(e),i=new TextEncoder().encode(n),o=Math.min(t.byteLength,i.byteLength);for(let r=0;r<o;r+=1){let s=t[r]-i[r];if(s!==0)return s}return t.byteLength-i.byteLength}function Wo(e){if(typeof e=="string")return {name:e,kind:"directory"};if(e===null||typeof e!="object")return null;let n=e;if(typeof n.name!="string")return null;if(n.kind==="file"||n.kind==="directory"||n.kind==="symlink"||n.kind==="other")return {name:n.name,kind:n.kind};if(n.type==="file"||n.type==="directory"||n.type==="symlink"||n.type==="other")return {name:n.name,kind:n.type};let t=n.isDirectory;if(typeof t=="function"&&t.call(e))return {name:n.name,kind:"directory"};let i=n.isSymbolicLink;if(typeof i=="function"&&i.call(e))return {name:n.name,kind:"symlink"};let o=n.isFile;return typeof o=="function"&&o.call(e)?{name:n.name,kind:"file"}:{name:n.name,kind:"other"}}function Hc(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 Jo(e){return Fc.decode(e)}function zc(e){return JSON.parse(Jo(e))}function $c(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 Gn(e,n,t,i,o){let r={code:e,...i===void 0?{}:{pluginId:i},source:n,relativePath:t,...o?.reason===void 0?{}:{reason:Object.freeze({...o.reason})},...o?.files===void 0?{}:{files:Object.freeze([...o.files])}};return Object.freeze(r)}function xo(e){switch(e){case "ENOENT":return "NOT_FOUND";case "ELOOP":case "EXDEV":return "PATH_ESCAPED";case "EFBIG":case "EOVERFLOW":return "LIMIT_EXCEEDED";case "EACCES":case "EPERM":case "ENOTDIR":return "READ_DENIED";default:return e}}function te(e){if(e instanceof N)return xo(e.code);if(e!==null&&typeof e=="object"&&"code"in e){let n=e.code;if(typeof n=="string")return xo(n)}}function ze(e,n){return e==="PATH_ESCAPED"||e==="IDENTITY_CHANGED"||e==="TOCTOU"?"PATH_ESCAPED":e==="LIMIT_EXCEEDED"?"LIMIT_EXCEEDED":n==="manifest"&&e==="NOT_FOUND"?"MANIFEST_MISSING":n==="entry"?"ENTRY_INVALID":n==="initial"?"INITIAL_STATE_INVALID":"MANIFEST_INVALID"}function vo(e){return {reason:e.reason,...e.code==="MANIFEST_DUAL_MISMATCH"?{files:e.files}:{}}}function jo(e){return e==="MANIFEST_DUAL_MISMATCH"?e:Ko(e)}function Gc(e){return Ko(e.code)}function Ko(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 Xo("UiPluginValidationError",e)}}function Xo(e,n){throw new Error(`Unmapped ${e} code: ${String(n)}`)}function Wc(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 Xo("McpAppContractError",e)}}function be(e,n){let t=n();return Number.isFinite(t)&&Number.isFinite(e)&&t-e<=5e3}function Jc(e){return {pluginId:e.appId,definitionKey:`${e.definition.id}\0${String(e.definition.version)}`}}function Kc(e,n){let t=n.get("package.json");if(t!==void 0)try{let o=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(t));if(ko(o)){let r=o.bin,s=typeof r=="string"?r:ko(r)?Object.values(r).find(a=>typeof a=="string"):void 0;for(let a of [s,o.main]){if(typeof a!="string")continue;let c=Xc(a);if(c&&n.has(c))return c}}}catch{}return [`${e.slice(e.lastIndexOf("/")+1)}.js`,"index.js","main.js"].find(o=>n.has(o))}function Xc(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 Yc(){return globalThis.performance?.now()??Date.now()}function He(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let n of Object.values(e))He(n);return Object.freeze(e)}function Fo(e){return Object.freeze(Array.from(e))}async function Wn(e,n,t,i){if(n.pinnedFiles!==void 0){let a=n.pinnedFiles.get(t);if(a===void 0)throw new N("NOT_FOUND");if(a.byteLength>i)throw new N("LIMIT_EXCEEDED");return new Uint8Array(a)}let o=`${n.relativePath}/${t}`,r=n.scanContext,s=e.fingerprintVerifiedFile;if(r===void 0||!r.cacheable||typeof s!="function")return zo(e,n.root,o,i);try{let a=r.priorFingerprints.get(o)??await s.call(e,r.workspaceRoot,o,i);r.candidateRealPath=a.candidateRealPath;let c=await zo(e,n.root,o,i),d=await s.call(e,r.workspaceRoot,o,i);return r.candidateRealPath=d.candidateRealPath,qo(a,d)&&d.size===BigInt(c.byteLength)&&!Zo(d,r.scanStartedAtNs)?r.files.set(o,{relativePath:o,byteLimit:i,fingerprint:d}):r.cacheable=!1,c}catch(a){let c=X.includes(t)&&te(a)==="NOT_FOUND"&&r.directoryListings.some(p=>p.relativePath===n.relativePath&&!Jn(p.key,t)),d=t===V&&te(a)==="NOT_FOUND"&&qc(r.directoryListings,n.relativePath);throw !c&&!d&&(r.cacheable=false),a}}function qc(e,n){let t=e.find(o=>o.relativePath===n);if(t===void 0)return false;if(!Jn(t.key,"dist"))return true;let i=e.find(o=>o.relativePath===`${n}/dist`);return i!==void 0&&!Jn(i.key,"tools.json")}function Yo(e,n){return JSON.stringify([e.realPath,n.source,n.relativePath])}async function Qc(e,n,t,i,o,r,s,a){let c=e.fingerprintVerifiedFile,d=Yo(t,i),p=o.candidates.get(d),A=i.relativePath,m;try{m=await Ho(e,n,A);}catch(D){if(te(D)!=="NOT_FOUND")throw D}let y=m===void 0?void 0:{relativePath:A,key:m};if(y!==void 0&&(i.source==="apps"||i.source==="skills")&&!X.some(D=>Jn(y.key,D)))return be(s,a)?p!==void 0&&p.candidate===void 0&&p.candidateRealPath===void 0&&p.files.length===0&&p.directoryListings.length===1&&p.directoryListings[0]?.relativePath===y.relativePath&&p.directoryListings[0]?.key===y.key&&(i.source==="apps"?p.diagnostic?.code==="MANIFEST_MISSING":p.diagnostic===void 0)&&typeof c=="function"?{memo:p}:typeof c!="function"?{}:{context:{state:o,cacheKey:d,workspaceRoot:n,scanStartedAtNs:r,directoryListings:Object.freeze([y]),priorFingerprints:new Map,files:new Map,cacheable:true}}:{timeLimitReached:true};let h=async D=>{if(D==="")return y;let l=`${i.relativePath}${D}`;try{let u=await Ho(e,n,l);return u===void 0?void 0:{relativePath:l,key:u}}catch(u){if(te(u)==="NOT_FOUND")return;throw u}},L=await Promise.all(Vo.map(h)),S=await Promise.all(Zc.map(h));if(!be(s,a))return {timeLimitReached:true};let j=typeof c=="function"&&L.every(D=>D!==void 0),C=L.filter(D=>D!==void 0),x=[...C,...S.filter(D=>D!==void 0)],F=new Map,E=p!==void 0&&j,T;if(p!==void 0&&typeof c=="function"){let D=await Promise.all(p.files.map(async l=>{if(!be(s,a))return {kind:"time",file:l};try{let u=await c.call(e,n,l.relativePath,l.byteLimit);return {kind:"fingerprint",file:l,current:u}}catch(u){return te(u)==="NOT_FOUND"?{kind:"missing",file:l}:{kind:"error",file:l,error:u}}}));if(D.some(l=>l.kind==="time"))return {timeLimitReached:true};for(let l of D){if(l.kind==="error")throw l.error;if(l.kind==="missing"){E=false;continue}if(l.kind!=="fingerprint")continue;let{file:u,current:I}=l;F.set(u.relativePath,I),T??=I.candidateRealPath,(I.candidateRealPath!==p.candidateRealPath||!qo(I,u.fingerprint)||Zo(I,r))&&(E=false);}}let U=p!==void 0&&p.directoryListings.length===x.length&&p.directoryListings.every((D,l)=>D.relativePath===x[l]?.relativePath&&D.key===x[l]?.key);return p!==void 0&&j&&U&&E&&T===p.candidateRealPath?{memo:p}:!j||C.length!==Vo.length?{}:{context:{state:o,cacheKey:d,workspaceRoot:n,scanStartedAtNs:r,directoryListings:Object.freeze(x),priorFingerprints:F,files:new Map,...T===void 0?{}:{candidateRealPath:T},cacheable:true}}}function Jn(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 Ho(e,n,t){let i=Qo(e);if(typeof i!="function")return;let o=await i.call(e,n,t);if(!Array.isArray(o)||o.some(s=>typeof s=="string"))return;let r=o.map(Wo);if(!r.some(s=>s===null))return JSON.stringify(r.slice().sort((s,a)=>hn(s.name,a.name)||hn(s.kind,a.kind)).map(s=>[s.name,s.kind]))}function qo(e,n){return e.dev===n.dev&&e.ino===n.ino&&e.size===n.size&&e.mtimeNs===n.mtimeNs&&e.ctimeNs===n.ctimeNs}function Zo(e,n){let t=e.mtimeNs-n;return t>=-Bo&&t<=Bo}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,o=t||i;if(n===void 0||!n.cacheable||n.candidateRealPath===void 0&&!o||n.files.size===0&&!o)return;let r=Object.freeze({...!o&&n.candidateRealPath!==void 0?{candidateRealPath:n.candidateRealPath}:{},directoryListings:n.directoryListings,files:Object.freeze([...n.files.values()]),...e.candidate===void 0?{}:{candidate:e.candidate},...e.diagnostic===void 0?{}:{diagnostic:e.diagnostic},...e.identity===void 0?{}:{identity:e.identity},...e.provenance===void 0?{}:{provenance:e.provenance}});n.state.candidates.set(n.cacheKey,r);}function ed(e,n,t){let i=li.createHash("sha256"),o=new TextEncoder().encode(oe(e)),r=s=>{let a=new Uint8Array(8);new DataView(a.buffer).setBigUint64(0,BigInt(s)),i.update(a);};return r(o.byteLength),i.update(o),r(n.byteLength),i.update(n),r(t.byteLength),i.update(t),i.digest("hex")}function nd(e,n){let t={...e.definition,sourceHash:n},i;try{i=pe(t);}catch(r){throw r instanceof O&&r.code==="INPUT_INVALID"?new ne("MANIFEST_INVALID","normalized definition is invalid"):r}let o={...t,hash:i};try{Pe(o);}catch{throw new ne("MANIFEST_INVALID","normalized definition is invalid")}return o}function td(e){return e.actions.some(n=>n.backend.type==="core"&&n.backend.handler!=="state.set")}function id(e){if(typeof e.readVerifiedFile=="function")return e.readVerifiedFile;if(typeof e.readFileVerified=="function")return e.readFileVerified}function Qo(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 zo(e,n,t,i){let o=id(e);if(!o)throw new N("READ_DENIED");return Hc(await o.call(e,n,t,i))}async function od(e,n,t){let i=Qo(e);if(!i)throw new N("READ_DENIED");let o=await i.call(e,n,t);if(!Array.isArray(o))throw new N("READ_DENIED");return o.map(Wo).filter(r=>r!==null)}function rd(e){let n=[];for(let t of [e.reserved,e.builtin])t&&n.push(t);return e.builtins&&"listMcpApps"in e.builtins?n.push($o(e.builtins)):e.builtins&&n.push(e.builtins),e.builtinCatalog&&n.push($o(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 $o(e){let n=[],t=[],i=[];for(let o of e.listMcpApps())typeof o.appId=="string"&&n.push(o.appId),o.definition&&typeof o.definition.id=="string"&&t.push(o.definition.id);for(let o of e.listMcpAppTools())typeof o.name=="string"&&i.push(o.name);return {appIds:n,definitionIds:t,toolNames:i}}function Se(e,n){e.diagnostic||(e.diagnostic=Gn(n,e.source,e.relativePath,e.identity?.pluginId));}function sd(e){let n=new Map;for(let i of e){let o=i.identity?.pluginId;if(o===void 0)continue;let r=n.get(o)??[];r.push(i),n.set(o,r);}for(let i of n.values()){if(i.length<2)continue;let o=i.filter(s=>s.provenance!==void 0);if(o.length>0){for(let s of i)s.provenance===void 0&&Se(s,"RESERVED_ID");if(o.length>1)for(let s of o)Se(s,"DUPLICATE_ID");continue}let r=i.filter(s=>s.source==="apps");if(r.length>1){for(let s of r)Se(s,"DUPLICATE_ID");for(let s of i.filter(a=>a.source==="skills"))Se(s,"DUPLICATE_ID");}else for(let s of i.filter(a=>a.source==="skills"))Se(s,"DUPLICATE_ID");}let t=new Map;for(let i of e){if(i.diagnostic?.code==="RESERVED_ID")continue;let o=i.identity?.definitionKey;if(o===void 0)continue;let r=t.get(o)??[];r.push(i),t.set(o,r);}for(let i of t.values())if(i.length>1)for(let o of i)Se(o,"DUPLICATE_ID");}function ad(e,n,t){let i=new Set,o=new Set,r=new Set,s=new Set(t.appIds),a=new Set(t.definitionIds);for(let c of rd(n)){for(let d of c.appIds??[])typeof d=="string"&&i.add(d);for(let d of c.definitionIds??[])typeof d=="string"&&o.add(d);for(let d of c.toolNames??[])typeof d=="string"&&r.add(d);}for(let c of e){let d=c.candidate;if(!d)continue;if(i.has(d.pluginId)||o.has(d.definitionId)){Se(c,"RESERVED_ID");continue}if(c.provenance===void 0&&(s.has(d.pluginId)||a.has(d.definitionId))){Se(c,"RESERVED_ID");continue}[d.toolNames.read,d.toolNames.action].filter(A=>A!==void 0).some(A=>r.has(A))&&Se(c,"DUPLICATE_ID");}}function cd(e){return [...e].sort((n,t)=>{let i=Co.indexOf(n.source)-Co.indexOf(t.source);return i!==0?i:hn(n.relativePath,t.relativePath)})}function k(e,n,t){e.diagnostic=Gn(n,e.source,e.relativePath,e.identity?.pluginId,t);}async function Go(e,n,t){let i=Fe(t,{mode:"local"});if(!i.ok&&i.parseFailure){k(n,jo(i.rejection.code),vo(i.rejection));return}let o=$c(i.identity);if(n.bundleIdentity===void 0)n.identity=o;else if(o?.pluginId!==n.bundleIdentity.appId||o.definitionKey!==`${n.bundleIdentity.definitionId}\0${String(n.bundleIdentity.version)}`){k(n,"BUNDLE_INTEGRITY");return}if(!i.ok&&i.builtinOnly){k(n,"RESERVED_ID");return}if(!i.ok){k(n,jo(i.rejection.code),vo(i.rejection));return}let r=i.manifest,s={pluginId:r.pluginId,definitionKey:`${r.definitionId}\0${String(r.version)}`};if(n.bundleIdentity===void 0&&(n.identity=s),r.actions.length>0)try{_o(r.actions.map(b=>({actionId:b.actionId,inputSchema:b.inputSchema})));}catch(b){if(b instanceof Ce){k(n,Wc(b.code));return}throw b}let a;try{a=await Wn(e,n,"ui/index.html",yn);}catch(b){k(n,ze(te(b),"entry"));return}if(a.byteLength>yn){k(n,"LIMIT_EXCEEDED");return}let c;try{c=Jo(a);}catch{k(n,"ENTRY_INVALID");return}if(a.byteLength===0||c.length===0){k(n,"ENTRY_INVALID");return}let d=li.createHash("sha256").update(a).digest("hex");if(r.entryHash!==void 0&&r.entryHash!==d){k(n,"ENTRY_INVALID");return}let p={},A,m;if(r.initialState!==void 0){try{A=await Wn(e,n,"ui/state.json",65536);}catch(b){k(n,ze(te(b),"initial"));return}if(A.byteLength>65536){k(n,"LIMIT_EXCEEDED");return}try{let b=zc(A),se=r.dataPaths??[],H=St(b,se);p=Ee(H,0,se),We(p);}catch{k(n,"INITIAL_STATE_INVALID");return}if(m=li.createHash("sha256").update(A).digest("hex"),r.initialState.hash!==void 0&&r.initialState.hash!==m){k(n,"INITIAL_STATE_INVALID");return}}let y={...r,entryHash:d,...r.initialState===void 0?{}:{initialState:{path:"ui/state.json",hash:m}}},h=cn(y),L=ed(y,a,A??new Uint8Array),S;try{S=nd(h,L);}catch(b){if(b instanceof ne){k(n,Gc(b));return}throw b}let j;if(n.bundleLineage!==void 0){let b=n.bundleLineage[n.bundleLineage.length-1];if(!b){k(n,"LINEAGE_INVALID");return}let{legacy:se,...H}=b.definition,{hash:he,..._e}=S;if(oe(H)!==oe(_e)){k(n,"LINEAGE_STALE");return}if(se!==void 0&&(S={...S,legacy:se}),se!==void 0)try{S={...S,hash:pe(S)},Pe(S);}catch{k(n,"LINEAGE_INVALID");return}j=n.bundleLineage;}if(n.bundleIdentity!==void 0&&n.bundleIdentity.appId!==r.pluginId){k(n,"BUNDLE_INTEGRITY");return}if(n.bundleIdentity!==void 0&&(n.bundleIdentity.definitionId!==S.id||n.bundleIdentity.version!==S.version||n.bundleIdentity.definitionHash!==S.hash)){k(n,"LINEAGE_STALE");return}let C=jc(r.pluginId),x=r.actions.length===0?{read:C.read}:C,F=He(h),E=He(y),T=He(S),U=He({...h.handlers}),D=Fo(a),l=A===void 0?void 0:Fo(A),u=Object.freeze({...n.provenance===void 0?{}:{provenance:n.provenance},entry:Object.freeze({path:"ui/index.html",hash:d,bytes:D}),...l===void 0?{}:{initialState:Object.freeze({path:"ui/state.json",hash:m,bytes:l})}}),I={appId:r.pluginId,pluginId:r.pluginId,definitionId:r.definitionId,version:r.version,...i.releaseVersion===void 0?{}:{releaseVersion:i.releaseVersion},manifestFile:i.file,...i.mcpb===void 0?{}:{mcpb:He(i.mcpb)},relativePath:n.relativePath,manifest:E,normalized:F,name:r.name,description:r.description,...r.icon===void 0?{}:{icon:r.icon},...r.tone===void 0?{}:{tone:r.tone},definition:T,handlers:U,resources:u,html:c,entryBytes:D,entryHash:d,initialState:He(p),...l===void 0?{}:{initialStateBytes:l},...m===void 0?{}:{initialStateHash:m},sourceHash:L,toolNames:Object.freeze(x)},P=n.provenance===void 0?{...I,source:n.source}:{...I,provenance:n.provenance,lineage:j??[]};n.candidate=Object.freeze(P),td(r)&&k(n,"EXEC_DENIED");}async function er(e,n){let t={};for(let i of X)try{t[i]=await Wn(e,n,i,262144);}catch(o){if(te(o)==="NOT_FOUND")continue;return {files:t,failure:ze(te(o),"manifest")}}if(t[G]!==void 0)try{t[V]=await Wn(e,n,V,262144);}catch(i){if(te(i)!=="NOT_FOUND")return {files:t,failure:ze(te(i),"manifest")}}return {files:t}}function oi(e){return X.some(n=>e[n]!==void 0)}async function dd(e,n){let{files:t,failure:i}=await er(e,n);if(i!==void 0){k(n,i);return}let o=t[G];return o!==void 0&&!Ct(o)&&(delete t[G],delete t[V]),oi(t)?t:void 0}function pd(e,n,t,i=vc,o=false){let r=cd(e);sd(r);let s=Object.freeze(r.filter(p=>p.candidate!==void 0&&p.diagnostic===void 0).map(p=>p.candidate)),a=Object.freeze(r.filter(p=>p.diagnostic!==void 0).map(p=>p.diagnostic)),c=o?Object.freeze({...t===void 0?{}:{indexHash:t},candidates:Object.freeze(r.filter(p=>p.source==="bundled"&&p.diagnostic===void 0&&t!==void 0&&p.candidate?.provenance?.indexHash===t).map(p=>p.candidate)),diagnostics:Object.freeze(a.filter(p=>p.source==="bundled").map(p=>Object.freeze({...p}))),reservedAppIds:Object.freeze([...i.appIds]),reservedDefinitionIds:Object.freeze([...i.definitionIds])}):void 0,d={apps:s,diagnostics:a,complete:n===void 0,...n===void 0?{}:{incompleteReason:n},...t===void 0?{}:{productBundleIndexHash:t},...c===void 0?{}:{productBundleSnapshotMetadata:c}};return Object.defineProperty(d,"candidates",{configurable:false,enumerable:false,get:()=>s}),Object.freeze(d)}function ld(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 ud(e,n){if(ld(e))return {fs:e,options:{}};let t=e??n??{};return {fs:t.filesystem??t.fileSystem??t.fs??So,options:t}}async function nr(e,n,t){if(typeof e!="string"||e.length===0)throw new TypeError("workspaceRoot must be explicit");let{fs:i,options:o}=ud(n,t),r=o.clock??Yc,s=r(),a=await Uo(o.productBundle,i,s,r),c=r(),d=BigInt(Date.now())*1000000n,p=[],A=0,m,y=false,h,L;if(o.scanCache!==void 0&&typeof i.getRootIdentity=="function"&&typeof i.fingerprintVerifiedFile=="function")try{L=await i.getRootIdentity(e),h=To(o.scanCache,L),h.scanStartedAtNs=d;}catch(E){if(te(E)!=="NOT_FOUND")throw E}let S=h!==void 0&&o.productBundle===void 0&&a.packages.length===0&&a.diagnostics.length===0,j=new Set,C=true;p.push(...a.diagnostics.map(E=>({source:E.source,root:o.productBundle?.root??e,name:"",relativePath:E.relativePath,diagnostic:E})));let x=a.reservedIds;a.incomplete&&(m="time_limit");for(let E of a.packages){if(!be(c,r)){y=true,m="time_limit";break}let T=E.indexEntry,U=T.packageDir,D=E.files===void 0?void 0:Kc(U,E.files),l=a.indexHash===void 0?void 0:lo(Object.freeze({kind:"bundled",launcher:T.launcher!==false,indexHash:a.indexHash,packageDir:U,appId:T.appId,definitionId:T.definition.id,version:T.definition.version,definitionHash:T.definition.hash,files:T.files}),D),u={source:"bundled",root:o.productBundle?.root??e,name:U.slice(5),relativePath:U,...l===void 0?{}:{provenance:l},...E.files===void 0?{}:{pinnedFiles:E.files},...E.lineage===void 0?{}:{bundleLineage:E.lineage},bundleIdentity:{appId:T.appId,definitionId:T.definition.id,version:T.definition.version,definitionHash:T.definition.hash},identity:Jc(T)};if(p.push(u),A+=1,E.failureCode!==void 0){k(u,E.failureCode);continue}if(E.files?.has(V)===true){k(u,"EXEC_DENIED",{reason:{path:"",rule:"bundled-tool-mode-unsupported",file:V}});continue}let I={};for(let P of X){let b=E.files?.get(P);b!==void 0&&(I[P]=b);}if(!oi(I)){k(u,"BUNDLE_INTEGRITY");continue}if(await Go(i,u,I),!be(c,r)){y=true,m="time_limit";break}}let F=[{source:"apps",directory:"apps"},{source:"skills",directory:"skills"}];e:for(let E of F){let{source:T,directory:U}=E,D;try{D=await od(i,e,U);}catch(u){if(te(u)==="NOT_FOUND")continue;S=false,C=false,p.push({source:T,root:e,name:"",relativePath:T,diagnostic:Gn(ze(te(u),"manifest"),T,T)});continue}let l=D.filter(u=>u.kind==="directory"||u.kind==="symlink").filter(u=>Bc(u.name)).map(u=>({source:T,root:e,name:u.name,relativePath:Vc(T,u.name)})).sort((u,I)=>hn(u.relativePath,I.relativePath));for(let u of l){let I={...u};if(p.push(I),L!==void 0?j.add(Yo(L,I)):S=false,!be(c,r)){y=true,m="time_limit";break e}let P;if(h!==void 0&&L!==void 0){try{let H=await Qc(i,e,L,I,h,d,c,r);if(H.timeLimitReached){y=!0,m="time_limit";break e}I.scanContext=H.context,P=H.memo;}catch(H){S=false,k(I,ze(te(H),"manifest"));continue}P===void 0&&(S=false);}if(P!==void 0){if(I.candidate=P.candidate,I.diagnostic=P.diagnostic,I.identity=P.identity,T==="skills"&&P.candidate===void 0&&P.diagnostic===void 0)continue;if(A>=64){k(I,"LIMIT_EXCEEDED");continue}if(u.relativePath.split("/").length-1>2){k(I,"LIMIT_EXCEEDED");continue}if(A+=1,!be(c,r)){y=true,m="time_limit";break e}continue}let b;if(T==="skills"&&(b=await dd(i,I),b===void 0)){I.diagnostic===void 0&&ii(I);continue}if(A>=64){k(I,"LIMIT_EXCEEDED");continue}if(u.relativePath.split("/").length-1>2){k(I,"LIMIT_EXCEEDED");continue}if(!be(c,r)){y=true,m="time_limit";break e}if(A+=1,b===void 0){let H=await er(i,I);if(H.failure!==void 0||!oi(H.files)){k(I,H.failure??ze("NOT_FOUND","manifest")),ii(I);continue}b=H.files;}if(await Go(i,I,b),ii(I),!be(c,r)){y=true,m="time_limit";break e}}}if(h!==void 0&&L!==void 0){let E=[...j].sort(hn),T=h.lastCandidateKeys,U=T!==void 0&&T.length===E.length&&T.every((l,u)=>l===E[u]);if(S=S&&U,C&&!y&&m===void 0)for(let l of h.candidates.keys())try{JSON.parse(l)[0]===L.realPath&&!j.has(l)&&h.candidates.delete(l);}catch{h.candidates.delete(l);}let D=[...h.candidates.keys()].filter(l=>{try{return JSON.parse(l)[0]===L.realPath}catch{return false}});S=S&&D.length===j.size&&D.every(l=>j.has(l))&&!y&&m===void 0,h.lastCandidateScanUnchanged=S,C&&!y&&m===void 0&&(h.lastCandidateKeys=Object.freeze(E));}return y&&p.push({source:"apps",root:e,name:"",relativePath:"apps",diagnostic:Gn("DISCOVERY_TIME_LIMIT","apps","apps")}),ad(p,o,x),pd(p,m,a.indexHash,x,o.productBundle!==void 0)}var vc,ti,Co,Fc,Vo,Zc,Bo,tr=v(()=>{g();xe();Tn();Te();kt();ke();Bt();kn();Po();Xt();xn();ni();ni();vc=zn([]),ti="crewx_local_app_";Co=["bundled","apps","skills"],Fc=new TextDecoder("utf-8",{fatal:true});Vo=["","/ui"],Zc=["/dist"],Bo=2000000000n;});g();kt();g();gt();g();var Zi="SKILL.md",za=/^---\s*\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;function Qi(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function $a(e){return e.isDirectory()||e.isSymbolicLink()}function oo(e){try{return q.existsSync(e)&&q.statSync(e).isDirectory()}catch{return false}}function xt(e){let n;try{n=q.readFileSync(e,"utf8");}catch{return {frontmatter:{},readable:false,valid:false,hasFrontmatter:false}}let t=n.match(za);if(!t)return {frontmatter:{},readable:true,valid:true,hasFrontmatter:false};try{let i=Ar.load(t[1]??"");if(!Qi(i))return {frontmatter:{},readable:!0,valid:!1,hasFrontmatter:!0};let o=Qi(i.metadata)?i.metadata:void 0;return {frontmatter:{...typeof i.name=="string"?{name:i.name}:{},...typeof(o?.version??i.version)=="string"?{version:o?.version??i.version}:{},...typeof i.description=="string"?{description:i.description}:{}},readable:!0,valid:!0,hasFrontmatter:!0}}catch{return {frontmatter:{},readable:true,valid:false,hasFrontmatter:true}}}function Ga(e){return [ie.join(e,Zi),ie.join(e,"skill",Zi)]}function eo(e,n){if(!oo(e))return null;for(let t of Ga(e)){if(!q.existsSync(t))continue;let o=xt(t).frontmatter;return {name:o.name??n,...o.version===void 0?{}:{version:o.version},...o.description===void 0?{}:{description:o.description},skillMdPath:t,dir:e}}return null}function no(e){try{return q.readdirSync(e,{withFileTypes:!0}).filter($a)}catch{return []}}function to(e,n,t){!e||n.has(e.name)||(n.add(e.name),t.push(e));}function ro(e){let n=[],t=new Set;for(let i of e)if(oo(i))for(let o of no(i)){if(o.name.startsWith("@")){let r=ie.join(i,o.name);for(let s of no(r))to(eo(ie.join(r,s.name),s.name),t,n);continue}to(eo(ie.join(i,o.name),o.name),t,n);}return n.sort((i,o)=>i.name.localeCompare(o.name))}g();wn();var Wa=/^[A-Za-z0-9_$.[\]"-]{0,200}$/,Ja=/^[a-z][a-z0-9-]{0,63}$/,Ka="<unknown>";function Xa(e){return typeof e=="string"&&(X.includes(e)||e===V)}function so(e){if(typeof e!="object"||e===null)return;let{file:n,path:t,rule:i}=e;if(!(typeof i!="string"||!Ja.test(i)))return {...Xa(n)?{file:n}:{},path:typeof t=="string"&&Wa.test(t)?t:Ka,rule:i}}function ao(e){if(!Array.isArray(e))return;let n=X.filter(t=>e.includes(t));return n.length>0?n:void 0}tr();var yd=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/;function Xn(e){let n="screenHash"in e?e.screenHash:void 0,i=("skillHash"in e?e.skillHash:void 0)??(e.relativePath!==void 0&&e.fileBytes!==void 0?Ad(e.relativePath,e.fileBytes):void 0);if(n!==void 0&&i!==void 0){let o=JSON.stringify({screenHash:n,skillHash:i});return li.createHash("sha256").update(o,"utf8").digest("hex")}if(n!==void 0)return n;if(i!==void 0)return i;throw new TypeError("App definition hash input must contain a screenHash or skill bytes")}function Ad(e,n){let t=new TextEncoder().encode(Yn(e)),i=Id(n),o=new Uint8Array(t.byteLength+1+i.byteLength);return o.set(t,0),o[t.byteLength]=0,o.set(i,t.byteLength+1),li.createHash("sha256").update(o).digest("hex")}function Id(e){if(typeof e=="string")return new TextEncoder().encode(e);if(e instanceof Uint8Array)return new Uint8Array(e);if(e instanceof ArrayBuffer)return new Uint8Array(e.slice(0));if(Array.isArray(e)&&e.every(n=>Number.isInteger(n)&&n>=0&&n<=255))return Uint8Array.from(e);throw new TypeError("fileBytes must be UTF-8 text or bytes")}function Yn(e){if(typeof e!="string"||e.length===0||ie.isAbsolute(e)||/[\\\u0000]/.test(e))throw new TypeError("relative path must be package-relative");let n=e.split("/").filter(t=>t.length>0&&t!==".").join("/");if(!n||n.split("/").some(t=>t===".."))throw new TypeError("relative path must stay inside the package");return n}function Kn(e,n){let t=new TextEncoder().encode(e),i=new TextEncoder().encode(n),o=Math.min(t.byteLength,i.byteLength);for(let r=0;r<o;r+=1){let s=t[r]-i[r];if(s!==0)return s}return t.byteLength-i.byteLength}function rr(e,n){let t=ie.relative(e,n).split(ie.sep).join("/");return !t||t===".."||t.startsWith("../")||ie.isAbsolute(t)?null:Yn(t)}function gd(e){return e==="apps"||e.startsWith("apps/")?"apps":e==="skills"||e.startsWith("skills/")?"skills":e==="node_modules"||e.startsWith("node_modules/")?"node_modules":null}function sr(e){return Object.freeze({packageRoot:e})}function md(e){return Object.freeze({id:e.definition.id,version:e.definition.version,hash:e.definition.hash,usage:e.definition.usage??Re,...e.definition.detailPanel===void 0?{}:{detailPanel:e.definition.detailPanel},...e.definition.displayModes===void 0?{}:{displayModes:e.definition.displayModes},...e.definition.summaryProjection===void 0?{}:{summaryProjection:e.definition.summaryProjection}})}function ar(e){return {capabilities:Object.freeze([...e]),origin:"local",ownership:"unknown",shareability:"unknown",sharingAvailability:"unavailable"}}function hd(e,n){let t=e.candidate,i=t.provenance!==void 0,o=n&&!i?["screen","skill"]:["screen"],r=md(t),s=Xn(n?{screenHash:r.hash,skillHash:n.skillHash}:{screenHash:r.hash}),a=t.description||n?.skill.description||"",c=t.releaseVersion??String(t.version),d={appId:t.pluginId,name:t.name,description:a,version:c,...ar(o),definition:r,...n===void 0||i?{}:{skillName:n.skill.name},...i?{provenance:t.provenance}:{localDefinitionRef:sr(e.packageRoot)},definitionHash:s,...t.manifest.csp===void 0?{}:{connectDomains:Object.freeze([...t.manifest.csp.connectDomains])}};return {...i?{}:{packageRoot:e.packageRoot},source:i?"bundled":t.source,appId:d.appId,capabilities:o,summary:Object.freeze(d)}}function _d(e){let n=Ed(e.skill.name),t={appId:n,name:e.skill.name,description:e.skill.description??"",...e.skill.version===void 0?{}:{version:e.skill.version},...ar(["skill"]),skillName:e.skill.name,localDefinitionRef:sr(e.packageRoot),definitionHash:Xn({skillHash:e.skillHash})};return {packageRoot:e.packageRoot,source:e.source,appId:n,capabilities:["skill"],summary:Object.freeze(t)}}function Ed(e){return `skill.${e.replace(/^@/,"").replace(/\//g,".").replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,122)||"unnamed"}`}function Y(e,n,t,i,o){let r=so(o?.reason),s=ao(o?.files);return Object.freeze({code:e,source:n,relativePath:Td(t),...i===void 0?{}:{appId:i},...r===void 0?{}:{reason:r},...s===void 0?{}:{files:s}})}function Td(e){if(typeof e!="string"||e.length===0||ie.isAbsolute(e)||/[\\\u0000]/.test(e))return "<unknown>";let n=e.split("/").filter(t=>t.length>0&&t!==".").join("/");return n.split("/").some(t=>t==="..")?"<unknown>":n}function cr(e){return Y(e.code,e.source,e.relativePath,e.pluginId,e)}function Pd(e,n){let t=rr(e,n.dir);if(!t)return {diagnostic:Y("PATH_ESCAPED","node_modules","node_modules")};let i=gd(t);if(!i)return {diagnostic:Y("PATH_ESCAPED","node_modules",t)};let o=xt(n.skillMdPath);if(!o.readable)return {diagnostic:Y("SKILL_READ_FAILED",i,t)};if(!o.valid)return {diagnostic:Y("SKILL_INVALID",i,t)};let r=Nd(n.dir,n.skillMdPath);if(!r)return {diagnostic:Y("PATH_ESCAPED",i,t)};try{let s=new Uint8Array(q.readFileSync(n.skillMdPath));return {skill:n,packageRoot:t,relativeSkillPath:r,skillHash:Xn({relativePath:r,fileBytes:s}),source:i}}catch{return {diagnostic:Y("SKILL_READ_FAILED",i,t)}}}function Nd(e,n){let t=ie.relative(e,n).split(ie.sep).join("/");try{return Yn(t)}catch{return null}}function Dd(e){if(!yd.test(e.appId))return {diagnostic:Y("BUILTIN_INVALID","builtin",`builtin/${e.appId||"unknown"}`)};let n=e.definition===void 0?void 0:{id:e.definition.id,version:e.definition.version,hash:e.definition.hash,usage:e.definition.usage??Re,...e.definition.detailPanel===void 0?{}:{detailPanel:e.definition.detailPanel},...e.definition.displayModes===void 0?{}:{displayModes:e.definition.displayModes},...e.definition.summaryProjection===void 0?{}:{summaryProjection:e.definition.summaryProjection}},t=n?.hash??li.createHash("sha256").update(JSON.stringify({appId:e.appId,name:e.name,description:e.description}),"utf8").digest("hex"),i={appId:e.appId,name:e.name,description:e.description,...n===void 0?{}:{version:String(n.version),definition:n},capabilities:["screen"],origin:"builtin",ownership:"unknown",shareability:"forbidden",sharingAvailability:"unavailable",definitionHash:t};return {source:"builtin",appId:e.appId,summary:Object.freeze(i)}}function bd(e){return e.builtinCatalog}function Sd(e){let n=e.packageRoot??e.relativePath??e.packageRootPath;if(n===void 0)return null;try{return Yn(n)}catch{return null}}function Md(e){let n=e.marketplaceContentId;return typeof n=="string"&&n.length>0?n:void 0}function Ld(e,n,t){let i=n.installed??[],o=new Map;for(let s of i){let a=Sd(s);if(!a){t.push(Y("INSTALLED_IDENTITY_MISMATCH","installed","installed"));continue}let c=o.get(a);if(c&&JSON.stringify(c)!==JSON.stringify(s)){t.push(Y("INSTALLED_IDENTITY_MISMATCH","installed",a));continue}o.set(a,s);}let r=new Map;for(let s of e)s.packageRoot!==void 0&&r.set(s.packageRoot,s);for(let[s,a]of o){let c=r.get(s);if(!c){t.push(Y("INSTALLED_MISSING","installed",s,a.appId));continue}let d=Md(a);if(!d){t.push(Y("INSTALLED_CONTENT_ID_MISSING","installed",s,a.appId));continue}if(a.appId!==void 0&&a.appId!==c.appId||a.definitionHash!==void 0&&a.definitionHash!==c.summary.definitionHash){t.push(Y("INSTALLED_IDENTITY_MISMATCH","installed",s,a.appId));continue}let p={...c.summary,origin:"installed",...a.slug===void 0?{}:{slug:a.slug},marketplaceContentId:d},A=e.indexOf(c);A>=0&&(e[A]={...c,summary:Object.freeze(p)});}}function Od(e,n){let t=new Map;for(let o of e){let r=t.get(o.appId)??[];r.push(o),t.set(o.appId,r);}let i=new Set;for(let o of t.values()){if(o.length<2)continue;let r=o.some(s=>s.source==="builtin")?"builtin":o.some(s=>s.source==="bundled")?"bundled":void 0;if(r!==void 0){let s=o.filter(a=>a.source===r);for(let a of o.filter(c=>c.source!==r))i.add(a),n.push(Y("RESERVED_ID",a.source,si(a),a.appId));if(s.length>1)for(let a of s)i.add(a),n.push(Y("DUPLICATE_ID",a.source,si(a),a.appId));continue}for(let s of o)i.add(s),n.push(Y("DUPLICATE_ID",s.source,si(s),s.appId));}return e.filter(o=>!i.has(o))}function si(e){return e.packageRoot??e.summary.provenance?.packageDir??`builtin/${e.appId}`}function Rd(e,n){return e.filter(t=>!(t.code==="MANIFEST_MISSING"&&n.has(t.relativePath))).map(cr)}function wd(e){return e.filesystem}function Ud(e,n){let t=wd(e),i=e.registeredProductBundle;return {...t===void 0?{}:{filesystem:t},...e.productBundle===void 0?{}:{productBundle:e.productBundle},...n===void 0?{}:{builtinCatalog:n},...i===void 0?{}:{reservedAppIds:i.reservedAppIds,reservedDefinitionIds:i.reservedDefinitionIds}}}async function dr(e,n={}){if(typeof e!="string"||e.length===0)throw new TypeError("workspaceRoot must be explicit");if(n.productBundle!==void 0&&n.registeredProductBundle!==void 0)throw new TypeError("registeredProductBundle cannot be combined with product bundle discovery");let t=bd(n),i=await nr(e,Ud(n,t)),o=n.registeredProductBundle??i.productBundleSnapshotMetadata,r=[ie.join(e,"skills"),ie.join(e,"node_modules"),ie.join(e,"apps")],s=[],a=[],c=[],d=new Set;for(let u of r)for(let I of ro([u])){let P=rr(e,I.dir);(P===null||!d.has(P))&&(c.push(I),P!==null&&d.add(P));}for(let u of c){let I=Pd(e,u);"diagnostic"in I?s.push(I.diagnostic):a.push(I);}let p=new Map,A=n.registeredProductBundle?.indexHash,m=(n.registeredProductBundle?.candidates??[]).filter(u=>A!==void 0&&u.provenance?.indexHash===A),y=[...i.apps??i.candidates??[],...m],h=new Set(m),L=new Set(A===void 0?[]:(t?.listMcpApps()??[]).filter(u=>u.provenance?.indexHash===A).map(u=>u.appId));for(let u of y){if(h.has(u)&&u.provenance?.indexHash===A&&L.has(u.appId))continue;let I=u.provenance===void 0?`workspace\0${u.relativePath}`:`bundled\0${u.provenance.indexHash}\0${u.provenance.packageDir}`;p.set(I,{candidate:u,packageRoot:u.relativePath});}let S=new Map(a.map(u=>[u.packageRoot,u])),j=[];for(let u of p.values()){let I=u.candidate.provenance===void 0?S.get(u.packageRoot):void 0,P=hd(u,I);j.push({...P.packageRoot===void 0?{}:{packageRoot:P.packageRoot},source:P.source,appId:P.appId,summary:P.summary});}let C=new Set([...p.values()].filter(u=>u.candidate.provenance===void 0).map(u=>u.packageRoot)),x=o===void 0?new Set:new Set(i.diagnostics.filter(u=>u.code==="RESERVED_ID"&&u.source!=="bundled").map(u=>u.relativePath)),F=new Set(o?.reservedAppIds??[]);for(let u of a){let I=_d(u);if(!(C.has(u.packageRoot)||x.has(u.packageRoot))){if(F.has(I.appId)){s.push(Y("RESERVED_ID",u.source,u.packageRoot,I.appId));continue}j.push({packageRoot:I.packageRoot,source:I.source,appId:I.appId,summary:I.summary});}}let E=[...Rd(i.diagnostics,new Set(a.map(u=>u.packageRoot))),...s,...n.registeredProductBundle?.diagnostics.filter(u=>u.source==="bundled").map(cr)??[]],T=[];if(t)for(let u of t.listMcpApps()){let I=Dd(u);"diagnostic"in I?E.push(I.diagnostic):T.push(I);}let U=Od([...j,...T],E);Ld(U,n,E);let D=U.map(u=>u.summary).sort((u,I)=>Kn(u.appId,I.appId)),l=[...E].sort((u,I)=>Kn(u.relativePath,I.relativePath)||Kn(u.code,I.code)||Kn(u.appId??"",I.appId??""));return Object.freeze({items:Object.freeze(D),diagnostics:Object.freeze(l)})}g();g();g();function Cd(e){let n=o=>o.replace(/[.+^${}()|[\]\\]/g,"\\$&"),i=e.split("/").map(o=>o==="**"?".*":o.split("*").map(n).join("[^/]*"));return new RegExp(`^${i.join("\\/")}$`)}function tn(e,n){try{return Cd(n).test(e)}catch{return false}}function qn(e,...n){let t=e.split("/");if(t.length<n.length)return false;let i=t.length-n.length;return n.every((o,r)=>tn(t[i+r],o))}function kd(e,n){return e.split("/").some(t=>tn(t,n))}var pr=[{label:".env*",test:e=>tn(e,".env*")},{label:".git/",test:(e,n,t)=>t&&e===".git"},{label:"memory/",test:(e,n,t)=>t&&e==="memory"},{label:"*.key",test:e=>tn(e,"*.key")},{label:"*.pem",test:e=>tn(e,"*.pem")},{label:"auth.json",test:e=>e==="auth.json"},{label:"node_modules/",test:(e,n,t)=>t&&e==="node_modules"},{label:"conversations/",test:(e,n,t)=>t&&e==="conversations"},{label:".crewx/threads/",test:(e,n,t)=>t&&qn(n,".crewx","threads")},{label:".crewx/crewx.db",test:(e,n,t)=>!t&&qn(n,".crewx","crewx.db")},{label:".crewx/*.log",test:(e,n,t)=>!t&&qn(n,".crewx","*.log")},{label:".crewx/publish/",test:(e,n,t)=>t&&qn(n,".crewx","publish")},{label:".crewx/",test:(e,n)=>kd(n,".crewx")}];function Zn(e,n,t){for(let i of pr)if(i.test(e,n,t))return i.label;return null}function di(e){let n=[],t=[];function i(o,r,s){let a;try{a=q__namespace.readdirSync(o,{withFileTypes:!0});}catch{return}a.sort((c,d)=>c.name.localeCompare(d.name));for(let c of a){let d=r?`${r}/${c.name}`:c.name,p=ie__namespace.join(o,c.name);if(c.isSymbolicLink()){let A;try{A=q__namespace.statSync(p);}catch{t.push({path:d,rule:"symlink"});continue}if(A.isDirectory()){t.push({path:d,rule:s??"symlink-dir"});continue}let m=s??Zn(c.name,d,false);m?t.push({path:d,rule:m}):t.push({path:d,rule:"symlink"});continue}if(c.isDirectory()){let A=s??Zn(c.name,d,true);i(p,d,A);continue}if(c.isFile()){let A=s??Zn(c.name,d,false);A?t.push({path:d,rule:A}):n.push(d);}}}return i(e,"",null),n.sort(),t.sort((o,r)=>o.path<r.path?-1:o.path>r.path?1:0),{included:n,excluded:t}}g();var xd=[{rule:"token-prefix",regex:/\b(?:sk-|ghp_|xoxb-)[A-Za-z0-9_-]{10,}/},{rule:"private-key",regex:/-----BEGIN [A-Z ]*PRIVATE KEY-----/},{rule:"aws-access-key",regex:/\bAKIA[0-9A-Z]{16}\b/}];function vd(e){return e.includes(0)}function pi(e,n,t){let i=[];for(let o of n){let r=ie__namespace.join(e,o),s;try{let c=t?.get(o);s=c===void 0?q__namespace.readFileSync(r):Buffer.from(c);}catch{continue}if(vd(s))continue;s.toString("utf8").split(/\r\n|\r|\n/).forEach((c,d)=>{for(let{rule:p,regex:A}of xd)A.test(c)&&i.push({path:o,line:d+1,rule:p});});}return i}g();g();var Me=class extends Error{constructor(t,i){super(`publish: [${t}]${i?` ${i}`:""}`);this.code=t;}code;name="PublishError"};function _(e,n){return new Me(e,n)}var yr=/^[a-z0-9-]+$/,jd=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/,Fd=/^[A-Za-z_][A-Za-z0-9_]*$/;function Vd(e){let n=ie__namespace.join(e,"crewx.yaml");if(!q__namespace.existsSync(n))return {};let t;try{t=Ar__namespace.load(q__namespace.readFileSync(n,"utf8"));}catch{return {}}if(!t||typeof t!="object")return {};let i=t.metadata;if(!i||typeof i!="object")return {};let o=i;return {name:typeof o.name=="string"?o.name:void 0,version:typeof o.version=="string"?o.version:void 0,description:typeof o.description=="string"?o.description:void 0,requiredEnv:o.requiredEnv,crewxMinVersion:typeof o.crewxMinVersion=="string"?o.crewxMinVersion:void 0}}function Bd(e){return li__namespace.createHash("sha256").update(e).digest("hex")}function Ir(e){let n;try{n=q__namespace.lstatSync(e);}catch{throw _("PACKAGE_FILE_INVALID",`file is not readable: ${ie__namespace.basename(e)}`)}if(n.isSymbolicLink())throw _("PACKAGE_SYMLINK","symlink content is not publishable");if(!n.isFile())throw _("PACKAGE_FILE_INVALID","only regular files are publishable");return li__namespace.createHash("sha256").update(new Uint8Array(q__namespace.readFileSync(e))).digest("hex")}function Hd(e,n){let t=new TextEncoder().encode(e),i=new TextEncoder().encode(n),o=Math.min(t.byteLength,i.byteLength);for(let r=0;r<o;r+=1){let s=t[r]-i[r];if(s!==0)return s}return t.byteLength-i.byteLength}function gr(e){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||ie__namespace.posix.isAbsolute(e)||e.split("/").some(n=>n===".."||n.length===0))throw _("PACKAGE_PATH_TRAVERSAL","manifest file path must be a non-empty POSIX relative path")}function zd(e){if(!/^(?:apps|skills)\/[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(e))throw _("APP_PACKAGE_ROOT_INVALID","packageRoot must be apps/<safe-id> or skills/<safe-id>")}function mr(e){if(!jd.test(e))throw new Error(`publish: invalid version "${e}" \u2014 must be semver (e.g. 1.0.0)`)}function hr(e,n,t={}){let i=Vd(e),o=i.name??ie__namespace.basename(e);if(!yr.test(o))throw new Error(`publish: invalid name "${o}" \u2014 must match ${yr} (lowercase letters, numbers, hyphen only)`);let r=t.version??i.version;if(!r)throw new Error("publish: version is required \u2014 set crewx.yaml metadata.version or pass opts.version");mr(r);let s=Array.isArray(i.requiredEnv)?i.requiredEnv:[],a=[];for(let p of s){if(typeof p!="string"||!Fd.test(p))throw new Error(`publish: requiredEnv must contain names only (no values), got "${String(p)}"`);a.push(p);}let c=n.map(p=>(gr(p),{path:p,sha256:Ir(ie__namespace.join(e,p))})).sort((p,A)=>p.path<A.path?-1:p.path>A.path?1:0),d={name:o,version:r,type:"template",description:i.description??"",files:c,requiredEnv:a};return i.crewxMinVersion&&(d.crewxMinVersion=i.crewxMinVersion),d}function $d(e){let n=e.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"");if(!n)throw _("APP_PACKAGE_ROOT_INVALID","appId cannot produce a marketplace name");return n}function _r(e,n){if(zd(n.packageRoot),!n.version)throw new Error("publish: version is required for App publishing \u2014 pass opts.version");if(mr(n.version),typeof n.description!="string")throw new Error("publish: App description must be a string");let t=[...new Set(n.capabilities)].sort();if(t.length===0||t.some(s=>s!=="screen"&&s!=="skill"))throw new Error("publish: App capabilities must contain screen or skill");let i=`${n.packageRoot}/`;if(t.includes("screen")){if(typeof n.definitionId!="string"||n.definitionId.length===0)throw _("APP_UI_MANIFEST_INVALID","screen App manifests require definitionId");let s=n.includedFiles.includes(`${i}manifest.json`),a=n.includedFiles.includes(`${i}ui-plugin.json`);if(!s&&!a)throw _("APP_UI_MANIFEST_INVALID","screen App is missing manifest.json or ui-plugin.json");if(s&&!a)throw _("APP_UI_MANIFEST_INVALID","a manifest.json App must also ship a generated ui-plugin.json");if(!n.includedFiles.includes(`${i}ui/index.html`))throw _("APP_UI_MANIFEST_INVALID","screen App is missing ui/index.html")}if(t.includes("skill")&&!n.includedFiles.includes(`${i}SKILL.md`))throw _("APP_SKILL_MISSING","skill capability requires package-root SKILL.md");let o=new Set,r=n.includedFiles.map(s=>{if(gr(s),!s.startsWith(i))throw _("PACKAGE_PATH_TRAVERSAL","App manifest file is outside packageRoot");let a=n.generatedFiles?.get(s);return a!==void 0&&o.add(s),{path:s,sha256:a===void 0?Ir(ie__namespace.join(e,s)):Bd(a),...a===void 0?{}:{generated:true}}}).sort((s,a)=>Hd(s.path,a.path));if(o.size>0&&(o.size!==1||!o.has(`${i}ui-plugin.json`)))throw new Error("publish: only the generated ui-plugin.json may be present in an App package");return {manifestVersion:1,name:$d(n.appId),version:n.version,type:"app",description:n.description,appId:n.appId,...n.definitionId===void 0?{}:{definitionId:n.definitionId},...n.definitionHash===void 0?{}:{definitionHash:n.definitionHash},capabilities:t,packageRoot:n.packageRoot,files:r,requiredEnv:[]}}g();function Er(e){return li__namespace.createHash("sha256").update(e).digest("hex")}function br(e,n){if(typeof n!="string"||n.length===0||n.includes("\\")||n.includes("\0")||ie__namespace.posix.isAbsolute(n)||n.split("/").some(o=>o===".."||o.length===0))throw _("PACKAGE_PATH_TRAVERSAL","archive paths must be non-empty POSIX relative paths");let t=ie__namespace.resolve(e),i=ie__namespace.resolve(t,...n.split("/"));if(i!==t&&!i.startsWith(`${t}${ie__namespace.sep}`))throw _("PACKAGE_PATH_TRAVERSAL","archive path escaped its root");return i}function Tr(e,n){let t=br(e,n),i;try{i=q__namespace.lstatSync(t);}catch{throw _("PACKAGE_FILE_INVALID","manifest file is missing")}if(i.isSymbolicLink())throw _("PACKAGE_SYMLINK","symlink content is not publishable");if(!i.isFile())throw _("PACKAGE_FILE_INVALID","only regular files are publishable");return new Uint8Array(q__namespace.readFileSync(t))}async function Sr(e,n,t={}){let i=ie__namespace.join(e,".crewx","publish");q__namespace.mkdirSync(i,{recursive:true});let o=ie__namespace.join(i,`${n.name}-${n.version}.tgz`),r=ie__namespace.join(i,`.${n.name}-${n.version}.${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}.tmp.tgz`),s=q__namespace.mkdtempSync(ie__namespace.join(Pr__namespace.tmpdir(),"crewx-publish-"));try{let a=new Set,c=[];for(let d of n.files){if(a.has(d.path))throw _("PACKAGE_PATH_TRAVERSAL","manifest contains duplicate file paths");a.add(d.path);let p=t.generatedFiles?.get(d.path);if(d.generated===!0&&p===void 0)throw _("PACKAGE_GENERATED_FILE_MISSING","generated manifest file bytes are missing");if(t.sourceFileHashes?.has(d.path)){let y=Tr(e,d.path);if(t.sourceFileHashes.get(d.path)!==Er(y))throw _("PACKAGE_STAGED_BYTES_MISMATCH","workspace source changed before staging")}let A=p??Tr(e,d.path);if(Er(A)!==d.sha256)throw _("PACKAGE_STAGED_BYTES_MISMATCH",`staged bytes differ for ${d.path}`);let m=br(s,d.path);q__namespace.mkdirSync(ie__namespace.dirname(m),{recursive:!0}),q__namespace.writeFileSync(m,new Uint8Array(A)),c.push(d.path);}q__namespace.writeFileSync(ie__namespace.join(s,"manifest.json"),JSON.stringify(n,null,2)),await Dr__namespace.create({gzip:!0,file:r,cwd:s,portable:!0,noMtime:!0},["manifest.json",...c]),q__namespace.renameSync(r,o);}finally{try{q__namespace.rmSync(r,{force:!0});}catch{}q__namespace.rmSync(s,{recursive:true,force:true});}return o}g();g();var on="/api/v1";var Jd=201,Kd=200,Xd=409,ui=401,Mr={APP_NAME_CONFLICT:"APP_NAME_CONFLICT",CONTENT_SUSPENDED:"PUBLISH_CONTENT_SUSPENDED",CONTENT_REJECTED:"CONTENT_REJECTED",APP_VERSION_MUST_INCREASE:"APP_VERSION_MUST_INCREASE",APP_VERSION_INVALID:"APP_VERSION_INVALID"};function Yd(){return process.env.WI013_FAKE_UPLOAD==="1"}function qd(e){let n=zlib.gunzipSync(new Uint8Array(e)),t=zlib.gzipSync(new Uint8Array(n),{level:1});if(Buffer.compare(new Uint8Array(t),new Uint8Array(e))===0)throw new Error("publish: [E_MALFORMED] Re-gzipped upload bytes are identical to the original \u2014 tamper is a no-op");return t}function Zd(e){return e.replace(/\/+$/,"")}async function _n(e){try{return await e.json()}catch{return null}}function Lr(e,n,t){let i=e;if(!i||i.success!==true||i.data===void 0)throw new Error(`publish: [E_MALFORMED] ${n} response envelope is malformed (expected { success: true, data }) \u2014 HTTP ${t}`);return i.data}function Qd(e){if(!e||typeof e!="object"||Array.isArray(e))return;let n=e;if(typeof n.contentId=="string"&&n.contentId.length>0)return n.contentId;if(!n.data||typeof n.data!="object"||Array.isArray(n.data))return;let t=n.data;return typeof t.contentId=="string"&&t.contentId.length>0?t.contentId:void 0}function ep(e){if(!e||typeof e!="object"||Array.isArray(e))return;let n=e;if(typeof n.slug=="string"&&n.slug.length>0)return n.slug;if(!n.data||typeof n.data!="object"||Array.isArray(n.data))return;let t=n.data;return typeof t.slug=="string"&&t.slug.length>0?t.slug:void 0}function Or(e,n){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e,i=t.data&&typeof t.data=="object"&&!Array.isArray(t.data)?t.data:void 0,o=[t.code,t.message,i?.code,i?.message];for(let r of o){if(typeof r!="string"||!Object.prototype.hasOwnProperty.call(Mr,r))continue;let s=r,a=s==="APP_NAME_CONFLICT"?`marketplace name is already in use: ${n}`:void 0;return _(Mr[s],a)}}async function np(e){if(!e.baseUrl.trim())throw new Error("publish: [E_ENV_MISSING] Marketplace base URL is required");if(!e.accessToken.trim())throw new Error("publish: [E_AUTH_EXPIRED] A valid bearer token is required");let n=Zd(e.baseUrl),t=e.accessPolicy??"private",i=e.manifest.name,o=e.manifest.type==="app"?e.manifest:void 0,r=o!==void 0,s=o?.appId,a;try{a=await fetch(`${n}${on}/publisher/items`,{method:"POST",headers:{Authorization:`Bearer ${e.accessToken}`,"Content-Type":"application/json"},body:JSON.stringify({slug:i,displayName:i,description:e.manifest.description,type:e.manifest.type,version:e.manifest.version,accessPolicy:t,...s===void 0?{}:{appId:s}})});}catch{throw new Error("publish: [E_NETWORK] Submit request failed (network)")}let c=await _n(a),d=Qd(c),p=ep(c),A=r&&p!==void 0?p:i,m;if(a.status===Jd)m="created";else if(r&&a.status===Kd){if(d===void 0)throw _("PUBLISH_CONTENT_ID_MISSING","App republish did not return an opaque contentId");m="existing";}else if(a.status===Xd){if(r)throw Or(c,i)??_("APP_NAME_CONFLICT",`marketplace name is already in use: ${i}`);m="existing";}else throw a.status===ui?new Error("publish: [E_AUTH_EXPIRED] Authentication is expired or missing \u2014 please log in again (HTTP 401)"):new Error(`publish: [E_HTTP] Submit request failed \u2014 HTTP ${a.status}`);let y="not-needed",h=null;if(m==="existing"&&!r){let U;try{U=await fetch(`${n}${on}/publisher/items`,{method:"GET",headers:{Authorization:`Bearer ${e.accessToken}`}});}catch{throw new Error("publish: [E_NETWORK] Publisher items request failed (network)")}let D=await _n(U);if(U.status!==200)throw new Error(`publish: [E_HTTP] Publisher items request failed \u2014 HTTP ${U.status}`);let u=Lr(D,"publisher items",U.status)?.items;if(!Array.isArray(u))throw new Error(`publish: [E_MALFORMED] Publisher items response is malformed (expected data.items[]) \u2014 HTTP ${U.status}`);let I=u.find(P=>!P||typeof P!="object"?false:P.slug===i);if(!I||typeof I.version!="string")throw new Error(`publish: [E_MALFORMED] Publisher items response does not contain slug "${i}" \u2014 HTTP ${U.status}`);if(h=I.version,h!==e.manifest.version){let P;try{P=await fetch(`${n}${on}/publisher/items/${encodeURIComponent(i)}`,{method:"PUT",headers:{Authorization:`Bearer ${e.accessToken}`,"Content-Type":"application/json"},body:JSON.stringify({version:e.manifest.version})});}catch{throw new Error("publish: [E_NETWORK] Version update request failed (network)")}if(!P.ok)throw await _n(P),P.status===ui?new Error(`publish: [E_AUTH_EXPIRED] Authentication is expired or missing \u2014 please log in again (HTTP ${P.status})`):P.status===403?new Error(`publish: [E_FORBIDDEN] Version update is forbidden; only the item owner can update an existing item (HTTP ${P.status})`):new Error(`publish: [E_HTTP] Version update failed \u2014 HTTP ${P.status}`);y="applied";}}let L=q__namespace.readFileSync(e.tgzPath),S=Yd()?qd(L):L,j=new FormData;j.set("archive",new Blob([new Uint8Array(S)],{type:"application/gzip"}),`${A}-${e.manifest.version}.tgz`);let C=r&&d!==void 0?d:i,x;try{x=await fetch(`${n}${on}/publisher/items/${encodeURIComponent(C)}/upload`,{method:"POST",headers:{Authorization:`Bearer ${e.accessToken}`},body:j});}catch{throw new Error("publish: [E_NETWORK] Upload request failed (network)")}if(x.status===ui)throw new Error("publish: [E_AUTH_EXPIRED] Authentication is expired or missing \u2014 please log in again (HTTP 401)");if(!x.ok){let U=await _n(x);if(r){let D=Or(U,A);if(D)throw D}throw new Error(`publish: [E_HTTP] Upload request failed \u2014 HTTP ${x.status}`)}let F=await _n(x),E=Lr(F,"upload",x.status),T=typeof E.contentId=="string"&&E.contentId.length>0?E.contentId:d;if(r&&T===void 0)throw _("PUBLISH_CONTENT_ID_MISSING","App upload did not return an opaque contentId");return {slug:A,version:e.manifest.version,...T===void 0?{}:{contentId:T},artifactChecksum:E.artifactChecksum,artifactSizeBytes:E.artifactSizeBytes,submitOutcome:m,versionUpdate:y,serverVersionBefore:h}}var tp=1e4,ip=100*1024*1024;function fi(e){return li__namespace.createHash("sha256").update(e).digest("hex")}function op(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function En(e,n){if(!n||n.includes("\\")||n.includes("\0")||ie__namespace.posix.isAbsolute(n)||n.split("/").some(r=>r===".."||r.length===0))throw _("PACKAGE_PATH_TRAVERSAL","workspace file path is not a safe relative path");let t=ie__namespace.resolve(e,...n.split("/")),i=ie__namespace.resolve(e);if(t!==i&&!t.startsWith(`${i}${ie__namespace.sep}`))throw _("PACKAGE_PATH_TRAVERSAL","workspace file path escaped the workspace root");let o;try{o=q__namespace.lstatSync(t);}catch{throw _("PACKAGE_FILE_INVALID",`workspace file is missing: ${n}`)}if(o.isSymbolicLink())throw _("PACKAGE_SYMLINK",`symlink is not publishable: ${n}`);if(!o.isFile())throw _("PACKAGE_FILE_INVALID",`not a regular file: ${n}`);return new Uint8Array(q__namespace.readFileSync(t))}function et(e,n){return e===n||e.startsWith(`${n}/`)}function rp(e,n){return e.path<n.path?-1:e.path>n.path?1:e.rule.localeCompare(n.rule)}function wr(e,n,t){let i=e??n;if(!Number.isSafeInteger(i)||i<=0)throw new Me("PACKAGE_SIZE_LIMIT",`${t} must be a positive integer`);return i}function Cr(e,n,t,i){let o=wr(t.maxFileCount??t.maxFiles,tp,"max file count"),r=wr(t.maxTotalBytes??t.maxBytes,ip,"max total bytes");if(n.length>o)throw new Me("PACKAGE_SIZE_LIMIT",`package exceeds file count limit (${o})`);let s=0;for(let a of n){let c=i?.get(a);if(c!==void 0?s+=c.byteLength:s+=En(e,a).byteLength,s>r)throw new Me("PACKAGE_SIZE_LIMIT",`package exceeds byte limit (${r})`)}}function sp(e){return e.appId!==void 0||e.expectedDefinitionHash!==void 0}function ap(e){let n=e.appId!==void 0,t=e.expectedDefinitionHash!==void 0;if(!n&&t)throw _("APP_ID_REQUIRED","appId is required with expectedDefinitionHash");if(n&&!t)throw _("APP_DEFINITION_HASH_REQUIRED","expectedDefinitionHash is required with appId");if(!n||!t)throw _("APP_ID_REQUIRED")}function cp(e,n){let t=e.filter(i=>i.appId===n);if(t.length===0)throw _("APP_NOT_FOUND",`no publishable App matches ${n}`);if(t.length!==1)throw _("APP_AMBIGUOUS",`more than one App matches ${n}`);return t[0]}function dp(e){let n=e.localDefinitionRef?.packageRoot;if(!n||!/^(?:apps|skills)\/[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(n))throw _("APP_PACKAGE_ROOT_INVALID","selected App is not rooted in apps/<safe-id> or skills/<safe-id>");return n}function pp(e,n){let t=[];for(let i of e.excluded)t.push(et(i.path,n)?i:{path:i.path,rule:"out-of-app-scope"});for(let i of e.included)et(i,n)||t.push({path:i,rule:"out-of-app-scope"});return t.sort(rp)}function yi(e){let{path:n,rule:t}=e.reason;return `${e.code} at ${n===""?"<file>":n} (${t})`+(e.files.length>0?` [${e.files.join(", ")}]`:"")}function lp(e,n,t){let i=Fe({[re]:t},{mode:"published"});if(!i.ok)throw _("APP_UI_MANIFEST_INVALID",`generated ${re} does not read: ${yi(i.rejection)}`);if(Qe(i.manifest)!==Qe(n))throw _("APP_UI_MANIFEST_INVALID",`generated ${re} normalizes to a different definition hash than the source`);let o=e[G];if(o===void 0)return;let r=e[V],s=Fe({[G]:o,[re]:t,...r===void 0?{}:{[V]:r}},{mode:"local"});if(!s.ok)throw _("APP_UI_MANIFEST_INVALID",yi(s.rejection))}function up(e,n,t,i){let o={};for(let y of X){let h=`${t}/${y}`;i.includes(h)&&(o[y]=En(e,h));}let r=`${t}/${V}`;if(o[G]!==void 0&&i.includes(r)&&(o[V]=En(e,r)),Object.keys(o).length===0)throw _("APP_UI_MANIFEST_INVALID","selected screen App has no package manifest.json or ui-plugin.json");let s=Fe(o,{mode:"local"});if(!s.ok)throw _("APP_UI_MANIFEST_INVALID",yi(s.rejection));if(s.manifest.pluginId!==n.appId)throw _("APP_DEFINITION_CONFLICT",`${s.file} identity no longer matches the selected App`);let a=o[re],c=a===void 0?void 0:fi(a),d=`${t}/ui/index.html`;if(!i.includes(d))throw _("APP_UI_MANIFEST_INVALID","screen entry is outside package scope");let p=fi(En(e,d)),A=JSON.parse(JSON.stringify(s.v2Input));if(A.entryHash=p,Object.prototype.hasOwnProperty.call(A,"initialState")){let y=A.initialState;if(!op(y)||y.path!=="ui/state.json")throw _("APP_INITIAL_STATE_OUT_OF_SCOPE","initialState must reference ui/state.json inside the package");let h=`${t}/ui/state.json`;if(!i.includes(h))throw _("APP_INITIAL_STATE_OUT_OF_SCOPE","initialState reference is outside the selected package");let L=En(e,h);A.initialState={...y,hash:fi(L)};}let m;try{let y=je(A,{mode:"published"});m=new Uint8Array(Buffer.from(JSON.stringify(y),"utf8"));}catch(y){throw y instanceof ne?_("APP_UI_MANIFEST_INVALID",y.code):_("APP_UI_MANIFEST_INVALID")}return lp(o,s.manifest,m),{bytes:m,...c===void 0?{}:{legacySourceHash:c}}}async function fp(e,n){let{included:t,excluded:i}=di(e);Cr(e,t,n);let o=hr(e,t,{version:n.version}),r=pi(e,t);return {plan:{manifest:o,included:t,excluded:i,secretFindings:r},archiveOptions:{}}}async function yp(e,n){ap(n);let t=await dr(e),i=cp(t.items,n.appId);if(i.definitionHash!==n.expectedDefinitionHash)throw _("APP_DEFINITION_CONFLICT",`definitionHash changed for ${n.appId}`);let o=dp(i),r=di(e);if(r.excluded.some(y=>et(y.path,o)&&(y.rule==="symlink"||y.rule==="symlink-dir")))throw _("PACKAGE_SYMLINK","selected App package contains a symlink");let s=r.included.filter(y=>et(y,o)),a=pp(r,o),c=new Map,d=new Map;if(i.capabilities.includes("screen")){let y=up(e,i,o,s),h=`${o}/${re}`;c.set(h,y.bytes),y.legacySourceHash!==void 0?d.set(h,y.legacySourceHash):(s.push(h),s.sort());}if(i.capabilities.includes("skill")&&!s.includes(`${o}/SKILL.md`))throw _("APP_SKILL_MISSING","skill capability requires package-root SKILL.md");Cr(e,s,n,c);let p={appId:i.appId,version:n.version??"",description:i.description,capabilities:i.capabilities,packageRoot:o,...i.definition?.id===void 0?{}:{definitionId:i.definition.id},definitionHash:i.definitionHash,includedFiles:s,generatedFiles:c},A=_r(e,p),m=pi(e,s,c);return {plan:{manifest:A,included:s,excluded:a,secretFindings:m},archiveOptions:{generatedFiles:c,sourceFileHashes:d}}}async function kr(e,n){let t=ie__namespace.resolve(e);if(sp(n))return yp(t,n);if(n.expectedDefinitionHash!==void 0)throw _("APP_ID_REQUIRED");return fp(t,n)}async function fy(e,n={}){return (await kr(e,n)).plan}function Ap(e){let n=e.map(t=>`${t.path}:${t.line} (${t.rule})`).join(", ");throw new Me("PUBLISH_SECRET_FINDINGS",`aborted \u2014 secret findings must be resolved before packing: ${n}`)}async function xr(e,n={}){let t=ie__namespace.resolve(e),i=await kr(t,n);i.plan.secretFindings.length>0&&Ap(i.plan.secretFindings);let o=await Sr(t,i.plan.manifest,i.archiveOptions);return {manifest:i.plan.manifest,tgzPath:o}}async function yy(e,n={}){return xr(e,n)}async function Ay(e,n){let t=await xr(e,n);if(t.manifest.type!=="app")throw new Error("publish: App pack unexpectedly produced a template manifest");return t}
2
- exports.DEFAULT_PUBLISH_MAX_BYTES=ip;exports.DEFAULT_PUBLISH_MAX_FILES=tp;exports.EXCLUDE_RULES=pr;exports.MARKETPLACE_API_PREFIX=on;exports.PublishError=Me;exports.packApp=Ay;exports.packPublish=xr;exports.packTemplate=yy;exports.planPublish=fy;exports.uploadToMarketplace=np;
1
+ 'use strict';var bi=require('crypto'),net=require('net'),ee=require('fs'),promises=require('fs/promises'),ae=require('path'),Wr=require('js-yaml'),es=require('os'),ts=require('tar'),zlib=require('zlib');function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var bi__namespace=/*#__PURE__*/_interopNamespace(bi);var ee__namespace=/*#__PURE__*/_interopNamespace(ee);var ae__namespace=/*#__PURE__*/_interopNamespace(ae);var Wr__namespace=/*#__PURE__*/_interopNamespace(Wr);var es__namespace=/*#__PURE__*/_interopNamespace(es);var ts__namespace=/*#__PURE__*/_interopNamespace(ts);var V=(e,n)=>()=>(e&&(n=e(e=0)),n);var m=V(()=>{});var U,On=V(()=>{m();U=class extends Error{constructor(t,i=t,o){super(i);this.code=t;this.currentRevision=o;}code;currentRevision;name="UiRuntimeError"};});function gt(e){return As.test(e)||Is.test(e)}function ue(){throw new U("INPUT_INVALID","JSON value is not projection-safe")}function _s(e){let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function At(e,n,t,i,o,r){if(n>i&&ue(),e===null||typeof e=="string"||typeof e=="boolean")return typeof e=="string"&&(gs.test(e)||hs.test(e)&&!Ps(o,r)||ms.test(e))&&ue(),e;if(typeof e=="number")return Number.isFinite(e)||ue(),e;(typeof e!="object"||e===void 0||typeof e=="function"||typeof e=="bigint")&&ue();let s=e;t.has(s)&&ue(),t.add(s);try{if(Array.isArray(e))return e.map(d=>At(d,n+1,t,i,o,r));_s(s)||ue();let a={};for(let[d,c]of Object.entries(e))gt(d)&&ue(),a[d]=At(c,n+1,t,i,[...o,d],r);return a}finally{t.delete(s);}}function fe(e,n=0,t=[]){(!Number.isInteger(n)||n<0||n>Ts)&&ue(),(!Array.isArray(t)||t.some(o=>typeof o!="string"))&&ue();let i=At(e,0,new Set,Es+n,[],t);return (i===null||Array.isArray(i)||typeof i!="object")&&ue(),i}function Xe(e,n){if(!e||!n)return false;let t=e.split("."),i=n.split(".");return t.length>=i.length&&i.every((o,r)=>t[r]===o)}function Ps(e,n){if(e.length===0)return false;let t=e.join(".");return n.some(i=>Xe(t,i))}function Ye(e){try{let n=JSON.stringify(e);return n===void 0&&ue(),n}catch{ue();}}function It(e){return Array.isArray(e)?e.map(It):e!==null&&typeof e=="object"?Object.fromEntries(Object.keys(e).sort().map(n=>[n,It(e[n])])):e}function ne(e){return Ye(It(e))}function mt(e){return Buffer.byteLength(e,"utf8")}var As,Is,gs,ms,hs,Es,Ts,Se=V(()=>{m();On();As=/(?:proof|token|secret|password|cookie|authorization|private[_-]?key|stack|exception|plugin[_-]?text)/i,Is=/(?:url|uri|endpoint|path|file(?:name|path)?|cwd|shell|directory|dir|folder)$/i,gs=/<\/?[A-Za-z][^>]*>/,ms=/^(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)/,hs=/^(?:https?|file|ftp|ws|wss):\/\//i;Es=8,Ts=4;});var Oi=V(()=>{m();Se();});var Rn,ht=V(()=>{m();Rn=["text/plain","application/json"];});var Ri=V(()=>{m();ht();});function qe(e){return Ds.has(e)||bs.test(e)||Ss.test(e)}var wi,Ds,bs,Ss,wn,ln,_e,_t,Et,Tt,Pt,Nt,Fe=V(()=>{m();wi=["__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"],Ds=new Set(wi),bs=/(?:proof|token|secret|password|cookie|authorization|private[_-]?key|stack|exception|plugin[_-]?text)/i,Ss=/(?:url|uri|endpoint|path|file(?:name|path)?|cwd|shell|directory|dir|folder)$/i;wn=/^[A-Za-z0-9_]+$/,ln=/^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)*$/,_e=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,_t=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/,Et=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,Tt=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/,Pt=["blue","violet","emerald","amber","rose","sky","slate","indigo"],Nt=["inline","panel"];});function Dt(e){return typeof e=="string"&&Rn.includes(e)}var Ui=V(()=>{m();ht();Fe();});function Un(e){if(!bt(e))return false;let n=Object.keys(e);return !(n.some(t=>t!=="in"&&t!=="out")||n.length===0||Object.hasOwn(e,"in")&&!Ms(e.in)||Object.hasOwn(e,"out")&&!Ls(e.out))}function Ms(e){return bt(e)?Object.keys(e).every(t=>t==="mediaType"||t==="required")&&Object.hasOwn(e,"mediaType")&&Dt(e.mediaType)&&(!Object.hasOwn(e,"required")||typeof e.required=="boolean"):false}function Ls(e){return bt(e)?Object.keys(e).every(t=>t==="mediaType"||t==="range")&&Object.hasOwn(e,"mediaType")&&Dt(e.mediaType)&&(!Object.hasOwn(e,"range")||typeof e.range=="boolean"):false}function bt(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}var St=V(()=>{m();Ri();Ui();new TextDecoder("utf-8",{fatal:true,ignoreBOM:true});});function pe(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(o=>o.resultProjection!==void 0)?{id:e.id,version:e.version,...e.renderer===void 0?{}:{renderer:e.renderer},...e.surfaces===void 0?{}:{surfaces:e.surfaces},...e.stateProjection===void 0?{}:{stateProjection:e.stateProjection},...e.dataPaths===void 0?{}:{dataPaths:e.dataPaths},...e.summaryProjection===void 0?{}:{summaryProjection:e.summaryProjection},...e.legacy===void 0?{}:{legacy:e.legacy},...e.usage===void 0?{}:{usage:e.usage},...e.detailPanel===void 0?{}:{detailPanel:e.detailPanel},...e.displayModes===void 0?{}:{displayModes:e.displayModes},...e.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=fe(t);return bi.createHash("sha256").update(ne(i)).digest("hex")}function Lt(e){return `${e.id}\0${e.version}`}function ye(e){if(!/^\d+$/.test(String(e.version))||e.version<1||e.id.length<1||e.id.length>128)throw new U("DEFINITION_UNSUPPORTED","UI definition is invalid");if(e.sourceHash!==void 0&&(typeof e.sourceHash!="string"||!Rs.test(e.sourceHash)))throw new U("DEFINITION_UNSUPPORTED","UI definition source hash is invalid");if(!/^[0-9a-f]{64}$/.test(e.hash)||pe(e)!==e.hash)throw new U("DEFINITION_UNSUPPORTED","UI definition hash is invalid");for(let[n,t]of Object.entries(e.actions)){if(!n||!Array.isArray(t.capabilities)||t.capabilities.some(i=>!Us(i)))throw new U("DEFINITION_UNSUPPORTED","UI action declaration is invalid");if(t.confirmation!==void 0&&t.confirmation!=="none"&&t.confirmation!=="native")throw new U("DEFINITION_UNSUPPORTED","UI action confirmation is invalid");if(t.inputKeys&&(!Array.isArray(t.inputKeys)||t.inputKeys.some(i=>typeof i!="string"||!i)))throw new U("DEFINITION_UNSUPPORTED","UI action input declaration is invalid");if(t.dataInputs!==void 0&&(!Array.isArray(t.dataInputs)||new Set(t.dataInputs).size!==t.dataInputs.length||t.dataInputs.some(i=>typeof i!="string"||!i||t.inputKeys!==void 0&&!t.inputKeys.includes(i))))throw new U("DEFINITION_UNSUPPORTED","UI action data input declaration is invalid");if(t.resultProjection&&Mt(t.resultProjection),t.content!==void 0&&!Un(t.content))throw new U("DEFINITION_UNSUPPORTED","UI action content declaration is invalid");if(t.env!==void 0&&(!Array.isArray(t.env)||t.env.length===0||new Set(t.env).size!==t.env.length||t.env.some(i=>i!=="CREWX_APP_INSTANCE_ID"&&i!=="CREWX_THREAD_ID")))throw new U("DEFINITION_UNSUPPORTED","UI action environment declaration is invalid")}if(e.renderer!==void 0&&(!e.renderer||e.renderer.length>128))throw new U("DEFINITION_UNSUPPORTED","UI definition renderer is invalid");if(e.surfaces&&(!Array.isArray(e.surfaces)||e.surfaces.some(n=>!n||n.length>64)))throw new U("DEFINITION_UNSUPPORTED","UI definition surfaces are invalid");if(e.usage!==void 0&&e.usage!=="card"&&e.usage!=="window")throw new U("DEFINITION_UNSUPPORTED","UI definition usage is invalid");if(e.detailPanel!==void 0&&typeof e.detailPanel!="boolean")throw new U("DEFINITION_UNSUPPORTED","UI definition detailPanel is invalid");if(e.displayModes&&(!Array.isArray(e.displayModes)||e.displayModes.length===0||new Set(e.displayModes).size!==e.displayModes.length||e.displayModes.some(n=>n!=="inline"&&n!=="floating"&&n!=="focused")))throw new U("DEFINITION_UNSUPPORTED","UI definition displayModes are invalid");if(e.usage==="card"&&e.displayModes!==void 0)throw new U("DEFINITION_UNSUPPORTED","Card definitions cannot declare displayModes");if(e.usage==="window"&&e.detailPanel!==void 0)throw new U("DEFINITION_UNSUPPORTED","Window definitions cannot declare detailPanel");if(e.stateProjection&&Mt(e.stateProjection),e.summaryProjection){Mt(e.summaryProjection);let n=new Set(e.stateProjection?.allow??[]);if(e.summaryProjection.allow.some(t=>!n.has(t)))throw new U("DEFINITION_UNSUPPORTED","UI summary projection exceeds state projection")}if(e.legacy!==void 0){if(!e.legacy||typeof e.legacy!="object"||Array.isArray(e.legacy)||Object.keys(e.legacy).some(o=>!["readTool","actionTool","hostTools","agentAccess"].includes(o)))throw new U("DEFINITION_UNSUPPORTED","UI legacy metadata is invalid");let n=new Set;for(let[o,r]of [["readTool",e.legacy.readTool],["actionTool",e.legacy.actionTool]])if(r!==void 0){if(ws(r,o==="readTool"),n.has(r.name))throw new U("DEFINITION_UNSUPPORTED","UI legacy tool names collide");n.add(r.name);}let t=e.legacy.hostTools;if(t!==void 0){if(!t||typeof t!="object"||Array.isArray(t))throw new U("DEFINITION_UNSUPPORTED","UI legacy host tools are invalid");let o={"doc.open":"crewx_app_html_viewer_open","pty.connect":"crewx_app_terminal_connect"};for(let[r,s]of Object.entries(t)){if(!Object.hasOwn(o,r)||o[r]!==s||typeof s!="string"||!/^[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(s)||n.has(s))throw new U("DEFINITION_UNSUPPORTED","UI legacy host tools are invalid");n.add(s);}}let i=e.legacy.agentAccess;if(i!==void 0&&(!i||typeof i!="object"||Array.isArray(i)||Object.entries(i).some(([o,r])=>!o||!Object.hasOwn(e.actions,o)||r!=="allowed"&&r!=="denied")))throw new U("DEFINITION_UNSUPPORTED","UI legacy agent access is invalid");if(e.legacy.actionTool!==void 0&&(!i||Object.keys(i).length===0))throw new U("DEFINITION_UNSUPPORTED","UI legacy action tool requires its complete agent access map")}if(e.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=>Xe(t,i))))throw new U("DEFINITION_UNSUPPORTED","UI definition dataPaths are invalid")}}function ws(e,n){if(!e||typeof e!="object"||Array.isArray(e))throw new U("DEFINITION_UNSUPPORTED","UI legacy tool metadata is invalid");let t=e,i=["name","description","inputSchema","textFallback","visibility"],o=Object.hasOwn(t,"fixedResult");if(Object.keys(t).some(r=>!i.includes(r)&&!(n&&r==="fixedResult"))||i.some(r=>!Object.hasOwn(t,r))||typeof t.name!="string"||!/^[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(t.name)||typeof t.description!="string"||t.description.trim().length===0||t.description.length>8192||typeof t.textFallback!="string"||t.textFallback.trim().length===0||t.textFallback.length>16384||!t.inputSchema||typeof t.inputSchema!="object"||Array.isArray(t.inputSchema)||!Array.isArray(t.visibility)||t.visibility.length===0||t.visibility.some(r=>r!=="model"&&r!=="app")||new Set(t.visibility).size!==t.visibility.length)throw new U("DEFINITION_UNSUPPORTED","UI legacy tool metadata is invalid");try{let r=fe(t.inputSchema);if(r.type!==void 0&&r.type!=="object")throw new Error("schema type");if(o){if(!n)throw new Error("fixed result location");let s=t.fixedResult;if(!s||typeof s!="object"||Array.isArray(s))throw new Error("fixed result");let a=s;if(Object.keys(a).sort().join(",")!=="argsPolicy,structuredContent"||a.argsPolicy!=="empty-only"&&a.argsPolicy!=="ignore"||!a.structuredContent||typeof a.structuredContent!="object"||Array.isArray(a.structuredContent))throw new Error("fixed result");let d=fe(a.structuredContent);if(mt(Ye(d))>4*1024)throw new Error("fixed result size")}}catch{throw new U("DEFINITION_UNSUPPORTED","UI legacy tool metadata is not projection-safe")}}function Mt(e){if(!Array.isArray(e.allow)||e.allow.some(n=>!/^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)*$/.test(n)))throw new U("DEFINITION_UNSUPPORTED","UI projection policy is invalid")}function Us(e){return e.length>0&&e.length<=128&&e!=="*"&&e!=="all"&&!/[/*]/.test(e)}var Rs,Ve=V(()=>{m();Se();On();St();Rs=/^[0-9a-f]{64}$/;});var B,Ze,Ot=V(()=>{m();B="dist/tools.json",Ze="dist/main.mjs";});var Ce,Rt=V(()=>{m();Ce="window";});function Ci(e){if(!Array.isArray(e)||e.length===0)return false;let n=new Set;for(let t of e){if(!Cs.some(i=>i===t)||n.has(t))return false;n.add(t);}return true}var Cs,ki=V(()=>{m();Cs=["CREWX_APP_INSTANCE_ID","CREWX_THREAD_ID"];});function H(e){throw new wt(e)}function Ws(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 Js(e,n){let t=Object.getOwnPropertyDescriptor(e,n);return (!t||!("value"in t))&&H("CSP_ORIGIN_INVALID"),t.value}function Cn(e,n){if(!Object.prototype.hasOwnProperty.call(e,n))return [];let t=Js(e,n);Array.isArray(t)||H("CSP_ORIGIN_INVALID"),Reflect.ownKeys(t).some(r=>typeof r!="string"||r!=="length"&&!/^(?:0|[1-9][0-9]*)$/.test(r))&&H("CSP_ORIGIN_INVALID");let o=[];for(let r=0;r<t.length;r+=1)(!Object.prototype.hasOwnProperty.call(t,r)||typeof t[r]!="string")&&H("CSP_ORIGIN_INVALID"),o.push(t[r]);return Object.keys(t).length!==t.length&&H("CSP_ORIGIN_INVALID"),o}function Ks(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 ji(e,n){/\s|\\/u.test(e)&&H("CSP_ORIGIN_INVALID");let t=Bs.exec(e);t||H("CSP_ORIGIN_INVALID");let i=t[1].toLowerCase(),o=t[2];(o.includes("@")||o.includes("%")||o.includes("*"))&&H("CSP_ORIGIN_INVALID"),(o.startsWith("[")?Hs:zs).test(o)||H("CSP_ORIGIN_INVALID"),i==="wss"&&n!=="connectDomains"&&H("CSP_ORIGIN_INVALID");let s;try{s=new URL(e);}catch{H("CSP_ORIGIN_INVALID");}(s.protocol!==`${i}:`||s.username!==""||s.password!==""||s.search!==""||s.hash!=="")&&H("CSP_ORIGIN_INVALID");let a=s.hostname.toLowerCase();if((!a||a.includes("%"))&&H("CSP_ORIGIN_INVALID"),!a.startsWith("[")){let c=a.endsWith(".")?a.slice(0,-1):a;(c.length===0||c.length>253)&&H("CSP_ORIGIN_INVALID"),c.split(".").some(p=>p.length>63||!$s.test(p))&&H("CSP_ORIGIN_INVALID");}let d=s.origin;return (d==="null"||!d.startsWith(`${i}://`))&&H("CSP_ORIGIN_INVALID"),{origin:d,hostname:a}}function Xs(e){let n=e.split(".").map(Number);return ((n[0]*256+n[1])*256+n[2])*256+n[3]}function Fi(e,n,t){let i=4294967295<<32-t>>>0;return (e&i)===(n&i)}function Hi(e){let n=Xs(e);return Fi(n,3221225472,24)?n!==3221225481&&n!==3221225482:Gs.some(([t,i])=>Fi(n,t,i))}function Ys(e){let n=e.indexOf("::"),t=(n<0?e:e.slice(0,n)).split(":").filter(Boolean),i=n<0?[]:e.slice(n+2).split(":").filter(Boolean);return (n<0?t:[...t,...Array(8-t.length-i.length).fill("0"),...i]).reduce((r,s)=>r<<16n|BigInt(Number.parseInt(s,16)),0n)}function qs(e){let n=Ys(e),t=Number(n>>112n),i=Number(n>>96n&0xffffn);if(n>>32n===0xffffn){let o=Number(n&0xffffffffn);return Hi([o>>>24&255,o>>>16&255,o>>>8&255,o&255].join("."))}return t<8192||t>16383||t===8193&&i<=511||t===8193&&i===3512||t===8194||t===16383&&i<=4095}function Zs(e,n){let t=e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e,i=net.isIP(t);if(i===4)return Hi(t);if(i===6)return qs(t);let o=e.toLowerCase().replace(/\.$/,"");return !o||!o.includes(".")||n.has(o)?true:Vs.some(r=>o===r||o.endsWith(`.${r}`))}function Vi(e){return Object.freeze([...new Set(e.map(n=>n.origin))].sort())}function Bi(e){return JSON.stringify({baseUriDomains:[],connectDomains:e.connectDomains,declared:e.declared,frameDomains:e.frameDomains,resourceDomains:[]})}function zi(e,n={}){if(e===void 0){let f=Bi({declared:false,connectDomains:[],frameDomains:[]});return Object.freeze({declared:false,connectDomains:Object.freeze([]),frameDomains:Object.freeze([]),resourceDomains:Object.freeze([]),baseUriDomains:Object.freeze([]),cspHash:bi.createHash("sha256").update(f,"utf8").digest("hex")})}Ws(e)||H("CSP_ORIGIN_INVALID");let t=Reflect.ownKeys(e);t.some(f=>typeof f!="string")&&H("CSP_ORIGIN_INVALID"),t.some(f=>!Fs.has(f))&&H("CSP_AXIS_UNKNOWN");let i=Cn(e,"connectDomains"),o=Cn(e,"frameDomains"),r=Cn(e,"resourceDomains"),s=Cn(e,"baseUriDomains");(r.length>0||s.length>0)&&H("CSP_AXIS_UNSUPPORTED"),(Ks(e)>xs||i.length>vi||o.length>vi||i.length+o.length>vs||[...i,...o].some(f=>new TextEncoder().encode(f).byteLength>js))&&H("CSP_LIMIT_EXCEEDED");let d=i.map(f=>ji(f,"connectDomains")),c=o.map(f=>ji(f,"frameDomains")),l=new Set((n.runtimeHostnames??[]).map(f=>f.toLowerCase().replace(/\.$/,"")));[...d,...c].some(f=>Zs(f.hostname,l))&&H("CSP_ORIGIN_FORBIDDEN");let p={declared:true,connectDomains:Vi(d),frameDomains:Vi(c)},u=Bi(p);return Object.freeze({...p,resourceDomains:Object.freeze([]),baseUriDomains:Object.freeze([]),cspHash:bi.createHash("sha256").update(u,"utf8").digest("hex")})}var xs,vi,vs,js,Fs,Vs,Bs,Hs,zs,$s,Gs,wt,$i=V(()=>{m();xs=4096,vi=16,vs=32,js=512,Fs=new Set(["connectDomains","frameDomains","resourceDomains","baseUriDomains"]),Vs=["localhost","local","internal","home.arpa","test","example","invalid","onion","lan","corp","home","intranet","private","localdomain"],Bs=/^(https|wss):\/\/([^/?#]+)$/i,Hs=/^\[[^\]]+\](?::[0-9]+)?$/,zs=/^[^:\[\]]+(?::[0-9]+)?$/,$s=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/,Gs=[[0,8],[1681915904,10],[167772160,8],[2130706432,8],[2851995648,16],[2886729728,12],[3221225984,24],[3227017984,24],[3232235520,16],[3323068416,15],[3325256704,24],[3405803776,24],[3758096384,4],[4026531840,4]],wt=class extends Error{constructor(t){super(t);this.code=t;}code;name="UiPluginCspNormalizationError"};});function fn(e,n){return n===void 0||n===""?e:e===""?n:n.startsWith("[")?`${e}${n}`:`${e}.${n}`}function A(e,n=e,t,i){throw new re(e,n,t,i)}function z(e,n){try{return n()}catch(t){throw t instanceof re?t.withPathPrefix(e):t}}function $(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 C(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function ba(e,n){let t={};for(let[i,o]of Object.entries(e))i!==n&&(t[i]=o);return t}function K(e,n,t=[]){let i=new Set([...n,...t]),o=Object.keys(e).find(s=>!i.has(s));o!==void 0&&A("MANIFEST_INVALID","MANIFEST_INVALID",o,"unknown-key");let r=n.find(s=>!C(e,s));r!==void 0&&A("MANIFEST_INVALID","MANIFEST_INVALID",r,"missing-key");}function jn(e,n=false,t=false,i=false){return ta.test(e)||!i&&oa.test(e)||ia.test(e)||t&&Gi.test(e)||ra.test(e)&&!(n&&/^\s*data:/i.test(e)&&!Gi.test(e))}function vn(e,n=new Set,t=0,i=false,o=false,r=""){if(typeof e=="string"){jn(e,i,o)&&A("UNSAFE_VALUE","UNSAFE_VALUE",r,"unsafe-value");return}if(!(e===null||typeof e!="object")){(t>8||n.has(e))&&A("MANIFEST_INVALID","MANIFEST_INVALID",r),n.add(e);try{if(Array.isArray(e)){e.forEach((s,a)=>vn(s,n,t+1,!1,!1,fn(r,`[${a}]`)));return}$(e)||A("MANIFEST_INVALID","MANIFEST_INVALID",r);for(let[s,a]of Object.entries(e))vn(a,n,t+1,i&&t===0&&(s==="name"||s==="description"),o,fn(r,s));}finally{n.delete(e);}}}function Ee(e,n){let t=e[n];return typeof t!="string"&&A("MANIFEST_INVALID"),t}function Ie(e,n,t){let i=e[n];return (!Number.isSafeInteger(i)||i<t)&&A("MANIFEST_INVALID"),i}function Ut(e){return na.test(e)||A("MANIFEST_INVALID"),e}function Qe(e){return ea.test(e)||A("TOKEN_INVALID"),e}function Sa(e){return eo.test(e)||A("MANIFEST_INVALID"),e}function Ma(e){$(e)||A("MANIFEST_INVALID");let n={};for(let[t,i]of Object.entries(e)){let o=Sa(t);$(i)||A("MANIFEST_INVALID");let r=i.type;if(r==="text"){K(i,["type","maxLength"]),n[o]={type:r,maxLength:Ie(i,"maxLength",1)};continue}if(r==="text-list"){K(i,["type","max","itemMaxLength"]),n[o]={type:r,max:Ie(i,"max",0),itemMaxLength:Ie(i,"itemMaxLength",1)};continue}if(r==="step-list"){K(i,["type","min","max","labelMaxLength","detailMaxLength"]);let s=Ie(i,"min",0),a=Ie(i,"max",1);s>a&&A("MANIFEST_INVALID"),n[o]={type:r,min:s,max:a,labelMaxLength:Ie(i,"labelMaxLength",1),detailMaxLength:Ie(i,"detailMaxLength",1)};continue}typeof r=="string"&&A("SCHEMA_TYPE_UNSUPPORTED"),A("MANIFEST_INVALID");}return n}function La(e,n,t){let i=e[n];(!i||i.type!==t)&&A("MANIFEST_INVALID");}function kn(e,n,t){let i=Ee(e,"field");return eo.test(i)||A("MANIFEST_INVALID"),La(n,i,t),i}function Oa(e,n){$(e)||A("MANIFEST_INVALID");let t=e.primitive;switch(typeof t!="string"&&A("MANIFEST_INVALID"),Da.includes(t)||A("PRIMITIVE_UNKNOWN"),t){case "card-shell":return K(e,["primitive"]),{primitive:t};case "meta-banner":return K(e,["primitive","badgeToken","noticeToken"]),{primitive:t,badgeToken:Qe(Ee(e,"badgeToken")),noticeToken:Qe(Ee(e,"noticeToken"))};case "heading":return K(e,["primitive","field"]),{primitive:t,field:kn(e,n,"text")};case "labeled-text":return K(e,["primitive","titleToken","field","variant"]),e.variant!=="callout"&&A("MANIFEST_INVALID"),{primitive:t,titleToken:Qe(Ee(e,"titleToken")),field:kn(e,n,"text"),variant:"callout"};case "step-flow":return K(e,["primitive","titleToken","field"]),{primitive:t,titleToken:Qe(Ee(e,"titleToken")),field:kn(e,n,"step-list")};case "text-list":{K(e,["primitive","titleToken","field"],["emptyToken","hideWhenEmpty"]);let i={primitive:t,titleToken:Qe(Ee(e,"titleToken")),field:kn(e,n,"text-list")};return C(e,"emptyToken")&&(i.emptyToken=Qe(Ee(e,"emptyToken"))),C(e,"hideWhenEmpty")&&(typeof e.hideWhenEmpty!="boolean"&&A("MANIFEST_INVALID"),i.hideWhenEmpty=e.hideWhenEmpty),i}}return A("MANIFEST_INVALID")}function Ra(e,n){return Array.isArray(e)||A("MANIFEST_INVALID"),e.map(t=>Oa(t,n))}function X(e="v2 manifest exceeds a contract limit",n,t){return A("LIMIT_EXCEEDED",e,n,t)}function Ae(e="initial state is not projection-safe"){return A("INITIAL_STATE_INVALID",e)}function Wi(e,n){return (typeof e!="string"||e.length===0||e.length>4096||e.trim().length===0||Ta.test(e)||Pa.test(e))&&A("MANIFEST_INVALID",`${n} is invalid`),(jn(e,true,true)||sa.test(e)||aa.test(e)||ca.test(e))&&A("UNSAFE_VALUE",`${n} contains an unsafe value`),e}function Ct(e,n){return (typeof e!="string"||!_e.test(e))&&A("MANIFEST_INVALID",`${n} is invalid`),e}function wa(e){return (typeof e!="string"||!_t.test(e)||e==="*"||e==="all")&&A("MANIFEST_INVALID","action capability is invalid"),e}function no(e){return (typeof e!="string"||!Ea.test(e))&&A("MANIFEST_INVALID","resource hash is invalid"),e}function kt(e,n=new Set,t=0,i=""){if(typeof e=="string"){e.length>4096&&X("v2 manifest string is too long",i,"string-too-long");return}if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){Number.isFinite(e)||A("MANIFEST_INVALID","v2 manifest contains a non-finite number",i,"non-finite-number");return}(e===void 0||typeof e=="function"||typeof e=="bigint")&&A("MANIFEST_INVALID","v2 manifest contains a non-JSON value",i,"non-json-value"),typeof e!="object"&&A("MANIFEST_INVALID","MANIFEST_INVALID",i),t>8&&X("v2 manifest nesting is too deep",i,"too-deep"),n.has(e)&&A("MANIFEST_INVALID","v2 manifest contains a cycle",i,"cycle"),n.add(e);try{if(Array.isArray(e)){e.length>128&&X("v2 manifest array is too long",i,"array-too-long"),e.forEach((o,r)=>kt(o,n,t+1,fn(i,`[${r}]`)));return}$(e)||A("MANIFEST_INVALID","v2 manifest contains a non-plain object",i,"non-plain-object");for(let[o,r]of Object.entries(e))kt(r,n,t+1,fn(i,o));}finally{n.delete(e);}}}function to(e){return (typeof e!="string"||e.length>4096||!ln.test(e))&&(typeof e=="string"&&e.length>4096&&X("projection path is too long"),A("MANIFEST_INVALID","projection paths must be canonical exact paths")),e.split(".").some(t=>qe(t))&&A("MANIFEST_INVALID","projection paths cannot address reserved state keys"),e}function xt(e){$(e)||A("MANIFEST_INVALID","projection policy must be an object"),K(e,["allow"]),Array.isArray(e.allow)||A("MANIFEST_INVALID","projection allow must be an array"),e.allow.length>128&&X("projection allowlist is too long");let n=[],t=new Set;for(let i of e.allow){let o=to(i);t.has(o)&&A("MANIFEST_INVALID","projection allowlist contains a duplicate path"),t.add(o),n.push(o);}return {allow:n}}function Ua(e,n){if(e===void 0)return;Array.isArray(e)||A("MANIFEST_INVALID","dataPaths must be an array"),e.length>Na&&X("dataPaths exceed the v2 limit");let t=[],i=new Set;for(let o of e){let r=to(o);i.has(r)&&A("MANIFEST_INVALID","dataPaths contain a duplicate path"),n.some(s=>Xe(r,s))||A("MANIFEST_INVALID","dataPaths must be projection-allowed"),i.add(r),t.push(r);}return t}function en(e,n,t=Number.MAX_SAFE_INTEGER){return (!Number.isSafeInteger(e)||e<0||e>t)&&A("MANIFEST_INVALID",`${n} is invalid`),e}function Ji(e,n){return (typeof e!="number"||!Number.isFinite(e))&&A("MANIFEST_INVALID",`${n} is invalid`),e}function vt(e,n=0,t=new Set){if(typeof e=="string")return (e.length>4096||jn(e))&&A("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)||A("MANIFEST_INVALID","schema enum contains a non-finite number"),e;(n>8||typeof e!="object"||e===void 0)&&X("schema enum is too deep"),t.has(e)&&A("MANIFEST_INVALID","schema enum contains a cycle"),t.add(e);try{if(Array.isArray(e))return e.length>128&&X("schema enum array is too long"),e.map(o=>vt(o,n+1,t));$(e)||A("MANIFEST_INVALID","schema enum contains a non-plain object");let i={};for(let[o,r]of Object.entries(e))qe(o)&&A("MANIFEST_INVALID","schema enum contains a reserved key"),i[o]=vt(r,n+1,t);return i}finally{t.delete(e);}}function Ca(e,n){if(e===void 0)return;Array.isArray(e)||A("MANIFEST_INVALID","schema required must be an array"),e.length>64&&X("schema required list is too long");let t=[],i=new Set;for(let o of e)(typeof o!="string"||!ln.test(o))&&A("MANIFEST_INVALID","schema required contains an invalid key"),o.length>4096&&X("schema required key is too long"),i.has(o)&&A("MANIFEST_INVALID","schema required contains a duplicate key"),n&&!Object.prototype.hasOwnProperty.call(n,o)&&A("MANIFEST_INVALID","schema required references an undeclared property"),i.add(o),t.push(o);return t}function ka(e,n){let t=n?ln:wn;return e.length>4096&&X("schema property name is too long"),(!t.test(e)||e.split(".").some(i=>qe(i)))&&A("MANIFEST_INVALID","schema property name is invalid"),e}function jt(e,n=0,t=false){$(e)||A("MANIFEST_INVALID","action inputSchema must be an object"),n>8&&X("action inputSchema is too deep");let i=e.type;i!=="object"&&i!=="string"&&i!=="number"&&i!=="integer"&&i!=="boolean"&&i!=="array"&&i!=="null"&&(typeof i=="string"&&A("SCHEMA_TYPE_UNSUPPORTED","action inputSchema type is unsupported"),A("MANIFEST_INVALID","action inputSchema type is required"));let o=["type","enum"];i==="string"&&o.push("minLength","maxLength"),i==="array"&&o.push("minItems","maxItems","items"),i==="object"&&o.push("minProperties","maxProperties","properties","required","additionalProperties"),(i==="number"||i==="integer")&&o.push("minimum","maximum"),K(e,["type"],o.filter(a=>a!=="type"));let r={type:i};if(C(e,"enum")&&(Array.isArray(e.enum)||A("MANIFEST_INVALID","schema enum must be an array"),e.enum.length>128&&X("schema enum is too long"),r.enum=e.enum.map(a=>vt(a))),i==="string"&&(C(e,"minLength")&&(r.minLength=en(e.minLength,"schema minLength",4096)),C(e,"maxLength")&&(r.maxLength=en(e.maxLength,"schema maxLength",4096)),r.minLength!==void 0&&r.maxLength!==void 0&&r.minLength>r.maxLength&&A("MANIFEST_INVALID","schema string length bounds are inverted")),(i==="number"||i==="integer")&&(C(e,"minimum")&&(r.minimum=Ji(e.minimum,"schema minimum")),C(e,"maximum")&&(r.maximum=Ji(e.maximum,"schema maximum")),r.minimum!==void 0&&r.maximum!==void 0&&r.minimum>r.maximum&&A("MANIFEST_INVALID","schema numeric bounds are inverted")),i==="array"&&(C(e,"minItems")&&(r.minItems=en(e.minItems,"schema minItems",128)),C(e,"maxItems")&&(r.maxItems=en(e.maxItems,"schema maxItems",128)),r.minItems!==void 0&&r.maxItems!==void 0&&r.minItems>r.maxItems&&A("MANIFEST_INVALID","schema array length bounds are inverted"),C(e,"items")&&(r.items=jt(e.items,n+1,false))),i==="object"){let a;if(C(e,"properties")){$(e.properties)||A("MANIFEST_INVALID","schema properties must be an object");let c=Object.entries(e.properties);c.length>64&&X("schema properties are too many"),a={};for(let[l,p]of c){let u=ka(l,t);a[u]=jt(p,n+1,false);}r.properties=a;}C(e,"minProperties")&&(r.minProperties=en(e.minProperties,"schema minProperties",64)),C(e,"maxProperties")&&(r.maxProperties=en(e.maxProperties,"schema maxProperties",64)),r.minProperties!==void 0&&r.maxProperties!==void 0&&r.minProperties>r.maxProperties&&A("MANIFEST_INVALID","schema object property bounds are inverted");let d=Ca(e.required,a);d!==void 0&&(r.required=d),C(e,"additionalProperties")&&(e.additionalProperties!==false&&A("MANIFEST_INVALID","schema additionalProperties must be false"),r.additionalProperties=false);}let s=JSON.stringify(r);return (s===void 0||Buffer.byteLength(s,"utf8")>65536)&&X("action inputSchema subtree is too large"),r}function xa(e){let n=jt(e,0,true);return (n.type!=="object"||!n.properties)&&A("MANIFEST_INVALID","action inputSchema must declare object properties"),n}function va(e){if($(e)||A("MANIFEST_INVALID","action backend must be an object"),e.type==="core"){K(e,Aa);let n=e.handler;return (typeof n!="string"||!Et.test(n))&&A("MANIFEST_INVALID","core backend handler is invalid"),{type:"core",handler:n}}if(e.type==="skill"&&C(e,"entry"))return K(e,ma),e.entry!==Ze&&A("MANIFEST_INVALID",`skill backend entry must be ${Ze}`),{type:"skill",entry:Ze};if(e.type==="skill"){K(e,Ia,ga),(!Array.isArray(e.command)||e.command.length===0||e.command.length>16)&&A("MANIFEST_INVALID","skill backend command is invalid");let n=[];for(let i of e.command)(typeof i!="string"||i.length===0||i.length>256||!Tt.test(i))&&A("MANIFEST_INVALID","skill backend command token is invalid"),n.push(i);let t=C(e,"env")?Fa(e.env):void 0;return {type:"skill",command:n,...t===void 0?{}:{env:t}}}A("MANIFEST_INVALID","action backend type is unsupported");}function ja(e){$(e)||A("MANIFEST_INVALID","action must be an object"),K(e,ua,fa),C(e,"_meta")&&z("_meta",()=>io(e._meta));let n=z("actionId",()=>Ct(e.actionId,"actionId"));gt(n)&&A("MANIFEST_INVALID",`actionId "${n}" is not projection-safe`,"actionId");let t=z("capability",()=>wa(e.capability)),i=e.mutation;typeof i!="boolean"&&A("MANIFEST_INVALID","action mutation must be boolean","mutation");let o=z("inputSchema",()=>xa(e.inputSchema)),r;if(C(e,"dataInputs")){Array.isArray(e.dataInputs)||A("MANIFEST_INVALID","action dataInputs must be an array","dataInputs");let l=o.properties,p=new Set,u=[];for(let f of e.dataInputs)(typeof f!="string"||!C(l,f)||p.has(f))&&A("MANIFEST_INVALID","action dataInputs must be unique declared properties","dataInputs"),p.add(f),u.push(f);r=u;}let s=z("resultProjection",()=>xt(e.resultProjection)),a=z("backend",()=>va(e.backend)),d;C(e,"content")&&((a.type!=="skill"||!Un(e.content))&&A("MANIFEST_INVALID","action content declaration is invalid","content"),d=Va(e.content));let c;if(C(e,"confirmation")){let l=e.confirmation;l!=="none"&&l!=="native"&&A("MANIFEST_INVALID","action confirmation is invalid","confirmation"),c=l;}return {actionId:n,capability:t,mutation:i,inputSchema:o,resultProjection:s,backend:a,...d===void 0?{}:{content:d},...r===void 0?{}:{dataInputs:r},...c===void 0?{}:{confirmation:c}}}function Fa(e){return Ci(e)||A("MANIFEST_INVALID","skill backend env is invalid"),Object.freeze([...e])}function Va(e){return Object.freeze({...e.in===void 0?{}:{in:Object.freeze({...e.in})},...e.out===void 0?{}:{out:Object.freeze({...e.out})}})}function Ba(e){return $(e)||A("INITIAL_STATE_INVALID","initialState must be an object"),K(e,ha,_a),e.path!=="ui/state.json"&&A("MANIFEST_INVALID","initialState path is not fixed"),C(e,"hash")?{path:"ui/state.json",hash:no(e.hash)}:{path:"ui/state.json"}}function Ha(e){let n=["wasm","terminal","htmlDocuments"];return (!$(e)||Object.keys(e).length===0||Object.keys(e).some(t=>!n.includes(t)||e[t]!==true))&&A("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 za(e,n){let t;try{t=zi(e);}catch(i){let o=i!==null&&typeof i=="object"&&"code"in i&&typeof i.code=="string"?i.code:"CSP_ORIGIN_INVALID";return A("MANIFEST_INVALID",o,void 0,o.toLowerCase().replace(/_/g,"-"))}if(t.frameDomains.length>0&&A("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&&A("MANIFEST_INVALID","runtime.terminal cannot be combined with csp.connectDomains","connectDomains","terminal-with-connect-domains"),Object.freeze({connectDomains:t.connectDomains})}function $a(e,n){vn($(e)&&C(e,"csp")?ba(e,"csp"):e,new Set,0,true,true),kt(e),$(e)||A("MANIFEST_INVALID"),K(e,pa,la),C(e,"_meta")&&z("_meta",()=>io(e._meta)),e.manifestVersion!==2&&A("MANIFEST_INVALID");let t;C(e,"runtime")&&(t=z("runtime",()=>Ha(e.runtime)));let i;C(e,"csp")&&(i=z("csp",()=>za(e.csp,t)));let o=z("pluginId",()=>Ct(e.pluginId,"pluginId")),r=z("definitionId",()=>Ct(e.definitionId,"definitionId")),s=z("version",()=>Ie(e,"version",1)),a=z("name",()=>Wi(e.name,"name")),d=z("description",()=>Wi(e.description,"description")),c;C(e,"icon")&&((typeof e.icon!="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(e.icon))&&A("MANIFEST_INVALID","icon is invalid","icon"),c=e.icon);let l;C(e,"tone")&&((typeof e.tone!="string"||!Pt.includes(e.tone))&&A("MANIFEST_INVALID","tone is invalid","tone"),l=e.tone),e.entry!=="ui/index.html"&&A("MANIFEST_INVALID","entry path is not fixed","entry","fixed-value");let p;C(e,"entryHash")&&(p=z("entryHash",()=>no(e.entryHash)));let u;C(e,"initialState")&&(u=z("initialState",()=>Ba(e.initialState)));let f;C(e,"usage")&&(e.usage!=="card"&&e.usage!=="window"&&A("MANIFEST_INVALID","usage is invalid","usage"),f=e.usage);let g;C(e,"detailPanel")&&(typeof e.detailPanel!="boolean"&&A("MANIFEST_INVALID","detailPanel is invalid","detailPanel"),g=e.detailPanel);let E;if(C(e,"displayModes")){((f??Ce)!==Ce||!Array.isArray(e.displayModes)||e.displayModes.length===0)&&A("MANIFEST_INVALID","displayModes are only valid for window Apps","displayModes");let y=new Set(["inline","floating","focused"]);(new Set(e.displayModes).size!==e.displayModes.length||e.displayModes.some(I=>typeof I!="string"||!y.has(I)))&&A("MANIFEST_INVALID","displayModes are invalid","displayModes"),E=e.displayModes;}(f??Ce)===Ce&&g!==void 0&&A("MANIFEST_INVALID","detailPanel is card-only","detailPanel");let O=n.mode??"local";O!=="local"&&O!=="installed"&&O!=="published"&&A("MANIFEST_INVALID","manifest mode is invalid"),O!=="local"&&p===void 0&&A("MANIFEST_INVALID","installed manifests require entryHash","entryHash","required-when-installed"),O!=="local"&&u!==void 0&&u.hash===void 0&&A("MANIFEST_INVALID","installed manifests require initialState.hash","initialState.hash","required-when-installed"),(!Array.isArray(e.surfaces)||e.surfaces.length===0)&&A("MANIFEST_INVALID","surfaces are invalid","surfaces"),e.surfaces.length>2&&X("surfaces exceed the v2 limit","surfaces","too-many-items");let F=[],x=new Set;for(let y of e.surfaces)(typeof y!="string"||!Nt.includes(y))&&A("MANIFEST_INVALID","surface is unsupported","surfaces"),x.has(y)&&A("MANIFEST_INVALID","surfaces contain a duplicate","surfaces","duplicate-item"),x.add(y),F.push(y);$(e.size)||A("MANIFEST_INVALID","size must be an object","size"),z("size",()=>K(e.size,["height"]));let N=z("size",()=>Ie(e.size,"height",1));N>720&&X("size.height exceeds the v2 limit","size.height","too-large");let w=z("stateProjection",()=>xt(e.stateProjection)),v=e.summaryProjection===void 0?void 0:z("summaryProjection",()=>xt(e.summaryProjection));v!==void 0&&v.allow.some(y=>!w.allow.includes(y))&&A("MANIFEST_INVALID","summaryProjection must be a subset of stateProjection.allow","summaryProjection");let T=z("dataPaths",()=>Ua(e.dataPaths,w.allow));Array.isArray(e.actions)||A("MANIFEST_INVALID","actions must be an array","actions"),e.actions.length>32&&X("actions exceed the v2 limit","actions","too-many-items");let D=[],L=new Set;for(let[y,I]of e.actions.entries()){let h=`actions[${y}]`,_=z(h,()=>ja(I));if(L.has(_.actionId)&&A("MANIFEST_INVALID","actions contain a duplicate actionId",`${h}.actionId`,"duplicate-item"),_.backend.type==="core"&&_.backend.handler==="state.set"){_.mutation||A("MANIFEST_INVALID","state.set actions must be mutations",`${h}.mutation`);for(let M of Object.keys(_.inputSchema.properties))w.allow.includes(M)||A("MANIFEST_INVALID","state.set input paths must be projection-allowed",`${h}.inputSchema.properties`);}L.add(_.actionId),D.push(_);}return {manifestVersion:2,pluginId:o,definitionId:r,version:s,name:a,description:d,...c===void 0?{}:{icon:c},...l===void 0?{}:{tone:l},entry:"ui/index.html",...p===void 0?{}:{entryHash:p},...t===void 0?{}:{runtime:t},...i===void 0?{}:{csp:i},...u===void 0?{}:{initialState:u},...f===void 0?{}:{usage:f},...g===void 0?{}:{detailPanel:g},...E===void 0?{}:{displayModes:E},surfaces:F,size:{height:N},stateProjection:w,...v===void 0?{}:{summaryProjection:v},...T===void 0?{}:{dataPaths:T},actions:D}}function io(e){$(e)||A("MANIFEST_INVALID","_meta must be an object");let n=JSON.stringify(e);(n===void 0||Buffer.byteLength(n,"utf8")>ya)&&X("_meta exceeds the 4 KiB limit",void 0,"meta-too-large");}function Ga(e){let n={},t={};for(let r of e.actions){n[r.actionId]={capabilities:[r.capability],inputKeys:Object.keys(r.inputSchema.properties??{}),...r.dataInputs===void 0?{}:{dataInputs:r.dataInputs},resultProjection:r.resultProjection,...r.confirmation===void 0?{}:{confirmation:r.confirmation},...r.content===void 0?{}:{content:r.content},...r.backend.type!=="skill"||r.backend.env===void 0?{}:{env:r.backend.env}};let s=r.backend.type==="skill"||r.backend.type==="core"&&r.backend.handler==="state.set";t[r.actionId]={actionId:r.actionId,mutation:r.mutation,backend:r.backend,launchPolicy:s?"allowed":"denied",...s?{}:{denialCode:"EXEC_DENIED"}};}let i={id:e.definitionId,version:e.version,renderer:"sandbox-html",...e.usage===void 0?{}:{usage:e.usage},...e.detailPanel===void 0?{}:{detailPanel:e.detailPanel},...e.displayModes===void 0?{}:{displayModes:e.displayModes},surfaces:e.surfaces,stateProjection:e.stateProjection,...e.summaryProjection===void 0?{}:{summaryProjection:e.summaryProjection},...e.dataPaths===void 0?{}:{dataPaths:e.dataPaths},actions:n},o={entry:{path:"ui/index.html",...e.entryHash===void 0?{}:{hash:e.entryHash}},...e.initialState===void 0?{}:{initialState:e.initialState}};return {manifest:e,definition:i,handlers:t,resources:o}}function Ft(e,n,t,i,o,r){if(typeof e=="string"){let s=o.length>0&&r.some(a=>Xe(o.join("."),a));return (e.length>4096||jn(e,false,false,s))&&Ae("state contains an unsafe string"),e}if(e===null||typeof e=="boolean")return e;if(typeof e=="number")return Number.isFinite(e)||Ae("state contains a non-finite number"),e;(e===void 0||typeof e!="object"||typeof e=="function"||typeof e=="bigint")&&Ae("state contains a non-JSON value"),t>8&&Ae("state is too deep"),n.has(e)&&Ae("state contains a cycle"),n.add(e);try{let s;if(Array.isArray(e))e.length>128&&Ae("state array is too long"),s=e.map(d=>Ft(d,n,t+1,65536,o,r));else {$(e)||Ae("state contains a non-plain object");let d={};for(let[c,l]of Object.entries(e))(c.length>4096||!wn.test(c)||qe(c))&&(c.length>4096&&Ae("state key is too long"),Ae("state contains a reserved or invalid key")),d[c]=Ft(l,n,t+1,65536,[...o,c],r);s=d;}let a=JSON.stringify(s);return (a===void 0||Buffer.byteLength(a,"utf8")>i)&&Ae("state subtree is too large"),s}finally{n.delete(e);}}function Bt(e,n=[]){$(e)||Ae("initial state must be a JSON object");let t=Ft(e,new Set,0,65536,[],n);return (t===null||Array.isArray(t)||typeof t!="object")&&Ae(),t}function Wa(e,n={}){vn(e),$(e)||A("MANIFEST_INVALID"),K(e,da),e.manifestVersion!==1&&A("MANIFEST_INVALID");let t=Ut(Ee(e,"pluginId")),i=Ut(Ee(e,"definitionId")),o=Ie(e,"version",1),r=Ie(e,"primitiveSet",1),s=n.supportedPrimitiveSet??Qs;(!Number.isSafeInteger(s)||s<1)&&A("MANIFEST_INVALID"),r>s&&A("PRIMITIVE_SET_UNSUPPORTED"),$(e.activation)||A("MANIFEST_INVALID"),K(e.activation,["kind","language"]),e.activation.kind!=="fenced-code"&&A("MANIFEST_INVALID");let a=Ut(Ee(e.activation,"language")),d=Ma(e.schema),c=Ra(e.layout,d);return {manifestVersion:1,pluginId:t,definitionId:i,version:o,primitiveSet:r,activation:{kind:"fenced-code",language:a},schema:d,layout:c}}function Ja(e,n={}){return $(e)||A("MANIFEST_INVALID"),Object.hasOwn(e,"lineage")&&A("MANIFEST_INVALID","lineage is only allowed in product bundle indexes"),e.manifestVersion===2?$a(e,n):Wa(e,n)}function He(e,n={}){try{return Ja(e,n)}catch(t){if(t instanceof re)throw t;return A("MANIFEST_INVALID")}}function yn(e,n={}){let t=He(e,n);return t.manifestVersion===2?Ga(t):t}var Qs,ea,na,eo,ta,ia,oa,ra,Gi,sa,aa,ca,da,pa,la,ua,fa,ya,Aa,Ia,ga,ma,ha,_a,Ea,Ta,Pa,Na,Da,re,Ht=V(()=>{m();Rt();Se();St();ki();Ot();$i();Fe();Qs=1,ea=/^[a-z][a-zA-Z0-9]*(\.[a-zA-Z0-9]+)+$/,na=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,eo=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,ta=/<\/?[A-Za-z][^>]*>/,ia=/^(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)/,oa=/^(?:https?|file|ftp|ws|wss):\/\//i,ra=/^\s*(?:javascript|data):/i,Gi=/data:[^,\s]*,/i,sa=/(?:https?|file|ftp|ws|wss):\/\//i,aa=/javascript:/i,ca=/(?:^[\s]*|[\s"'(=])(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)(?=[^\s"'<>])[^\s"'<>]*/,da=["manifestVersion","pluginId","definitionId","version","primitiveSet","activation","schema","layout"],pa=["manifestVersion","pluginId","definitionId","version","name","description","entry","surfaces","size","stateProjection","actions"],la=["_meta","icon","tone","entryHash","runtime","csp","initialState","usage","detailPanel","displayModes","summaryProjection","dataPaths","focusedAiDataPaths"],ua=["actionId","capability","mutation","inputSchema","resultProjection","backend"],fa=["confirmation","dataInputs","content","_meta"],ya=4*1024,Aa=["type","handler"],Ia=["type","command"],ga=["env"],ma=["type","entry"],ha=["path"],_a=["hash"],Ea=/^[0-9a-f]{64}$/,Ta=/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/,Pa=/[\r\n]/,Na=16,Da=["card-shell","meta-banner","heading","labeled-text","step-flow","text-list"],re=class e extends Error{constructor(t,i=t,o,r){super(i);this.code=t;this.path=o;this.rule=r;}code;path;rule;name="UiPluginValidationError";withPathPrefix(t){return new e(this.code,this.message,fn(t,this.path),this.rule)}};});function po(e){return typeof e=="string"&&e.length<=Xa&&Ka.test(e)}function k(e,n,t,i,o){throw new Pe(e,{path:n,rule:t,...i===void 0?{}:{message:i},...o===void 0?{}:{file:o}})}function te(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 Y(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function me(e){let n=`_meta["${ke}"]`;return e===void 0||e===""?n:e.startsWith("[")?`${n}${e}`:`${n}.${e}`}function Qa(e){return e.toLowerCase().replace(/_/g,"-")}function ec(e){if(e===void 0||e==="")return "";let n=/^([^.[]+)(.*)$/.exec(e);if(!n)return me(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 me("definitionVersion");case "definitionId":return me("definitionId");default:return me(`${t}${i}`)}}function lo(e,n,t){return {path:t(e.path),rule:e.rule??Qa(e.code),...e.message!==e.code?{message:e.message}:{},file:n}}function uo(e){return JSON.parse(JSON.stringify(e))}function Gt(e,n,t=0,i=new Set){if(typeof e=="string"){e.length>4096&&k("LIMIT_EXCEEDED",n,"string-too-long"),(Ya.test(e)||qa.test(e)||Za.test(e))&&k("UNSAFE_VALUE",n,"unsafe-value");return}if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){Number.isFinite(e)||k("MANIFEST_INVALID",n,"non-finite-number");return}typeof e!="object"&&k("MANIFEST_INVALID",n,"non-json-value"),t>8&&k("LIMIT_EXCEEDED",n,"too-deep"),i.has(e)&&k("MANIFEST_INVALID",n,"cycle"),i.add(e);try{if(Array.isArray(e)){e.length>128&&k("LIMIT_EXCEEDED",n,"array-too-long"),e.forEach((o,r)=>Gt(o,`${n}[${r}]`,t+1,i));return}te(e)||k("MANIFEST_INVALID",n,"non-plain-object");for(let[o,r]of Object.entries(e))Gt(r,n===""?o:`${n}.${o}`,t+1,i);}finally{i.delete(e);}}}function ge(e,n){return (typeof e!="string"||e.length===0)&&k("MANIFEST_INVALID",n,"string"),e}function tn(e,n){return te(e)||k("MANIFEST_INVALID",n,"object"),e}function nc(e,n){Array.isArray(e)||k("MANIFEST_INVALID",n,"array"),e.forEach((t,i)=>ge(t,`${n}[${i}]`));}function tc(e,n){typeof e!="boolean"&&k("MANIFEST_INVALID",n,"boolean");}function An(e,n,t,i){for(let o of Object.keys(e))!t.includes(o)&&!i.includes(o)&&k("MANIFEST_INVALID",`${n}.${o}`,"unknown-key");for(let o of t)Y(e,o)||k("MANIFEST_INVALID",`${n}.${o}`,"missing-key");}function ic(e,n){switch(Gt(n,e),e){case "long_description":case "homepage":case "documentation":case "support":case "icon":case "license":ge(n,e);return;case "author":{let t=tn(n,e);An(t,e,["name"],["email","url"]);for(let i of Object.keys(t))ge(t[i],`${e}.${i}`);return}case "repository":{let t=tn(n,e);An(t,e,[],["type","url"]);for(let i of Object.keys(t))ge(t[i],`${e}.${i}`);return}case "icons":{Array.isArray(n)||k("MANIFEST_INVALID",e,"array"),n.forEach((t,i)=>{let o=`${e}[${i}]`,r=tn(t,o);An(r,o,["src","size"],["theme"]),ge(r.src,`${o}.src`),ge(r.size,`${o}.size`),Y(r,"theme")&&ge(r.theme,`${o}.theme`);});return}case "screenshots":case "keywords":case "privacy_policies":nc(n,e);return;case "tools":{Array.isArray(n)||k("MANIFEST_INVALID",e,"array"),n.forEach((t,i)=>{let o=`${e}[${i}]`,r=tn(t,o);An(r,o,["name"],["description"]),ge(r.name,`${o}.name`),Y(r,"description")&&ge(r.description,`${o}.description`);});return}case "prompts":{Array.isArray(n)||k("MANIFEST_INVALID",e,"array"),n.forEach((t,i)=>{let o=`${e}[${i}]`,r=tn(t,o);An(r,o,["name","text"],["description","arguments"]),ge(r.name,`${o}.name`),ge(r.text,`${o}.text`);});return}case "tools_generated":case "prompts_generated":tc(n,e);return;case "localization":case "compatibility":case "user_config":tn(n,e);return;default:k("MANIFEST_INVALID",e,"unknown-key");}}function Fn(e){return typeof e=="string"&&_e.test(e)?e:void 0}function fo(e){return Number.isSafeInteger(e)&&e>=1?e:void 0}function oc(e){let n=Fn(e.name);if(n===void 0)return;let t=e._meta,i=te(t)?t[ke]:void 0,o=te(i)?i:{},r=Y(o,"definitionId")?Fn(o.definitionId):n,s=Y(o,"definitionVersion")?fo(o.definitionVersion):1;return {pluginId:n,...r===void 0?{}:{definitionId:r},...s===void 0?{}:{definitionVersion:s}}}function rc(e){let n=Fn(e.pluginId);if(n===void 0)return;let t=Fn(e.definitionId),i=fo(e.version);return {pluginId:n,...t===void 0?{}:{definitionId:t},...i===void 0?{}:{definitionVersion:i}}}function Kt(e){try{let n=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e));if(!te(n))return !1;let t=n._meta;return te(t)&&Y(t,ke)}catch{return false}}function sc(e,n){if(e===ce)return n.builtinOnly===true;let t=n._meta,i=te(t)?t[ke]:void 0;return te(i)&&i.builtinOnly===true}function ac(e,n){Y(e,"server")&&k("MANIFEST_INVALID","server","server-unsupported","phase 1 runs CrewX-owned Apps only");for(let a of Object.keys(e))Wt.includes(a)||k("MANIFEST_INVALID",a,"unknown-key");for(let a of Jt)Y(e,a)||k("MANIFEST_INVALID",a,"missing-key");e.manifest_version!==zt&&k("MANIFEST_INVALID","manifest_version","unsupported-version",`manifest_version must be "${zt}"`),po(e.version)||k("MANIFEST_INVALID","version","semver","version must be a semver.org version such as 0.1.0");let t=e._meta;te(t)||k("MANIFEST_INVALID","_meta","object"),Y(t,ke)||k("MANIFEST_INVALID",me(),"missing-key");let i=t[ke];te(i)||k("MANIFEST_INVALID",me(),"object");for(let a of Object.keys(i))$t.includes(a)||co.includes(a)||k("MANIFEST_INVALID",me(a),"unknown-key");for(let a of $t)a==="actions"&&n!==void 0||Y(i,a)||k("MANIFEST_INVALID",me(a),"missing-key");if(n!==void 0&&Y(i,"actions")&&k("MANIFEST_INVALID",me("actions"),"two-truths",`actions are declared in both ${G} and ${B}; a server.ts App keeps them in the tools file only`),cc(i.actions),Y(i,"definitionVersion")){let a=i.definitionVersion;(!Number.isSafeInteger(a)||a<1)&&k("MANIFEST_INVALID",me("definitionVersion"),"positive-integer");}let o={};for(let a of ao)Y(e,a)&&(ic(a,e[a]),o[a]=uo(e[a]));let r={};for(let[a,d]of Object.entries(t))a!==ke&&(r[a]=d);let s={manifestVersion:2,pluginId:e.name,definitionId:Y(i,"definitionId")?i.definitionId:e.name,version:Y(i,"definitionVersion")?i.definitionVersion:1,name:e.display_name,description:e.description};for(let[a,d]of Object.entries(i))a==="definitionId"||a==="definitionVersion"||(s[a]=d);return n!==void 0&&(s.actions=n.map(a=>({...a,backend:{type:"skill",entry:Ze}}))),Object.keys(r).length>0&&(s._meta=r),{v2Input:s,...Object.keys(r).length>0?{vendorMeta:r}:{},passthrough:o}}function cc(e){Array.isArray(e)&&e.forEach((n,t)=>{let i=te(n)?n.backend:void 0;te(i)&&Y(i,"entry")&&k("MANIFEST_INVALID",me(`actions[${t}].backend.entry`),"entry-not-authorable",`an action in ${G} cannot name an entry; a server.ts App declares its actions in ${B}`);});}function dc(e,n,t){te(e)||k("MANIFEST_INVALID","","not-object","manifest.json must be a JSON object",G);let i;try{i=ac(e,t);}catch(s){throw s instanceof Pe?new Pe(s.code,{...s.reason,file:G}):s}let o;try{let s=He(i.v2Input,{mode:n.mode??"local"});s.manifestVersion!==2&&k("MANIFEST_INVALID","","v2-required"),o=s;}catch(s){throw s instanceof re?new Pe(s.code,lo(s,G,ec)):s}let r=e.tools;if(Array.isArray(r)){let s=new Set(o.actions.map(a=>a.actionId));r.forEach((a,d)=>{let c=a.name;if(!s.has(c))throw new Pe("MANIFEST_INVALID",{path:`tools[${d}].name`,rule:"tool-not-action",message:"every tools[].name must be an action id",file:G})});}return {file:G,manifest:o,v2Input:i.v2Input,releaseVersion:e.version,...Object.keys(i.passthrough).length>0?{mcpb:i.passthrough}:{}}}function pc(e,n){try{let t=He(e,{mode:n.mode??"local"});if(t.manifestVersion!==2)throw new Pe("MANIFEST_INVALID",{path:"manifestVersion",rule:"v2-required",message:"a workspace App requires manifestVersion 2",file:ce});return {file:ce,manifest:t,v2Input:e}}catch(t){throw t instanceof re?new Pe(t.code,lo(t,ce,i=>i??"")):t}}function on(e){return pe(yn(e).definition)}function ro(e){let{entryHash:n,initialState:t,...i}=e,o={...i};return t!==void 0&&(o.initialState={path:t.path}),uo(o)}function lc(e,n){let t=ro(e),i=ro(n);return [...new Set([...Object.keys(t),...Object.keys(i)])].sort().filter(r=>ne(t[r]??null)!==ne(i[r]??null))}function uc(e,n){return e.entryHash!==void 0&&n.entryHash!==void 0&&e.entryHash!==n.entryHash||e.initialState?.hash!==void 0&&n.initialState?.hash!==void 0&&e.initialState.hash!==n.initialState.hash}function fc(e,n){let t=lc(e,n),i=uc(e,n),o="";try{let r=on(e),s=on(n);i=i||r!==s,o=` (definition hash ${r.slice(0,12)} vs ${s.slice(0,12)})`;}catch{i=true;}t.length===0&&!i||k("MANIFEST_DUAL_MISMATCH","","dual-manifest-mismatch",`${G} and ${ce} normalize to different definitions${o}`+(t.length>0?`; differing fields: ${t.join(", ")}`:""));}function Te(e,n,t="MANIFEST_INVALID",i){return {code:t,reason:{path:e,rule:n,...i===void 0?{}:{message:i},file:B},files:[]}}function so(e){return {...Te("","tools-needs-manifest-json","MANIFEST_INVALID",`${B} is read with ${G} only`),files:e}}function yc(e,n){if(e.byteLength>n)return {failure:Te("","file-too-large","LIMIT_EXCEEDED")};let t;try{t=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e));}catch{return {failure:Te("","invalid-json")}}if(!te(t))return {failure:Te("","not-object","MANIFEST_INVALID",`${B} must be a JSON object`)};for(let o of Object.keys(t))if(o!=="schemaVersion"&&o!=="actions")return {failure:Te(o,"unknown-key")};for(let o of ["schemaVersion","actions"])if(!Y(t,o))return {failure:Te(o,"missing-key")};if(t.schemaVersion!==1)return {failure:Te("schemaVersion","unsupported-version","MANIFEST_INVALID",`schemaVersion must be ${1}`)};let i=t.actions;if(!Array.isArray(i))return {failure:Te("actions","array")};for(let[o,r]of i.entries()){if(!te(r))return {failure:Te(`actions[${o}]`,"object")};if(Y(r,"backend"))return {failure:Te(`actions[${o}].backend`,"tools-backend","MANIFEST_INVALID",`an action in ${B} cannot carry a backend`)}}return {actions:i}}function Ac(e,n){let t=n.maxBytes??262144,i=[],o=new TextDecoder("utf-8",{fatal:true});for(let r of q){let s=e[r];if(s===void 0)continue;if(s.byteLength>t)return {parsed:i,failure:{code:"LIMIT_EXCEEDED",reason:{path:"",rule:"file-too-large",file:r},files:[r]}};let a;try{a=JSON.parse(o.decode(s));}catch{return {parsed:i,failure:{code:"MANIFEST_INVALID",reason:{path:"",rule:"invalid-json",file:r},files:[r]}}}if(!te(a))return {parsed:i,failure:{code:"MANIFEST_INVALID",reason:{path:"",rule:"not-object",message:`${r} must be a JSON object`,file:r},files:[r]}};i.push({file:r,raw:a});}return {parsed:i}}function ze(e,n={}){let{parsed:t,failure:i}=Ac(e,n),o=q.filter(f=>e[f]!==void 0);if(i!==void 0)return {ok:false,rejection:i,parseFailure:true,builtinOnly:false};let r=e[B],s=r===void 0?void 0:yc(r,n.maxBytes??262144);if(t.length===0)return {ok:false,rejection:s===void 0?{code:"MANIFEST_INVALID",reason:{path:"",rule:"no-manifest-file",message:"neither manifest.json nor ui-plugin.json is present"},files:[]}:so(o),parseFailure:true,builtinOnly:false};let a=t[0],d=a.file===G?oc(a.raw):rc(a.raw),c=t.some(f=>sc(f.file,f.raw)),l;if(s!==void 0){let f=t.some(g=>g.file===G)?s.failure:so(o);if(f!==void 0)return {ok:false,rejection:f,parseFailure:false,...d===void 0?{}:{identity:d},builtinOnly:c};l=s.actions;}let p=[];try{for(let f of t)p.push(f.file===G?dc(f.raw,n,l):pc(f.raw,n));p.length===2&&fc(p[0].manifest,p[1].manifest);}catch(f){if(f instanceof Pe)return {ok:false,rejection:{code:f.code,reason:f.reason,files:f.code==="MANIFEST_DUAL_MISMATCH"?[...q]:f.reason.file===void 0||f.reason.file===B?o:[f.reason.file]},parseFailure:false,...d===void 0?{}:{identity:d},builtinOnly:c};throw f}let u=p[0];return {ok:true,...u,identity:d??{pluginId:u.manifest.pluginId},files:o}}var G,ce,q,zt,ke,Wt,Jt,ao,$t,co,Ka,Xa,Ya,qa,Za,Pe,Vn=V(()=>{m();Ve();Se();Ot();Fe();Ht();G="manifest.json",ce="ui-plugin.json",q=[G,ce],zt="0.3",ke="dev.crewx",Wt=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"]),Jt=Object.freeze(["manifest_version","name","display_name","version","description","_meta"]),ao=Object.freeze(Wt.filter(e=>e!=="server"&&!Jt.includes(e))),$t=Object.freeze(["entry","surfaces","size","stateProjection","actions"]),co=Object.freeze(["definitionId","definitionVersion","icon","tone","entryHash","runtime","initialState","usage","detailPanel","displayModes","summaryProjection","dataPaths","focusedAiDataPaths","csp"]),Ka=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/,Xa=256,Ya=/<\/?[A-Za-z][^>]*>/,qa=/^\s*javascript:/i,Za=/data:[^,\s]*,/i;Pe=class extends Error{constructor(t,i){super(`${t}: ${i.path||"<file>"} (${i.rule})`);this.code=t;this.reason=i;}code;reason};});var Xt=V(()=>{m();Oi();Vn();Ht();Fe();});function b(e,n=e){throw new Ne(e,n)}var Ne,Hn=V(()=>{m();Ne=class extends Error{constructor(t,i=t){super(i);this.code=t;}code;name="McpAppContractError"};});var No=V(()=>{m();});var Do=V(()=>{m();Ve();Se();Hn();No();});function So(e,n){return bo.add(e),n!==void 0&&Sc.set(e,n),e}function rn(e){return e!==null&&typeof e=="object"&&bo.has(e)}var bo,Sc,zn=V(()=>{m();bo=new WeakSet,Sc=new WeakMap;});function hn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function qt(e,n,t=[]){let i=new Set([...n,...t]),o=Object.keys(e);return n.every(r=>Object.hasOwn(e,r))&&o.every(r=>i.has(r))}function Oo(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let n of Object.values(e))Oo(n);return Object.freeze(e)}function ie(e){throw new De("LINEAGE_INVALID",e)}function Cc(e){throw new De("LINEAGE_STALE",e)}function Ro(e){if(!hn(e)||!qt(e,Oc,Rc)||!hn(e.actions))return ie("Lineage definition shape is invalid");for(let n of Object.values(e.actions))if(!hn(n)||!qt(n,wc,Uc))return ie("Lineage action definition shape is invalid");return e}function kc(e){if(!hn(e)||!qt(e,Mc,Lc))return ie("Lineage entry shape is invalid");if(!Number.isSafeInteger(e.version)||e.version<1||typeof e.hash!="string"||!Mo.test(e.hash))return ie("Lineage entry identity is invalid");if(e.sourceHash!==void 0&&(typeof e.sourceHash!="string"||!Mo.test(e.sourceHash)))return ie("Lineage source hash is invalid");if(e.compat!==void 0&&e.compat!=="break")return ie("Lineage compatibility marker is invalid");let n=Ro(e.definition);if(n.version!==e.version)return ie("Lineage version does not match its definition");if(e.sourceHash!==void 0&&n.sourceHash!==e.sourceHash)return ie("Lineage source hash does not match its definition");let t;try{t=pe(n),ye({...n,hash:e.hash});}catch{return ie("Lineage definition is invalid")}return t!==e.hash?ie("Lineage definition hash does not match"):Oo({version:e.version,hash:e.hash,definition:n,...e.sourceHash===void 0?{}:{sourceHash:e.sourceHash},...e.compat===void 0?{}:{compat:e.compat}})}function Lo(e){return e.stateProjection?.allow??[]}function xc(e,n){let t=[],i=new Set(Lo(n));Lo(e).some(a=>!i.has(a))&&t.push("S1_STATE_PROJECTION");let o=new Set(n.dataPaths??[]);(e.dataPaths??[]).some(a=>!o.has(a))&&t.push("S2_DATA_PATHS");for(let[a,d]of Object.entries(e.actions)){let c=n.actions[a];if(c&&(d.confirmation??"native")==="native"&&(c.confirmation??"native")!=="native"){t.push("S3_ACTION_CONFIRMATION");break}}Object.keys(e.legacy?.agentAccess??{}).some(a=>!Object.hasOwn(n.actions,a))&&t.push("S4_LEGACY_AGENT_ACTIONS");let s=e.summaryProjection?.allow;if(s!==void 0){let a=new Set(n.summaryProjection?.allow??[]);s.some(d=>!a.has(d))&&t.push("S5_SUMMARY_PROJECTION");}return t}function vc(e,n){return ne(e)===ne(n)}function Zt(e,n){if(!Array.isArray(e)||e.length===0)return ie("Definition lineage is missing");if(!hn(n)||typeof n.hash!="string")return ie("Current definition is invalid");let t,i;try{let{hash:a,...d}=n;i=Ro(d),t={...i,hash:a},ye(t);}catch{return ie("Current definition is invalid")}let o=e.map(kc),r=o[0].definition.id;if(o.some(a=>a.definition.id!==r))return ie("Lineage definition ids do not match");if(o.some((a,d)=>d>0&&a.version<=o[d-1].version))return ie("Lineage generations are not in increasing version order");if(o.some((a,d)=>o.findIndex(c=>c.hash===a.hash)!==d))return ie("Lineage contains a duplicate hash");let s=o[o.length-1];if(s.version!==t.version||s.hash!==t.hash||s.definition.id!==t.id||!vc(s.definition,i))return Cc("The last lineage generation does not match the current package");if(t.legacy!==void 0){let a=new Set(Object.keys(t.actions)),d=new Set;for(let l of o)if(l.sourceHash===void 0)for(let p of Object.keys(l.definition.actions))a.has(p)&&d.add(p);let c=Object.keys(t.legacy.agentAccess??{});if(c.length!==d.size||c.some(l=>!d.has(l))){let l="S4_LEGACY_AGENT_ACCESS_COMPLETE";throw new De("LINEAGE_INVALID",`Lineage compatibility failed: ${l}`,[l])}}for(let a=0;a<o.length-1;a+=1){if(o.slice(a,-1).some(l=>l.compat==="break"))continue;let c=xc(o[a].definition,t);if(c.length>0)throw new De("LINEAGE_INVALID",`Lineage compatibility failed: ${c.join(", ")}`,c)}return Object.freeze({entries:Object.freeze(o),current:t})}var De,Mo,Mc,Lc,Oc,Rc,wc,Uc,Qt=V(()=>{m();Ve();Se();De=class extends Error{constructor(t,i=t,o=[]){super(i);this.code=t;this.violations=o;}code;violations;name="UiDefinitionLineageError"},Mo=/^[0-9a-f]{64}$/,Mc=["version","hash","definition"],Lc=["sourceHash","compat"],Oc=["id","version","actions"],Rc=["sourceHash","usage","detailPanel","displayModes","renderer","surfaces","stateProjection","dataPaths","summaryProjection","legacy"],wc=["capabilities"],Uc=["inputKeys","dataInputs","confirmation","resultProjection","content","env"];});var wo,Uo,Co,ei,ko=V(()=>{m();wo="text/html;profile=mcp-app",Uo=["crewx_app_terminal_connect","crewx_app_html_viewer_open"],Co=["crewx_listWorkspaces","crewx_queryAgent","crewx_executeAgent","crewx_getTaskResult","crewx_listTasks","crewx_listAgents","callBrowser","openTab","listTabs","closeTab"],ei="text/html";});function xo(e,n=[],t){if(e.content!==void 0||e.confirmation!=="none")return "denied";let i=jc();return i&&Object.hasOwn(i,e.actionId)?i[e.actionId]:e.backend?.type==="core"&&e.backend.handler.startsWith("host.")?"denied":e.backend?.type==="core"&&e.backend.handler==="state.set"?"allowed":e.backend?.type==="skill"?"approval_required":e.backend===void 0&&n.includes(e.actionId)?"allowed":"denied"}function jc(e){return;}var vo=V(()=>{m();Ve();zn();});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:ve}),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:ve}),n}function je(e,n,t){return (typeof e!="string"||!Fo.test(e))&&b(n,`${t} must be a safe identifier`),e}function _n(e,n,t){let i=e??t;return (typeof i!="string"||i.trim().length===0||i.length>Bc)&&b("TOOL_INVALID",`${n} must be a meaningful description`),i}function ti(e){return (typeof e!="string"||e.length===0||e.length>sn||!/<html(?:\s|>)/i.test(e)||!/<\/html\s*>/i.test(e))&&b("HTML_INVALID","MCP App HTML must be a non-empty HTML document"),e}function En(e,n=0){try{let t=fe(e,n);return t.type!==void 0&&t.type!=="object"&&b("TOOL_INVALID","MCP App inputSchema must describe an object"),t}catch(t){if(t instanceof Ne)throw t;b("TOOL_INVALID","MCP App inputSchema must be projection-safe JSON");}}function Kc(e){return (typeof e!="string"||e.trim().length===0||e.length>Hc)&&b("TOOL_INVALID","MCP App tools require a meaningful text fallback"),e}function Xc(e){e===void 0&&b("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)&&b("TOOL_INVALID","MCP App tool visibility must contain model and/or app once"),n}function Ho(e){return (typeof e!="string"||!Vo.test(e))&&b("RESOURCE_URI_INVALID","MCP App resource URI is not a registered ui:// URI"),e}function zo(e){let n=je(e.appId,"APP_ID_INVALID","Local App id"),t=_n(e.name,"Local App name",n),i=_n(e.description,"Local App description",`${t} interactive view`),o=Jn(e.definition),r=ti(e.html),s=$n(e.entryHash,"Local App entry hash"),a=e.entryBytes===void 0?Array.from(new TextEncoder().encode(r)):Wn(e.entryBytes,"Local App entry bytes");(Gn(a)!==s||Wo(a)!==r)&&b("HTML_INVALID","Local App entry bytes do not match the HTML hash");let d=Yc(e),c=[];Array.isArray(e.actions)||b("TOOL_INVALID","Local App actions must be an array");for(let N of e.actions){let w=je(N.actionId,"TOOL_ID_INVALID","Local App action id");(c.includes(w)||!Object.prototype.hasOwnProperty.call(o.actions,w))&&b("TOOL_INVALID",`Local App action is not declared by the UI definition: ${w}`),c.push(w);}let l=je(e.readToolName,"TOOL_ID_INVALID","Local App read tool name"),p=e.actionToolName===void 0?void 0:je(e.actionToolName,"TOOL_ID_INVALID","Local App action tool name");c.length===0&&p!==void 0&&b("TOOL_INVALID","A static local App cannot register an action tool"),c.length>0&&p===void 0&&b("TOOL_INVALID","A stateful local App requires an action tool name"),p!==void 0&&p===l&&b("TOOL_ID_CONFLICT",`Local App read and action tools share a name: ${l}`);let u=Jc(e.runtime);u.some(N=>N.name===l||N.name===p)&&b("TOOL_ID_CONFLICT","Local App read or action tool conflicts with a requested Host capability");let f={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:ve},g=[Object.freeze(f)];if(g.push(...u.map(N=>Object.freeze(N))),p!==void 0){let N={name:p,description:`${t} actions`,inputSchema:ii(e.actions),textFallback:`${t} action requests are handled by the open App instance.`,visibility:Object.freeze(["app"]),kind:"action",resourceBinding:ve,actionIds:Object.freeze([...c])};g.push(Object.freeze(N));}let E=[],O=new Set(g.map(N=>N.name));if(p!==void 0)for(let N of e.actions){let w=`${p}__${N.actionId}`;if(w.length>128||!Fo.test(w)){E.push(Object.freeze({toolName:w,actionId:N.actionId,reason:"name_too_long"}));continue}if(O.has(w)){E.push(Object.freeze({toolName:w,actionId:N.actionId,reason:"name_collision"}));continue}let v=xo({actionId:N.actionId,confirmation:o.actions[N.actionId]?.confirmation,content:o.actions[N.actionId]?.content,backend:N.backend},e.modelActions),T=Object.freeze(v==="denied"?["app"]:["model","app"]),D={name:w,description:`${w} action`,inputSchema:En(N.inputSchema),textFallback:`${w} action requests are handled by the open App instance.`,visibility:T,kind:"action",resourceBinding:ve,actionId:N.actionId,actionIds:Object.freeze([N.actionId]),_meta:Object.freeze({ui:Object.freeze({visibility:T})})};g.push(Object.freeze(D)),O.add(w);}let F={mimeType:ei,entryHash:s,html:r,bytes:Object.freeze([...a]),...d===void 0?{}:{initialState:Object.freeze({hash:d.hash,bytes:Object.freeze([...d.bytes])})}},x={appId:n,name:t,description:i,...e.icon===void 0?{}:{icon:Jo(e.icon)},...e.tone===void 0?{}:{tone:Ko(e.tone)},builtinOnly:false,definition:o,...e.runtime===void 0?{}:{runtime:Object.freeze({...e.runtime})},resourceBinding:ve,resource:Object.freeze(F),tools:Object.freeze(g),toolDiagnostics:Object.freeze(E)};return Z(x)}function $o(e={}){return new ni(e)}function ii(e){if(e.length===0)return En({type:"object",properties:{},additionalProperties:false});let n=e.map(i=>i.actionId),t=new Map;for(let i of e)t.set(i.actionId,En(i.inputSchema));return En(qc(n,t),Bo)}function Yc(e){let n=e.definition.dataPaths??[];if(e.initialStateBytes===void 0){e.initialStateHash!==void 0&&b("STATE_INVALID","Initial state hash has no bytes"),e.initialState!==void 0&&fe(e.initialState,0,n);return}e.initialStateHash===void 0&&b("STATE_INVALID","Initial state bytes require a hash");let t=$n(e.initialStateHash,"Initial state hash"),i=Wn(e.initialStateBytes,"Initial state bytes");Gn(i)!==t&&b("STATE_INVALID","Initial state bytes do not match the hash");let o;try{let r=new TextDecoder("utf-8",{fatal:!0}).decode(Uint8Array.from(i));o=fe(JSON.parse(r),0,n);}catch{b("STATE_INVALID","Initial state bytes are not projection-safe JSON");}return e.initialState!==void 0&&ne(o)!==ne(fe(e.initialState,0,n))&&b("STATE_INVALID","Initial state bytes do not match the state value"),{hash:t,bytes:Object.freeze([...i])}}function qc(e,n){let t=e.map(i=>({type:"object",properties:{actionId:{type:"string",const:i},input:n.get(i)??{type:"object"}},required:["actionId","input"],additionalProperties:false}));return Object.freeze({type:"object",oneOf:Object.freeze(t),properties:Object.freeze({actionId:Object.freeze({type:"string",enum:Object.freeze([...e])}),input:Object.freeze({type:"object"})}),required:Object.freeze(["actionId","input"]),additionalProperties:false})}function Zc(e){let n=Tn(e),t=je(n.appId,"APP_ID_INVALID","MCP App id"),i=ti(n.html);Ho(n.uiUri);let o=n.definition===void 0?void 0:Jn(n.definition),r=e.provenance;r!==void 0&&(!rn(r)||r.appId!==t||r.definitionId!==o?.id||r.version!==o?.version||r.definitionHash!==o?.hash)&&b("TOOL_INVALID","Product App built-in registration provenance is not verified");let s=Object.freeze(n.tools.map(c=>Z(Tn(c)))),a=Z({...n,appId:t,html:i,...o===void 0?{}:{definition:o},...r===void 0?{}:{provenance:r},tools:s}),d=Z({uri:a.uiUri,mimeType:wo,text:i,...a.csp===void 0?{}:{_meta:{ui:{csp:a.csp}}}});return Z({appId:t,name:a.name,description:a.description,...a.icon===void 0?{}:{icon:a.icon},...a.tone===void 0?{}:{tone:a.tone},builtinOnly:a.builtinOnly,uiUri:a.uiUri,...o===void 0?{}:{definition:o},resourceBinding:Object.freeze({kind:"mcp",uri:a.uiUri}),resource:d,tools:s,descriptor:a})}function Qc(e){(e.resourceBinding.kind!=="instance"||e.builtinOnly!==false)&&b("STATE_INVALID","Local App registration binding is invalid"),Object.prototype.hasOwnProperty.call(e,"uiUri")&&b("STATE_INVALID","Local App registration cannot contain uiUri");let n=je(e.appId,"APP_ID_INVALID","Local App id"),t=Jn(e.definition),i=e.provenance;i!==void 0&&(!rn(i)||i.appId!==n||i.definitionId!==t.id||i.version!==t.version||i.definitionHash!==t.hash)&&b("TOOL_INVALID","Product App local registration provenance is not verified");let o=ti(e.resource.html),r=$n(e.resource.entryHash,"Local App entry hash"),s=Wn(e.resource.bytes,"Local App entry bytes");(Gn(s)!==r||Wo(s)!==o)&&b("HTML_INVALID","Local App entry bytes do not match the HTML hash");let a=e.resource.initialState===void 0?void 0:{hash:$n(e.resource.initialState.hash,"Initial state hash"),bytes:Wn(e.resource.initialState.bytes,"Initial state bytes")};a&&Gn(a.bytes)!==a.hash&&b("STATE_INVALID","Initial state bytes do not match the hash");let d=e.tools.map(c=>{je(c.name,"TOOL_ID_INVALID","Local App tool name"),_n(c.description,"Local App tool description","Local App tool"),Kc(c.textFallback);let l=En(c.inputSchema,c.kind==="action"&&!("actionId"in c)?Bo:0);if((c.resourceBinding.kind!=="instance"||Object.prototype.hasOwnProperty.call(c,"resourceUri"))&&b("TOOL_INVALID","Local App tools cannot carry an MCP resource URI"),c.kind==="host")return (!Gc.has(c.name)||c.visibility.length!==1||c.visibility[0]!=="app"||Object.prototype.hasOwnProperty.call(c,"actionId"))&&b("TOOL_INVALID","Local App Host tools must use an allow-listed name and app-only visibility"),Z({...c,inputSchema:l,visibility:Object.freeze(["app"])});if(c.kind==="action"){if("actionId"in c){let u=je(c.actionId,"TOOL_ID_INVALID","Local App action id");Object.prototype.hasOwnProperty.call(t.actions,u)||b("TOOL_INVALID","Local App action tool references an undeclared action");let f=Xc(c._meta.ui.visibility);return JSON.stringify(f)!==JSON.stringify(c.visibility)&&b("TOOL_INVALID","Local App action metadata visibility must match the tool visibility"),Z({...c,actionId:u,actionIds:Object.freeze([u]),inputSchema:l,visibility:f,_meta:{ui:{visibility:f}}})}let p=[...c.actionIds];return (p.length===0||p.some(u=>!Object.prototype.hasOwnProperty.call(t.actions,u)))&&b("TOOL_INVALID","Local App action tool references an undeclared action"),Z({...c,inputSchema:l,actionIds:Object.freeze(p)})}return Z({...c,inputSchema:l})});return Z({appId:n,name:_n(e.name,"Local App name",e.appId),description:_n(e.description,"Local App description",e.name),...e.icon===void 0?{}:{icon:Jo(e.icon)},...e.tone===void 0?{}:{tone:Ko(e.tone)},builtinOnly:false,definition:t,...e.runtime===void 0?{}:{runtime:Object.freeze({...e.runtime})},...i===void 0?{}:{provenance:i},resourceBinding:ve,resource:Z({mimeType:ei,entryHash:r,html:o,bytes:Object.freeze([...s]),...a===void 0?{}:{initialState:Object.freeze({hash:a.hash,bytes:Object.freeze([...a.bytes])})}}),tools:Object.freeze(d),toolDiagnostics:Object.freeze([...e.toolDiagnostics??[]])})}function ed(e){return Z({appId:e.appId,name:e.name,description:e.description,...e.icon===void 0?{}:{icon:e.icon},...e.tone===void 0?{}:{tone:e.tone},builtinOnly:false,definition:Go(e.definition),...e.provenance===void 0?{}:{provenance:e.provenance},entryHash:e.resource.entryHash,resourceBinding:ve,tools:e.tools})}function nd(e){return Z({appId:e.appId,name:e.name,description:e.description,...e.icon===void 0?{}:{icon:e.icon},...e.tone===void 0?{}:{tone:e.tone},builtinOnly:e.builtinOnly,uiUri:e.uiUri,...e.definition===void 0?{}:{definition:Go(e.definition)},resourceBinding:Object.freeze({kind:"mcp",uri:e.uiUri}),tools:e.tools})}function Jn(e){try{if(Object.isFrozen(e))return ye(e),Z(e);let n=Tn(e);return ye(n),Z(n)}catch(n){if(n instanceof Ne)throw n;b("STATE_INVALID","UI definition is not a valid immutable definition");}}function Go(e){return Z({id:e.id,version:e.version,hash:e.hash})}function td(e){return e!==null&&typeof e=="object"&&typeof e.id=="string"&&Number.isSafeInteger(e.version)&&typeof e.hash=="string"}function jo(e,n,t){return `${e}\0${n}\0${t}`}function $n(e,n){return (typeof e!="string"||!Vc.test(e))&&b("SERIALIZATION_INVALID",`${n} is invalid`),e}function Gn(e){return bi.createHash("sha256").update(Uint8Array.from(e)).digest("hex")}function Wn(e,n){return (!Array.isArray(e)||e.some(t=>!Number.isInteger(t)||t<0||t>255))&&b("SERIALIZATION_INVALID",`${n} is invalid`),[...e]}function Wo(e){try{return new TextDecoder("utf-8",{fatal:!0}).decode(Uint8Array.from(e))}catch{b("SERIALIZATION_INVALID","UTF-8 bytes are invalid");}}function Jo(e){return (typeof e!="string"||!zc.test(e))&&b("TOOL_INVALID","MCP App icon is invalid"),e}function Ko(e){return (typeof e!="string"||!$c.has(e))&&b("TOOL_INVALID","MCP App tone is invalid"),e}function Tn(e,n=new Map){if(e===null||typeof e!="object")return e;let t=e;if(n.has(t)&&b("SERIALIZATION_INVALID","MCP App value contains a cycle"),Array.isArray(e)){let r=[];n.set(t,r);for(let s of e)r.push(Tn(s,n));return n.delete(t),r}let i;try{i=Object.getPrototypeOf(e);}catch{b("SERIALIZATION_INVALID","MCP App value cannot be cloned");}i!==Object.prototype&&i!==null&&b("SERIALIZATION_INVALID","MCP App value must be plain JSON");let o={};n.set(t,o);for(let[r,s]of Object.entries(e))Object.defineProperty(o,r,{configurable:true,enumerable:true,value:Tn(s,n),writable:true});return n.delete(t),o}function Z(e,n=new Set){if(e===null||typeof e!="object"||n.has(e))return e;n.add(e);for(let t of Object.values(e))Z(t,n);return Object.freeze(e),e}var Fo,Vo,Vc,sn,Bc,Hc,zc,$c,Gc,ve,Wc,Bo,ni,Kn=V(()=>{m();Do();Ve();Se();zn();Hn();Qt();ko();vo();Fo=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,Vo=/^ui:\/\/crewx\/([A-Za-z][A-Za-z0-9._-]{0,127})\/([0-9a-f]{12})$/,Vc=/^[0-9a-f]{64}$/,sn=8*1024*1024,Bc=8*1024,Hc=16*1024,zc=/^[a-z][a-z0-9-]{0,63}$/,$c=new Set(["blue","violet","emerald","amber","rose","sky","slate","indigo"]),Gc=new Set(Uo),new Set(Co),ve=Object.freeze({kind:"instance"}),Wc=Object.freeze({type:"object",properties:Object.freeze({}),additionalProperties:false});Bo=4;ni=class{builtinApps;localApps;builtinDescriptors;builtinTools;mcpResources=new Map;localById=new Map;registrationById=new Map;launcherById=new Map;definitionByKey=new Map;handlerByKey=new Map;mcpToolByName=new Map;localToolByName=new Map;constructor(n){let t=n.builtins??n.builtin,i=[],o=[],r=[],s=new Set,a=new Set;for(let p of t?.listMcpApps()??[]){let u=Zc(p);s.has(u.appId)&&b("APP_ID_CONFLICT",`MCP App id is already registered: ${u.appId}`),s.add(u.appId);let f=u.tools;for(let g of f)a.has(g.name)&&b("TOOL_ID_CONFLICT",`MCP App tool name is already registered: ${g.name}`),a.add(g.name),this.mcpToolByName.set(g.name,g),r.push(g);this.mcpResources.set(u.resource.uri,u.resource),i.push(u),o.push(u.descriptor);}let d=(n.localApps??n.locals??[]).map(Qc),c=new Set(d.flatMap(p=>p.tools.filter(u=>!(u.kind==="action"&&"actionId"in u)).map(u=>u.name))),l=[];for(let p of d){let u=p;s.has(u.appId)&&b("APP_ID_CONFLICT",`MCP App id is already registered: ${u.appId}`),s.add(u.appId);let f=[],g=[...u.toolDiagnostics??[]];for(let E of u.tools){if(a.has(E.name)){if(E.kind==="host"&&this.localToolByName.get(E.name)?.kind==="host"){f.push(E);continue}if(E.kind==="action"&&"actionId"in E){g.push(Object.freeze({toolName:E.name,actionId:E.actionId,reason:"name_collision"}));continue}b("TOOL_ID_CONFLICT",`MCP App tool name is already registered: ${E.name}`);}if(E.kind==="action"&&"actionId"in E&&c.has(E.name)){g.push(Object.freeze({toolName:E.name,actionId:E.actionId,reason:"name_collision"}));continue}a.add(E.name),this.localToolByName.set(E.name,E),f.push(E);}(f.length!==u.tools.length||g.length!==(u.toolDiagnostics?.length??0))&&(u=Z({...u,tools:Object.freeze(f),toolDiagnostics:Object.freeze(g)})),l.push(u),this.localById.set(u.appId,u);}for(let p of i)this.registrationById.set(p.appId,p),this.launcherById.set(p.appId,nd(p)),p.definition&&this.addDefinition(p.definition);for(let p of l)this.registrationById.set(p.appId,p),this.launcherById.set(p.appId,ed(p)),this.addDefinition(p.definition);for(let p of n.definitions??[])this.addDefinition(p);for(let p of n.handlers??[])this.addHandler(p);this.builtinApps=Object.freeze(i),this.localApps=Object.freeze(l),this.builtinDescriptors=Object.freeze(o),this.builtinTools=Object.freeze(r);}getMcpApp(n){return this.builtinApps.find(t=>t.appId===n)?.descriptor??null}listMcpApps(){return this.builtinDescriptors}listMcpAppTools(){return this.builtinTools}resolveMcpAppTool(n){return this.mcpToolByName.get(n)??null}resolveMcpAppResource(n){return typeof n!="string"||!Vo.test(n)?null:this.mcpResources.get(n)??null}requireMcpAppResource(n){Ho(n);let t=this.mcpResources.get(n);return t||b("RESOURCE_NOT_FOUND",`MCP App resource is not registered: ${n}`),t}listLocalMcpApps(){return this.localApps}getLocalMcpApp(n){return this.localById.get(n)??null}listLocalMcpAppTools(){return Object.freeze([...this.localToolByName.values()])}resolveLocalMcpAppTool(n){return this.localToolByName.get(n)??null}resolveLocalMcpAppResource(n,t){let i=this.localById.get(n);return !i||t!==void 0&&i.definition.hash!==t?null:i.resource}listRegistrations(){return Object.freeze([...this.builtinApps,...this.localApps])}getRegistration(n){return this.registrationById.get(n)??null}listLaunchers(){return Object.freeze([...this.launcherById.values()].filter(n=>{let t=this.registrationById.get(n.appId),i=t?"descriptor"in t?t.descriptor.provenance:t.provenance:void 0,o=rn(i)&&i.launcher===false;return t?.definition?.usage!=="card"&&!o}))}getLauncher(n){return this.launcherById.get(n)??null}resolveDefinition(n){if(!td(n))return null;let t=this.definitionByKey.get(Lt(n));if(!t||t.hash!==n.hash)return null;try{return pe(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(jo(n,t,i))??null}addDefinition(n){let t=Jn(n),i=Lt(t),o=this.definitionByKey.get(i);o&&o.hash!==t.hash&&b("STATE_INVALID",`UI definition generation conflicts: ${i}`),o||this.definitionByKey.set(i,t);}addHandler(n){(!n||typeof n.definitionId!="string"||typeof n.actionId!="string"||!Number.isSafeInteger(n.version)||n.version<1||typeof n.handle!="function")&&b("STATE_INVALID","UI action handler registration is invalid");let t=jo(n.definitionId,n.version,n.actionId);this.handlerByKey.has(t)&&b("TOOL_INVALID",`Duplicate UI action handler registration: ${t}`),this.handlerByKey.set(t,Object.freeze({...n}));}};});function id(e){let n=zo({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 Xo(e){let n=e.normalized.manifest.actions;if(n.some(i=>i.backend.type==="skill")&&n.some(i=>i.backend.type==="core"))throw new Error("Mixed workspace App execution models");let t=id(e);$o({localApps:[t],definitions:[e.definition]});}var Yo=V(()=>{m();Kn();});function od(e){if(e===null||typeof e!="object"||!(qo in e))throw new TypeError("scanCache must be created by createWorkspaceAppScanCache");return e[qo]}function Zo(e,n){let t=od(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.lastCandidateScanUnchanged=void 0,t.lastCandidateKeys=void 0,t.scanStartedAtNs=void 0,t.lastAssetCatalogsUnchanged=void 0,t.lastSnapshot=void 0,t.lastSnapshotBuildInputs=void 0),t.rootIdentity=n,t}var qo,Qo=V(()=>{m();qo=Symbol("crewx.workspace-app-scan-cache.state");});function le(e){let n=typeof e=="object"&&e!==null&&"code"in e?String(e.code):"";return n==="ENOENT"?new S("NOT_FOUND"):n==="ELOOP"?new S("PATH_ESCAPED"):n==="EFBIG"||n==="EOVERFLOW"?new S("LIMIT_EXCEEDED"):n==="EACCES"||n==="EPERM"||n==="ENOTDIR"?new S("READ_DENIED"):new S("READ_DENIED")}function cd(e){if(typeof e!="string"||e.length===0||!ae.isAbsolute(e))throw new S("READ_DENIED")}function oi(e){if(typeof e!="string"||ae.isAbsolute(e)||/[\\\u0000]/.test(e))throw new S("PATH_ESCAPED");if(e==="")return [];let n=e.split("/");if(n.some(t=>t.length===0||t==="."||t===".."))throw new S("PATH_ESCAPED");return n}function Zn(e,n){let t=ae.relative(e,n);return t===""||t!==".."&&!t.startsWith(`..${ae.sep}`)&&!ae.isAbsolute(t)}function cn(e){return {dev:e.dev,ino:e.ino,size:e.size,mtimeNs:e.mtimeNs,ctimeNs:e.ctimeNs}}function ci(e,n){return e.dev===n.dev&&e.ino===n.ino}function di(e,n){return ci(e,n)&&e.size===n.size&&e.mtimeNs===n.mtimeNs&&e.ctimeNs===n.ctimeNs}async function Xn(e){cd(e);let n,t;try{n=await promises.realpath(e),t=await promises.stat(n,{bigint:!0});}catch(i){throw le(i)}if(!t.isDirectory())throw new S("READ_DENIED");return {realRoot:n,identity:cn(t)}}async function tr(e,n,t){if(t.length<2||t[0]!=="apps"&&t[0]!=="skills")return;let i,o;try{if(i=ae.resolve(e,t[0],t[1]),o=await promises.realpath(i),!(await promises.stat(o,{bigint:!0})).isDirectory())throw new S("READ_DENIED")}catch(r){throw r instanceof S?r:le(r)}if(!Zn(n,o))throw new S("PATH_ESCAPED");return o}async function Yn(e,n,t,i){let o,r,s;try{o=await promises.lstat(e,{bigint:!0}),r=await promises.realpath(e),s=await promises.stat(r,{bigint:!0});}catch(a){throw le(a)}if(!Zn(n,r)||t!==void 0&&!Zn(t,r))throw new S("PATH_ESCAPED");if(!o.isFile()||!s.isFile())throw new S("READ_DENIED");if(!ci(i,o)||!ci(i,s)||i.dev!==s.dev)throw new S("PATH_ESCAPED")}async function an(e,n){let t,i;try{t=await promises.realpath(e),i=await promises.stat(t,{bigint:!0});}catch{throw new S("PATH_ESCAPED")}if(t!==n.realRoot||!di(n.identity,cn(i)))throw new S("PATH_ESCAPED")}function dd(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 S,ai,ad,nr,Qn,ir,li=V(()=>{m();S=class extends Error{constructor(t){super(t);this.code=t;}code;name="AppDiscoveryFsError"},ai=ee.constants.O_NOFOLLOW,ad=ee.constants.O_NONBLOCK,nr=ee.constants.O_RDONLY|(ai??0)|(ad??0);Qn=class{async getRootIdentity(n){let t=await Xn(n);return await an(n,t),{dev:t.identity.dev,ino:t.identity.ino,realPath:t.realRoot}}async listDirectory(n,t){let i=oi(t),o=await Xn(n),r=ae.resolve(n,...i),s,a;try{s=await promises.realpath(r),a=await promises.stat(s,{bigint:!0});}catch(d){let c=le(d);if(c.code==="NOT_FOUND")return [];throw c}if(!Zn(o.realRoot,s)||!a.isDirectory())throw new S("PATH_ESCAPED");try{let d=await promises.readdir(s,{withFileTypes:!0,encoding:"utf8"});return await an(n,o),d.map(dd)}catch(d){let c=le(d);if(c.code==="NOT_FOUND")return [];throw c}}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 S("READ_DENIED");if(ai===void 0)throw new S("UNSUPPORTED");let o=oi(t),r=await Xn(n),s=ae.resolve(n,...o),a=ae.relative(n,s);if(a===".."||a.startsWith(`..${ae.sep}`)||ae.isAbsolute(a))throw new S("PATH_ESCAPED");let d;try{d=await promises.open(s,nr);}catch(c){throw le(c)}try{let c;try{let g=await d.stat({bigint:!0});c=cn(g);}catch(g){throw le(g)}if(c.size>BigInt(i))throw new S("LIMIT_EXCEEDED");if(c.size>BigInt(Number.MAX_SAFE_INTEGER))throw new S("LIMIT_EXCEEDED");await an(n,r);let l=await tr(n,r.realRoot,o);await Yn(s,r.realRoot,l,c);let p=new Uint8Array(new ArrayBuffer(Number(c.size))),u=0;for(;u<p.byteLength;){let g;try{g=(await d.read(p,u,p.byteLength-u,u)).bytesRead;}catch(E){throw le(E)}if(g<=0)throw new S("IDENTITY_CHANGED");u+=g;}let f;try{let g=await d.stat({bigint:!0});f=cn(g);}catch(g){throw le(g)}if(!di(c,f))throw new S("IDENTITY_CHANGED");return await Yn(s,r.realRoot,l,f),await an(n,r),new Uint8Array(p)}finally{await d.close().catch(()=>{});}}async fingerprintVerifiedFile(n,t,i){if(!Number.isSafeInteger(i)||i<0)throw new S("READ_DENIED");if(ai===void 0)throw new S("UNSUPPORTED");let o=oi(t),r=await Xn(n),s=ae.resolve(n,...o),a=ae.relative(n,s);if(a===".."||a.startsWith(`..${ae.sep}`)||ae.isAbsolute(a))throw new S("PATH_ESCAPED");let d;try{d=await promises.open(s,nr);}catch(c){throw le(c)}try{let c;try{let u=await d.stat({bigint:!0});c=cn(u);}catch(u){throw le(u)}if(c.size>BigInt(i)||c.size>BigInt(Number.MAX_SAFE_INTEGER))throw new S("LIMIT_EXCEEDED");await an(n,r);let l=await tr(n,r.realRoot,o);await Yn(s,r.realRoot,l,c);let p;try{let u=await d.stat({bigint:!0});p=cn(u);}catch(u){throw le(u)}if(!di(c,p))throw new S("IDENTITY_CHANGED");return await Yn(s,r.realRoot,l,p),await an(n,r),{...p,candidateRealPath:l??r.realRoot}}catch(c){throw c instanceof S?c:le(c)}finally{await d.close().catch(()=>{});}}async readFileVerified(n,t,i){return this.readVerifiedFile(n,t,i)}},ir=new Qn;});function bn(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;try{let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}catch{return false}}function rr(e){return typeof e=="string"&&_e.test(e)?e:void 0}function Id(e){return e.length>0&&e!=="."&&e!==".."&&!/[\\/\u0000]/.test(e)}function Ge(e,n){let t=new TextEncoder().encode(e),i=new TextEncoder().encode(n),o=Math.min(t.byteLength,i.byteLength);for(let r=0;r<o;r+=1){let s=t[r]-i[r];if(s!==0)return s}return t.byteLength-i.byteLength}function gd(e){if(typeof e=="string")return {name:e,kind:"directory"};if(e===null||typeof e!="object")return null;let n=e;if(typeof n.name!="string")return null;if(n.kind==="file"||n.kind==="directory"||n.kind==="symlink"||n.kind==="other")return {name:n.name,kind:n.kind};if(n.type==="file"||n.type==="directory"||n.type==="symlink"||n.type==="other")return {name:n.name,kind:n.type};let t=n.isDirectory;if(typeof t=="function"&&t.call(e))return {name:n.name,kind:"directory"};let i=n.isSymbolicLink;if(typeof i=="function"&&i.call(e))return {name:n.name,kind:"symlink"};let o=n.isFile;return typeof o=="function"&&o.call(e)?{name:n.name,kind:"file"}:{name:n.name,kind:"other"}}function md(e){if(e instanceof Uint8Array)return new Uint8Array(e);if(e instanceof ArrayBuffer)return new Uint8Array(e.slice(0));if(Array.isArray(e)&&e.every(n=>Number.isInteger(n)&&n>=0&&n<=255))return Uint8Array.from(e);throw new TypeError("filesystem port returned an invalid byte array")}function hd(e){return yd.decode(e)}function _d(e){return JSON.parse(hd(e))}function sr(e){switch(e){case "ENOENT":return "NOT_FOUND";case "ELOOP":case "EXDEV":return "PATH_ESCAPED";case "EFBIG":case "EOVERFLOW":return "LIMIT_EXCEEDED";case "EACCES":case "EPERM":case "ENOTDIR":return "READ_DENIED";default:return e}}function Ed(e){if(e instanceof S)return sr(e.code);if(e!==null&&typeof e=="object"&&"code"in e){let n=e.code;if(typeof n=="string")return sr(n)}}function Le(e,n){let t=n();return Number.isFinite(t)&&Number.isFinite(e)&&t-e<=5e3}function Td(e){if(typeof e.readVerifiedFile=="function")return e.readVerifiedFile;if(typeof e.readFileVerified=="function")return e.readFileVerified}function Pd(e){if(typeof e.listDirectory=="function")return e.listDirectory;if(typeof e.readDirectory=="function")return e.readDirectory;if(typeof e.readdir=="function")return e.readdir}async function ar(e,n,t,i){let o=Td(e);if(!o)throw new S("READ_DENIED");return md(await o.call(e,n,t,i))}async function yi(e,n,t){let i=Pd(e);if(!i)throw new S("READ_DENIED");let o=await i.call(e,n,t);if(!Array.isArray(o))throw new S("READ_DENIED");return o.map(gd).filter(r=>r!==null)}function Nd(e,n,t,i){return Object.freeze({code:e,...{},source:n,relativePath:t})}function Dd(e){if(!bn(e))throw new TypeError("productBundle.reservedIds must be an object with appIds and definitionIds arrays");try{let n=Reflect.ownKeys(e);if(n.length!==2||!n.includes("appIds")||!n.includes("definitionIds"))throw new TypeError("productBundle.reservedIds must contain exactly appIds and definitionIds");let t=(i,o)=>{if(!Array.isArray(i))throw new TypeError("productBundle.reservedIds."+o+" must be an array");let r=[];for(let s=0;s<i.length;s+=1){let a=i[s];if(typeof a!="string"||a.length===0)throw new TypeError("productBundle.reservedIds."+o+" must contain non-empty strings");r.push(a);}return Object.freeze([...new Set(r)].sort(Ge))};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 bd(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 nt(e){return Object.freeze({appIds:Object.freeze([...new Set(e.map(n=>n.appId))].sort(Ge)),definitionIds:Object.freeze([...new Set(e.map(n=>n.definition.id))].sort(Ge))})}function et(e,n){let t=Object.keys(e).sort(Ge),i=[...n].sort(Ge);return t.length===i.length&&t.every((o,r)=>o===i[r])}function cr(e){if(typeof e!="string"||e.length===0||e.startsWith("/")||/[\\\u0000]/.test(e))return;let n=e.split("/");if(!n.some(t=>t.length===0||t==="."||t===".."))return n}function Sd(e){let n;try{n=_d(e);}catch{return}if(!bn(n)||!et(n,["version","packages"])||n.version!==1||!Array.isArray(n.packages)||n.packages.length>Ai)return;let t=new Set,i=new Set,o=0,r=[];for(let s of n.packages){if(!bn(s))return;let a=["packageDir","appId","definition","files"],d=Object.hasOwn(s,"lineage"),c=Object.hasOwn(s,"launcher"),l=[...d?["lineage"]:[],...c?["launcher"]:[]];if(!et(s,[...a,...l])||c&&s.launcher!==false)return;let p=cr(s.packageDir),u=rr(s.appId);if(!p||p.length!==2||p[0]!=="apps"||!Id(p[1])||!u||t.has(s.packageDir)||!bn(s.definition)||!et(s.definition,["id","version","hash"]))return;let f=rr(s.definition.id),g=s.definition.version,E=s.definition.hash;if(!f||!Number.isSafeInteger(g)||g<1||typeof E!="string"||!fi.test(E)||!Array.isArray(s.files)||s.files.length<2||s.files.length>Ii)return;let O=new Set,F=[];for(let x of s.files){if(!bn(x)||!et(x,["path","sha256"]))return;let N=cr(x.path);if(!N||typeof x.sha256!="string"||!fi.test(x.sha256))return;let w=N.join("/"),v=`${s.packageDir}/${w}`;if(O.has(w)||i.has(v))return;O.add(w),i.add(v),F.push(Object.freeze({path:w,sha256:x.sha256}));}if(!q.some(x=>O.has(x))||!O.has("ui/index.html")||(o+=F.length,o>ld))return;t.add(s.packageDir),r.push(Object.freeze({packageDir:s.packageDir,...c?{launcher:false}:{},appId:u,definition:Object.freeze({id:f,version:g,hash:E}),lineage:Array.isArray(s.lineage)?s.lineage:[],files:Object.freeze(F.sort((x,N)=>Ge(x.path,N.path)))}));}return Object.freeze({version:1,packages:Object.freeze(r)})}function $e(e){let n=Ed(e);return n==="PATH_ESCAPED"||n==="IDENTITY_CHANGED"||n==="TOCTOU"?"PATH_ESCAPED":n==="LIMIT_EXCEEDED"?"LIMIT_EXCEEDED":"BUNDLE_INTEGRITY"}async function Md(e,n,t,i,o){let r=[],s=async(a,d)=>{if(!Le(i,o))throw new S("LIMIT_EXCEEDED");if(d>2)throw new S("LIMIT_EXCEEDED");let c=await yi(e,n,a);for(let l of c){if(typeof l.name!="string"||l.name.length===0||l.name==="."||l.name===".."||/[\\/\u0000]/.test(l.name))throw new S("PATH_ESCAPED");let p=`${a}/${l.name}`;if(l.kind==="file"){if(r.push(p.slice(t.length+1)),r.length>Ii)throw new S("LIMIT_EXCEEDED")}else if(l.kind==="directory")await s(p,d+1);else throw l.kind==="symlink"?new S("PATH_ESCAPED"):new S("READ_DENIED")}};return await s(t,0),r.sort(Ge)}function Ld(e){return q.includes(e)?262144:e==="ui/index.html"?sn:e==="ui/state.json"?65536:e.startsWith("ui/assets/")?fd:ud}async function dr(e,n,t,i){if(e===void 0)return {packages:[],diagnostics:[],incomplete:false,reservedIds:Ad};let o=Dd(e.reservedIds),r=[],s=(y,I,h)=>Nd(y,"bundled",I),a=(y=[],I=false,h)=>({...h===void 0?{}:{indexHash:h},packages:y,diagnostics:r,incomplete:I,reservedIds:o});if(typeof e.root!="string"||e.root.length===0||typeof e.expectedIndexHash!="string"||!fi.test(e.expectedIndexHash))return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a();let d;try{d=await ar(n,e.root,"bundle-index.json",pd);}catch(y){return r.push(s($e(y),"bundle-index.json")),a()}let c=bi.createHash("sha256").update(d).digest("hex");if(c!==e.expectedIndexHash)return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a();let l=Sd(d);if(l===void 0)return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a();if(!bd(nt(l.packages),o))return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a([],false,c);if(!Le(t,i))return r.push(s("LIMIT_EXCEEDED","bundle-index.json")),a(l.packages.map(y=>({indexEntry:y,failureCode:"LIMIT_EXCEEDED"})),true,c);let p;try{p=await yi(n,e.root,"");}catch(y){return r.push(s($e(y),"bundle-index.json")),a(l.packages.map(I=>({indexEntry:I,failureCode:$e(y)})),false,c)}if(!Le(t,i))return r.push(s("LIMIT_EXCEEDED","bundle-index.json")),a(l.packages.map(y=>({indexEntry:y,failureCode:"LIMIT_EXCEEDED"})),true,c);let u=p.find(y=>y.name==="bundle-index.json"&&y.kind==="file"),f=p.find(y=>y.name==="apps"&&y.kind==="directory"),g=y=>l.packages.map(I=>({indexEntry:I,failureCode:y}));if(!u)return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a(g("BUNDLE_INTEGRITY"),false,c);let E=p.filter(y=>y.name!=="bundle-index.json"&&y.name!=="apps");if(E.length>0){let y=E.some(I=>I.kind==="symlink")?"PATH_ESCAPED":"BUNDLE_INTEGRITY";return r.push(s(y,"bundle-index.json")),a(g("BUNDLE_INTEGRITY"),false,c)}if(p.some(y=>y.name==="apps"&&y.kind!=="directory"))return r.push(s("PATH_ESCAPED","apps")),a(g("PATH_ESCAPED"),false,c);let O=[];if(f)try{O=await yi(n,e.root,"apps");}catch(y){return r.push(s($e(y),"apps")),a(g($e(y)),false,c)}if(!Le(t,i)||O.length>Ai)return r.push(s("LIMIT_EXCEEDED","apps")),a(g("LIMIT_EXCEEDED"),true,c);let F=new Map(l.packages.map(y=>[y.packageDir.slice(5),y])),x=O.filter(y=>!F.has(y.name));for(let y of x)r.push(s(y.kind==="symlink"?"PATH_ESCAPED":"BUNDLE_INTEGRITY",`apps/${y.name}`));if(x.length>0){let y=x.some(I=>I.kind==="symlink")?"PATH_ESCAPED":"BUNDLE_INTEGRITY";return a(g(y),false,c)}let N=new Set,w=new Map,v=new Map;for(let y of l.packages){let I=w.get(y.appId)??[];I.push(y),w.set(y.appId,I);let h=`${y.definition.id}\0${String(y.definition.version)}`,_=v.get(h)??[];_.push(y),v.set(h,_);}for(let y of [...w.values(),...v.values()])if(y.length>1)for(let I of y)N.add(I);let T=[],D=d.byteLength,L=false;for(let y of l.packages){if(!Le(t,i)){L=true,T.push({indexEntry:y,failureCode:"LIMIT_EXCEEDED"});continue}let I;try{let M=y.lineage[y.lineage.length-1];if(!M)throw new De("LINEAGE_INVALID","Definition lineage is missing");if(M.definition.id!==y.definition.id||M.version!==y.definition.version||M.hash!==y.definition.hash)throw new De("LINEAGE_STALE","Last lineage generation does not match bundle identity");I=Zt(y.lineage,{...M.definition,hash:M.hash}).entries;}catch(M){let W=M instanceof De?M.code:"LINEAGE_INVALID";r.push(s(W,y.packageDir)),T.push({indexEntry:y,failureCode:W});continue}let h=O.find(M=>M.name===y.packageDir.slice(5));if(!f||!h){T.push({indexEntry:y,failureCode:"BUNDLE_INTEGRITY"});continue}if(h.kind!=="directory"){T.push({indexEntry:y,failureCode:h.kind==="symlink"?"PATH_ESCAPED":"BUNDLE_INTEGRITY"});continue}let _;try{let M=await Md(n,e.root,y.packageDir,t,i);if(!Le(t,i)){L=!0,T.push({indexEntry:y,failureCode:"LIMIT_EXCEEDED"});continue}let W=y.files.map(J=>J.path);if(M.length!==W.length||M.some((J,be)=>J!==W[be])){T.push({indexEntry:y,failureCode:"BUNDLE_INTEGRITY"});continue}_=new Map;let de;for(let J of y.files){if(!Le(t,i)){de="LIMIT_EXCEEDED",L=!0;break}if(D>=ui){de="LIMIT_EXCEEDED";break}let be;try{be=await ar(n,e.root,`${y.packageDir}/${J.path}`,Ld(J.path));}catch(ys){de=$e(ys);break}if(!Le(t,i)){de="LIMIT_EXCEEDED",L=!0;break}if(D+be.byteLength>ui){D=ui,de="LIMIT_EXCEEDED";break}if(D+=be.byteLength,bi.createHash("sha256").update(be).digest("hex")!==J.sha256){de="BUNDLE_INTEGRITY";break}_.set(J.path,be);}if(de!==void 0){T.push({indexEntry:y,failureCode:de});continue}}catch(M){Le(t,i)||(L=true),T.push({indexEntry:y,failureCode:$e(M)});continue}T.push({indexEntry:y,lineage:I,files:_,...N.has(y)?{failureCode:"DUPLICATE_ID"}:{}});}return a(T,L,c)}var pd,Ai,Ii,ld,ud,fd,ui,fi,yd,Ad,gi=V(()=>{m();Qt();Fe();Vn();Kn();li();pd=256*1024,Ai=64,Ii=128,ld=Ai*Ii,ud=2*1024*1024,fd=8*1024*1024,ui=32*1024*1024,fi=/^[0-9a-f]{64}$/,yd=new TextDecoder("utf-8",{fatal:true}),Ad=Object.freeze({appIds:Object.freeze([]),definitionIds:Object.freeze([])});});function Rd(e){if(typeof e!="string"||!_e.test(e))throw new TypeError("pluginId must be a safe UI plugin identifier");let n=`${mi}${e}`.length+7<=128?e:`hash_${bi.createHash("sha256").update(e,"utf8").digest("hex")}`;return {read:`${mi}${n}_read`,action:`${mi}${n}_action`}}function lr(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;try{let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}catch{return false}}function Ud(e,n){return n.length===0||n==="."||n===".."||/[\\/\u0000]/.test(n)?e==="skills"?"skills":"apps":`${e==="skills"?"skills":"apps"}/${n}`}function Cd(e){return e.length>0&&e!=="."&&e!==".."&&!/[\\/\u0000]/.test(e)}function Sn(e,n){let t=new TextEncoder().encode(e),i=new TextEncoder().encode(n),o=Math.min(t.byteLength,i.byteLength);for(let r=0;r<o;r+=1){let s=t[r]-i[r];if(s!==0)return s}return t.byteLength-i.byteLength}function 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 o=n.isFile;return typeof o=="function"&&o.call(e)?{name:n.name,kind:"file"}:{name:n.name,kind:"other"}}function kd(e){if(e instanceof Uint8Array)return new Uint8Array(e);if(e instanceof ArrayBuffer)return new Uint8Array(e.slice(0));if(Array.isArray(e)&&e.every(n=>Number.isInteger(n)&&n>=0&&n<=255))return Uint8Array.from(e);throw new TypeError("filesystem port returned an invalid byte array")}function Pr(e){return wd.decode(e)}function xd(e){return JSON.parse(Pr(e))}function vd(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,o){let r={code:e,...i===void 0?{}:{pluginId:i},source:n,relativePath:t,...o?.reason===void 0?{}:{reason:Object.freeze({...o.reason})},...o?.files===void 0?{}:{files:Object.freeze([...o.files])}};return Object.freeze(r)}function ur(e){switch(e){case "ENOENT":return "NOT_FOUND";case "ELOOP":case "EXDEV":return "PATH_ESCAPED";case "EFBIG":case "EOVERFLOW":return "LIMIT_EXCEEDED";case "EACCES":case "EPERM":case "ENOTDIR":return "READ_DENIED";default:return e}}function se(e){if(e instanceof S)return ur(e.code);if(e!==null&&typeof e=="object"&&"code"in e){let n=e.code;if(typeof n=="string")return ur(n)}}function Je(e,n){return e==="PATH_ESCAPED"||e==="IDENTITY_CHANGED"||e==="TOCTOU"?"PATH_ESCAPED":e==="LIMIT_EXCEEDED"?"LIMIT_EXCEEDED":n==="manifest"&&e==="NOT_FOUND"?"MANIFEST_MISSING":n==="entry"?"ENTRY_INVALID":n==="initial"?"INITIAL_STATE_INVALID":"MANIFEST_INVALID"}function fr(e){return {reason:e.reason,...e.code==="MANIFEST_DUAL_MISMATCH"?{files:e.files}:{}}}function yr(e){return e==="MANIFEST_DUAL_MISMATCH"?e:Nr(e)}function jd(e){return Nr(e.code)}function Nr(e){switch(e){case "MANIFEST_INVALID":case "PRIMITIVE_UNKNOWN":case "PRIMITIVE_SET_UNSUPPORTED":case "SCHEMA_TYPE_UNSUPPORTED":case "TOKEN_INVALID":case "UNSAFE_VALUE":return "MANIFEST_INVALID";case "LIMIT_EXCEEDED":return "LIMIT_EXCEEDED";case "INITIAL_STATE_INVALID":return "INITIAL_STATE_INVALID";default:return Dr("UiPluginValidationError",e)}}function Dr(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 Dr("McpAppContractError",e)}}function Oe(e,n){let t=n();return Number.isFinite(t)&&Number.isFinite(e)&&t-e<=5e3}function Fd(e){return {pluginId:e.appId,definitionKey:`${e.definition.id}\0${String(e.definition.version)}`}}function Vd(e,n){let t=n.get("package.json");if(t!==void 0)try{let o=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(t));if(lr(o)){let r=o.bin,s=typeof r=="string"?r:lr(r)?Object.values(r).find(a=>typeof a=="string"):void 0;for(let a of [s,o.main]){if(typeof a!="string")continue;let d=Bd(a);if(d&&n.has(d))return d}}}catch{}return [`${e.slice(e.lastIndexOf("/")+1)}.js`,"index.js","main.js"].find(o=>n.has(o))}function Bd(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 Hd(){return globalThis.performance?.now()??Date.now()}function We(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let n of Object.values(e))We(n);return Object.freeze(e)}function Ar(e){return Object.freeze(Array.from(e))}async function ot(e,n,t,i){if(n.pinnedFiles!==void 0){let a=n.pinnedFiles.get(t);if(a===void 0)throw new S("NOT_FOUND");if(a.byteLength>i)throw new S("LIMIT_EXCEEDED");return new Uint8Array(a)}let o=`${n.relativePath}/${t}`,r=n.scanContext,s=e.fingerprintVerifiedFile;if(r===void 0||!r.cacheable||typeof s!="function")return hr(e,n.root,o,i);try{let a=r.priorFingerprints.get(o)??await s.call(e,r.workspaceRoot,o,i);r.candidateRealPath=a.candidateRealPath;let d=await hr(e,n.root,o,i),c=await s.call(e,r.workspaceRoot,o,i);return r.candidateRealPath=c.candidateRealPath,Mr(a,c)&&c.size===BigInt(d.byteLength)&&!Lr(c,r.scanStartedAtNs)?r.files.set(o,{relativePath:o,byteLimit:i,fingerprint:c}):r.cacheable=!1,d}catch(a){let d=q.includes(t)&&se(a)==="NOT_FOUND"&&r.directoryListings.some(l=>l.relativePath===n.relativePath&&!rt(l.key,t)),c=t===B&&se(a)==="NOT_FOUND"&&zd(r.directoryListings,n.relativePath);throw !d&&!c&&(r.cacheable=false),a}}function zd(e,n){let t=e.find(o=>o.relativePath===n);if(t===void 0)return false;if(!rt(t.key,"dist"))return true;let i=e.find(o=>o.relativePath===`${n}/dist`);return i!==void 0&&!rt(i.key,"tools.json")}function Sr(e,n){return JSON.stringify([e.realPath,n.source,n.relativePath])}async function Gd(e,n,t,i,o,r,s,a){let d=e.fingerprintVerifiedFile,c=Sr(t,i),l=o.candidates.get(c),p=i.relativePath,u;try{u=await mr(e,n,p);}catch(L){if(se(L)!=="NOT_FOUND")throw L}let f=u===void 0?void 0:{relativePath:p,key:u};if(f!==void 0&&(i.source==="apps"||i.source==="skills")&&!q.some(L=>rt(f.key,L)))return Oe(s,a)?l!==void 0&&l.candidate===void 0&&l.candidateRealPath===void 0&&l.files.length===0&&l.directoryListings.length===1&&l.directoryListings[0]?.relativePath===f.relativePath&&l.directoryListings[0]?.key===f.key&&(i.source==="apps"?l.diagnostic?.code==="MANIFEST_MISSING":l.diagnostic===void 0)&&typeof d=="function"?{memo:l}:typeof d!="function"?{}:{context:{state:o,cacheKey:c,workspaceRoot:n,scanStartedAtNs:r,directoryListings:Object.freeze([f]),priorFingerprints:new Map,files:new Map,cacheable:true}}:{timeLimitReached:true};let g=async L=>{if(L==="")return f;let y=`${i.relativePath}${L}`;try{let I=await mr(e,n,y);return I===void 0?void 0:{relativePath:y,key:I}}catch(I){if(se(I)==="NOT_FOUND")return;throw I}},E=await Promise.all(Ir.map(g)),O=await Promise.all($d.map(g));if(!Oe(s,a))return {timeLimitReached:true};let F=typeof d=="function"&&E.every(L=>L!==void 0),x=E.filter(L=>L!==void 0),N=[...x,...O.filter(L=>L!==void 0)],w=new Map,v=l!==void 0&&F,T;if(l!==void 0&&typeof d=="function"){let L=await Promise.all(l.files.map(async y=>{if(!Oe(s,a))return {kind:"time",file:y};try{let I=await d.call(e,n,y.relativePath,y.byteLimit);return {kind:"fingerprint",file:y,current:I}}catch(I){return se(I)==="NOT_FOUND"?{kind:"missing",file:y}:{kind:"error",file:y,error:I}}}));if(L.some(y=>y.kind==="time"))return {timeLimitReached:true};for(let y of L){if(y.kind==="error")throw y.error;if(y.kind==="missing"){v=false;continue}if(y.kind!=="fingerprint")continue;let{file:I,current:h}=y;w.set(I.relativePath,h),T??=h.candidateRealPath,(h.candidateRealPath!==l.candidateRealPath||!Mr(h,I.fingerprint)||Lr(h,r))&&(v=false);}}let D=l!==void 0&&l.directoryListings.length===N.length&&l.directoryListings.every((L,y)=>L.relativePath===N[y]?.relativePath&&L.key===N[y]?.key);return l!==void 0&&F&&D&&v&&T===l.candidateRealPath?{memo:l}:!F||x.length!==Ir.length?{}:{context:{state:o,cacheKey:c,workspaceRoot:n,scanStartedAtNs:r,directoryListings:Object.freeze(N),priorFingerprints:w,files:new Map,...T===void 0?{}:{candidateRealPath:T},cacheable:true}}}function rt(e,n){try{let t=JSON.parse(e);return Array.isArray(t)&&t.some(i=>Array.isArray(i)&&i[0]===n)}catch{return true}}async function mr(e,n,t){let i=Or(e);if(typeof i!="function")return;let o=await i.call(e,n,t);if(!Array.isArray(o)||o.some(s=>typeof s=="string"))return;let r=o.map(Tr);if(!r.some(s=>s===null))return JSON.stringify(r.slice().sort((s,a)=>Sn(s.name,a.name)||Sn(s.kind,a.kind)).map(s=>[s.name,s.kind]))}function Mr(e,n){return e.dev===n.dev&&e.ino===n.ino&&e.size===n.size&&e.mtimeNs===n.mtimeNs&&e.ctimeNs===n.ctimeNs}function Lr(e,n){let t=e.mtimeNs-n;return t>=-gr&&t<=gr}function hi(e){let n=e.scanContext,t=e.source==="skills"&&e.candidate===void 0&&e.diagnostic===void 0&&n?.files.size===0,i=e.source==="apps"&&e.candidate===void 0&&e.diagnostic?.code==="MANIFEST_MISSING"&&n?.files.size===0,o=t||i;if(n===void 0||!n.cacheable||n.candidateRealPath===void 0&&!o||n.files.size===0&&!o)return;let r=Object.freeze({...!o&&n.candidateRealPath!==void 0?{candidateRealPath:n.candidateRealPath}:{},directoryListings:n.directoryListings,files:Object.freeze([...n.files.values()]),...e.candidate===void 0?{}:{candidate:e.candidate},...e.diagnostic===void 0?{}:{diagnostic:e.diagnostic},...e.identity===void 0?{}:{identity:e.identity},...e.provenance===void 0?{}:{provenance:e.provenance}});n.state.candidates.set(n.cacheKey,r);}function Wd(e,n,t){let i=bi.createHash("sha256"),o=new TextEncoder().encode(ne(e)),r=s=>{let a=new Uint8Array(8);new DataView(a.buffer).setBigUint64(0,BigInt(s)),i.update(a);};return r(o.byteLength),i.update(o),r(n.byteLength),i.update(n),r(t.byteLength),i.update(t),i.digest("hex")}function Jd(e,n){let t={...e.definition,sourceHash:n},i;try{i=pe(t);}catch(r){throw r instanceof U&&r.code==="INPUT_INVALID"?new re("MANIFEST_INVALID","normalized definition is invalid"):r}let o={...t,hash:i};try{ye(o);}catch{throw new re("MANIFEST_INVALID","normalized definition is invalid")}return o}function Kd(e){return e.actions.some(n=>n.backend.type==="core"&&n.backend.handler!=="state.set")}function Xd(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 hr(e,n,t,i){let o=Xd(e);if(!o)throw new S("READ_DENIED");return kd(await o.call(e,n,t,i))}async function Yd(e,n,t){let i=Or(e);if(!i)throw new S("READ_DENIED");let o=await i.call(e,n,t);if(!Array.isArray(o))throw new S("READ_DENIED");return o.map(Tr).filter(r=>r!==null)}function qd(e){let n=[];for(let t of [e.reserved,e.builtin])t&&n.push(t);return e.builtins&&"listMcpApps"in e.builtins?n.push(_r(e.builtins)):e.builtins&&n.push(e.builtins),e.builtinCatalog&&n.push(_r(e.builtinCatalog)),n.push({...e.reservedAppIds===void 0?{}:{appIds:e.reservedAppIds},...e.reservedDefinitionIds===void 0?{}:{definitionIds:e.reservedDefinitionIds},...e.reservedToolNames===void 0?{}:{toolNames:e.reservedToolNames}}),n}function _r(e){let n=[],t=[],i=[];for(let o of e.listMcpApps())typeof o.appId=="string"&&n.push(o.appId),o.definition&&typeof o.definition.id=="string"&&t.push(o.definition.id);for(let o of e.listMcpAppTools())typeof o.name=="string"&&i.push(o.name);return {appIds:n,definitionIds:t,toolNames:i}}function he(e,n){e.diagnostic||(e.diagnostic=it(n,e.source,e.relativePath,e.identity?.pluginId));}function Zd(e,n){let t=new Set,i=new Map;for(let r of e){let s=r.identity?.pluginId;if(s===void 0)continue;let a=i.get(s)??[];a.push(r),i.set(s,a);}for(let r of i.values()){if(r.length<2)continue;let s=r.filter(d=>d.provenance!==void 0);if(s.length>0){let d=r.find(c=>n.has(c));if(d){for(let c of s)t.add(c);for(let c of r)c!==d&&c.provenance===void 0&&he(c,"RESERVED_ID");continue}for(let c of r)c.provenance===void 0&&he(c,"RESERVED_ID");if(s.length>1)for(let c of s)he(c,"DUPLICATE_ID");continue}let a=r.filter(d=>d.source==="apps");if(a.length>1){for(let d of a)he(d,"DUPLICATE_ID");for(let d of r.filter(c=>c.source==="skills"))he(d,"DUPLICATE_ID");}else for(let d of r.filter(c=>c.source==="skills"))he(d,"DUPLICATE_ID");}let o=new Map;for(let r of e){if(r.diagnostic?.code==="RESERVED_ID"||t.has(r)||r.provenance===void 0&&!n.has(r)&&i.get(r.identity?.pluginId??"")?.some(d=>d.provenance!==void 0))continue;let s=r.identity?.definitionKey;if(s===void 0)continue;let a=o.get(s)??[];a.push(r),o.set(s,a);}for(let r of o.values())if(r.length>1)for(let s of r)he(s,"DUPLICATE_ID");return t}function Qd(e,n,t){let i=new Set,o=new Set,r=new Set,s=new Set([...t.appIds,...n.productBundleReservationMetadata?.reservedAppIds??[]]),a=new Set([...t.definitionIds,...n.productBundleReservationMetadata?.reservedDefinitionIds??[]]);for(let l of qd(n)){for(let p of l.appIds??[])typeof p=="string"&&i.add(p);for(let p of l.definitionIds??[])typeof p=="string"&&o.add(p);for(let p of l.toolNames??[])typeof p=="string"&&r.add(p);}for(let l of e){let p=l.candidate;if(!p)continue;if(i.has(p.pluginId)||o.has(p.definitionId)){he(l,"RESERVED_ID");continue}[p.toolNames.read,p.toolNames.action].filter(f=>f!==void 0).some(f=>r.has(f))&&he(l,"DUPLICATE_ID");}let d=[...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)],c=new Set;for(let l of e){let p=l.candidate;if(!(!p||l.diagnostic||l.source!=="apps"||l.provenance!==void 0)&&e.filter(u=>u.source==="apps"&&u.identity?.pluginId===p.pluginId).length===1&&d.some(u=>u.pluginId===p.pluginId)&&!(a.has(p.definitionId)&&!d.some(u=>u.pluginId===p.pluginId&&u.definitionId===p.definitionId))&&!d.some(u=>u.pluginId!==p.pluginId&&u.definitionId===p.definitionId)&&!e.some(u=>u.identity?.pluginId!==p.pluginId&&u.identity?.definitionKey===`${p.definitionId}\0${p.version}`&&u.diagnostic?.code!=="RESERVED_ID"))try{Xo(p),c.add(l);}catch(u){he(l,u instanceof Ne?br(u.code):"EXEC_DENIED");}}for(let l of e){let p=l.candidate;p&&l.provenance===void 0&&!c.has(l)&&(s.has(p.pluginId)||a.has(p.definitionId))&&he(l,"RESERVED_ID");}return c}function ep(e){return [...e].sort((n,t)=>{let i=pr.indexOf(n.source)-pr.indexOf(t.source);return i!==0?i:Sn(n.relativePath,t.relativePath)})}function j(e,n,t){e.diagnostic=it(n,e.source,e.relativePath,e.identity?.pluginId,t);}async function Er(e,n,t){let i=ze(t,{mode:"local"});if(!i.ok&&i.parseFailure){j(n,yr(i.rejection.code),fr(i.rejection));return}let o=vd(i.identity);if(n.bundleIdentity===void 0)n.identity=o;else if(o?.pluginId!==n.bundleIdentity.appId||o.definitionKey!==`${n.bundleIdentity.definitionId}\0${String(n.bundleIdentity.version)}`){j(n,"BUNDLE_INTEGRITY");return}if(!i.ok&&i.builtinOnly){j(n,"RESERVED_ID");return}if(!i.ok){j(n,yr(i.rejection.code),fr(i.rejection));return}let r=i.manifest,s={pluginId:r.pluginId,definitionKey:`${r.definitionId}\0${String(r.version)}`};if(n.bundleIdentity===void 0&&(n.identity=s),r.actions.length>0)try{ii(r.actions.map(M=>({actionId:M.actionId,inputSchema:M.inputSchema})));}catch(M){if(M instanceof Ne){j(n,br(M.code));return}throw M}let a;try{a=await ot(e,n,"ui/index.html",sn);}catch(M){j(n,Je(se(M),"entry"));return}if(a.byteLength>sn){j(n,"LIMIT_EXCEEDED");return}let d;try{d=Pr(a);}catch{j(n,"ENTRY_INVALID");return}if(a.byteLength===0||d.length===0){j(n,"ENTRY_INVALID");return}let c=bi.createHash("sha256").update(a).digest("hex");if(r.entryHash!==void 0&&r.entryHash!==c){j(n,"ENTRY_INVALID");return}let l={},p,u;if(r.initialState!==void 0){try{p=await ot(e,n,"ui/state.json",65536);}catch(M){j(n,Je(se(M),"initial"));return}if(p.byteLength>65536){j(n,"LIMIT_EXCEEDED");return}try{let M=xd(p),W=r.dataPaths??[],de=Bt(M,W);l=fe(de,0,W),Ye(l);}catch{j(n,"INITIAL_STATE_INVALID");return}if(u=bi.createHash("sha256").update(p).digest("hex"),r.initialState.hash!==void 0&&r.initialState.hash!==u){j(n,"INITIAL_STATE_INVALID");return}}let f={...r,entryHash:c,...r.initialState===void 0?{}:{initialState:{path:"ui/state.json",hash:u}}},g=yn(f),E=Wd(f,a,p??new Uint8Array),O;try{O=Jd(g,E);}catch(M){if(M instanceof re){j(n,jd(M));return}throw M}let F;if(n.bundleLineage!==void 0){let M=n.bundleLineage[n.bundleLineage.length-1];if(!M){j(n,"LINEAGE_INVALID");return}let{legacy:W,...de}=M.definition,{hash:J,...be}=O;if(ne(de)!==ne(be)){j(n,"LINEAGE_STALE");return}if(W!==void 0&&(O={...O,legacy:W}),W!==void 0)try{O={...O,hash:pe(O)},ye(O);}catch{j(n,"LINEAGE_INVALID");return}F=n.bundleLineage;}if(n.bundleIdentity!==void 0&&n.bundleIdentity.appId!==r.pluginId){j(n,"BUNDLE_INTEGRITY");return}if(n.bundleIdentity!==void 0&&(n.bundleIdentity.definitionId!==O.id||n.bundleIdentity.version!==O.version||n.bundleIdentity.definitionHash!==O.hash)){j(n,"LINEAGE_STALE");return}let x=Rd(r.pluginId),N=r.actions.length===0?{read:x.read}:x,w=We(g),v=We(f),T=We(O),D=We({...g.handlers}),L=Ar(a),y=p===void 0?void 0:Ar(p),I=Object.freeze({...n.provenance===void 0?{}:{provenance:n.provenance},entry:Object.freeze({path:"ui/index.html",hash:c,bytes:L}),...y===void 0?{}:{initialState:Object.freeze({path:"ui/state.json",hash:u,bytes:y})}}),h={appId:r.pluginId,pluginId:r.pluginId,definitionId:r.definitionId,version:r.version,...i.releaseVersion===void 0?{}:{releaseVersion:i.releaseVersion},manifestFile:i.file,...i.mcpb===void 0?{}:{mcpb:We(i.mcpb)},relativePath:n.relativePath,manifest:v,normalized:w,name:r.name,description:r.description,...r.icon===void 0?{}:{icon:r.icon},...r.tone===void 0?{}:{tone:r.tone},definition:T,handlers:D,resources:I,html:d,entryBytes:L,entryHash:c,initialState:We(l),...y===void 0?{}:{initialStateBytes:y},...u===void 0?{}:{initialStateHash:u},sourceHash:E,toolNames:Object.freeze(N)},_=n.provenance===void 0?{...h,source:n.source}:{...h,provenance:n.provenance,lineage:F??[]};n.candidate=Object.freeze(_),Kd(r)&&j(n,"EXEC_DENIED");}async function Rr(e,n){let t={};for(let i of q)try{t[i]=await ot(e,n,i,262144);}catch(o){if(se(o)==="NOT_FOUND")continue;return {files:t,failure:Je(se(o),"manifest")}}if(t[G]!==void 0)try{t[B]=await ot(e,n,B,262144);}catch(i){if(se(i)!=="NOT_FOUND")return {files:t,failure:Je(se(i),"manifest")}}return {files:t}}function _i(e){return q.some(n=>e[n]!==void 0)}async function np(e,n){let{files:t,failure:i}=await Rr(e,n);if(i!==void 0){j(n,i);return}let o=t[G];return o!==void 0&&!Kt(o)&&(delete t[G],delete t[B]),_i(t)?t:void 0}function tp(e,n,t,i=Od,o=false,r=new Set){let s=ep(e),a=Zd(s,r),d=Object.freeze(s.filter(u=>u.candidate!==void 0&&u.diagnostic===void 0&&!a.has(u)).map(u=>u.candidate)),c=Object.freeze(s.filter(u=>u.diagnostic!==void 0).map(u=>u.diagnostic)),l=o?Object.freeze({...t===void 0?{}:{indexHash:t},candidates:Object.freeze(s.filter(u=>u.source==="bundled"&&u.diagnostic===void 0&&t!==void 0&&u.candidate?.provenance?.indexHash===t).map(u=>u.candidate)),diagnostics:Object.freeze(c.filter(u=>u.source==="bundled").map(u=>Object.freeze({...u}))),reservedAppIds:Object.freeze([...i.appIds]),reservedDefinitionIds:Object.freeze([...i.definitionIds])}):void 0,p={apps:d,diagnostics:c,complete:n===void 0,...n===void 0?{}:{incompleteReason:n},...t===void 0?{}:{productBundleIndexHash:t},...l===void 0?{}:{productBundleSnapshotMetadata:l}};return Object.defineProperty(p,"candidates",{configurable:false,enumerable:false,get:()=>d}),Object.freeze(p)}function ip(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 op(e,n){if(ip(e))return {fs:e,options:{}};let t=e??n??{};return {fs:t.filesystem??t.fileSystem??t.fs??ir,options:t}}async function wr(e,n,t){if(typeof e!="string"||e.length===0)throw new TypeError("workspaceRoot must be explicit");let{fs:i,options:o}=op(n,t),r=o.clock??Hd,s=r(),a=await dr(o.productBundle,i,s,r),d=r(),c=BigInt(Date.now())*1000000n,l=[],p=0,u,f=false,g,E;if(o.scanCache!==void 0&&typeof i.getRootIdentity=="function"&&typeof i.fingerprintVerifiedFile=="function")try{E=await i.getRootIdentity(e),g=Zo(o.scanCache,E),g.scanStartedAtNs=c;}catch(T){if(se(T)!=="NOT_FOUND")throw T}let O=g!==void 0&&o.productBundle===void 0&&a.packages.length===0&&a.diagnostics.length===0,F=new Set,x=true;l.push(...a.diagnostics.map(T=>({source:T.source,root:o.productBundle?.root??e,name:"",relativePath:T.relativePath,diagnostic:T})));let N=a.reservedIds;a.incomplete&&(u="time_limit");for(let T of a.packages){if(!Oe(d,r)){f=true,u="time_limit";break}let D=T.indexEntry,L=D.packageDir,y=T.files===void 0?void 0:Vd(L,T.files),I=a.indexHash===void 0?void 0:So(Object.freeze({kind:"bundled",launcher:D.launcher!==false,indexHash:a.indexHash,packageDir:L,appId:D.appId,definitionId:D.definition.id,version:D.definition.version,definitionHash:D.definition.hash,files:D.files}),y),h={source:"bundled",root:o.productBundle?.root??e,name:L.slice(5),relativePath:L,...I===void 0?{}:{provenance:I},...T.files===void 0?{}:{pinnedFiles:T.files},...T.lineage===void 0?{}:{bundleLineage:T.lineage},bundleIdentity:{appId:D.appId,definitionId:D.definition.id,version:D.definition.version,definitionHash:D.definition.hash},identity:Fd(D)};if(l.push(h),p+=1,T.failureCode!==void 0){j(h,T.failureCode);continue}if(T.files?.has(B)===true){j(h,"EXEC_DENIED",{reason:{path:"",rule:"bundled-tool-mode-unsupported",file:B}});continue}let _={};for(let M of q){let W=T.files?.get(M);W!==void 0&&(_[M]=W);}if(!_i(_)){j(h,"BUNDLE_INTEGRITY");continue}if(await Er(i,h,_),!Oe(d,r)){f=true,u="time_limit";break}}let w=[{source:"apps",directory:"apps"},{source:"skills",directory:"skills"}];e:for(let T of w){let{source:D,directory:L}=T,y;try{y=await Yd(i,e,L);}catch(h){if(se(h)==="NOT_FOUND")continue;O=false,x=false,l.push({source:D,root:e,name:"",relativePath:D,diagnostic:it(Je(se(h),"manifest"),D,D)});continue}let I=y.filter(h=>h.kind==="directory"||h.kind==="symlink").filter(h=>Cd(h.name)).map(h=>({source:D,root:e,name:h.name,relativePath:Ud(D,h.name)})).sort((h,_)=>Sn(h.relativePath,_.relativePath));for(let h of I){let _={...h};if(l.push(_),E!==void 0?F.add(Sr(E,_)):O=false,!Oe(d,r)){f=true,u="time_limit";break e}let M;if(g!==void 0&&E!==void 0){try{let J=await Gd(i,e,E,_,g,c,d,r);if(J.timeLimitReached){f=!0,u="time_limit";break e}_.scanContext=J.context,M=J.memo;}catch(J){O=false,j(_,Je(se(J),"manifest"));continue}M===void 0&&(O=false);}if(M!==void 0){if(_.candidate=M.candidate,_.diagnostic=M.diagnostic,_.identity=M.identity,D==="skills"&&M.candidate===void 0&&M.diagnostic===void 0)continue;if(p>=64){j(_,"LIMIT_EXCEEDED");continue}if(h.relativePath.split("/").length-1>2){j(_,"LIMIT_EXCEEDED");continue}if(p+=1,!Oe(d,r)){f=true,u="time_limit";break e}continue}let W;if(D==="skills"&&(W=await np(i,_),W===void 0)){_.diagnostic===void 0&&hi(_);continue}if(p>=64){j(_,"LIMIT_EXCEEDED");continue}if(h.relativePath.split("/").length-1>2){j(_,"LIMIT_EXCEEDED");continue}if(!Oe(d,r)){f=true,u="time_limit";break e}if(p+=1,W===void 0){let J=await Rr(i,_);if(J.failure!==void 0||!_i(J.files)){j(_,J.failure??Je("NOT_FOUND","manifest")),hi(_);continue}W=J.files;}if(await Er(i,_,W),hi(_),!Oe(d,r)){f=true,u="time_limit";break e}}}if(g!==void 0&&E!==void 0){let T=[...F].sort(Sn),D=g.lastCandidateKeys,L=D!==void 0&&D.length===T.length&&D.every((I,h)=>I===T[h]);if(O=O&&L,x&&!f&&u===void 0)for(let I of g.candidates.keys())try{JSON.parse(I)[0]===E.realPath&&!F.has(I)&&g.candidates.delete(I);}catch{g.candidates.delete(I);}let y=[...g.candidates.keys()].filter(I=>{try{return JSON.parse(I)[0]===E.realPath}catch{return false}});O=O&&y.length===F.size&&y.every(I=>F.has(I))&&!f&&u===void 0,g.lastCandidateScanUnchanged=O,x&&!f&&u===void 0&&(g.lastCandidateKeys=Object.freeze(T));}f&&l.push({source:"apps",root:e,name:"",relativePath:"apps",diagnostic:it("DISCOVERY_TIME_LIMIT","apps","apps")});let v=Qd(l,o,N);return tp(l,u,a.indexHash,N,o.productBundle!==void 0,v)}var Od,mi,pr,wd,Ir,$d,gr,Ur=V(()=>{m();Ve();On();Se();Xt();Fe();Kn();Yo();Hn();Qo();li();zn();gi();gi();Od=nt([]),mi="crewx_local_app_";pr=["bundled","apps","skills"],wd=new TextDecoder("utf-8",{fatal:true});Ir=["","/ui"],$d=["/dist"],gr=2000000000n;});m();Xt();m();Rt();m();var yo="SKILL.md",_c=/^---\s*\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;function Ao(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function Ec(e){return e.isDirectory()||e.isSymbolicLink()}function _o(e){try{return ee.existsSync(e)&&ee.statSync(e).isDirectory()}catch{return false}}function Yt(e){let n;try{n=ee.readFileSync(e,"utf8");}catch{return {frontmatter:{},readable:false,valid:false,hasFrontmatter:false}}let t=n.match(_c);if(!t)return {frontmatter:{},readable:true,valid:true,hasFrontmatter:false};try{let i=Wr.load(t[1]??"");if(!Ao(i))return {frontmatter:{},readable:!0,valid:!1,hasFrontmatter:!0};let o=Ao(i.metadata)?i.metadata:void 0;return {frontmatter:{...typeof i.name=="string"?{name:i.name}:{},...typeof(o?.version??i.version)=="string"?{version:o?.version??i.version}:{},...typeof i.description=="string"?{description:i.description}:{}},readable:!0,valid:!0,hasFrontmatter:!0}}catch{return {frontmatter:{},readable:true,valid:false,hasFrontmatter:true}}}function Tc(e){return [ae.join(e,yo),ae.join(e,"skill",yo)]}function Io(e,n){if(!_o(e))return null;for(let t of Tc(e)){if(!ee.existsSync(t))continue;let o=Yt(t).frontmatter;return {name:o.name??n,...o.version===void 0?{}:{version:o.version},...o.description===void 0?{}:{description:o.description},skillMdPath:t,dir:e}}return null}function go(e){try{return ee.readdirSync(e,{withFileTypes:!0}).filter(Ec)}catch{return []}}function mo(e,n,t){!e||n.has(e.name)||(n.add(e.name),t.push(e));}function Eo(e){let n=[],t=new Set;for(let i of e)if(_o(i))for(let o of go(i)){if(o.name.startsWith("@")){let r=ae.join(i,o.name);for(let s of go(r))mo(Io(ae.join(r,s.name),s.name),t,n);continue}mo(Io(ae.join(i,o.name),o.name),t,n);}return n.sort((i,o)=>i.name.localeCompare(o.name))}m();Vn();var Pc=/^[A-Za-z0-9_$.[\]"-]{0,200}$/,Nc=/^[a-z][a-z0-9-]{0,63}$/,Dc="<unknown>";function bc(e){return typeof e=="string"&&(q.includes(e)||e===B)}function To(e){if(typeof e!="object"||e===null)return;let{file:n,path:t,rule:i}=e;if(!(typeof i!="string"||!Nc.test(i)))return {...bc(n)?{file:n}:{},path:typeof t=="string"&&Pc.test(t)?t:Dc,rule:i}}function Po(e){if(!Array.isArray(e))return;let n=q.filter(t=>e.includes(t));return n.length>0?n:void 0}Ur();var sp=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/;function ct(e){let n="screenHash"in e?e.screenHash:void 0,i=("skillHash"in e?e.skillHash:void 0)??(e.relativePath!==void 0&&e.fileBytes!==void 0?ap(e.relativePath,e.fileBytes):void 0);if(n!==void 0&&i!==void 0){let o=JSON.stringify({screenHash:n,skillHash:i});return bi.createHash("sha256").update(o,"utf8").digest("hex")}if(n!==void 0)return n;if(i!==void 0)return i;throw new TypeError("App definition hash input must contain a screenHash or skill bytes")}function ap(e,n){let t=new TextEncoder().encode(dt(e)),i=cp(n),o=new Uint8Array(t.byteLength+1+i.byteLength);return o.set(t,0),o[t.byteLength]=0,o.set(i,t.byteLength+1),bi.createHash("sha256").update(o).digest("hex")}function cp(e){if(typeof e=="string")return new TextEncoder().encode(e);if(e instanceof Uint8Array)return new Uint8Array(e);if(e instanceof ArrayBuffer)return new Uint8Array(e.slice(0));if(Array.isArray(e)&&e.every(n=>Number.isInteger(n)&&n>=0&&n<=255))return Uint8Array.from(e);throw new TypeError("fileBytes must be UTF-8 text or bytes")}function dt(e){if(typeof e!="string"||e.length===0||ae.isAbsolute(e)||/[\\\u0000]/.test(e))throw new TypeError("relative path must be package-relative");let n=e.split("/").filter(t=>t.length>0&&t!==".").join("/");if(!n||n.split("/").some(t=>t===".."))throw new TypeError("relative path must stay inside the package");return n}function st(e,n){let t=new TextEncoder().encode(e),i=new TextEncoder().encode(n),o=Math.min(t.byteLength,i.byteLength);for(let r=0;r<o;r+=1){let s=t[r]-i[r];if(s!==0)return s}return t.byteLength-i.byteLength}function xr(e,n){let t=ae.relative(e,n).split(ae.sep).join("/");return !t||t===".."||t.startsWith("../")||ae.isAbsolute(t)?null:dt(t)}function dp(e){return e==="apps"||e.startsWith("apps/")?"apps":e==="skills"||e.startsWith("skills/")?"skills":e==="node_modules"||e.startsWith("node_modules/")?"node_modules":null}function vr(e){return Object.freeze({packageRoot:e})}function pp(e){return Object.freeze({id:e.definition.id,version:e.definition.version,hash:e.definition.hash,usage:e.definition.usage??Ce,...e.definition.detailPanel===void 0?{}:{detailPanel:e.definition.detailPanel},...e.definition.displayModes===void 0?{}:{displayModes:e.definition.displayModes},...e.definition.summaryProjection===void 0?{}:{summaryProjection:e.definition.summaryProjection}})}function jr(e){return {capabilities:Object.freeze([...e]),origin:"local",ownership:"unknown",shareability:"unknown",sharingAvailability:"unavailable"}}function lp(e,n){let t=e.candidate,i=t.provenance!==void 0,o=n&&!i?["screen","skill"]:["screen"],r=pp(t),s=ct(n?{screenHash:r.hash,skillHash:n.skillHash}:{screenHash:r.hash}),a=t.description||n?.skill.description||"",d=t.releaseVersion??String(t.version),c={appId:t.pluginId,name:t.name,description:a,version:d,...jr(o),definition:r,...n===void 0||i?{}:{skillName:n.skill.name},...i?{provenance:t.provenance}:{localDefinitionRef:vr(e.packageRoot)},definitionHash:s,...t.manifest.csp===void 0?{}:{connectDomains:Object.freeze([...t.manifest.csp.connectDomains])}};return {...i?{}:{packageRoot:e.packageRoot},source:i?"bundled":t.source,appId:c.appId,capabilities:o,summary:Object.freeze(c)}}function up(e){let n=fp(e.skill.name),t={appId:n,name:e.skill.name,description:e.skill.description??"",...e.skill.version===void 0?{}:{version:e.skill.version},...jr(["skill"]),skillName:e.skill.name,localDefinitionRef:vr(e.packageRoot),definitionHash:ct({skillHash:e.skillHash})};return {packageRoot:e.packageRoot,source:e.source,appId:n,capabilities:["skill"],summary:Object.freeze(t)}}function fp(e){return `skill.${e.replace(/^@/,"").replace(/\//g,".").replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,122)||"unnamed"}`}function Q(e,n,t,i,o){let r=To(o?.reason),s=Po(o?.files);return Object.freeze({code:e,source:n,relativePath:yp(t),...i===void 0?{}:{appId:i},...r===void 0?{}:{reason:r},...s===void 0?{}:{files:s}})}function yp(e){if(typeof e!="string"||e.length===0||ae.isAbsolute(e)||/[\\\u0000]/.test(e))return "<unknown>";let n=e.split("/").filter(t=>t.length>0&&t!==".").join("/");return n.split("/").some(t=>t==="..")?"<unknown>":n}function Fr(e){return Q(e.code,e.source,e.relativePath,e.pluginId,e)}function Ap(e,n){let t=xr(e,n.dir);if(!t)return {diagnostic:Q("PATH_ESCAPED","node_modules","node_modules")};let i=dp(t);if(!i)return {diagnostic:Q("PATH_ESCAPED","node_modules",t)};let o=Yt(n.skillMdPath);if(!o.readable)return {diagnostic:Q("SKILL_READ_FAILED",i,t)};if(!o.valid)return {diagnostic:Q("SKILL_INVALID",i,t)};let r=Ip(n.dir,n.skillMdPath);if(!r)return {diagnostic:Q("PATH_ESCAPED",i,t)};try{let s=new Uint8Array(ee.readFileSync(n.skillMdPath));return {skill:n,packageRoot:t,relativeSkillPath:r,skillHash:ct({relativePath:r,fileBytes:s}),source:i}}catch{return {diagnostic:Q("SKILL_READ_FAILED",i,t)}}}function Ip(e,n){let t=ae.relative(e,n).split(ae.sep).join("/");try{return dt(t)}catch{return null}}function gp(e){if(!sp.test(e.appId))return {diagnostic:Q("BUILTIN_INVALID","builtin",`builtin/${e.appId||"unknown"}`)};let n=e.definition===void 0?void 0:{id:e.definition.id,version:e.definition.version,hash:e.definition.hash,usage:e.definition.usage??Ce,...e.definition.detailPanel===void 0?{}:{detailPanel:e.definition.detailPanel},...e.definition.displayModes===void 0?{}:{displayModes:e.definition.displayModes},...e.definition.summaryProjection===void 0?{}:{summaryProjection:e.definition.summaryProjection}},t=n?.hash??bi.createHash("sha256").update(JSON.stringify({appId:e.appId,name:e.name,description:e.description}),"utf8").digest("hex"),i={appId:e.appId,name:e.name,description:e.description,...n===void 0?{}:{version:String(n.version),definition:n},capabilities:["screen"],origin:"builtin",ownership:"unknown",shareability:"forbidden",sharingAvailability:"unavailable",definitionHash:t};return {source:"builtin",appId:e.appId,summary:Object.freeze(i)}}function mp(e){return e.builtinCatalog}function hp(e){let n=e.packageRoot??e.relativePath??e.packageRootPath;if(n===void 0)return null;try{return dt(n)}catch{return null}}function _p(e){let n=e.marketplaceContentId;return typeof n=="string"&&n.length>0?n:void 0}function Ep(e,n,t){let i=n.installed??[],o=new Map;for(let s of i){let a=hp(s);if(!a){t.push(Q("INSTALLED_IDENTITY_MISMATCH","installed","installed"));continue}let d=o.get(a);if(d&&JSON.stringify(d)!==JSON.stringify(s)){t.push(Q("INSTALLED_IDENTITY_MISMATCH","installed",a));continue}o.set(a,s);}let r=new Map;for(let s of e)s.packageRoot!==void 0&&r.set(s.packageRoot,s);for(let[s,a]of o){let d=r.get(s);if(!d){t.push(Q("INSTALLED_MISSING","installed",s,a.appId));continue}let c=_p(a);if(!c){t.push(Q("INSTALLED_CONTENT_ID_MISSING","installed",s,a.appId));continue}if(a.appId!==void 0&&a.appId!==d.appId||a.definitionHash!==void 0&&a.definitionHash!==d.summary.definitionHash){t.push(Q("INSTALLED_IDENTITY_MISMATCH","installed",s,a.appId));continue}let l={...d.summary,origin:"installed",...a.slug===void 0?{}:{slug:a.slug},marketplaceContentId:c},p=e.indexOf(d);p>=0&&(e[p]={...d,summary:Object.freeze(l)});}}function Tp(e,n){let t=new Map;for(let o of e){let r=t.get(o.appId)??[];r.push(o),t.set(o.appId,r);}let i=new Set;for(let o of t.values()){if(o.length<2)continue;let r=o.some(s=>s.source==="builtin")?"builtin":o.some(s=>s.source==="bundled")?"bundled":void 0;if(r==="bundled"){let s=o.filter(a=>a.source==="apps"&&a.summary.definition!==void 0);if(s.length===1){for(let a of o)a.source==="bundled"?i.add(a):a!==s[0]&&(i.add(a),n.push(Q("RESERVED_ID",a.source,at(a),a.appId)));continue}}if(r!==void 0){let s=o.filter(a=>a.source===r);for(let a of o.filter(d=>d.source!==r))i.add(a),n.push(Q("RESERVED_ID",a.source,at(a),a.appId));if(s.length>1)for(let a of s)i.add(a),n.push(Q("DUPLICATE_ID",a.source,at(a),a.appId));continue}for(let s of o)i.add(s),n.push(Q("DUPLICATE_ID",s.source,at(s),s.appId));}return e.filter(o=>!i.has(o))}function at(e){return e.packageRoot??e.summary.provenance?.packageDir??`builtin/${e.appId}`}function Pp(e,n){return e.filter(t=>!(t.code==="MANIFEST_MISSING"&&n.has(t.relativePath))).map(Fr)}function Np(e){return e.filesystem}function Dp(e,n){let t=Np(e),i=e.registeredProductBundle;return {...t===void 0?{}:{filesystem:t},...e.productBundle===void 0?{}:{productBundle:e.productBundle},...n===void 0?{}:{builtinCatalog:n},...i===void 0?{}:{productBundleReservationMetadata:i}}}async function Vr(e,n={}){if(typeof e!="string"||e.length===0)throw new TypeError("workspaceRoot must be explicit");if(n.productBundle!==void 0&&n.registeredProductBundle!==void 0)throw new TypeError("registeredProductBundle cannot be combined with product bundle discovery");let t=mp(n),i=await wr(e,Dp(n,t)),o=n.registeredProductBundle??i.productBundleSnapshotMetadata,r=[ae.join(e,"skills"),ae.join(e,"node_modules"),ae.join(e,"apps")],s=[],a=[],d=[],c=new Set;for(let I of r)for(let h of Eo([I])){let _=xr(e,h.dir);(_===null||!c.has(_))&&(d.push(h),_!==null&&c.add(_));}for(let I of d){let h=Ap(e,I);"diagnostic"in h?s.push(h.diagnostic):a.push(h);}let l=new Map,p=n.registeredProductBundle?.indexHash,u=(n.registeredProductBundle?.candidates??[]).filter(I=>p!==void 0&&I.provenance?.indexHash===p),f=[...new Set([...i.apps??i.candidates??[],...i.productBundleSnapshotMetadata?.candidates??[]]),...u],g=new Set(u),E=new Set(p===void 0?[]:(t?.listMcpApps()??[]).filter(I=>I.provenance?.indexHash===p).map(I=>I.appId));for(let I of f){if(g.has(I)&&I.provenance?.indexHash===p&&E.has(I.appId))continue;let h=I.provenance===void 0?`workspace\0${I.relativePath}`:`bundled\0${I.provenance.indexHash}\0${I.provenance.packageDir}`;l.set(h,{candidate:I,packageRoot:I.relativePath});}let O=new Map(a.map(I=>[I.packageRoot,I])),F=[];for(let I of l.values()){let h=I.candidate.provenance===void 0?O.get(I.packageRoot):void 0,_=lp(I,h);F.push({..._.packageRoot===void 0?{}:{packageRoot:_.packageRoot},source:_.source,appId:_.appId,summary:_.summary});}let x=new Set([...l.values()].filter(I=>I.candidate.provenance===void 0).map(I=>I.packageRoot)),N=o===void 0?new Set:new Set(i.diagnostics.filter(I=>I.code==="RESERVED_ID"&&I.source!=="bundled").map(I=>I.relativePath)),w=new Set(o?.reservedAppIds??[]);for(let I of a){let h=up(I);if(!(x.has(I.packageRoot)||N.has(I.packageRoot))){if(w.has(h.appId)){s.push(Q("RESERVED_ID",I.source,I.packageRoot,h.appId));continue}F.push({packageRoot:h.packageRoot,source:h.source,appId:h.appId,summary:h.summary});}}let v=[...Pp(i.diagnostics,new Set(a.map(I=>I.packageRoot))),...s,...n.registeredProductBundle?.diagnostics.filter(I=>I.source==="bundled").map(Fr)??[]],T=[];if(t)for(let I of t.listMcpApps()){let h=gp(I);"diagnostic"in h?v.push(h.diagnostic):T.push(h);}let D=Tp([...F,...T],v);Ep(D,n,v);let L=D.map(I=>I.summary).sort((I,h)=>st(I.appId,h.appId)),y=[...v].sort((I,h)=>st(I.relativePath,h.relativePath)||st(I.code,h.code)||st(I.appId??"",h.appId??""));return Object.freeze({items:Object.freeze(L),diagnostics:Object.freeze(y)})}m();m();m();function bp(e){let n=o=>o.replace(/[.+^${}()|[\]\\]/g,"\\$&"),i=e.split("/").map(o=>o==="**"?".*":o.split("*").map(n).join("[^/]*"));return new RegExp(`^${i.join("\\/")}$`)}function dn(e,n){try{return bp(n).test(e)}catch{return false}}function pt(e,...n){let t=e.split("/");if(t.length<n.length)return false;let i=t.length-n.length;return n.every((o,r)=>dn(t[i+r],o))}function Sp(e,n){return e.split("/").some(t=>dn(t,n))}var Br=[{label:".env*",test:e=>dn(e,".env*")},{label:".git/",test:(e,n,t)=>t&&e===".git"},{label:"memory/",test:(e,n,t)=>t&&e==="memory"},{label:"*.key",test:e=>dn(e,"*.key")},{label:"*.pem",test:e=>dn(e,"*.pem")},{label:"auth.json",test:e=>e==="auth.json"},{label:"node_modules/",test:(e,n,t)=>t&&e==="node_modules"},{label:"conversations/",test:(e,n,t)=>t&&e==="conversations"},{label:".crewx/threads/",test:(e,n,t)=>t&&pt(n,".crewx","threads")},{label:".crewx/crewx.db",test:(e,n,t)=>!t&&pt(n,".crewx","crewx.db")},{label:".crewx/*.log",test:(e,n,t)=>!t&&pt(n,".crewx","*.log")},{label:".crewx/publish/",test:(e,n,t)=>t&&pt(n,".crewx","publish")},{label:".crewx/",test:(e,n)=>Sp(n,".crewx")}];function lt(e,n,t){for(let i of Br)if(i.test(e,n,t))return i.label;return null}function Ni(e){let n=[],t=[];function i(o,r,s){let a;try{a=ee__namespace.readdirSync(o,{withFileTypes:!0});}catch{return}a.sort((d,c)=>d.name.localeCompare(c.name));for(let d of a){let c=r?`${r}/${d.name}`:d.name,l=ae__namespace.join(o,d.name);if(d.isSymbolicLink()){let p;try{p=ee__namespace.statSync(l);}catch{t.push({path:c,rule:"symlink"});continue}if(p.isDirectory()){t.push({path:c,rule:s??"symlink-dir"});continue}let u=s??lt(d.name,c,false);u?t.push({path:c,rule:u}):t.push({path:c,rule:"symlink"});continue}if(d.isDirectory()){let p=s??lt(d.name,c,true);i(l,c,p);continue}if(d.isFile()){let p=s??lt(d.name,c,false);p?t.push({path:c,rule:p}):n.push(c);}}}return i(e,"",null),n.sort(),t.sort((o,r)=>o.path<r.path?-1:o.path>r.path?1:0),{included:n,excluded:t}}m();var Mp=[{rule:"token-prefix",regex:/\b(?:sk-|ghp_|xoxb-)[A-Za-z0-9_-]{10,}/},{rule:"private-key",regex:/-----BEGIN [A-Z ]*PRIVATE KEY-----/},{rule:"aws-access-key",regex:/\bAKIA[0-9A-Z]{16}\b/}];function Lp(e){return e.includes(0)}function Di(e,n,t){let i=[];for(let o of n){let r=ae__namespace.join(e,o),s;try{let d=t?.get(o);s=d===void 0?ee__namespace.readFileSync(r):Buffer.from(d);}catch{continue}if(Lp(s))continue;s.toString("utf8").split(/\r\n|\r|\n/).forEach((d,c)=>{for(let{rule:l,regex:p}of Mp)p.test(d)&&i.push({path:o,line:c+1,rule:l});});}return i}m();m();var Re=class extends Error{constructor(t,i){super(`publish: [${t}]${i?` ${i}`:""}`);this.code=t;}code;name="PublishError"};function P(e,n){return new Re(e,n)}var Gr=/^[a-z0-9-]+$/,Op=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/,Rp=/^[A-Za-z_][A-Za-z0-9_]*$/;function wp(e){let n=ae__namespace.join(e,"crewx.yaml");if(!ee__namespace.existsSync(n))return {};let t;try{t=Wr__namespace.load(ee__namespace.readFileSync(n,"utf8"));}catch{return {}}if(!t||typeof t!="object")return {};let i=t.metadata;if(!i||typeof i!="object")return {};let o=i;return {name:typeof o.name=="string"?o.name:void 0,version:typeof o.version=="string"?o.version:void 0,description:typeof o.description=="string"?o.description:void 0,requiredEnv:o.requiredEnv,crewxMinVersion:typeof o.crewxMinVersion=="string"?o.crewxMinVersion:void 0}}function Up(e){return bi__namespace.createHash("sha256").update(e).digest("hex")}function Jr(e){let n;try{n=ee__namespace.lstatSync(e);}catch{throw P("PACKAGE_FILE_INVALID",`file is not readable: ${ae__namespace.basename(e)}`)}if(n.isSymbolicLink())throw P("PACKAGE_SYMLINK","symlink content is not publishable");if(!n.isFile())throw P("PACKAGE_FILE_INVALID","only regular files are publishable");return bi__namespace.createHash("sha256").update(new Uint8Array(ee__namespace.readFileSync(e))).digest("hex")}function Cp(e,n){let t=new TextEncoder().encode(e),i=new TextEncoder().encode(n),o=Math.min(t.byteLength,i.byteLength);for(let r=0;r<o;r+=1){let s=t[r]-i[r];if(s!==0)return s}return t.byteLength-i.byteLength}function Kr(e){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||ae__namespace.posix.isAbsolute(e)||e.split("/").some(n=>n===".."||n.length===0))throw P("PACKAGE_PATH_TRAVERSAL","manifest file path must be a non-empty POSIX relative path")}function kp(e){if(!/^(?:apps|skills)\/[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(e))throw P("APP_PACKAGE_ROOT_INVALID","packageRoot must be apps/<safe-id> or skills/<safe-id>")}function Xr(e){if(!Op.test(e))throw new Error(`publish: invalid version "${e}" \u2014 must be semver (e.g. 1.0.0)`)}function Yr(e,n,t={}){let i=wp(e),o=i.name??ae__namespace.basename(e);if(!Gr.test(o))throw new Error(`publish: invalid name "${o}" \u2014 must match ${Gr} (lowercase letters, numbers, hyphen only)`);let r=t.version??i.version;if(!r)throw new Error("publish: version is required \u2014 set crewx.yaml metadata.version or pass opts.version");Xr(r);let s=Array.isArray(i.requiredEnv)?i.requiredEnv:[],a=[];for(let l of s){if(typeof l!="string"||!Rp.test(l))throw new Error(`publish: requiredEnv must contain names only (no values), got "${String(l)}"`);a.push(l);}let d=n.map(l=>(Kr(l),{path:l,sha256:Jr(ae__namespace.join(e,l))})).sort((l,p)=>l.path<p.path?-1:l.path>p.path?1:0),c={name:o,version:r,type:"template",description:i.description??"",files:d,requiredEnv:a};return i.crewxMinVersion&&(c.crewxMinVersion=i.crewxMinVersion),c}function xp(e){let n=e.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"");if(!n)throw P("APP_PACKAGE_ROOT_INVALID","appId cannot produce a marketplace name");return n}function qr(e,n){if(kp(n.packageRoot),!n.version)throw new Error("publish: version is required for App publishing \u2014 pass opts.version");if(Xr(n.version),typeof n.description!="string")throw new Error("publish: App description must be a string");let t=[...new Set(n.capabilities)].sort();if(t.length===0||t.some(s=>s!=="screen"&&s!=="skill"))throw new Error("publish: App capabilities must contain screen or skill");let i=`${n.packageRoot}/`;if(t.includes("screen")){if(typeof n.definitionId!="string"||n.definitionId.length===0)throw P("APP_UI_MANIFEST_INVALID","screen App manifests require definitionId");let s=n.includedFiles.includes(`${i}manifest.json`),a=n.includedFiles.includes(`${i}ui-plugin.json`);if(!s&&!a)throw P("APP_UI_MANIFEST_INVALID","screen App is missing manifest.json or ui-plugin.json");if(s&&!a)throw P("APP_UI_MANIFEST_INVALID","a manifest.json App must also ship a generated ui-plugin.json");if(!n.includedFiles.includes(`${i}ui/index.html`))throw P("APP_UI_MANIFEST_INVALID","screen App is missing ui/index.html")}if(t.includes("skill")&&!n.includedFiles.includes(`${i}SKILL.md`))throw P("APP_SKILL_MISSING","skill capability requires package-root SKILL.md");let o=new Set,r=n.includedFiles.map(s=>{if(Kr(s),!s.startsWith(i))throw P("PACKAGE_PATH_TRAVERSAL","App manifest file is outside packageRoot");let a=n.generatedFiles?.get(s);return a!==void 0&&o.add(s),{path:s,sha256:a===void 0?Jr(ae__namespace.join(e,s)):Up(a),...a===void 0?{}:{generated:true}}}).sort((s,a)=>Cp(s.path,a.path));if(o.size>0&&(o.size!==1||!o.has(`${i}ui-plugin.json`)))throw new Error("publish: only the generated ui-plugin.json may be present in an App package");return {manifestVersion:1,name:xp(n.appId),version:n.version,type:"app",description:n.description,appId:n.appId,...n.definitionId===void 0?{}:{definitionId:n.definitionId},...n.definitionHash===void 0?{}:{definitionHash:n.definitionHash},capabilities:t,packageRoot:n.packageRoot,files:r,requiredEnv:[]}}m();function Zr(e){return bi__namespace.createHash("sha256").update(e).digest("hex")}function is(e,n){if(typeof n!="string"||n.length===0||n.includes("\\")||n.includes("\0")||ae__namespace.posix.isAbsolute(n)||n.split("/").some(o=>o===".."||o.length===0))throw P("PACKAGE_PATH_TRAVERSAL","archive paths must be non-empty POSIX relative paths");let t=ae__namespace.resolve(e),i=ae__namespace.resolve(t,...n.split("/"));if(i!==t&&!i.startsWith(`${t}${ae__namespace.sep}`))throw P("PACKAGE_PATH_TRAVERSAL","archive path escaped its root");return i}function Qr(e,n){let t=is(e,n),i;try{i=ee__namespace.lstatSync(t);}catch{throw P("PACKAGE_FILE_INVALID","manifest file is missing")}if(i.isSymbolicLink())throw P("PACKAGE_SYMLINK","symlink content is not publishable");if(!i.isFile())throw P("PACKAGE_FILE_INVALID","only regular files are publishable");return new Uint8Array(ee__namespace.readFileSync(t))}async function os(e,n,t={}){let i=ae__namespace.join(e,".crewx","publish");ee__namespace.mkdirSync(i,{recursive:true});let o=ae__namespace.join(i,`${n.name}-${n.version}.tgz`),r=ae__namespace.join(i,`.${n.name}-${n.version}.${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}.tmp.tgz`),s=ee__namespace.mkdtempSync(ae__namespace.join(es__namespace.tmpdir(),"crewx-publish-"));try{let a=new Set,d=[];for(let c of n.files){if(a.has(c.path))throw P("PACKAGE_PATH_TRAVERSAL","manifest contains duplicate file paths");a.add(c.path);let l=t.generatedFiles?.get(c.path);if(c.generated===!0&&l===void 0)throw P("PACKAGE_GENERATED_FILE_MISSING","generated manifest file bytes are missing");if(t.sourceFileHashes?.has(c.path)){let f=Qr(e,c.path);if(t.sourceFileHashes.get(c.path)!==Zr(f))throw P("PACKAGE_STAGED_BYTES_MISMATCH","workspace source changed before staging")}let p=l??Qr(e,c.path);if(Zr(p)!==c.sha256)throw P("PACKAGE_STAGED_BYTES_MISMATCH",`staged bytes differ for ${c.path}`);let u=is(s,c.path);ee__namespace.mkdirSync(ae__namespace.dirname(u),{recursive:!0}),ee__namespace.writeFileSync(u,new Uint8Array(p)),d.push(c.path);}ee__namespace.writeFileSync(ae__namespace.join(s,"manifest.json"),JSON.stringify(n,null,2)),await ts__namespace.create({gzip:!0,file:r,cwd:s,portable:!0,noMtime:!0},["manifest.json",...d]),ee__namespace.renameSync(r,o);}finally{try{ee__namespace.rmSync(r,{force:!0});}catch{}ee__namespace.rmSync(s,{recursive:true,force:true});}return o}m();m();var pn="/api/v1";var Fp=201,Vp=200,Bp=409,Si=401,rs={APP_NAME_CONFLICT:"APP_NAME_CONFLICT",CONTENT_SUSPENDED:"PUBLISH_CONTENT_SUSPENDED",CONTENT_REJECTED:"CONTENT_REJECTED",APP_VERSION_MUST_INCREASE:"APP_VERSION_MUST_INCREASE",APP_VERSION_INVALID:"APP_VERSION_INVALID"};function Hp(){return process.env.WI013_FAKE_UPLOAD==="1"}function zp(e){let n=zlib.gunzipSync(new Uint8Array(e)),t=zlib.gzipSync(new Uint8Array(n),{level:1});if(Buffer.compare(new Uint8Array(t),new Uint8Array(e))===0)throw new Error("publish: [E_MALFORMED] Re-gzipped upload bytes are identical to the original \u2014 tamper is a no-op");return t}function $p(e){return e.replace(/\/+$/,"")}async function Mn(e){try{return await e.json()}catch{return null}}function ss(e,n,t){let i=e;if(!i||i.success!==true||i.data===void 0)throw new Error(`publish: [E_MALFORMED] ${n} response envelope is malformed (expected { success: true, data }) \u2014 HTTP ${t}`);return i.data}function Gp(e){if(!e||typeof e!="object"||Array.isArray(e))return;let n=e;if(typeof n.contentId=="string"&&n.contentId.length>0)return n.contentId;if(!n.data||typeof n.data!="object"||Array.isArray(n.data))return;let t=n.data;return typeof t.contentId=="string"&&t.contentId.length>0?t.contentId:void 0}function Wp(e){if(!e||typeof e!="object"||Array.isArray(e))return;let n=e;if(typeof n.slug=="string"&&n.slug.length>0)return n.slug;if(!n.data||typeof n.data!="object"||Array.isArray(n.data))return;let t=n.data;return typeof t.slug=="string"&&t.slug.length>0?t.slug:void 0}function as(e,n){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e,i=t.data&&typeof t.data=="object"&&!Array.isArray(t.data)?t.data:void 0,o=[t.code,t.message,i?.code,i?.message];for(let r of o){if(typeof r!="string"||!Object.prototype.hasOwnProperty.call(rs,r))continue;let s=r,a=s==="APP_NAME_CONFLICT"?`marketplace name is already in use: ${n}`:void 0;return P(rs[s],a)}}async function Jp(e){if(!e.baseUrl.trim())throw new Error("publish: [E_ENV_MISSING] Marketplace base URL is required");if(!e.accessToken.trim())throw new Error("publish: [E_AUTH_EXPIRED] A valid bearer token is required");let n=$p(e.baseUrl),t=e.accessPolicy??"private",i=e.manifest.name,o=e.manifest.type==="app"?e.manifest:void 0,r=o!==void 0,s=o?.appId,a;try{a=await fetch(`${n}${pn}/publisher/items`,{method:"POST",headers:{Authorization:`Bearer ${e.accessToken}`,"Content-Type":"application/json"},body:JSON.stringify({slug:i,displayName:i,description:e.manifest.description,type:e.manifest.type,version:e.manifest.version,accessPolicy:t,...s===void 0?{}:{appId:s}})});}catch{throw new Error("publish: [E_NETWORK] Submit request failed (network)")}let d=await Mn(a),c=Gp(d),l=Wp(d),p=r&&l!==void 0?l:i,u;if(a.status===Fp)u="created";else if(r&&a.status===Vp){if(c===void 0)throw P("PUBLISH_CONTENT_ID_MISSING","App republish did not return an opaque contentId");u="existing";}else if(a.status===Bp){if(r)throw as(d,i)??P("APP_NAME_CONFLICT",`marketplace name is already in use: ${i}`);u="existing";}else throw a.status===Si?new Error("publish: [E_AUTH_EXPIRED] Authentication is expired or missing \u2014 please log in again (HTTP 401)"):new Error(`publish: [E_HTTP] Submit request failed \u2014 HTTP ${a.status}`);let f="not-needed",g=null;if(u==="existing"&&!r){let D;try{D=await fetch(`${n}${pn}/publisher/items`,{method:"GET",headers:{Authorization:`Bearer ${e.accessToken}`}});}catch{throw new Error("publish: [E_NETWORK] Publisher items request failed (network)")}let L=await Mn(D);if(D.status!==200)throw new Error(`publish: [E_HTTP] Publisher items request failed \u2014 HTTP ${D.status}`);let I=ss(L,"publisher items",D.status)?.items;if(!Array.isArray(I))throw new Error(`publish: [E_MALFORMED] Publisher items response is malformed (expected data.items[]) \u2014 HTTP ${D.status}`);let h=I.find(_=>!_||typeof _!="object"?false:_.slug===i);if(!h||typeof h.version!="string")throw new Error(`publish: [E_MALFORMED] Publisher items response does not contain slug "${i}" \u2014 HTTP ${D.status}`);if(g=h.version,g!==e.manifest.version){let _;try{_=await fetch(`${n}${pn}/publisher/items/${encodeURIComponent(i)}`,{method:"PUT",headers:{Authorization:`Bearer ${e.accessToken}`,"Content-Type":"application/json"},body:JSON.stringify({version:e.manifest.version})});}catch{throw new Error("publish: [E_NETWORK] Version update request failed (network)")}if(!_.ok)throw await Mn(_),_.status===Si?new Error(`publish: [E_AUTH_EXPIRED] Authentication is expired or missing \u2014 please log in again (HTTP ${_.status})`):_.status===403?new Error(`publish: [E_FORBIDDEN] Version update is forbidden; only the item owner can update an existing item (HTTP ${_.status})`):new Error(`publish: [E_HTTP] Version update failed \u2014 HTTP ${_.status}`);f="applied";}}let E=ee__namespace.readFileSync(e.tgzPath),O=Hp()?zp(E):E,F=new FormData;F.set("archive",new Blob([new Uint8Array(O)],{type:"application/gzip"}),`${p}-${e.manifest.version}.tgz`);let x=r&&c!==void 0?c:i,N;try{N=await fetch(`${n}${pn}/publisher/items/${encodeURIComponent(x)}/upload`,{method:"POST",headers:{Authorization:`Bearer ${e.accessToken}`},body:F});}catch{throw new Error("publish: [E_NETWORK] Upload request failed (network)")}if(N.status===Si)throw new Error("publish: [E_AUTH_EXPIRED] Authentication is expired or missing \u2014 please log in again (HTTP 401)");if(!N.ok){let D=await Mn(N);if(r){let L=as(D,p);if(L)throw L}throw new Error(`publish: [E_HTTP] Upload request failed \u2014 HTTP ${N.status}`)}let w=await Mn(N),v=ss(w,"upload",N.status),T=typeof v.contentId=="string"&&v.contentId.length>0?v.contentId:c;if(r&&T===void 0)throw P("PUBLISH_CONTENT_ID_MISSING","App upload did not return an opaque contentId");return {slug:p,version:e.manifest.version,...T===void 0?{}:{contentId:T},artifactChecksum:v.artifactChecksum,artifactSizeBytes:v.artifactSizeBytes,submitOutcome:u,versionUpdate:f,serverVersionBefore:g}}var Kp=1e4,Xp=100*1024*1024;function Mi(e){return bi__namespace.createHash("sha256").update(e).digest("hex")}function Yp(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function Ln(e,n){if(!n||n.includes("\\")||n.includes("\0")||ae__namespace.posix.isAbsolute(n)||n.split("/").some(r=>r===".."||r.length===0))throw P("PACKAGE_PATH_TRAVERSAL","workspace file path is not a safe relative path");let t=ae__namespace.resolve(e,...n.split("/")),i=ae__namespace.resolve(e);if(t!==i&&!t.startsWith(`${i}${ae__namespace.sep}`))throw P("PACKAGE_PATH_TRAVERSAL","workspace file path escaped the workspace root");let o;try{o=ee__namespace.lstatSync(t);}catch{throw P("PACKAGE_FILE_INVALID",`workspace file is missing: ${n}`)}if(o.isSymbolicLink())throw P("PACKAGE_SYMLINK",`symlink is not publishable: ${n}`);if(!o.isFile())throw P("PACKAGE_FILE_INVALID",`not a regular file: ${n}`);return new Uint8Array(ee__namespace.readFileSync(t))}function ft(e,n){return e===n||e.startsWith(`${n}/`)}function qp(e,n){return e.path<n.path?-1:e.path>n.path?1:e.rule.localeCompare(n.rule)}function ds(e,n,t){let i=e??n;if(!Number.isSafeInteger(i)||i<=0)throw new Re("PACKAGE_SIZE_LIMIT",`${t} must be a positive integer`);return i}function ls(e,n,t,i){let o=ds(t.maxFileCount??t.maxFiles,Kp,"max file count"),r=ds(t.maxTotalBytes??t.maxBytes,Xp,"max total bytes");if(n.length>o)throw new Re("PACKAGE_SIZE_LIMIT",`package exceeds file count limit (${o})`);let s=0;for(let a of n){let d=i?.get(a);if(d!==void 0?s+=d.byteLength:s+=Ln(e,a).byteLength,s>r)throw new Re("PACKAGE_SIZE_LIMIT",`package exceeds byte limit (${r})`)}}function Zp(e){return e.appId!==void 0||e.expectedDefinitionHash!==void 0}function Qp(e){let n=e.appId!==void 0,t=e.expectedDefinitionHash!==void 0;if(!n&&t)throw P("APP_ID_REQUIRED","appId is required with expectedDefinitionHash");if(n&&!t)throw P("APP_DEFINITION_HASH_REQUIRED","expectedDefinitionHash is required with appId");if(!n||!t)throw P("APP_ID_REQUIRED")}function el(e,n){let t=e.filter(i=>i.appId===n);if(t.length===0)throw P("APP_NOT_FOUND",`no publishable App matches ${n}`);if(t.length!==1)throw P("APP_AMBIGUOUS",`more than one App matches ${n}`);return t[0]}function nl(e){let n=e.localDefinitionRef?.packageRoot;if(!n||!/^(?:apps|skills)\/[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(n))throw P("APP_PACKAGE_ROOT_INVALID","selected App is not rooted in apps/<safe-id> or skills/<safe-id>");return n}function tl(e,n){let t=[];for(let i of e.excluded)t.push(ft(i.path,n)?i:{path:i.path,rule:"out-of-app-scope"});for(let i of e.included)ft(i,n)||t.push({path:i,rule:"out-of-app-scope"});return t.sort(qp)}function Li(e){let{path:n,rule:t}=e.reason;return `${e.code} at ${n===""?"<file>":n} (${t})`+(e.files.length>0?` [${e.files.join(", ")}]`:"")}function il(e,n,t){let i=ze({[ce]:t},{mode:"published"});if(!i.ok)throw P("APP_UI_MANIFEST_INVALID",`generated ${ce} does not read: ${Li(i.rejection)}`);if(on(i.manifest)!==on(n))throw P("APP_UI_MANIFEST_INVALID",`generated ${ce} normalizes to a different definition hash than the source`);let o=e[G];if(o===void 0)return;let r=e[B],s=ze({[G]:o,[ce]:t,...r===void 0?{}:{[B]:r}},{mode:"local"});if(!s.ok)throw P("APP_UI_MANIFEST_INVALID",Li(s.rejection))}function ol(e,n,t,i){let o={};for(let f of q){let g=`${t}/${f}`;i.includes(g)&&(o[f]=Ln(e,g));}let r=`${t}/${B}`;if(o[G]!==void 0&&i.includes(r)&&(o[B]=Ln(e,r)),Object.keys(o).length===0)throw P("APP_UI_MANIFEST_INVALID","selected screen App has no package manifest.json or ui-plugin.json");let s=ze(o,{mode:"local"});if(!s.ok)throw P("APP_UI_MANIFEST_INVALID",Li(s.rejection));if(s.manifest.pluginId!==n.appId)throw P("APP_DEFINITION_CONFLICT",`${s.file} identity no longer matches the selected App`);let a=o[ce],d=a===void 0?void 0:Mi(a),c=`${t}/ui/index.html`;if(!i.includes(c))throw P("APP_UI_MANIFEST_INVALID","screen entry is outside package scope");let l=Mi(Ln(e,c)),p=JSON.parse(JSON.stringify(s.v2Input));if(p.entryHash=l,Object.prototype.hasOwnProperty.call(p,"initialState")){let f=p.initialState;if(!Yp(f)||f.path!=="ui/state.json")throw P("APP_INITIAL_STATE_OUT_OF_SCOPE","initialState must reference ui/state.json inside the package");let g=`${t}/ui/state.json`;if(!i.includes(g))throw P("APP_INITIAL_STATE_OUT_OF_SCOPE","initialState reference is outside the selected package");let E=Ln(e,g);p.initialState={...f,hash:Mi(E)};}let u;try{let f=He(p,{mode:"published"});u=new Uint8Array(Buffer.from(JSON.stringify(f),"utf8"));}catch(f){throw f instanceof re?P("APP_UI_MANIFEST_INVALID",f.code):P("APP_UI_MANIFEST_INVALID")}return il(o,s.manifest,u),{bytes:u,...d===void 0?{}:{legacySourceHash:d}}}async function rl(e,n){let{included:t,excluded:i}=Ni(e);ls(e,t,n);let o=Yr(e,t,{version:n.version}),r=Di(e,t);return {plan:{manifest:o,included:t,excluded:i,secretFindings:r},archiveOptions:{}}}async function sl(e,n){Qp(n);let t=await Vr(e),i=el(t.items,n.appId);if(i.definitionHash!==n.expectedDefinitionHash)throw P("APP_DEFINITION_CONFLICT",`definitionHash changed for ${n.appId}`);let o=nl(i),r=Ni(e);if(r.excluded.some(f=>ft(f.path,o)&&(f.rule==="symlink"||f.rule==="symlink-dir")))throw P("PACKAGE_SYMLINK","selected App package contains a symlink");let s=r.included.filter(f=>ft(f,o)),a=tl(r,o),d=new Map,c=new Map;if(i.capabilities.includes("screen")){let f=ol(e,i,o,s),g=`${o}/${ce}`;d.set(g,f.bytes),f.legacySourceHash!==void 0?c.set(g,f.legacySourceHash):(s.push(g),s.sort());}if(i.capabilities.includes("skill")&&!s.includes(`${o}/SKILL.md`))throw P("APP_SKILL_MISSING","skill capability requires package-root SKILL.md");ls(e,s,n,d);let l={appId:i.appId,version:n.version??"",description:i.description,capabilities:i.capabilities,packageRoot:o,...i.definition?.id===void 0?{}:{definitionId:i.definition.id},definitionHash:i.definitionHash,includedFiles:s,generatedFiles:d},p=qr(e,l),u=Di(e,s,d);return {plan:{manifest:p,included:s,excluded:a,secretFindings:u},archiveOptions:{generatedFiles:d,sourceFileHashes:c}}}async function us(e,n){let t=ae__namespace.resolve(e);if(Zp(n))return sl(t,n);if(n.expectedDefinitionHash!==void 0)throw P("APP_ID_REQUIRED");return rl(t,n)}async function Qy(e,n={}){return (await us(e,n)).plan}function al(e){let n=e.map(t=>`${t.path}:${t.line} (${t.rule})`).join(", ");throw new Re("PUBLISH_SECRET_FINDINGS",`aborted \u2014 secret findings must be resolved before packing: ${n}`)}async function fs(e,n={}){let t=ae__namespace.resolve(e),i=await us(t,n);i.plan.secretFindings.length>0&&al(i.plan.secretFindings);let o=await os(t,i.plan.manifest,i.archiveOptions);return {manifest:i.plan.manifest,tgzPath:o}}async function eA(e,n={}){return fs(e,n)}async function nA(e,n){let t=await fs(e,n);if(t.manifest.type!=="app")throw new Error("publish: App pack unexpectedly produced a template manifest");return t}
2
+ exports.DEFAULT_PUBLISH_MAX_BYTES=Xp;exports.DEFAULT_PUBLISH_MAX_FILES=Kp;exports.EXCLUDE_RULES=Br;exports.MARKETPLACE_API_PREFIX=pn;exports.PublishError=Re;exports.packApp=nA;exports.packPublish=fs;exports.packTemplate=eA;exports.planPublish=Qy;exports.uploadToMarketplace=Jp;