@crewx/sdk 0.9.0-rc.154 → 0.9.0-rc.156

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 Di=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 Di__namespace=/*#__PURE__*/_interopNamespace(Di);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 k,Cn=V(()=>{m();k=class extends Error{constructor(t,i=t,r){super(i);this.code=t;this.currentRevision=r;}code;currentRevision;name="UiRuntimeError"};});function gt(e){return As.test(e)||Is.test(e)}function ue(){throw new k("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,r,o){if(n>i&&ue(),e===null||typeof e=="string"||typeof e=="boolean")return typeof e=="string"&&(gs.test(e)||hs.test(e)&&!Ps(r,o)||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,r,o));_s(s)||ue();let a={};for(let[d,c]of Object.entries(e))gt(d)&&ue(),a[d]=At(c,n+1,t,i,[...r,d],o);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(r=>typeof r!="string"))&&ue();let i=At(e,0,new Set,Es+n,[],t);return (i===null||Array.isArray(i)||typeof i!="object")&&ue(),i}function qe(e,n){if(!e||!n)return false;let t=e.split("."),i=n.split(".");return t.length>=i.length&&i.every((r,o)=>t[o]===r)}function Ps(e,n){if(e.length===0)return false;let t=e.join(".");return n.some(i=>qe(t,i))}function Ze(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 Ze(It(e))}function mt(e){return Buffer.byteLength(e,"utf8")}var As,Is,gs,ms,hs,Es,Ts,Me=V(()=>{m();Cn();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 Li=V(()=>{m();Me();});var Un,ht=V(()=>{m();Un=["text/plain","application/json"];});var Oi=V(()=>{m();ht();});function Qe(e){return Ds.has(e)||bs.test(e)||Ss.test(e)}var Ri,Ds,bs,Ss,kn,yn,Ee,_t,Et,Tt,Pt,Nt,Ve=V(()=>{m();Ri=["__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(Ri),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;kn=/^[A-Za-z0-9_]+$/,yn=/^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)*$/,Ee=/^[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"&&Un.includes(e)}var wi=V(()=>{m();ht();Ve();});function xn(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();Oi();wi();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(r=>r.resultProjection!==void 0)?{id:e.id,version:e.version,...e.renderer===void 0?{}:{renderer:e.renderer},...e.surfaces===void 0?{}:{surfaces:e.surfaces},...e.stateProjection===void 0?{}:{stateProjection:e.stateProjection},...e.dataPaths===void 0?{}:{dataPaths:e.dataPaths},...e.summaryProjection===void 0?{}:{summaryProjection:e.summaryProjection},...e.legacy===void 0?{}:{legacy:e.legacy},...e.usage===void 0?{}:{usage:e.usage},...e.detailPanel===void 0?{}:{detailPanel:e.detailPanel},...e.displayModes===void 0?{}:{displayModes:e.displayModes},...e.sourceHash===void 0?{}:{sourceHash:e.sourceHash},actions:e.actions}:e.sourceHash===void 0?{id:e.id,version:e.version,actions:e.actions}:{id:e.id,version:e.version,sourceHash:e.sourceHash,actions:e.actions},i=fe(t);return Di.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 k("DEFINITION_UNSUPPORTED","UI definition is invalid");if(e.sourceHash!==void 0&&(typeof e.sourceHash!="string"||!Rs.test(e.sourceHash)))throw new k("DEFINITION_UNSUPPORTED","UI definition source hash is invalid");if(!/^[0-9a-f]{64}$/.test(e.hash)||pe(e)!==e.hash)throw new k("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=>!Cs(i)))throw new k("DEFINITION_UNSUPPORTED","UI action declaration is invalid");if(t.confirmation!==void 0&&t.confirmation!=="none"&&t.confirmation!=="native")throw new k("DEFINITION_UNSUPPORTED","UI action confirmation is invalid");if(t.inputKeys&&(!Array.isArray(t.inputKeys)||t.inputKeys.some(i=>typeof i!="string"||!i)))throw new k("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 k("DEFINITION_UNSUPPORTED","UI action data input declaration is invalid");if(t.resultProjection&&Mt(t.resultProjection),t.content!==void 0&&!xn(t.content))throw new k("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 k("DEFINITION_UNSUPPORTED","UI action environment declaration is invalid")}if(e.renderer!==void 0&&(!e.renderer||e.renderer.length>128))throw new k("DEFINITION_UNSUPPORTED","UI definition renderer is invalid");if(e.surfaces&&(!Array.isArray(e.surfaces)||e.surfaces.some(n=>!n||n.length>64)))throw new k("DEFINITION_UNSUPPORTED","UI definition surfaces are invalid");if(e.usage!==void 0&&e.usage!=="card"&&e.usage!=="window")throw new k("DEFINITION_UNSUPPORTED","UI definition usage is invalid");if(e.detailPanel!==void 0&&typeof e.detailPanel!="boolean")throw new k("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 k("DEFINITION_UNSUPPORTED","UI definition displayModes are invalid");if(e.usage==="card"&&e.displayModes!==void 0)throw new k("DEFINITION_UNSUPPORTED","Card definitions cannot declare displayModes");if(e.usage==="window"&&e.detailPanel!==void 0)throw new k("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 k("DEFINITION_UNSUPPORTED","UI summary projection exceeds state projection")}if(e.legacy!==void 0){if(!e.legacy||typeof e.legacy!="object"||Array.isArray(e.legacy)||Object.keys(e.legacy).some(r=>!["readTool","actionTool","hostTools","agentAccess"].includes(r)))throw new k("DEFINITION_UNSUPPORTED","UI legacy metadata is invalid");let n=new Set;for(let[r,o]of [["readTool",e.legacy.readTool],["actionTool",e.legacy.actionTool]])if(o!==void 0){if(ws(o,r==="readTool"),n.has(o.name))throw new k("DEFINITION_UNSUPPORTED","UI legacy tool names collide");n.add(o.name);}let t=e.legacy.hostTools;if(t!==void 0){if(!t||typeof t!="object"||Array.isArray(t))throw new k("DEFINITION_UNSUPPORTED","UI legacy host tools are invalid");let r={"doc.open":"crewx_app_html_viewer_open","pty.connect":"crewx_app_terminal_connect"};for(let[o,s]of Object.entries(t)){if(!Object.hasOwn(r,o)||r[o]!==s||typeof s!="string"||!/^[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(s)||n.has(s))throw new k("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(([r,o])=>!r||!Object.hasOwn(e.actions,r)||o!=="allowed"&&o!=="denied")))throw new k("DEFINITION_UNSUPPORTED","UI legacy agent access is invalid");if(e.legacy.actionTool!==void 0&&(!i||Object.keys(i).length===0))throw new k("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=>qe(t,i))))throw new k("DEFINITION_UNSUPPORTED","UI definition dataPaths are invalid")}}function ws(e,n){if(!e||typeof e!="object"||Array.isArray(e))throw new k("DEFINITION_UNSUPPORTED","UI legacy tool metadata is invalid");let t=e,i=["name","description","inputSchema","textFallback","visibility"],r=Object.hasOwn(t,"fixedResult");if(Object.keys(t).some(o=>!i.includes(o)&&!(n&&o==="fixedResult"))||i.some(o=>!Object.hasOwn(t,o))||typeof t.name!="string"||!/^[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(t.name)||typeof t.description!="string"||t.description.trim().length===0||t.description.length>8192||typeof t.textFallback!="string"||t.textFallback.trim().length===0||t.textFallback.length>16384||!t.inputSchema||typeof t.inputSchema!="object"||Array.isArray(t.inputSchema)||!Array.isArray(t.visibility)||t.visibility.length===0||t.visibility.some(o=>o!=="model"&&o!=="app")||new Set(t.visibility).size!==t.visibility.length)throw new k("DEFINITION_UNSUPPORTED","UI legacy tool metadata is invalid");try{let o=fe(t.inputSchema);if(o.type!==void 0&&o.type!=="object")throw new Error("schema type");if(r){if(!n)throw new Error("fixed result location");let 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(Ze(d))>4*1024)throw new Error("fixed result size")}}catch{throw new k("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 k("DEFINITION_UNSUPPORTED","UI projection policy is invalid")}function Cs(e){return e.length>0&&e.length<=128&&e!=="*"&&e!=="all"&&!/[/*]/.test(e)}var Rs,Be=V(()=>{m();Me();Cn();St();Rs=/^[0-9a-f]{64}$/;});var B,en,Ot=V(()=>{m();B="dist/tools.json",en="dist/main.mjs";});var ke,Rt=V(()=>{m();ke="window";});function Ci(e){if(!Array.isArray(e)||e.length===0)return false;let n=new Set;for(let t of e){if(!Us.some(i=>i===t)||n.has(t))return false;n.add(t);}return true}var Us,Ui=V(()=>{m();Us=["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 vn(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(o=>typeof o!="string"||o!=="length"&&!/^(?:0|[1-9][0-9]*)$/.test(o))&&H("CSP_ORIGIN_INVALID");let r=[];for(let o=0;o<t.length;o+=1)(!Object.prototype.hasOwnProperty.call(t,o)||typeof t[o]!="string")&&H("CSP_ORIGIN_INVALID"),r.push(t[o]);return Object.keys(t).length!==t.length&&H("CSP_ORIGIN_INVALID"),r}function 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 vi(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(),r=t[2];(r.includes("@")||r.includes("%")||r.includes("*"))&&H("CSP_ORIGIN_INVALID"),(r.startsWith("[")?Hs:zs).test(r)||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 ji(e,n,t){let i=4294967295<<32-t>>>0;return (e&i)===(n&i)}function Bi(e){let n=Xs(e);return ji(n,3221225472,24)?n!==3221225481&&n!==3221225482:Gs.some(([t,i])=>ji(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((o,s)=>o<<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 r=Number(n&0xffffffffn);return Bi([r>>>24&255,r>>>16&255,r>>>8&255,r&255].join("."))}return t<8192||t>16383||t===8193&&i<=511||t===8193&&i===3512||t===8194||t===16383&&i<=4095}function Zs(e,n){let t=e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e,i=net.isIP(t);if(i===4)return Bi(t);if(i===6)return qs(t);let r=e.toLowerCase().replace(/\.$/,"");return !r||!r.includes(".")||n.has(r)?true:Vs.some(o=>r===o||r.endsWith(`.${o}`))}function Fi(e){return Object.freeze([...new Set(e.map(n=>n.origin))].sort())}function Vi(e){return JSON.stringify({baseUriDomains:[],connectDomains:e.connectDomains,declared:e.declared,frameDomains:e.frameDomains,resourceDomains:[]})}function Hi(e,n={}){if(e===void 0){let f=Vi({declared:false,connectDomains:[],frameDomains:[]});return Object.freeze({declared:false,connectDomains:Object.freeze([]),frameDomains:Object.freeze([]),resourceDomains:Object.freeze([]),baseUriDomains:Object.freeze([]),cspHash:Di.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=vn(e,"connectDomains"),r=vn(e,"frameDomains"),o=vn(e,"resourceDomains"),s=vn(e,"baseUriDomains");(o.length>0||s.length>0)&&H("CSP_AXIS_UNSUPPORTED"),(Ks(e)>xs||i.length>xi||r.length>xi||i.length+r.length>vs||[...i,...r].some(f=>new TextEncoder().encode(f).byteLength>js))&&H("CSP_LIMIT_EXCEEDED");let d=i.map(f=>vi(f,"connectDomains")),c=r.map(f=>vi(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:Fi(d),frameDomains:Fi(c)},u=Vi(p);return Object.freeze({...p,resourceDomains:Object.freeze([]),baseUriDomains:Object.freeze([]),cspHash:Di.createHash("sha256").update(u,"utf8").digest("hex")})}var xs,xi,vs,js,Fs,Vs,Bs,Hs,zs,$s,Gs,wt,zi=V(()=>{m();xs=4096,xi=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 In(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 x(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function ba(e,n){let t={};for(let[i,r]of Object.entries(e))i!==n&&(t[i]=r);return t}function K(e,n,t=[]){let i=new Set([...n,...t]),r=Object.keys(e).find(s=>!i.has(s));r!==void 0&&A("MANIFEST_INVALID","MANIFEST_INVALID",r,"unknown-key");let o=n.find(s=>!x(e,s));o!==void 0&&A("MANIFEST_INVALID","MANIFEST_INVALID",o,"missing-key");}function Bn(e,n=false,t=false,i=false){return ta.test(e)||!i&&oa.test(e)||ia.test(e)||t&&$i.test(e)||ra.test(e)&&!(n&&/^\s*data:/i.test(e)&&!$i.test(e))}function Vn(e,n=new Set,t=0,i=false,r=false,o=""){if(typeof e=="string"){Bn(e,i,r)&&A("UNSAFE_VALUE","UNSAFE_VALUE",o,"unsafe-value");return}if(!(e===null||typeof e!="object")){(t>8||n.has(e))&&A("MANIFEST_INVALID","MANIFEST_INVALID",o),n.add(e);try{if(Array.isArray(e)){e.forEach((s,a)=>Vn(s,n,t+1,!1,!1,In(o,`[${a}]`)));return}$(e)||A("MANIFEST_INVALID","MANIFEST_INVALID",o);for(let[s,a]of Object.entries(e))Vn(a,n,t+1,i&&t===0&&(s==="name"||s==="description"),r,In(o,s));}finally{n.delete(e);}}}function Te(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 Ct(e){return na.test(e)||A("MANIFEST_INVALID"),e}function nn(e){return ea.test(e)||A("TOKEN_INVALID"),e}function Sa(e){return Qi.test(e)||A("MANIFEST_INVALID"),e}function Ma(e){$(e)||A("MANIFEST_INVALID");let n={};for(let[t,i]of Object.entries(e)){let r=Sa(t);$(i)||A("MANIFEST_INVALID");let o=i.type;if(o==="text"){K(i,["type","maxLength"]),n[r]={type:o,maxLength:Ie(i,"maxLength",1)};continue}if(o==="text-list"){K(i,["type","max","itemMaxLength"]),n[r]={type:o,max:Ie(i,"max",0),itemMaxLength:Ie(i,"itemMaxLength",1)};continue}if(o==="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[r]={type:o,min:s,max:a,labelMaxLength:Ie(i,"labelMaxLength",1),detailMaxLength:Ie(i,"detailMaxLength",1)};continue}typeof o=="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 jn(e,n,t){let i=Te(e,"field");return Qi.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:nn(Te(e,"badgeToken")),noticeToken:nn(Te(e,"noticeToken"))};case "heading":return K(e,["primitive","field"]),{primitive:t,field:jn(e,n,"text")};case "labeled-text":return K(e,["primitive","titleToken","field","variant"]),e.variant!=="callout"&&A("MANIFEST_INVALID"),{primitive:t,titleToken:nn(Te(e,"titleToken")),field:jn(e,n,"text"),variant:"callout"};case "step-flow":return K(e,["primitive","titleToken","field"]),{primitive:t,titleToken:nn(Te(e,"titleToken")),field:jn(e,n,"step-list")};case "text-list":{K(e,["primitive","titleToken","field"],["emptyToken","hideWhenEmpty"]);let i={primitive:t,titleToken:nn(Te(e,"titleToken")),field:jn(e,n,"text-list")};return x(e,"emptyToken")&&(i.emptyToken=nn(Te(e,"emptyToken"))),x(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 Gi(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`),(Bn(e,true,true)||sa.test(e)||aa.test(e)||ca.test(e))&&A("UNSAFE_VALUE",`${n} contains an unsafe value`),e}function Ut(e,n){return (typeof e!="string"||!Ee.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 eo(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((r,o)=>kt(r,n,t+1,In(i,`[${o}]`)));return}$(e)||A("MANIFEST_INVALID","v2 manifest contains a non-plain object",i,"non-plain-object");for(let[r,o]of Object.entries(e))kt(o,n,t+1,In(i,r));}finally{n.delete(e);}}}function no(e){return (typeof e!="string"||e.length>4096||!yn.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 r=no(i);t.has(r)&&A("MANIFEST_INVALID","projection allowlist contains a duplicate path"),t.add(r),n.push(r);}return {allow:n}}function Ca(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 r of e){let o=no(r);i.has(o)&&A("MANIFEST_INVALID","dataPaths contain a duplicate path"),n.some(s=>qe(o,s))||A("MANIFEST_INVALID","dataPaths must be projection-allowed"),i.add(o),t.push(o);}return t}function tn(e,n,t=Number.MAX_SAFE_INTEGER){return (!Number.isSafeInteger(e)||e<0||e>t)&&A("MANIFEST_INVALID",`${n} is invalid`),e}function Wi(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||Bn(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(r=>vt(r,n+1,t));$(e)||A("MANIFEST_INVALID","schema enum contains a non-plain object");let i={};for(let[r,o]of Object.entries(e))Qe(r)&&A("MANIFEST_INVALID","schema enum contains a reserved key"),i[r]=vt(o,n+1,t);return i}finally{t.delete(e);}}function Ua(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 r of e)(typeof r!="string"||!yn.test(r))&&A("MANIFEST_INVALID","schema required contains an invalid key"),r.length>4096&&X("schema required key is too long"),i.has(r)&&A("MANIFEST_INVALID","schema required contains a duplicate key"),n&&!Object.prototype.hasOwnProperty.call(n,r)&&A("MANIFEST_INVALID","schema required references an undeclared property"),i.add(r),t.push(r);return t}function ka(e,n){let t=n?yn:kn;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 r=["type","enum"];i==="string"&&r.push("minLength","maxLength"),i==="array"&&r.push("minItems","maxItems","items"),i==="object"&&r.push("minProperties","maxProperties","properties","required","additionalProperties"),(i==="number"||i==="integer")&&r.push("minimum","maximum"),K(e,["type"],r.filter(a=>a!=="type"));let o={type:i};if(x(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"),o.enum=e.enum.map(a=>vt(a))),i==="string"&&(x(e,"minLength")&&(o.minLength=tn(e.minLength,"schema minLength",4096)),x(e,"maxLength")&&(o.maxLength=tn(e.maxLength,"schema maxLength",4096)),o.minLength!==void 0&&o.maxLength!==void 0&&o.minLength>o.maxLength&&A("MANIFEST_INVALID","schema string length bounds are inverted")),(i==="number"||i==="integer")&&(x(e,"minimum")&&(o.minimum=Wi(e.minimum,"schema minimum")),x(e,"maximum")&&(o.maximum=Wi(e.maximum,"schema maximum")),o.minimum!==void 0&&o.maximum!==void 0&&o.minimum>o.maximum&&A("MANIFEST_INVALID","schema numeric bounds are inverted")),i==="array"&&(x(e,"minItems")&&(o.minItems=tn(e.minItems,"schema minItems",128)),x(e,"maxItems")&&(o.maxItems=tn(e.maxItems,"schema maxItems",128)),o.minItems!==void 0&&o.maxItems!==void 0&&o.minItems>o.maxItems&&A("MANIFEST_INVALID","schema array length bounds are inverted"),x(e,"items")&&(o.items=jt(e.items,n+1,false))),i==="object"){let a;if(x(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);}o.properties=a;}x(e,"minProperties")&&(o.minProperties=tn(e.minProperties,"schema minProperties",64)),x(e,"maxProperties")&&(o.maxProperties=tn(e.maxProperties,"schema maxProperties",64)),o.minProperties!==void 0&&o.maxProperties!==void 0&&o.minProperties>o.maxProperties&&A("MANIFEST_INVALID","schema object property bounds are inverted");let d=Ua(e.required,a);d!==void 0&&(o.required=d),x(e,"additionalProperties")&&(e.additionalProperties!==false&&A("MANIFEST_INVALID","schema additionalProperties must be false"),o.additionalProperties=false);}let s=JSON.stringify(o);return (s===void 0||Buffer.byteLength(s,"utf8")>1048576)&&X("action inputSchema subtree is too large"),o}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"&&x(e,"entry"))return K(e,ma),e.entry!==en&&A("MANIFEST_INVALID",`skill backend entry must be ${en}`),{type:"skill",entry:en};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=x(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),x(e,"_meta")&&z("_meta",()=>to(e._meta));let n=z("actionId",()=>Ut(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 r=z("inputSchema",()=>xa(e.inputSchema)),o;if(x(e,"dataInputs")){Array.isArray(e.dataInputs)||A("MANIFEST_INVALID","action dataInputs must be an array","dataInputs");let l=r.properties,p=new Set,u=[];for(let f of e.dataInputs)(typeof f!="string"||!x(l,f)||p.has(f))&&A("MANIFEST_INVALID","action dataInputs must be unique declared properties","dataInputs"),p.add(f),u.push(f);o=u;}let s=z("resultProjection",()=>xt(e.resultProjection)),a=z("backend",()=>va(e.backend)),d;x(e,"content")&&((a.type!=="skill"||!xn(e.content))&&A("MANIFEST_INVALID","action content declaration is invalid","content"),d=Va(e.content));let c;if(x(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:r,resultProjection:s,backend:a,...d===void 0?{}:{content:d},...o===void 0?{}:{dataInputs:o},...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"),x(e,"hash")?{path:"ui/state.json",hash:eo(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=Hi(e);}catch(i){let r=i!==null&&typeof i=="object"&&"code"in i&&typeof i.code=="string"?i.code:"CSP_ORIGIN_INVALID";return A("MANIFEST_INVALID",r,void 0,r.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)&&x(e,"csp")?ba(e,"csp"):e,new Set,0,true,true),kt(e),$(e)||A("MANIFEST_INVALID"),K(e,pa,la),x(e,"_meta")&&z("_meta",()=>to(e._meta)),e.manifestVersion!==2&&A("MANIFEST_INVALID");let t;x(e,"runtime")&&(t=z("runtime",()=>Ha(e.runtime)));let i;x(e,"csp")&&(i=z("csp",()=>za(e.csp,t)));let r=z("pluginId",()=>Ut(e.pluginId,"pluginId")),o=z("definitionId",()=>Ut(e.definitionId,"definitionId")),s=z("version",()=>Ie(e,"version",1)),a=z("name",()=>Gi(e.name,"name")),d=z("description",()=>Gi(e.description,"description")),c;x(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;x(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;x(e,"entryHash")&&(p=z("entryHash",()=>eo(e.entryHash)));let u;x(e,"initialState")&&(u=z("initialState",()=>Ba(e.initialState)));let f;x(e,"usage")&&(e.usage!=="card"&&e.usage!=="window"&&A("MANIFEST_INVALID","usage is invalid","usage"),f=e.usage);let g;x(e,"detailPanel")&&(typeof e.detailPanel!="boolean"&&A("MANIFEST_INVALID","detailPanel is invalid","detailPanel"),g=e.detailPanel);let _;if(x(e,"displayModes")){((f??ke)!==ke||!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.displayModes;}(f??ke)===ke&&g!==void 0&&A("MANIFEST_INVALID","detailPanel is card-only","detailPanel");let P=n.mode??"local";P!=="local"&&P!=="installed"&&P!=="published"&&A("MANIFEST_INVALID","manifest mode is invalid"),P!=="local"&&p===void 0&&A("MANIFEST_INVALID","installed manifests require entryHash","entryHash","required-when-installed"),P!=="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 C=[],U=new Set;for(let y of e.surfaces)(typeof y!="string"||!Nt.includes(y))&&A("MANIFEST_INVALID","surface is unsupported","surfaces"),U.has(y)&&A("MANIFEST_INVALID","surfaces contain a duplicate","surfaces","duplicate-item"),U.add(y),C.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)),j=e.summaryProjection===void 0?void 0:z("summaryProjection",()=>xt(e.summaryProjection));j!==void 0&&j.allow.some(y=>!w.allow.includes(y))&&A("MANIFEST_INVALID","summaryProjection must be a subset of stateProjection.allow","summaryProjection");let D=z("dataPaths",()=>Ca(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 b=[],O=new Set;for(let[y,I]of e.actions.entries()){let h=`actions[${y}]`,E=z(h,()=>ja(I));if(O.has(E.actionId)&&A("MANIFEST_INVALID","actions contain a duplicate actionId",`${h}.actionId`,"duplicate-item"),E.backend.type==="core"&&E.backend.handler==="state.set"){E.mutation||A("MANIFEST_INVALID","state.set actions must be mutations",`${h}.mutation`);for(let L of Object.keys(E.inputSchema.properties))w.allow.includes(L)||A("MANIFEST_INVALID","state.set input paths must be projection-allowed",`${h}.inputSchema.properties`);}O.add(E.actionId),b.push(E);}return {manifestVersion:2,pluginId:r,definitionId:o,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},..._===void 0?{}:{displayModes:_},surfaces:C,size:{height:N},stateProjection:w,...j===void 0?{}:{summaryProjection:j},...D===void 0?{}:{dataPaths:D},actions:b}}function to(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 o of e.actions){n[o.actionId]={capabilities:[o.capability],inputKeys:Object.keys(o.inputSchema.properties??{}),...o.dataInputs===void 0?{}:{dataInputs:o.dataInputs},resultProjection:o.resultProjection,...o.confirmation===void 0?{}:{confirmation:o.confirmation},...o.content===void 0?{}:{content:o.content},...o.backend.type!=="skill"||o.backend.env===void 0?{}:{env:o.backend.env}};let s=o.backend.type==="skill"||o.backend.type==="core"&&o.backend.handler==="state.set";t[o.actionId]={actionId:o.actionId,mutation:o.mutation,backend:o.backend,launchPolicy: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},r={entry:{path:"ui/index.html",...e.entryHash===void 0?{}:{hash:e.entryHash}},...e.initialState===void 0?{}:{initialState:e.initialState}};return {manifest:e,definition:i,handlers:t,resources:r}}function Ft(e,n,t,i,r,o){if(typeof e=="string"){let s=r.length>0&&o.some(a=>qe(r.join("."),a));return (e.length>4096||Bn(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,1048576,r,o));else {$(e)||Ae("state contains a non-plain object");let d={};for(let[c,l]of Object.entries(e))(c.length>4096||!kn.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,1048576,[...r,c],o);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,1048576,[],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=Ct(Te(e,"pluginId")),i=Ct(Te(e,"definitionId")),r=Ie(e,"version",1),o=Ie(e,"primitiveSet",1),s=n.supportedPrimitiveSet??Qs;(!Number.isSafeInteger(s)||s<1)&&A("MANIFEST_INVALID"),o>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=Ct(Te(e.activation,"language")),d=Ma(e.schema),c=Ra(e.layout,d);return {manifestVersion:1,pluginId:t,definitionId:i,version:r,primitiveSet:o,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 ze(e,n={}){try{return Ja(e,n)}catch(t){if(t instanceof re)throw t;return A("MANIFEST_INVALID")}}function gn(e,n={}){let t=ze(e,n);return t.manifestVersion===2?Ga(t):t}var Qs,ea,na,Qi,ta,ia,oa,ra,$i,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();Me();St();Ui();Ot();zi();Ve();Qs=1,ea=/^[a-z][a-zA-Z0-9]*(\.[a-zA-Z0-9]+)+$/,na=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,Qi=/^[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,$i=/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,r,o){super(i);this.code=t;this.path=r;this.rule=o;}code;path;rule;name="UiPluginValidationError";withPathPrefix(t){return new e(this.code,this.message,In(t,this.path),this.rule)}};});function co(e){return typeof e=="string"&&e.length<=Xa&&Ka.test(e)}function v(e,n,t,i,r){throw new Ne(e,{path:n,rule:t,...i===void 0?{}:{message:i},...r===void 0?{}:{file:r}})}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["${xe}"]`;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 po(e,n,t){return {path:t(e.path),rule:e.rule??Qa(e.code),...e.message!==e.code?{message:e.message}:{},file:n}}function lo(e){return JSON.parse(JSON.stringify(e))}function Gt(e,n,t=0,i=new Set){if(typeof e=="string"){e.length>4096&&v("LIMIT_EXCEEDED",n,"string-too-long"),(Ya.test(e)||qa.test(e)||Za.test(e))&&v("UNSAFE_VALUE",n,"unsafe-value");return}if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){Number.isFinite(e)||v("MANIFEST_INVALID",n,"non-finite-number");return}typeof e!="object"&&v("MANIFEST_INVALID",n,"non-json-value"),t>8&&v("LIMIT_EXCEEDED",n,"too-deep"),i.has(e)&&v("MANIFEST_INVALID",n,"cycle"),i.add(e);try{if(Array.isArray(e)){e.length>128&&v("LIMIT_EXCEEDED",n,"array-too-long"),e.forEach((r,o)=>Gt(r,`${n}[${o}]`,t+1,i));return}te(e)||v("MANIFEST_INVALID",n,"non-plain-object");for(let[r,o]of Object.entries(e))Gt(o,n===""?r:`${n}.${r}`,t+1,i);}finally{i.delete(e);}}}function ge(e,n){return (typeof e!="string"||e.length===0)&&v("MANIFEST_INVALID",n,"string"),e}function rn(e,n){return te(e)||v("MANIFEST_INVALID",n,"object"),e}function nc(e,n){Array.isArray(e)||v("MANIFEST_INVALID",n,"array"),e.forEach((t,i)=>ge(t,`${n}[${i}]`));}function tc(e,n){typeof e!="boolean"&&v("MANIFEST_INVALID",n,"boolean");}function mn(e,n,t,i){for(let r of Object.keys(e))!t.includes(r)&&!i.includes(r)&&v("MANIFEST_INVALID",`${n}.${r}`,"unknown-key");for(let r of t)Y(e,r)||v("MANIFEST_INVALID",`${n}.${r}`,"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=rn(n,e);mn(t,e,["name"],["email","url"]);for(let i of Object.keys(t))ge(t[i],`${e}.${i}`);return}case "repository":{let t=rn(n,e);mn(t,e,[],["type","url"]);for(let i of Object.keys(t))ge(t[i],`${e}.${i}`);return}case "icons":{Array.isArray(n)||v("MANIFEST_INVALID",e,"array"),n.forEach((t,i)=>{let r=`${e}[${i}]`,o=rn(t,r);mn(o,r,["src","size"],["theme"]),ge(o.src,`${r}.src`),ge(o.size,`${r}.size`),Y(o,"theme")&&ge(o.theme,`${r}.theme`);});return}case "screenshots":case "keywords":case "privacy_policies":nc(n,e);return;case "tools":{Array.isArray(n)||v("MANIFEST_INVALID",e,"array"),n.forEach((t,i)=>{let r=`${e}[${i}]`,o=rn(t,r);mn(o,r,["name"],["description"]),ge(o.name,`${r}.name`),Y(o,"description")&&ge(o.description,`${r}.description`);});return}case "prompts":{Array.isArray(n)||v("MANIFEST_INVALID",e,"array"),n.forEach((t,i)=>{let r=`${e}[${i}]`,o=rn(t,r);mn(o,r,["name","text"],["description","arguments"]),ge(o.name,`${r}.name`),ge(o.text,`${r}.text`);});return}case "tools_generated":case "prompts_generated":tc(n,e);return;case "localization":case "compatibility":case "user_config":rn(n,e);return;default:v("MANIFEST_INVALID",e,"unknown-key");}}function Hn(e){return typeof e=="string"&&Ee.test(e)?e:void 0}function uo(e){return Number.isSafeInteger(e)&&e>=1?e:void 0}function oc(e){let n=Hn(e.name);if(n===void 0)return;let t=e._meta,i=te(t)?t[xe]:void 0,r=te(i)?i:{},o=Y(r,"definitionId")?Hn(r.definitionId):n,s=Y(r,"definitionVersion")?uo(r.definitionVersion):1;return {pluginId:n,...o===void 0?{}:{definitionId:o},...s===void 0?{}:{definitionVersion:s}}}function rc(e){let n=Hn(e.pluginId);if(n===void 0)return;let t=Hn(e.definitionId),i=uo(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,xe)}catch{return false}}function sc(e,n){if(e===ce)return n.builtinOnly===true;let t=n._meta,i=te(t)?t[xe]:void 0;return te(i)&&i.builtinOnly===true}function ac(e,n){Y(e,"server")&&v("MANIFEST_INVALID","server","server-unsupported","phase 1 runs CrewX-owned Apps only");for(let a of Object.keys(e))Wt.includes(a)||v("MANIFEST_INVALID",a,"unknown-key");for(let a of Jt)Y(e,a)||v("MANIFEST_INVALID",a,"missing-key");e.manifest_version!==zt&&v("MANIFEST_INVALID","manifest_version","unsupported-version",`manifest_version must be "${zt}"`),co(e.version)||v("MANIFEST_INVALID","version","semver","version must be a semver.org version such as 0.1.0");let t=e._meta;te(t)||v("MANIFEST_INVALID","_meta","object"),Y(t,xe)||v("MANIFEST_INVALID",me(),"missing-key");let i=t[xe];te(i)||v("MANIFEST_INVALID",me(),"object");for(let a of Object.keys(i))$t.includes(a)||ao.includes(a)||v("MANIFEST_INVALID",me(a),"unknown-key");for(let a of $t)a==="actions"&&n!==void 0||Y(i,a)||v("MANIFEST_INVALID",me(a),"missing-key");if(n!==void 0&&Y(i,"actions")&&v("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)&&v("MANIFEST_INVALID",me("definitionVersion"),"positive-integer");}let r={};for(let a of so)Y(e,a)&&(ic(a,e[a]),r[a]=lo(e[a]));let o={};for(let[a,d]of Object.entries(t))a!==xe&&(o[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:en}}))),Object.keys(o).length>0&&(s._meta=o),{v2Input:s,...Object.keys(o).length>0?{vendorMeta:o}:{},passthrough:r}}function cc(e){Array.isArray(e)&&e.forEach((n,t)=>{let i=te(n)?n.backend:void 0;te(i)&&Y(i,"entry")&&v("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)||v("MANIFEST_INVALID","","not-object","manifest.json must be a JSON object",G);let i;try{i=ac(e,t);}catch(s){throw s instanceof Ne?new Ne(s.code,{...s.reason,file:G}):s}let r;try{let s=ze(i.v2Input,{mode:n.mode??"local"});s.manifestVersion!==2&&v("MANIFEST_INVALID","","v2-required"),r=s;}catch(s){throw s instanceof re?new Ne(s.code,po(s,G,ec)):s}let o=e.tools;if(Array.isArray(o)){let s=new Set(r.actions.map(a=>a.actionId));o.forEach((a,d)=>{let c=a.name;if(!s.has(c))throw new Ne("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:r,v2Input:i.v2Input,releaseVersion:e.version,...Object.keys(i.passthrough).length>0?{mcpb:i.passthrough}:{}}}function pc(e,n){try{let t=ze(e,{mode:n.mode??"local"});if(t.manifestVersion!==2)throw new Ne("MANIFEST_INVALID",{path:"manifestVersion",rule:"v2-required",message:"a workspace App requires manifestVersion 2",file:ce});return {file:ce,manifest:t,v2Input:e}}catch(t){throw t instanceof re?new Ne(t.code,po(t,ce,i=>i??"")):t}}function sn(e){return pe(gn(e).definition)}function oo(e){let{entryHash:n,initialState:t,...i}=e,r={...i};return t!==void 0&&(r.initialState={path:t.path}),lo(r)}function lc(e,n){let t=oo(e),i=oo(n);return [...new Set([...Object.keys(t),...Object.keys(i)])].sort().filter(o=>ne(t[o]??null)!==ne(i[o]??null))}function uc(e,n){return e.entryHash!==void 0&&n.entryHash!==void 0&&e.entryHash!==n.entryHash||e.initialState?.hash!==void 0&&n.initialState?.hash!==void 0&&e.initialState.hash!==n.initialState.hash}function fc(e,n){let t=lc(e,n),i=uc(e,n),r="";try{let o=sn(e),s=sn(n);i=i||o!==s,r=` (definition hash ${o.slice(0,12)} vs ${s.slice(0,12)})`;}catch{i=true;}t.length===0&&!i||v("MANIFEST_DUAL_MISMATCH","","dual-manifest-mismatch",`${G} and ${ce} normalize to different definitions${r}`+(t.length>0?`; differing fields: ${t.join(", ")}`:""));}function Pe(e,n,t="MANIFEST_INVALID",i){return {code:t,reason:{path:e,rule:n,...i===void 0?{}:{message:i},file:B},files:[]}}function ro(e){return {...Pe("","tools-needs-manifest-json","MANIFEST_INVALID",`${B} is read with ${G} only`),files:e}}function yc(e,n){if(e.byteLength>n)return {failure:Pe("","file-too-large","LIMIT_EXCEEDED")};let t;try{t=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e));}catch{return {failure:Pe("","invalid-json")}}if(!te(t))return {failure:Pe("","not-object","MANIFEST_INVALID",`${B} must be a JSON object`)};for(let r of Object.keys(t))if(r!=="schemaVersion"&&r!=="actions")return {failure:Pe(r,"unknown-key")};for(let r of ["schemaVersion","actions"])if(!Y(t,r))return {failure:Pe(r,"missing-key")};if(t.schemaVersion!==1)return {failure:Pe("schemaVersion","unsupported-version","MANIFEST_INVALID",`schemaVersion must be ${1}`)};let i=t.actions;if(!Array.isArray(i))return {failure:Pe("actions","array")};for(let[r,o]of i.entries()){if(!te(o))return {failure:Pe(`actions[${r}]`,"object")};if(Y(o,"backend"))return {failure:Pe(`actions[${r}].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=[],r=new TextDecoder("utf-8",{fatal:true});for(let o of q){let s=e[o];if(s===void 0)continue;if(s.byteLength>t)return {parsed:i,failure:{code:"LIMIT_EXCEEDED",reason:{path:"",rule:"file-too-large",file:o},files:[o]}};let a;try{a=JSON.parse(r.decode(s));}catch{return {parsed:i,failure:{code:"MANIFEST_INVALID",reason:{path:"",rule:"invalid-json",file:o},files:[o]}}}if(!te(a))return {parsed:i,failure:{code:"MANIFEST_INVALID",reason:{path:"",rule:"not-object",message:`${o} must be a JSON object`,file:o},files:[o]}};i.push({file:o,raw:a});}return {parsed:i}}function $e(e,n={}){let{parsed:t,failure:i}=Ac(e,n),r=q.filter(f=>e[f]!==void 0);if(i!==void 0)return {ok:false,rejection:i,parseFailure:true,builtinOnly:false};let o=e[B],s=o===void 0?void 0:yc(o,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:[]}:ro(r),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:ro(r);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 Ne)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?r:[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:r}}var G,ce,q,zt,xe,Wt,Jt,so,$t,ao,Ka,Xa,Ya,qa,Za,Ne,zn=V(()=>{m();Be();Me();Ot();Ve();Ht();G="manifest.json",ce="ui-plugin.json",q=[G,ce],zt="0.3",xe="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"]),so=Object.freeze(Wt.filter(e=>e!=="server"&&!Jt.includes(e))),$t=Object.freeze(["entry","surfaces","size","stateProjection","actions"]),ao=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;Ne=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();Li();zn();Ht();Ve();});function S(e,n=e){throw new De(e,n)}var De,Gn=V(()=>{m();De=class extends Error{constructor(t,i=t){super(i);this.code=t;}code;name="McpAppContractError"};});var Po=V(()=>{m();});var No=V(()=>{m();Be();Me();Gn();Po();});function bo(e,n){return Do.add(e),n!==void 0&&Sc.set(e,n),e}function an(e){return e!==null&&typeof e=="object"&&Do.has(e)}var Do,Sc,Wn=V(()=>{m();Do=new WeakSet,Sc=new WeakMap;});function Tn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function qt(e,n,t=[]){let i=new Set([...n,...t]),r=Object.keys(e);return n.every(o=>Object.hasOwn(e,o))&&r.every(o=>i.has(o))}function Lo(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let n of Object.values(e))Lo(n);return Object.freeze(e)}function ie(e){throw new be("LINEAGE_INVALID",e)}function Uc(e){throw new be("LINEAGE_STALE",e)}function Oo(e){if(!Tn(e)||!qt(e,Oc,Rc)||!Tn(e.actions))return ie("Lineage definition shape is invalid");for(let n of Object.values(e.actions))if(!Tn(n)||!qt(n,wc,Cc))return ie("Lineage action definition shape is invalid");return e}function kc(e){if(!Tn(e)||!qt(e,Mc,Lc))return ie("Lineage entry shape is invalid");if(!Number.isSafeInteger(e.version)||e.version<1||typeof e.hash!="string"||!So.test(e.hash))return ie("Lineage entry identity is invalid");if(e.sourceHash!==void 0&&(typeof e.sourceHash!="string"||!So.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=Oo(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"):Lo({version:e.version,hash:e.hash,definition:n,...e.sourceHash===void 0?{}:{sourceHash:e.sourceHash},...e.compat===void 0?{}:{compat:e.compat}})}function Mo(e){return e.stateProjection?.allow??[]}function xc(e,n){let t=[],i=new Set(Mo(n));Mo(e).some(a=>!i.has(a))&&t.push("S1_STATE_PROJECTION");let r=new Set(n.dataPaths??[]);(e.dataPaths??[]).some(a=>!r.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(!Tn(n)||typeof n.hash!="string")return ie("Current definition is invalid");let t,i;try{let{hash:a,...d}=n;i=Oo(d),t={...i,hash:a},ye(t);}catch{return ie("Current definition is invalid")}let r=e.map(kc),o=r[0].definition.id;if(r.some(a=>a.definition.id!==o))return ie("Lineage definition ids do not match");if(r.some((a,d)=>d>0&&a.version<=r[d-1].version))return ie("Lineage generations are not in increasing version order");if(r.some((a,d)=>r.findIndex(c=>c.hash===a.hash)!==d))return ie("Lineage contains a duplicate hash");let s=r[r.length-1];if(s.version!==t.version||s.hash!==t.hash||s.definition.id!==t.id||!vc(s.definition,i))return Uc("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 r)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 be("LINEAGE_INVALID",`Lineage compatibility failed: ${l}`,[l])}}for(let a=0;a<r.length-1;a+=1){if(r.slice(a,-1).some(l=>l.compat==="break"))continue;let c=xc(r[a].definition,t);if(c.length>0)throw new be("LINEAGE_INVALID",`Lineage compatibility failed: ${c.join(", ")}`,c)}return Object.freeze({entries:Object.freeze(r),current:t})}var be,So,Mc,Lc,Oc,Rc,wc,Cc,Qt=V(()=>{m();Be();Me();be=class extends Error{constructor(t,i=t,r=[]){super(i);this.code=t;this.violations=r;}code;violations;name="UiDefinitionLineageError"},So=/^[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"],Cc=["inputKeys","dataInputs","confirmation","resultProjection","content","env"];});var Ro,wo,Co,ei,Uo=V(()=>{m();Ro="text/html;profile=mcp-app",wo=["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 ko(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 xo=V(()=>{m();Be();Wn();});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:je}),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:je}),n}function Fe(e,n,t){return (typeof e!="string"||!jo.test(e))&&S(n,`${t} must be a safe identifier`),e}function Pn(e,n,t){let i=e??t;return (typeof i!="string"||i.trim().length===0||i.length>Bc)&&S("TOOL_INVALID",`${n} must be a meaningful description`),i}function ti(e){return (typeof e!="string"||e.length===0||e.length>cn||!/<html(?:\s|>)/i.test(e)||!/<\/html\s*>/i.test(e))&&S("HTML_INVALID","MCP App HTML must be a non-empty HTML document"),e}function Nn(e,n=0){try{let t=fe(e,n);return t.type!==void 0&&t.type!=="object"&&S("TOOL_INVALID","MCP App inputSchema must describe an object"),t}catch(t){if(t instanceof De)throw t;S("TOOL_INVALID","MCP App inputSchema must be projection-safe JSON");}}function Kc(e){return (typeof e!="string"||e.trim().length===0||e.length>Hc)&&S("TOOL_INVALID","MCP App tools require a meaningful text fallback"),e}function Xc(e){e===void 0&&S("TOOL_INVALID","MCP App tool visibility is required");let n=[...e];return (n.length===0||n.some(t=>t!=="model"&&t!=="app")||new Set(n).size!==n.length)&&S("TOOL_INVALID","MCP App tool visibility must contain model and/or app once"),n}function Bo(e){return (typeof e!="string"||!Fo.test(e))&&S("RESOURCE_URI_INVALID","MCP App resource URI is not a registered ui:// URI"),e}function Ho(e){let n=Fe(e.appId,"APP_ID_INVALID","Local App id"),t=Pn(e.name,"Local App name",n),i=Pn(e.description,"Local App description",`${t} interactive view`),r=Yn(e.definition),o=ti(e.html),s=Jn(e.entryHash,"Local App entry hash"),a=e.entryBytes===void 0?Array.from(new TextEncoder().encode(o)):Xn(e.entryBytes,"Local App entry bytes");(Kn(a)!==s||Go(a)!==o)&&S("HTML_INVALID","Local App entry bytes do not match the HTML hash");let d=Yc(e),c=[];Array.isArray(e.actions)||S("TOOL_INVALID","Local App actions must be an array");for(let N of e.actions){let w=Fe(N.actionId,"TOOL_ID_INVALID","Local App action id");(c.includes(w)||!Object.prototype.hasOwnProperty.call(r.actions,w))&&S("TOOL_INVALID",`Local App action is not declared by the UI definition: ${w}`),c.push(w);}let l=Fe(e.readToolName,"TOOL_ID_INVALID","Local App read tool name"),p=e.actionToolName===void 0?void 0:Fe(e.actionToolName,"TOOL_ID_INVALID","Local App action tool name");c.length===0&&p!==void 0&&S("TOOL_INVALID","A static local App cannot register an action tool"),c.length>0&&p===void 0&&S("TOOL_INVALID","A stateful local App requires an action tool name"),p!==void 0&&p===l&&S("TOOL_ID_CONFLICT",`Local App read and action tools share a name: ${l}`);let u=Jc(e.runtime);u.some(N=>N.name===l||N.name===p)&&S("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:je},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:je,actionIds:Object.freeze([...c])};g.push(Object.freeze(N));}let _=[],P=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||!jo.test(w)){_.push(Object.freeze({toolName:w,actionId:N.actionId,reason:"name_too_long"}));continue}if(P.has(w)){_.push(Object.freeze({toolName:w,actionId:N.actionId,reason:"name_collision"}));continue}let j=ko({actionId:N.actionId,confirmation:r.actions[N.actionId]?.confirmation,content:r.actions[N.actionId]?.content,backend:N.backend},e.modelActions),D=Object.freeze(j==="denied"?["app"]:["model","app"]),b={name:w,description:`${w} action`,inputSchema:Nn(N.inputSchema),textFallback:`${w} action requests are handled by the open App instance.`,visibility:D,kind:"action",resourceBinding:je,actionId:N.actionId,actionIds:Object.freeze([N.actionId]),_meta:Object.freeze({ui:Object.freeze({visibility:D})})};g.push(Object.freeze(b)),P.add(w);}let C={mimeType:ei,entryHash:s,html:o,bytes:Object.freeze([...a]),...d===void 0?{}:{initialState:Object.freeze({hash:d.hash,bytes:Object.freeze([...d.bytes])})}},U={appId:n,name:t,description:i,...e.icon===void 0?{}:{icon:Wo(e.icon)},...e.tone===void 0?{}:{tone:Jo(e.tone)},builtinOnly:false,definition:r,...e.runtime===void 0?{}:{runtime:Object.freeze({...e.runtime})},resourceBinding:je,resource:Object.freeze(C),tools:Object.freeze(g),toolDiagnostics:Object.freeze(_)};return Z(U)}function zo(e={}){return new ni(e)}function ii(e){if(e.length===0)return Nn({type:"object",properties:{},additionalProperties:false});let n=e.map(i=>i.actionId),t=new Map;for(let i of e)t.set(i.actionId,Nn(i.inputSchema));return Nn(qc(n,t),Vo)}function Yc(e){let n=e.definition.dataPaths??[];if(e.initialStateBytes===void 0){e.initialStateHash!==void 0&&S("STATE_INVALID","Initial state hash has no bytes"),e.initialState!==void 0&&fe(e.initialState,0,n);return}e.initialStateHash===void 0&&S("STATE_INVALID","Initial state bytes require a hash");let t=Jn(e.initialStateHash,"Initial state hash"),i=Xn(e.initialStateBytes,"Initial state bytes");Kn(i)!==t&&S("STATE_INVALID","Initial state bytes do not match the hash");let r;try{let o=new TextDecoder("utf-8",{fatal:!0}).decode(Uint8Array.from(i));r=fe(JSON.parse(o),0,n);}catch{S("STATE_INVALID","Initial state bytes are not projection-safe JSON");}return e.initialState!==void 0&&ne(r)!==ne(fe(e.initialState,0,n))&&S("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=Dn(e),t=Fe(n.appId,"APP_ID_INVALID","MCP App id"),i=ti(n.html);Bo(n.uiUri);let r=n.definition===void 0?void 0:Yn(n.definition),o=e.provenance;o!==void 0&&(!an(o)||o.appId!==t||o.definitionId!==r?.id||o.version!==r?.version||o.definitionHash!==r?.hash)&&S("TOOL_INVALID","Product App built-in registration provenance is not verified");let s=Object.freeze(n.tools.map(c=>Z(Dn(c)))),a=Z({...n,appId:t,html:i,...r===void 0?{}:{definition:r},...o===void 0?{}:{provenance:o},tools:s}),d=Z({uri:a.uiUri,mimeType:Ro,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,...r===void 0?{}:{definition:r},resourceBinding:Object.freeze({kind:"mcp",uri:a.uiUri}),resource:d,tools:s,descriptor:a})}function Qc(e){(e.resourceBinding.kind!=="instance"||e.builtinOnly!==false)&&S("STATE_INVALID","Local App registration binding is invalid"),Object.prototype.hasOwnProperty.call(e,"uiUri")&&S("STATE_INVALID","Local App registration cannot contain uiUri");let n=Fe(e.appId,"APP_ID_INVALID","Local App id"),t=Yn(e.definition),i=e.provenance;i!==void 0&&(!an(i)||i.appId!==n||i.definitionId!==t.id||i.version!==t.version||i.definitionHash!==t.hash)&&S("TOOL_INVALID","Product App local registration provenance is not verified");let r=ti(e.resource.html),o=Jn(e.resource.entryHash,"Local App entry hash"),s=Xn(e.resource.bytes,"Local App entry bytes");(Kn(s)!==o||Go(s)!==r)&&S("HTML_INVALID","Local App entry bytes do not match the HTML hash");let a=e.resource.initialState===void 0?void 0:{hash:Jn(e.resource.initialState.hash,"Initial state hash"),bytes:Xn(e.resource.initialState.bytes,"Initial state bytes")};a&&Kn(a.bytes)!==a.hash&&S("STATE_INVALID","Initial state bytes do not match the hash");let d=e.tools.map(c=>{Fe(c.name,"TOOL_ID_INVALID","Local App tool name"),Pn(c.description,"Local App tool description","Local App tool"),Kc(c.textFallback);let l=Nn(c.inputSchema,c.kind==="action"&&!("actionId"in c)?Vo:0);if((c.resourceBinding.kind!=="instance"||Object.prototype.hasOwnProperty.call(c,"resourceUri"))&&S("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"))&&S("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=Fe(c.actionId,"TOOL_ID_INVALID","Local App action id");Object.prototype.hasOwnProperty.call(t.actions,u)||S("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)&&S("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)))&&S("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:Pn(e.name,"Local App name",e.appId),description:Pn(e.description,"Local App description",e.name),...e.icon===void 0?{}:{icon:Wo(e.icon)},...e.tone===void 0?{}:{tone:Jo(e.tone)},builtinOnly:false,definition:t,...e.runtime===void 0?{}:{runtime:Object.freeze({...e.runtime})},...i===void 0?{}:{provenance:i},resourceBinding:je,resource:Z({mimeType:ei,entryHash:o,html:r,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:$o(e.definition),...e.provenance===void 0?{}:{provenance:e.provenance},entryHash:e.resource.entryHash,resourceBinding:je,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:$o(e.definition)},resourceBinding:Object.freeze({kind:"mcp",uri:e.uiUri}),tools:e.tools})}function Yn(e){try{if(Object.isFrozen(e))return ye(e),Z(e);let n=Dn(e);return ye(n),Z(n)}catch(n){if(n instanceof De)throw n;S("STATE_INVALID","UI definition is not a valid immutable definition");}}function $o(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 vo(e,n,t){return `${e}\0${n}\0${t}`}function Jn(e,n){return (typeof e!="string"||!Vc.test(e))&&S("SERIALIZATION_INVALID",`${n} is invalid`),e}function Kn(e){return Di.createHash("sha256").update(Uint8Array.from(e)).digest("hex")}function Xn(e,n){return (!Array.isArray(e)||e.some(t=>!Number.isInteger(t)||t<0||t>255))&&S("SERIALIZATION_INVALID",`${n} is invalid`),[...e]}function Go(e){try{return new TextDecoder("utf-8",{fatal:!0}).decode(Uint8Array.from(e))}catch{S("SERIALIZATION_INVALID","UTF-8 bytes are invalid");}}function Wo(e){return (typeof e!="string"||!zc.test(e))&&S("TOOL_INVALID","MCP App icon is invalid"),e}function Jo(e){return (typeof e!="string"||!$c.has(e))&&S("TOOL_INVALID","MCP App tone is invalid"),e}function Dn(e,n=new Map){if(e===null||typeof e!="object")return e;let t=e;if(n.has(t)&&S("SERIALIZATION_INVALID","MCP App value contains a cycle"),Array.isArray(e)){let o=[];n.set(t,o);for(let s of e)o.push(Dn(s,n));return n.delete(t),o}let i;try{i=Object.getPrototypeOf(e);}catch{S("SERIALIZATION_INVALID","MCP App value cannot be cloned");}i!==Object.prototype&&i!==null&&S("SERIALIZATION_INVALID","MCP App value must be plain JSON");let r={};n.set(t,r);for(let[o,s]of Object.entries(e))Object.defineProperty(r,o,{configurable:true,enumerable:true,value:Dn(s,n),writable:true});return n.delete(t),r}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 jo,Fo,Vc,cn,Bc,Hc,zc,$c,Gc,je,Wc,Vo,ni,qn=V(()=>{m();No();Be();Me();Wn();Gn();Qt();Uo();xo();jo=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,Fo=/^ui:\/\/crewx\/([A-Za-z][A-Za-z0-9._-]{0,127})\/([0-9a-f]{12})$/,Vc=/^[0-9a-f]{64}$/,cn=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(wo),new Set(Co),je=Object.freeze({kind:"instance"}),Wc=Object.freeze({type:"object",properties:Object.freeze({}),additionalProperties:false});Vo=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=[],r=[],o=[],s=new Set,a=new Set;for(let p of t?.listMcpApps()??[]){let u=Zc(p);s.has(u.appId)&&S("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)&&S("TOOL_ID_CONFLICT",`MCP App tool name is already registered: ${g.name}`),a.add(g.name),this.mcpToolByName.set(g.name,g),o.push(g);this.mcpResources.set(u.resource.uri,u.resource),i.push(u),r.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)&&S("APP_ID_CONFLICT",`MCP App id is already registered: ${u.appId}`),s.add(u.appId);let f=[],g=[...u.toolDiagnostics??[]];for(let _ of u.tools){if(a.has(_.name)){if(_.kind==="host"&&this.localToolByName.get(_.name)?.kind==="host"){f.push(_);continue}if(_.kind==="action"&&"actionId"in _){g.push(Object.freeze({toolName:_.name,actionId:_.actionId,reason:"name_collision"}));continue}S("TOOL_ID_CONFLICT",`MCP App tool name is already registered: ${_.name}`);}if(_.kind==="action"&&"actionId"in _&&c.has(_.name)){g.push(Object.freeze({toolName:_.name,actionId:_.actionId,reason:"name_collision"}));continue}a.add(_.name),this.localToolByName.set(_.name,_),f.push(_);}(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(r),this.builtinTools=Object.freeze(o);}getMcpApp(n){return this.builtinApps.find(t=>t.appId===n)?.descriptor??null}listMcpApps(){return this.builtinDescriptors}listMcpAppTools(){return this.builtinTools}resolveMcpAppTool(n){return this.mcpToolByName.get(n)??null}resolveMcpAppResource(n){return typeof n!="string"||!Fo.test(n)?null:this.mcpResources.get(n)??null}requireMcpAppResource(n){Bo(n);let t=this.mcpResources.get(n);return t||S("RESOURCE_NOT_FOUND",`MCP App resource is not registered: ${n}`),t}listLocalMcpApps(){return this.localApps}getLocalMcpApp(n){return this.localById.get(n)??null}listLocalMcpAppTools(){return Object.freeze([...this.localToolByName.values()])}resolveLocalMcpAppTool(n){return this.localToolByName.get(n)??null}resolveLocalMcpAppResource(n,t){let i=this.localById.get(n);return !i||t!==void 0&&i.definition.hash!==t?null:i.resource}listRegistrations(){return Object.freeze([...this.builtinApps,...this.localApps])}getRegistration(n){return this.registrationById.get(n)??null}listLaunchers(){return Object.freeze([...this.launcherById.values()].filter(n=>{let t=this.registrationById.get(n.appId),i=t?"descriptor"in t?t.descriptor.provenance:t.provenance:void 0,r=an(i)&&i.launcher===false;return t?.definition?.usage!=="card"&&!r}))}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(vo(n,t,i))??null}addDefinition(n){let t=Yn(n),i=Lt(t),r=this.definitionByKey.get(i);r&&r.hash!==t.hash&&S("STATE_INVALID",`UI definition generation conflicts: ${i}`),r||this.definitionByKey.set(i,t);}addHandler(n){(!n||typeof n.definitionId!="string"||typeof n.actionId!="string"||!Number.isSafeInteger(n.version)||n.version<1||typeof n.handle!="function")&&S("STATE_INVALID","UI action handler registration is invalid");let t=vo(n.definitionId,n.version,n.actionId);this.handlerByKey.has(t)&&S("TOOL_INVALID",`Duplicate UI action handler registration: ${t}`),this.handlerByKey.set(t,Object.freeze({...n}));}};});function id(e){let n=Ho({appId:e.appId,name:e.name,description:e.description,...e.icon===void 0?{}:{icon:e.icon},...e.tone===void 0?{}:{tone:e.tone},...e.normalized.manifest.runtime===void 0?{}:{runtime:e.normalized.manifest.runtime},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 Ko(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);zo({localApps:[t],definitions:[e.definition]});}var Xo=V(()=>{m();qn();});function od(e){if(e===null||typeof e!="object"||!(Yo in e))throw new TypeError("scanCache must be created by createWorkspaceAppScanCache");return e[Yo]}function qo(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 Yo,Zo=V(()=>{m();Yo=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 M("NOT_FOUND"):n==="ELOOP"?new M("PATH_ESCAPED"):n==="EFBIG"||n==="EOVERFLOW"?new M("LIMIT_EXCEEDED"):n==="EACCES"||n==="EPERM"||n==="ENOTDIR"?new M("READ_DENIED"):new M("READ_DENIED")}function cd(e){if(typeof e!="string"||e.length===0||!ae.isAbsolute(e))throw new M("READ_DENIED")}function oi(e){if(typeof e!="string"||ae.isAbsolute(e)||/[\\\u0000]/.test(e))throw new M("PATH_ESCAPED");if(e==="")return [];let n=e.split("/");if(n.some(t=>t.length===0||t==="."||t===".."))throw new M("PATH_ESCAPED");return n}function nt(e,n){let t=ae.relative(e,n);return t===""||t!==".."&&!t.startsWith(`..${ae.sep}`)&&!ae.isAbsolute(t)}function pn(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 Zn(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 M("READ_DENIED");return {realRoot:n,identity:pn(t)}}async function nr(e,n,t){if(t.length<2||t[0]!=="apps"&&t[0]!=="skills")return;let i,r;try{if(i=ae.resolve(e,t[0],t[1]),r=await promises.realpath(i),!(await promises.stat(r,{bigint:!0})).isDirectory())throw new M("READ_DENIED")}catch(o){throw o instanceof M?o:le(o)}if(!nt(n,r))throw new M("PATH_ESCAPED");return r}async function Qn(e,n,t,i){let r,o,s;try{r=await promises.lstat(e,{bigint:!0}),o=await promises.realpath(e),s=await promises.stat(o,{bigint:!0});}catch(a){throw le(a)}if(!nt(n,o)||t!==void 0&&!nt(t,o))throw new M("PATH_ESCAPED");if(!r.isFile()||!s.isFile())throw new M("READ_DENIED");if(!ci(i,r)||!ci(i,s)||i.dev!==s.dev)throw new M("PATH_ESCAPED")}async function dn(e,n){let t,i;try{t=await promises.realpath(e),i=await promises.stat(t,{bigint:!0});}catch{throw new M("PATH_ESCAPED")}if(t!==n.realRoot||!di(n.identity,pn(i)))throw new M("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 M,ai,ad,er,tt,tr,li=V(()=>{m();M=class extends Error{constructor(t){super(t);this.code=t;}code;name="AppDiscoveryFsError"},ai=ee.constants.O_NOFOLLOW,ad=ee.constants.O_NONBLOCK,er=ee.constants.O_RDONLY|(ai??0)|(ad??0);tt=class{async getRootIdentity(n){let t=await Zn(n);return await dn(n,t),{dev:t.identity.dev,ino:t.identity.ino,realPath:t.realRoot}}async listDirectory(n,t){let i=oi(t),r=await Zn(n),o=ae.resolve(n,...i),s,a;try{s=await promises.realpath(o),a=await promises.stat(s,{bigint:!0});}catch(d){let c=le(d);if(c.code==="NOT_FOUND")return [];throw c}if(!nt(r.realRoot,s)||!a.isDirectory())throw new M("PATH_ESCAPED");try{let d=await promises.readdir(s,{withFileTypes:!0,encoding:"utf8"});return await dn(n,r),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 M("READ_DENIED");if(ai===void 0)throw new M("UNSUPPORTED");let r=oi(t),o=await Zn(n),s=ae.resolve(n,...r),a=ae.relative(n,s);if(a===".."||a.startsWith(`..${ae.sep}`)||ae.isAbsolute(a))throw new M("PATH_ESCAPED");let d;try{d=await promises.open(s,er);}catch(c){throw le(c)}try{let c;try{let g=await d.stat({bigint:!0});c=pn(g);}catch(g){throw le(g)}if(c.size>BigInt(i))throw new M("LIMIT_EXCEEDED");if(c.size>BigInt(Number.MAX_SAFE_INTEGER))throw new M("LIMIT_EXCEEDED");await dn(n,o);let l=await nr(n,o.realRoot,r);await Qn(s,o.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(_){throw le(_)}if(g<=0)throw new M("IDENTITY_CHANGED");u+=g;}let f;try{let g=await d.stat({bigint:!0});f=pn(g);}catch(g){throw le(g)}if(!di(c,f))throw new M("IDENTITY_CHANGED");return await Qn(s,o.realRoot,l,f),await dn(n,o),new Uint8Array(p)}finally{await d.close().catch(()=>{});}}async fingerprintVerifiedFile(n,t,i){if(!Number.isSafeInteger(i)||i<0)throw new M("READ_DENIED");if(ai===void 0)throw new M("UNSUPPORTED");let r=oi(t),o=await Zn(n),s=ae.resolve(n,...r),a=ae.relative(n,s);if(a===".."||a.startsWith(`..${ae.sep}`)||ae.isAbsolute(a))throw new M("PATH_ESCAPED");let d;try{d=await promises.open(s,er);}catch(c){throw le(c)}try{let c;try{let u=await d.stat({bigint:!0});c=pn(u);}catch(u){throw le(u)}if(c.size>BigInt(i)||c.size>BigInt(Number.MAX_SAFE_INTEGER))throw new M("LIMIT_EXCEEDED");await dn(n,o);let l=await nr(n,o.realRoot,r);await Qn(s,o.realRoot,l,c);let p;try{let u=await d.stat({bigint:!0});p=pn(u);}catch(u){throw le(u)}if(!di(c,p))throw new M("IDENTITY_CHANGED");return await Qn(s,o.realRoot,l,p),await dn(n,o),{...p,candidateRealPath:l??o.realRoot}}catch(c){throw c instanceof M?c:le(c)}finally{await d.close().catch(()=>{});}}async readFileVerified(n,t,i){return this.readVerifiedFile(n,t,i)}},tr=new tt;});function Ln(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;try{let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}catch{return false}}function or(e){return typeof e=="string"&&Ee.test(e)?e:void 0}function Id(e){return e.length>0&&e!=="."&&e!==".."&&!/[\\/\u0000]/.test(e)}function We(e,n){let t=new TextEncoder().encode(e),i=new TextEncoder().encode(n),r=Math.min(t.byteLength,i.byteLength);for(let o=0;o<r;o+=1){let s=t[o]-i[o];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 r=n.isFile;return typeof r=="function"&&r.call(e)?{name:n.name,kind:"file"}:{name:n.name,kind:"other"}}function md(e){if(e instanceof Uint8Array)return new Uint8Array(e);if(e instanceof ArrayBuffer)return new Uint8Array(e.slice(0));if(Array.isArray(e)&&e.every(n=>Number.isInteger(n)&&n>=0&&n<=255))return Uint8Array.from(e);throw new TypeError("filesystem port returned an invalid byte array")}function hd(e){return yd.decode(e)}function _d(e){return JSON.parse(hd(e))}function rr(e){switch(e){case "ENOENT":return "NOT_FOUND";case "ELOOP":case "EXDEV":return "PATH_ESCAPED";case "EFBIG":case "EOVERFLOW":return "LIMIT_EXCEEDED";case "EACCES":case "EPERM":case "ENOTDIR":return "READ_DENIED";default:return e}}function Ed(e){if(e instanceof M)return rr(e.code);if(e!==null&&typeof e=="object"&&"code"in e){let n=e.code;if(typeof n=="string")return rr(n)}}function Oe(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 sr(e,n,t,i){let r=Td(e);if(!r)throw new M("READ_DENIED");return md(await r.call(e,n,t,i))}async function yi(e,n,t){let i=Pd(e);if(!i)throw new M("READ_DENIED");let r=await i.call(e,n,t);if(!Array.isArray(r))throw new M("READ_DENIED");return r.map(gd).filter(o=>o!==null)}function Nd(e,n,t,i){return Object.freeze({code:e,...{},source:n,relativePath:t})}function Dd(e){if(!Ln(e))throw new TypeError("productBundle.reservedIds must be an object with appIds and definitionIds arrays");try{let n=Reflect.ownKeys(e);if(n.length!==2||!n.includes("appIds")||!n.includes("definitionIds"))throw new TypeError("productBundle.reservedIds must contain exactly appIds and definitionIds");let t=(i,r)=>{if(!Array.isArray(i))throw new TypeError("productBundle.reservedIds."+r+" must be an array");let o=[];for(let s=0;s<i.length;s+=1){let a=i[s];if(typeof a!="string"||a.length===0)throw new TypeError("productBundle.reservedIds."+r+" must contain non-empty strings");o.push(a);}return Object.freeze([...new Set(o)].sort(We))};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 ot(e){return Object.freeze({appIds:Object.freeze([...new Set(e.map(n=>n.appId))].sort(We)),definitionIds:Object.freeze([...new Set(e.map(n=>n.definition.id))].sort(We))})}function it(e,n){let t=Object.keys(e).sort(We),i=[...n].sort(We);return t.length===i.length&&t.every((r,o)=>r===i[o])}function ar(e){if(typeof e!="string"||e.length===0||e.startsWith("/")||/[\\\u0000]/.test(e))return;let n=e.split("/");if(!n.some(t=>t.length===0||t==="."||t===".."))return n}function Sd(e){let n;try{n=_d(e);}catch{return}if(!Ln(n)||!it(n,["version","packages"])||n.version!==1||!Array.isArray(n.packages)||n.packages.length>Ai)return;let t=new Set,i=new Set,r=0,o=[];for(let s of n.packages){if(!Ln(s))return;let a=["packageDir","appId","definition","files"],d=Object.hasOwn(s,"lineage"),c=Object.hasOwn(s,"launcher"),l=[...d?["lineage"]:[],...c?["launcher"]:[]];if(!it(s,[...a,...l])||c&&s.launcher!==false)return;let p=ar(s.packageDir),u=or(s.appId);if(!p||p.length!==2||p[0]!=="apps"||!Id(p[1])||!u||t.has(s.packageDir)||!Ln(s.definition)||!it(s.definition,["id","version","hash"]))return;let f=or(s.definition.id),g=s.definition.version,_=s.definition.hash;if(!f||!Number.isSafeInteger(g)||g<1||typeof _!="string"||!fi.test(_)||!Array.isArray(s.files)||s.files.length<2||s.files.length>Ii)return;let P=new Set,C=[];for(let U of s.files){if(!Ln(U)||!it(U,["path","sha256"]))return;let N=ar(U.path);if(!N||typeof U.sha256!="string"||!fi.test(U.sha256))return;let w=N.join("/"),j=`${s.packageDir}/${w}`;if(P.has(w)||i.has(j))return;P.add(w),i.add(j),C.push(Object.freeze({path:w,sha256:U.sha256}));}if(!q.some(U=>P.has(U))||!P.has("ui/index.html")||(r+=C.length,r>ld))return;t.add(s.packageDir),o.push(Object.freeze({packageDir:s.packageDir,...c?{launcher:false}:{},appId:u,definition:Object.freeze({id:f,version:g,hash:_}),lineage:Array.isArray(s.lineage)?s.lineage:[],files:Object.freeze(C.sort((U,N)=>We(U.path,N.path)))}));}return Object.freeze({version:1,packages:Object.freeze(o)})}function Ge(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,r){let o=[],s=async(a,d)=>{if(!Oe(i,r))throw new M("LIMIT_EXCEEDED");if(d>2)throw new M("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 M("PATH_ESCAPED");let p=`${a}/${l.name}`;if(l.kind==="file"){if(o.push(p.slice(t.length+1)),o.length>Ii)throw new M("LIMIT_EXCEEDED")}else if(l.kind==="directory")await s(p,d+1);else throw l.kind==="symlink"?new M("PATH_ESCAPED"):new M("READ_DENIED")}};return await s(t,0),o.sort(We)}function Ld(e){return q.includes(e)?262144:e==="ui/index.html"?cn:e==="ui/state.json"?1048576:e.startsWith("ui/assets/")?fd:ud}async function cr(e,n,t,i){if(e===void 0)return {packages:[],diagnostics:[],incomplete:false,reservedIds:Ad};let r=Dd(e.reservedIds),o=[],s=(y,I,h)=>Nd(y,"bundled",I),a=(y=[],I=false,h)=>({...h===void 0?{}:{indexHash:h},packages:y,diagnostics:o,incomplete:I,reservedIds:r});if(typeof e.root!="string"||e.root.length===0||typeof e.expectedIndexHash!="string"||!fi.test(e.expectedIndexHash))return o.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a();let d;try{d=await sr(n,e.root,"bundle-index.json",pd);}catch(y){return o.push(s(Ge(y),"bundle-index.json")),a()}let c=Di.createHash("sha256").update(d).digest("hex");if(c!==e.expectedIndexHash)return o.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a();let l=Sd(d);if(l===void 0)return o.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a();if(!bd(ot(l.packages),r))return o.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a([],false,c);if(!Oe(t,i))return o.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 o.push(s(Ge(y),"bundle-index.json")),a(l.packages.map(I=>({indexEntry:I,failureCode:Ge(y)})),false,c)}if(!Oe(t,i))return o.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 o.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a(g("BUNDLE_INTEGRITY"),false,c);let _=p.filter(y=>y.name!=="bundle-index.json"&&y.name!=="apps");if(_.length>0){let y=_.some(I=>I.kind==="symlink")?"PATH_ESCAPED":"BUNDLE_INTEGRITY";return o.push(s(y,"bundle-index.json")),a(g("BUNDLE_INTEGRITY"),false,c)}if(p.some(y=>y.name==="apps"&&y.kind!=="directory"))return o.push(s("PATH_ESCAPED","apps")),a(g("PATH_ESCAPED"),false,c);let P=[];if(f)try{P=await yi(n,e.root,"apps");}catch(y){return o.push(s(Ge(y),"apps")),a(g(Ge(y)),false,c)}if(!Oe(t,i)||P.length>Ai)return o.push(s("LIMIT_EXCEEDED","apps")),a(g("LIMIT_EXCEEDED"),true,c);let C=new Map(l.packages.map(y=>[y.packageDir.slice(5),y])),U=P.filter(y=>!C.has(y.name));for(let y of U)o.push(s(y.kind==="symlink"?"PATH_ESCAPED":"BUNDLE_INTEGRITY",`apps/${y.name}`));if(U.length>0){let y=U.some(I=>I.kind==="symlink")?"PATH_ESCAPED":"BUNDLE_INTEGRITY";return a(g(y),false,c)}let N=new Set,w=new Map,j=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)}`,E=j.get(h)??[];E.push(y),j.set(h,E);}for(let y of [...w.values(),...j.values()])if(y.length>1)for(let I of y)N.add(I);let D=[],b=d.byteLength,O=false;for(let y of l.packages){if(!Oe(t,i)){O=true,D.push({indexEntry:y,failureCode:"LIMIT_EXCEEDED"});continue}let I;try{let L=y.lineage[y.lineage.length-1];if(!L)throw new be("LINEAGE_INVALID","Definition lineage is missing");if(L.definition.id!==y.definition.id||L.version!==y.definition.version||L.hash!==y.definition.hash)throw new be("LINEAGE_STALE","Last lineage generation does not match bundle identity");I=Zt(y.lineage,{...L.definition,hash:L.hash}).entries;}catch(L){let W=L instanceof be?L.code:"LINEAGE_INVALID";o.push(s(W,y.packageDir)),D.push({indexEntry:y,failureCode:W});continue}let h=P.find(L=>L.name===y.packageDir.slice(5));if(!f||!h){D.push({indexEntry:y,failureCode:"BUNDLE_INTEGRITY"});continue}if(h.kind!=="directory"){D.push({indexEntry:y,failureCode:h.kind==="symlink"?"PATH_ESCAPED":"BUNDLE_INTEGRITY"});continue}let E;try{let L=await Md(n,e.root,y.packageDir,t,i);if(!Oe(t,i)){O=!0,D.push({indexEntry:y,failureCode:"LIMIT_EXCEEDED"});continue}let W=y.files.map(J=>J.path);if(L.length!==W.length||L.some((J,Se)=>J!==W[Se])){D.push({indexEntry:y,failureCode:"BUNDLE_INTEGRITY"});continue}E=new Map;let de;for(let J of y.files){if(!Oe(t,i)){de="LIMIT_EXCEEDED",O=!0;break}if(b>=ui){de="LIMIT_EXCEEDED";break}let Se;try{Se=await sr(n,e.root,`${y.packageDir}/${J.path}`,Ld(J.path));}catch(ys){de=Ge(ys);break}if(!Oe(t,i)){de="LIMIT_EXCEEDED",O=!0;break}if(b+Se.byteLength>ui){b=ui,de="LIMIT_EXCEEDED";break}if(b+=Se.byteLength,Di.createHash("sha256").update(Se).digest("hex")!==J.sha256){de="BUNDLE_INTEGRITY";break}E.set(J.path,Se);}if(de!==void 0){D.push({indexEntry:y,failureCode:de});continue}}catch(L){Oe(t,i)||(O=true),D.push({indexEntry:y,failureCode:Ge(L)});continue}D.push({indexEntry:y,lineage:I,files:E,...N.has(y)?{failureCode:"DUPLICATE_ID"}:{}});}return a(D,O,c)}var pd,Ai,Ii,ld,ud,fd,ui,fi,yd,Ad,gi=V(()=>{m();Qt();Ve();zn();qn();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"||!Ee.test(e))throw new TypeError("pluginId must be a safe UI plugin identifier");let n=`${mi}${e}`.length+7<=128?e:`hash_${Di.createHash("sha256").update(e,"utf8").digest("hex")}`;return {read:`${mi}${n}_read`,action:`${mi}${n}_action`}}function pr(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;try{let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}catch{return false}}function Cd(e,n){return n.length===0||n==="."||n===".."||/[\\/\u0000]/.test(n)?e==="skills"?"skills":"apps":`${e==="skills"?"skills":"apps"}/${n}`}function Ud(e){return e.length>0&&e!=="."&&e!==".."&&!/[\\/\u0000]/.test(e)}function On(e,n){let t=new TextEncoder().encode(e),i=new TextEncoder().encode(n),r=Math.min(t.byteLength,i.byteLength);for(let o=0;o<r;o+=1){let s=t[o]-i[o];if(s!==0)return s}return t.byteLength-i.byteLength}function Er(e){if(typeof e=="string")return {name:e,kind:"directory"};if(e===null||typeof e!="object")return null;let n=e;if(typeof n.name!="string")return null;if(n.kind==="file"||n.kind==="directory"||n.kind==="symlink"||n.kind==="other")return {name:n.name,kind:n.kind};if(n.type==="file"||n.type==="directory"||n.type==="symlink"||n.type==="other")return {name:n.name,kind:n.type};let t=n.isDirectory;if(typeof t=="function"&&t.call(e))return {name:n.name,kind:"directory"};let i=n.isSymbolicLink;if(typeof i=="function"&&i.call(e))return {name:n.name,kind:"symlink"};let r=n.isFile;return typeof r=="function"&&r.call(e)?{name:n.name,kind:"file"}:{name:n.name,kind:"other"}}function 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 Tr(e){return wd.decode(e)}function xd(e){return JSON.parse(Tr(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 st(e,n,t,i,r){let o={code:e,...i===void 0?{}:{pluginId:i},source:n,relativePath:t,...r?.reason===void 0?{}:{reason:Object.freeze({...r.reason})},...r?.files===void 0?{}:{files:Object.freeze([...r.files])}};return Object.freeze(o)}function lr(e){switch(e){case "ENOENT":return "NOT_FOUND";case "ELOOP":case "EXDEV":return "PATH_ESCAPED";case "EFBIG":case "EOVERFLOW":return "LIMIT_EXCEEDED";case "EACCES":case "EPERM":case "ENOTDIR":return "READ_DENIED";default:return e}}function se(e){if(e instanceof M)return lr(e.code);if(e!==null&&typeof e=="object"&&"code"in e){let n=e.code;if(typeof n=="string")return lr(n)}}function Ke(e,n){return e==="PATH_ESCAPED"||e==="IDENTITY_CHANGED"||e==="TOCTOU"?"PATH_ESCAPED":e==="LIMIT_EXCEEDED"?"LIMIT_EXCEEDED":n==="manifest"&&e==="NOT_FOUND"?"MANIFEST_MISSING":n==="entry"?"ENTRY_INVALID":n==="initial"?"INITIAL_STATE_INVALID":"MANIFEST_INVALID"}function ur(e){return {reason:e.reason,...e.code==="MANIFEST_DUAL_MISMATCH"?{files:e.files}:{}}}function fr(e){return e==="MANIFEST_DUAL_MISMATCH"?e:Pr(e)}function jd(e){return Pr(e.code)}function Pr(e){switch(e){case "MANIFEST_INVALID":case "PRIMITIVE_UNKNOWN":case "PRIMITIVE_SET_UNSUPPORTED":case "SCHEMA_TYPE_UNSUPPORTED":case "TOKEN_INVALID":case "UNSAFE_VALUE":return "MANIFEST_INVALID";case "LIMIT_EXCEEDED":return "LIMIT_EXCEEDED";case "INITIAL_STATE_INVALID":return "INITIAL_STATE_INVALID";default:return Nr("UiPluginValidationError",e)}}function Nr(e,n){throw new Error(`Unmapped ${e} code: ${String(n)}`)}function Dr(e){switch(e){case "APP_ID_INVALID":case "TOOL_ID_INVALID":case "RESOURCE_URI_INVALID":case "TOOL_INVALID":case "SERIALIZATION_INVALID":return "MANIFEST_INVALID";case "APP_ID_CONFLICT":case "TOOL_ID_CONFLICT":return "DUPLICATE_ID";case "RESOURCE_NOT_FOUND":case "HTML_INVALID":return "ENTRY_INVALID";case "STATE_INVALID":case "STATE_PROJECTION_INVALID":case "BUTTON_INVALID":return "INITIAL_STATE_INVALID";default:return Nr("McpAppContractError",e)}}function Re(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 r=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(t));if(pr(r)){let o=r.bin,s=typeof o=="string"?o:pr(o)?Object.values(o).find(a=>typeof a=="string"):void 0;for(let a of [s,r.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(r=>n.has(r))}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 Je(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let n of Object.values(e))Je(n);return Object.freeze(e)}function yr(e){return Object.freeze(Array.from(e))}async function at(e,n,t,i){if(n.pinnedFiles!==void 0){let a=n.pinnedFiles.get(t);if(a===void 0)throw new M("NOT_FOUND");if(a.byteLength>i)throw new M("LIMIT_EXCEEDED");return new Uint8Array(a)}let r=`${n.relativePath}/${t}`,o=n.scanContext,s=e.fingerprintVerifiedFile;if(o===void 0||!o.cacheable||typeof s!="function")return mr(e,n.root,r,i);try{let a=o.priorFingerprints.get(r)??await s.call(e,o.workspaceRoot,r,i);o.candidateRealPath=a.candidateRealPath;let d=await mr(e,n.root,r,i),c=await s.call(e,o.workspaceRoot,r,i);return o.candidateRealPath=c.candidateRealPath,Sr(a,c)&&c.size===BigInt(d.byteLength)&&!Mr(c,o.scanStartedAtNs)?o.files.set(r,{relativePath:r,byteLimit:i,fingerprint:c}):o.cacheable=!1,d}catch(a){let d=q.includes(t)&&se(a)==="NOT_FOUND"&&o.directoryListings.some(l=>l.relativePath===n.relativePath&&!ct(l.key,t)),c=t===B&&se(a)==="NOT_FOUND"&&zd(o.directoryListings,n.relativePath);throw !d&&!c&&(o.cacheable=false),a}}function zd(e,n){let t=e.find(r=>r.relativePath===n);if(t===void 0)return false;if(!ct(t.key,"dist"))return true;let i=e.find(r=>r.relativePath===`${n}/dist`);return i!==void 0&&!ct(i.key,"tools.json")}function br(e,n){return JSON.stringify([e.realPath,n.source,n.relativePath])}async function Gd(e,n,t,i,r,o,s,a){let d=e.fingerprintVerifiedFile,c=br(t,i),l=r.candidates.get(c),p=i.relativePath,u;try{u=await gr(e,n,p);}catch(O){if(se(O)!=="NOT_FOUND")throw O}let f=u===void 0?void 0:{relativePath:p,key:u};if(f!==void 0&&(i.source==="apps"||i.source==="skills")&&!q.some(O=>ct(f.key,O)))return Re(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:r,cacheKey:c,workspaceRoot:n,scanStartedAtNs:o,directoryListings:Object.freeze([f]),priorFingerprints:new Map,files:new Map,cacheable:true}}:{timeLimitReached:true};let g=async O=>{if(O==="")return f;let y=`${i.relativePath}${O}`;try{let I=await gr(e,n,y);return I===void 0?void 0:{relativePath:y,key:I}}catch(I){if(se(I)==="NOT_FOUND")return;throw I}},_=await Promise.all(Ar.map(g)),P=await Promise.all($d.map(g));if(!Re(s,a))return {timeLimitReached:true};let C=typeof d=="function"&&_.every(O=>O!==void 0),U=_.filter(O=>O!==void 0),N=[...U,...P.filter(O=>O!==void 0)],w=new Map,j=l!==void 0&&C,D;if(l!==void 0&&typeof d=="function"){let O=await Promise.all(l.files.map(async y=>{if(!Re(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(O.some(y=>y.kind==="time"))return {timeLimitReached:true};for(let y of O){if(y.kind==="error")throw y.error;if(y.kind==="missing"){j=false;continue}if(y.kind!=="fingerprint")continue;let{file:I,current:h}=y;w.set(I.relativePath,h),D??=h.candidateRealPath,(h.candidateRealPath!==l.candidateRealPath||!Sr(h,I.fingerprint)||Mr(h,o))&&(j=false);}}let b=l!==void 0&&l.directoryListings.length===N.length&&l.directoryListings.every((O,y)=>O.relativePath===N[y]?.relativePath&&O.key===N[y]?.key);return l!==void 0&&C&&b&&j&&D===l.candidateRealPath?{memo:l}:!C||U.length!==Ar.length?{}:{context:{state:r,cacheKey:c,workspaceRoot:n,scanStartedAtNs:o,directoryListings:Object.freeze(N),priorFingerprints:w,files:new Map,...D===void 0?{}:{candidateRealPath:D},cacheable:true}}}function ct(e,n){try{let t=JSON.parse(e);return Array.isArray(t)&&t.some(i=>Array.isArray(i)&&i[0]===n)}catch{return true}}async function gr(e,n,t){let i=Lr(e);if(typeof i!="function")return;let r=await i.call(e,n,t);if(!Array.isArray(r)||r.some(s=>typeof s=="string"))return;let o=r.map(Er);if(!o.some(s=>s===null))return JSON.stringify(o.slice().sort((s,a)=>On(s.name,a.name)||On(s.kind,a.kind)).map(s=>[s.name,s.kind]))}function Sr(e,n){return e.dev===n.dev&&e.ino===n.ino&&e.size===n.size&&e.mtimeNs===n.mtimeNs&&e.ctimeNs===n.ctimeNs}function Mr(e,n){let t=e.mtimeNs-n;return t>=-Ir&&t<=Ir}function 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,r=t||i;if(n===void 0||!n.cacheable||n.candidateRealPath===void 0&&!r||n.files.size===0&&!r)return;let o=Object.freeze({...!r&&n.candidateRealPath!==void 0?{candidateRealPath:n.candidateRealPath}:{},directoryListings:n.directoryListings,files:Object.freeze([...n.files.values()]),...e.candidate===void 0?{}:{candidate:e.candidate},...e.diagnostic===void 0?{}:{diagnostic:e.diagnostic},...e.identity===void 0?{}:{identity:e.identity},...e.provenance===void 0?{}:{provenance:e.provenance}});n.state.candidates.set(n.cacheKey,o);}function Wd(e,n,t){let i=Di.createHash("sha256"),r=new TextEncoder().encode(ne(e)),o=s=>{let a=new Uint8Array(8);new DataView(a.buffer).setBigUint64(0,BigInt(s)),i.update(a);};return o(r.byteLength),i.update(r),o(n.byteLength),i.update(n),o(t.byteLength),i.update(t),i.digest("hex")}function Jd(e,n){let t={...e.definition,sourceHash:n},i;try{i=pe(t);}catch(o){throw o instanceof k&&o.code==="INPUT_INVALID"?new re("MANIFEST_INVALID","normalized definition is invalid"):o}let r={...t,hash:i};try{ye(r);}catch{throw new re("MANIFEST_INVALID","normalized definition is invalid")}return r}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 Lr(e){if(typeof e.listDirectory=="function")return e.listDirectory;if(typeof e.readDirectory=="function")return e.readDirectory;if(typeof e.readdir=="function")return e.readdir}async function mr(e,n,t,i){let r=Xd(e);if(!r)throw new M("READ_DENIED");return kd(await r.call(e,n,t,i))}async function Yd(e,n,t){let i=Lr(e);if(!i)throw new M("READ_DENIED");let r=await i.call(e,n,t);if(!Array.isArray(r))throw new M("READ_DENIED");return r.map(Er).filter(o=>o!==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(hr(e.builtins)):e.builtins&&n.push(e.builtins),e.builtinCatalog&&n.push(hr(e.builtinCatalog)),n.push({...e.reservedAppIds===void 0?{}:{appIds:e.reservedAppIds},...e.reservedDefinitionIds===void 0?{}:{definitionIds:e.reservedDefinitionIds},...e.reservedToolNames===void 0?{}:{toolNames:e.reservedToolNames}}),n}function hr(e){let n=[],t=[],i=[];for(let r of e.listMcpApps())typeof r.appId=="string"&&n.push(r.appId),r.definition&&typeof r.definition.id=="string"&&t.push(r.definition.id);for(let r of e.listMcpAppTools())typeof r.name=="string"&&i.push(r.name);return {appIds:n,definitionIds:t,toolNames:i}}function he(e,n){e.diagnostic||(e.diagnostic=st(n,e.source,e.relativePath,e.identity?.pluginId));}function Zd(e,n){let t=new Set,i=new Map;for(let o of e){let s=o.identity?.pluginId;if(s===void 0)continue;let a=i.get(s)??[];a.push(o),i.set(s,a);}for(let o of i.values()){if(o.length<2)continue;let s=o.filter(d=>d.provenance!==void 0);if(s.length>0){let d=o.find(c=>n.has(c));if(d){for(let c of s)t.add(c);for(let c of o)c!==d&&c.provenance===void 0&&he(c,"RESERVED_ID");continue}for(let c of o)c.provenance===void 0&&he(c,"RESERVED_ID");if(s.length>1)for(let c of s)he(c,"DUPLICATE_ID");continue}let a=o.filter(d=>d.source==="apps");if(a.length>1){for(let d of a)he(d,"DUPLICATE_ID");for(let d of o.filter(c=>c.source==="skills"))he(d,"DUPLICATE_ID");}else for(let d of o.filter(c=>c.source==="skills"))he(d,"DUPLICATE_ID");}let r=new Map;for(let o of e){if(o.diagnostic?.code==="RESERVED_ID"||t.has(o)||o.provenance===void 0&&!n.has(o)&&i.get(o.identity?.pluginId??"")?.some(d=>d.provenance!==void 0))continue;let s=o.identity?.definitionKey;if(s===void 0)continue;let a=r.get(s)??[];a.push(o),r.set(s,a);}for(let o of r.values())if(o.length>1)for(let s of o)he(s,"DUPLICATE_ID");return t}function Qd(e,n,t){let i=new Set,r=new Set,o=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"&&r.add(p);for(let p of l.toolNames??[])typeof p=="string"&&o.add(p);}for(let l of e){let p=l.candidate;if(!p)continue;if(i.has(p.pluginId)||r.has(p.definitionId)){he(l,"RESERVED_ID");continue}[p.toolNames.read,p.toolNames.action].filter(f=>f!==void 0).some(f=>o.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{Ko(p),c.add(l);}catch(u){he(l,u instanceof De?Dr(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=dr.indexOf(n.source)-dr.indexOf(t.source);return i!==0?i:On(n.relativePath,t.relativePath)})}function F(e,n,t){e.diagnostic=st(n,e.source,e.relativePath,e.identity?.pluginId,t);}async function _r(e,n,t){let i=$e(t,{mode:"local"});if(!i.ok&&i.parseFailure){F(n,fr(i.rejection.code),ur(i.rejection));return}let r=vd(i.identity);if(n.bundleIdentity===void 0)n.identity=r;else if(r?.pluginId!==n.bundleIdentity.appId||r.definitionKey!==`${n.bundleIdentity.definitionId}\0${String(n.bundleIdentity.version)}`){F(n,"BUNDLE_INTEGRITY");return}if(!i.ok&&i.builtinOnly){F(n,"RESERVED_ID");return}if(!i.ok){F(n,fr(i.rejection.code),ur(i.rejection));return}let o=i.manifest,s={pluginId:o.pluginId,definitionKey:`${o.definitionId}\0${String(o.version)}`};if(n.bundleIdentity===void 0&&(n.identity=s),o.actions.length>0)try{ii(o.actions.map(L=>({actionId:L.actionId,inputSchema:L.inputSchema})));}catch(L){if(L instanceof De){F(n,Dr(L.code));return}throw L}let a;try{a=await at(e,n,"ui/index.html",cn);}catch(L){F(n,Ke(se(L),"entry"));return}if(a.byteLength>cn){F(n,"LIMIT_EXCEEDED");return}let d;try{d=Tr(a);}catch{F(n,"ENTRY_INVALID");return}if(a.byteLength===0||d.length===0){F(n,"ENTRY_INVALID");return}let c=Di.createHash("sha256").update(a).digest("hex");if(o.entryHash!==void 0&&o.entryHash!==c){F(n,"ENTRY_INVALID");return}let l={},p,u;if(o.initialState!==void 0){try{p=await at(e,n,"ui/state.json",1048576);}catch(L){F(n,Ke(se(L),"initial"));return}if(p.byteLength>1048576){F(n,"LIMIT_EXCEEDED");return}try{let L=xd(p),W=o.dataPaths??[],de=Bt(L,W);l=fe(de,0,W),Ze(l);}catch{F(n,"INITIAL_STATE_INVALID");return}if(u=Di.createHash("sha256").update(p).digest("hex"),o.initialState.hash!==void 0&&o.initialState.hash!==u){F(n,"INITIAL_STATE_INVALID");return}}let f={...o,entryHash:c,...o.initialState===void 0?{}:{initialState:{path:"ui/state.json",hash:u}}},g=gn(f),_=Wd(f,a,p??new Uint8Array),P;try{P=Jd(g,_);}catch(L){if(L instanceof re){F(n,jd(L));return}throw L}let C;if(n.bundleLineage!==void 0){let L=n.bundleLineage[n.bundleLineage.length-1];if(!L){F(n,"LINEAGE_INVALID");return}let{legacy:W,...de}=L.definition,{hash:J,...Se}=P;if(ne(de)!==ne(Se)){F(n,"LINEAGE_STALE");return}if(W!==void 0&&(P={...P,legacy:W}),W!==void 0)try{P={...P,hash:pe(P)},ye(P);}catch{F(n,"LINEAGE_INVALID");return}C=n.bundleLineage;}if(n.bundleIdentity!==void 0&&n.bundleIdentity.appId!==o.pluginId){F(n,"BUNDLE_INTEGRITY");return}if(n.bundleIdentity!==void 0&&(n.bundleIdentity.definitionId!==P.id||n.bundleIdentity.version!==P.version||n.bundleIdentity.definitionHash!==P.hash)){F(n,"LINEAGE_STALE");return}let U=Rd(o.pluginId),N=o.actions.length===0?{read:U.read}:U,w=Je(g),j=Je(f),D=Je(P),b=Je({...g.handlers}),O=yr(a),y=p===void 0?void 0:yr(p),I=Object.freeze({...n.provenance===void 0?{}:{provenance:n.provenance},entry:Object.freeze({path:"ui/index.html",hash:c,bytes:O}),...y===void 0?{}:{initialState:Object.freeze({path:"ui/state.json",hash:u,bytes:y})}}),h={appId:o.pluginId,pluginId:o.pluginId,definitionId:o.definitionId,version:o.version,...i.releaseVersion===void 0?{}:{releaseVersion:i.releaseVersion},manifestFile:i.file,...i.mcpb===void 0?{}:{mcpb:Je(i.mcpb)},relativePath:n.relativePath,manifest:j,normalized:w,name:o.name,description:o.description,...o.icon===void 0?{}:{icon:o.icon},...o.tone===void 0?{}:{tone:o.tone},definition:D,handlers:b,resources:I,html:d,entryBytes:O,entryHash:c,initialState:Je(l),...y===void 0?{}:{initialStateBytes:y},...u===void 0?{}:{initialStateHash:u},sourceHash:_,toolNames:Object.freeze(N)},E=n.provenance===void 0?{...h,source:n.source}:{...h,provenance:n.provenance,lineage:C??[]};n.candidate=Object.freeze(E),Kd(o)&&F(n,"EXEC_DENIED");}async function Or(e,n){let t={};for(let i of q)try{t[i]=await at(e,n,i,262144);}catch(r){if(se(r)==="NOT_FOUND")continue;return {files:t,failure:Ke(se(r),"manifest")}}if(t[G]!==void 0)try{t[B]=await at(e,n,B,262144);}catch(i){if(se(i)!=="NOT_FOUND")return {files:t,failure:Ke(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 Or(e,n);if(i!==void 0){F(n,i);return}let r=t[G];return r!==void 0&&!Kt(r)&&(delete t[G],delete t[B]),_i(t)?t:void 0}function tp(e,n,t,i=Od,r=false,o=new Set){let s=ep(e),a=Zd(s,o),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=r?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??tr,options:t}}async function Rr(e,n,t){if(typeof e!="string"||e.length===0)throw new TypeError("workspaceRoot must be explicit");let{fs:i,options:r}=op(n,t),o=r.clock??Hd,s=o(),a=await cr(r.productBundle,i,s,o),d=o(),c=BigInt(Date.now())*1000000n,l=[],p=0,u,f=false,g,_;if(r.scanCache!==void 0&&typeof i.getRootIdentity=="function"&&typeof i.fingerprintVerifiedFile=="function")try{_=await i.getRootIdentity(e),g=qo(r.scanCache,_),g.scanStartedAtNs=c;}catch(D){if(se(D)!=="NOT_FOUND")throw D}let P=g!==void 0&&r.productBundle===void 0&&a.packages.length===0&&a.diagnostics.length===0,C=new Set,U=true;l.push(...a.diagnostics.map(D=>({source:D.source,root:r.productBundle?.root??e,name:"",relativePath:D.relativePath,diagnostic:D})));let N=a.reservedIds;a.incomplete&&(u="time_limit");for(let D of a.packages){if(!Re(d,o)){f=true,u="time_limit";break}let b=D.indexEntry,O=b.packageDir,y=D.files===void 0?void 0:Vd(O,D.files),I=a.indexHash===void 0?void 0:bo(Object.freeze({kind:"bundled",launcher:b.launcher!==false,indexHash:a.indexHash,packageDir:O,appId:b.appId,definitionId:b.definition.id,version:b.definition.version,definitionHash:b.definition.hash,files:b.files}),y),h={source:"bundled",root:r.productBundle?.root??e,name:O.slice(5),relativePath:O,...I===void 0?{}:{provenance:I},...D.files===void 0?{}:{pinnedFiles:D.files},...D.lineage===void 0?{}:{bundleLineage:D.lineage},bundleIdentity:{appId:b.appId,definitionId:b.definition.id,version:b.definition.version,definitionHash:b.definition.hash},identity:Fd(b)};if(l.push(h),p+=1,D.failureCode!==void 0){F(h,D.failureCode);continue}if(D.files?.has(B)===true){F(h,"EXEC_DENIED",{reason:{path:"",rule:"bundled-tool-mode-unsupported",file:B}});continue}let E={};for(let L of q){let W=D.files?.get(L);W!==void 0&&(E[L]=W);}if(!_i(E)){F(h,"BUNDLE_INTEGRITY");continue}if(await _r(i,h,E),!Re(d,o)){f=true,u="time_limit";break}}let w=[{source:"apps",directory:"apps"},{source:"skills",directory:"skills"}];e:for(let D of w){let{source:b,directory:O}=D,y;try{y=await Yd(i,e,O);}catch(h){if(se(h)==="NOT_FOUND")continue;P=false,U=false,l.push({source:b,root:e,name:"",relativePath:b,diagnostic:st(Ke(se(h),"manifest"),b,b)});continue}let I=y.filter(h=>h.kind==="directory"||h.kind==="symlink").filter(h=>Ud(h.name)).map(h=>({source:b,root:e,name:h.name,relativePath:Cd(b,h.name)})).sort((h,E)=>On(h.relativePath,E.relativePath));for(let h of I){let E={...h};if(l.push(E),_!==void 0?C.add(br(_,E)):P=false,!Re(d,o)){f=true,u="time_limit";break e}let L;if(g!==void 0&&_!==void 0){try{let J=await Gd(i,e,_,E,g,c,d,o);if(J.timeLimitReached){f=!0,u="time_limit";break e}E.scanContext=J.context,L=J.memo;}catch(J){P=false,F(E,Ke(se(J),"manifest"));continue}L===void 0&&(P=false);}if(L!==void 0){if(E.candidate=L.candidate,E.diagnostic=L.diagnostic,E.identity=L.identity,b==="skills"&&L.candidate===void 0&&L.diagnostic===void 0)continue;if(p>=64){F(E,"LIMIT_EXCEEDED");continue}if(h.relativePath.split("/").length-1>2){F(E,"LIMIT_EXCEEDED");continue}if(p+=1,!Re(d,o)){f=true,u="time_limit";break e}continue}let W;if(b==="skills"&&(W=await np(i,E),W===void 0)){E.diagnostic===void 0&&hi(E);continue}if(p>=64){F(E,"LIMIT_EXCEEDED");continue}if(h.relativePath.split("/").length-1>2){F(E,"LIMIT_EXCEEDED");continue}if(!Re(d,o)){f=true,u="time_limit";break e}if(p+=1,W===void 0){let J=await Or(i,E);if(J.failure!==void 0||!_i(J.files)){F(E,J.failure??Ke("NOT_FOUND","manifest")),hi(E);continue}W=J.files;}if(await _r(i,E,W),hi(E),!Re(d,o)){f=true,u="time_limit";break e}}}if(g!==void 0&&_!==void 0){let D=[...C].sort(On),b=g.lastCandidateKeys,O=b!==void 0&&b.length===D.length&&b.every((I,h)=>I===D[h]);if(P=P&&O,U&&!f&&u===void 0)for(let I of g.candidates.keys())try{JSON.parse(I)[0]===_.realPath&&!C.has(I)&&g.candidates.delete(I);}catch{g.candidates.delete(I);}let y=[...g.candidates.keys()].filter(I=>{try{return JSON.parse(I)[0]===_.realPath}catch{return false}});P=P&&y.length===C.size&&y.every(I=>C.has(I))&&!f&&u===void 0,g.lastCandidateScanUnchanged=P,U&&!f&&u===void 0&&(g.lastCandidateKeys=Object.freeze(D));}f&&l.push({source:"apps",root:e,name:"",relativePath:"apps",diagnostic:st("DISCOVERY_TIME_LIMIT","apps","apps")});let j=Qd(l,r,N);return tp(l,u,a.indexHash,N,r.productBundle!==void 0,j)}var Od,mi,dr,wd,Ar,$d,Ir,wr=V(()=>{m();Be();Cn();Me();Xt();Ve();qn();Xo();Gn();Zo();li();Wn();gi();gi();Od=ot([]),mi="crewx_local_app_";dr=["bundled","apps","skills"],wd=new TextDecoder("utf-8",{fatal:true});Ar=["","/ui"],$d=["/dist"],Ir=2000000000n;});m();Xt();m();Rt();m();var fo="SKILL.md",_c=/^---\s*\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;function yo(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function Ec(e){return e.isDirectory()||e.isSymbolicLink()}function ho(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(!yo(i))return {frontmatter:{},readable:!0,valid:!1,hasFrontmatter:!0};let r=yo(i.metadata)?i.metadata:void 0;return {frontmatter:{...typeof i.name=="string"?{name:i.name}:{},...typeof(r?.version??i.version)=="string"?{version:r?.version??i.version}:{},...typeof i.description=="string"?{description:i.description}:{}},readable:!0,valid:!0,hasFrontmatter:!0}}catch{return {frontmatter:{},readable:true,valid:false,hasFrontmatter:true}}}function Tc(e){return [ae.join(e,fo),ae.join(e,"skill",fo)]}function Ao(e,n){if(!ho(e))return null;for(let t of Tc(e)){if(!ee.existsSync(t))continue;let r=Yt(t).frontmatter;return {name:r.name??n,...r.version===void 0?{}:{version:r.version},...r.description===void 0?{}:{description:r.description},skillMdPath:t,dir:e}}return null}function Io(e){try{return ee.readdirSync(e,{withFileTypes:!0}).filter(Ec)}catch{return []}}function go(e,n,t){!e||n.has(e.name)||(n.add(e.name),t.push(e));}function _o(e){let n=[],t=new Set;for(let i of e)if(ho(i))for(let r of Io(i)){if(r.name.startsWith("@")){let o=ae.join(i,r.name);for(let s of Io(o))go(Ao(ae.join(o,s.name),s.name),t,n);continue}go(Ao(ae.join(i,r.name),r.name),t,n);}return n.sort((i,r)=>i.name.localeCompare(r.name))}m();zn();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 Eo(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 To(e){if(!Array.isArray(e))return;let n=q.filter(t=>e.includes(t));return n.length>0?n:void 0}wr();var sp=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/;function lt(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 r=JSON.stringify({screenHash:n,skillHash:i});return Di.createHash("sha256").update(r,"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(ut(e)),i=cp(n),r=new Uint8Array(t.byteLength+1+i.byteLength);return r.set(t,0),r[t.byteLength]=0,r.set(i,t.byteLength+1),Di.createHash("sha256").update(r).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 ut(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 dt(e,n){let t=new TextEncoder().encode(e),i=new TextEncoder().encode(n),r=Math.min(t.byteLength,i.byteLength);for(let o=0;o<r;o+=1){let s=t[o]-i[o];if(s!==0)return s}return t.byteLength-i.byteLength}function kr(e,n){let t=ae.relative(e,n).split(ae.sep).join("/");return !t||t===".."||t.startsWith("../")||ae.isAbsolute(t)?null:ut(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 xr(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??ke,...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 vr(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,r=n&&!i?["screen","skill"]:["screen"],o=pp(t),s=lt(n?{screenHash:o.hash,skillHash:n.skillHash}:{screenHash:o.hash}),a=t.description||n?.skill.description||"",d=t.releaseVersion??String(t.version),c={appId:t.pluginId,name:t.name,description:a,version:d,...vr(r),definition:o,...n===void 0||i?{}:{skillName:n.skill.name},...i?{provenance:t.provenance}:{localDefinitionRef:xr(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:r,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},...vr(["skill"]),skillName:e.skill.name,localDefinitionRef:xr(e.packageRoot),definitionHash:lt({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,r){let o=Eo(r?.reason),s=To(r?.files);return Object.freeze({code:e,source:n,relativePath:yp(t),...i===void 0?{}:{appId:i},...o===void 0?{}:{reason:o},...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 jr(e){return Q(e.code,e.source,e.relativePath,e.pluginId,e)}function Ap(e,n){let t=kr(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 r=Yt(n.skillMdPath);if(!r.readable)return {diagnostic:Q("SKILL_READ_FAILED",i,t)};if(!r.valid)return {diagnostic:Q("SKILL_INVALID",i,t)};let o=Ip(n.dir,n.skillMdPath);if(!o)return {diagnostic:Q("PATH_ESCAPED",i,t)};try{let s=new Uint8Array(ee.readFileSync(n.skillMdPath));return {skill:n,packageRoot:t,relativeSkillPath:o,skillHash:lt({relativePath:o,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 ut(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??ke,...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??Di.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 ut(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??[],r=new Map;for(let s of i){let a=hp(s);if(!a){t.push(Q("INSTALLED_IDENTITY_MISMATCH","installed","installed"));continue}let d=r.get(a);if(d&&JSON.stringify(d)!==JSON.stringify(s)){t.push(Q("INSTALLED_IDENTITY_MISMATCH","installed",a));continue}r.set(a,s);}let o=new Map;for(let s of e)s.packageRoot!==void 0&&o.set(s.packageRoot,s);for(let[s,a]of r){let d=o.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 r of e){let o=t.get(r.appId)??[];o.push(r),t.set(r.appId,o);}let i=new Set;for(let r of t.values()){if(r.length<2)continue;let o=r.some(s=>s.source==="builtin")?"builtin":r.some(s=>s.source==="bundled")?"bundled":void 0;if(o==="bundled"){let s=r.filter(a=>a.source==="apps"&&a.summary.definition!==void 0);if(s.length===1){for(let a of r)a.source==="bundled"?i.add(a):a!==s[0]&&(i.add(a),n.push(Q("RESERVED_ID",a.source,pt(a),a.appId)));continue}}if(o!==void 0){let s=r.filter(a=>a.source===o);for(let a of r.filter(d=>d.source!==o))i.add(a),n.push(Q("RESERVED_ID",a.source,pt(a),a.appId));if(s.length>1)for(let a of s)i.add(a),n.push(Q("DUPLICATE_ID",a.source,pt(a),a.appId));continue}for(let s of r)i.add(s),n.push(Q("DUPLICATE_ID",s.source,pt(s),s.appId));}return e.filter(r=>!i.has(r))}function pt(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(jr)}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 Fr(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 Rr(e,Dp(n,t)),r=n.registeredProductBundle??i.productBundleSnapshotMetadata,o=[ae.join(e,"skills"),ae.join(e,"node_modules"),ae.join(e,"apps")],s=[],a=[],d=[],c=new Set;for(let I of o)for(let h of _o([I])){let E=kr(e,h.dir);(E===null||!c.has(E))&&(d.push(h),E!==null&&c.add(E));}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),_=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&&_.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 P=new Map(a.map(I=>[I.packageRoot,I])),C=[];for(let I of l.values()){let h=I.candidate.provenance===void 0?P.get(I.packageRoot):void 0,E=lp(I,h);C.push({...E.packageRoot===void 0?{}:{packageRoot:E.packageRoot},source:E.source,appId:E.appId,summary:E.summary});}let U=new Set([...l.values()].filter(I=>I.candidate.provenance===void 0).map(I=>I.packageRoot)),N=r===void 0?new Set:new Set(i.diagnostics.filter(I=>I.code==="RESERVED_ID"&&I.source!=="bundled").map(I=>I.relativePath)),w=new Set(r?.reservedAppIds??[]);for(let I of a){let h=up(I);if(!(U.has(I.packageRoot)||N.has(I.packageRoot))){if(w.has(h.appId)){s.push(Q("RESERVED_ID",I.source,I.packageRoot,h.appId));continue}C.push({packageRoot:h.packageRoot,source:h.source,appId:h.appId,summary:h.summary});}}let j=[...Pp(i.diagnostics,new Set(a.map(I=>I.packageRoot))),...s,...n.registeredProductBundle?.diagnostics.filter(I=>I.source==="bundled").map(jr)??[]],D=[];if(t)for(let I of t.listMcpApps()){let h=gp(I);"diagnostic"in h?j.push(h.diagnostic):D.push(h);}let b=Tp([...C,...D],j);Ep(b,n,j);let O=b.map(I=>I.summary).sort((I,h)=>dt(I.appId,h.appId)),y=[...j].sort((I,h)=>dt(I.relativePath,h.relativePath)||dt(I.code,h.code)||dt(I.appId??"",h.appId??""));return Object.freeze({items:Object.freeze(O),diagnostics:Object.freeze(y)})}m();m();m();function bp(e){let n=r=>r.replace(/[.+^${}()|[\]\\]/g,"\\$&"),i=e.split("/").map(r=>r==="**"?".*":r.split("*").map(n).join("[^/]*"));return new RegExp(`^${i.join("\\/")}$`)}function ln(e,n){try{return bp(n).test(e)}catch{return false}}function ft(e,...n){let t=e.split("/");if(t.length<n.length)return false;let i=t.length-n.length;return n.every((r,o)=>ln(t[i+o],r))}function Sp(e,n){return e.split("/").some(t=>ln(t,n))}var Vr=[{label:".env*",test:e=>ln(e,".env*")},{label:".git/",test:(e,n,t)=>t&&e===".git"},{label:"memory/",test:(e,n,t)=>t&&e==="memory"},{label:"*.key",test:e=>ln(e,"*.key")},{label:"*.pem",test:e=>ln(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&&ft(n,".crewx","threads")},{label:".crewx/crewx.db",test:(e,n,t)=>!t&&ft(n,".crewx","crewx.db")},{label:".crewx/*.log",test:(e,n,t)=>!t&&ft(n,".crewx","*.log")},{label:".crewx/publish/",test:(e,n,t)=>t&&ft(n,".crewx","publish")},{label:".crewx/",test:(e,n)=>Sp(n,".crewx")}];function un(e,n,t){for(let i of Vr)if(i.test(e,n,t))return i.label;return null}m();var we=class extends Error{constructor(t,i){super(`publish: [${t}]${i?` ${i}`:""}`);this.code=t;}code;name="PublishError"};function T(e,n){return new we(e,n)}function Br(e,n){if(!n||/[\\\u0000]/.test(n)||ae__namespace.posix.isAbsolute(n)||n.split("/").some(f=>!f||f==="."||f===".."))throw T("PACKAGE_PATH_TRAVERSAL","package root must be a safe workspace-relative path");let t=ae__namespace.resolve(e),i=ae__namespace.resolve(t,...n.split("/"));if(!i.startsWith(`${t}${ae__namespace.sep}`))throw T("PACKAGE_PATH_TRAVERSAL","package root escaped the workspace");function r(f,g){let _;try{_=ee__namespace.lstatSync(f);}catch{throw T("PACKAGE_FILE_INVALID",`package directory is missing: ${g}`)}if(_.isSymbolicLink())throw T("PACKAGE_SYMLINK",`symlink is not publishable: ${g}`);if(!_.isDirectory())throw T("PACKAGE_FILE_INVALID",`not a package directory: ${g}`)}r(t,".");let o=t,s="",a=null;for(let f of n.split("/"))o=ae__namespace.join(o,f),s=s?`${s}/${f}`:f,r(o,s),a??=un(f,s,true);let d=[],c=[];function l(f,g){r(f,g);let _=ee__namespace.readdirSync(f,{withFileTypes:true});for(let P of _){let C=`${g}/${P.name}`,U=ae__namespace.join(f,P.name);if(P.isSymbolicLink())throw T("PACKAGE_SYMLINK",`symlink is not publishable: ${C}`);let N=un(P.name,C,P.isDirectory());N?c.push({path:C,rule:N}):P.isDirectory()?l(U,C):P.isFile()&&d.push(C);}}a?c.push({path:n,rule:a}):l(i,n);let p=new TextEncoder,u=(f,g)=>Buffer.compare(p.encode(f),p.encode(g));return d.sort(u),c.sort((f,g)=>u(f.path,g.path)),{included:d,excluded:c}}function Hr(e){let n=[],t=[];function i(r,o,s){let a;try{a=ee__namespace.readdirSync(r,{withFileTypes:!0});}catch{return}a.sort((d,c)=>d.name.localeCompare(c.name));for(let d of a){let c=o?`${o}/${d.name}`:d.name,l=ae__namespace.join(r,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??un(d.name,c,false);u?t.push({path:c,rule:u}):t.push({path:c,rule:"symlink"});continue}if(d.isDirectory()){let p=s??un(d.name,c,true);i(l,c,p);continue}if(d.isFile()){let p=s??un(d.name,c,false);p?t.push({path:c,rule:p}):n.push(c);}}}return i(e,"",null),n.sort(),t.sort((r,o)=>r.path<o.path?-1:r.path>o.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 Ni(e,n,t){let i=[];for(let r of n){let o=ae__namespace.join(e,r),s;try{let d=t?.get(r);s=d===void 0?ee__namespace.readFileSync(o):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:r,line:c+1,rule:l});});}return i}m();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 r=i;return {name:typeof r.name=="string"?r.name:void 0,version:typeof r.version=="string"?r.version:void 0,description:typeof r.description=="string"?r.description:void 0,requiredEnv:r.requiredEnv,crewxMinVersion:typeof r.crewxMinVersion=="string"?r.crewxMinVersion:void 0}}function Cp(e){return Di__namespace.createHash("sha256").update(e).digest("hex")}function Jr(e){let n;try{n=ee__namespace.lstatSync(e);}catch{throw T("PACKAGE_FILE_INVALID",`file is not readable: ${ae__namespace.basename(e)}`)}if(n.isSymbolicLink())throw T("PACKAGE_SYMLINK","symlink content is not publishable");if(!n.isFile())throw T("PACKAGE_FILE_INVALID","only regular files are publishable");return Di__namespace.createHash("sha256").update(new Uint8Array(ee__namespace.readFileSync(e))).digest("hex")}function Up(e,n){let t=new TextEncoder().encode(e),i=new TextEncoder().encode(n),r=Math.min(t.byteLength,i.byteLength);for(let o=0;o<r;o+=1){let s=t[o]-i[o];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 T("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 T("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),r=i.name??ae__namespace.basename(e);if(!Gr.test(r))throw new Error(`publish: invalid name "${r}" \u2014 must match ${Gr} (lowercase letters, numbers, hyphen only)`);let o=t.version??i.version;if(!o)throw new Error("publish: version is required \u2014 set crewx.yaml metadata.version or pass opts.version");Xr(o);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:r,version:o,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 T("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 T("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 T("APP_UI_MANIFEST_INVALID","screen App is missing manifest.json or ui-plugin.json");if(s&&!a)throw T("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 T("APP_UI_MANIFEST_INVALID","screen App is missing ui/index.html")}if(t.includes("skill")&&!n.includedFiles.includes(`${i}SKILL.md`))throw T("APP_SKILL_MISSING","skill capability requires package-root SKILL.md");let r=new Set,o=n.includedFiles.map(s=>{if(Kr(s),!s.startsWith(i))throw T("PACKAGE_PATH_TRAVERSAL","App manifest file is outside packageRoot");let a=n.generatedFiles?.get(s);return a!==void 0&&r.add(s),{path:s,sha256:a===void 0?Jr(ae__namespace.join(e,s)):Cp(a),...a===void 0?{}:{generated:true}}}).sort((s,a)=>Up(s.path,a.path));if(r.size>0&&(r.size!==1||!r.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:o,requiredEnv:[]}}m();function Zr(e){return Di__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(r=>r===".."||r.length===0))throw T("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 T("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 T("PACKAGE_FILE_INVALID","manifest file is missing")}if(i.isSymbolicLink())throw T("PACKAGE_SYMLINK","symlink content is not publishable");if(!i.isFile())throw T("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 r=ae__namespace.join(i,`${n.name}-${n.version}.tgz`),o=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 T("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 T("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 T("PACKAGE_STAGED_BYTES_MISMATCH","workspace source changed before staging")}let p=l??Qr(e,c.path);if(Zr(p)!==c.sha256)throw T("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:o,cwd:s,portable:!0,noMtime:!0},["manifest.json",...d]),ee__namespace.renameSync(o,r);}finally{try{ee__namespace.rmSync(o,{force:!0});}catch{}ee__namespace.rmSync(s,{recursive:true,force:true});}return r}m();m();var fn="/api/v1";var Fp=201,Vp=200,Bp=409,bi=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 Rn(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,r=[t.code,t.message,i?.code,i?.message];for(let o of r){if(typeof o!="string"||!Object.prototype.hasOwnProperty.call(rs,o))continue;let s=o,a=s==="APP_NAME_CONFLICT"?`marketplace name is already in use: ${n}`:void 0;return T(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,r=e.manifest.type==="app"?e.manifest:void 0,o=r!==void 0,s=r?.appId,a;try{a=await fetch(`${n}${fn}/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 Rn(a),c=Gp(d),l=Wp(d),p=o&&l!==void 0?l:i,u;if(a.status===Fp)u="created";else if(o&&a.status===Vp){if(c===void 0)throw T("PUBLISH_CONTENT_ID_MISSING","App republish did not return an opaque contentId");u="existing";}else if(a.status===Bp){if(o)throw as(d,i)??T("APP_NAME_CONFLICT",`marketplace name is already in use: ${i}`);u="existing";}else throw a.status===bi?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"&&!o){let b;try{b=await fetch(`${n}${fn}/publisher/items`,{method:"GET",headers:{Authorization:`Bearer ${e.accessToken}`}});}catch{throw new Error("publish: [E_NETWORK] Publisher items request failed (network)")}let O=await Rn(b);if(b.status!==200)throw new Error(`publish: [E_HTTP] Publisher items request failed \u2014 HTTP ${b.status}`);let I=ss(O,"publisher items",b.status)?.items;if(!Array.isArray(I))throw new Error(`publish: [E_MALFORMED] Publisher items response is malformed (expected data.items[]) \u2014 HTTP ${b.status}`);let h=I.find(E=>!E||typeof E!="object"?false:E.slug===i);if(!h||typeof h.version!="string")throw new Error(`publish: [E_MALFORMED] Publisher items response does not contain slug "${i}" \u2014 HTTP ${b.status}`);if(g=h.version,g!==e.manifest.version){let E;try{E=await fetch(`${n}${fn}/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(!E.ok)throw await Rn(E),E.status===bi?new Error(`publish: [E_AUTH_EXPIRED] Authentication is expired or missing \u2014 please log in again (HTTP ${E.status})`):E.status===403?new Error(`publish: [E_FORBIDDEN] Version update is forbidden; only the item owner can update an existing item (HTTP ${E.status})`):new Error(`publish: [E_HTTP] Version update failed \u2014 HTTP ${E.status}`);f="applied";}}let _=ee__namespace.readFileSync(e.tgzPath),P=Hp()?zp(_):_,C=new FormData;C.set("archive",new Blob([new Uint8Array(P)],{type:"application/gzip"}),`${p}-${e.manifest.version}.tgz`);let U=o&&c!==void 0?c:i,N;try{N=await fetch(`${n}${fn}/publisher/items/${encodeURIComponent(U)}/upload`,{method:"POST",headers:{Authorization:`Bearer ${e.accessToken}`},body:C});}catch{throw new Error("publish: [E_NETWORK] Upload request failed (network)")}if(N.status===bi)throw new Error("publish: [E_AUTH_EXPIRED] Authentication is expired or missing \u2014 please log in again (HTTP 401)");if(!N.ok){let b=await Rn(N);if(o){let O=as(b,p);if(O)throw O}throw new Error(`publish: [E_HTTP] Upload request failed \u2014 HTTP ${N.status}`)}let w=await Rn(N),j=ss(w,"upload",N.status),D=typeof j.contentId=="string"&&j.contentId.length>0?j.contentId:c;if(o&&D===void 0)throw T("PUBLISH_CONTENT_ID_MISSING","App upload did not return an opaque contentId");return {slug:p,version:e.manifest.version,...D===void 0?{}:{contentId:D},artifactChecksum:j.artifactChecksum,artifactSizeBytes:j.artifactSizeBytes,submitOutcome:u,versionUpdate:f,serverVersionBefore:g}}var Kp=1e4,Xp=100*1024*1024;function Si(e){return Di__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 wn(e,n){if(!n||n.includes("\\")||n.includes("\0")||ae__namespace.posix.isAbsolute(n)||n.split("/").some(o=>o===".."||o.length===0))throw T("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 T("PACKAGE_PATH_TRAVERSAL","workspace file path escaped the workspace root");let r;try{r=ee__namespace.lstatSync(t);}catch{throw T("PACKAGE_FILE_INVALID",`workspace file is missing: ${n}`)}if(r.isSymbolicLink())throw T("PACKAGE_SYMLINK",`symlink is not publishable: ${n}`);if(!r.isFile())throw T("PACKAGE_FILE_INVALID",`not a regular file: ${n}`);return new Uint8Array(ee__namespace.readFileSync(t))}function ds(e,n,t){let i=e??n;if(!Number.isSafeInteger(i)||i<=0)throw new we("PACKAGE_SIZE_LIMIT",`${t} must be a positive integer`);return i}function ls(e,n,t,i){let r=ds(t.maxFileCount??t.maxFiles,Kp,"max file count"),o=ds(t.maxTotalBytes??t.maxBytes,Xp,"max total bytes");if(n.length>r)throw new we("PACKAGE_SIZE_LIMIT",`package exceeds file count limit (${r})`);let s=0;for(let a of n){let d=i?.get(a);if(d!==void 0?s+=d.byteLength:s+=wn(e,a).byteLength,s>o)throw new we("PACKAGE_SIZE_LIMIT",`package exceeds byte limit (${o})`)}}function qp(e){return e.appId!==void 0||e.expectedDefinitionHash!==void 0}function Zp(e){let n=e.appId!==void 0,t=e.expectedDefinitionHash!==void 0;if(!n&&t)throw T("APP_ID_REQUIRED","appId is required with expectedDefinitionHash");if(n&&!t)throw T("APP_DEFINITION_HASH_REQUIRED","expectedDefinitionHash is required with appId");if(!n||!t)throw T("APP_ID_REQUIRED")}function Qp(e,n){let t=e.filter(i=>i.appId===n);if(t.length===0)throw T("APP_NOT_FOUND",`no publishable App matches ${n}`);if(t.length!==1)throw T("APP_AMBIGUOUS",`more than one App matches ${n}`);return t[0]}function el(e){let n=e.localDefinitionRef?.packageRoot;if(!n||!/^(?:apps|skills)\/[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(n))throw T("APP_PACKAGE_ROOT_INVALID","selected App is not rooted in apps/<safe-id> or skills/<safe-id>");return n}function Mi(e){let{path:n,rule:t}=e.reason;return `${e.code} at ${n===""?"<file>":n} (${t})`+(e.files.length>0?` [${e.files.join(", ")}]`:"")}function nl(e,n,t){let i=$e({[ce]:t},{mode:"published"});if(!i.ok)throw T("APP_UI_MANIFEST_INVALID",`generated ${ce} does not read: ${Mi(i.rejection)}`);if(sn(i.manifest)!==sn(n))throw T("APP_UI_MANIFEST_INVALID",`generated ${ce} normalizes to a different definition hash than the source`);let r=e[G];if(r===void 0)return;let o=e[B],s=$e({[G]:r,[ce]:t,...o===void 0?{}:{[B]:o}},{mode:"local"});if(!s.ok)throw T("APP_UI_MANIFEST_INVALID",Mi(s.rejection))}function tl(e,n,t,i){let r={};for(let f of q){let g=`${t}/${f}`;i.includes(g)&&(r[f]=wn(e,g));}let o=`${t}/${B}`;if(r[G]!==void 0&&i.includes(o)&&(r[B]=wn(e,o)),Object.keys(r).length===0)throw T("APP_UI_MANIFEST_INVALID","selected screen App has no package manifest.json or ui-plugin.json");let s=$e(r,{mode:"local"});if(!s.ok)throw T("APP_UI_MANIFEST_INVALID",Mi(s.rejection));if(s.manifest.pluginId!==n.appId)throw T("APP_DEFINITION_CONFLICT",`${s.file} identity no longer matches the selected App`);let a=r[ce],d=a===void 0?void 0:Si(a),c=`${t}/ui/index.html`;if(!i.includes(c))throw T("APP_UI_MANIFEST_INVALID","screen entry is outside package scope");let l=Si(wn(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 T("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 T("APP_INITIAL_STATE_OUT_OF_SCOPE","initialState reference is outside the selected package");let _=wn(e,g);p.initialState={...f,hash:Si(_)};}let u;try{let f=ze(p,{mode:"published"});u=new Uint8Array(Buffer.from(JSON.stringify(f),"utf8"));}catch(f){throw f instanceof re?T("APP_UI_MANIFEST_INVALID",f.code):T("APP_UI_MANIFEST_INVALID")}return nl(r,s.manifest,u),{bytes:u,...d===void 0?{}:{legacySourceHash:d}}}async function il(e,n){let{included:t,excluded:i}=Hr(e);ls(e,t,n);let r=Yr(e,t,{version:n.version}),o=Ni(e,t);return {plan:{manifest:r,included:t,excluded:i,secretFindings:o},archiveOptions:{}}}async function ol(e,n){Zp(n);let t=await Fr(e),i=Qp(t.items,n.appId);if(i.definitionHash!==n.expectedDefinitionHash)throw T("APP_DEFINITION_CONFLICT",`definitionHash changed for ${n.appId}`);let r=el(i),{included:o,excluded:s}=Br(e,r),a=new Map,d=new Map;if(i.capabilities.includes("screen")){let u=tl(e,i,r,o),f=`${r}/${ce}`;if(a.set(f,u.bytes),u.legacySourceHash!==void 0)d.set(f,u.legacySourceHash);else {o.push(f);let g=new TextEncoder;o.sort((_,P)=>Buffer.compare(g.encode(_),g.encode(P)));}}if(i.capabilities.includes("skill")&&!o.includes(`${r}/SKILL.md`))throw T("APP_SKILL_MISSING","skill capability requires package-root SKILL.md");ls(e,o,n,a);let c={appId:i.appId,version:n.version??"",description:i.description,capabilities:i.capabilities,packageRoot:r,...i.definition?.id===void 0?{}:{definitionId:i.definition.id},definitionHash:i.definitionHash,includedFiles:o,generatedFiles:a},l=qr(e,c),p=Ni(e,o,a);return {plan:{manifest:l,included:o,excluded:s,secretFindings:p},archiveOptions:{generatedFiles:a,sourceFileHashes:d}}}async function us(e,n){let t=ae__namespace.resolve(e);if(qp(n))return ol(t,n);if(n.expectedDefinitionHash!==void 0)throw T("APP_ID_REQUIRED");return il(t,n)}async function Zy(e,n={}){return (await us(e,n)).plan}function rl(e){let n=e.map(t=>`${t.path}:${t.line} (${t.rule})`).join(", ");throw new we("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&&rl(i.plan.secretFindings);let r=await os(t,i.plan.manifest,i.archiveOptions);return {manifest:i.plan.manifest,tgzPath:r}}async function Qy(e,n={}){return fs(e,n)}async function eA(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=Vr;exports.MARKETPLACE_API_PREFIX=fn;exports.PublishError=we;exports.packApp=eA;exports.packPublish=fs;exports.packTemplate=Qy;exports.planPublish=Zy;exports.uploadToMarketplace=Jp;
1
+ 'use strict';var Di=require('crypto'),net=require('net'),ee=require('fs'),promises=require('fs/promises'),ae=require('path'),Xr=require('js-yaml'),is=require('os'),rs=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 Di__namespace=/*#__PURE__*/_interopNamespace(Di);var ee__namespace=/*#__PURE__*/_interopNamespace(ee);var ae__namespace=/*#__PURE__*/_interopNamespace(ae);var Xr__namespace=/*#__PURE__*/_interopNamespace(Xr);var is__namespace=/*#__PURE__*/_interopNamespace(is);var rs__namespace=/*#__PURE__*/_interopNamespace(rs);var V=(e,n)=>()=>(e&&(n=e(e=0)),n);var m=V(()=>{});var k,Un=V(()=>{m();k=class extends Error{constructor(t,i=t,o){super(i);this.code=t;this.currentRevision=o;}code;currentRevision;name="UiRuntimeError"};});function mt(e){return ms.test(e)||hs.test(e)}function ue(){throw new k("INPUT_INVALID","JSON value is not projection-safe")}function Ps(e){let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function It(e,n,t,i,o,r){if(n>i&&ue(),e===null||typeof e=="string"||typeof e=="boolean")return typeof e=="string"&&(_s.test(e)||Ts.test(e)&&!bs(o,r)||Es.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(c=>It(c,n+1,t,i,o,r));Ps(s)||ue();let a={};for(let[c,d]of Object.entries(e))mt(c)&&ue(),a[c]=It(d,n+1,t,i,[...o,c],r);return a}finally{t.delete(s);}}function fe(e,n=0,t=[]){(!Number.isInteger(n)||n<0||n>Ds)&&ue(),(!Array.isArray(t)||t.some(o=>typeof o!="string"))&&ue();let i=It(e,0,new Set,Ns+n,[],t);return (i===null||Array.isArray(i)||typeof i!="object")&&ue(),i}function qe(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 bs(e,n){if(e.length===0)return false;let t=e.join(".");return n.some(i=>qe(t,i))}function Ze(e){try{let n=JSON.stringify(e);return n===void 0&&ue(),n}catch{ue();}}function gt(e){return Array.isArray(e)?e.map(gt):e!==null&&typeof e=="object"?Object.fromEntries(Object.keys(e).sort().map(n=>[n,gt(e[n])])):e}function ne(e){return Ze(gt(e))}function ht(e){return Buffer.byteLength(e,"utf8")}var ms,hs,_s,Es,Ts,Ns,Ds,Me=V(()=>{m();Un();ms=/(?:proof|token|secret|password|cookie|authorization|private[_-]?key|stack|exception|plugin[_-]?text)/i,hs=/(?:url|uri|endpoint|path|file(?:name|path)?|cwd|shell|directory|dir|folder)$/i,_s=/<\/?[A-Za-z][^>]*>/,Es=/^(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)/,Ts=/^(?:https?|file|ftp|ws|wss):\/\//i;Ns=8,Ds=4;});var Li=V(()=>{m();Me();});var kn,_t=V(()=>{m();kn=["text/plain","application/json"];});var Ri=V(()=>{m();_t();});function Qe(e){return Ms.has(e)||Ls.test(e)||Rs.test(e)}var Oi,Ms,Ls,Rs,xn,yn,Ee,Et,Tt,Pt,Nt,Dt,Ve=V(()=>{m();Oi=["__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"],Ms=new Set(Oi),Ls=/(?:proof|token|secret|password|cookie|authorization|private[_-]?key|stack|exception|plugin[_-]?text)/i,Rs=/(?:url|uri|endpoint|path|file(?:name|path)?|cwd|shell|directory|dir|folder)$/i;xn=/^[A-Za-z0-9_]+$/,yn=/^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)*$/,Ee=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,Et=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/,Tt=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,Pt=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/,Nt=["blue","violet","emerald","amber","rose","sky","slate","indigo"],Dt=["inline","panel"];});function bt(e){return typeof e=="string"&&kn.includes(e)}var wi=V(()=>{m();_t();Ve();});function vn(e){if(!St(e))return false;let n=Object.keys(e);return !(n.some(t=>t!=="in"&&t!=="out")||n.length===0||Object.hasOwn(e,"in")&&!Os(e.in)||Object.hasOwn(e,"out")&&!ws(e.out))}function Os(e){return St(e)?Object.keys(e).every(t=>t==="mediaType"||t==="required")&&Object.hasOwn(e,"mediaType")&&bt(e.mediaType)&&(!Object.hasOwn(e,"required")||typeof e.required=="boolean"):false}function ws(e){return St(e)?Object.keys(e).every(t=>t==="mediaType"||t==="range")&&Object.hasOwn(e,"mediaType")&&bt(e.mediaType)&&(!Object.hasOwn(e,"range")||typeof e.range=="boolean"):false}function St(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}var Mt=V(()=>{m();Ri();wi();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 Di.createHash("sha256").update(ne(i)).digest("hex")}function Rt(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 k("DEFINITION_UNSUPPORTED","UI definition is invalid");if(e.sourceHash!==void 0&&(typeof e.sourceHash!="string"||!Us.test(e.sourceHash)))throw new k("DEFINITION_UNSUPPORTED","UI definition source hash is invalid");if(!/^[0-9a-f]{64}$/.test(e.hash)||pe(e)!==e.hash)throw new k("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=>!xs(i)))throw new k("DEFINITION_UNSUPPORTED","UI action declaration is invalid");if(t.confirmation!==void 0&&t.confirmation!=="none"&&t.confirmation!=="native")throw new k("DEFINITION_UNSUPPORTED","UI action confirmation is invalid");if(t.inputKeys&&(!Array.isArray(t.inputKeys)||t.inputKeys.some(i=>typeof i!="string"||!i)))throw new k("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 k("DEFINITION_UNSUPPORTED","UI action data input declaration is invalid");if(t.resultProjection&&Lt(t.resultProjection),t.content!==void 0&&!vn(t.content))throw new k("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 k("DEFINITION_UNSUPPORTED","UI action environment declaration is invalid")}if(e.renderer!==void 0&&(!e.renderer||e.renderer.length>128))throw new k("DEFINITION_UNSUPPORTED","UI definition renderer is invalid");if(e.surfaces&&(!Array.isArray(e.surfaces)||e.surfaces.some(n=>!n||n.length>64)))throw new k("DEFINITION_UNSUPPORTED","UI definition surfaces are invalid");if(e.usage!==void 0&&e.usage!=="card"&&e.usage!=="window")throw new k("DEFINITION_UNSUPPORTED","UI definition usage is invalid");if(e.detailPanel!==void 0&&typeof e.detailPanel!="boolean")throw new k("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 k("DEFINITION_UNSUPPORTED","UI definition displayModes are invalid");if(e.usage==="card"&&e.displayModes!==void 0)throw new k("DEFINITION_UNSUPPORTED","Card definitions cannot declare displayModes");if(e.usage==="window"&&e.detailPanel!==void 0)throw new k("DEFINITION_UNSUPPORTED","Window definitions cannot declare detailPanel");if(e.stateProjection&&Lt(e.stateProjection),e.summaryProjection){Lt(e.summaryProjection);let n=new Set(e.stateProjection?.allow??[]);if(e.summaryProjection.allow.some(t=>!n.has(t)))throw new k("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 k("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(ks(r,o==="readTool"),n.has(r.name))throw new k("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 k("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 k("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 k("DEFINITION_UNSUPPORTED","UI legacy agent access is invalid");if(e.legacy.actionTool!==void 0&&(!i||Object.keys(i).length===0))throw new k("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=>qe(t,i))))throw new k("DEFINITION_UNSUPPORTED","UI definition dataPaths are invalid")}}function ks(e,n){if(!e||typeof e!="object"||Array.isArray(e))throw new k("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 k("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 c=fe(a.structuredContent);if(ht(Ze(c))>4*1024)throw new Error("fixed result size")}}catch{throw new k("DEFINITION_UNSUPPORTED","UI legacy tool metadata is not projection-safe")}}function Lt(e){if(!Array.isArray(e.allow)||e.allow.some(n=>!/^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)*$/.test(n)))throw new k("DEFINITION_UNSUPPORTED","UI projection policy is invalid")}function xs(e){return e.length>0&&e.length<=128&&e!=="*"&&e!=="all"&&!/[/*]/.test(e)}var Us,Be=V(()=>{m();Me();Un();Mt();Us=/^[0-9a-f]{64}$/;});var B,en,Ot=V(()=>{m();B="dist/tools.json",en="dist/main.mjs";});var ke,wt=V(()=>{m();ke="window";});function Ci(e){if(!Array.isArray(e)||e.length===0)return false;let n=new Set;for(let t of e){if(!vs.some(i=>i===t)||n.has(t))return false;n.add(t);}return true}var vs,Ui=V(()=>{m();vs=["CREWX_APP_INSTANCE_ID","CREWX_THREAD_ID"];});function H(e){throw new Ct(e)}function Xs(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 Ys(e,n){let t=Object.getOwnPropertyDescriptor(e,n);return (!t||!("value"in t))&&H("CSP_ORIGIN_INVALID"),t.value}function jn(e,n){if(!Object.prototype.hasOwnProperty.call(e,n))return [];let t=Ys(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 qs(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 vi(e,n){/\s|\\/u.test(e)&&H("CSP_ORIGIN_INVALID");let t=$s.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("[")?Gs:Ws).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 d=a.endsWith(".")?a.slice(0,-1):a;(d.length===0||d.length>253)&&H("CSP_ORIGIN_INVALID"),d.split(".").some(p=>p.length>63||!Js.test(p))&&H("CSP_ORIGIN_INVALID");}let c=s.origin;return (c==="null"||!c.startsWith(`${i}://`))&&H("CSP_ORIGIN_INVALID"),{origin:c,hostname:a}}function Zs(e){let n=e.split(".").map(Number);return ((n[0]*256+n[1])*256+n[2])*256+n[3]}function ji(e,n,t){let i=4294967295<<32-t>>>0;return (e&i)===(n&i)}function Bi(e){let n=Zs(e);return ji(n,3221225472,24)?n!==3221225481&&n!==3221225482:Ks.some(([t,i])=>ji(n,t,i))}function Qs(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 ea(e){let n=Qs(e),t=Number(n>>112n),i=Number(n>>96n&0xffffn);if(n>>32n===0xffffn){let o=Number(n&0xffffffffn);return Bi([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 na(e,n){let t=e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e,i=net.isIP(t);if(i===4)return Bi(t);if(i===6)return ea(t);let o=e.toLowerCase().replace(/\.$/,"");return !o||!o.includes(".")||n.has(o)?true:zs.some(r=>o===r||o.endsWith(`.${r}`))}function Fi(e){return Object.freeze([...new Set(e.map(n=>n.origin))].sort())}function Vi(e){return JSON.stringify({baseUriDomains:[],connectDomains:e.connectDomains,declared:e.declared,frameDomains:e.frameDomains,resourceDomains:[]})}function Hi(e,n={}){if(e===void 0){let f=Vi({declared:false,connectDomains:[],frameDomains:[]});return Object.freeze({declared:false,connectDomains:Object.freeze([]),frameDomains:Object.freeze([]),resourceDomains:Object.freeze([]),baseUriDomains:Object.freeze([]),cspHash:Di.createHash("sha256").update(f,"utf8").digest("hex")})}Xs(e)||H("CSP_ORIGIN_INVALID");let t=Reflect.ownKeys(e);t.some(f=>typeof f!="string")&&H("CSP_ORIGIN_INVALID"),t.some(f=>!Hs.has(f))&&H("CSP_AXIS_UNKNOWN");let i=jn(e,"connectDomains"),o=jn(e,"frameDomains"),r=jn(e,"resourceDomains"),s=jn(e,"baseUriDomains");(r.length>0||s.length>0)&&H("CSP_AXIS_UNSUPPORTED"),(qs(e)>Fs||i.length>xi||o.length>xi||i.length+o.length>Vs||[...i,...o].some(f=>new TextEncoder().encode(f).byteLength>Bs))&&H("CSP_LIMIT_EXCEEDED");let c=i.map(f=>vi(f,"connectDomains")),d=o.map(f=>vi(f,"frameDomains")),l=new Set((n.runtimeHostnames??[]).map(f=>f.toLowerCase().replace(/\.$/,"")));[...c,...d].some(f=>na(f.hostname,l))&&H("CSP_ORIGIN_FORBIDDEN");let p={declared:true,connectDomains:Fi(c),frameDomains:Fi(d)},u=Vi(p);return Object.freeze({...p,resourceDomains:Object.freeze([]),baseUriDomains:Object.freeze([]),cspHash:Di.createHash("sha256").update(u,"utf8").digest("hex")})}var Fs,xi,Vs,Bs,Hs,zs,$s,Gs,Ws,Js,Ks,Ct,zi=V(()=>{m();Fs=4096,xi=16,Vs=32,Bs=512,Hs=new Set(["connectDomains","frameDomains","resourceDomains","baseUriDomains"]),zs=["localhost","local","internal","home.arpa","test","example","invalid","onion","lan","corp","home","intranet","private","localdomain"],$s=/^(https|wss):\/\/([^/?#]+)$/i,Gs=/^\[[^\]]+\](?::[0-9]+)?$/,Ws=/^[^:\[\]]+(?::[0-9]+)?$/,Js=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/,Ks=[[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]],Ct=class extends Error{constructor(t){super(t);this.code=t;}code;name="UiPluginCspNormalizationError"};});function In(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 x(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function La(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=>!x(e,s));r!==void 0&&A("MANIFEST_INVALID","MANIFEST_INVALID",r,"missing-key");}function Hn(e,n=false,t=false,i=false){return ra.test(e)||!i&&aa.test(e)||sa.test(e)||t&&$i.test(e)||ca.test(e)&&!(n&&/^\s*data:/i.test(e)&&!$i.test(e))}function Bn(e,n=new Set,t=0,i=false,o=false,r=""){if(typeof e=="string"){Hn(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)=>Bn(s,n,t+1,!1,!1,In(r,`[${a}]`)));return}$(e)||A("MANIFEST_INVALID","MANIFEST_INVALID",r);for(let[s,a]of Object.entries(e))Bn(a,n,t+1,i&&t===0&&(s==="name"||s==="description"),o,In(r,s));}finally{n.delete(e);}}}function Te(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 oa.test(e)||A("MANIFEST_INVALID"),e}function nn(e){return ia.test(e)||A("TOKEN_INVALID"),e}function Ra(e){return Qi.test(e)||A("MANIFEST_INVALID"),e}function Oa(e){$(e)||A("MANIFEST_INVALID");let n={};for(let[t,i]of Object.entries(e)){let o=Ra(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 wa(e,n,t){let i=e[n];(!i||i.type!==t)&&A("MANIFEST_INVALID");}function Fn(e,n,t){let i=Te(e,"field");return Qi.test(i)||A("MANIFEST_INVALID"),wa(n,i,t),i}function Ca(e,n){$(e)||A("MANIFEST_INVALID");let t=e.primitive;switch(typeof t!="string"&&A("MANIFEST_INVALID"),Ma.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:nn(Te(e,"badgeToken")),noticeToken:nn(Te(e,"noticeToken"))};case "heading":return K(e,["primitive","field"]),{primitive:t,field:Fn(e,n,"text")};case "labeled-text":return K(e,["primitive","titleToken","field","variant"]),e.variant!=="callout"&&A("MANIFEST_INVALID"),{primitive:t,titleToken:nn(Te(e,"titleToken")),field:Fn(e,n,"text"),variant:"callout"};case "step-flow":return K(e,["primitive","titleToken","field"]),{primitive:t,titleToken:nn(Te(e,"titleToken")),field:Fn(e,n,"step-list")};case "text-list":{K(e,["primitive","titleToken","field"],["emptyToken","hideWhenEmpty"]);let i={primitive:t,titleToken:nn(Te(e,"titleToken")),field:Fn(e,n,"text-list")};return x(e,"emptyToken")&&(i.emptyToken=nn(Te(e,"emptyToken"))),x(e,"hideWhenEmpty")&&(typeof e.hideWhenEmpty!="boolean"&&A("MANIFEST_INVALID"),i.hideWhenEmpty=e.hideWhenEmpty),i}}return A("MANIFEST_INVALID")}function Ua(e,n){return Array.isArray(e)||A("MANIFEST_INVALID"),e.map(t=>Ca(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 Gi(e,n){return (typeof e!="string"||e.length===0||e.length>4096||e.trim().length===0||Da.test(e)||ba.test(e))&&A("MANIFEST_INVALID",`${n} is invalid`),(Hn(e,true,true)||da.test(e)||pa.test(e)||la.test(e))&&A("UNSAFE_VALUE",`${n} contains an unsafe value`),e}function kt(e,n){return (typeof e!="string"||!Ee.test(e))&&A("MANIFEST_INVALID",`${n} is invalid`),e}function ka(e){return (typeof e!="string"||!Et.test(e)||e==="*"||e==="all")&&A("MANIFEST_INVALID","action capability is invalid"),e}function eo(e){return (typeof e!="string"||!Na.test(e))&&A("MANIFEST_INVALID","resource hash is invalid"),e}function xt(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)=>xt(o,n,t+1,In(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))xt(r,n,t+1,In(i,o));}finally{n.delete(e);}}}function no(e){return (typeof e!="string"||e.length>4096||!yn.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 vt(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=no(i);t.has(o)&&A("MANIFEST_INVALID","projection allowlist contains a duplicate path"),t.add(o),n.push(o);}return {allow:n}}function xa(e,n){if(e===void 0)return;Array.isArray(e)||A("MANIFEST_INVALID","dataPaths must be an array"),e.length>Sa&&X("dataPaths exceed the v2 limit");let t=[],i=new Set;for(let o of e){let r=no(o);i.has(r)&&A("MANIFEST_INVALID","dataPaths contain a duplicate path"),n.some(s=>qe(r,s))||A("MANIFEST_INVALID","dataPaths must be projection-allowed"),i.add(r),t.push(r);}return t}function tn(e,n,t=Number.MAX_SAFE_INTEGER){return (!Number.isSafeInteger(e)||e<0||e>t)&&A("MANIFEST_INVALID",`${n} is invalid`),e}function Wi(e,n){return (typeof e!="number"||!Number.isFinite(e))&&A("MANIFEST_INVALID",`${n} is invalid`),e}function jt(e,n=0,t=new Set){if(typeof e=="string")return (e.length>4096||Hn(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=>jt(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]=jt(r,n+1,t);return i}finally{t.delete(e);}}function va(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"||!yn.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 ja(e,n){let t=n?yn:xn;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 Ft(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(x(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=>jt(a))),i==="string"&&(x(e,"minLength")&&(r.minLength=tn(e.minLength,"schema minLength",4096)),x(e,"maxLength")&&(r.maxLength=tn(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")&&(x(e,"minimum")&&(r.minimum=Wi(e.minimum,"schema minimum")),x(e,"maximum")&&(r.maximum=Wi(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"&&(x(e,"minItems")&&(r.minItems=tn(e.minItems,"schema minItems",128)),x(e,"maxItems")&&(r.maxItems=tn(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"),x(e,"items")&&(r.items=Ft(e.items,n+1,false))),i==="object"){let a;if(x(e,"properties")){$(e.properties)||A("MANIFEST_INVALID","schema properties must be an object");let d=Object.entries(e.properties);d.length>64&&X("schema properties are too many"),a={};for(let[l,p]of d){let u=ja(l,t);a[u]=Ft(p,n+1,false);}r.properties=a;}x(e,"minProperties")&&(r.minProperties=tn(e.minProperties,"schema minProperties",64)),x(e,"maxProperties")&&(r.maxProperties=tn(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 c=va(e.required,a);c!==void 0&&(r.required=c),x(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")>2097152)&&X("action inputSchema subtree is too large"),r}function Fa(e){let n=Ft(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,ma);let n=e.handler;return (typeof n!="string"||!Tt.test(n))&&A("MANIFEST_INVALID","core backend handler is invalid"),{type:"core",handler:n}}if(e.type==="skill"&&x(e,"entry"))return K(e,Ea),e.entry!==en&&A("MANIFEST_INVALID",`skill backend entry must be ${en}`),{type:"skill",entry:en};if(e.type==="skill"){K(e,ha,_a),(!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||!Pt.test(i))&&A("MANIFEST_INVALID","skill backend command token is invalid"),n.push(i);let t=x(e,"env")?Ha(e.env):void 0;return {type:"skill",command:n,...t===void 0?{}:{env:t}}}A("MANIFEST_INVALID","action backend type is unsupported");}function Ba(e){$(e)||A("MANIFEST_INVALID","action must be an object"),K(e,Aa,Ia),x(e,"_meta")&&z("_meta",()=>to(e._meta));let n=z("actionId",()=>kt(e.actionId,"actionId"));mt(n)&&A("MANIFEST_INVALID",`actionId "${n}" is not projection-safe`,"actionId");let t=z("capability",()=>ka(e.capability)),i=e.mutation;typeof i!="boolean"&&A("MANIFEST_INVALID","action mutation must be boolean","mutation");let o=z("inputSchema",()=>Fa(e.inputSchema)),r;if(x(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"||!x(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",()=>vt(e.resultProjection)),a=z("backend",()=>Va(e.backend)),c;x(e,"content")&&((a.type!=="skill"||!vn(e.content))&&A("MANIFEST_INVALID","action content declaration is invalid","content"),c=za(e.content));let d;if(x(e,"confirmation")){let l=e.confirmation;l!=="none"&&l!=="native"&&A("MANIFEST_INVALID","action confirmation is invalid","confirmation"),d=l;}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 Ha(e){return Ci(e)||A("MANIFEST_INVALID","skill backend env is invalid"),Object.freeze([...e])}function za(e){return Object.freeze({...e.in===void 0?{}:{in:Object.freeze({...e.in})},...e.out===void 0?{}:{out:Object.freeze({...e.out})}})}function $a(e){return $(e)||A("INITIAL_STATE_INVALID","initialState must be an object"),K(e,Ta,Pa),e.path!=="ui/state.json"&&A("MANIFEST_INVALID","initialState path is not fixed"),x(e,"hash")?{path:"ui/state.json",hash:eo(e.hash)}:{path:"ui/state.json"}}function Ga(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 Wa(e,n){let t;try{t=Hi(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 Ja(e,n){Bn($(e)&&x(e,"csp")?La(e,"csp"):e,new Set,0,true,true),xt(e),$(e)||A("MANIFEST_INVALID"),K(e,fa,ya),x(e,"_meta")&&z("_meta",()=>to(e._meta)),e.manifestVersion!==2&&A("MANIFEST_INVALID");let t;x(e,"runtime")&&(t=z("runtime",()=>Ga(e.runtime)));let i;x(e,"csp")&&(i=z("csp",()=>Wa(e.csp,t)));let o=z("pluginId",()=>kt(e.pluginId,"pluginId")),r=z("definitionId",()=>kt(e.definitionId,"definitionId")),s=z("version",()=>Ie(e,"version",1)),a=z("name",()=>Gi(e.name,"name")),c=z("description",()=>Gi(e.description,"description")),d;x(e,"icon")&&((typeof e.icon!="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(e.icon))&&A("MANIFEST_INVALID","icon is invalid","icon"),d=e.icon);let l;x(e,"tone")&&((typeof e.tone!="string"||!Nt.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;x(e,"entryHash")&&(p=z("entryHash",()=>eo(e.entryHash)));let u;x(e,"initialState")&&(u=z("initialState",()=>$a(e.initialState)));let f;x(e,"usage")&&(e.usage!=="card"&&e.usage!=="window"&&A("MANIFEST_INVALID","usage is invalid","usage"),f=e.usage);let g;x(e,"detailPanel")&&(typeof e.detailPanel!="boolean"&&A("MANIFEST_INVALID","detailPanel is invalid","detailPanel"),g=e.detailPanel);let _;if(x(e,"displayModes")){((f??ke)!==ke||!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.displayModes;}(f??ke)===ke&&g!==void 0&&A("MANIFEST_INVALID","detailPanel is card-only","detailPanel");let P=n.mode??"local";P!=="local"&&P!=="installed"&&P!=="published"&&A("MANIFEST_INVALID","manifest mode is invalid"),P!=="local"&&p===void 0&&A("MANIFEST_INVALID","installed manifests require entryHash","entryHash","required-when-installed"),P!=="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 C=[],U=new Set;for(let y of e.surfaces)(typeof y!="string"||!Dt.includes(y))&&A("MANIFEST_INVALID","surface is unsupported","surfaces"),U.has(y)&&A("MANIFEST_INVALID","surfaces contain a duplicate","surfaces","duplicate-item"),U.add(y),C.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",()=>vt(e.stateProjection)),j=e.summaryProjection===void 0?void 0:z("summaryProjection",()=>vt(e.summaryProjection));j!==void 0&&j.allow.some(y=>!w.allow.includes(y))&&A("MANIFEST_INVALID","summaryProjection must be a subset of stateProjection.allow","summaryProjection");let D=z("dataPaths",()=>xa(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 b=[],R=new Set;for(let[y,I]of e.actions.entries()){let h=`actions[${y}]`,E=z(h,()=>Ba(I));if(R.has(E.actionId)&&A("MANIFEST_INVALID","actions contain a duplicate actionId",`${h}.actionId`,"duplicate-item"),E.backend.type==="core"&&E.backend.handler==="state.set"){E.mutation||A("MANIFEST_INVALID","state.set actions must be mutations",`${h}.mutation`);for(let L of Object.keys(E.inputSchema.properties))w.allow.includes(L)||A("MANIFEST_INVALID","state.set input paths must be projection-allowed",`${h}.inputSchema.properties`);}R.add(E.actionId),b.push(E);}return {manifestVersion:2,pluginId:o,definitionId:r,version:s,name:a,description:c,...d===void 0?{}:{icon:d},...l===void 0?{}:{tone:l},entry:"ui/index.html",...p===void 0?{}:{entryHash:p},...t===void 0?{}:{runtime:t},...i===void 0?{}:{csp:i},...u===void 0?{}:{initialState:u},...f===void 0?{}:{usage:f},...g===void 0?{}:{detailPanel:g},..._===void 0?{}:{displayModes:_},surfaces:C,size:{height:N},stateProjection:w,...j===void 0?{}:{summaryProjection:j},...D===void 0?{}:{dataPaths:D},actions:b}}function to(e){$(e)||A("MANIFEST_INVALID","_meta must be an object");let n=JSON.stringify(e);(n===void 0||Buffer.byteLength(n,"utf8")>ga)&&X("_meta exceeds the 4 KiB limit",void 0,"meta-too-large");}function Ka(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 Vt(e,n,t,i,o,r){if(typeof e=="string"){let s=o.length>0&&r.some(a=>qe(o.join("."),a));return (e.length>4096||Hn(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(c=>Vt(c,n,t+1,2097152,o,r));else {$(e)||Ae("state contains a non-plain object");let c={};for(let[d,l]of Object.entries(e))(d.length>4096||!xn.test(d)||Qe(d))&&(d.length>4096&&Ae("state key is too long"),Ae("state contains a reserved or invalid key")),c[d]=Vt(l,n,t+1,2097152,[...o,d],r);s=c;}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 Ht(e,n=[]){$(e)||Ae("initial state must be a JSON object");let t=Vt(e,new Set,0,2097152,[],n);return (t===null||Array.isArray(t)||typeof t!="object")&&Ae(),t}function Xa(e,n={}){Bn(e),$(e)||A("MANIFEST_INVALID"),K(e,ua),e.manifestVersion!==1&&A("MANIFEST_INVALID");let t=Ut(Te(e,"pluginId")),i=Ut(Te(e,"definitionId")),o=Ie(e,"version",1),r=Ie(e,"primitiveSet",1),s=n.supportedPrimitiveSet??ta;(!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(Te(e.activation,"language")),c=Oa(e.schema),d=Ua(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 Ya(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?Ja(e,n):Xa(e,n)}function ze(e,n={}){try{return Ya(e,n)}catch(t){if(t instanceof re)throw t;return A("MANIFEST_INVALID")}}function gn(e,n={}){let t=ze(e,n);return t.manifestVersion===2?Ka(t):t}var ta,ia,oa,Qi,ra,sa,aa,ca,$i,da,pa,la,ua,fa,ya,Aa,Ia,ga,ma,ha,_a,Ea,Ta,Pa,Na,Da,ba,Sa,Ma,re,zt=V(()=>{m();wt();Me();Mt();Ui();Ot();zi();Ve();ta=1,ia=/^[a-z][a-zA-Z0-9]*(\.[a-zA-Z0-9]+)+$/,oa=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,Qi=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,ra=/<\/?[A-Za-z][^>]*>/,sa=/^(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)/,aa=/^(?:https?|file|ftp|ws|wss):\/\//i,ca=/^\s*(?:javascript|data):/i,$i=/data:[^,\s]*,/i,da=/(?:https?|file|ftp|ws|wss):\/\//i,pa=/javascript:/i,la=/(?:^[\s]*|[\s"'(=])(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)(?=[^\s"'<>])[^\s"'<>]*/,ua=["manifestVersion","pluginId","definitionId","version","primitiveSet","activation","schema","layout"],fa=["manifestVersion","pluginId","definitionId","version","name","description","entry","surfaces","size","stateProjection","actions"],ya=["_meta","icon","tone","entryHash","runtime","csp","initialState","usage","detailPanel","displayModes","summaryProjection","dataPaths","focusedAiDataPaths"],Aa=["actionId","capability","mutation","inputSchema","resultProjection","backend"],Ia=["confirmation","dataInputs","content","_meta"],ga=4*1024,ma=["type","handler"],ha=["type","command"],_a=["env"],Ea=["type","entry"],Ta=["path"],Pa=["hash"],Na=/^[0-9a-f]{64}$/,Da=/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/,ba=/[\r\n]/,Sa=16,Ma=["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,In(t,this.path),this.rule)}};});function co(e){return typeof e=="string"&&e.length<=Za&&qa.test(e)}function v(e,n,t,i,o){throw new Ne(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["${xe}"]`;return e===void 0||e===""?n:e.startsWith("[")?`${n}${e}`:`${n}.${e}`}function tc(e){return e.toLowerCase().replace(/_/g,"-")}function ic(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 po(e,n,t){return {path:t(e.path),rule:e.rule??tc(e.code),...e.message!==e.code?{message:e.message}:{},file:n}}function lo(e){return JSON.parse(JSON.stringify(e))}function Wt(e,n,t=0,i=new Set){if(typeof e=="string"){e.length>4096&&v("LIMIT_EXCEEDED",n,"string-too-long"),(Qa.test(e)||ec.test(e)||nc.test(e))&&v("UNSAFE_VALUE",n,"unsafe-value");return}if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){Number.isFinite(e)||v("MANIFEST_INVALID",n,"non-finite-number");return}typeof e!="object"&&v("MANIFEST_INVALID",n,"non-json-value"),t>8&&v("LIMIT_EXCEEDED",n,"too-deep"),i.has(e)&&v("MANIFEST_INVALID",n,"cycle"),i.add(e);try{if(Array.isArray(e)){e.length>128&&v("LIMIT_EXCEEDED",n,"array-too-long"),e.forEach((o,r)=>Wt(o,`${n}[${r}]`,t+1,i));return}te(e)||v("MANIFEST_INVALID",n,"non-plain-object");for(let[o,r]of Object.entries(e))Wt(r,n===""?o:`${n}.${o}`,t+1,i);}finally{i.delete(e);}}}function ge(e,n){return (typeof e!="string"||e.length===0)&&v("MANIFEST_INVALID",n,"string"),e}function rn(e,n){return te(e)||v("MANIFEST_INVALID",n,"object"),e}function oc(e,n){Array.isArray(e)||v("MANIFEST_INVALID",n,"array"),e.forEach((t,i)=>ge(t,`${n}[${i}]`));}function rc(e,n){typeof e!="boolean"&&v("MANIFEST_INVALID",n,"boolean");}function mn(e,n,t,i){for(let o of Object.keys(e))!t.includes(o)&&!i.includes(o)&&v("MANIFEST_INVALID",`${n}.${o}`,"unknown-key");for(let o of t)Y(e,o)||v("MANIFEST_INVALID",`${n}.${o}`,"missing-key");}function sc(e,n){switch(Wt(n,e),e){case "long_description":case "homepage":case "documentation":case "support":case "icon":case "license":ge(n,e);return;case "author":{let t=rn(n,e);mn(t,e,["name"],["email","url"]);for(let i of Object.keys(t))ge(t[i],`${e}.${i}`);return}case "repository":{let t=rn(n,e);mn(t,e,[],["type","url"]);for(let i of Object.keys(t))ge(t[i],`${e}.${i}`);return}case "icons":{Array.isArray(n)||v("MANIFEST_INVALID",e,"array"),n.forEach((t,i)=>{let o=`${e}[${i}]`,r=rn(t,o);mn(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":oc(n,e);return;case "tools":{Array.isArray(n)||v("MANIFEST_INVALID",e,"array"),n.forEach((t,i)=>{let o=`${e}[${i}]`,r=rn(t,o);mn(r,o,["name"],["description"]),ge(r.name,`${o}.name`),Y(r,"description")&&ge(r.description,`${o}.description`);});return}case "prompts":{Array.isArray(n)||v("MANIFEST_INVALID",e,"array"),n.forEach((t,i)=>{let o=`${e}[${i}]`,r=rn(t,o);mn(r,o,["name","text"],["description","arguments"]),ge(r.name,`${o}.name`),ge(r.text,`${o}.text`);});return}case "tools_generated":case "prompts_generated":rc(n,e);return;case "localization":case "compatibility":case "user_config":rn(n,e);return;default:v("MANIFEST_INVALID",e,"unknown-key");}}function zn(e){return typeof e=="string"&&Ee.test(e)?e:void 0}function uo(e){return Number.isSafeInteger(e)&&e>=1?e:void 0}function ac(e){let n=zn(e.name);if(n===void 0)return;let t=e._meta,i=te(t)?t[xe]:void 0,o=te(i)?i:{},r=Y(o,"definitionId")?zn(o.definitionId):n,s=Y(o,"definitionVersion")?uo(o.definitionVersion):1;return {pluginId:n,...r===void 0?{}:{definitionId:r},...s===void 0?{}:{definitionVersion:s}}}function cc(e){let n=zn(e.pluginId);if(n===void 0)return;let t=zn(e.definitionId),i=uo(e.version);return {pluginId:n,...t===void 0?{}:{definitionId:t},...i===void 0?{}:{definitionVersion:i}}}function Xt(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,xe)}catch{return false}}function dc(e,n){if(e===ce)return n.builtinOnly===true;let t=n._meta,i=te(t)?t[xe]:void 0;return te(i)&&i.builtinOnly===true}function pc(e,n){Y(e,"server")&&v("MANIFEST_INVALID","server","server-unsupported","phase 1 runs CrewX-owned Apps only");for(let a of Object.keys(e))Jt.includes(a)||v("MANIFEST_INVALID",a,"unknown-key");for(let a of Kt)Y(e,a)||v("MANIFEST_INVALID",a,"missing-key");e.manifest_version!==$t&&v("MANIFEST_INVALID","manifest_version","unsupported-version",`manifest_version must be "${$t}"`),co(e.version)||v("MANIFEST_INVALID","version","semver","version must be a semver.org version such as 0.1.0");let t=e._meta;te(t)||v("MANIFEST_INVALID","_meta","object"),Y(t,xe)||v("MANIFEST_INVALID",me(),"missing-key");let i=t[xe];te(i)||v("MANIFEST_INVALID",me(),"object");for(let a of Object.keys(i))Gt.includes(a)||ao.includes(a)||v("MANIFEST_INVALID",me(a),"unknown-key");for(let a of Gt)a==="actions"&&n!==void 0||Y(i,a)||v("MANIFEST_INVALID",me(a),"missing-key");if(n!==void 0&&Y(i,"actions")&&v("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`),lc(i.actions),Y(i,"definitionVersion")){let a=i.definitionVersion;(!Number.isSafeInteger(a)||a<1)&&v("MANIFEST_INVALID",me("definitionVersion"),"positive-integer");}let o={};for(let a of so)Y(e,a)&&(sc(a,e[a]),o[a]=lo(e[a]));let r={};for(let[a,c]of Object.entries(t))a!==xe&&(r[a]=c);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,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:en}}))),Object.keys(r).length>0&&(s._meta=r),{v2Input:s,...Object.keys(r).length>0?{vendorMeta:r}:{},passthrough:o}}function lc(e){Array.isArray(e)&&e.forEach((n,t)=>{let i=te(n)?n.backend:void 0;te(i)&&Y(i,"entry")&&v("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 uc(e,n,t){te(e)||v("MANIFEST_INVALID","","not-object","manifest.json must be a JSON object",G);let i;try{i=pc(e,t);}catch(s){throw s instanceof Ne?new Ne(s.code,{...s.reason,file:G}):s}let o;try{let s=ze(i.v2Input,{mode:n.mode??"local"});s.manifestVersion!==2&&v("MANIFEST_INVALID","","v2-required"),o=s;}catch(s){throw s instanceof re?new Ne(s.code,po(s,G,ic)):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 Ne("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 fc(e,n){try{let t=ze(e,{mode:n.mode??"local"});if(t.manifestVersion!==2)throw new Ne("MANIFEST_INVALID",{path:"manifestVersion",rule:"v2-required",message:"a workspace App requires manifestVersion 2",file:ce});return {file:ce,manifest:t,v2Input:e}}catch(t){throw t instanceof re?new Ne(t.code,po(t,ce,i=>i??"")):t}}function sn(e){return pe(gn(e).definition)}function oo(e){let{entryHash:n,initialState:t,...i}=e,o={...i};return t!==void 0&&(o.initialState={path:t.path}),lo(o)}function yc(e,n){let t=oo(e),i=oo(n);return [...new Set([...Object.keys(t),...Object.keys(i)])].sort().filter(r=>ne(t[r]??null)!==ne(i[r]??null))}function Ac(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 Ic(e,n){let t=yc(e,n),i=Ac(e,n),o="";try{let r=sn(e),s=sn(n);i=i||r!==s,o=` (definition hash ${r.slice(0,12)} vs ${s.slice(0,12)})`;}catch{i=true;}t.length===0&&!i||v("MANIFEST_DUAL_MISMATCH","","dual-manifest-mismatch",`${G} and ${ce} normalize to different definitions${o}`+(t.length>0?`; differing fields: ${t.join(", ")}`:""));}function Pe(e,n,t="MANIFEST_INVALID",i){return {code:t,reason:{path:e,rule:n,...i===void 0?{}:{message:i},file:B},files:[]}}function ro(e){return {...Pe("","tools-needs-manifest-json","MANIFEST_INVALID",`${B} is read with ${G} only`),files:e}}function gc(e,n){if(e.byteLength>n)return {failure:Pe("","file-too-large","LIMIT_EXCEEDED")};let t;try{t=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e));}catch{return {failure:Pe("","invalid-json")}}if(!te(t))return {failure:Pe("","not-object","MANIFEST_INVALID",`${B} must be a JSON object`)};for(let o of Object.keys(t))if(o!=="schemaVersion"&&o!=="actions")return {failure:Pe(o,"unknown-key")};for(let o of ["schemaVersion","actions"])if(!Y(t,o))return {failure:Pe(o,"missing-key")};if(t.schemaVersion!==1)return {failure:Pe("schemaVersion","unsupported-version","MANIFEST_INVALID",`schemaVersion must be ${1}`)};let i=t.actions;if(!Array.isArray(i))return {failure:Pe("actions","array")};for(let[o,r]of i.entries()){if(!te(r))return {failure:Pe(`actions[${o}]`,"object")};if(Y(r,"backend"))return {failure:Pe(`actions[${o}].backend`,"tools-backend","MANIFEST_INVALID",`an action in ${B} cannot carry a backend`)}}return {actions:i}}function mc(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 $e(e,n={}){let{parsed:t,failure:i}=mc(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:gc(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:[]}:ro(o),parseFailure:true,builtinOnly:false};let a=t[0],c=a.file===G?ac(a.raw):cc(a.raw),d=t.some(f=>dc(f.file,f.raw)),l;if(s!==void 0){let f=t.some(g=>g.file===G)?s.failure:ro(o);if(f!==void 0)return {ok:false,rejection:f,parseFailure:false,...c===void 0?{}:{identity:c},builtinOnly:d};l=s.actions;}let p=[];try{for(let f of t)p.push(f.file===G?uc(f.raw,n,l):fc(f.raw,n));p.length===2&&Ic(p[0].manifest,p[1].manifest);}catch(f){if(f instanceof Ne)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,...c===void 0?{}:{identity:c},builtinOnly:d};throw f}let u=p[0];return {ok:true,...u,identity:c??{pluginId:u.manifest.pluginId},files:o}}var G,ce,q,$t,xe,Jt,Kt,so,Gt,ao,qa,Za,Qa,ec,nc,Ne,$n=V(()=>{m();Be();Me();Ot();Ve();zt();G="manifest.json",ce="ui-plugin.json",q=[G,ce],$t="0.3",xe="dev.crewx",Jt=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"]),Kt=Object.freeze(["manifest_version","name","display_name","version","description","_meta"]),so=Object.freeze(Jt.filter(e=>e!=="server"&&!Kt.includes(e))),Gt=Object.freeze(["entry","surfaces","size","stateProjection","actions"]),ao=Object.freeze(["definitionId","definitionVersion","icon","tone","entryHash","runtime","initialState","usage","detailPanel","displayModes","summaryProjection","dataPaths","focusedAiDataPaths","csp"]),qa=/^(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-]+)*))?$/,Za=256,Qa=/<\/?[A-Za-z][^>]*>/,ec=/^\s*javascript:/i,nc=/data:[^,\s]*,/i;Ne=class extends Error{constructor(t,i){super(`${t}: ${i.path||"<file>"} (${i.rule})`);this.code=t;this.reason=i;}code;reason};});var Yt=V(()=>{m();Li();$n();zt();Ve();});function S(e,n=e){throw new De(e,n)}var De,Wn=V(()=>{m();De=class extends Error{constructor(t,i=t){super(i);this.code=t;}code;name="McpAppContractError"};});var Po=V(()=>{m();});var No=V(()=>{m();Be();Me();Wn();Po();});function bo(e,n){return Do.add(e),n!==void 0&&Rc.set(e,n),e}function an(e){return e!==null&&typeof e=="object"&&Do.has(e)}var Do,Rc,Jn=V(()=>{m();Do=new WeakSet,Rc=new WeakMap;});function Tn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Zt(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 Lo(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let n of Object.values(e))Lo(n);return Object.freeze(e)}function ie(e){throw new be("LINEAGE_INVALID",e)}function vc(e){throw new be("LINEAGE_STALE",e)}function Ro(e){if(!Tn(e)||!Zt(e,Cc,Uc)||!Tn(e.actions))return ie("Lineage definition shape is invalid");for(let n of Object.values(e.actions))if(!Tn(n)||!Zt(n,kc,xc))return ie("Lineage action definition shape is invalid");return e}function jc(e){if(!Tn(e)||!Zt(e,Oc,wc))return ie("Lineage entry shape is invalid");if(!Number.isSafeInteger(e.version)||e.version<1||typeof e.hash!="string"||!So.test(e.hash))return ie("Lineage entry identity is invalid");if(e.sourceHash!==void 0&&(typeof e.sourceHash!="string"||!So.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"):Lo({version:e.version,hash:e.hash,definition:n,...e.sourceHash===void 0?{}:{sourceHash:e.sourceHash},...e.compat===void 0?{}:{compat:e.compat}})}function Mo(e){return e.stateProjection?.allow??[]}function Fc(e,n){let t=[],i=new Set(Mo(n));Mo(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 Vc(e,n){return ne(e)===ne(n)}function Qt(e,n){if(!Array.isArray(e)||e.length===0)return ie("Definition lineage is missing");if(!Tn(n)||typeof n.hash!="string")return ie("Current definition is invalid");let t,i;try{let{hash:a,...c}=n;i=Ro(c),t={...i,hash:a},ye(t);}catch{return ie("Current definition is invalid")}let o=e.map(jc),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,c)=>c>0&&a.version<=o[c-1].version))return ie("Lineage generations are not in increasing version order");if(o.some((a,c)=>o.findIndex(d=>d.hash===a.hash)!==c))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 vc("The last lineage generation does not match the current package");if(t.legacy!==void 0){let a=new Set(Object.keys(t.actions)),c=new Set;for(let l of o)if(l.sourceHash===void 0)for(let p of Object.keys(l.definition.actions))a.has(p)&&c.add(p);let d=Object.keys(t.legacy.agentAccess??{});if(d.length!==c.size||d.some(l=>!c.has(l))){let l="S4_LEGACY_AGENT_ACCESS_COMPLETE";throw new be("LINEAGE_INVALID",`Lineage compatibility failed: ${l}`,[l])}}for(let a=0;a<o.length-1;a+=1){if(o.slice(a,-1).some(l=>l.compat==="break"))continue;let d=Fc(o[a].definition,t);if(d.length>0)throw new be("LINEAGE_INVALID",`Lineage compatibility failed: ${d.join(", ")}`,d)}return Object.freeze({entries:Object.freeze(o),current:t})}var be,So,Oc,wc,Cc,Uc,kc,xc,ei=V(()=>{m();Be();Me();be=class extends Error{constructor(t,i=t,o=[]){super(i);this.code=t;this.violations=o;}code;violations;name="UiDefinitionLineageError"},So=/^[0-9a-f]{64}$/,Oc=["version","hash","definition"],wc=["sourceHash","compat"],Cc=["id","version","actions"],Uc=["sourceHash","usage","detailPanel","displayModes","renderer","surfaces","stateProjection","dataPaths","summaryProjection","legacy"],kc=["capabilities"],xc=["inputKeys","dataInputs","confirmation","resultProjection","content","env"];});var Oo,wo,Co,Uo,ko=V(()=>{m();Oo="text/html;profile=mcp-app",wo=["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"],Uo="text/html";});function xo(e,n=[],t){if(e.content!==void 0||e.confirmation!=="none")return "denied";let i=Bc();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 Bc(e){return;}var vo=V(()=>{m();Be();Jn();});function Yc(e){return Dn.has(e)&&(e.initialState===void 0||Dn.has(e.initialState))}function Ho(e,n,t,i){let o=i===void 0?void 0:Object.freeze({hash:i.hash,bytes:Object.freeze(i.bytes)}),r=Object.freeze({mimeType:Uo,entryHash:e,html:n,bytes:Object.freeze(t),...o===void 0?{}:{initialState:o}});return o!==void 0&&Dn.add(o),Dn.add(r),r}function qc(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:je}),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:je}),n}function Fe(e,n,t){return (typeof e!="string"||!Vo.test(e))&&S(n,`${t} must be a safe identifier`),e}function Pn(e,n,t){let i=e??t;return (typeof i!="string"||i.trim().length===0||i.length>$c)&&S("TOOL_INVALID",`${n} must be a meaningful description`),i}function ti(e){return (typeof e!="string"||e.length===0||e.length>cn||!/<html(?:\s|>)/i.test(e)||!/<\/html\s*>/i.test(e))&&S("HTML_INVALID","MCP App HTML must be a non-empty HTML document"),e}function Nn(e,n=0){try{let t=fe(e,n);return t.type!==void 0&&t.type!=="object"&&S("TOOL_INVALID","MCP App inputSchema must describe an object"),t}catch(t){if(t instanceof De)throw t;S("TOOL_INVALID","MCP App inputSchema must be projection-safe JSON");}}function Zc(e){return (typeof e!="string"||e.trim().length===0||e.length>Gc)&&S("TOOL_INVALID","MCP App tools require a meaningful text fallback"),e}function Qc(e){e===void 0&&S("TOOL_INVALID","MCP App tool visibility is required");let n=[...e];return (n.length===0||n.some(t=>t!=="model"&&t!=="app")||new Set(n).size!==n.length)&&S("TOOL_INVALID","MCP App tool visibility must contain model and/or app once"),n}function $o(e){return (typeof e!="string"||!Bo.test(e))&&S("RESOURCE_URI_INVALID","MCP App resource URI is not a registered ui:// URI"),e}function Go(e){let n=Fe(e.appId,"APP_ID_INVALID","Local App id"),t=Pn(e.name,"Local App name",n),i=Pn(e.description,"Local App description",`${t} interactive view`),o=qn(e.definition),r=ti(e.html),s=Kn(e.entryHash,"Local App entry hash"),a=e.entryBytes===void 0?Array.from(new TextEncoder().encode(r)):Yn(e.entryBytes,"Local App entry bytes");(Xn(a)!==s||Ko(a)!==r)&&S("HTML_INVALID","Local App entry bytes do not match the HTML hash");let c=ed(e),d=[];Array.isArray(e.actions)||S("TOOL_INVALID","Local App actions must be an array");for(let N of e.actions){let w=Fe(N.actionId,"TOOL_ID_INVALID","Local App action id");(d.includes(w)||!Object.prototype.hasOwnProperty.call(o.actions,w))&&S("TOOL_INVALID",`Local App action is not declared by the UI definition: ${w}`),d.push(w);}let l=Fe(e.readToolName,"TOOL_ID_INVALID","Local App read tool name"),p=e.actionToolName===void 0?void 0:Fe(e.actionToolName,"TOOL_ID_INVALID","Local App action tool name");d.length===0&&p!==void 0&&S("TOOL_INVALID","A static local App cannot register an action tool"),d.length>0&&p===void 0&&S("TOOL_INVALID","A stateful local App requires an action tool name"),p!==void 0&&p===l&&S("TOOL_ID_CONFLICT",`Local App read and action tools share a name: ${l}`);let u=qc(e.runtime);u.some(N=>N.name===l||N.name===p)&&S("TOOL_ID_CONFLICT","Local App read or action tool conflicts with a requested Host capability");let f={name:l,description:`${t} current state`,inputSchema:Xc,textFallback:`${t} current state is available through its open instance.`,visibility:Object.freeze(["model","app"]),kind:"read",resourceBinding:je},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:je,actionIds:Object.freeze([...d])};g.push(Object.freeze(N));}let _=[],P=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||!Vo.test(w)){_.push(Object.freeze({toolName:w,actionId:N.actionId,reason:"name_too_long"}));continue}if(P.has(w)){_.push(Object.freeze({toolName:w,actionId:N.actionId,reason:"name_collision"}));continue}let j=xo({actionId:N.actionId,confirmation:o.actions[N.actionId]?.confirmation,content:o.actions[N.actionId]?.content,backend:N.backend},e.modelActions),D=Object.freeze(j==="denied"?["app"]:["model","app"]),b={name:w,description:`${w} action`,inputSchema:Nn(N.inputSchema),textFallback:`${w} action requests are handled by the open App instance.`,visibility:D,kind:"action",resourceBinding:je,actionId:N.actionId,actionIds:Object.freeze([N.actionId]),_meta:Object.freeze({ui:Object.freeze({visibility:D})})};g.push(Object.freeze(b)),P.add(w);}let C=Ho(s,r,a,c===void 0?void 0:{hash:c.hash,bytes:[...c.bytes]}),U={appId:n,name:t,description:i,...e.icon===void 0?{}:{icon:Xo(e.icon)},...e.tone===void 0?{}:{tone:Yo(e.tone)},builtinOnly:false,definition:o,...e.runtime===void 0?{}:{runtime:Object.freeze({...e.runtime})},resourceBinding:je,resource:C,tools:Object.freeze(g),toolDiagnostics:Object.freeze(_)};return Q(U)}function Wo(e={}){return new ni(e)}function ii(e){if(e.length===0)return Nn({type:"object",properties:{},additionalProperties:false});let n=e.map(i=>i.actionId),t=new Map;for(let i of e)t.set(i.actionId,Nn(i.inputSchema));return Nn(nd(n,t),zo)}function ed(e){let n=e.definition.dataPaths??[];if(e.initialStateBytes===void 0){e.initialStateHash!==void 0&&S("STATE_INVALID","Initial state hash has no bytes"),e.initialState!==void 0&&fe(e.initialState,0,n);return}e.initialStateHash===void 0&&S("STATE_INVALID","Initial state bytes require a hash");let t=Kn(e.initialStateHash,"Initial state hash"),i=Yn(e.initialStateBytes,"Initial state bytes");Xn(i)!==t&&S("STATE_INVALID","Initial state bytes do not match the hash");let o;try{let r=new TextDecoder("utf-8",{fatal:!0}).decode(Uint8Array.from(i));o=fe(JSON.parse(r),0,n);}catch{S("STATE_INVALID","Initial state bytes are not projection-safe JSON");}return e.initialState!==void 0&&ne(o)!==ne(fe(e.initialState,0,n))&&S("STATE_INVALID","Initial state bytes do not match the state value"),{hash:t,bytes:Object.freeze([...i])}}function nd(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 td(e){let n=bn(e),t=Fe(n.appId,"APP_ID_INVALID","MCP App id"),i=ti(n.html);$o(n.uiUri);let o=n.definition===void 0?void 0:qn(n.definition),r=e.provenance;r!==void 0&&(!an(r)||r.appId!==t||r.definitionId!==o?.id||r.version!==o?.version||r.definitionHash!==o?.hash)&&S("TOOL_INVALID","Product App built-in registration provenance is not verified");let s=Object.freeze(n.tools.map(d=>Q(bn(d)))),a=Q({...n,appId:t,html:i,...o===void 0?{}:{definition:o},...r===void 0?{}:{provenance:r},tools:s}),c=Q({uri:a.uiUri,mimeType:Oo,text:i,...a.csp===void 0?{}:{_meta:{ui:{csp:a.csp}}}});return Q({appId:t,name:a.name,description:a.description,...a.icon===void 0?{}:{icon:a.icon},...a.tone===void 0?{}:{tone:a.tone},builtinOnly:a.builtinOnly,uiUri:a.uiUri,...o===void 0?{}:{definition:o},resourceBinding:Object.freeze({kind:"mcp",uri:a.uiUri}),resource:c,tools:s,descriptor:a})}function id(e){(e.resourceBinding.kind!=="instance"||e.builtinOnly!==false)&&S("STATE_INVALID","Local App registration binding is invalid"),Object.prototype.hasOwnProperty.call(e,"uiUri")&&S("STATE_INVALID","Local App registration cannot contain uiUri");let n=Fe(e.appId,"APP_ID_INVALID","Local App id"),t=qn(e.definition),i=e.provenance;i!==void 0&&(!an(i)||i.appId!==n||i.definitionId!==t.id||i.version!==t.version||i.definitionHash!==t.hash)&&S("TOOL_INVALID","Product App local registration provenance is not verified");let o=od(e.resource),r=e.tools.map(a=>{Fe(a.name,"TOOL_ID_INVALID","Local App tool name"),Pn(a.description,"Local App tool description","Local App tool"),Zc(a.textFallback);let c=Nn(a.inputSchema,a.kind==="action"&&!("actionId"in a)?zo:0);if((a.resourceBinding.kind!=="instance"||Object.prototype.hasOwnProperty.call(a,"resourceUri"))&&S("TOOL_INVALID","Local App tools cannot carry an MCP resource URI"),a.kind==="host")return (!Kc.has(a.name)||a.visibility.length!==1||a.visibility[0]!=="app"||Object.prototype.hasOwnProperty.call(a,"actionId"))&&S("TOOL_INVALID","Local App Host tools must use an allow-listed name and app-only visibility"),Q({...a,inputSchema:c,visibility:Object.freeze(["app"])});if(a.kind==="action"){if("actionId"in a){let l=Fe(a.actionId,"TOOL_ID_INVALID","Local App action id");Object.prototype.hasOwnProperty.call(t.actions,l)||S("TOOL_INVALID","Local App action tool references an undeclared action");let p=Qc(a._meta.ui.visibility);return JSON.stringify(p)!==JSON.stringify(a.visibility)&&S("TOOL_INVALID","Local App action metadata visibility must match the tool visibility"),Q({...a,actionId:l,actionIds:Object.freeze([l]),inputSchema:c,visibility:p,_meta:{ui:{visibility:p}}})}let d=[...a.actionIds];return (d.length===0||d.some(l=>!Object.prototype.hasOwnProperty.call(t.actions,l)))&&S("TOOL_INVALID","Local App action tool references an undeclared action"),Q({...a,inputSchema:c,actionIds:Object.freeze(d)})}return Q({...a,inputSchema:c})}),s=Q({appId:n,name:Pn(e.name,"Local App name",e.appId),description:Pn(e.description,"Local App description",e.name),...e.icon===void 0?{}:{icon:Xo(e.icon)},...e.tone===void 0?{}:{tone:Yo(e.tone)},builtinOnly:false,definition:t,...e.runtime===void 0?{}:{runtime:Object.freeze({...e.runtime})},...i===void 0?{}:{provenance:i},resourceBinding:je,resource:o,tools:Object.freeze(r),toolDiagnostics:Object.freeze([...e.toolDiagnostics??[]])});return jo.has(e)?e:(jo.add(s),s)}function od(e){let n=ti(e.html),t=Kn(e.entryHash,"Local App entry hash");if(Yc(e))return e;let i=Yn(e.bytes,"Local App entry bytes");(Xn(i)!==t||Ko(i)!==n)&&S("HTML_INVALID","Local App entry bytes do not match the HTML hash");let o=e.initialState===void 0?void 0:{hash:Kn(e.initialState.hash,"Initial state hash"),bytes:Yn(e.initialState.bytes,"Initial state bytes")};return o&&Xn(o.bytes)!==o.hash&&S("STATE_INVALID","Initial state bytes do not match the hash"),Ho(t,n,i,o)}function rd(e){return Q({appId:e.appId,name:e.name,description:e.description,...e.icon===void 0?{}:{icon:e.icon},...e.tone===void 0?{}:{tone:e.tone},builtinOnly:false,definition:Jo(e.definition),...e.provenance===void 0?{}:{provenance:e.provenance},entryHash:e.resource.entryHash,resourceBinding:je,tools:e.tools})}function sd(e){return Q({appId:e.appId,name:e.name,description:e.description,...e.icon===void 0?{}:{icon:e.icon},...e.tone===void 0?{}:{tone:e.tone},builtinOnly:e.builtinOnly,uiUri:e.uiUri,...e.definition===void 0?{}:{definition:Jo(e.definition)},resourceBinding:Object.freeze({kind:"mcp",uri:e.uiUri}),tools:e.tools})}function qn(e){try{if(Object.isFrozen(e))return ye(e),Q(e);let n=bn(e);return ye(n),Q(n)}catch(n){if(n instanceof De)throw n;S("STATE_INVALID","UI definition is not a valid immutable definition");}}function Jo(e){return Q({id:e.id,version:e.version,hash:e.hash})}function ad(e){return e!==null&&typeof e=="object"&&typeof e.id=="string"&&Number.isSafeInteger(e.version)&&typeof e.hash=="string"}function Fo(e,n,t){return `${e}\0${n}\0${t}`}function Kn(e,n){return (typeof e!="string"||!zc.test(e))&&S("SERIALIZATION_INVALID",`${n} is invalid`),e}function Xn(e){return Di.createHash("sha256").update(Uint8Array.from(e)).digest("hex")}function Yn(e,n){return (!Array.isArray(e)||e.some(t=>!Number.isInteger(t)||t<0||t>255))&&S("SERIALIZATION_INVALID",`${n} is invalid`),[...e]}function Ko(e){try{return new TextDecoder("utf-8",{fatal:!0}).decode(Uint8Array.from(e))}catch{S("SERIALIZATION_INVALID","UTF-8 bytes are invalid");}}function Xo(e){return (typeof e!="string"||!Wc.test(e))&&S("TOOL_INVALID","MCP App icon is invalid"),e}function Yo(e){return (typeof e!="string"||!Jc.has(e))&&S("TOOL_INVALID","MCP App tone is invalid"),e}function bn(e,n=new Map){if(e===null||typeof e!="object")return e;let t=e;if(n.has(t)&&S("SERIALIZATION_INVALID","MCP App value contains a cycle"),Array.isArray(e)){let r=[];n.set(t,r);for(let s of e)r.push(bn(s,n));return n.delete(t),r}let i;try{i=Object.getPrototypeOf(e);}catch{S("SERIALIZATION_INVALID","MCP App value cannot be cloned");}i!==Object.prototype&&i!==null&&S("SERIALIZATION_INVALID","MCP App value must be plain JSON");let o={};n.set(t,o);for(let[r,s]of Object.entries(e))Object.defineProperty(o,r,{configurable:true,enumerable:true,value:bn(s,n),writable:true});return n.delete(t),o}function Q(e,n=new Set){if(e===null||typeof e!="object"||n.has(e)||Dn.has(e))return e;n.add(e);for(let t of Object.values(e))Q(t,n);return Object.freeze(e),e}var Vo,Bo,zc,cn,$c,Gc,Wc,Jc,Kc,je,Xc,Dn,jo,zo,ni,Zn=V(()=>{m();No();Be();Me();Jn();Wn();ei();ko();vo();Vo=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,Bo=/^ui:\/\/crewx\/([A-Za-z][A-Za-z0-9._-]{0,127})\/([0-9a-f]{12})$/,zc=/^[0-9a-f]{64}$/,cn=8*1024*1024,$c=8*1024,Gc=16*1024,Wc=/^[a-z][a-z0-9-]{0,63}$/,Jc=new Set(["blue","violet","emerald","amber","rose","sky","slate","indigo"]),Kc=new Set(wo),new Set(Co),je=Object.freeze({kind:"instance"}),Xc=Object.freeze({type:"object",properties:Object.freeze({}),additionalProperties:false}),Dn=new WeakSet,jo=new WeakSet;zo=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=td(p);s.has(u.appId)&&S("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)&&S("TOOL_ID_CONFLICT",`MCP App tool name is already registered: ${g.name}`),a.add(g.name),this.mcpToolByName.set(g.name,g),r.push(g);this.mcpResources.set(u.resource.uri,u.resource),i.push(u),o.push(u.descriptor);}let c=(n.localApps??n.locals??[]).map(id),d=new Set(c.flatMap(p=>p.tools.filter(u=>!(u.kind==="action"&&"actionId"in u)).map(u=>u.name))),l=[];for(let p of c){let u=p;s.has(u.appId)&&S("APP_ID_CONFLICT",`MCP App id is already registered: ${u.appId}`),s.add(u.appId);let f=[],g=[...u.toolDiagnostics??[]];for(let _ of u.tools){if(a.has(_.name)){if(_.kind==="host"&&this.localToolByName.get(_.name)?.kind==="host"){f.push(_);continue}if(_.kind==="action"&&"actionId"in _){g.push(Object.freeze({toolName:_.name,actionId:_.actionId,reason:"name_collision"}));continue}S("TOOL_ID_CONFLICT",`MCP App tool name is already registered: ${_.name}`);}if(_.kind==="action"&&"actionId"in _&&d.has(_.name)){g.push(Object.freeze({toolName:_.name,actionId:_.actionId,reason:"name_collision"}));continue}a.add(_.name),this.localToolByName.set(_.name,_),f.push(_);}(f.length!==u.tools.length||g.length!==(u.toolDiagnostics?.length??0))&&(u=Q({...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,sd(p)),p.definition&&this.addDefinition(p.definition);for(let p of l)this.registrationById.set(p.appId,p),this.launcherById.set(p.appId,rd(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"||!Bo.test(n)?null:this.mcpResources.get(n)??null}requireMcpAppResource(n){$o(n);let t=this.mcpResources.get(n);return t||S("RESOURCE_NOT_FOUND",`MCP App resource is not registered: ${n}`),t}listLocalMcpApps(){return this.localApps}getLocalMcpApp(n){return this.localById.get(n)??null}listLocalMcpAppTools(){return Object.freeze([...this.localToolByName.values()])}resolveLocalMcpAppTool(n){return this.localToolByName.get(n)??null}resolveLocalMcpAppResource(n,t){let i=this.localById.get(n);return !i||t!==void 0&&i.definition.hash!==t?null:i.resource}listRegistrations(){return Object.freeze([...this.builtinApps,...this.localApps])}getRegistration(n){return this.registrationById.get(n)??null}listLaunchers(){return Object.freeze([...this.launcherById.values()].filter(n=>{let t=this.registrationById.get(n.appId),i=t?"descriptor"in t?t.descriptor.provenance:t.provenance:void 0,o=an(i)&&i.launcher===false;return t?.definition?.usage!=="card"&&!o}))}getLauncher(n){return this.launcherById.get(n)??null}resolveDefinition(n){if(!ad(n))return null;let t=this.definitionByKey.get(Rt(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(Fo(n,t,i))??null}addDefinition(n){let t=qn(n),i=Rt(t),o=this.definitionByKey.get(i);o&&o.hash!==t.hash&&S("STATE_INVALID",`UI definition generation conflicts: ${i}`),o||this.definitionByKey.set(i,t);}addHandler(n){(!n||typeof n.definitionId!="string"||typeof n.actionId!="string"||!Number.isSafeInteger(n.version)||n.version<1||typeof n.handle!="function")&&S("STATE_INVALID","UI action handler registration is invalid");let t=Fo(n.definitionId,n.version,n.actionId);this.handlerByKey.has(t)&&S("TOOL_INVALID",`Duplicate UI action handler registration: ${t}`),this.handlerByKey.set(t,Object.freeze({...n}));}};});function cd(e){let n=Go({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 qo(e){let n=e.normalized.manifest.actions;if(n.some(i=>i.backend.type==="skill")&&n.some(i=>i.backend.type==="core"))throw new Error("Mixed workspace App execution models");let t=cd(e);Wo({localApps:[t],definitions:[e.definition]});}var Zo=V(()=>{m();Zn();});function dd(e){if(e===null||typeof e!="object"||!(Qo in e))throw new TypeError("scanCache must be created by createWorkspaceAppScanCache");return e[Qo]}function er(e,n){let t=dd(e),i=t.rootIdentity;return i!==void 0&&(i.dev!==n.dev||i.ino!==n.ino||i.realPath!==n.realPath)&&(t.candidates.clear(),t.assetCatalogs.clear(),t.preparedCandidates.clear(),t.lastCandidateScanUnchanged=void 0,t.lastCandidateKeys=void 0,t.scanStartedAtNs=void 0,t.lastAssetCatalogsUnchanged=void 0,t.lastSnapshot=void 0,t.lastSnapshotBuildInputs=void 0,t.lastSnapshotCandidates=void 0,t.lastSnapshotCatalogFingerprint=void 0),t.rootIdentity=n,t}var Qo,nr=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 M("NOT_FOUND"):n==="ELOOP"?new M("PATH_ESCAPED"):n==="EFBIG"||n==="EOVERFLOW"?new M("LIMIT_EXCEEDED"):n==="EACCES"||n==="EPERM"||n==="ENOTDIR"?new M("READ_DENIED"):new M("READ_DENIED")}function fd(e){if(typeof e!="string"||e.length===0||!ae.isAbsolute(e))throw new M("READ_DENIED")}function oi(e){if(typeof e!="string"||ae.isAbsolute(e)||/[\\\u0000]/.test(e))throw new M("PATH_ESCAPED");if(e==="")return [];let n=e.split("/");if(n.some(t=>t.length===0||t==="."||t===".."))throw new M("PATH_ESCAPED");return n}function tt(e,n){let t=ae.relative(e,n);return t===""||t!==".."&&!t.startsWith(`..${ae.sep}`)&&!ae.isAbsolute(t)}function pn(e){return {dev:e.dev,ino:e.ino,size:e.size,mtimeNs:e.mtimeNs,ctimeNs:e.ctimeNs}}function ci(e,n){return e.dev===n.dev&&e.ino===n.ino}function di(e,n){return ci(e,n)&&e.size===n.size&&e.mtimeNs===n.mtimeNs&&e.ctimeNs===n.ctimeNs}async function Qn(e){fd(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 M("READ_DENIED");return {realRoot:n,identity:pn(t)}}async function or(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 M("READ_DENIED")}catch(r){throw r instanceof M?r:le(r)}if(!tt(n,o))throw new M("PATH_ESCAPED");return o}async function et(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(!tt(n,r)||t!==void 0&&!tt(t,r))throw new M("PATH_ESCAPED");if(!o.isFile()||!s.isFile())throw new M("READ_DENIED");if(!ci(i,o)||!ci(i,s)||i.dev!==s.dev)throw new M("PATH_ESCAPED")}async function dn(e,n){let t,i;try{t=await promises.realpath(e),i=await promises.stat(t,{bigint:!0});}catch{throw new M("PATH_ESCAPED")}if(t!==n.realRoot||!di(n.identity,pn(i)))throw new M("PATH_ESCAPED")}function yd(e){return e.isSymbolicLink()?{name:e.name,kind:"symlink"}:e.isDirectory()?{name:e.name,kind:"directory"}:e.isFile()?{name:e.name,kind:"file"}:{name:e.name,kind:"other"}}var M,ai,ud,ir,it,rr,li=V(()=>{m();M=class extends Error{constructor(t){super(t);this.code=t;}code;name="AppDiscoveryFsError"},ai=ee.constants.O_NOFOLLOW,ud=ee.constants.O_NONBLOCK,ir=ee.constants.O_RDONLY|(ai??0)|(ud??0);it=class{async getRootIdentity(n){let t=await Qn(n);return await dn(n,t),{dev:t.identity.dev,ino:t.identity.ino,realPath:t.realRoot}}async listDirectory(n,t){let i=oi(t),o=await Qn(n),r=ae.resolve(n,...i),s,a;try{s=await promises.realpath(r),a=await promises.stat(s,{bigint:!0});}catch(c){let d=le(c);if(d.code==="NOT_FOUND")return [];throw d}if(!tt(o.realRoot,s)||!a.isDirectory())throw new M("PATH_ESCAPED");try{let c=await promises.readdir(s,{withFileTypes:!0,encoding:"utf8"});return await dn(n,o),c.map(yd)}catch(c){let d=le(c);if(d.code==="NOT_FOUND")return [];throw d}}async readdir(n,t){return this.listDirectory(n,t)}async readDirectory(n,t){return this.listDirectory(n,t)}async readVerifiedFile(n,t,i){if(!Number.isSafeInteger(i)||i<0)throw new M("READ_DENIED");if(ai===void 0)throw new M("UNSUPPORTED");let o=oi(t),r=await Qn(n),s=ae.resolve(n,...o),a=ae.relative(n,s);if(a===".."||a.startsWith(`..${ae.sep}`)||ae.isAbsolute(a))throw new M("PATH_ESCAPED");let c;try{c=await promises.open(s,ir);}catch(d){throw le(d)}try{let d;try{let g=await c.stat({bigint:!0});d=pn(g);}catch(g){throw le(g)}if(d.size>BigInt(i))throw new M("LIMIT_EXCEEDED");if(d.size>BigInt(Number.MAX_SAFE_INTEGER))throw new M("LIMIT_EXCEEDED");await dn(n,r);let l=await or(n,r.realRoot,o);await et(s,r.realRoot,l,d);let p=new Uint8Array(new ArrayBuffer(Number(d.size))),u=0;for(;u<p.byteLength;){let g;try{g=(await c.read(p,u,p.byteLength-u,u)).bytesRead;}catch(_){throw le(_)}if(g<=0)throw new M("IDENTITY_CHANGED");u+=g;}let f;try{let g=await c.stat({bigint:!0});f=pn(g);}catch(g){throw le(g)}if(!di(d,f))throw new M("IDENTITY_CHANGED");return await et(s,r.realRoot,l,f),await dn(n,r),new Uint8Array(p)}finally{await c.close().catch(()=>{});}}async fingerprintVerifiedFile(n,t,i){if(!Number.isSafeInteger(i)||i<0)throw new M("READ_DENIED");if(ai===void 0)throw new M("UNSUPPORTED");let o=oi(t),r=await Qn(n),s=ae.resolve(n,...o),a=ae.relative(n,s);if(a===".."||a.startsWith(`..${ae.sep}`)||ae.isAbsolute(a))throw new M("PATH_ESCAPED");let c;try{c=await promises.open(s,ir);}catch(d){throw le(d)}try{let d;try{let u=await c.stat({bigint:!0});d=pn(u);}catch(u){throw le(u)}if(d.size>BigInt(i)||d.size>BigInt(Number.MAX_SAFE_INTEGER))throw new M("LIMIT_EXCEEDED");await dn(n,r);let l=await or(n,r.realRoot,o);await et(s,r.realRoot,l,d);let p;try{let u=await c.stat({bigint:!0});p=pn(u);}catch(u){throw le(u)}if(!di(d,p))throw new M("IDENTITY_CHANGED");return await et(s,r.realRoot,l,p),await dn(n,r),{...p,candidateRealPath:l??r.realRoot}}catch(d){throw d instanceof M?d:le(d)}finally{await c.close().catch(()=>{});}}async readFileVerified(n,t,i){return this.readVerifiedFile(n,t,i)}},rr=new it;});function Rn(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 ar(e){return typeof e=="string"&&Ee.test(e)?e:void 0}function Ed(e){return e.length>0&&e!=="."&&e!==".."&&!/[\\/\u0000]/.test(e)}function We(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 Td(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 Pd(e){if(e instanceof Uint8Array)return new Uint8Array(e);if(e instanceof ArrayBuffer)return new Uint8Array(e.slice(0));if(Array.isArray(e)&&e.every(n=>Number.isInteger(n)&&n>=0&&n<=255))return Uint8Array.from(e);throw new TypeError("filesystem port returned an invalid byte array")}function Nd(e){return hd.decode(e)}function Dd(e){return JSON.parse(Nd(e))}function cr(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 bd(e){if(e instanceof M)return cr(e.code);if(e!==null&&typeof e=="object"&&"code"in e){let n=e.code;if(typeof n=="string")return cr(n)}}function Re(e,n){let t=n();return Number.isFinite(t)&&Number.isFinite(e)&&t-e<=5e3}function Sd(e){if(typeof e.readVerifiedFile=="function")return e.readVerifiedFile;if(typeof e.readFileVerified=="function")return e.readFileVerified}function Md(e){if(typeof e.listDirectory=="function")return e.listDirectory;if(typeof e.readDirectory=="function")return e.readDirectory;if(typeof e.readdir=="function")return e.readdir}async function dr(e,n,t,i){let o=Sd(e);if(!o)throw new M("READ_DENIED");return Pd(await o.call(e,n,t,i))}async function yi(e,n,t){let i=Md(e);if(!i)throw new M("READ_DENIED");let o=await i.call(e,n,t);if(!Array.isArray(o))throw new M("READ_DENIED");return o.map(Td).filter(r=>r!==null)}function Ld(e,n,t,i){return Object.freeze({code:e,...{},source:n,relativePath:t})}function Rd(e){if(!Rn(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(We))};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 Od(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 rt(e){return Object.freeze({appIds:Object.freeze([...new Set(e.map(n=>n.appId))].sort(We)),definitionIds:Object.freeze([...new Set(e.map(n=>n.definition.id))].sort(We))})}function ot(e,n){let t=Object.keys(e).sort(We),i=[...n].sort(We);return t.length===i.length&&t.every((o,r)=>o===i[r])}function pr(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 wd(e){let n;try{n=Dd(e);}catch{return}if(!Rn(n)||!ot(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(!Rn(s))return;let a=["packageDir","appId","definition","files"],c=Object.hasOwn(s,"lineage"),d=Object.hasOwn(s,"launcher"),l=[...c?["lineage"]:[],...d?["launcher"]:[]];if(!ot(s,[...a,...l])||d&&s.launcher!==false)return;let p=pr(s.packageDir),u=ar(s.appId);if(!p||p.length!==2||p[0]!=="apps"||!Ed(p[1])||!u||t.has(s.packageDir)||!Rn(s.definition)||!ot(s.definition,["id","version","hash"]))return;let f=ar(s.definition.id),g=s.definition.version,_=s.definition.hash;if(!f||!Number.isSafeInteger(g)||g<1||typeof _!="string"||!fi.test(_)||!Array.isArray(s.files)||s.files.length<2||s.files.length>Ii)return;let P=new Set,C=[];for(let U of s.files){if(!Rn(U)||!ot(U,["path","sha256"]))return;let N=pr(U.path);if(!N||typeof U.sha256!="string"||!fi.test(U.sha256))return;let w=N.join("/"),j=`${s.packageDir}/${w}`;if(P.has(w)||i.has(j))return;P.add(w),i.add(j),C.push(Object.freeze({path:w,sha256:U.sha256}));}if(!q.some(U=>P.has(U))||!P.has("ui/index.html")||(o+=C.length,o>Id))return;t.add(s.packageDir),r.push(Object.freeze({packageDir:s.packageDir,...d?{launcher:false}:{},appId:u,definition:Object.freeze({id:f,version:g,hash:_}),lineage:Array.isArray(s.lineage)?s.lineage:[],files:Object.freeze(C.sort((U,N)=>We(U.path,N.path)))}));}return Object.freeze({version:1,packages:Object.freeze(r)})}function Ge(e){let n=bd(e);return n==="PATH_ESCAPED"||n==="IDENTITY_CHANGED"||n==="TOCTOU"?"PATH_ESCAPED":n==="LIMIT_EXCEEDED"?"LIMIT_EXCEEDED":"BUNDLE_INTEGRITY"}async function Cd(e,n,t,i,o){let r=[],s=async(a,c)=>{if(!Re(i,o))throw new M("LIMIT_EXCEEDED");if(c>2)throw new M("LIMIT_EXCEEDED");let d=await yi(e,n,a);for(let l of d){if(typeof l.name!="string"||l.name.length===0||l.name==="."||l.name===".."||/[\\/\u0000]/.test(l.name))throw new M("PATH_ESCAPED");let p=`${a}/${l.name}`;if(l.kind==="file"){if(r.push(p.slice(t.length+1)),r.length>Ii)throw new M("LIMIT_EXCEEDED")}else if(l.kind==="directory")await s(p,c+1);else throw l.kind==="symlink"?new M("PATH_ESCAPED"):new M("READ_DENIED")}};return await s(t,0),r.sort(We)}function Ud(e){return q.includes(e)?262144:e==="ui/index.html"?cn:e==="ui/state.json"?2097152:e.startsWith("ui/assets/")?md:gd}async function lr(e,n,t,i){if(e===void 0)return {packages:[],diagnostics:[],incomplete:false,reservedIds:_d};let o=Rd(e.reservedIds),r=[],s=(y,I,h)=>Ld(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 c;try{c=await dr(n,e.root,"bundle-index.json",Ad);}catch(y){return r.push(s(Ge(y),"bundle-index.json")),a()}let d=Di.createHash("sha256").update(c).digest("hex");if(d!==e.expectedIndexHash)return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a();let l=wd(c);if(l===void 0)return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a();if(!Od(rt(l.packages),o))return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a([],false,d);if(!Re(t,i))return r.push(s("LIMIT_EXCEEDED","bundle-index.json")),a(l.packages.map(y=>({indexEntry:y,failureCode:"LIMIT_EXCEEDED"})),true,d);let p;try{p=await yi(n,e.root,"");}catch(y){return r.push(s(Ge(y),"bundle-index.json")),a(l.packages.map(I=>({indexEntry:I,failureCode:Ge(y)})),false,d)}if(!Re(t,i))return r.push(s("LIMIT_EXCEEDED","bundle-index.json")),a(l.packages.map(y=>({indexEntry:y,failureCode:"LIMIT_EXCEEDED"})),true,d);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,d);let _=p.filter(y=>y.name!=="bundle-index.json"&&y.name!=="apps");if(_.length>0){let y=_.some(I=>I.kind==="symlink")?"PATH_ESCAPED":"BUNDLE_INTEGRITY";return r.push(s(y,"bundle-index.json")),a(g("BUNDLE_INTEGRITY"),false,d)}if(p.some(y=>y.name==="apps"&&y.kind!=="directory"))return r.push(s("PATH_ESCAPED","apps")),a(g("PATH_ESCAPED"),false,d);let P=[];if(f)try{P=await yi(n,e.root,"apps");}catch(y){return r.push(s(Ge(y),"apps")),a(g(Ge(y)),false,d)}if(!Re(t,i)||P.length>Ai)return r.push(s("LIMIT_EXCEEDED","apps")),a(g("LIMIT_EXCEEDED"),true,d);let C=new Map(l.packages.map(y=>[y.packageDir.slice(5),y])),U=P.filter(y=>!C.has(y.name));for(let y of U)r.push(s(y.kind==="symlink"?"PATH_ESCAPED":"BUNDLE_INTEGRITY",`apps/${y.name}`));if(U.length>0){let y=U.some(I=>I.kind==="symlink")?"PATH_ESCAPED":"BUNDLE_INTEGRITY";return a(g(y),false,d)}let N=new Set,w=new Map,j=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)}`,E=j.get(h)??[];E.push(y),j.set(h,E);}for(let y of [...w.values(),...j.values()])if(y.length>1)for(let I of y)N.add(I);let D=[],b=c.byteLength,R=false;for(let y of l.packages){if(!Re(t,i)){R=true,D.push({indexEntry:y,failureCode:"LIMIT_EXCEEDED"});continue}let I;try{let L=y.lineage[y.lineage.length-1];if(!L)throw new be("LINEAGE_INVALID","Definition lineage is missing");if(L.definition.id!==y.definition.id||L.version!==y.definition.version||L.hash!==y.definition.hash)throw new be("LINEAGE_STALE","Last lineage generation does not match bundle identity");I=Qt(y.lineage,{...L.definition,hash:L.hash}).entries;}catch(L){let W=L instanceof be?L.code:"LINEAGE_INVALID";r.push(s(W,y.packageDir)),D.push({indexEntry:y,failureCode:W});continue}let h=P.find(L=>L.name===y.packageDir.slice(5));if(!f||!h){D.push({indexEntry:y,failureCode:"BUNDLE_INTEGRITY"});continue}if(h.kind!=="directory"){D.push({indexEntry:y,failureCode:h.kind==="symlink"?"PATH_ESCAPED":"BUNDLE_INTEGRITY"});continue}let E;try{let L=await Cd(n,e.root,y.packageDir,t,i);if(!Re(t,i)){R=!0,D.push({indexEntry:y,failureCode:"LIMIT_EXCEEDED"});continue}let W=y.files.map(J=>J.path);if(L.length!==W.length||L.some((J,Se)=>J!==W[Se])){D.push({indexEntry:y,failureCode:"BUNDLE_INTEGRITY"});continue}E=new Map;let de;for(let J of y.files){if(!Re(t,i)){de="LIMIT_EXCEEDED",R=!0;break}if(b>=ui){de="LIMIT_EXCEEDED";break}let Se;try{Se=await dr(n,e.root,`${y.packageDir}/${J.path}`,Ud(J.path));}catch(gs){de=Ge(gs);break}if(!Re(t,i)){de="LIMIT_EXCEEDED",R=!0;break}if(b+Se.byteLength>ui){b=ui,de="LIMIT_EXCEEDED";break}if(b+=Se.byteLength,Di.createHash("sha256").update(Se).digest("hex")!==J.sha256){de="BUNDLE_INTEGRITY";break}E.set(J.path,Se);}if(de!==void 0){D.push({indexEntry:y,failureCode:de});continue}}catch(L){Re(t,i)||(R=true),D.push({indexEntry:y,failureCode:Ge(L)});continue}D.push({indexEntry:y,lineage:I,files:E,...N.has(y)?{failureCode:"DUPLICATE_ID"}:{}});}return a(D,R,d)}var Ad,Ai,Ii,Id,gd,md,ui,fi,hd,_d,gi=V(()=>{m();ei();Ve();$n();Zn();li();Ad=256*1024,Ai=64,Ii=128,Id=Ai*Ii,gd=2*1024*1024,md=8*1024*1024,ui=32*1024*1024,fi=/^[0-9a-f]{64}$/,hd=new TextDecoder("utf-8",{fatal:true}),_d=Object.freeze({appIds:Object.freeze([]),definitionIds:Object.freeze([])});});function xd(e){if(typeof e!="string"||!Ee.test(e))throw new TypeError("pluginId must be a safe UI plugin identifier");let n=`${mi}${e}`.length+7<=128?e:`hash_${Di.createHash("sha256").update(e,"utf8").digest("hex")}`;return {read:`${mi}${n}_read`,action:`${mi}${n}_action`}}function fr(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 jd(e,n){return n.length===0||n==="."||n===".."||/[\\/\u0000]/.test(n)?e==="skills"?"skills":"apps":`${e==="skills"?"skills":"apps"}/${n}`}function Fd(e){return e.length>0&&e!=="."&&e!==".."&&!/[\\/\u0000]/.test(e)}function On(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 Nr(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 Vd(e){if(e instanceof Uint8Array)return new Uint8Array(e);if(e instanceof ArrayBuffer)return new Uint8Array(e.slice(0));if(Array.isArray(e)&&e.every(n=>Number.isInteger(n)&&n>=0&&n<=255))return Uint8Array.from(e);throw new TypeError("filesystem port returned an invalid byte array")}function Dr(e){return vd.decode(e)}function Bd(e){return JSON.parse(Dr(e))}function Hd(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 at(e,n,t,i,o){let r={code:e,...i===void 0?{}:{pluginId:i},source:n,relativePath:t,...o?.reason===void 0?{}:{reason:Object.freeze({...o.reason})},...o?.files===void 0?{}:{files:Object.freeze([...o.files])}};return Object.freeze(r)}function yr(e){switch(e){case "ENOENT":return "NOT_FOUND";case "ELOOP":case "EXDEV":return "PATH_ESCAPED";case "EFBIG":case "EOVERFLOW":return "LIMIT_EXCEEDED";case "EACCES":case "EPERM":case "ENOTDIR":return "READ_DENIED";default:return e}}function se(e){if(e instanceof M)return yr(e.code);if(e!==null&&typeof e=="object"&&"code"in e){let n=e.code;if(typeof n=="string")return yr(n)}}function Ke(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 Ar(e){return {reason:e.reason,...e.code==="MANIFEST_DUAL_MISMATCH"?{files:e.files}:{}}}function Ir(e){return e==="MANIFEST_DUAL_MISMATCH"?e:br(e)}function zd(e){return br(e.code)}function br(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 Sr("UiPluginValidationError",e)}}function Sr(e,n){throw new Error(`Unmapped ${e} code: ${String(n)}`)}function Mr(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 Sr("McpAppContractError",e)}}function Oe(e,n){let t=n();return Number.isFinite(t)&&Number.isFinite(e)&&t-e<=5e3}function $d(e){return {pluginId:e.appId,definitionKey:`${e.definition.id}\0${String(e.definition.version)}`}}function Gd(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(fr(o)){let r=o.bin,s=typeof r=="string"?r:fr(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=Wd(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 Wd(e){if(e.startsWith("/")||e.includes("\\")||e.includes("\0"))return;let n=e.split("/").filter(t=>t!==".");if(!(n.length===0||n.some(t=>t.length===0||t==="..")))return n.join("/")}function Jd(){return globalThis.performance?.now()??Date.now()}function Je(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let n of Object.values(e))Je(n);return Object.freeze(e)}function gr(e){return Object.freeze(Array.from(e))}async function ct(e,n,t,i){if(n.pinnedFiles!==void 0){let a=n.pinnedFiles.get(t);if(a===void 0)throw new M("NOT_FOUND");if(a.byteLength>i)throw new M("LIMIT_EXCEEDED");return new Uint8Array(a)}let o=`${n.relativePath}/${t}`,r=n.scanContext,s=e.fingerprintVerifiedFile;if(r===void 0||!r.cacheable||typeof s!="function")return Er(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 Er(e,n.root,o,i),d=await s.call(e,r.workspaceRoot,o,i);return r.candidateRealPath=d.candidateRealPath,Rr(a,d)&&d.size===BigInt(c.byteLength)&&!Or(d,r.scanStartedAtNs)?r.files.set(o,{relativePath:o,byteLimit:i,fingerprint:d}):r.cacheable=!1,c}catch(a){let c=q.includes(t)&&se(a)==="NOT_FOUND"&&r.directoryListings.some(l=>l.relativePath===n.relativePath&&!dt(l.key,t)),d=t===B&&se(a)==="NOT_FOUND"&&Kd(r.directoryListings,n.relativePath);throw !c&&!d&&(r.cacheable=false),a}}function Kd(e,n){let t=e.find(o=>o.relativePath===n);if(t===void 0)return false;if(!dt(t.key,"dist"))return true;let i=e.find(o=>o.relativePath===`${n}/dist`);return i!==void 0&&!dt(i.key,"tools.json")}function Lr(e,n){return JSON.stringify([e.realPath,n.source,n.relativePath])}async function Yd(e,n,t,i,o,r,s,a){let c=e.fingerprintVerifiedFile,d=Lr(t,i),l=o.candidates.get(d),p=i.relativePath,u;try{u=await _r(e,n,p);}catch(R){if(se(R)!=="NOT_FOUND")throw R}let f=u===void 0?void 0:{relativePath:p,key:u};if(f!==void 0&&(i.source==="apps"||i.source==="skills")&&!q.some(R=>dt(f.key,R)))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 c=="function"?{memo:l}:typeof c!="function"?{}:{context:{state:o,cacheKey:d,workspaceRoot:n,scanStartedAtNs:r,directoryListings:Object.freeze([f]),priorFingerprints:new Map,files:new Map,cacheable:true}}:{timeLimitReached:true};let g=async R=>{if(R==="")return f;let y=`${i.relativePath}${R}`;try{let I=await _r(e,n,y);return I===void 0?void 0:{relativePath:y,key:I}}catch(I){if(se(I)==="NOT_FOUND")return;throw I}},_=await Promise.all(mr.map(g)),P=await Promise.all(Xd.map(g));if(!Oe(s,a))return {timeLimitReached:true};let C=typeof c=="function"&&_.every(R=>R!==void 0),U=_.filter(R=>R!==void 0),N=[...U,...P.filter(R=>R!==void 0)],w=new Map,j=l!==void 0&&C,D;if(l!==void 0&&typeof c=="function"){let R=await Promise.all(l.files.map(async y=>{if(!Oe(s,a))return {kind:"time",file:y};try{let I=await c.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(R.some(y=>y.kind==="time"))return {timeLimitReached:true};for(let y of R){if(y.kind==="error")throw y.error;if(y.kind==="missing"){j=false;continue}if(y.kind!=="fingerprint")continue;let{file:I,current:h}=y;w.set(I.relativePath,h),D??=h.candidateRealPath,(h.candidateRealPath!==l.candidateRealPath||!Rr(h,I.fingerprint)||Or(h,r))&&(j=false);}}let b=l!==void 0&&l.directoryListings.length===N.length&&l.directoryListings.every((R,y)=>R.relativePath===N[y]?.relativePath&&R.key===N[y]?.key);return l!==void 0&&C&&b&&j&&D===l.candidateRealPath?{memo:l}:!C||U.length!==mr.length?{}:{context:{state:o,cacheKey:d,workspaceRoot:n,scanStartedAtNs:r,directoryListings:Object.freeze(N),priorFingerprints:w,files:new Map,...D===void 0?{}:{candidateRealPath:D},cacheable:true}}}function dt(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 _r(e,n,t){let i=wr(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(Nr);if(!r.some(s=>s===null))return JSON.stringify(r.slice().sort((s,a)=>On(s.name,a.name)||On(s.kind,a.kind)).map(s=>[s.name,s.kind]))}function Rr(e,n){return e.dev===n.dev&&e.ino===n.ino&&e.size===n.size&&e.mtimeNs===n.mtimeNs&&e.ctimeNs===n.ctimeNs}function Or(e,n){let t=e.mtimeNs-n;return t>=-hr&&t<=hr}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 qd(e,n,t){let i=Di.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 Zd(e,n){let t={...e.definition,sourceHash:n},i;try{i=pe(t);}catch(r){throw r instanceof k&&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 Qd(e){return e.actions.some(n=>n.backend.type==="core"&&n.backend.handler!=="state.set")}function ep(e){if(typeof e.readVerifiedFile=="function")return e.readVerifiedFile;if(typeof e.readFileVerified=="function")return e.readFileVerified}function wr(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 Er(e,n,t,i){let o=ep(e);if(!o)throw new M("READ_DENIED");return Vd(await o.call(e,n,t,i))}async function np(e,n,t){let i=wr(e);if(!i)throw new M("READ_DENIED");let o=await i.call(e,n,t);if(!Array.isArray(o))throw new M("READ_DENIED");return o.map(Nr).filter(r=>r!==null)}function tp(e){let n=[];for(let t of [e.reserved,e.builtin])t&&n.push(t);return e.builtins&&"listMcpApps"in e.builtins?n.push(Tr(e.builtins)):e.builtins&&n.push(e.builtins),e.builtinCatalog&&n.push(Tr(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 Tr(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=at(n,e.source,e.relativePath,e.identity?.pluginId));}function ip(e,n){let t=new Set,i=new Map;for(let r of e){let s=r.identity?.pluginId;if(s===void 0)continue;let a=i.get(s)??[];a.push(r),i.set(s,a);}for(let r of i.values()){if(r.length<2)continue;let s=r.filter(c=>c.provenance!==void 0);if(s.length>0){let c=r.find(d=>n.has(d));if(c){for(let d of s)t.add(d);for(let d of r)d!==c&&d.provenance===void 0&&he(d,"RESERVED_ID");continue}for(let d of r)d.provenance===void 0&&he(d,"RESERVED_ID");if(s.length>1)for(let d of s)he(d,"DUPLICATE_ID");continue}let a=r.filter(c=>c.source==="apps");if(a.length>1){for(let c of a)he(c,"DUPLICATE_ID");for(let c of r.filter(d=>d.source==="skills"))he(c,"DUPLICATE_ID");}else for(let c of r.filter(d=>d.source==="skills"))he(c,"DUPLICATE_ID");}let o=new Map;for(let r of e){if(r.diagnostic?.code==="RESERVED_ID"||t.has(r)||r.provenance===void 0&&!n.has(r)&&i.get(r.identity?.pluginId??"")?.some(c=>c.provenance!==void 0))continue;let s=r.identity?.definitionKey;if(s===void 0)continue;let a=o.get(s)??[];a.push(r),o.set(s,a);}for(let r of o.values())if(r.length>1)for(let s of r)he(s,"DUPLICATE_ID");return t}function op(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 tp(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 c=[...e.filter(l=>l.provenance!==void 0&&l.diagnostic===void 0).flatMap(l=>l.candidate?[l.candidate]:[]),...(n.productBundleReservationMetadata?.candidates??[]).filter(l=>n.productBundleReservationMetadata?.indexHash!==void 0&&l.provenance?.indexHash===n.productBundleReservationMetadata.indexHash)],d=new Set;for(let l of e){let p=l.candidate;if(!(!p||l.diagnostic||l.source!=="apps"||l.provenance!==void 0)&&e.filter(u=>u.source==="apps"&&u.identity?.pluginId===p.pluginId).length===1&&c.some(u=>u.pluginId===p.pluginId)&&!(a.has(p.definitionId)&&!c.some(u=>u.pluginId===p.pluginId&&u.definitionId===p.definitionId))&&!c.some(u=>u.pluginId!==p.pluginId&&u.definitionId===p.definitionId)&&!e.some(u=>u.identity?.pluginId!==p.pluginId&&u.identity?.definitionKey===`${p.definitionId}\0${p.version}`&&u.diagnostic?.code!=="RESERVED_ID"))try{qo(p),d.add(l);}catch(u){he(l,u instanceof De?Mr(u.code):"EXEC_DENIED");}}for(let l of e){let p=l.candidate;p&&l.provenance===void 0&&!d.has(l)&&(s.has(p.pluginId)||a.has(p.definitionId))&&he(l,"RESERVED_ID");}return d}function rp(e){return [...e].sort((n,t)=>{let i=ur.indexOf(n.source)-ur.indexOf(t.source);return i!==0?i:On(n.relativePath,t.relativePath)})}function F(e,n,t){e.diagnostic=at(n,e.source,e.relativePath,e.identity?.pluginId,t);}async function Pr(e,n,t){let i=$e(t,{mode:"local"});if(!i.ok&&i.parseFailure){F(n,Ir(i.rejection.code),Ar(i.rejection));return}let o=Hd(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)}`){F(n,"BUNDLE_INTEGRITY");return}if(!i.ok&&i.builtinOnly){F(n,"RESERVED_ID");return}if(!i.ok){F(n,Ir(i.rejection.code),Ar(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(L=>({actionId:L.actionId,inputSchema:L.inputSchema})));}catch(L){if(L instanceof De){F(n,Mr(L.code));return}throw L}let a;try{a=await ct(e,n,"ui/index.html",cn);}catch(L){F(n,Ke(se(L),"entry"));return}if(a.byteLength>cn){F(n,"LIMIT_EXCEEDED");return}let c;try{c=Dr(a);}catch{F(n,"ENTRY_INVALID");return}if(a.byteLength===0||c.length===0){F(n,"ENTRY_INVALID");return}let d=Di.createHash("sha256").update(a).digest("hex");if(r.entryHash!==void 0&&r.entryHash!==d){F(n,"ENTRY_INVALID");return}let l={},p,u;if(r.initialState!==void 0){try{p=await ct(e,n,"ui/state.json",2097152);}catch(L){F(n,Ke(se(L),"initial"));return}if(p.byteLength>2097152){F(n,"LIMIT_EXCEEDED");return}try{let L=Bd(p),W=r.dataPaths??[],de=Ht(L,W);l=fe(de,0,W),Ze(l);}catch{F(n,"INITIAL_STATE_INVALID");return}if(u=Di.createHash("sha256").update(p).digest("hex"),r.initialState.hash!==void 0&&r.initialState.hash!==u){F(n,"INITIAL_STATE_INVALID");return}}let f={...r,entryHash:d,...r.initialState===void 0?{}:{initialState:{path:"ui/state.json",hash:u}}},g=gn(f),_=qd(f,a,p??new Uint8Array),P;try{P=Zd(g,_);}catch(L){if(L instanceof re){F(n,zd(L));return}throw L}let C;if(n.bundleLineage!==void 0){let L=n.bundleLineage[n.bundleLineage.length-1];if(!L){F(n,"LINEAGE_INVALID");return}let{legacy:W,...de}=L.definition,{hash:J,...Se}=P;if(ne(de)!==ne(Se)){F(n,"LINEAGE_STALE");return}if(W!==void 0&&(P={...P,legacy:W}),W!==void 0)try{P={...P,hash:pe(P)},ye(P);}catch{F(n,"LINEAGE_INVALID");return}C=n.bundleLineage;}if(n.bundleIdentity!==void 0&&n.bundleIdentity.appId!==r.pluginId){F(n,"BUNDLE_INTEGRITY");return}if(n.bundleIdentity!==void 0&&(n.bundleIdentity.definitionId!==P.id||n.bundleIdentity.version!==P.version||n.bundleIdentity.definitionHash!==P.hash)){F(n,"LINEAGE_STALE");return}let U=xd(r.pluginId),N=r.actions.length===0?{read:U.read}:U,w=Je(g),j=Je(f),D=Je(P),b=Je({...g.handlers}),R=gr(a),y=p===void 0?void 0:gr(p),I=Object.freeze({...n.provenance===void 0?{}:{provenance:n.provenance},entry:Object.freeze({path:"ui/index.html",hash:d,bytes:R}),...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:Je(i.mcpb)},relativePath:n.relativePath,manifest:j,normalized:w,name:r.name,description:r.description,...r.icon===void 0?{}:{icon:r.icon},...r.tone===void 0?{}:{tone:r.tone},definition:D,handlers:b,resources:I,html:c,entryBytes:R,entryHash:d,initialState:Je(l),...y===void 0?{}:{initialStateBytes:y},...u===void 0?{}:{initialStateHash:u},sourceHash:_,toolNames:Object.freeze(N)},E=n.provenance===void 0?{...h,source:n.source}:{...h,provenance:n.provenance,lineage:C??[]};n.candidate=Object.freeze(E),Qd(r)&&F(n,"EXEC_DENIED");}async function Cr(e,n){let t={};for(let i of q)try{t[i]=await ct(e,n,i,262144);}catch(o){if(se(o)==="NOT_FOUND")continue;return {files:t,failure:Ke(se(o),"manifest")}}if(t[G]!==void 0)try{t[B]=await ct(e,n,B,262144);}catch(i){if(se(i)!=="NOT_FOUND")return {files:t,failure:Ke(se(i),"manifest")}}return {files:t}}function _i(e){return q.some(n=>e[n]!==void 0)}async function sp(e,n){let{files:t,failure:i}=await Cr(e,n);if(i!==void 0){F(n,i);return}let o=t[G];return o!==void 0&&!Xt(o)&&(delete t[G],delete t[B]),_i(t)?t:void 0}function ap(e,n,t,i=kd,o=false,r=new Set){let s=rp(e),a=ip(s,r),c=Object.freeze(s.filter(u=>u.candidate!==void 0&&u.diagnostic===void 0&&!a.has(u)).map(u=>u.candidate)),d=Object.freeze(s.filter(u=>u.diagnostic!==void 0).map(u=>u.diagnostic)),l=o?Object.freeze({...t===void 0?{}:{indexHash:t},candidates:Object.freeze(s.filter(u=>u.source==="bundled"&&u.diagnostic===void 0&&t!==void 0&&u.candidate?.provenance?.indexHash===t).map(u=>u.candidate)),diagnostics:Object.freeze(d.filter(u=>u.source==="bundled").map(u=>Object.freeze({...u}))),reservedAppIds:Object.freeze([...i.appIds]),reservedDefinitionIds:Object.freeze([...i.definitionIds])}):void 0,p={apps:c,diagnostics:d,complete:n===void 0,...n===void 0?{}:{incompleteReason:n},...t===void 0?{}:{productBundleIndexHash:t},...l===void 0?{}:{productBundleSnapshotMetadata:l}};return Object.defineProperty(p,"candidates",{configurable:false,enumerable:false,get:()=>c}),Object.freeze(p)}function cp(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 dp(e,n){if(cp(e))return {fs:e,options:{}};let t=e??n??{};return {fs:t.filesystem??t.fileSystem??t.fs??rr,options:t}}async function Ur(e,n,t){if(typeof e!="string"||e.length===0)throw new TypeError("workspaceRoot must be explicit");let{fs:i,options:o}=dp(n,t),r=o.clock??Jd,s=r(),a=await lr(o.productBundle,i,s,r),c=r(),d=BigInt(Date.now())*1000000n,l=[],p=0,u,f=false,g,_;if(o.scanCache!==void 0&&typeof i.getRootIdentity=="function"&&typeof i.fingerprintVerifiedFile=="function")try{_=await i.getRootIdentity(e),g=er(o.scanCache,_),g.scanStartedAtNs=d;}catch(D){if(se(D)!=="NOT_FOUND")throw D}let P=g!==void 0&&o.productBundle===void 0&&a.packages.length===0&&a.diagnostics.length===0,C=new Set,U=true;l.push(...a.diagnostics.map(D=>({source:D.source,root:o.productBundle?.root??e,name:"",relativePath:D.relativePath,diagnostic:D})));let N=a.reservedIds;a.incomplete&&(u="time_limit");for(let D of a.packages){if(!Oe(c,r)){f=true,u="time_limit";break}let b=D.indexEntry,R=b.packageDir,y=D.files===void 0?void 0:Gd(R,D.files),I=a.indexHash===void 0?void 0:bo(Object.freeze({kind:"bundled",launcher:b.launcher!==false,indexHash:a.indexHash,packageDir:R,appId:b.appId,definitionId:b.definition.id,version:b.definition.version,definitionHash:b.definition.hash,files:b.files}),y),h={source:"bundled",root:o.productBundle?.root??e,name:R.slice(5),relativePath:R,...I===void 0?{}:{provenance:I},...D.files===void 0?{}:{pinnedFiles:D.files},...D.lineage===void 0?{}:{bundleLineage:D.lineage},bundleIdentity:{appId:b.appId,definitionId:b.definition.id,version:b.definition.version,definitionHash:b.definition.hash},identity:$d(b)};if(l.push(h),p+=1,D.failureCode!==void 0){F(h,D.failureCode);continue}if(D.files?.has(B)===true){F(h,"EXEC_DENIED",{reason:{path:"",rule:"bundled-tool-mode-unsupported",file:B}});continue}let E={};for(let L of q){let W=D.files?.get(L);W!==void 0&&(E[L]=W);}if(!_i(E)){F(h,"BUNDLE_INTEGRITY");continue}if(await Pr(i,h,E),!Oe(c,r)){f=true,u="time_limit";break}}let w=[{source:"apps",directory:"apps"},{source:"skills",directory:"skills"}];e:for(let D of w){let{source:b,directory:R}=D,y;try{y=await np(i,e,R);}catch(h){if(se(h)==="NOT_FOUND")continue;P=false,U=false,l.push({source:b,root:e,name:"",relativePath:b,diagnostic:at(Ke(se(h),"manifest"),b,b)});continue}let I=y.filter(h=>h.kind==="directory"||h.kind==="symlink").filter(h=>Fd(h.name)).map(h=>({source:b,root:e,name:h.name,relativePath:jd(b,h.name)})).sort((h,E)=>On(h.relativePath,E.relativePath));for(let h of I){let E={...h};if(l.push(E),_!==void 0?C.add(Lr(_,E)):P=false,!Oe(c,r)){f=true,u="time_limit";break e}let L;if(g!==void 0&&_!==void 0){try{let J=await Yd(i,e,_,E,g,d,c,r);if(J.timeLimitReached){f=!0,u="time_limit";break e}E.scanContext=J.context,L=J.memo;}catch(J){P=false,F(E,Ke(se(J),"manifest"));continue}L===void 0&&(P=false);}if(L!==void 0){if(E.candidate=L.candidate,E.diagnostic=L.diagnostic,E.identity=L.identity,b==="skills"&&L.candidate===void 0&&L.diagnostic===void 0)continue;if(p>=64){F(E,"LIMIT_EXCEEDED");continue}if(h.relativePath.split("/").length-1>2){F(E,"LIMIT_EXCEEDED");continue}if(p+=1,!Oe(c,r)){f=true,u="time_limit";break e}continue}let W;if(b==="skills"&&(W=await sp(i,E),W===void 0)){E.diagnostic===void 0&&hi(E);continue}if(p>=64){F(E,"LIMIT_EXCEEDED");continue}if(h.relativePath.split("/").length-1>2){F(E,"LIMIT_EXCEEDED");continue}if(!Oe(c,r)){f=true,u="time_limit";break e}if(p+=1,W===void 0){let J=await Cr(i,E);if(J.failure!==void 0||!_i(J.files)){F(E,J.failure??Ke("NOT_FOUND","manifest")),hi(E);continue}W=J.files;}if(await Pr(i,E,W),hi(E),!Oe(c,r)){f=true,u="time_limit";break e}}}if(g!==void 0&&_!==void 0){let D=[...C].sort(On),b=g.lastCandidateKeys,R=b!==void 0&&b.length===D.length&&b.every((I,h)=>I===D[h]);if(P=P&&R,U&&!f&&u===void 0)for(let I of g.candidates.keys())try{JSON.parse(I)[0]===_.realPath&&!C.has(I)&&g.candidates.delete(I);}catch{g.candidates.delete(I);}let y=[...g.candidates.keys()].filter(I=>{try{return JSON.parse(I)[0]===_.realPath}catch{return false}});P=P&&y.length===C.size&&y.every(I=>C.has(I))&&!f&&u===void 0,g.lastCandidateScanUnchanged=P,U&&!f&&u===void 0&&(g.lastCandidateKeys=Object.freeze(D));}f&&l.push({source:"apps",root:e,name:"",relativePath:"apps",diagnostic:at("DISCOVERY_TIME_LIMIT","apps","apps")});let j=op(l,o,N);return ap(l,u,a.indexHash,N,o.productBundle!==void 0,j)}var kd,mi,ur,vd,mr,Xd,hr,kr=V(()=>{m();Be();Un();Me();Yt();Ve();Zn();Zo();Wn();nr();li();Jn();gi();gi();kd=rt([]),mi="crewx_local_app_";ur=["bundled","apps","skills"],vd=new TextDecoder("utf-8",{fatal:true});mr=["","/ui"],Xd=["/dist"],hr=2000000000n;});m();Yt();m();wt();m();var fo="SKILL.md",Pc=/^---\s*\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;function yo(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function Nc(e){return e.isDirectory()||e.isSymbolicLink()}function ho(e){try{return ee.existsSync(e)&&ee.statSync(e).isDirectory()}catch{return false}}function qt(e){let n;try{n=ee.readFileSync(e,"utf8");}catch{return {frontmatter:{},readable:false,valid:false,hasFrontmatter:false}}let t=n.match(Pc);if(!t)return {frontmatter:{},readable:true,valid:true,hasFrontmatter:false};try{let i=Xr.load(t[1]??"");if(!yo(i))return {frontmatter:{},readable:!0,valid:!1,hasFrontmatter:!0};let o=yo(i.metadata)?i.metadata:void 0;return {frontmatter:{...typeof i.name=="string"?{name:i.name}:{},...typeof(o?.version??i.version)=="string"?{version:o?.version??i.version}:{},...typeof i.description=="string"?{description:i.description}:{}},readable:!0,valid:!0,hasFrontmatter:!0}}catch{return {frontmatter:{},readable:true,valid:false,hasFrontmatter:true}}}function Dc(e){return [ae.join(e,fo),ae.join(e,"skill",fo)]}function Ao(e,n){if(!ho(e))return null;for(let t of Dc(e)){if(!ee.existsSync(t))continue;let o=qt(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 Io(e){try{return ee.readdirSync(e,{withFileTypes:!0}).filter(Nc)}catch{return []}}function go(e,n,t){!e||n.has(e.name)||(n.add(e.name),t.push(e));}function _o(e){let n=[],t=new Set;for(let i of e)if(ho(i))for(let o of Io(i)){if(o.name.startsWith("@")){let r=ae.join(i,o.name);for(let s of Io(r))go(Ao(ae.join(r,s.name),s.name),t,n);continue}go(Ao(ae.join(i,o.name),o.name),t,n);}return n.sort((i,o)=>i.name.localeCompare(o.name))}m();$n();var bc=/^[A-Za-z0-9_$.[\]"-]{0,200}$/,Sc=/^[a-z][a-z0-9-]{0,63}$/,Mc="<unknown>";function Lc(e){return typeof e=="string"&&(q.includes(e)||e===B)}function Eo(e){if(typeof e!="object"||e===null)return;let{file:n,path:t,rule:i}=e;if(!(typeof i!="string"||!Sc.test(i)))return {...Lc(n)?{file:n}:{},path:typeof t=="string"&&bc.test(t)?t:Mc,rule:i}}function To(e){if(!Array.isArray(e))return;let n=q.filter(t=>e.includes(t));return n.length>0?n:void 0}kr();var lp=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/;function ut(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?up(e.relativePath,e.fileBytes):void 0);if(n!==void 0&&i!==void 0){let o=JSON.stringify({screenHash:n,skillHash:i});return Di.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 up(e,n){let t=new TextEncoder().encode(ft(e)),i=fp(n),o=new Uint8Array(t.byteLength+1+i.byteLength);return o.set(t,0),o[t.byteLength]=0,o.set(i,t.byteLength+1),Di.createHash("sha256").update(o).digest("hex")}function fp(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 ft(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 pt(e,n){let t=new TextEncoder().encode(e),i=new TextEncoder().encode(n),o=Math.min(t.byteLength,i.byteLength);for(let r=0;r<o;r+=1){let s=t[r]-i[r];if(s!==0)return s}return t.byteLength-i.byteLength}function jr(e,n){let t=ae.relative(e,n).split(ae.sep).join("/");return !t||t===".."||t.startsWith("../")||ae.isAbsolute(t)?null:ft(t)}function yp(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 Fr(e){return Object.freeze({packageRoot:e})}function Ap(e){return Object.freeze({id:e.definition.id,version:e.definition.version,hash:e.definition.hash,usage:e.definition.usage??ke,...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 Vr(e){return {capabilities:Object.freeze([...e]),origin:"local",ownership:"unknown",shareability:"unknown",sharingAvailability:"unavailable"}}function Ip(e,n){let t=e.candidate,i=t.provenance!==void 0,o=n&&!i?["screen","skill"]:["screen"],r=Ap(t),s=ut(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,...Vr(o),definition:r,...n===void 0||i?{}:{skillName:n.skill.name},...i?{provenance:t.provenance}:{localDefinitionRef:Fr(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 gp(e){let n=mp(e.skill.name),t={appId:n,name:e.skill.name,description:e.skill.description??"",...e.skill.version===void 0?{}:{version:e.skill.version},...Vr(["skill"]),skillName:e.skill.name,localDefinitionRef:Fr(e.packageRoot),definitionHash:ut({skillHash:e.skillHash})};return {packageRoot:e.packageRoot,source:e.source,appId:n,capabilities:["skill"],summary:Object.freeze(t)}}function mp(e){return `skill.${e.replace(/^@/,"").replace(/\//g,".").replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,122)||"unnamed"}`}function Z(e,n,t,i,o){let r=Eo(o?.reason),s=To(o?.files);return Object.freeze({code:e,source:n,relativePath:hp(t),...i===void 0?{}:{appId:i},...r===void 0?{}:{reason:r},...s===void 0?{}:{files:s}})}function hp(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 Br(e){return Z(e.code,e.source,e.relativePath,e.pluginId,e)}function _p(e,n){let t=jr(e,n.dir);if(!t)return {diagnostic:Z("PATH_ESCAPED","node_modules","node_modules")};let i=yp(t);if(!i)return {diagnostic:Z("PATH_ESCAPED","node_modules",t)};let o=qt(n.skillMdPath);if(!o.readable)return {diagnostic:Z("SKILL_READ_FAILED",i,t)};if(!o.valid)return {diagnostic:Z("SKILL_INVALID",i,t)};let r=Ep(n.dir,n.skillMdPath);if(!r)return {diagnostic:Z("PATH_ESCAPED",i,t)};try{let s=new Uint8Array(ee.readFileSync(n.skillMdPath));return {skill:n,packageRoot:t,relativeSkillPath:r,skillHash:ut({relativePath:r,fileBytes:s}),source:i}}catch{return {diagnostic:Z("SKILL_READ_FAILED",i,t)}}}function Ep(e,n){let t=ae.relative(e,n).split(ae.sep).join("/");try{return ft(t)}catch{return null}}function Tp(e){if(!lp.test(e.appId))return {diagnostic:Z("BUILTIN_INVALID","builtin",`builtin/${e.appId||"unknown"}`)};let n=e.definition===void 0?void 0:{id:e.definition.id,version:e.definition.version,hash:e.definition.hash,usage:e.definition.usage??ke,...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??Di.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 Pp(e){return e.builtinCatalog}function Np(e){let n=e.packageRoot??e.relativePath??e.packageRootPath;if(n===void 0)return null;try{return ft(n)}catch{return null}}function Dp(e){let n=e.marketplaceContentId;return typeof n=="string"&&n.length>0?n:void 0}function bp(e,n,t){let i=n.installed??[],o=new Map;for(let s of i){let a=Np(s);if(!a){t.push(Z("INSTALLED_IDENTITY_MISMATCH","installed","installed"));continue}let c=o.get(a);if(c&&JSON.stringify(c)!==JSON.stringify(s)){t.push(Z("INSTALLED_IDENTITY_MISMATCH","installed",a));continue}o.set(a,s);}let r=new Map;for(let s of e)s.packageRoot!==void 0&&r.set(s.packageRoot,s);for(let[s,a]of o){let c=r.get(s);if(!c){t.push(Z("INSTALLED_MISSING","installed",s,a.appId));continue}let d=Dp(a);if(!d){t.push(Z("INSTALLED_CONTENT_ID_MISSING","installed",s,a.appId));continue}if(a.appId!==void 0&&a.appId!==c.appId||a.definitionHash!==void 0&&a.definitionHash!==c.summary.definitionHash){t.push(Z("INSTALLED_IDENTITY_MISMATCH","installed",s,a.appId));continue}let l={...c.summary,origin:"installed",...a.slug===void 0?{}:{slug:a.slug},marketplaceContentId:d},p=e.indexOf(c);p>=0&&(e[p]={...c,summary:Object.freeze(l)});}}function Sp(e,n){let t=new Map;for(let o of e){let r=t.get(o.appId)??[];r.push(o),t.set(o.appId,r);}let i=new Set;for(let o of t.values()){if(o.length<2)continue;let r=o.some(s=>s.source==="builtin")?"builtin":o.some(s=>s.source==="bundled")?"bundled":void 0;if(r==="bundled"){let s=o.filter(a=>a.source==="apps"&&a.summary.definition!==void 0);if(s.length===1){for(let a of o)a.source==="bundled"?i.add(a):a!==s[0]&&(i.add(a),n.push(Z("RESERVED_ID",a.source,lt(a),a.appId)));continue}}if(r!==void 0){let s=o.filter(a=>a.source===r);for(let a of o.filter(c=>c.source!==r))i.add(a),n.push(Z("RESERVED_ID",a.source,lt(a),a.appId));if(s.length>1)for(let a of s)i.add(a),n.push(Z("DUPLICATE_ID",a.source,lt(a),a.appId));continue}for(let s of o)i.add(s),n.push(Z("DUPLICATE_ID",s.source,lt(s),s.appId));}return e.filter(o=>!i.has(o))}function lt(e){return e.packageRoot??e.summary.provenance?.packageDir??`builtin/${e.appId}`}function Mp(e,n){return e.filter(t=>!(t.code==="MANIFEST_MISSING"&&n.has(t.relativePath))).map(Br)}function Lp(e){return e.filesystem}function Rp(e,n){let t=Lp(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 Hr(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=Pp(n),i=await Ur(e,Rp(n,t)),o=n.registeredProductBundle??i.productBundleSnapshotMetadata,r=[ae.join(e,"skills"),ae.join(e,"node_modules"),ae.join(e,"apps")],s=[],a=[],c=[],d=new Set;for(let I of r)for(let h of _o([I])){let E=jr(e,h.dir);(E===null||!d.has(E))&&(c.push(h),E!==null&&d.add(E));}for(let I of c){let h=_p(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),_=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&&_.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 P=new Map(a.map(I=>[I.packageRoot,I])),C=[];for(let I of l.values()){let h=I.candidate.provenance===void 0?P.get(I.packageRoot):void 0,E=Ip(I,h);C.push({...E.packageRoot===void 0?{}:{packageRoot:E.packageRoot},source:E.source,appId:E.appId,summary:E.summary});}let U=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=gp(I);if(!(U.has(I.packageRoot)||N.has(I.packageRoot))){if(w.has(h.appId)){s.push(Z("RESERVED_ID",I.source,I.packageRoot,h.appId));continue}C.push({packageRoot:h.packageRoot,source:h.source,appId:h.appId,summary:h.summary});}}let j=[...Mp(i.diagnostics,new Set(a.map(I=>I.packageRoot))),...s,...n.registeredProductBundle?.diagnostics.filter(I=>I.source==="bundled").map(Br)??[]],D=[];if(t)for(let I of t.listMcpApps()){let h=Tp(I);"diagnostic"in h?j.push(h.diagnostic):D.push(h);}let b=Sp([...C,...D],j);bp(b,n,j);let R=b.map(I=>I.summary).sort((I,h)=>pt(I.appId,h.appId)),y=[...j].sort((I,h)=>pt(I.relativePath,h.relativePath)||pt(I.code,h.code)||pt(I.appId??"",h.appId??""));return Object.freeze({items:Object.freeze(R),diagnostics:Object.freeze(y)})}m();m();m();function Op(e){let n=o=>o.replace(/[.+^${}()|[\]\\]/g,"\\$&"),i=e.split("/").map(o=>o==="**"?".*":o.split("*").map(n).join("[^/]*"));return new RegExp(`^${i.join("\\/")}$`)}function ln(e,n){try{return Op(n).test(e)}catch{return false}}function yt(e,...n){let t=e.split("/");if(t.length<n.length)return false;let i=t.length-n.length;return n.every((o,r)=>ln(t[i+r],o))}function wp(e,n){return e.split("/").some(t=>ln(t,n))}var zr=[{label:".env*",test:e=>ln(e,".env*")},{label:".git/",test:(e,n,t)=>t&&e===".git"},{label:"memory/",test:(e,n,t)=>t&&e==="memory"},{label:"*.key",test:e=>ln(e,"*.key")},{label:"*.pem",test:e=>ln(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&&yt(n,".crewx","threads")},{label:".crewx/crewx.db",test:(e,n,t)=>!t&&yt(n,".crewx","crewx.db")},{label:".crewx/*.log",test:(e,n,t)=>!t&&yt(n,".crewx","*.log")},{label:".crewx/publish/",test:(e,n,t)=>t&&yt(n,".crewx","publish")},{label:".crewx/",test:(e,n)=>wp(n,".crewx")}];function un(e,n,t){for(let i of zr)if(i.test(e,n,t))return i.label;return null}m();var we=class extends Error{constructor(t,i){super(`publish: [${t}]${i?` ${i}`:""}`);this.code=t;}code;name="PublishError"};function T(e,n){return new we(e,n)}function $r(e,n){if(!n||/[\\\u0000]/.test(n)||ae__namespace.posix.isAbsolute(n)||n.split("/").some(f=>!f||f==="."||f===".."))throw T("PACKAGE_PATH_TRAVERSAL","package root must be a safe workspace-relative path");let t=ae__namespace.resolve(e),i=ae__namespace.resolve(t,...n.split("/"));if(!i.startsWith(`${t}${ae__namespace.sep}`))throw T("PACKAGE_PATH_TRAVERSAL","package root escaped the workspace");function o(f,g){let _;try{_=ee__namespace.lstatSync(f);}catch{throw T("PACKAGE_FILE_INVALID",`package directory is missing: ${g}`)}if(_.isSymbolicLink())throw T("PACKAGE_SYMLINK",`symlink is not publishable: ${g}`);if(!_.isDirectory())throw T("PACKAGE_FILE_INVALID",`not a package directory: ${g}`)}o(t,".");let r=t,s="",a=null;for(let f of n.split("/"))r=ae__namespace.join(r,f),s=s?`${s}/${f}`:f,o(r,s),a??=un(f,s,true);let c=[],d=[];function l(f,g){o(f,g);let _=ee__namespace.readdirSync(f,{withFileTypes:true});for(let P of _){let C=`${g}/${P.name}`,U=ae__namespace.join(f,P.name);if(P.isSymbolicLink())throw T("PACKAGE_SYMLINK",`symlink is not publishable: ${C}`);let N=un(P.name,C,P.isDirectory());N?d.push({path:C,rule:N}):P.isDirectory()?l(U,C):P.isFile()&&c.push(C);}}a?d.push({path:n,rule:a}):l(i,n);let p=new TextEncoder,u=(f,g)=>Buffer.compare(p.encode(f),p.encode(g));return c.sort(u),d.sort((f,g)=>u(f.path,g.path)),{included:c,excluded:d}}function Gr(e){let n=[],t=[];function i(o,r,s){let a;try{a=ee__namespace.readdirSync(o,{withFileTypes:!0});}catch{return}a.sort((c,d)=>c.name.localeCompare(d.name));for(let c of a){let d=r?`${r}/${c.name}`:c.name,l=ae__namespace.join(o,c.name);if(c.isSymbolicLink()){let p;try{p=ee__namespace.statSync(l);}catch{t.push({path:d,rule:"symlink"});continue}if(p.isDirectory()){t.push({path:d,rule:s??"symlink-dir"});continue}let u=s??un(c.name,d,false);u?t.push({path:d,rule:u}):t.push({path:d,rule:"symlink"});continue}if(c.isDirectory()){let p=s??un(c.name,d,true);i(l,d,p);continue}if(c.isFile()){let p=s??un(c.name,d,false);p?t.push({path:d,rule:p}):n.push(d);}}}return i(e,"",null),n.sort(),t.sort((o,r)=>o.path<r.path?-1:o.path>r.path?1:0),{included:n,excluded:t}}m();var Cp=[{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 Up(e){return e.includes(0)}function Ni(e,n,t){let i=[];for(let o of n){let r=ae__namespace.join(e,o),s;try{let c=t?.get(o);s=c===void 0?ee__namespace.readFileSync(r):Buffer.from(c);}catch{continue}if(Up(s))continue;s.toString("utf8").split(/\r\n|\r|\n/).forEach((c,d)=>{for(let{rule:l,regex:p}of Cp)p.test(c)&&i.push({path:o,line:d+1,rule:l});});}return i}m();var Kr=/^[a-z0-9-]+$/,kp=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/,xp=/^[A-Za-z_][A-Za-z0-9_]*$/;function vp(e){let n=ae__namespace.join(e,"crewx.yaml");if(!ee__namespace.existsSync(n))return {};let t;try{t=Xr__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 jp(e){return Di__namespace.createHash("sha256").update(e).digest("hex")}function Yr(e){let n;try{n=ee__namespace.lstatSync(e);}catch{throw T("PACKAGE_FILE_INVALID",`file is not readable: ${ae__namespace.basename(e)}`)}if(n.isSymbolicLink())throw T("PACKAGE_SYMLINK","symlink content is not publishable");if(!n.isFile())throw T("PACKAGE_FILE_INVALID","only regular files are publishable");return Di__namespace.createHash("sha256").update(new Uint8Array(ee__namespace.readFileSync(e))).digest("hex")}function Fp(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 qr(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 T("PACKAGE_PATH_TRAVERSAL","manifest file path must be a non-empty POSIX relative path")}function Vp(e){if(!/^(?:apps|skills)\/[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(e))throw T("APP_PACKAGE_ROOT_INVALID","packageRoot must be apps/<safe-id> or skills/<safe-id>")}function Zr(e){if(!kp.test(e))throw new Error(`publish: invalid version "${e}" \u2014 must be semver (e.g. 1.0.0)`)}function Qr(e,n,t={}){let i=vp(e),o=i.name??ae__namespace.basename(e);if(!Kr.test(o))throw new Error(`publish: invalid name "${o}" \u2014 must match ${Kr} (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");Zr(r);let s=Array.isArray(i.requiredEnv)?i.requiredEnv:[],a=[];for(let l of s){if(typeof l!="string"||!xp.test(l))throw new Error(`publish: requiredEnv must contain names only (no values), got "${String(l)}"`);a.push(l);}let c=n.map(l=>(qr(l),{path:l,sha256:Yr(ae__namespace.join(e,l))})).sort((l,p)=>l.path<p.path?-1:l.path>p.path?1:0),d={name:o,version:r,type:"template",description:i.description??"",files:c,requiredEnv:a};return i.crewxMinVersion&&(d.crewxMinVersion=i.crewxMinVersion),d}function Bp(e){let n=e.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"");if(!n)throw T("APP_PACKAGE_ROOT_INVALID","appId cannot produce a marketplace name");return n}function es(e,n){if(Vp(n.packageRoot),!n.version)throw new Error("publish: version is required for App publishing \u2014 pass opts.version");if(Zr(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 T("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 T("APP_UI_MANIFEST_INVALID","screen App is missing manifest.json or ui-plugin.json");if(s&&!a)throw T("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 T("APP_UI_MANIFEST_INVALID","screen App is missing ui/index.html")}if(t.includes("skill")&&!n.includedFiles.includes(`${i}SKILL.md`))throw T("APP_SKILL_MISSING","skill capability requires package-root SKILL.md");let o=new Set,r=n.includedFiles.map(s=>{if(qr(s),!s.startsWith(i))throw T("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?Yr(ae__namespace.join(e,s)):jp(a),...a===void 0?{}:{generated:true}}}).sort((s,a)=>Fp(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:Bp(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 ns(e){return Di__namespace.createHash("sha256").update(e).digest("hex")}function ss(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 T("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 T("PACKAGE_PATH_TRAVERSAL","archive path escaped its root");return i}function ts(e,n){let t=ss(e,n),i;try{i=ee__namespace.lstatSync(t);}catch{throw T("PACKAGE_FILE_INVALID","manifest file is missing")}if(i.isSymbolicLink())throw T("PACKAGE_SYMLINK","symlink content is not publishable");if(!i.isFile())throw T("PACKAGE_FILE_INVALID","only regular files are publishable");return new Uint8Array(ee__namespace.readFileSync(t))}async function as(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(is__namespace.tmpdir(),"crewx-publish-"));try{let a=new Set,c=[];for(let d of n.files){if(a.has(d.path))throw T("PACKAGE_PATH_TRAVERSAL","manifest contains duplicate file paths");a.add(d.path);let l=t.generatedFiles?.get(d.path);if(d.generated===!0&&l===void 0)throw T("PACKAGE_GENERATED_FILE_MISSING","generated manifest file bytes are missing");if(t.sourceFileHashes?.has(d.path)){let f=ts(e,d.path);if(t.sourceFileHashes.get(d.path)!==ns(f))throw T("PACKAGE_STAGED_BYTES_MISMATCH","workspace source changed before staging")}let p=l??ts(e,d.path);if(ns(p)!==d.sha256)throw T("PACKAGE_STAGED_BYTES_MISMATCH",`staged bytes differ for ${d.path}`);let u=ss(s,d.path);ee__namespace.mkdirSync(ae__namespace.dirname(u),{recursive:!0}),ee__namespace.writeFileSync(u,new Uint8Array(p)),c.push(d.path);}ee__namespace.writeFileSync(ae__namespace.join(s,"manifest.json"),JSON.stringify(n,null,2)),await rs__namespace.create({gzip:!0,file:r,cwd:s,portable:!0,noMtime:!0},["manifest.json",...c]),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 fn="/api/v1";var $p=201,Gp=200,Wp=409,bi=401,cs={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 Jp(){return process.env.WI013_FAKE_UPLOAD==="1"}function Kp(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 Xp(e){return e.replace(/\/+$/,"")}async function wn(e){try{return await e.json()}catch{return null}}function ds(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 Yp(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 qp(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 ps(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(cs,r))continue;let s=r,a=s==="APP_NAME_CONFLICT"?`marketplace name is already in use: ${n}`:void 0;return T(cs[s],a)}}async function Zp(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=Xp(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}${fn}/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 wn(a),d=Yp(c),l=qp(c),p=r&&l!==void 0?l:i,u;if(a.status===$p)u="created";else if(r&&a.status===Gp){if(d===void 0)throw T("PUBLISH_CONTENT_ID_MISSING","App republish did not return an opaque contentId");u="existing";}else if(a.status===Wp){if(r)throw ps(c,i)??T("APP_NAME_CONFLICT",`marketplace name is already in use: ${i}`);u="existing";}else throw a.status===bi?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 b;try{b=await fetch(`${n}${fn}/publisher/items`,{method:"GET",headers:{Authorization:`Bearer ${e.accessToken}`}});}catch{throw new Error("publish: [E_NETWORK] Publisher items request failed (network)")}let R=await wn(b);if(b.status!==200)throw new Error(`publish: [E_HTTP] Publisher items request failed \u2014 HTTP ${b.status}`);let I=ds(R,"publisher items",b.status)?.items;if(!Array.isArray(I))throw new Error(`publish: [E_MALFORMED] Publisher items response is malformed (expected data.items[]) \u2014 HTTP ${b.status}`);let h=I.find(E=>!E||typeof E!="object"?false:E.slug===i);if(!h||typeof h.version!="string")throw new Error(`publish: [E_MALFORMED] Publisher items response does not contain slug "${i}" \u2014 HTTP ${b.status}`);if(g=h.version,g!==e.manifest.version){let E;try{E=await fetch(`${n}${fn}/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(!E.ok)throw await wn(E),E.status===bi?new Error(`publish: [E_AUTH_EXPIRED] Authentication is expired or missing \u2014 please log in again (HTTP ${E.status})`):E.status===403?new Error(`publish: [E_FORBIDDEN] Version update is forbidden; only the item owner can update an existing item (HTTP ${E.status})`):new Error(`publish: [E_HTTP] Version update failed \u2014 HTTP ${E.status}`);f="applied";}}let _=ee__namespace.readFileSync(e.tgzPath),P=Jp()?Kp(_):_,C=new FormData;C.set("archive",new Blob([new Uint8Array(P)],{type:"application/gzip"}),`${p}-${e.manifest.version}.tgz`);let U=r&&d!==void 0?d:i,N;try{N=await fetch(`${n}${fn}/publisher/items/${encodeURIComponent(U)}/upload`,{method:"POST",headers:{Authorization:`Bearer ${e.accessToken}`},body:C});}catch{throw new Error("publish: [E_NETWORK] Upload request failed (network)")}if(N.status===bi)throw new Error("publish: [E_AUTH_EXPIRED] Authentication is expired or missing \u2014 please log in again (HTTP 401)");if(!N.ok){let b=await wn(N);if(r){let R=ps(b,p);if(R)throw R}throw new Error(`publish: [E_HTTP] Upload request failed \u2014 HTTP ${N.status}`)}let w=await wn(N),j=ds(w,"upload",N.status),D=typeof j.contentId=="string"&&j.contentId.length>0?j.contentId:d;if(r&&D===void 0)throw T("PUBLISH_CONTENT_ID_MISSING","App upload did not return an opaque contentId");return {slug:p,version:e.manifest.version,...D===void 0?{}:{contentId:D},artifactChecksum:j.artifactChecksum,artifactSizeBytes:j.artifactSizeBytes,submitOutcome:u,versionUpdate:f,serverVersionBefore:g}}var Qp=1e4,el=100*1024*1024;function Si(e){return Di__namespace.createHash("sha256").update(e).digest("hex")}function nl(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function Cn(e,n){if(!n||n.includes("\\")||n.includes("\0")||ae__namespace.posix.isAbsolute(n)||n.split("/").some(r=>r===".."||r.length===0))throw T("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 T("PACKAGE_PATH_TRAVERSAL","workspace file path escaped the workspace root");let o;try{o=ee__namespace.lstatSync(t);}catch{throw T("PACKAGE_FILE_INVALID",`workspace file is missing: ${n}`)}if(o.isSymbolicLink())throw T("PACKAGE_SYMLINK",`symlink is not publishable: ${n}`);if(!o.isFile())throw T("PACKAGE_FILE_INVALID",`not a regular file: ${n}`);return new Uint8Array(ee__namespace.readFileSync(t))}function us(e,n,t){let i=e??n;if(!Number.isSafeInteger(i)||i<=0)throw new we("PACKAGE_SIZE_LIMIT",`${t} must be a positive integer`);return i}function ys(e,n,t,i){let o=us(t.maxFileCount??t.maxFiles,Qp,"max file count"),r=us(t.maxTotalBytes??t.maxBytes,el,"max total bytes");if(n.length>o)throw new we("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+=Cn(e,a).byteLength,s>r)throw new we("PACKAGE_SIZE_LIMIT",`package exceeds byte limit (${r})`)}}function tl(e){return e.appId!==void 0||e.expectedDefinitionHash!==void 0}function il(e){let n=e.appId!==void 0,t=e.expectedDefinitionHash!==void 0;if(!n&&t)throw T("APP_ID_REQUIRED","appId is required with expectedDefinitionHash");if(n&&!t)throw T("APP_DEFINITION_HASH_REQUIRED","expectedDefinitionHash is required with appId");if(!n||!t)throw T("APP_ID_REQUIRED")}function ol(e,n){let t=e.filter(i=>i.appId===n);if(t.length===0)throw T("APP_NOT_FOUND",`no publishable App matches ${n}`);if(t.length!==1)throw T("APP_AMBIGUOUS",`more than one App matches ${n}`);return t[0]}function rl(e){let n=e.localDefinitionRef?.packageRoot;if(!n||!/^(?:apps|skills)\/[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(n))throw T("APP_PACKAGE_ROOT_INVALID","selected App is not rooted in apps/<safe-id> or skills/<safe-id>");return n}function Mi(e){let{path:n,rule:t}=e.reason;return `${e.code} at ${n===""?"<file>":n} (${t})`+(e.files.length>0?` [${e.files.join(", ")}]`:"")}function sl(e,n,t){let i=$e({[ce]:t},{mode:"published"});if(!i.ok)throw T("APP_UI_MANIFEST_INVALID",`generated ${ce} does not read: ${Mi(i.rejection)}`);if(sn(i.manifest)!==sn(n))throw T("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=$e({[G]:o,[ce]:t,...r===void 0?{}:{[B]:r}},{mode:"local"});if(!s.ok)throw T("APP_UI_MANIFEST_INVALID",Mi(s.rejection))}function al(e,n,t,i){let o={};for(let f of q){let g=`${t}/${f}`;i.includes(g)&&(o[f]=Cn(e,g));}let r=`${t}/${B}`;if(o[G]!==void 0&&i.includes(r)&&(o[B]=Cn(e,r)),Object.keys(o).length===0)throw T("APP_UI_MANIFEST_INVALID","selected screen App has no package manifest.json or ui-plugin.json");let s=$e(o,{mode:"local"});if(!s.ok)throw T("APP_UI_MANIFEST_INVALID",Mi(s.rejection));if(s.manifest.pluginId!==n.appId)throw T("APP_DEFINITION_CONFLICT",`${s.file} identity no longer matches the selected App`);let a=o[ce],c=a===void 0?void 0:Si(a),d=`${t}/ui/index.html`;if(!i.includes(d))throw T("APP_UI_MANIFEST_INVALID","screen entry is outside package scope");let l=Si(Cn(e,d)),p=JSON.parse(JSON.stringify(s.v2Input));if(p.entryHash=l,Object.prototype.hasOwnProperty.call(p,"initialState")){let f=p.initialState;if(!nl(f)||f.path!=="ui/state.json")throw T("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 T("APP_INITIAL_STATE_OUT_OF_SCOPE","initialState reference is outside the selected package");let _=Cn(e,g);p.initialState={...f,hash:Si(_)};}let u;try{let f=ze(p,{mode:"published"});u=new Uint8Array(Buffer.from(JSON.stringify(f),"utf8"));}catch(f){throw f instanceof re?T("APP_UI_MANIFEST_INVALID",f.code):T("APP_UI_MANIFEST_INVALID")}return sl(o,s.manifest,u),{bytes:u,...c===void 0?{}:{legacySourceHash:c}}}async function cl(e,n){let{included:t,excluded:i}=Gr(e);ys(e,t,n);let o=Qr(e,t,{version:n.version}),r=Ni(e,t);return {plan:{manifest:o,included:t,excluded:i,secretFindings:r},archiveOptions:{}}}async function dl(e,n){il(n);let t=await Hr(e),i=ol(t.items,n.appId);if(i.definitionHash!==n.expectedDefinitionHash)throw T("APP_DEFINITION_CONFLICT",`definitionHash changed for ${n.appId}`);let o=rl(i),{included:r,excluded:s}=$r(e,o),a=new Map,c=new Map;if(i.capabilities.includes("screen")){let u=al(e,i,o,r),f=`${o}/${ce}`;if(a.set(f,u.bytes),u.legacySourceHash!==void 0)c.set(f,u.legacySourceHash);else {r.push(f);let g=new TextEncoder;r.sort((_,P)=>Buffer.compare(g.encode(_),g.encode(P)));}}if(i.capabilities.includes("skill")&&!r.includes(`${o}/SKILL.md`))throw T("APP_SKILL_MISSING","skill capability requires package-root SKILL.md");ys(e,r,n,a);let d={appId:i.appId,version:n.version??"",description:i.description,capabilities:i.capabilities,packageRoot:o,...i.definition?.id===void 0?{}:{definitionId:i.definition.id},definitionHash:i.definitionHash,includedFiles:r,generatedFiles:a},l=es(e,d),p=Ni(e,r,a);return {plan:{manifest:l,included:r,excluded:s,secretFindings:p},archiveOptions:{generatedFiles:a,sourceFileHashes:c}}}async function As(e,n){let t=ae__namespace.resolve(e);if(tl(n))return dl(t,n);if(n.expectedDefinitionHash!==void 0)throw T("APP_ID_REQUIRED");return cl(t,n)}async function iA(e,n={}){return (await As(e,n)).plan}function pl(e){let n=e.map(t=>`${t.path}:${t.line} (${t.rule})`).join(", ");throw new we("PUBLISH_SECRET_FINDINGS",`aborted \u2014 secret findings must be resolved before packing: ${n}`)}async function Is(e,n={}){let t=ae__namespace.resolve(e),i=await As(t,n);i.plan.secretFindings.length>0&&pl(i.plan.secretFindings);let o=await as(t,i.plan.manifest,i.archiveOptions);return {manifest:i.plan.manifest,tgzPath:o}}async function oA(e,n={}){return Is(e,n)}async function rA(e,n){let t=await Is(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=el;exports.DEFAULT_PUBLISH_MAX_FILES=Qp;exports.EXCLUDE_RULES=zr;exports.MARKETPLACE_API_PREFIX=fn;exports.PublishError=we;exports.packApp=rA;exports.packPublish=Is;exports.packTemplate=oA;exports.planPublish=iA;exports.uploadToMarketplace=Zp;