@crewx/sdk 0.9.0-rc.146 → 0.9.0-rc.148
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/esm/index.js +212 -212
- package/dist/esm/publish/index.js +2 -2
- package/dist/esm/skills/index.js +2 -2
- package/dist/index.js +208 -208
- package/dist/mcp-app/candidate-registration.d.ts +4 -0
- package/dist/mcp-app/discovery.d.ts +1 -0
- package/dist/publish/index.js +2 -2
- package/dist/skills/index.js +2 -2
- package/package.json +1 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import*as oe from'path';import {resolve,relative,sep,isAbsolute,join}from'path';import'url';import*as ui from'crypto';import {createHash}from'crypto';import {isIP}from'net';import*as Z from'fs';import {constants,readFileSync,existsSync,statSync,readdirSync}from'fs';import {realpath,stat,readdir,open,lstat}from'fs/promises';import*as Ir from'js-yaml';import {load}from'js-yaml';import*as Nr from'os';import*as br from'tar';import {gunzipSync,gzipSync}from'zlib';var j=(e,n)=>()=>(e&&(n=e(e=0)),n);var g=j(()=>{});var R,Pn=j(()=>{g();R=class extends Error{constructor(t,i=t,o){super(i);this.code=t;this.currentRevision=o;}code;currentRevision;name="UiRuntimeError"};});function rt(e){return Fr.test(e)||Vr.test(e)}function de(){throw new R("INPUT_INVALID","JSON value is not projection-safe")}function $r(e){let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function it(e,n,t,i,o,r){if(n>i&&de(),e===null||typeof e=="string"||typeof e=="boolean")return typeof e=="string"&&(Br.test(e)||zr.test(e)&&!Jr(o,r)||Hr.test(e))&&de(),e;if(typeof e=="number")return Number.isFinite(e)||de(),e;(typeof e!="object"||e===void 0||typeof e=="function"||typeof e=="bigint")&&de();let s=e;t.has(s)&&de(),t.add(s);try{if(Array.isArray(e))return e.map(c=>it(c,n+1,t,i,o,r));$r(s)||de();let a={};for(let[c,d]of Object.entries(e))rt(c)&&de(),a[c]=it(d,n+1,t,i,[...o,c],r);return a}finally{t.delete(s);}}function Te(e,n=0,t=[]){(!Number.isInteger(n)||n<0||n>Wr)&&de(),(!Array.isArray(t)||t.some(o=>typeof o!="string"))&&de();let i=it(e,0,new Set,Gr+n,[],t);return (i===null||Array.isArray(i)||typeof i!="object")&&de(),i}function We(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 Jr(e,n){if(e.length===0)return false;let t=e.join(".");return n.some(i=>We(t,i))}function Je(e){try{let n=JSON.stringify(e);return n===void 0&&de(),n}catch{de();}}function ot(e){return Array.isArray(e)?e.map(ot):e!==null&&typeof e=="object"?Object.fromEntries(Object.keys(e).sort().map(n=>[n,ot(e[n])])):e}function re(e){return Je(ot(e))}function st(e){return Buffer.byteLength(e,"utf8")}var Fr,Vr,Br,Hr,zr,Gr,Wr,Pe=j(()=>{g();Pn();Fr=/(?:proof|token|secret|password|cookie|authorization|private[_-]?key|stack|exception|plugin[_-]?text)/i,Vr=/(?:url|uri|endpoint|path|file(?:name|path)?|cwd|shell|directory|dir|folder)$/i,Br=/<\/?[A-Za-z][^>]*>/,Hr=/^(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)/,zr=/^(?:https?|file|ftp|ws|wss):\/\//i;Gr=8,Wr=4;});var Ii=j(()=>{g();Pe();});var Nn,at=j(()=>{g();Nn=["text/plain","application/json"];});var gi=j(()=>{g();at();});function Ke(e){return Xr.has(e)||Yr.test(e)||qr.test(e)}var mi,Xr,Yr,qr,Dn,sn,Ae,ct,dt,pt,lt,ut,xe=j(()=>{g();mi=["__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"],Xr=new Set(mi),Yr=/(?:proof|token|secret|password|cookie|authorization|private[_-]?key|stack|exception|plugin[_-]?text)/i,qr=/(?:url|uri|endpoint|path|file(?:name|path)?|cwd|shell|directory|dir|folder)$/i;Dn=/^[A-Za-z0-9_]+$/,sn=/^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)*$/,Ae=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,ct=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/,dt=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,pt=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/,lt=["blue","violet","emerald","amber","rose","sky","slate","indigo"],ut=["inline","panel"];});function ft(e){return typeof e=="string"&&Nn.includes(e)}var hi=j(()=>{g();at();xe();});function bn(e){if(!yt(e))return false;let n=Object.keys(e);return !(n.some(t=>t!=="in"&&t!=="out")||n.length===0||Object.hasOwn(e,"in")&&!Zr(e.in)||Object.hasOwn(e,"out")&&!Qr(e.out))}function Zr(e){return yt(e)?Object.keys(e).every(t=>t==="mediaType"||t==="required")&&Object.hasOwn(e,"mediaType")&&ft(e.mediaType)&&(!Object.hasOwn(e,"required")||typeof e.required=="boolean"):false}function Qr(e){return yt(e)?Object.keys(e).every(t=>t==="mediaType"||t==="range")&&Object.hasOwn(e,"mediaType")&&ft(e.mediaType)&&(!Object.hasOwn(e,"range")||typeof e.range=="boolean"):false}function yt(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}var At=j(()=>{g();gi();hi();new TextDecoder("utf-8",{fatal:true,ignoreBOM:true});});function le(e){let t=e.renderer!==void 0||e.surfaces!==void 0||e.stateProjection!==void 0||e.dataPaths!==void 0||e.usage!==void 0||e.detailPanel!==void 0||e.displayModes!==void 0||e.summaryProjection!==void 0||e.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=Te(t);return createHash("sha256").update(re(i)).digest("hex")}function Ne(e){if(!/^\d+$/.test(String(e.version))||e.version<1||e.id.length<1||e.id.length>128)throw new R("DEFINITION_UNSUPPORTED","UI definition is invalid");if(e.sourceHash!==void 0&&(typeof e.sourceHash!="string"||!ns.test(e.sourceHash)))throw new R("DEFINITION_UNSUPPORTED","UI definition source hash is invalid");if(!/^[0-9a-f]{64}$/.test(e.hash)||le(e)!==e.hash)throw new R("DEFINITION_UNSUPPORTED","UI definition hash is invalid");for(let[n,t]of Object.entries(e.actions)){if(!n||!Array.isArray(t.capabilities)||t.capabilities.some(i=>!is(i)))throw new R("DEFINITION_UNSUPPORTED","UI action declaration is invalid");if(t.confirmation!==void 0&&t.confirmation!=="none"&&t.confirmation!=="native")throw new R("DEFINITION_UNSUPPORTED","UI action confirmation is invalid");if(t.inputKeys&&(!Array.isArray(t.inputKeys)||t.inputKeys.some(i=>typeof i!="string"||!i)))throw new R("DEFINITION_UNSUPPORTED","UI action input declaration is invalid");if(t.dataInputs!==void 0&&(!Array.isArray(t.dataInputs)||new Set(t.dataInputs).size!==t.dataInputs.length||t.dataInputs.some(i=>typeof i!="string"||!i||t.inputKeys!==void 0&&!t.inputKeys.includes(i))))throw new R("DEFINITION_UNSUPPORTED","UI action data input declaration is invalid");if(t.resultProjection&&It(t.resultProjection),t.content!==void 0&&!bn(t.content))throw new R("DEFINITION_UNSUPPORTED","UI action content declaration is invalid");if(t.env!==void 0&&(!Array.isArray(t.env)||t.env.length===0||new Set(t.env).size!==t.env.length||t.env.some(i=>i!=="CREWX_APP_INSTANCE_ID"&&i!=="CREWX_THREAD_ID")))throw new R("DEFINITION_UNSUPPORTED","UI action environment declaration is invalid")}if(e.renderer!==void 0&&(!e.renderer||e.renderer.length>128))throw new R("DEFINITION_UNSUPPORTED","UI definition renderer is invalid");if(e.surfaces&&(!Array.isArray(e.surfaces)||e.surfaces.some(n=>!n||n.length>64)))throw new R("DEFINITION_UNSUPPORTED","UI definition surfaces are invalid");if(e.usage!==void 0&&e.usage!=="card"&&e.usage!=="window")throw new R("DEFINITION_UNSUPPORTED","UI definition usage is invalid");if(e.detailPanel!==void 0&&typeof e.detailPanel!="boolean")throw new R("DEFINITION_UNSUPPORTED","UI definition detailPanel is invalid");if(e.displayModes&&(!Array.isArray(e.displayModes)||e.displayModes.length===0||new Set(e.displayModes).size!==e.displayModes.length||e.displayModes.some(n=>n!=="inline"&&n!=="floating"&&n!=="focused")))throw new R("DEFINITION_UNSUPPORTED","UI definition displayModes are invalid");if(e.usage==="card"&&e.displayModes!==void 0)throw new R("DEFINITION_UNSUPPORTED","Card definitions cannot declare displayModes");if(e.usage==="window"&&e.detailPanel!==void 0)throw new R("DEFINITION_UNSUPPORTED","Window definitions cannot declare detailPanel");if(e.stateProjection&&It(e.stateProjection),e.summaryProjection){It(e.summaryProjection);let n=new Set(e.stateProjection?.allow??[]);if(e.summaryProjection.allow.some(t=>!n.has(t)))throw new R("DEFINITION_UNSUPPORTED","UI summary projection exceeds state projection")}if(e.legacy!==void 0){if(!e.legacy||typeof e.legacy!="object"||Array.isArray(e.legacy)||Object.keys(e.legacy).some(o=>!["readTool","actionTool","hostTools","agentAccess"].includes(o)))throw new R("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(ts(r,o==="readTool"),n.has(r.name))throw new R("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 R("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 R("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 R("DEFINITION_UNSUPPORTED","UI legacy agent access is invalid");if(e.legacy.actionTool!==void 0&&(!i||Object.keys(i).length===0))throw new R("DEFINITION_UNSUPPORTED","UI legacy action tool requires its complete agent access map")}if(e.dataPaths!==void 0){let n=new Set(["__proto__","prototype","constructor"]);if(!Array.isArray(e.dataPaths)||e.dataPaths.length>16||new Set(e.dataPaths).size!==e.dataPaths.length||e.dataPaths.some(t=>typeof t!="string"||!/^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)*$/.test(t)||t.split(".").some(i=>n.has(i))||!(e.stateProjection?.allow??[]).some(i=>We(t,i))))throw new R("DEFINITION_UNSUPPORTED","UI definition dataPaths are invalid")}}function ts(e,n){if(!e||typeof e!="object"||Array.isArray(e))throw new R("DEFINITION_UNSUPPORTED","UI legacy tool metadata is invalid");let t=e,i=["name","description","inputSchema","textFallback","visibility"],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 R("DEFINITION_UNSUPPORTED","UI legacy tool metadata is invalid");try{let r=Te(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=Te(a.structuredContent);if(st(Je(c))>4*1024)throw new Error("fixed result size")}}catch{throw new R("DEFINITION_UNSUPPORTED","UI legacy tool metadata is not projection-safe")}}function It(e){if(!Array.isArray(e.allow)||e.allow.some(n=>!/^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)*$/.test(n)))throw new R("DEFINITION_UNSUPPORTED","UI projection policy is invalid")}function is(e){return e.length>0&&e.length<=128&&e!=="*"&&e!=="all"&&!/[/*]/.test(e)}var ns,ve=j(()=>{g();Pe();Pn();At();ns=/^[0-9a-f]{64}$/;});var B,Xe,gt=j(()=>{g();B="dist/tools.json",Xe="dist/main.mjs";});var we,mt=j(()=>{g();we="window";});function _i(e){if(!Array.isArray(e)||e.length===0)return false;let n=new Set;for(let t of e){if(!os.some(i=>i===t)||n.has(t))return false;n.add(t);}return true}var os,Ei=j(()=>{g();os=["CREWX_APP_INSTANCE_ID","CREWX_THREAD_ID"];});function H(e){throw new ht(e)}function Is(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 gs(e,n){let t=Object.getOwnPropertyDescriptor(e,n);return (!t||!("value"in t))&&H("CSP_ORIGIN_INVALID"),t.value}function Sn(e,n){if(!Object.prototype.hasOwnProperty.call(e,n))return [];let t=gs(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 ms(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 Ni(e,n){/\s|\\/u.test(e)&&H("CSP_ORIGIN_INVALID");let t=ls.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("[")?us:fs).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(A=>A.length>63||!ys.test(A))&&H("CSP_ORIGIN_INVALID");}let c=s.origin;return (c==="null"||!c.startsWith(`${i}://`))&&H("CSP_ORIGIN_INVALID"),{origin:c,hostname:a}}function hs(e){let n=e.split(".").map(Number);return ((n[0]*256+n[1])*256+n[2])*256+n[3]}function Di(e,n,t){let i=4294967295<<32-t>>>0;return (e&i)===(n&i)}function Mi(e){let n=hs(e);return Di(n,3221225472,24)?n!==3221225481&&n!==3221225482:As.some(([t,i])=>Di(n,t,i))}function _s(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 Es(e){let n=_s(e),t=Number(n>>112n),i=Number(n>>96n&0xffffn);if(n>>32n===0xffffn){let o=Number(n&0xffffffffn);return Mi([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 Ts(e,n){let t=e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e,i=isIP(t);if(i===4)return Mi(t);if(i===6)return Es(t);let o=e.toLowerCase().replace(/\.$/,"");return !o||!o.includes(".")||n.has(o)?true:ps.some(r=>o===r||o.endsWith(`.${r}`))}function bi(e){return Object.freeze([...new Set(e.map(n=>n.origin))].sort())}function Si(e){return JSON.stringify({baseUriDomains:[],connectDomains:e.connectDomains,declared:e.declared,frameDomains:e.frameDomains,resourceDomains:[]})}function Li(e,n={}){if(e===void 0){let y=Si({declared:false,connectDomains:[],frameDomains:[]});return Object.freeze({declared:false,connectDomains:Object.freeze([]),frameDomains:Object.freeze([]),resourceDomains:Object.freeze([]),baseUriDomains:Object.freeze([]),cspHash:createHash("sha256").update(y,"utf8").digest("hex")})}Is(e)||H("CSP_ORIGIN_INVALID");let t=Reflect.ownKeys(e);t.some(y=>typeof y!="string")&&H("CSP_ORIGIN_INVALID"),t.some(y=>!ds.has(y))&&H("CSP_AXIS_UNKNOWN");let i=Sn(e,"connectDomains"),o=Sn(e,"frameDomains"),r=Sn(e,"resourceDomains"),s=Sn(e,"baseUriDomains");(r.length>0||s.length>0)&&H("CSP_AXIS_UNSUPPORTED"),(ms(e)>ss||i.length>Pi||o.length>Pi||i.length+o.length>as||[...i,...o].some(y=>new TextEncoder().encode(y).byteLength>cs))&&H("CSP_LIMIT_EXCEEDED");let c=i.map(y=>Ni(y,"connectDomains")),d=o.map(y=>Ni(y,"frameDomains")),p=new Set((n.runtimeHostnames??[]).map(y=>y.toLowerCase().replace(/\.$/,"")));[...c,...d].some(y=>Ts(y.hostname,p))&&H("CSP_ORIGIN_FORBIDDEN");let A={declared:true,connectDomains:bi(c),frameDomains:bi(d)},m=Si(A);return Object.freeze({...A,resourceDomains:Object.freeze([]),baseUriDomains:Object.freeze([]),cspHash:createHash("sha256").update(m,"utf8").digest("hex")})}var ss,Pi,as,cs,ds,ps,ls,us,fs,ys,As,ht,Oi=j(()=>{g();ss=4096,Pi=16,as=32,cs=512,ds=new Set(["connectDomains","frameDomains","resourceDomains","baseUriDomains"]),ps=["localhost","local","internal","home.arpa","test","example","invalid","onion","lan","corp","home","intranet","private","localdomain"],ls=/^(https|wss):\/\/([^/?#]+)$/i,us=/^\[[^\]]+\](?::[0-9]+)?$/,fs=/^[^:\[\]]+(?::[0-9]+)?$/,ys=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/,As=[[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]],ht=class extends Error{constructor(t){super(t);this.code=t;}code;name="UiPluginCspNormalizationError"};});function cn(e,n){return n===void 0||n===""?e:e===""?n:n.startsWith("[")?`${e}${n}`:`${e}.${n}`}function f(e,n=e,t,i){throw new te(e,n,t,i)}function $(e,n){try{return n()}catch(t){throw t instanceof te?t.withPathPrefix(e):t}}function G(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;try{let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}catch{return false}}function w(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function Ys(e,n){let t={};for(let[i,o]of Object.entries(e))i!==n&&(t[i]=o);return t}function J(e,n,t=[]){let i=new Set([...n,...t]),o=Object.keys(e).find(s=>!i.has(s));o!==void 0&&f("MANIFEST_INVALID","MANIFEST_INVALID",o,"unknown-key");let r=n.find(s=>!w(e,s));r!==void 0&&f("MANIFEST_INVALID","MANIFEST_INVALID",r,"missing-key");}function Rn(e,n=false,t=false,i=false){return bs.test(e)||!i&&Ms.test(e)||Ss.test(e)||t&&Ri.test(e)||Ls.test(e)&&!(n&&/^\s*data:/i.test(e)&&!Ri.test(e))}function On(e,n=new Set,t=0,i=false,o=false,r=""){if(typeof e=="string"){Rn(e,i,o)&&f("UNSAFE_VALUE","UNSAFE_VALUE",r,"unsafe-value");return}if(!(e===null||typeof e!="object")){(t>8||n.has(e))&&f("MANIFEST_INVALID","MANIFEST_INVALID",r),n.add(e);try{if(Array.isArray(e)){e.forEach((s,a)=>On(s,n,t+1,!1,!1,cn(r,`[${a}]`)));return}G(e)||f("MANIFEST_INVALID","MANIFEST_INVALID",r);for(let[s,a]of Object.entries(e))On(a,n,t+1,i&&t===0&&(s==="name"||s==="description"),o,cn(r,s));}finally{n.delete(e);}}}function Ie(e,n){let t=e[n];return typeof t!="string"&&f("MANIFEST_INVALID"),t}function ue(e,n,t){let i=e[n];return (!Number.isSafeInteger(i)||i<t)&&f("MANIFEST_INVALID"),i}function _t(e){return Ds.test(e)||f("MANIFEST_INVALID"),e}function Ye(e){return Ns.test(e)||f("TOKEN_INVALID"),e}function qs(e){return Vi.test(e)||f("MANIFEST_INVALID"),e}function Zs(e){G(e)||f("MANIFEST_INVALID");let n={};for(let[t,i]of Object.entries(e)){let o=qs(t);G(i)||f("MANIFEST_INVALID");let r=i.type;if(r==="text"){J(i,["type","maxLength"]),n[o]={type:r,maxLength:ue(i,"maxLength",1)};continue}if(r==="text-list"){J(i,["type","max","itemMaxLength"]),n[o]={type:r,max:ue(i,"max",0),itemMaxLength:ue(i,"itemMaxLength",1)};continue}if(r==="step-list"){J(i,["type","min","max","labelMaxLength","detailMaxLength"]);let s=ue(i,"min",0),a=ue(i,"max",1);s>a&&f("MANIFEST_INVALID"),n[o]={type:r,min:s,max:a,labelMaxLength:ue(i,"labelMaxLength",1),detailMaxLength:ue(i,"detailMaxLength",1)};continue}typeof r=="string"&&f("SCHEMA_TYPE_UNSUPPORTED"),f("MANIFEST_INVALID");}return n}function Qs(e,n,t){let i=e[n];(!i||i.type!==t)&&f("MANIFEST_INVALID");}function Mn(e,n,t){let i=Ie(e,"field");return Vi.test(i)||f("MANIFEST_INVALID"),Qs(n,i,t),i}function ea(e,n){G(e)||f("MANIFEST_INVALID");let t=e.primitive;switch(typeof t!="string"&&f("MANIFEST_INVALID"),Xs.includes(t)||f("PRIMITIVE_UNKNOWN"),t){case "card-shell":return J(e,["primitive"]),{primitive:t};case "meta-banner":return J(e,["primitive","badgeToken","noticeToken"]),{primitive:t,badgeToken:Ye(Ie(e,"badgeToken")),noticeToken:Ye(Ie(e,"noticeToken"))};case "heading":return J(e,["primitive","field"]),{primitive:t,field:Mn(e,n,"text")};case "labeled-text":return J(e,["primitive","titleToken","field","variant"]),e.variant!=="callout"&&f("MANIFEST_INVALID"),{primitive:t,titleToken:Ye(Ie(e,"titleToken")),field:Mn(e,n,"text"),variant:"callout"};case "step-flow":return J(e,["primitive","titleToken","field"]),{primitive:t,titleToken:Ye(Ie(e,"titleToken")),field:Mn(e,n,"step-list")};case "text-list":{J(e,["primitive","titleToken","field"],["emptyToken","hideWhenEmpty"]);let i={primitive:t,titleToken:Ye(Ie(e,"titleToken")),field:Mn(e,n,"text-list")};return w(e,"emptyToken")&&(i.emptyToken=Ye(Ie(e,"emptyToken"))),w(e,"hideWhenEmpty")&&(typeof e.hideWhenEmpty!="boolean"&&f("MANIFEST_INVALID"),i.hideWhenEmpty=e.hideWhenEmpty),i}}return f("MANIFEST_INVALID")}function na(e,n){return Array.isArray(e)||f("MANIFEST_INVALID"),e.map(t=>ea(t,n))}function K(e="v2 manifest exceeds a contract limit",n,t){return f("LIMIT_EXCEEDED",e,n,t)}function pe(e="initial state is not projection-safe"){return f("INITIAL_STATE_INVALID",e)}function wi(e,n){return (typeof e!="string"||e.length===0||e.length>4096||e.trim().length===0||Ws.test(e)||Js.test(e))&&f("MANIFEST_INVALID",`${n} is invalid`),(Rn(e,true,true)||Os.test(e)||Rs.test(e)||ws.test(e))&&f("UNSAFE_VALUE",`${n} contains an unsafe value`),e}function Et(e,n){return (typeof e!="string"||!Ae.test(e))&&f("MANIFEST_INVALID",`${n} is invalid`),e}function ta(e){return (typeof e!="string"||!ct.test(e)||e==="*"||e==="all")&&f("MANIFEST_INVALID","action capability is invalid"),e}function Bi(e){return (typeof e!="string"||!Gs.test(e))&&f("MANIFEST_INVALID","resource hash is invalid"),e}function Tt(e,n=new Set,t=0,i=""){if(typeof e=="string"){e.length>4096&&K("v2 manifest string is too long",i,"string-too-long");return}if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){Number.isFinite(e)||f("MANIFEST_INVALID","v2 manifest contains a non-finite number",i,"non-finite-number");return}(e===void 0||typeof e=="function"||typeof e=="bigint")&&f("MANIFEST_INVALID","v2 manifest contains a non-JSON value",i,"non-json-value"),typeof e!="object"&&f("MANIFEST_INVALID","MANIFEST_INVALID",i),t>8&&K("v2 manifest nesting is too deep",i,"too-deep"),n.has(e)&&f("MANIFEST_INVALID","v2 manifest contains a cycle",i,"cycle"),n.add(e);try{if(Array.isArray(e)){e.length>128&&K("v2 manifest array is too long",i,"array-too-long"),e.forEach((o,r)=>Tt(o,n,t+1,cn(i,`[${r}]`)));return}G(e)||f("MANIFEST_INVALID","v2 manifest contains a non-plain object",i,"non-plain-object");for(let[o,r]of Object.entries(e))Tt(r,n,t+1,cn(i,o));}finally{n.delete(e);}}}function Hi(e){return (typeof e!="string"||e.length>4096||!sn.test(e))&&(typeof e=="string"&&e.length>4096&&K("projection path is too long"),f("MANIFEST_INVALID","projection paths must be canonical exact paths")),e.split(".").some(t=>Ke(t))&&f("MANIFEST_INVALID","projection paths cannot address reserved state keys"),e}function Pt(e){G(e)||f("MANIFEST_INVALID","projection policy must be an object"),J(e,["allow"]),Array.isArray(e.allow)||f("MANIFEST_INVALID","projection allow must be an array"),e.allow.length>128&&K("projection allowlist is too long");let n=[],t=new Set;for(let i of e.allow){let o=Hi(i);t.has(o)&&f("MANIFEST_INVALID","projection allowlist contains a duplicate path"),t.add(o),n.push(o);}return {allow:n}}function ia(e,n){if(e===void 0)return;Array.isArray(e)||f("MANIFEST_INVALID","dataPaths must be an array"),e.length>Ks&&K("dataPaths exceed the v2 limit");let t=[],i=new Set;for(let o of e){let r=Hi(o);i.has(r)&&f("MANIFEST_INVALID","dataPaths contain a duplicate path"),n.some(s=>We(r,s))||f("MANIFEST_INVALID","dataPaths must be projection-allowed"),i.add(r),t.push(r);}return t}function qe(e,n,t=Number.MAX_SAFE_INTEGER){return (!Number.isSafeInteger(e)||e<0||e>t)&&f("MANIFEST_INVALID",`${n} is invalid`),e}function Ui(e,n){return (typeof e!="number"||!Number.isFinite(e))&&f("MANIFEST_INVALID",`${n} is invalid`),e}function Nt(e,n=0,t=new Set){if(typeof e=="string")return (e.length>4096||Rn(e))&&f("UNSAFE_VALUE","schema enum contains an unsafe string"),e;if(e===null||typeof e=="boolean")return e;if(typeof e=="number")return Number.isFinite(e)||f("MANIFEST_INVALID","schema enum contains a non-finite number"),e;(n>8||typeof e!="object"||e===void 0)&&K("schema enum is too deep"),t.has(e)&&f("MANIFEST_INVALID","schema enum contains a cycle"),t.add(e);try{if(Array.isArray(e))return e.length>128&&K("schema enum array is too long"),e.map(o=>Nt(o,n+1,t));G(e)||f("MANIFEST_INVALID","schema enum contains a non-plain object");let i={};for(let[o,r]of Object.entries(e))Ke(o)&&f("MANIFEST_INVALID","schema enum contains a reserved key"),i[o]=Nt(r,n+1,t);return i}finally{t.delete(e);}}function oa(e,n){if(e===void 0)return;Array.isArray(e)||f("MANIFEST_INVALID","schema required must be an array"),e.length>64&&K("schema required list is too long");let t=[],i=new Set;for(let o of e)(typeof o!="string"||!sn.test(o))&&f("MANIFEST_INVALID","schema required contains an invalid key"),o.length>4096&&K("schema required key is too long"),i.has(o)&&f("MANIFEST_INVALID","schema required contains a duplicate key"),n&&!Object.prototype.hasOwnProperty.call(n,o)&&f("MANIFEST_INVALID","schema required references an undeclared property"),i.add(o),t.push(o);return t}function ra(e,n){let t=n?sn:Dn;return e.length>4096&&K("schema property name is too long"),(!t.test(e)||e.split(".").some(i=>Ke(i)))&&f("MANIFEST_INVALID","schema property name is invalid"),e}function Dt(e,n=0,t=false){G(e)||f("MANIFEST_INVALID","action inputSchema must be an object"),n>8&&K("action inputSchema is too deep");let i=e.type;i!=="object"&&i!=="string"&&i!=="number"&&i!=="integer"&&i!=="boolean"&&i!=="array"&&i!=="null"&&(typeof i=="string"&&f("SCHEMA_TYPE_UNSUPPORTED","action inputSchema type is unsupported"),f("MANIFEST_INVALID","action inputSchema type is required"));let o=["type","enum"];i==="string"&&o.push("minLength","maxLength"),i==="array"&&o.push("minItems","maxItems","items"),i==="object"&&o.push("minProperties","maxProperties","properties","required","additionalProperties"),(i==="number"||i==="integer")&&o.push("minimum","maximum"),J(e,["type"],o.filter(a=>a!=="type"));let r={type:i};if(w(e,"enum")&&(Array.isArray(e.enum)||f("MANIFEST_INVALID","schema enum must be an array"),e.enum.length>128&&K("schema enum is too long"),r.enum=e.enum.map(a=>Nt(a))),i==="string"&&(w(e,"minLength")&&(r.minLength=qe(e.minLength,"schema minLength",4096)),w(e,"maxLength")&&(r.maxLength=qe(e.maxLength,"schema maxLength",4096)),r.minLength!==void 0&&r.maxLength!==void 0&&r.minLength>r.maxLength&&f("MANIFEST_INVALID","schema string length bounds are inverted")),(i==="number"||i==="integer")&&(w(e,"minimum")&&(r.minimum=Ui(e.minimum,"schema minimum")),w(e,"maximum")&&(r.maximum=Ui(e.maximum,"schema maximum")),r.minimum!==void 0&&r.maximum!==void 0&&r.minimum>r.maximum&&f("MANIFEST_INVALID","schema numeric bounds are inverted")),i==="array"&&(w(e,"minItems")&&(r.minItems=qe(e.minItems,"schema minItems",128)),w(e,"maxItems")&&(r.maxItems=qe(e.maxItems,"schema maxItems",128)),r.minItems!==void 0&&r.maxItems!==void 0&&r.minItems>r.maxItems&&f("MANIFEST_INVALID","schema array length bounds are inverted"),w(e,"items")&&(r.items=Dt(e.items,n+1,false))),i==="object"){let a;if(w(e,"properties")){G(e.properties)||f("MANIFEST_INVALID","schema properties must be an object");let d=Object.entries(e.properties);d.length>64&&K("schema properties are too many"),a={};for(let[p,A]of d){let m=ra(p,t);a[m]=Dt(A,n+1,false);}r.properties=a;}w(e,"minProperties")&&(r.minProperties=qe(e.minProperties,"schema minProperties",64)),w(e,"maxProperties")&&(r.maxProperties=qe(e.maxProperties,"schema maxProperties",64)),r.minProperties!==void 0&&r.maxProperties!==void 0&&r.minProperties>r.maxProperties&&f("MANIFEST_INVALID","schema object property bounds are inverted");let c=oa(e.required,a);c!==void 0&&(r.required=c),w(e,"additionalProperties")&&(e.additionalProperties!==false&&f("MANIFEST_INVALID","schema additionalProperties must be false"),r.additionalProperties=false);}let s=JSON.stringify(r);return (s===void 0||Buffer.byteLength(s,"utf8")>65536)&&K("action inputSchema subtree is too large"),r}function sa(e){let n=Dt(e,0,true);return (n.type!=="object"||!n.properties)&&f("MANIFEST_INVALID","action inputSchema must declare object properties"),n}function aa(e){if(G(e)||f("MANIFEST_INVALID","action backend must be an object"),e.type==="core"){J(e,Fs);let n=e.handler;return (typeof n!="string"||!dt.test(n))&&f("MANIFEST_INVALID","core backend handler is invalid"),{type:"core",handler:n}}if(e.type==="skill"&&w(e,"entry"))return J(e,Hs),e.entry!==Xe&&f("MANIFEST_INVALID",`skill backend entry must be ${Xe}`),{type:"skill",entry:Xe};if(e.type==="skill"){J(e,Vs,Bs),(!Array.isArray(e.command)||e.command.length===0||e.command.length>16)&&f("MANIFEST_INVALID","skill backend command is invalid");let n=[];for(let i of e.command)(typeof i!="string"||i.length===0||i.length>256||!pt.test(i))&&f("MANIFEST_INVALID","skill backend command token is invalid"),n.push(i);let t=w(e,"env")?da(e.env):void 0;return {type:"skill",command:n,...t===void 0?{}:{env:t}}}f("MANIFEST_INVALID","action backend type is unsupported");}function ca(e){G(e)||f("MANIFEST_INVALID","action must be an object"),J(e,xs,vs),w(e,"_meta")&&$("_meta",()=>zi(e._meta));let n=$("actionId",()=>Et(e.actionId,"actionId"));rt(n)&&f("MANIFEST_INVALID",`actionId "${n}" is not projection-safe`,"actionId");let t=$("capability",()=>ta(e.capability)),i=e.mutation;typeof i!="boolean"&&f("MANIFEST_INVALID","action mutation must be boolean","mutation");let o=$("inputSchema",()=>sa(e.inputSchema)),r;if(w(e,"dataInputs")){Array.isArray(e.dataInputs)||f("MANIFEST_INVALID","action dataInputs must be an array","dataInputs");let p=o.properties,A=new Set,m=[];for(let y of e.dataInputs)(typeof y!="string"||!w(p,y)||A.has(y))&&f("MANIFEST_INVALID","action dataInputs must be unique declared properties","dataInputs"),A.add(y),m.push(y);r=m;}let s=$("resultProjection",()=>Pt(e.resultProjection)),a=$("backend",()=>aa(e.backend)),c;w(e,"content")&&((a.type!=="skill"||!bn(e.content))&&f("MANIFEST_INVALID","action content declaration is invalid","content"),c=pa(e.content));let d;if(w(e,"confirmation")){let p=e.confirmation;p!=="none"&&p!=="native"&&f("MANIFEST_INVALID","action confirmation is invalid","confirmation"),d=p;}return {actionId:n,capability:t,mutation:i,inputSchema:o,resultProjection:s,backend:a,...c===void 0?{}:{content:c},...r===void 0?{}:{dataInputs:r},...d===void 0?{}:{confirmation:d}}}function da(e){return _i(e)||f("MANIFEST_INVALID","skill backend env is invalid"),Object.freeze([...e])}function pa(e){return Object.freeze({...e.in===void 0?{}:{in:Object.freeze({...e.in})},...e.out===void 0?{}:{out:Object.freeze({...e.out})}})}function la(e){return G(e)||f("INITIAL_STATE_INVALID","initialState must be an object"),J(e,zs,$s),e.path!=="ui/state.json"&&f("MANIFEST_INVALID","initialState path is not fixed"),w(e,"hash")?{path:"ui/state.json",hash:Bi(e.hash)}:{path:"ui/state.json"}}function ua(e){let n=["wasm","terminal","htmlDocuments"];return (!G(e)||Object.keys(e).length===0||Object.keys(e).some(t=>!n.includes(t)||e[t]!==true))&&f("MANIFEST_INVALID","runtime must contain only known capability flags set to true"),{...e.wasm===true?{wasm:true}:{},...e.terminal===true?{terminal:true}:{},...e.htmlDocuments===true?{htmlDocuments:true}:{}}}function fa(e,n){let t;try{t=Li(e);}catch(i){let o=i!==null&&typeof i=="object"&&"code"in i&&typeof i.code=="string"?i.code:"CSP_ORIGIN_INVALID";return f("MANIFEST_INVALID",o,void 0,o.toLowerCase().replace(/_/g,"-"))}if(t.frameDomains.length>0&&f("MANIFEST_INVALID","external origins in csp are not enabled in this rollout",void 0,"csp-not-enabled"),t.connectDomains.length!==0)return n?.terminal===true&&f("MANIFEST_INVALID","runtime.terminal cannot be combined with csp.connectDomains","connectDomains","terminal-with-connect-domains"),Object.freeze({connectDomains:t.connectDomains})}function ya(e,n){On(G(e)&&w(e,"csp")?Ys(e,"csp"):e,new Set,0,true,true),Tt(e),G(e)||f("MANIFEST_INVALID"),J(e,Cs,ks),w(e,"_meta")&&$("_meta",()=>zi(e._meta)),e.manifestVersion!==2&&f("MANIFEST_INVALID");let t;w(e,"runtime")&&(t=$("runtime",()=>ua(e.runtime)));let i;w(e,"csp")&&(i=$("csp",()=>fa(e.csp,t)));let o=$("pluginId",()=>Et(e.pluginId,"pluginId")),r=$("definitionId",()=>Et(e.definitionId,"definitionId")),s=$("version",()=>ue(e,"version",1)),a=$("name",()=>wi(e.name,"name")),c=$("description",()=>wi(e.description,"description")),d;w(e,"icon")&&((typeof e.icon!="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(e.icon))&&f("MANIFEST_INVALID","icon is invalid","icon"),d=e.icon);let p;w(e,"tone")&&((typeof e.tone!="string"||!lt.includes(e.tone))&&f("MANIFEST_INVALID","tone is invalid","tone"),p=e.tone),e.entry!=="ui/index.html"&&f("MANIFEST_INVALID","entry path is not fixed","entry","fixed-value");let A;w(e,"entryHash")&&(A=$("entryHash",()=>Bi(e.entryHash)));let m;w(e,"initialState")&&(m=$("initialState",()=>la(e.initialState)));let y;w(e,"usage")&&(e.usage!=="card"&&e.usage!=="window"&&f("MANIFEST_INVALID","usage is invalid","usage"),y=e.usage);let h;w(e,"detailPanel")&&(typeof e.detailPanel!="boolean"&&f("MANIFEST_INVALID","detailPanel is invalid","detailPanel"),h=e.detailPanel);let O;if(w(e,"displayModes")){((y??we)!==we||!Array.isArray(e.displayModes)||e.displayModes.length===0)&&f("MANIFEST_INVALID","displayModes are only valid for window Apps","displayModes");let l=new Set(["inline","floating","focused"]);(new Set(e.displayModes).size!==e.displayModes.length||e.displayModes.some(u=>typeof u!="string"||!l.has(u)))&&f("MANIFEST_INVALID","displayModes are invalid","displayModes"),O=e.displayModes;}(y??we)===we&&h!==void 0&&f("MANIFEST_INVALID","detailPanel is card-only","detailPanel");let S=n.mode??"local";S!=="local"&&S!=="installed"&&S!=="published"&&f("MANIFEST_INVALID","manifest mode is invalid"),S!=="local"&&A===void 0&&f("MANIFEST_INVALID","installed manifests require entryHash","entryHash","required-when-installed"),S!=="local"&&m!==void 0&&m.hash===void 0&&f("MANIFEST_INVALID","installed manifests require initialState.hash","initialState.hash","required-when-installed"),(!Array.isArray(e.surfaces)||e.surfaces.length===0)&&f("MANIFEST_INVALID","surfaces are invalid","surfaces"),e.surfaces.length>2&&K("surfaces exceed the v2 limit","surfaces","too-many-items");let F=[],k=new Set;for(let l of e.surfaces)(typeof l!="string"||!ut.includes(l))&&f("MANIFEST_INVALID","surface is unsupported","surfaces"),k.has(l)&&f("MANIFEST_INVALID","surfaces contain a duplicate","surfaces","duplicate-item"),k.add(l),F.push(l);G(e.size)||f("MANIFEST_INVALID","size must be an object","size"),$("size",()=>J(e.size,["height"]));let v=$("size",()=>ue(e.size,"height",1));v>720&&K("size.height exceeds the v2 limit","size.height","too-large");let V=$("stateProjection",()=>Pt(e.stateProjection)),E=e.summaryProjection===void 0?void 0:$("summaryProjection",()=>Pt(e.summaryProjection));E!==void 0&&E.allow.some(l=>!V.allow.includes(l))&&f("MANIFEST_INVALID","summaryProjection must be a subset of stateProjection.allow","summaryProjection");let T=$("dataPaths",()=>ia(e.dataPaths,V.allow));Array.isArray(e.actions)||f("MANIFEST_INVALID","actions must be an array","actions"),e.actions.length>32&&K("actions exceed the v2 limit","actions","too-many-items");let C=[],D=new Set;for(let[l,u]of e.actions.entries()){let I=`actions[${l}]`,P=$(I,()=>ca(u));if(D.has(P.actionId)&&f("MANIFEST_INVALID","actions contain a duplicate actionId",`${I}.actionId`,"duplicate-item"),P.backend.type==="core"&&P.backend.handler==="state.set"){P.mutation||f("MANIFEST_INVALID","state.set actions must be mutations",`${I}.mutation`);for(let b of Object.keys(P.inputSchema.properties))V.allow.includes(b)||f("MANIFEST_INVALID","state.set input paths must be projection-allowed",`${I}.inputSchema.properties`);}D.add(P.actionId),C.push(P);}return {manifestVersion:2,pluginId:o,definitionId:r,version:s,name:a,description:c,...d===void 0?{}:{icon:d},...p===void 0?{}:{tone:p},entry:"ui/index.html",...A===void 0?{}:{entryHash:A},...t===void 0?{}:{runtime:t},...i===void 0?{}:{csp:i},...m===void 0?{}:{initialState:m},...y===void 0?{}:{usage:y},...h===void 0?{}:{detailPanel:h},...O===void 0?{}:{displayModes:O},surfaces:F,size:{height:v},stateProjection:V,...E===void 0?{}:{summaryProjection:E},...T===void 0?{}:{dataPaths:T},actions:C}}function zi(e){G(e)||f("MANIFEST_INVALID","_meta must be an object");let n=JSON.stringify(e);(n===void 0||Buffer.byteLength(n,"utf8")>js)&&K("_meta exceeds the 4 KiB limit",void 0,"meta-too-large");}function Aa(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 bt(e,n,t,i,o,r){if(typeof e=="string"){let s=o.length>0&&r.some(a=>We(o.join("."),a));return (e.length>4096||Rn(e,false,false,s))&&pe("state contains an unsafe string"),e}if(e===null||typeof e=="boolean")return e;if(typeof e=="number")return Number.isFinite(e)||pe("state contains a non-finite number"),e;(e===void 0||typeof e!="object"||typeof e=="function"||typeof e=="bigint")&&pe("state contains a non-JSON value"),t>8&&pe("state is too deep"),n.has(e)&&pe("state contains a cycle"),n.add(e);try{let s;if(Array.isArray(e))e.length>128&&pe("state array is too long"),s=e.map(c=>bt(c,n,t+1,65536,o,r));else {G(e)||pe("state contains a non-plain object");let c={};for(let[d,p]of Object.entries(e))(d.length>4096||!Dn.test(d)||Ke(d))&&(d.length>4096&&pe("state key is too long"),pe("state contains a reserved or invalid key")),c[d]=bt(p,n,t+1,65536,[...o,d],r);s=c;}let a=JSON.stringify(s);return (a===void 0||Buffer.byteLength(a,"utf8")>i)&&pe("state subtree is too large"),s}finally{n.delete(e);}}function Mt(e,n=[]){G(e)||pe("initial state must be a JSON object");let t=bt(e,new Set,0,65536,[],n);return (t===null||Array.isArray(t)||typeof t!="object")&&pe(),t}function Ia(e,n={}){On(e),G(e)||f("MANIFEST_INVALID"),J(e,Us),e.manifestVersion!==1&&f("MANIFEST_INVALID");let t=_t(Ie(e,"pluginId")),i=_t(Ie(e,"definitionId")),o=ue(e,"version",1),r=ue(e,"primitiveSet",1),s=n.supportedPrimitiveSet??Ps;(!Number.isSafeInteger(s)||s<1)&&f("MANIFEST_INVALID"),r>s&&f("PRIMITIVE_SET_UNSUPPORTED"),G(e.activation)||f("MANIFEST_INVALID"),J(e.activation,["kind","language"]),e.activation.kind!=="fenced-code"&&f("MANIFEST_INVALID");let a=_t(Ie(e.activation,"language")),c=Zs(e.schema),d=na(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 ga(e,n={}){return G(e)||f("MANIFEST_INVALID"),Object.hasOwn(e,"lineage")&&f("MANIFEST_INVALID","lineage is only allowed in product bundle indexes"),e.manifestVersion===2?ya(e,n):Ia(e,n)}function Fe(e,n={}){try{return ga(e,n)}catch(t){if(t instanceof te)throw t;return f("MANIFEST_INVALID")}}function dn(e,n={}){let t=Fe(e,n);return t.manifestVersion===2?Aa(t):t}var Ps,Ns,Ds,Vi,bs,Ss,Ms,Ls,Ri,Os,Rs,ws,Us,Cs,ks,xs,vs,js,Fs,Vs,Bs,Hs,zs,$s,Gs,Ws,Js,Ks,Xs,te,Lt=j(()=>{g();mt();Pe();At();Ei();gt();Oi();xe();Ps=1,Ns=/^[a-z][a-zA-Z0-9]*(\.[a-zA-Z0-9]+)+$/,Ds=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,Vi=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,bs=/<\/?[A-Za-z][^>]*>/,Ss=/^(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)/,Ms=/^(?:https?|file|ftp|ws|wss):\/\//i,Ls=/^\s*(?:javascript|data):/i,Ri=/data:[^,\s]*,/i,Os=/(?:https?|file|ftp|ws|wss):\/\//i,Rs=/javascript:/i,ws=/(?:^[\s]*|[\s"'(=])(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)(?=[^\s"'<>])[^\s"'<>]*/,Us=["manifestVersion","pluginId","definitionId","version","primitiveSet","activation","schema","layout"],Cs=["manifestVersion","pluginId","definitionId","version","name","description","entry","surfaces","size","stateProjection","actions"],ks=["_meta","icon","tone","entryHash","runtime","csp","initialState","usage","detailPanel","displayModes","summaryProjection","dataPaths","focusedAiDataPaths"],xs=["actionId","capability","mutation","inputSchema","resultProjection","backend"],vs=["confirmation","dataInputs","content","_meta"],js=4*1024,Fs=["type","handler"],Vs=["type","command"],Bs=["env"],Hs=["type","entry"],zs=["path"],$s=["hash"],Gs=/^[0-9a-f]{64}$/,Ws=/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/,Js=/[\r\n]/,Ks=16,Xs=["card-shell","meta-banner","heading","labeled-text","step-flow","text-list"],te=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,cn(t,this.path),this.rule)}};});function Xi(e){return typeof e=="string"&&e.length<=ha&&ma.test(e)}function U(e,n,t,i,o){throw new me(e,{path:n,rule:t,...i===void 0?{}:{message:i},...o===void 0?{}:{file:o}})}function Q(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;try{let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}catch{return false}}function X(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function ye(e){let n=`_meta["${Ue}"]`;return e===void 0||e===""?n:e.startsWith("[")?`${n}${e}`:`${n}.${e}`}function Pa(e){return e.toLowerCase().replace(/_/g,"-")}function Na(e){if(e===void 0||e==="")return "";let n=/^([^.[]+)(.*)$/.exec(e);if(!n)return ye(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 ye("definitionVersion");case "definitionId":return ye("definitionId");default:return ye(`${t}${i}`)}}function Yi(e,n,t){return {path:t(e.path),rule:e.rule??Pa(e.code),...e.message!==e.code?{message:e.message}:{},file:n}}function qi(e){return JSON.parse(JSON.stringify(e))}function wt(e,n,t=0,i=new Set){if(typeof e=="string"){e.length>4096&&U("LIMIT_EXCEEDED",n,"string-too-long"),(_a.test(e)||Ea.test(e)||Ta.test(e))&&U("UNSAFE_VALUE",n,"unsafe-value");return}if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){Number.isFinite(e)||U("MANIFEST_INVALID",n,"non-finite-number");return}typeof e!="object"&&U("MANIFEST_INVALID",n,"non-json-value"),t>8&&U("LIMIT_EXCEEDED",n,"too-deep"),i.has(e)&&U("MANIFEST_INVALID",n,"cycle"),i.add(e);try{if(Array.isArray(e)){e.length>128&&U("LIMIT_EXCEEDED",n,"array-too-long"),e.forEach((o,r)=>wt(o,`${n}[${r}]`,t+1,i));return}Q(e)||U("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 fe(e,n){return (typeof e!="string"||e.length===0)&&U("MANIFEST_INVALID",n,"string"),e}function Qe(e,n){return Q(e)||U("MANIFEST_INVALID",n,"object"),e}function Da(e,n){Array.isArray(e)||U("MANIFEST_INVALID",n,"array"),e.forEach((t,i)=>fe(t,`${n}[${i}]`));}function ba(e,n){typeof e!="boolean"&&U("MANIFEST_INVALID",n,"boolean");}function pn(e,n,t,i){for(let o of Object.keys(e))!t.includes(o)&&!i.includes(o)&&U("MANIFEST_INVALID",`${n}.${o}`,"unknown-key");for(let o of t)X(e,o)||U("MANIFEST_INVALID",`${n}.${o}`,"missing-key");}function Sa(e,n){switch(wt(n,e),e){case "long_description":case "homepage":case "documentation":case "support":case "icon":case "license":fe(n,e);return;case "author":{let t=Qe(n,e);pn(t,e,["name"],["email","url"]);for(let i of Object.keys(t))fe(t[i],`${e}.${i}`);return}case "repository":{let t=Qe(n,e);pn(t,e,[],["type","url"]);for(let i of Object.keys(t))fe(t[i],`${e}.${i}`);return}case "icons":{Array.isArray(n)||U("MANIFEST_INVALID",e,"array"),n.forEach((t,i)=>{let o=`${e}[${i}]`,r=Qe(t,o);pn(r,o,["src","size"],["theme"]),fe(r.src,`${o}.src`),fe(r.size,`${o}.size`),X(r,"theme")&&fe(r.theme,`${o}.theme`);});return}case "screenshots":case "keywords":case "privacy_policies":Da(n,e);return;case "tools":{Array.isArray(n)||U("MANIFEST_INVALID",e,"array"),n.forEach((t,i)=>{let o=`${e}[${i}]`,r=Qe(t,o);pn(r,o,["name"],["description"]),fe(r.name,`${o}.name`),X(r,"description")&&fe(r.description,`${o}.description`);});return}case "prompts":{Array.isArray(n)||U("MANIFEST_INVALID",e,"array"),n.forEach((t,i)=>{let o=`${e}[${i}]`,r=Qe(t,o);pn(r,o,["name","text"],["description","arguments"]),fe(r.name,`${o}.name`),fe(r.text,`${o}.text`);});return}case "tools_generated":case "prompts_generated":ba(n,e);return;case "localization":case "compatibility":case "user_config":Qe(n,e);return;default:U("MANIFEST_INVALID",e,"unknown-key");}}function wn(e){return typeof e=="string"&&Ae.test(e)?e:void 0}function Zi(e){return Number.isSafeInteger(e)&&e>=1?e:void 0}function Ma(e){let n=wn(e.name);if(n===void 0)return;let t=e._meta,i=Q(t)?t[Ue]:void 0,o=Q(i)?i:{},r=X(o,"definitionId")?wn(o.definitionId):n,s=X(o,"definitionVersion")?Zi(o.definitionVersion):1;return {pluginId:n,...r===void 0?{}:{definitionId:r},...s===void 0?{}:{definitionVersion:s}}}function La(e){let n=wn(e.pluginId);if(n===void 0)return;let t=wn(e.definitionId),i=Zi(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(!Q(n))return !1;let t=n._meta;return Q(t)&&X(t,Ue)}catch{return false}}function Oa(e,n){if(e===se)return n.builtinOnly===true;let t=n._meta,i=Q(t)?t[Ue]:void 0;return Q(i)&&i.builtinOnly===true}function Ra(e,n){X(e,"server")&&U("MANIFEST_INVALID","server","server-unsupported","phase 1 runs CrewX-owned Apps only");for(let a of Object.keys(e))Ut.includes(a)||U("MANIFEST_INVALID",a,"unknown-key");for(let a of Ct)X(e,a)||U("MANIFEST_INVALID",a,"missing-key");e.manifest_version!==Ot&&U("MANIFEST_INVALID","manifest_version","unsupported-version",`manifest_version must be "${Ot}"`),Xi(e.version)||U("MANIFEST_INVALID","version","semver","version must be a semver.org version such as 0.1.0");let t=e._meta;Q(t)||U("MANIFEST_INVALID","_meta","object"),X(t,Ue)||U("MANIFEST_INVALID",ye(),"missing-key");let i=t[Ue];Q(i)||U("MANIFEST_INVALID",ye(),"object");for(let a of Object.keys(i))Rt.includes(a)||Ki.includes(a)||U("MANIFEST_INVALID",ye(a),"unknown-key");for(let a of Rt)a==="actions"&&n!==void 0||X(i,a)||U("MANIFEST_INVALID",ye(a),"missing-key");if(n!==void 0&&X(i,"actions")&&U("MANIFEST_INVALID",ye("actions"),"two-truths",`actions are declared in both ${W} and ${B}; a server.ts App keeps them in the tools file only`),wa(i.actions),X(i,"definitionVersion")){let a=i.definitionVersion;(!Number.isSafeInteger(a)||a<1)&&U("MANIFEST_INVALID",ye("definitionVersion"),"positive-integer");}let o={};for(let a of Ji)X(e,a)&&(Sa(a,e[a]),o[a]=qi(e[a]));let r={};for(let[a,c]of Object.entries(t))a!==Ue&&(r[a]=c);let s={manifestVersion:2,pluginId:e.name,definitionId:X(i,"definitionId")?i.definitionId:e.name,version:X(i,"definitionVersion")?i.definitionVersion:1,name:e.display_name,description:e.description};for(let[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:Xe}}))),Object.keys(r).length>0&&(s._meta=r),{v2Input:s,...Object.keys(r).length>0?{vendorMeta:r}:{},passthrough:o}}function wa(e){Array.isArray(e)&&e.forEach((n,t)=>{let i=Q(n)?n.backend:void 0;Q(i)&&X(i,"entry")&&U("MANIFEST_INVALID",ye(`actions[${t}].backend.entry`),"entry-not-authorable",`an action in ${W} cannot name an entry; a server.ts App declares its actions in ${B}`);});}function Ua(e,n,t){Q(e)||U("MANIFEST_INVALID","","not-object","manifest.json must be a JSON object",W);let i;try{i=Ra(e,t);}catch(s){throw s instanceof me?new me(s.code,{...s.reason,file:W}):s}let o;try{let s=Fe(i.v2Input,{mode:n.mode??"local"});s.manifestVersion!==2&&U("MANIFEST_INVALID","","v2-required"),o=s;}catch(s){throw s instanceof te?new me(s.code,Yi(s,W,Na)):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 me("MANIFEST_INVALID",{path:`tools[${c}].name`,rule:"tool-not-action",message:"every tools[].name must be an action id",file:W})});}return {file:W,manifest:o,v2Input:i.v2Input,releaseVersion:e.version,...Object.keys(i.passthrough).length>0?{mcpb:i.passthrough}:{}}}function Ca(e,n){try{let t=Fe(e,{mode:n.mode??"local"});if(t.manifestVersion!==2)throw new me("MANIFEST_INVALID",{path:"manifestVersion",rule:"v2-required",message:"a workspace App requires manifestVersion 2",file:se});return {file:se,manifest:t,v2Input:e}}catch(t){throw t instanceof te?new me(t.code,Yi(t,se,i=>i??"")):t}}function en(e){return le(dn(e).definition)}function Gi(e){let{entryHash:n,initialState:t,...i}=e,o={...i};return t!==void 0&&(o.initialState={path:t.path}),qi(o)}function ka(e,n){let t=Gi(e),i=Gi(n);return [...new Set([...Object.keys(t),...Object.keys(i)])].sort().filter(r=>re(t[r]??null)!==re(i[r]??null))}function xa(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 va(e,n){let t=ka(e,n),i=xa(e,n),o="";try{let r=en(e),s=en(n);i=i||r!==s,o=` (definition hash ${r.slice(0,12)} vs ${s.slice(0,12)})`;}catch{i=true;}t.length===0&&!i||U("MANIFEST_DUAL_MISMATCH","","dual-manifest-mismatch",`${W} and ${se} normalize to different definitions${o}`+(t.length>0?`; differing fields: ${t.join(", ")}`:""));}function ge(e,n,t="MANIFEST_INVALID",i){return {code:t,reason:{path:e,rule:n,...i===void 0?{}:{message:i},file:B},files:[]}}function Wi(e){return {...ge("","tools-needs-manifest-json","MANIFEST_INVALID",`${B} is read with ${W} only`),files:e}}function ja(e,n){if(e.byteLength>n)return {failure:ge("","file-too-large","LIMIT_EXCEEDED")};let t;try{t=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e));}catch{return {failure:ge("","invalid-json")}}if(!Q(t))return {failure:ge("","not-object","MANIFEST_INVALID",`${B} must be a JSON object`)};for(let o of Object.keys(t))if(o!=="schemaVersion"&&o!=="actions")return {failure:ge(o,"unknown-key")};for(let o of ["schemaVersion","actions"])if(!X(t,o))return {failure:ge(o,"missing-key")};if(t.schemaVersion!==1)return {failure:ge("schemaVersion","unsupported-version","MANIFEST_INVALID",`schemaVersion must be ${1}`)};let i=t.actions;if(!Array.isArray(i))return {failure:ge("actions","array")};for(let[o,r]of i.entries()){if(!Q(r))return {failure:ge(`actions[${o}]`,"object")};if(X(r,"backend"))return {failure:ge(`actions[${o}].backend`,"tools-backend","MANIFEST_INVALID",`an action in ${B} cannot carry a backend`)}}return {actions:i}}function Fa(e,n){let t=n.maxBytes??262144,i=[],o=new TextDecoder("utf-8",{fatal:true});for(let r of Y){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(!Q(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 Ve(e,n={}){let{parsed:t,failure:i}=Fa(e,n),o=Y.filter(y=>e[y]!==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:ja(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:[]}:Wi(o),parseFailure:true,builtinOnly:false};let a=t[0],c=a.file===W?Ma(a.raw):La(a.raw),d=t.some(y=>Oa(y.file,y.raw)),p;if(s!==void 0){let y=t.some(h=>h.file===W)?s.failure:Wi(o);if(y!==void 0)return {ok:false,rejection:y,parseFailure:false,...c===void 0?{}:{identity:c},builtinOnly:d};p=s.actions;}let A=[];try{for(let y of t)A.push(y.file===W?Ua(y.raw,n,p):Ca(y.raw,n));A.length===2&&va(A[0].manifest,A[1].manifest);}catch(y){if(y instanceof me)return {ok:false,rejection:{code:y.code,reason:y.reason,files:y.code==="MANIFEST_DUAL_MISMATCH"?[...Y]:y.reason.file===void 0||y.reason.file===B?o:[y.reason.file]},parseFailure:false,...c===void 0?{}:{identity:c},builtinOnly:d};throw y}let m=A[0];return {ok:true,...m,identity:c??{pluginId:m.manifest.pluginId},files:o}}var W,se,Y,Ot,Ue,Ut,Ct,Ji,Rt,Ki,ma,ha,_a,Ea,Ta,me,Un=j(()=>{g();ve();Pe();gt();xe();Lt();W="manifest.json",se="ui-plugin.json",Y=[W,se],Ot="0.3",Ue="dev.crewx",Ut=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"]),Ct=Object.freeze(["manifest_version","name","display_name","version","description","_meta"]),Ji=Object.freeze(Ut.filter(e=>e!=="server"&&!Ct.includes(e))),Rt=Object.freeze(["entry","surfaces","size","stateProjection","actions"]),Ki=Object.freeze(["definitionId","definitionVersion","icon","tone","entryHash","runtime","initialState","usage","detailPanel","displayModes","summaryProjection","dataPaths","focusedAiDataPaths","csp"]),ma=/^(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-]+)*))?$/,ha=256,_a=/<\/?[A-Za-z][^>]*>/,Ea=/^\s*javascript:/i,Ta=/data:[^,\s]*,/i;me=class extends Error{constructor(t,i){super(`${t}: ${i.path||"<file>"} (${i.rule})`);this.code=t;this.reason=i;}code;reason};});var xt=j(()=>{g();Ii();Un();Lt();xe();});function kn(e,n=e){throw new ke(e,n)}var ke,xn=j(()=>{g();ke=class extends Error{constructor(t,i=t){super(i);this.code=t;}code;name="McpAppContractError"};});var po=j(()=>{g();});var lo=j(()=>{g();ve();Pe();xn();po();});function uo(e,n){return qa.add(e),n!==void 0&&Za.set(e,n),e}var qa,Za,vn=j(()=>{g();qa=new WeakSet,Za=new WeakMap;});function yn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function jt(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 Ao(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let n of Object.values(e))Ao(n);return Object.freeze(e)}function ee(e){throw new he("LINEAGE_INVALID",e)}function rc(e){throw new he("LINEAGE_STALE",e)}function Io(e){if(!yn(e)||!jt(e,nc,tc)||!yn(e.actions))return ee("Lineage definition shape is invalid");for(let n of Object.values(e.actions))if(!yn(n)||!jt(n,ic,oc))return ee("Lineage action definition shape is invalid");return e}function sc(e){if(!yn(e)||!jt(e,Qa,ec))return ee("Lineage entry shape is invalid");if(!Number.isSafeInteger(e.version)||e.version<1||typeof e.hash!="string"||!fo.test(e.hash))return ee("Lineage entry identity is invalid");if(e.sourceHash!==void 0&&(typeof e.sourceHash!="string"||!fo.test(e.sourceHash)))return ee("Lineage source hash is invalid");if(e.compat!==void 0&&e.compat!=="break")return ee("Lineage compatibility marker is invalid");let n=Io(e.definition);if(n.version!==e.version)return ee("Lineage version does not match its definition");if(e.sourceHash!==void 0&&n.sourceHash!==e.sourceHash)return ee("Lineage source hash does not match its definition");let t;try{t=le(n),Ne({...n,hash:e.hash});}catch{return ee("Lineage definition is invalid")}return t!==e.hash?ee("Lineage definition hash does not match"):Ao({version:e.version,hash:e.hash,definition:n,...e.sourceHash===void 0?{}:{sourceHash:e.sourceHash},...e.compat===void 0?{}:{compat:e.compat}})}function yo(e){return e.stateProjection?.allow??[]}function ac(e,n){let t=[],i=new Set(yo(n));yo(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 cc(e,n){return re(e)===re(n)}function Ft(e,n){if(!Array.isArray(e)||e.length===0)return ee("Definition lineage is missing");if(!yn(n)||typeof n.hash!="string")return ee("Current definition is invalid");let t,i;try{let{hash:a,...c}=n;i=Io(c),t={...i,hash:a},Ne(t);}catch{return ee("Current definition is invalid")}let o=e.map(sc),r=o[0].definition.id;if(o.some(a=>a.definition.id!==r))return ee("Lineage definition ids do not match");if(o.some((a,c)=>c>0&&a.version<=o[c-1].version))return ee("Lineage generations are not in increasing version order");if(o.some((a,c)=>o.findIndex(d=>d.hash===a.hash)!==c))return ee("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||!cc(s.definition,i))return rc("The last lineage generation does not match the current package");if(t.legacy!==void 0){let a=new Set(Object.keys(t.actions)),c=new Set;for(let p of o)if(p.sourceHash===void 0)for(let A of Object.keys(p.definition.actions))a.has(A)&&c.add(A);let d=Object.keys(t.legacy.agentAccess??{});if(d.length!==c.size||d.some(p=>!c.has(p))){let p="S4_LEGACY_AGENT_ACCESS_COMPLETE";throw new he("LINEAGE_INVALID",`Lineage compatibility failed: ${p}`,[p])}}for(let a=0;a<o.length-1;a+=1){if(o.slice(a,-1).some(p=>p.compat==="break"))continue;let d=ac(o[a].definition,t);if(d.length>0)throw new he("LINEAGE_INVALID",`Lineage compatibility failed: ${d.join(", ")}`,d)}return Object.freeze({entries:Object.freeze(o),current:t})}var he,fo,Qa,ec,nc,tc,ic,oc,Vt=j(()=>{g();ve();Pe();he=class extends Error{constructor(t,i=t,o=[]){super(i);this.code=t;this.violations=o;}code;violations;name="UiDefinitionLineageError"},fo=/^[0-9a-f]{64}$/,Qa=["version","hash","definition"],ec=["sourceHash","compat"],nc=["id","version","actions"],tc=["sourceHash","usage","detailPanel","displayModes","renderer","surfaces","stateProjection","dataPaths","summaryProjection","legacy"],ic=["capabilities"],oc=["inputKeys","dataInputs","confirmation","resultProjection","content","env"];});var go,mo,ho=j(()=>{g();go=["crewx_app_terminal_connect","crewx_app_html_viewer_open"],mo=["crewx_listWorkspaces","crewx_queryAgent","crewx_executeAgent","crewx_getTaskResult","crewx_listTasks","crewx_listAgents","callBrowser","openTab","listTabs","closeTab"];});var _o=j(()=>{g();ve();vn();});function Bt(e,n=0){try{let t=Te(e,n);return t.type!==void 0&&t.type!=="object"&&kn("TOOL_INVALID","MCP App inputSchema must describe an object"),t}catch(t){if(t instanceof ke)throw t;kn("TOOL_INVALID","MCP App inputSchema must be projection-safe JSON");}}function Eo(e){if(e.length===0)return Bt({type:"object",properties:{},additionalProperties:false});let n=e.map(i=>i.actionId),t=new Map;for(let i of e)t.set(i.actionId,Bt(i.inputSchema));return Bt(lc(n,t),pc)}function lc(e,n){let t=e.map(i=>({type:"object",properties:{actionId:{type:"string",const:i},input:n.get(i)??{type:"object"}},required:["actionId","input"],additionalProperties:false}));return Object.freeze({type:"object",oneOf:Object.freeze(t),properties:Object.freeze({actionId:Object.freeze({type:"string",enum:Object.freeze([...e])}),input:Object.freeze({type:"object"})}),required:Object.freeze(["actionId","input"]),additionalProperties:false})}var An,pc,Ht=j(()=>{g();lo();ve();Pe();vn();xn();Vt();ho();_o();An=8*1024*1024,new Set(go),new Set(mo),pc=4;});function uc(e){if(e===null||typeof e!="object"||!(To in e))throw new TypeError("scanCache must be created by createWorkspaceAppScanCache");return e[To]}function Po(e,n){let t=uc(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 To,No=j(()=>{g();To=Symbol("crewx.workspace-app-scan-cache.state");});function ce(e){let n=typeof e=="object"&&e!==null&&"code"in e?String(e.code):"";return n==="ENOENT"?new N("NOT_FOUND"):n==="ELOOP"?new N("PATH_ESCAPED"):n==="EFBIG"||n==="EOVERFLOW"?new N("LIMIT_EXCEEDED"):n==="EACCES"||n==="EPERM"||n==="ENOTDIR"?new N("READ_DENIED"):new N("READ_DENIED")}function Ic(e){if(typeof e!="string"||e.length===0||!isAbsolute(e))throw new N("READ_DENIED")}function zt(e){if(typeof e!="string"||isAbsolute(e)||/[\\\u0000]/.test(e))throw new N("PATH_ESCAPED");if(e==="")return [];let n=e.split("/");if(n.some(t=>t.length===0||t==="."||t===".."))throw new N("PATH_ESCAPED");return n}function Bn(e,n){let t=relative(e,n);return t===""||t!==".."&&!t.startsWith(`..${sep}`)&&!isAbsolute(t)}function tn(e){return {dev:e.dev,ino:e.ino,size:e.size,mtimeNs:e.mtimeNs,ctimeNs:e.ctimeNs}}function Jt(e,n){return e.dev===n.dev&&e.ino===n.ino}function Kt(e,n){return Jt(e,n)&&e.size===n.size&&e.mtimeNs===n.mtimeNs&&e.ctimeNs===n.ctimeNs}async function jn(e){Ic(e);let n,t;try{n=await realpath(e),t=await stat(n,{bigint:!0});}catch(i){throw ce(i)}if(!t.isDirectory())throw new N("READ_DENIED");return {realRoot:n,identity:tn(t)}}async function So(e,n,t){if(t.length<2||t[0]!=="apps"&&t[0]!=="skills")return;let i,o;try{if(i=resolve(e,t[0],t[1]),o=await realpath(i),!(await stat(o,{bigint:!0})).isDirectory())throw new N("READ_DENIED")}catch(r){throw r instanceof N?r:ce(r)}if(!Bn(n,o))throw new N("PATH_ESCAPED");return o}async function Fn(e,n,t,i){let o,r,s;try{o=await lstat(e,{bigint:!0}),r=await realpath(e),s=await stat(r,{bigint:!0});}catch(a){throw ce(a)}if(!Bn(n,r)||t!==void 0&&!Bn(t,r))throw new N("PATH_ESCAPED");if(!o.isFile()||!s.isFile())throw new N("READ_DENIED");if(!Jt(i,o)||!Jt(i,s)||i.dev!==s.dev)throw new N("PATH_ESCAPED")}async function nn(e,n){let t,i;try{t=await realpath(e),i=await stat(t,{bigint:!0});}catch{throw new N("PATH_ESCAPED")}if(t!==n.realRoot||!Kt(n.identity,tn(i)))throw new N("PATH_ESCAPED")}function gc(e){return e.isSymbolicLink()?{name:e.name,kind:"symlink"}:e.isDirectory()?{name:e.name,kind:"directory"}:e.isFile()?{name:e.name,kind:"file"}:{name:e.name,kind:"other"}}var N,Wt,Ac,bo,Hn,Mo,Yt=j(()=>{g();N=class extends Error{constructor(t){super(t);this.code=t;}code;name="AppDiscoveryFsError"},Wt=constants.O_NOFOLLOW,Ac=constants.O_NONBLOCK,bo=constants.O_RDONLY|(Wt??0)|(Ac??0);Hn=class{async getRootIdentity(n){let t=await jn(n);return await nn(n,t),{dev:t.identity.dev,ino:t.identity.ino,realPath:t.realRoot}}async listDirectory(n,t){let i=zt(t),o=await jn(n),r=resolve(n,...i),s,a;try{s=await realpath(r),a=await stat(s,{bigint:!0});}catch(c){let d=ce(c);if(d.code==="NOT_FOUND")return [];throw d}if(!Bn(o.realRoot,s)||!a.isDirectory())throw new N("PATH_ESCAPED");try{let c=await readdir(s,{withFileTypes:!0,encoding:"utf8"});return await nn(n,o),c.map(gc)}catch(c){let d=ce(c);if(d.code==="NOT_FOUND")return [];throw d}}async readdir(n,t){return this.listDirectory(n,t)}async readDirectory(n,t){return this.listDirectory(n,t)}async readVerifiedFile(n,t,i){if(!Number.isSafeInteger(i)||i<0)throw new N("READ_DENIED");if(Wt===void 0)throw new N("UNSUPPORTED");let o=zt(t),r=await jn(n),s=resolve(n,...o),a=relative(n,s);if(a===".."||a.startsWith(`..${sep}`)||isAbsolute(a))throw new N("PATH_ESCAPED");let c;try{c=await open(s,bo);}catch(d){throw ce(d)}try{let d;try{let h=await c.stat({bigint:!0});d=tn(h);}catch(h){throw ce(h)}if(d.size>BigInt(i))throw new N("LIMIT_EXCEEDED");if(d.size>BigInt(Number.MAX_SAFE_INTEGER))throw new N("LIMIT_EXCEEDED");await nn(n,r);let p=await So(n,r.realRoot,o);await Fn(s,r.realRoot,p,d);let A=new Uint8Array(new ArrayBuffer(Number(d.size))),m=0;for(;m<A.byteLength;){let h;try{h=(await c.read(A,m,A.byteLength-m,m)).bytesRead;}catch(O){throw ce(O)}if(h<=0)throw new N("IDENTITY_CHANGED");m+=h;}let y;try{let h=await c.stat({bigint:!0});y=tn(h);}catch(h){throw ce(h)}if(!Kt(d,y))throw new N("IDENTITY_CHANGED");return await Fn(s,r.realRoot,p,y),await nn(n,r),new Uint8Array(A)}finally{await c.close().catch(()=>{});}}async fingerprintVerifiedFile(n,t,i){if(!Number.isSafeInteger(i)||i<0)throw new N("READ_DENIED");if(Wt===void 0)throw new N("UNSUPPORTED");let o=zt(t),r=await jn(n),s=resolve(n,...o),a=relative(n,s);if(a===".."||a.startsWith(`..${sep}`)||isAbsolute(a))throw new N("PATH_ESCAPED");let c;try{c=await open(s,bo);}catch(d){throw ce(d)}try{let d;try{let m=await c.stat({bigint:!0});d=tn(m);}catch(m){throw ce(m)}if(d.size>BigInt(i)||d.size>BigInt(Number.MAX_SAFE_INTEGER))throw new N("LIMIT_EXCEEDED");await nn(n,r);let p=await So(n,r.realRoot,o);await Fn(s,r.realRoot,p,d);let A;try{let m=await c.stat({bigint:!0});A=tn(m);}catch(m){throw ce(m)}if(!Kt(d,A))throw new N("IDENTITY_CHANGED");return await Fn(s,r.realRoot,p,A),await nn(n,r),{...A,candidateRealPath:p??r.realRoot}}catch(d){throw d instanceof N?d:ce(d)}finally{await c.close().catch(()=>{});}}async readFileVerified(n,t,i){return this.readVerifiedFile(n,t,i)}},Mo=new Hn;});function hn(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 Oo(e){return typeof e=="string"&&Ae.test(e)?e:void 0}function Nc(e){return e.length>0&&e!=="."&&e!==".."&&!/[\\/\u0000]/.test(e)}function He(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 Dc(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 bc(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 Sc(e){return Tc.decode(e)}function Mc(e){return JSON.parse(Sc(e))}function Ro(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 Lc(e){if(e instanceof N)return Ro(e.code);if(e!==null&&typeof e=="object"&&"code"in e){let n=e.code;if(typeof n=="string")return Ro(n)}}function be(e,n){let t=n();return Number.isFinite(t)&&Number.isFinite(e)&&t-e<=5e3}function Oc(e){if(typeof e.readVerifiedFile=="function")return e.readVerifiedFile;if(typeof e.readFileVerified=="function")return e.readFileVerified}function Rc(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 wo(e,n,t,i){let o=Oc(e);if(!o)throw new N("READ_DENIED");return bc(await o.call(e,n,t,i))}async function Qt(e,n,t){let i=Rc(e);if(!i)throw new N("READ_DENIED");let o=await i.call(e,n,t);if(!Array.isArray(o))throw new N("READ_DENIED");return o.map(Dc).filter(r=>r!==null)}function wc(e,n,t,i){return Object.freeze({code:e,...{},source:n,relativePath:t})}function Uc(e){if(!hn(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(He))};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 Cc(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 $n(e){return Object.freeze({appIds:Object.freeze([...new Set(e.map(n=>n.appId))].sort(He)),definitionIds:Object.freeze([...new Set(e.map(n=>n.definition.id))].sort(He))})}function zn(e,n){let t=Object.keys(e).sort(He),i=[...n].sort(He);return t.length===i.length&&t.every((o,r)=>o===i[r])}function Uo(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 kc(e){let n;try{n=Mc(e);}catch{return}if(!hn(n)||!zn(n,["version","packages"])||n.version!==1||!Array.isArray(n.packages)||n.packages.length>ei)return;let t=new Set,i=new Set,o=0,r=[];for(let s of n.packages){if(!hn(s))return;let a=["packageDir","appId","definition","files"],c=Object.hasOwn(s,"lineage"),d=Object.hasOwn(s,"launcher"),p=[...c?["lineage"]:[],...d?["launcher"]:[]];if(!zn(s,[...a,...p])||d&&s.launcher!==false)return;let A=Uo(s.packageDir),m=Oo(s.appId);if(!A||A.length!==2||A[0]!=="apps"||!Nc(A[1])||!m||t.has(s.packageDir)||!hn(s.definition)||!zn(s.definition,["id","version","hash"]))return;let y=Oo(s.definition.id),h=s.definition.version,O=s.definition.hash;if(!y||!Number.isSafeInteger(h)||h<1||typeof O!="string"||!Zt.test(O)||!Array.isArray(s.files)||s.files.length<2||s.files.length>ni)return;let S=new Set,F=[];for(let k of s.files){if(!hn(k)||!zn(k,["path","sha256"]))return;let v=Uo(k.path);if(!v||typeof k.sha256!="string"||!Zt.test(k.sha256))return;let V=v.join("/"),E=`${s.packageDir}/${V}`;if(S.has(V)||i.has(E))return;S.add(V),i.add(E),F.push(Object.freeze({path:V,sha256:k.sha256}));}if(!Y.some(k=>S.has(k))||!S.has("ui/index.html")||(o+=F.length,o>hc))return;t.add(s.packageDir),r.push(Object.freeze({packageDir:s.packageDir,...d?{launcher:false}:{},appId:m,definition:Object.freeze({id:y,version:h,hash:O}),lineage:Array.isArray(s.lineage)?s.lineage:[],files:Object.freeze(F.sort((k,v)=>He(k.path,v.path)))}));}return Object.freeze({version:1,packages:Object.freeze(r)})}function Be(e){let n=Lc(e);return n==="PATH_ESCAPED"||n==="IDENTITY_CHANGED"||n==="TOCTOU"?"PATH_ESCAPED":n==="LIMIT_EXCEEDED"?"LIMIT_EXCEEDED":"BUNDLE_INTEGRITY"}async function xc(e,n,t,i,o){let r=[],s=async(a,c)=>{if(!be(i,o))throw new N("LIMIT_EXCEEDED");if(c>2)throw new N("LIMIT_EXCEEDED");let d=await Qt(e,n,a);for(let p of d){if(typeof p.name!="string"||p.name.length===0||p.name==="."||p.name===".."||/[\\/\u0000]/.test(p.name))throw new N("PATH_ESCAPED");let A=`${a}/${p.name}`;if(p.kind==="file"){if(r.push(A.slice(t.length+1)),r.length>ni)throw new N("LIMIT_EXCEEDED")}else if(p.kind==="directory")await s(A,c+1);else throw p.kind==="symlink"?new N("PATH_ESCAPED"):new N("READ_DENIED")}};return await s(t,0),r.sort(He)}function vc(e){return Y.includes(e)?262144:e==="ui/index.html"?An:e==="ui/state.json"?65536:e.startsWith("ui/assets/")?Ec:_c}async function Co(e,n,t,i){if(e===void 0)return {packages:[],diagnostics:[],incomplete:false,reservedIds:Pc};let o=Uc(e.reservedIds),r=[],s=(l,u,I)=>wc(l,"bundled",u),a=(l=[],u=false,I)=>({...I===void 0?{}:{indexHash:I},packages:l,diagnostics:r,incomplete:u,reservedIds:o});if(typeof e.root!="string"||e.root.length===0||typeof e.expectedIndexHash!="string"||!Zt.test(e.expectedIndexHash))return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a();let c;try{c=await wo(n,e.root,"bundle-index.json",mc);}catch(l){return r.push(s(Be(l),"bundle-index.json")),a()}let d=createHash("sha256").update(c).digest("hex");if(d!==e.expectedIndexHash)return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a();let p=kc(c);if(p===void 0)return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a();if(!Cc($n(p.packages),o))return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a([],false,d);if(!be(t,i))return r.push(s("LIMIT_EXCEEDED","bundle-index.json")),a(p.packages.map(l=>({indexEntry:l,failureCode:"LIMIT_EXCEEDED"})),true,d);let A;try{A=await Qt(n,e.root,"");}catch(l){return r.push(s(Be(l),"bundle-index.json")),a(p.packages.map(u=>({indexEntry:u,failureCode:Be(l)})),false,d)}if(!be(t,i))return r.push(s("LIMIT_EXCEEDED","bundle-index.json")),a(p.packages.map(l=>({indexEntry:l,failureCode:"LIMIT_EXCEEDED"})),true,d);let m=A.find(l=>l.name==="bundle-index.json"&&l.kind==="file"),y=A.find(l=>l.name==="apps"&&l.kind==="directory"),h=l=>p.packages.map(u=>({indexEntry:u,failureCode:l}));if(!m)return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a(h("BUNDLE_INTEGRITY"),false,d);let O=A.filter(l=>l.name!=="bundle-index.json"&&l.name!=="apps");if(O.length>0){let l=O.some(u=>u.kind==="symlink")?"PATH_ESCAPED":"BUNDLE_INTEGRITY";return r.push(s(l,"bundle-index.json")),a(h("BUNDLE_INTEGRITY"),false,d)}if(A.some(l=>l.name==="apps"&&l.kind!=="directory"))return r.push(s("PATH_ESCAPED","apps")),a(h("PATH_ESCAPED"),false,d);let S=[];if(y)try{S=await Qt(n,e.root,"apps");}catch(l){return r.push(s(Be(l),"apps")),a(h(Be(l)),false,d)}if(!be(t,i)||S.length>ei)return r.push(s("LIMIT_EXCEEDED","apps")),a(h("LIMIT_EXCEEDED"),true,d);let F=new Map(p.packages.map(l=>[l.packageDir.slice(5),l])),k=S.filter(l=>!F.has(l.name));for(let l of k)r.push(s(l.kind==="symlink"?"PATH_ESCAPED":"BUNDLE_INTEGRITY",`apps/${l.name}`));if(k.length>0){let l=k.some(u=>u.kind==="symlink")?"PATH_ESCAPED":"BUNDLE_INTEGRITY";return a(h(l),false,d)}let v=new Set,V=new Map,E=new Map;for(let l of p.packages){let u=V.get(l.appId)??[];u.push(l),V.set(l.appId,u);let I=`${l.definition.id}\0${String(l.definition.version)}`,P=E.get(I)??[];P.push(l),E.set(I,P);}for(let l of [...V.values(),...E.values()])if(l.length>1)for(let u of l)v.add(u);let T=[],C=c.byteLength,D=false;for(let l of p.packages){if(!be(t,i)){D=true,T.push({indexEntry:l,failureCode:"LIMIT_EXCEEDED"});continue}let u;try{let b=l.lineage[l.lineage.length-1];if(!b)throw new he("LINEAGE_INVALID","Definition lineage is missing");if(b.definition.id!==l.definition.id||b.version!==l.definition.version||b.hash!==l.definition.hash)throw new he("LINEAGE_STALE","Last lineage generation does not match bundle identity");u=Ft(l.lineage,{...b.definition,hash:b.hash}).entries;}catch(b){let ae=b instanceof he?b.code:"LINEAGE_INVALID";r.push(s(ae,l.packageDir)),T.push({indexEntry:l,failureCode:ae});continue}let I=S.find(b=>b.name===l.packageDir.slice(5));if(!y||!I){T.push({indexEntry:l,failureCode:"BUNDLE_INTEGRITY"});continue}if(I.kind!=="directory"){T.push({indexEntry:l,failureCode:I.kind==="symlink"?"PATH_ESCAPED":"BUNDLE_INTEGRITY"});continue}let P;try{let b=await xc(n,e.root,l.packageDir,t,i);if(!be(t,i)){D=!0,T.push({indexEntry:l,failureCode:"LIMIT_EXCEEDED"});continue}let ae=l.files.map(_e=>_e.path);if(b.length!==ae.length||b.some((_e,Ee)=>_e!==ae[Ee])){T.push({indexEntry:l,failureCode:"BUNDLE_INTEGRITY"});continue}P=new Map;let z;for(let _e of l.files){if(!be(t,i)){z="LIMIT_EXCEEDED",D=!0;break}if(C>=qt){z="LIMIT_EXCEEDED";break}let Ee;try{Ee=await wo(n,e.root,`${l.packageDir}/${_e.path}`,vc(_e.path));}catch(jr){z=Be(jr);break}if(!be(t,i)){z="LIMIT_EXCEEDED",D=!0;break}if(C+Ee.byteLength>qt){C=qt,z="LIMIT_EXCEEDED";break}if(C+=Ee.byteLength,createHash("sha256").update(Ee).digest("hex")!==_e.sha256){z="BUNDLE_INTEGRITY";break}P.set(_e.path,Ee);}if(z!==void 0){T.push({indexEntry:l,failureCode:z});continue}}catch(b){be(t,i)||(D=true),T.push({indexEntry:l,failureCode:Be(b)});continue}T.push({indexEntry:l,lineage:u,files:P,...v.has(l)?{failureCode:"DUPLICATE_ID"}:{}});}return a(T,D,d)}var mc,ei,ni,hc,_c,Ec,qt,Zt,Tc,Pc,ti=j(()=>{g();Vt();xe();Un();Ht();Yt();mc=256*1024,ei=64,ni=128,hc=ei*ni,_c=2*1024*1024,Ec=8*1024*1024,qt=32*1024*1024,Zt=/^[0-9a-f]{64}$/,Tc=new TextDecoder("utf-8",{fatal:true}),Pc=Object.freeze({appIds:Object.freeze([]),definitionIds:Object.freeze([])});});function Fc(e){if(typeof e!="string"||!Ae.test(e))throw new TypeError("pluginId must be a safe UI plugin identifier");let n=`${ii}${e}`.length+7<=128?e:`hash_${createHash("sha256").update(e,"utf8").digest("hex")}`;return {read:`${ii}${n}_read`,action:`${ii}${n}_action`}}function xo(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 Bc(e,n){return n.length===0||n==="."||n===".."||/[\\/\u0000]/.test(n)?e==="skills"?"skills":"apps":`${e==="skills"?"skills":"apps"}/${n}`}function Hc(e){return e.length>0&&e!=="."&&e!==".."&&!/[\\/\u0000]/.test(e)}function _n(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 Jo(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 zc(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 Ko(e){return Vc.decode(e)}function $c(e){return JSON.parse(Ko(e))}function Gc(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 Wn(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 vo(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 ie(e){if(e instanceof N)return vo(e.code);if(e!==null&&typeof e=="object"&&"code"in e){let n=e.code;if(typeof n=="string")return vo(n)}}function $e(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 jo(e){return {reason:e.reason,...e.code==="MANIFEST_DUAL_MISMATCH"?{files:e.files}:{}}}function Fo(e){return e==="MANIFEST_DUAL_MISMATCH"?e:Xo(e)}function Wc(e){return Xo(e.code)}function Xo(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 Yo("UiPluginValidationError",e)}}function Yo(e,n){throw new Error(`Unmapped ${e} code: ${String(n)}`)}function Jc(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 Yo("McpAppContractError",e)}}function Se(e,n){let t=n();return Number.isFinite(t)&&Number.isFinite(e)&&t-e<=5e3}function Kc(e){return {pluginId:e.appId,definitionKey:`${e.definition.id}\0${String(e.definition.version)}`}}function Xc(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(xo(o)){let r=o.bin,s=typeof r=="string"?r:xo(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=Yc(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 Yc(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 qc(){return globalThis.performance?.now()??Date.now()}function ze(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let n of Object.values(e))ze(n);return Object.freeze(e)}function Vo(e){return Object.freeze(Array.from(e))}async function Jn(e,n,t,i){if(n.pinnedFiles!==void 0){let a=n.pinnedFiles.get(t);if(a===void 0)throw new N("NOT_FOUND");if(a.byteLength>i)throw new N("LIMIT_EXCEEDED");return new Uint8Array(a)}let o=`${n.relativePath}/${t}`,r=n.scanContext,s=e.fingerprintVerifiedFile;if(r===void 0||!r.cacheable||typeof s!="function")return $o(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 $o(e,n.root,o,i),d=await s.call(e,r.workspaceRoot,o,i);return r.candidateRealPath=d.candidateRealPath,Zo(a,d)&&d.size===BigInt(c.byteLength)&&!Qo(d,r.scanStartedAtNs)?r.files.set(o,{relativePath:o,byteLimit:i,fingerprint:d}):r.cacheable=!1,c}catch(a){let c=Y.includes(t)&&ie(a)==="NOT_FOUND"&&r.directoryListings.some(p=>p.relativePath===n.relativePath&&!Kn(p.key,t)),d=t===B&&ie(a)==="NOT_FOUND"&&Zc(r.directoryListings,n.relativePath);throw !c&&!d&&(r.cacheable=false),a}}function Zc(e,n){let t=e.find(o=>o.relativePath===n);if(t===void 0)return false;if(!Kn(t.key,"dist"))return true;let i=e.find(o=>o.relativePath===`${n}/dist`);return i!==void 0&&!Kn(i.key,"tools.json")}function qo(e,n){return JSON.stringify([e.realPath,n.source,n.relativePath])}async function ed(e,n,t,i,o,r,s,a){let c=e.fingerprintVerifiedFile,d=qo(t,i),p=o.candidates.get(d),A=i.relativePath,m;try{m=await zo(e,n,A);}catch(D){if(ie(D)!=="NOT_FOUND")throw D}let y=m===void 0?void 0:{relativePath:A,key:m};if(y!==void 0&&(i.source==="apps"||i.source==="skills")&&!Y.some(D=>Kn(y.key,D)))return Se(s,a)?p!==void 0&&p.candidate===void 0&&p.candidateRealPath===void 0&&p.files.length===0&&p.directoryListings.length===1&&p.directoryListings[0]?.relativePath===y.relativePath&&p.directoryListings[0]?.key===y.key&&(i.source==="apps"?p.diagnostic?.code==="MANIFEST_MISSING":p.diagnostic===void 0)&&typeof c=="function"?{memo:p}:typeof c!="function"?{}:{context:{state:o,cacheKey:d,workspaceRoot:n,scanStartedAtNs:r,directoryListings:Object.freeze([y]),priorFingerprints:new Map,files:new Map,cacheable:true}}:{timeLimitReached:true};let h=async D=>{if(D==="")return y;let l=`${i.relativePath}${D}`;try{let u=await zo(e,n,l);return u===void 0?void 0:{relativePath:l,key:u}}catch(u){if(ie(u)==="NOT_FOUND")return;throw u}},O=await Promise.all(Bo.map(h)),S=await Promise.all(Qc.map(h));if(!Se(s,a))return {timeLimitReached:true};let F=typeof c=="function"&&O.every(D=>D!==void 0),k=O.filter(D=>D!==void 0),v=[...k,...S.filter(D=>D!==void 0)],V=new Map,E=p!==void 0&&F,T;if(p!==void 0&&typeof c=="function"){let D=await Promise.all(p.files.map(async l=>{if(!Se(s,a))return {kind:"time",file:l};try{let u=await c.call(e,n,l.relativePath,l.byteLimit);return {kind:"fingerprint",file:l,current:u}}catch(u){return ie(u)==="NOT_FOUND"?{kind:"missing",file:l}:{kind:"error",file:l,error:u}}}));if(D.some(l=>l.kind==="time"))return {timeLimitReached:true};for(let l of D){if(l.kind==="error")throw l.error;if(l.kind==="missing"){E=false;continue}if(l.kind!=="fingerprint")continue;let{file:u,current:I}=l;V.set(u.relativePath,I),T??=I.candidateRealPath,(I.candidateRealPath!==p.candidateRealPath||!Zo(I,u.fingerprint)||Qo(I,r))&&(E=false);}}let C=p!==void 0&&p.directoryListings.length===v.length&&p.directoryListings.every((D,l)=>D.relativePath===v[l]?.relativePath&&D.key===v[l]?.key);return p!==void 0&&F&&C&&E&&T===p.candidateRealPath?{memo:p}:!F||k.length!==Bo.length?{}:{context:{state:o,cacheKey:d,workspaceRoot:n,scanStartedAtNs:r,directoryListings:Object.freeze(v),priorFingerprints:V,files:new Map,...T===void 0?{}:{candidateRealPath:T},cacheable:true}}}function Kn(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 zo(e,n,t){let i=er(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(Jo);if(!r.some(s=>s===null))return JSON.stringify(r.slice().sort((s,a)=>_n(s.name,a.name)||_n(s.kind,a.kind)).map(s=>[s.name,s.kind]))}function Zo(e,n){return e.dev===n.dev&&e.ino===n.ino&&e.size===n.size&&e.mtimeNs===n.mtimeNs&&e.ctimeNs===n.ctimeNs}function Qo(e,n){let t=e.mtimeNs-n;return t>=-Ho&&t<=Ho}function oi(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 nd(e,n,t){let i=createHash("sha256"),o=new TextEncoder().encode(re(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 td(e,n){let t={...e.definition,sourceHash:n},i;try{i=le(t);}catch(r){throw r instanceof R&&r.code==="INPUT_INVALID"?new te("MANIFEST_INVALID","normalized definition is invalid"):r}let o={...t,hash:i};try{Ne(o);}catch{throw new te("MANIFEST_INVALID","normalized definition is invalid")}return o}function id(e){return e.actions.some(n=>n.backend.type==="core"&&n.backend.handler!=="state.set")}function od(e){if(typeof e.readVerifiedFile=="function")return e.readVerifiedFile;if(typeof e.readFileVerified=="function")return e.readFileVerified}function er(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 $o(e,n,t,i){let o=od(e);if(!o)throw new N("READ_DENIED");return zc(await o.call(e,n,t,i))}async function rd(e,n,t){let i=er(e);if(!i)throw new N("READ_DENIED");let o=await i.call(e,n,t);if(!Array.isArray(o))throw new N("READ_DENIED");return o.map(Jo).filter(r=>r!==null)}function sd(e){let n=[];for(let t of [e.reserved,e.builtin])t&&n.push(t);return e.builtins&&"listMcpApps"in e.builtins?n.push(Go(e.builtins)):e.builtins&&n.push(e.builtins),e.builtinCatalog&&n.push(Go(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 Go(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 Me(e,n){e.diagnostic||(e.diagnostic=Wn(n,e.source,e.relativePath,e.identity?.pluginId));}function ad(e){let n=new Map;for(let i of e){let o=i.identity?.pluginId;if(o===void 0)continue;let r=n.get(o)??[];r.push(i),n.set(o,r);}for(let i of n.values()){if(i.length<2)continue;let o=i.filter(s=>s.provenance!==void 0);if(o.length>0){for(let s of i)s.provenance===void 0&&Me(s,"RESERVED_ID");if(o.length>1)for(let s of o)Me(s,"DUPLICATE_ID");continue}let r=i.filter(s=>s.source==="apps");if(r.length>1){for(let s of r)Me(s,"DUPLICATE_ID");for(let s of i.filter(a=>a.source==="skills"))Me(s,"DUPLICATE_ID");}else for(let s of i.filter(a=>a.source==="skills"))Me(s,"DUPLICATE_ID");}let t=new Map;for(let i of e){if(i.diagnostic?.code==="RESERVED_ID")continue;let o=i.identity?.definitionKey;if(o===void 0)continue;let r=t.get(o)??[];r.push(i),t.set(o,r);}for(let i of t.values())if(i.length>1)for(let o of i)Me(o,"DUPLICATE_ID");}function cd(e,n,t){let i=new Set,o=new Set,r=new Set,s=new Set(t.appIds),a=new Set(t.definitionIds);for(let c of sd(n)){for(let d of c.appIds??[])typeof d=="string"&&i.add(d);for(let d of c.definitionIds??[])typeof d=="string"&&o.add(d);for(let d of c.toolNames??[])typeof d=="string"&&r.add(d);}for(let c of e){let d=c.candidate;if(!d)continue;if(i.has(d.pluginId)||o.has(d.definitionId)){Me(c,"RESERVED_ID");continue}if(c.provenance===void 0&&(s.has(d.pluginId)||a.has(d.definitionId))){Me(c,"RESERVED_ID");continue}[d.toolNames.read,d.toolNames.action].filter(A=>A!==void 0).some(A=>r.has(A))&&Me(c,"DUPLICATE_ID");}}function dd(e){return [...e].sort((n,t)=>{let i=ko.indexOf(n.source)-ko.indexOf(t.source);return i!==0?i:_n(n.relativePath,t.relativePath)})}function x(e,n,t){e.diagnostic=Wn(n,e.source,e.relativePath,e.identity?.pluginId,t);}async function Wo(e,n,t){let i=Ve(t,{mode:"local"});if(!i.ok&&i.parseFailure){x(n,Fo(i.rejection.code),jo(i.rejection));return}let o=Gc(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)}`){x(n,"BUNDLE_INTEGRITY");return}if(!i.ok&&i.builtinOnly){x(n,"RESERVED_ID");return}if(!i.ok){x(n,Fo(i.rejection.code),jo(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{Eo(r.actions.map(b=>({actionId:b.actionId,inputSchema:b.inputSchema})));}catch(b){if(b instanceof ke){x(n,Jc(b.code));return}throw b}let a;try{a=await Jn(e,n,"ui/index.html",An);}catch(b){x(n,$e(ie(b),"entry"));return}if(a.byteLength>An){x(n,"LIMIT_EXCEEDED");return}let c;try{c=Ko(a);}catch{x(n,"ENTRY_INVALID");return}if(a.byteLength===0||c.length===0){x(n,"ENTRY_INVALID");return}let d=createHash("sha256").update(a).digest("hex");if(r.entryHash!==void 0&&r.entryHash!==d){x(n,"ENTRY_INVALID");return}let p={},A,m;if(r.initialState!==void 0){try{A=await Jn(e,n,"ui/state.json",65536);}catch(b){x(n,$e(ie(b),"initial"));return}if(A.byteLength>65536){x(n,"LIMIT_EXCEEDED");return}try{let b=$c(A),ae=r.dataPaths??[],z=Mt(b,ae);p=Te(z,0,ae),Je(p);}catch{x(n,"INITIAL_STATE_INVALID");return}if(m=createHash("sha256").update(A).digest("hex"),r.initialState.hash!==void 0&&r.initialState.hash!==m){x(n,"INITIAL_STATE_INVALID");return}}let y={...r,entryHash:d,...r.initialState===void 0?{}:{initialState:{path:"ui/state.json",hash:m}}},h=dn(y),O=nd(y,a,A??new Uint8Array),S;try{S=td(h,O);}catch(b){if(b instanceof te){x(n,Wc(b));return}throw b}let F;if(n.bundleLineage!==void 0){let b=n.bundleLineage[n.bundleLineage.length-1];if(!b){x(n,"LINEAGE_INVALID");return}let{legacy:ae,...z}=b.definition,{hash:_e,...Ee}=S;if(re(z)!==re(Ee)){x(n,"LINEAGE_STALE");return}if(ae!==void 0&&(S={...S,legacy:ae}),ae!==void 0)try{S={...S,hash:le(S)},Ne(S);}catch{x(n,"LINEAGE_INVALID");return}F=n.bundleLineage;}if(n.bundleIdentity!==void 0&&n.bundleIdentity.appId!==r.pluginId){x(n,"BUNDLE_INTEGRITY");return}if(n.bundleIdentity!==void 0&&(n.bundleIdentity.definitionId!==S.id||n.bundleIdentity.version!==S.version||n.bundleIdentity.definitionHash!==S.hash)){x(n,"LINEAGE_STALE");return}let k=Fc(r.pluginId),v=r.actions.length===0?{read:k.read}:k,V=ze(h),E=ze(y),T=ze(S),C=ze({...h.handlers}),D=Vo(a),l=A===void 0?void 0:Vo(A),u=Object.freeze({...n.provenance===void 0?{}:{provenance:n.provenance},entry:Object.freeze({path:"ui/index.html",hash:d,bytes:D}),...l===void 0?{}:{initialState:Object.freeze({path:"ui/state.json",hash:m,bytes:l})}}),I={appId:r.pluginId,pluginId:r.pluginId,definitionId:r.definitionId,version:r.version,...i.releaseVersion===void 0?{}:{releaseVersion:i.releaseVersion},manifestFile:i.file,...i.mcpb===void 0?{}:{mcpb:ze(i.mcpb)},relativePath:n.relativePath,manifest:E,normalized:V,name:r.name,description:r.description,...r.icon===void 0?{}:{icon:r.icon},...r.tone===void 0?{}:{tone:r.tone},definition:T,handlers:C,resources:u,html:c,entryBytes:D,entryHash:d,initialState:ze(p),...l===void 0?{}:{initialStateBytes:l},...m===void 0?{}:{initialStateHash:m},sourceHash:O,toolNames:Object.freeze(v)},P=n.provenance===void 0?{...I,source:n.source}:{...I,provenance:n.provenance,lineage:F??[]};n.candidate=Object.freeze(P),id(r)&&x(n,"EXEC_DENIED");}async function nr(e,n){let t={};for(let i of Y)try{t[i]=await Jn(e,n,i,262144);}catch(o){if(ie(o)==="NOT_FOUND")continue;return {files:t,failure:$e(ie(o),"manifest")}}if(t[W]!==void 0)try{t[B]=await Jn(e,n,B,262144);}catch(i){if(ie(i)!=="NOT_FOUND")return {files:t,failure:$e(ie(i),"manifest")}}return {files:t}}function ri(e){return Y.some(n=>e[n]!==void 0)}async function pd(e,n){let{files:t,failure:i}=await nr(e,n);if(i!==void 0){x(n,i);return}let o=t[W];return o!==void 0&&!kt(o)&&(delete t[W],delete t[B]),ri(t)?t:void 0}function ld(e,n,t,i=jc,o=false){let r=dd(e);ad(r);let s=Object.freeze(r.filter(p=>p.candidate!==void 0&&p.diagnostic===void 0).map(p=>p.candidate)),a=Object.freeze(r.filter(p=>p.diagnostic!==void 0).map(p=>p.diagnostic)),c=o?Object.freeze({...t===void 0?{}:{indexHash:t},candidates:Object.freeze(r.filter(p=>p.source==="bundled"&&p.diagnostic===void 0&&t!==void 0&&p.candidate?.provenance?.indexHash===t).map(p=>p.candidate)),diagnostics:Object.freeze(a.filter(p=>p.source==="bundled").map(p=>Object.freeze({...p}))),reservedAppIds:Object.freeze([...i.appIds]),reservedDefinitionIds:Object.freeze([...i.definitionIds])}):void 0,d={apps:s,diagnostics:a,complete:n===void 0,...n===void 0?{}:{incompleteReason:n},...t===void 0?{}:{productBundleIndexHash:t},...c===void 0?{}:{productBundleSnapshotMetadata:c}};return Object.defineProperty(d,"candidates",{configurable:false,enumerable:false,get:()=>s}),Object.freeze(d)}function ud(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 fd(e,n){if(ud(e))return {fs:e,options:{}};let t=e??n??{};return {fs:t.filesystem??t.fileSystem??t.fs??Mo,options:t}}async function tr(e,n,t){if(typeof e!="string"||e.length===0)throw new TypeError("workspaceRoot must be explicit");let{fs:i,options:o}=fd(n,t),r=o.clock??qc,s=r(),a=await Co(o.productBundle,i,s,r),c=r(),d=BigInt(Date.now())*1000000n,p=[],A=0,m,y=false,h,O;if(o.scanCache!==void 0&&typeof i.getRootIdentity=="function"&&typeof i.fingerprintVerifiedFile=="function")try{O=await i.getRootIdentity(e),h=Po(o.scanCache,O),h.scanStartedAtNs=d;}catch(E){if(ie(E)!=="NOT_FOUND")throw E}let S=h!==void 0&&o.productBundle===void 0&&a.packages.length===0&&a.diagnostics.length===0,F=new Set,k=true;p.push(...a.diagnostics.map(E=>({source:E.source,root:o.productBundle?.root??e,name:"",relativePath:E.relativePath,diagnostic:E})));let v=a.reservedIds;a.incomplete&&(m="time_limit");for(let E of a.packages){if(!Se(c,r)){y=true,m="time_limit";break}let T=E.indexEntry,C=T.packageDir,D=E.files===void 0?void 0:Xc(C,E.files),l=a.indexHash===void 0?void 0:uo(Object.freeze({kind:"bundled",launcher:T.launcher!==false,indexHash:a.indexHash,packageDir:C,appId:T.appId,definitionId:T.definition.id,version:T.definition.version,definitionHash:T.definition.hash,files:T.files}),D),u={source:"bundled",root:o.productBundle?.root??e,name:C.slice(5),relativePath:C,...l===void 0?{}:{provenance:l},...E.files===void 0?{}:{pinnedFiles:E.files},...E.lineage===void 0?{}:{bundleLineage:E.lineage},bundleIdentity:{appId:T.appId,definitionId:T.definition.id,version:T.definition.version,definitionHash:T.definition.hash},identity:Kc(T)};if(p.push(u),A+=1,E.failureCode!==void 0){x(u,E.failureCode);continue}if(E.files?.has(B)===true){x(u,"EXEC_DENIED",{reason:{path:"",rule:"bundled-tool-mode-unsupported",file:B}});continue}let I={};for(let P of Y){let b=E.files?.get(P);b!==void 0&&(I[P]=b);}if(!ri(I)){x(u,"BUNDLE_INTEGRITY");continue}if(await Wo(i,u,I),!Se(c,r)){y=true,m="time_limit";break}}let V=[{source:"apps",directory:"apps"},{source:"skills",directory:"skills"}];e:for(let E of V){let{source:T,directory:C}=E,D;try{D=await rd(i,e,C);}catch(u){if(ie(u)==="NOT_FOUND")continue;S=false,k=false,p.push({source:T,root:e,name:"",relativePath:T,diagnostic:Wn($e(ie(u),"manifest"),T,T)});continue}let l=D.filter(u=>u.kind==="directory"||u.kind==="symlink").filter(u=>Hc(u.name)).map(u=>({source:T,root:e,name:u.name,relativePath:Bc(T,u.name)})).sort((u,I)=>_n(u.relativePath,I.relativePath));for(let u of l){let I={...u};if(p.push(I),O!==void 0?F.add(qo(O,I)):S=false,!Se(c,r)){y=true,m="time_limit";break e}let P;if(h!==void 0&&O!==void 0){try{let z=await ed(i,e,O,I,h,d,c,r);if(z.timeLimitReached){y=!0,m="time_limit";break e}I.scanContext=z.context,P=z.memo;}catch(z){S=false,x(I,$e(ie(z),"manifest"));continue}P===void 0&&(S=false);}if(P!==void 0){if(I.candidate=P.candidate,I.diagnostic=P.diagnostic,I.identity=P.identity,T==="skills"&&P.candidate===void 0&&P.diagnostic===void 0)continue;if(A>=64){x(I,"LIMIT_EXCEEDED");continue}if(u.relativePath.split("/").length-1>2){x(I,"LIMIT_EXCEEDED");continue}if(A+=1,!Se(c,r)){y=true,m="time_limit";break e}continue}let b;if(T==="skills"&&(b=await pd(i,I),b===void 0)){I.diagnostic===void 0&&oi(I);continue}if(A>=64){x(I,"LIMIT_EXCEEDED");continue}if(u.relativePath.split("/").length-1>2){x(I,"LIMIT_EXCEEDED");continue}if(!Se(c,r)){y=true,m="time_limit";break e}if(A+=1,b===void 0){let z=await nr(i,I);if(z.failure!==void 0||!ri(z.files)){x(I,z.failure??$e("NOT_FOUND","manifest")),oi(I);continue}b=z.files;}if(await Wo(i,I,b),oi(I),!Se(c,r)){y=true,m="time_limit";break e}}}if(h!==void 0&&O!==void 0){let E=[...F].sort(_n),T=h.lastCandidateKeys,C=T!==void 0&&T.length===E.length&&T.every((l,u)=>l===E[u]);if(S=S&&C,k&&!y&&m===void 0)for(let l of h.candidates.keys())try{JSON.parse(l)[0]===O.realPath&&!F.has(l)&&h.candidates.delete(l);}catch{h.candidates.delete(l);}let D=[...h.candidates.keys()].filter(l=>{try{return JSON.parse(l)[0]===O.realPath}catch{return false}});S=S&&D.length===F.size&&D.every(l=>F.has(l))&&!y&&m===void 0,h.lastCandidateScanUnchanged=S,k&&!y&&m===void 0&&(h.lastCandidateKeys=Object.freeze(E));}return y&&p.push({source:"apps",root:e,name:"",relativePath:"apps",diagnostic:Wn("DISCOVERY_TIME_LIMIT","apps","apps")}),cd(p,o,v),ld(p,m,a.indexHash,v,o.productBundle!==void 0)}var jc,ii,ko,Vc,Bo,Qc,Ho,ir=j(()=>{g();ve();Pn();Pe();xt();xe();Ht();xn();No();Yt();vn();ti();ti();jc=$n([]),ii="crewx_local_app_";ko=["bundled","apps","skills"],Vc=new TextDecoder("utf-8",{fatal:true});Bo=["","/ui"],Qc=["/dist"],Ho=2000000000n;});g();xt();g();mt();g();var Qi="SKILL.md",$a=/^---\s*\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;function eo(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function Ga(e){return e.isDirectory()||e.isSymbolicLink()}function ro(e){try{return existsSync(e)&&statSync(e).isDirectory()}catch{return false}}function vt(e){let n;try{n=readFileSync(e,"utf8");}catch{return {frontmatter:{},readable:false,valid:false,hasFrontmatter:false}}let t=n.match($a);if(!t)return {frontmatter:{},readable:true,valid:true,hasFrontmatter:false};try{let i=load(t[1]??"");if(!eo(i))return {frontmatter:{},readable:!0,valid:!1,hasFrontmatter:!0};let o=eo(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 Wa(e){return [join(e,Qi),join(e,"skill",Qi)]}function no(e,n){if(!ro(e))return null;for(let t of Wa(e)){if(!existsSync(t))continue;let o=vt(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 to(e){try{return readdirSync(e,{withFileTypes:!0}).filter(Ga)}catch{return []}}function io(e,n,t){!e||n.has(e.name)||(n.add(e.name),t.push(e));}function so(e){let n=[],t=new Set;for(let i of e)if(ro(i))for(let o of to(i)){if(o.name.startsWith("@")){let r=join(i,o.name);for(let s of to(r))io(no(join(r,s.name),s.name),t,n);continue}io(no(join(i,o.name),o.name),t,n);}return n.sort((i,o)=>i.name.localeCompare(o.name))}g();Un();var Ja=/^[A-Za-z0-9_$.[\]"-]{0,200}$/,Ka=/^[a-z][a-z0-9-]{0,63}$/,Xa="<unknown>";function Ya(e){return typeof e=="string"&&(Y.includes(e)||e===B)}function ao(e){if(typeof e!="object"||e===null)return;let{file:n,path:t,rule:i}=e;if(!(typeof i!="string"||!Ka.test(i)))return {...Ya(n)?{file:n}:{},path:typeof t=="string"&&Ja.test(t)?t:Xa,rule:i}}function co(e){if(!Array.isArray(e))return;let n=Y.filter(t=>e.includes(t));return n.length>0?n:void 0}ir();var Ad=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/;function Yn(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?Id(e.relativePath,e.fileBytes):void 0);if(n!==void 0&&i!==void 0){let o=JSON.stringify({screenHash:n,skillHash:i});return 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 Id(e,n){let t=new TextEncoder().encode(qn(e)),i=gd(n),o=new Uint8Array(t.byteLength+1+i.byteLength);return o.set(t,0),o[t.byteLength]=0,o.set(i,t.byteLength+1),createHash("sha256").update(o).digest("hex")}function gd(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 qn(e){if(typeof e!="string"||e.length===0||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 Xn(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 sr(e,n){let t=relative(e,n).split(sep).join("/");return !t||t===".."||t.startsWith("../")||isAbsolute(t)?null:qn(t)}function md(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 ar(e){return Object.freeze({packageRoot:e})}function hd(e){return Object.freeze({id:e.definition.id,version:e.definition.version,hash:e.definition.hash,usage:e.definition.usage??we,...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 cr(e){return {capabilities:Object.freeze([...e]),origin:"local",ownership:"unknown",shareability:"unknown",sharingAvailability:"unavailable"}}function _d(e,n){let t=e.candidate,i=t.provenance!==void 0,o=n&&!i?["screen","skill"]:["screen"],r=hd(t),s=Yn(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,...cr(o),definition:r,...n===void 0||i?{}:{skillName:n.skill.name},...i?{provenance:t.provenance}:{localDefinitionRef:ar(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 Ed(e){let n=Td(e.skill.name),t={appId:n,name:e.skill.name,description:e.skill.description??"",...e.skill.version===void 0?{}:{version:e.skill.version},...cr(["skill"]),skillName:e.skill.name,localDefinitionRef:ar(e.packageRoot),definitionHash:Yn({skillHash:e.skillHash})};return {packageRoot:e.packageRoot,source:e.source,appId:n,capabilities:["skill"],summary:Object.freeze(t)}}function Td(e){return `skill.${e.replace(/^@/,"").replace(/\//g,".").replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,122)||"unnamed"}`}function q(e,n,t,i,o){let r=ao(o?.reason),s=co(o?.files);return Object.freeze({code:e,source:n,relativePath:Pd(t),...i===void 0?{}:{appId:i},...r===void 0?{}:{reason:r},...s===void 0?{}:{files:s}})}function Pd(e){if(typeof e!="string"||e.length===0||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 dr(e){return q(e.code,e.source,e.relativePath,e.pluginId,e)}function Nd(e,n){let t=sr(e,n.dir);if(!t)return {diagnostic:q("PATH_ESCAPED","node_modules","node_modules")};let i=md(t);if(!i)return {diagnostic:q("PATH_ESCAPED","node_modules",t)};let o=vt(n.skillMdPath);if(!o.readable)return {diagnostic:q("SKILL_READ_FAILED",i,t)};if(!o.valid)return {diagnostic:q("SKILL_INVALID",i,t)};let r=Dd(n.dir,n.skillMdPath);if(!r)return {diagnostic:q("PATH_ESCAPED",i,t)};try{let s=new Uint8Array(readFileSync(n.skillMdPath));return {skill:n,packageRoot:t,relativeSkillPath:r,skillHash:Yn({relativePath:r,fileBytes:s}),source:i}}catch{return {diagnostic:q("SKILL_READ_FAILED",i,t)}}}function Dd(e,n){let t=relative(e,n).split(sep).join("/");try{return qn(t)}catch{return null}}function bd(e){if(!Ad.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??we,...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??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 Sd(e){return e.builtinCatalog}function Md(e){let n=e.packageRoot??e.relativePath??e.packageRootPath;if(n===void 0)return null;try{return qn(n)}catch{return null}}function Ld(e){let n=e.marketplaceContentId;return typeof n=="string"&&n.length>0?n:void 0}function Od(e,n,t){let i=n.installed??[],o=new Map;for(let s of i){let a=Md(s);if(!a){t.push(q("INSTALLED_IDENTITY_MISMATCH","installed","installed"));continue}let c=o.get(a);if(c&&JSON.stringify(c)!==JSON.stringify(s)){t.push(q("INSTALLED_IDENTITY_MISMATCH","installed",a));continue}o.set(a,s);}let r=new Map;for(let s of e)s.packageRoot!==void 0&&r.set(s.packageRoot,s);for(let[s,a]of o){let c=r.get(s);if(!c){t.push(q("INSTALLED_MISSING","installed",s,a.appId));continue}let d=Ld(a);if(!d){t.push(q("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(q("INSTALLED_IDENTITY_MISMATCH","installed",s,a.appId));continue}let p={...c.summary,origin:"installed",...a.slug===void 0?{}:{slug:a.slug},marketplaceContentId:d},A=e.indexOf(c);A>=0&&(e[A]={...c,summary:Object.freeze(p)});}}function Rd(e,n){let t=new Map;for(let o of e){let r=t.get(o.appId)??[];r.push(o),t.set(o.appId,r);}let i=new Set;for(let o of t.values()){if(o.length<2)continue;let r=o.some(s=>s.source==="builtin")?"builtin":o.some(s=>s.source==="bundled")?"bundled":void 0;if(r!==void 0){let s=o.filter(a=>a.source===r);for(let a of o.filter(c=>c.source!==r))i.add(a),n.push(q("RESERVED_ID",a.source,ai(a),a.appId));if(s.length>1)for(let a of s)i.add(a),n.push(q("DUPLICATE_ID",a.source,ai(a),a.appId));continue}for(let s of o)i.add(s),n.push(q("DUPLICATE_ID",s.source,ai(s),s.appId));}return e.filter(o=>!i.has(o))}function ai(e){return e.packageRoot??e.summary.provenance?.packageDir??`builtin/${e.appId}`}function wd(e,n){return e.filter(t=>!(t.code==="MANIFEST_MISSING"&&n.has(t.relativePath))).map(dr)}function Ud(e){return e.filesystem}function Cd(e,n){let t=Ud(e),i=e.registeredProductBundle;return {...t===void 0?{}:{filesystem:t},...e.productBundle===void 0?{}:{productBundle:e.productBundle},...n===void 0?{}:{builtinCatalog:n},...i===void 0?{}:{reservedAppIds:i.reservedAppIds,reservedDefinitionIds:i.reservedDefinitionIds}}}async function pr(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=Sd(n),i=await tr(e,Cd(n,t)),o=n.registeredProductBundle??i.productBundleSnapshotMetadata,r=[join(e,"skills"),join(e,"node_modules"),join(e,"apps")],s=[],a=[],c=[],d=new Set;for(let u of r)for(let I of so([u])){let P=sr(e,I.dir);(P===null||!d.has(P))&&(c.push(I),P!==null&&d.add(P));}for(let u of c){let I=Nd(e,u);"diagnostic"in I?s.push(I.diagnostic):a.push(I);}let p=new Map,A=n.registeredProductBundle?.indexHash,m=(n.registeredProductBundle?.candidates??[]).filter(u=>A!==void 0&&u.provenance?.indexHash===A),y=[...i.apps??i.candidates??[],...m],h=new Set(m),O=new Set(A===void 0?[]:(t?.listMcpApps()??[]).filter(u=>u.provenance?.indexHash===A).map(u=>u.appId));for(let u of y){if(h.has(u)&&u.provenance?.indexHash===A&&O.has(u.appId))continue;let I=u.provenance===void 0?`workspace\0${u.relativePath}`:`bundled\0${u.provenance.indexHash}\0${u.provenance.packageDir}`;p.set(I,{candidate:u,packageRoot:u.relativePath});}let S=new Map(a.map(u=>[u.packageRoot,u])),F=[];for(let u of p.values()){let I=u.candidate.provenance===void 0?S.get(u.packageRoot):void 0,P=_d(u,I);F.push({...P.packageRoot===void 0?{}:{packageRoot:P.packageRoot},source:P.source,appId:P.appId,summary:P.summary});}let k=new Set([...p.values()].filter(u=>u.candidate.provenance===void 0).map(u=>u.packageRoot)),v=o===void 0?new Set:new Set(i.diagnostics.filter(u=>u.code==="RESERVED_ID"&&u.source!=="bundled").map(u=>u.relativePath)),V=new Set(o?.reservedAppIds??[]);for(let u of a){let I=Ed(u);if(!(k.has(u.packageRoot)||v.has(u.packageRoot))){if(V.has(I.appId)){s.push(q("RESERVED_ID",u.source,u.packageRoot,I.appId));continue}F.push({packageRoot:I.packageRoot,source:I.source,appId:I.appId,summary:I.summary});}}let E=[...wd(i.diagnostics,new Set(a.map(u=>u.packageRoot))),...s,...n.registeredProductBundle?.diagnostics.filter(u=>u.source==="bundled").map(dr)??[]],T=[];if(t)for(let u of t.listMcpApps()){let I=bd(u);"diagnostic"in I?E.push(I.diagnostic):T.push(I);}let C=Rd([...F,...T],E);Od(C,n,E);let D=C.map(u=>u.summary).sort((u,I)=>Xn(u.appId,I.appId)),l=[...E].sort((u,I)=>Xn(u.relativePath,I.relativePath)||Xn(u.code,I.code)||Xn(u.appId??"",I.appId??""));return Object.freeze({items:Object.freeze(D),diagnostics:Object.freeze(l)})}g();g();g();function kd(e){let n=o=>o.replace(/[.+^${}()|[\]\\]/g,"\\$&"),i=e.split("/").map(o=>o==="**"?".*":o.split("*").map(n).join("[^/]*"));return new RegExp(`^${i.join("\\/")}$`)}function on(e,n){try{return kd(n).test(e)}catch{return false}}function Zn(e,...n){let t=e.split("/");if(t.length<n.length)return false;let i=t.length-n.length;return n.every((o,r)=>on(t[i+r],o))}function xd(e,n){return e.split("/").some(t=>on(t,n))}var lr=[{label:".env*",test:e=>on(e,".env*")},{label:".git/",test:(e,n,t)=>t&&e===".git"},{label:"memory/",test:(e,n,t)=>t&&e==="memory"},{label:"*.key",test:e=>on(e,"*.key")},{label:"*.pem",test:e=>on(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&&Zn(n,".crewx","threads")},{label:".crewx/crewx.db",test:(e,n,t)=>!t&&Zn(n,".crewx","crewx.db")},{label:".crewx/*.log",test:(e,n,t)=>!t&&Zn(n,".crewx","*.log")},{label:".crewx/publish/",test:(e,n,t)=>t&&Zn(n,".crewx","publish")},{label:".crewx/",test:(e,n)=>xd(n,".crewx")}];function Qn(e,n,t){for(let i of lr)if(i.test(e,n,t))return i.label;return null}function pi(e){let n=[],t=[];function i(o,r,s){let a;try{a=Z.readdirSync(o,{withFileTypes:!0});}catch{return}a.sort((c,d)=>c.name.localeCompare(d.name));for(let c of a){let d=r?`${r}/${c.name}`:c.name,p=oe.join(o,c.name);if(c.isSymbolicLink()){let A;try{A=Z.statSync(p);}catch{t.push({path:d,rule:"symlink"});continue}if(A.isDirectory()){t.push({path:d,rule:s??"symlink-dir"});continue}let m=s??Qn(c.name,d,false);m?t.push({path:d,rule:m}):t.push({path:d,rule:"symlink"});continue}if(c.isDirectory()){let A=s??Qn(c.name,d,true);i(p,d,A);continue}if(c.isFile()){let A=s??Qn(c.name,d,false);A?t.push({path:d,rule:A}):n.push(d);}}}return i(e,"",null),n.sort(),t.sort((o,r)=>o.path<r.path?-1:o.path>r.path?1:0),{included:n,excluded:t}}g();var vd=[{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 jd(e){return e.includes(0)}function li(e,n,t){let i=[];for(let o of n){let r=oe.join(e,o),s;try{let c=t?.get(o);s=c===void 0?Z.readFileSync(r):Buffer.from(c);}catch{continue}if(jd(s))continue;s.toString("utf8").split(/\r\n|\r|\n/).forEach((c,d)=>{for(let{rule:p,regex:A}of vd)A.test(c)&&i.push({path:o,line:d+1,rule:p});});}return i}g();g();var Le=class extends Error{constructor(t,i){super(`publish: [${t}]${i?` ${i}`:""}`);this.code=t;}code;name="PublishError"};function _(e,n){return new Le(e,n)}var Ar=/^[a-z0-9-]+$/,Fd=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/,Vd=/^[A-Za-z_][A-Za-z0-9_]*$/;function Bd(e){let n=oe.join(e,"crewx.yaml");if(!Z.existsSync(n))return {};let t;try{t=Ir.load(Z.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 Hd(e){return ui.createHash("sha256").update(e).digest("hex")}function gr(e){let n;try{n=Z.lstatSync(e);}catch{throw _("PACKAGE_FILE_INVALID",`file is not readable: ${oe.basename(e)}`)}if(n.isSymbolicLink())throw _("PACKAGE_SYMLINK","symlink content is not publishable");if(!n.isFile())throw _("PACKAGE_FILE_INVALID","only regular files are publishable");return ui.createHash("sha256").update(new Uint8Array(Z.readFileSync(e))).digest("hex")}function zd(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 mr(e){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||oe.posix.isAbsolute(e)||e.split("/").some(n=>n===".."||n.length===0))throw _("PACKAGE_PATH_TRAVERSAL","manifest file path must be a non-empty POSIX relative path")}function $d(e){if(!/^(?:apps|skills)\/[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(e))throw _("APP_PACKAGE_ROOT_INVALID","packageRoot must be apps/<safe-id> or skills/<safe-id>")}function hr(e){if(!Fd.test(e))throw new Error(`publish: invalid version "${e}" \u2014 must be semver (e.g. 1.0.0)`)}function _r(e,n,t={}){let i=Bd(e),o=i.name??oe.basename(e);if(!Ar.test(o))throw new Error(`publish: invalid name "${o}" \u2014 must match ${Ar} (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");hr(r);let s=Array.isArray(i.requiredEnv)?i.requiredEnv:[],a=[];for(let p of s){if(typeof p!="string"||!Vd.test(p))throw new Error(`publish: requiredEnv must contain names only (no values), got "${String(p)}"`);a.push(p);}let c=n.map(p=>(mr(p),{path:p,sha256:gr(oe.join(e,p))})).sort((p,A)=>p.path<A.path?-1:p.path>A.path?1:0),d={name:o,version:r,type:"template",description:i.description??"",files:c,requiredEnv:a};return i.crewxMinVersion&&(d.crewxMinVersion=i.crewxMinVersion),d}function Gd(e){let n=e.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"");if(!n)throw _("APP_PACKAGE_ROOT_INVALID","appId cannot produce a marketplace name");return n}function Er(e,n){if($d(n.packageRoot),!n.version)throw new Error("publish: version is required for App publishing \u2014 pass opts.version");if(hr(n.version),typeof n.description!="string")throw new Error("publish: App description must be a string");let t=[...new Set(n.capabilities)].sort();if(t.length===0||t.some(s=>s!=="screen"&&s!=="skill"))throw new Error("publish: App capabilities must contain screen or skill");let i=`${n.packageRoot}/`;if(t.includes("screen")){if(typeof n.definitionId!="string"||n.definitionId.length===0)throw _("APP_UI_MANIFEST_INVALID","screen App manifests require definitionId");let s=n.includedFiles.includes(`${i}manifest.json`),a=n.includedFiles.includes(`${i}ui-plugin.json`);if(!s&&!a)throw _("APP_UI_MANIFEST_INVALID","screen App is missing manifest.json or ui-plugin.json");if(s&&!a)throw _("APP_UI_MANIFEST_INVALID","a manifest.json App must also ship a generated ui-plugin.json");if(!n.includedFiles.includes(`${i}ui/index.html`))throw _("APP_UI_MANIFEST_INVALID","screen App is missing ui/index.html")}if(t.includes("skill")&&!n.includedFiles.includes(`${i}SKILL.md`))throw _("APP_SKILL_MISSING","skill capability requires package-root SKILL.md");let o=new Set,r=n.includedFiles.map(s=>{if(mr(s),!s.startsWith(i))throw _("PACKAGE_PATH_TRAVERSAL","App manifest file is outside packageRoot");let a=n.generatedFiles?.get(s);return a!==void 0&&o.add(s),{path:s,sha256:a===void 0?gr(oe.join(e,s)):Hd(a),...a===void 0?{}:{generated:true}}}).sort((s,a)=>zd(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:Gd(n.appId),version:n.version,type:"app",description:n.description,appId:n.appId,...n.definitionId===void 0?{}:{definitionId:n.definitionId},...n.definitionHash===void 0?{}:{definitionHash:n.definitionHash},capabilities:t,packageRoot:n.packageRoot,files:r,requiredEnv:[]}}g();function Tr(e){return ui.createHash("sha256").update(e).digest("hex")}function Sr(e,n){if(typeof n!="string"||n.length===0||n.includes("\\")||n.includes("\0")||oe.posix.isAbsolute(n)||n.split("/").some(o=>o===".."||o.length===0))throw _("PACKAGE_PATH_TRAVERSAL","archive paths must be non-empty POSIX relative paths");let t=oe.resolve(e),i=oe.resolve(t,...n.split("/"));if(i!==t&&!i.startsWith(`${t}${oe.sep}`))throw _("PACKAGE_PATH_TRAVERSAL","archive path escaped its root");return i}function Pr(e,n){let t=Sr(e,n),i;try{i=Z.lstatSync(t);}catch{throw _("PACKAGE_FILE_INVALID","manifest file is missing")}if(i.isSymbolicLink())throw _("PACKAGE_SYMLINK","symlink content is not publishable");if(!i.isFile())throw _("PACKAGE_FILE_INVALID","only regular files are publishable");return new Uint8Array(Z.readFileSync(t))}async function Mr(e,n,t={}){let i=oe.join(e,".crewx","publish");Z.mkdirSync(i,{recursive:true});let o=oe.join(i,`${n.name}-${n.version}.tgz`),r=oe.join(i,`.${n.name}-${n.version}.${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}.tmp.tgz`),s=Z.mkdtempSync(oe.join(Nr.tmpdir(),"crewx-publish-"));try{let a=new Set,c=[];for(let d of n.files){if(a.has(d.path))throw _("PACKAGE_PATH_TRAVERSAL","manifest contains duplicate file paths");a.add(d.path);let p=t.generatedFiles?.get(d.path);if(d.generated===!0&&p===void 0)throw _("PACKAGE_GENERATED_FILE_MISSING","generated manifest file bytes are missing");if(t.sourceFileHashes?.has(d.path)){let y=Pr(e,d.path);if(t.sourceFileHashes.get(d.path)!==Tr(y))throw _("PACKAGE_STAGED_BYTES_MISMATCH","workspace source changed before staging")}let A=p??Pr(e,d.path);if(Tr(A)!==d.sha256)throw _("PACKAGE_STAGED_BYTES_MISMATCH",`staged bytes differ for ${d.path}`);let m=Sr(s,d.path);Z.mkdirSync(oe.dirname(m),{recursive:!0}),Z.writeFileSync(m,new Uint8Array(A)),c.push(d.path);}Z.writeFileSync(oe.join(s,"manifest.json"),JSON.stringify(n,null,2)),await br.create({gzip:!0,file:r,cwd:s,portable:!0,noMtime:!0},["manifest.json",...c]),Z.renameSync(r,o);}finally{try{Z.rmSync(r,{force:!0});}catch{}Z.rmSync(s,{recursive:true,force:true});}return o}g();g();var rn="/api/v1";var Kd=201,Xd=200,Yd=409,fi=401,Lr={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 qd(){return process.env.WI013_FAKE_UPLOAD==="1"}function Zd(e){let n=gunzipSync(new Uint8Array(e)),t=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 Qd(e){return e.replace(/\/+$/,"")}async function En(e){try{return await e.json()}catch{return null}}function Or(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 ep(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 np(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 Rr(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(Lr,r))continue;let s=r,a=s==="APP_NAME_CONFLICT"?`marketplace name is already in use: ${n}`:void 0;return _(Lr[s],a)}}async function tp(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=Qd(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}${rn}/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 En(a),d=ep(c),p=np(c),A=r&&p!==void 0?p:i,m;if(a.status===Kd)m="created";else if(r&&a.status===Xd){if(d===void 0)throw _("PUBLISH_CONTENT_ID_MISSING","App republish did not return an opaque contentId");m="existing";}else if(a.status===Yd){if(r)throw Rr(c,i)??_("APP_NAME_CONFLICT",`marketplace name is already in use: ${i}`);m="existing";}else throw a.status===fi?new Error("publish: [E_AUTH_EXPIRED] Authentication is expired or missing \u2014 please log in again (HTTP 401)"):new Error(`publish: [E_HTTP] Submit request failed \u2014 HTTP ${a.status}`);let y="not-needed",h=null;if(m==="existing"&&!r){let C;try{C=await fetch(`${n}${rn}/publisher/items`,{method:"GET",headers:{Authorization:`Bearer ${e.accessToken}`}});}catch{throw new Error("publish: [E_NETWORK] Publisher items request failed (network)")}let D=await En(C);if(C.status!==200)throw new Error(`publish: [E_HTTP] Publisher items request failed \u2014 HTTP ${C.status}`);let u=Or(D,"publisher items",C.status)?.items;if(!Array.isArray(u))throw new Error(`publish: [E_MALFORMED] Publisher items response is malformed (expected data.items[]) \u2014 HTTP ${C.status}`);let I=u.find(P=>!P||typeof P!="object"?false:P.slug===i);if(!I||typeof I.version!="string")throw new Error(`publish: [E_MALFORMED] Publisher items response does not contain slug "${i}" \u2014 HTTP ${C.status}`);if(h=I.version,h!==e.manifest.version){let P;try{P=await fetch(`${n}${rn}/publisher/items/${encodeURIComponent(i)}`,{method:"PUT",headers:{Authorization:`Bearer ${e.accessToken}`,"Content-Type":"application/json"},body:JSON.stringify({version:e.manifest.version})});}catch{throw new Error("publish: [E_NETWORK] Version update request failed (network)")}if(!P.ok)throw await En(P),P.status===fi?new Error(`publish: [E_AUTH_EXPIRED] Authentication is expired or missing \u2014 please log in again (HTTP ${P.status})`):P.status===403?new Error(`publish: [E_FORBIDDEN] Version update is forbidden; only the item owner can update an existing item (HTTP ${P.status})`):new Error(`publish: [E_HTTP] Version update failed \u2014 HTTP ${P.status}`);y="applied";}}let O=Z.readFileSync(e.tgzPath),S=qd()?Zd(O):O,F=new FormData;F.set("archive",new Blob([new Uint8Array(S)],{type:"application/gzip"}),`${A}-${e.manifest.version}.tgz`);let k=r&&d!==void 0?d:i,v;try{v=await fetch(`${n}${rn}/publisher/items/${encodeURIComponent(k)}/upload`,{method:"POST",headers:{Authorization:`Bearer ${e.accessToken}`},body:F});}catch{throw new Error("publish: [E_NETWORK] Upload request failed (network)")}if(v.status===fi)throw new Error("publish: [E_AUTH_EXPIRED] Authentication is expired or missing \u2014 please log in again (HTTP 401)");if(!v.ok){let C=await En(v);if(r){let D=Rr(C,A);if(D)throw D}throw new Error(`publish: [E_HTTP] Upload request failed \u2014 HTTP ${v.status}`)}let V=await En(v),E=Or(V,"upload",v.status),T=typeof E.contentId=="string"&&E.contentId.length>0?E.contentId:d;if(r&&T===void 0)throw _("PUBLISH_CONTENT_ID_MISSING","App upload did not return an opaque contentId");return {slug:A,version:e.manifest.version,...T===void 0?{}:{contentId:T},artifactChecksum:E.artifactChecksum,artifactSizeBytes:E.artifactSizeBytes,submitOutcome:m,versionUpdate:y,serverVersionBefore:h}}var ip=1e4,op=100*1024*1024;function yi(e){return ui.createHash("sha256").update(e).digest("hex")}function rp(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function Tn(e,n){if(!n||n.includes("\\")||n.includes("\0")||oe.posix.isAbsolute(n)||n.split("/").some(r=>r===".."||r.length===0))throw _("PACKAGE_PATH_TRAVERSAL","workspace file path is not a safe relative path");let t=oe.resolve(e,...n.split("/")),i=oe.resolve(e);if(t!==i&&!t.startsWith(`${i}${oe.sep}`))throw _("PACKAGE_PATH_TRAVERSAL","workspace file path escaped the workspace root");let o;try{o=Z.lstatSync(t);}catch{throw _("PACKAGE_FILE_INVALID",`workspace file is missing: ${n}`)}if(o.isSymbolicLink())throw _("PACKAGE_SYMLINK",`symlink is not publishable: ${n}`);if(!o.isFile())throw _("PACKAGE_FILE_INVALID",`not a regular file: ${n}`);return new Uint8Array(Z.readFileSync(t))}function nt(e,n){return e===n||e.startsWith(`${n}/`)}function sp(e,n){return e.path<n.path?-1:e.path>n.path?1:e.rule.localeCompare(n.rule)}function Ur(e,n,t){let i=e??n;if(!Number.isSafeInteger(i)||i<=0)throw new Le("PACKAGE_SIZE_LIMIT",`${t} must be a positive integer`);return i}function kr(e,n,t,i){let o=Ur(t.maxFileCount??t.maxFiles,ip,"max file count"),r=Ur(t.maxTotalBytes??t.maxBytes,op,"max total bytes");if(n.length>o)throw new Le("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+=Tn(e,a).byteLength,s>r)throw new Le("PACKAGE_SIZE_LIMIT",`package exceeds byte limit (${r})`)}}function ap(e){return e.appId!==void 0||e.expectedDefinitionHash!==void 0}function cp(e){let n=e.appId!==void 0,t=e.expectedDefinitionHash!==void 0;if(!n&&t)throw _("APP_ID_REQUIRED","appId is required with expectedDefinitionHash");if(n&&!t)throw _("APP_DEFINITION_HASH_REQUIRED","expectedDefinitionHash is required with appId");if(!n||!t)throw _("APP_ID_REQUIRED")}function dp(e,n){let t=e.filter(i=>i.appId===n);if(t.length===0)throw _("APP_NOT_FOUND",`no publishable App matches ${n}`);if(t.length!==1)throw _("APP_AMBIGUOUS",`more than one App matches ${n}`);return t[0]}function pp(e){let n=e.localDefinitionRef?.packageRoot;if(!n||!/^(?:apps|skills)\/[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(n))throw _("APP_PACKAGE_ROOT_INVALID","selected App is not rooted in apps/<safe-id> or skills/<safe-id>");return n}function lp(e,n){let t=[];for(let i of e.excluded)t.push(nt(i.path,n)?i:{path:i.path,rule:"out-of-app-scope"});for(let i of e.included)nt(i,n)||t.push({path:i,rule:"out-of-app-scope"});return t.sort(sp)}function Ai(e){let{path:n,rule:t}=e.reason;return `${e.code} at ${n===""?"<file>":n} (${t})`+(e.files.length>0?` [${e.files.join(", ")}]`:"")}function up(e,n,t){let i=Ve({[se]:t},{mode:"published"});if(!i.ok)throw _("APP_UI_MANIFEST_INVALID",`generated ${se} does not read: ${Ai(i.rejection)}`);if(en(i.manifest)!==en(n))throw _("APP_UI_MANIFEST_INVALID",`generated ${se} normalizes to a different definition hash than the source`);let o=e[W];if(o===void 0)return;let r=e[B],s=Ve({[W]:o,[se]:t,...r===void 0?{}:{[B]:r}},{mode:"local"});if(!s.ok)throw _("APP_UI_MANIFEST_INVALID",Ai(s.rejection))}function fp(e,n,t,i){let o={};for(let y of Y){let h=`${t}/${y}`;i.includes(h)&&(o[y]=Tn(e,h));}let r=`${t}/${B}`;if(o[W]!==void 0&&i.includes(r)&&(o[B]=Tn(e,r)),Object.keys(o).length===0)throw _("APP_UI_MANIFEST_INVALID","selected screen App has no package manifest.json or ui-plugin.json");let s=Ve(o,{mode:"local"});if(!s.ok)throw _("APP_UI_MANIFEST_INVALID",Ai(s.rejection));if(s.manifest.pluginId!==n.appId)throw _("APP_DEFINITION_CONFLICT",`${s.file} identity no longer matches the selected App`);let a=o[se],c=a===void 0?void 0:yi(a),d=`${t}/ui/index.html`;if(!i.includes(d))throw _("APP_UI_MANIFEST_INVALID","screen entry is outside package scope");let p=yi(Tn(e,d)),A=JSON.parse(JSON.stringify(s.v2Input));if(A.entryHash=p,Object.prototype.hasOwnProperty.call(A,"initialState")){let y=A.initialState;if(!rp(y)||y.path!=="ui/state.json")throw _("APP_INITIAL_STATE_OUT_OF_SCOPE","initialState must reference ui/state.json inside the package");let h=`${t}/ui/state.json`;if(!i.includes(h))throw _("APP_INITIAL_STATE_OUT_OF_SCOPE","initialState reference is outside the selected package");let O=Tn(e,h);A.initialState={...y,hash:yi(O)};}let m;try{let y=Fe(A,{mode:"published"});m=new Uint8Array(Buffer.from(JSON.stringify(y),"utf8"));}catch(y){throw y instanceof te?_("APP_UI_MANIFEST_INVALID",y.code):_("APP_UI_MANIFEST_INVALID")}return up(o,s.manifest,m),{bytes:m,...c===void 0?{}:{legacySourceHash:c}}}async function yp(e,n){let{included:t,excluded:i}=pi(e);kr(e,t,n);let o=_r(e,t,{version:n.version}),r=li(e,t);return {plan:{manifest:o,included:t,excluded:i,secretFindings:r},archiveOptions:{}}}async function Ap(e,n){cp(n);let t=await pr(e),i=dp(t.items,n.appId);if(i.definitionHash!==n.expectedDefinitionHash)throw _("APP_DEFINITION_CONFLICT",`definitionHash changed for ${n.appId}`);let o=pp(i),r=pi(e);if(r.excluded.some(y=>nt(y.path,o)&&(y.rule==="symlink"||y.rule==="symlink-dir")))throw _("PACKAGE_SYMLINK","selected App package contains a symlink");let s=r.included.filter(y=>nt(y,o)),a=lp(r,o),c=new Map,d=new Map;if(i.capabilities.includes("screen")){let y=fp(e,i,o,s),h=`${o}/${se}`;c.set(h,y.bytes),y.legacySourceHash!==void 0?d.set(h,y.legacySourceHash):(s.push(h),s.sort());}if(i.capabilities.includes("skill")&&!s.includes(`${o}/SKILL.md`))throw _("APP_SKILL_MISSING","skill capability requires package-root SKILL.md");kr(e,s,n,c);let p={appId:i.appId,version:n.version??"",description:i.description,capabilities:i.capabilities,packageRoot:o,...i.definition?.id===void 0?{}:{definitionId:i.definition.id},definitionHash:i.definitionHash,includedFiles:s,generatedFiles:c},A=Er(e,p),m=li(e,s,c);return {plan:{manifest:A,included:s,excluded:a,secretFindings:m},archiveOptions:{generatedFiles:c,sourceFileHashes:d}}}async function xr(e,n){let t=oe.resolve(e);if(ap(n))return Ap(t,n);if(n.expectedDefinitionHash!==void 0)throw _("APP_ID_REQUIRED");return yp(t,n)}async function my(e,n={}){return (await xr(e,n)).plan}function Ip(e){let n=e.map(t=>`${t.path}:${t.line} (${t.rule})`).join(", ");throw new Le("PUBLISH_SECRET_FINDINGS",`aborted \u2014 secret findings must be resolved before packing: ${n}`)}async function vr(e,n={}){let t=oe.resolve(e),i=await xr(t,n);i.plan.secretFindings.length>0&&Ip(i.plan.secretFindings);let o=await Mr(t,i.plan.manifest,i.archiveOptions);return {manifest:i.plan.manifest,tgzPath:o}}async function hy(e,n={}){return vr(e,n)}async function _y(e,n){let t=await vr(e,n);if(t.manifest.type!=="app")throw new Error("publish: App pack unexpectedly produced a template manifest");return t}
|
|
2
|
-
export{
|
|
1
|
+
import*as ce from'path';import {resolve,relative,sep,isAbsolute,join}from'path';import'url';import*as Si from'crypto';import {createHash}from'crypto';import {isIP}from'net';import*as ne from'fs';import {constants,readFileSync,existsSync,statSync,readdirSync}from'fs';import {realpath,stat,readdir,open,lstat}from'fs/promises';import*as Jr from'js-yaml';import {load}from'js-yaml';import*as ns from'os';import*as is from'tar';import {gunzipSync,gzipSync}from'zlib';var B=(e,n)=>()=>(e&&(n=e(e=0)),n);var m=B(()=>{});var U,Rn=B(()=>{m();U=class extends Error{constructor(t,i=t,o){super(i);this.code=t;this.currentRevision=o;}code;currentRevision;name="UiRuntimeError"};});function mt(e){return Is.test(e)||gs.test(e)}function fe(){throw new U("INPUT_INVALID","JSON value is not projection-safe")}function Es(e){let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function It(e,n,t,i,o,r){if(n>i&&fe(),e===null||typeof e=="string"||typeof e=="boolean")return typeof e=="string"&&(ms.test(e)||_s.test(e)&&!Ns(o,r)||hs.test(e))&&fe(),e;if(typeof e=="number")return Number.isFinite(e)||fe(),e;(typeof e!="object"||e===void 0||typeof e=="function"||typeof e=="bigint")&&fe();let s=e;t.has(s)&&fe(),t.add(s);try{if(Array.isArray(e))return e.map(d=>It(d,n+1,t,i,o,r));Es(s)||fe();let a={};for(let[d,c]of Object.entries(e))mt(d)&&fe(),a[d]=It(c,n+1,t,i,[...o,d],r);return a}finally{t.delete(s);}}function ye(e,n=0,t=[]){(!Number.isInteger(n)||n<0||n>Ps)&&fe(),(!Array.isArray(t)||t.some(o=>typeof o!="string"))&&fe();let i=It(e,0,new Set,Ts+n,[],t);return (i===null||Array.isArray(i)||typeof i!="object")&&fe(),i}function Ye(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 Ns(e,n){if(e.length===0)return false;let t=e.join(".");return n.some(i=>Ye(t,i))}function qe(e){try{let n=JSON.stringify(e);return n===void 0&&fe(),n}catch{fe();}}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 te(e){return qe(gt(e))}function ht(e){return Buffer.byteLength(e,"utf8")}var Is,gs,ms,hs,_s,Ts,Ps,Me=B(()=>{m();Rn();Is=/(?:proof|token|secret|password|cookie|authorization|private[_-]?key|stack|exception|plugin[_-]?text)/i,gs=/(?:url|uri|endpoint|path|file(?:name|path)?|cwd|shell|directory|dir|folder)$/i,ms=/<\/?[A-Za-z][^>]*>/,hs=/^(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)/,_s=/^(?:https?|file|ftp|ws|wss):\/\//i;Ts=8,Ps=4;});var Ri=B(()=>{m();Me();});var wn,_t=B(()=>{m();wn=["text/plain","application/json"];});var wi=B(()=>{m();_t();});function Ze(e){return bs.has(e)||Ss.test(e)||Ms.test(e)}var Ci,bs,Ss,Ms,Cn,un,Ee,Et,Tt,Pt,Nt,Dt,Ve=B(()=>{m();Ci=["__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"],bs=new Set(Ci),Ss=/(?:proof|token|secret|password|cookie|authorization|private[_-]?key|stack|exception|plugin[_-]?text)/i,Ms=/(?:url|uri|endpoint|path|file(?:name|path)?|cwd|shell|directory|dir|folder)$/i;Cn=/^[A-Za-z0-9_]+$/,un=/^[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"&&wn.includes(e)}var Ui=B(()=>{m();_t();Ve();});function Un(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")&&!Ls(e.in)||Object.hasOwn(e,"out")&&!Os(e.out))}function Ls(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 Os(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=B(()=>{m();wi();Ui();new TextDecoder("utf-8",{fatal:true,ignoreBOM:true});});function le(e){let t=e.renderer!==void 0||e.surfaces!==void 0||e.stateProjection!==void 0||e.dataPaths!==void 0||e.usage!==void 0||e.detailPanel!==void 0||e.displayModes!==void 0||e.summaryProjection!==void 0||e.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=ye(t);return createHash("sha256").update(te(i)).digest("hex")}function Ot(e){return `${e.id}\0${e.version}`}function Ae(e){if(!/^\d+$/.test(String(e.version))||e.version<1||e.id.length<1||e.id.length>128)throw new U("DEFINITION_UNSUPPORTED","UI definition is invalid");if(e.sourceHash!==void 0&&(typeof e.sourceHash!="string"||!ws.test(e.sourceHash)))throw new U("DEFINITION_UNSUPPORTED","UI definition source hash is invalid");if(!/^[0-9a-f]{64}$/.test(e.hash)||le(e)!==e.hash)throw new U("DEFINITION_UNSUPPORTED","UI definition hash is invalid");for(let[n,t]of Object.entries(e.actions)){if(!n||!Array.isArray(t.capabilities)||t.capabilities.some(i=>!Us(i)))throw new U("DEFINITION_UNSUPPORTED","UI action declaration is invalid");if(t.confirmation!==void 0&&t.confirmation!=="none"&&t.confirmation!=="native")throw new U("DEFINITION_UNSUPPORTED","UI action confirmation is invalid");if(t.inputKeys&&(!Array.isArray(t.inputKeys)||t.inputKeys.some(i=>typeof i!="string"||!i)))throw new U("DEFINITION_UNSUPPORTED","UI action input declaration is invalid");if(t.dataInputs!==void 0&&(!Array.isArray(t.dataInputs)||new Set(t.dataInputs).size!==t.dataInputs.length||t.dataInputs.some(i=>typeof i!="string"||!i||t.inputKeys!==void 0&&!t.inputKeys.includes(i))))throw new U("DEFINITION_UNSUPPORTED","UI action data input declaration is invalid");if(t.resultProjection&&Lt(t.resultProjection),t.content!==void 0&&!Un(t.content))throw new U("DEFINITION_UNSUPPORTED","UI action content declaration is invalid");if(t.env!==void 0&&(!Array.isArray(t.env)||t.env.length===0||new Set(t.env).size!==t.env.length||t.env.some(i=>i!=="CREWX_APP_INSTANCE_ID"&&i!=="CREWX_THREAD_ID")))throw new U("DEFINITION_UNSUPPORTED","UI action environment declaration is invalid")}if(e.renderer!==void 0&&(!e.renderer||e.renderer.length>128))throw new U("DEFINITION_UNSUPPORTED","UI definition renderer is invalid");if(e.surfaces&&(!Array.isArray(e.surfaces)||e.surfaces.some(n=>!n||n.length>64)))throw new U("DEFINITION_UNSUPPORTED","UI definition surfaces are invalid");if(e.usage!==void 0&&e.usage!=="card"&&e.usage!=="window")throw new U("DEFINITION_UNSUPPORTED","UI definition usage is invalid");if(e.detailPanel!==void 0&&typeof e.detailPanel!="boolean")throw new U("DEFINITION_UNSUPPORTED","UI definition detailPanel is invalid");if(e.displayModes&&(!Array.isArray(e.displayModes)||e.displayModes.length===0||new Set(e.displayModes).size!==e.displayModes.length||e.displayModes.some(n=>n!=="inline"&&n!=="floating"&&n!=="focused")))throw new U("DEFINITION_UNSUPPORTED","UI definition displayModes are invalid");if(e.usage==="card"&&e.displayModes!==void 0)throw new U("DEFINITION_UNSUPPORTED","Card definitions cannot declare displayModes");if(e.usage==="window"&&e.detailPanel!==void 0)throw new U("DEFINITION_UNSUPPORTED","Window definitions cannot declare detailPanel");if(e.stateProjection&&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 U("DEFINITION_UNSUPPORTED","UI summary projection exceeds state projection")}if(e.legacy!==void 0){if(!e.legacy||typeof e.legacy!="object"||Array.isArray(e.legacy)||Object.keys(e.legacy).some(o=>!["readTool","actionTool","hostTools","agentAccess"].includes(o)))throw new U("DEFINITION_UNSUPPORTED","UI legacy metadata is invalid");let n=new Set;for(let[o,r]of [["readTool",e.legacy.readTool],["actionTool",e.legacy.actionTool]])if(r!==void 0){if(Cs(r,o==="readTool"),n.has(r.name))throw new U("DEFINITION_UNSUPPORTED","UI legacy tool names collide");n.add(r.name);}let t=e.legacy.hostTools;if(t!==void 0){if(!t||typeof t!="object"||Array.isArray(t))throw new U("DEFINITION_UNSUPPORTED","UI legacy host tools are invalid");let o={"doc.open":"crewx_app_html_viewer_open","pty.connect":"crewx_app_terminal_connect"};for(let[r,s]of Object.entries(t)){if(!Object.hasOwn(o,r)||o[r]!==s||typeof s!="string"||!/^[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(s)||n.has(s))throw new U("DEFINITION_UNSUPPORTED","UI legacy host tools are invalid");n.add(s);}}let i=e.legacy.agentAccess;if(i!==void 0&&(!i||typeof i!="object"||Array.isArray(i)||Object.entries(i).some(([o,r])=>!o||!Object.hasOwn(e.actions,o)||r!=="allowed"&&r!=="denied")))throw new U("DEFINITION_UNSUPPORTED","UI legacy agent access is invalid");if(e.legacy.actionTool!==void 0&&(!i||Object.keys(i).length===0))throw new U("DEFINITION_UNSUPPORTED","UI legacy action tool requires its complete agent access map")}if(e.dataPaths!==void 0){let n=new Set(["__proto__","prototype","constructor"]);if(!Array.isArray(e.dataPaths)||e.dataPaths.length>16||new Set(e.dataPaths).size!==e.dataPaths.length||e.dataPaths.some(t=>typeof t!="string"||!/^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)*$/.test(t)||t.split(".").some(i=>n.has(i))||!(e.stateProjection?.allow??[]).some(i=>Ye(t,i))))throw new U("DEFINITION_UNSUPPORTED","UI definition dataPaths are invalid")}}function Cs(e,n){if(!e||typeof e!="object"||Array.isArray(e))throw new U("DEFINITION_UNSUPPORTED","UI legacy tool metadata is invalid");let t=e,i=["name","description","inputSchema","textFallback","visibility"],o=Object.hasOwn(t,"fixedResult");if(Object.keys(t).some(r=>!i.includes(r)&&!(n&&r==="fixedResult"))||i.some(r=>!Object.hasOwn(t,r))||typeof t.name!="string"||!/^[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(t.name)||typeof t.description!="string"||t.description.trim().length===0||t.description.length>8192||typeof t.textFallback!="string"||t.textFallback.trim().length===0||t.textFallback.length>16384||!t.inputSchema||typeof t.inputSchema!="object"||Array.isArray(t.inputSchema)||!Array.isArray(t.visibility)||t.visibility.length===0||t.visibility.some(r=>r!=="model"&&r!=="app")||new Set(t.visibility).size!==t.visibility.length)throw new U("DEFINITION_UNSUPPORTED","UI legacy tool metadata is invalid");try{let r=ye(t.inputSchema);if(r.type!==void 0&&r.type!=="object")throw new Error("schema type");if(o){if(!n)throw new Error("fixed result location");let s=t.fixedResult;if(!s||typeof s!="object"||Array.isArray(s))throw new Error("fixed result");let a=s;if(Object.keys(a).sort().join(",")!=="argsPolicy,structuredContent"||a.argsPolicy!=="empty-only"&&a.argsPolicy!=="ignore"||!a.structuredContent||typeof a.structuredContent!="object"||Array.isArray(a.structuredContent))throw new Error("fixed result");let d=ye(a.structuredContent);if(ht(qe(d))>4*1024)throw new Error("fixed result size")}}catch{throw new U("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 U("DEFINITION_UNSUPPORTED","UI projection policy is invalid")}function Us(e){return e.length>0&&e.length<=128&&e!=="*"&&e!=="all"&&!/[/*]/.test(e)}var ws,Be=B(()=>{m();Me();Rn();Mt();ws=/^[0-9a-f]{64}$/;});var H,Qe,Rt=B(()=>{m();H="dist/tools.json",Qe="dist/main.mjs";});var ke,wt=B(()=>{m();ke="window";});function ki(e){if(!Array.isArray(e)||e.length===0)return false;let n=new Set;for(let t of e){if(!ks.some(i=>i===t)||n.has(t))return false;n.add(t);}return true}var ks,xi=B(()=>{m();ks=["CREWX_APP_INSTANCE_ID","CREWX_THREAD_ID"];});function z(e){throw new Ct(e)}function Js(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 Ks(e,n){let t=Object.getOwnPropertyDescriptor(e,n);return (!t||!("value"in t))&&z("CSP_ORIGIN_INVALID"),t.value}function kn(e,n){if(!Object.prototype.hasOwnProperty.call(e,n))return [];let t=Ks(e,n);Array.isArray(t)||z("CSP_ORIGIN_INVALID"),Reflect.ownKeys(t).some(r=>typeof r!="string"||r!=="length"&&!/^(?:0|[1-9][0-9]*)$/.test(r))&&z("CSP_ORIGIN_INVALID");let o=[];for(let r=0;r<t.length;r+=1)(!Object.prototype.hasOwnProperty.call(t,r)||typeof t[r]!="string")&&z("CSP_ORIGIN_INVALID"),o.push(t[r]);return Object.keys(t).length!==t.length&&z("CSP_ORIGIN_INVALID"),o}function Xs(e){let n;try{n=JSON.stringify(e);}catch{z("CSP_ORIGIN_INVALID");}return n===void 0&&z("CSP_ORIGIN_INVALID"),new TextEncoder().encode(n).byteLength}function Fi(e,n){/\s|\\/u.test(e)&&z("CSP_ORIGIN_INVALID");let t=Hs.exec(e);t||z("CSP_ORIGIN_INVALID");let i=t[1].toLowerCase(),o=t[2];(o.includes("@")||o.includes("%")||o.includes("*"))&&z("CSP_ORIGIN_INVALID"),(o.startsWith("[")?zs:$s).test(o)||z("CSP_ORIGIN_INVALID"),i==="wss"&&n!=="connectDomains"&&z("CSP_ORIGIN_INVALID");let s;try{s=new URL(e);}catch{z("CSP_ORIGIN_INVALID");}(s.protocol!==`${i}:`||s.username!==""||s.password!==""||s.search!==""||s.hash!=="")&&z("CSP_ORIGIN_INVALID");let a=s.hostname.toLowerCase();if((!a||a.includes("%"))&&z("CSP_ORIGIN_INVALID"),!a.startsWith("[")){let c=a.endsWith(".")?a.slice(0,-1):a;(c.length===0||c.length>253)&&z("CSP_ORIGIN_INVALID"),c.split(".").some(p=>p.length>63||!Gs.test(p))&&z("CSP_ORIGIN_INVALID");}let d=s.origin;return (d==="null"||!d.startsWith(`${i}://`))&&z("CSP_ORIGIN_INVALID"),{origin:d,hostname:a}}function Ys(e){let n=e.split(".").map(Number);return ((n[0]*256+n[1])*256+n[2])*256+n[3]}function Vi(e,n,t){let i=4294967295<<32-t>>>0;return (e&i)===(n&i)}function zi(e){let n=Ys(e);return Vi(n,3221225472,24)?n!==3221225481&&n!==3221225482:Ws.some(([t,i])=>Vi(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 Zs(e){let n=qs(e),t=Number(n>>112n),i=Number(n>>96n&0xffffn);if(n>>32n===0xffffn){let o=Number(n&0xffffffffn);return zi([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 Qs(e,n){let t=e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e,i=isIP(t);if(i===4)return zi(t);if(i===6)return Zs(t);let o=e.toLowerCase().replace(/\.$/,"");return !o||!o.includes(".")||n.has(o)?true:Bs.some(r=>o===r||o.endsWith(`.${r}`))}function Bi(e){return Object.freeze([...new Set(e.map(n=>n.origin))].sort())}function Hi(e){return JSON.stringify({baseUriDomains:[],connectDomains:e.connectDomains,declared:e.declared,frameDomains:e.frameDomains,resourceDomains:[]})}function $i(e,n={}){if(e===void 0){let f=Hi({declared:false,connectDomains:[],frameDomains:[]});return Object.freeze({declared:false,connectDomains:Object.freeze([]),frameDomains:Object.freeze([]),resourceDomains:Object.freeze([]),baseUriDomains:Object.freeze([]),cspHash:createHash("sha256").update(f,"utf8").digest("hex")})}Js(e)||z("CSP_ORIGIN_INVALID");let t=Reflect.ownKeys(e);t.some(f=>typeof f!="string")&&z("CSP_ORIGIN_INVALID"),t.some(f=>!Vs.has(f))&&z("CSP_AXIS_UNKNOWN");let i=kn(e,"connectDomains"),o=kn(e,"frameDomains"),r=kn(e,"resourceDomains"),s=kn(e,"baseUriDomains");(r.length>0||s.length>0)&&z("CSP_AXIS_UNSUPPORTED"),(Xs(e)>vs||i.length>ji||o.length>ji||i.length+o.length>js||[...i,...o].some(f=>new TextEncoder().encode(f).byteLength>Fs))&&z("CSP_LIMIT_EXCEEDED");let d=i.map(f=>Fi(f,"connectDomains")),c=o.map(f=>Fi(f,"frameDomains")),l=new Set((n.runtimeHostnames??[]).map(f=>f.toLowerCase().replace(/\.$/,"")));[...d,...c].some(f=>Qs(f.hostname,l))&&z("CSP_ORIGIN_FORBIDDEN");let p={declared:true,connectDomains:Bi(d),frameDomains:Bi(c)},u=Hi(p);return Object.freeze({...p,resourceDomains:Object.freeze([]),baseUriDomains:Object.freeze([]),cspHash:createHash("sha256").update(u,"utf8").digest("hex")})}var vs,ji,js,Fs,Vs,Bs,Hs,zs,$s,Gs,Ws,Ct,Gi=B(()=>{m();vs=4096,ji=16,js=32,Fs=512,Vs=new Set(["connectDomains","frameDomains","resourceDomains","baseUriDomains"]),Bs=["localhost","local","internal","home.arpa","test","example","invalid","onion","lan","corp","home","intranet","private","localdomain"],Hs=/^(https|wss):\/\/([^/?#]+)$/i,zs=/^\[[^\]]+\](?::[0-9]+)?$/,$s=/^[^:\[\]]+(?::[0-9]+)?$/,Gs=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/,Ws=[[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 yn(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 se(e,n,t,i)}function $(e,n){try{return n()}catch(t){throw t instanceof se?t.withPathPrefix(e):t}}function G(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;try{let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}catch{return false}}function k(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function Sa(e,n){let t={};for(let[i,o]of Object.entries(e))i!==n&&(t[i]=o);return t}function X(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=>!k(e,s));r!==void 0&&A("MANIFEST_INVALID","MANIFEST_INVALID",r,"missing-key");}function Fn(e,n=false,t=false,i=false){return ia.test(e)||!i&&ra.test(e)||oa.test(e)||t&&Wi.test(e)||sa.test(e)&&!(n&&/^\s*data:/i.test(e)&&!Wi.test(e))}function jn(e,n=new Set,t=0,i=false,o=false,r=""){if(typeof e=="string"){Fn(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)=>jn(s,n,t+1,!1,!1,yn(r,`[${a}]`)));return}G(e)||A("MANIFEST_INVALID","MANIFEST_INVALID",r);for(let[s,a]of Object.entries(e))jn(a,n,t+1,i&&t===0&&(s==="name"||s==="description"),o,yn(r,s));}finally{n.delete(e);}}}function Te(e,n){let t=e[n];return typeof t!="string"&&A("MANIFEST_INVALID"),t}function ge(e,n,t){let i=e[n];return (!Number.isSafeInteger(i)||i<t)&&A("MANIFEST_INVALID"),i}function Ut(e){return ta.test(e)||A("MANIFEST_INVALID"),e}function en(e){return na.test(e)||A("TOKEN_INVALID"),e}function Ma(e){return no.test(e)||A("MANIFEST_INVALID"),e}function La(e){G(e)||A("MANIFEST_INVALID");let n={};for(let[t,i]of Object.entries(e)){let o=Ma(t);G(i)||A("MANIFEST_INVALID");let r=i.type;if(r==="text"){X(i,["type","maxLength"]),n[o]={type:r,maxLength:ge(i,"maxLength",1)};continue}if(r==="text-list"){X(i,["type","max","itemMaxLength"]),n[o]={type:r,max:ge(i,"max",0),itemMaxLength:ge(i,"itemMaxLength",1)};continue}if(r==="step-list"){X(i,["type","min","max","labelMaxLength","detailMaxLength"]);let s=ge(i,"min",0),a=ge(i,"max",1);s>a&&A("MANIFEST_INVALID"),n[o]={type:r,min:s,max:a,labelMaxLength:ge(i,"labelMaxLength",1),detailMaxLength:ge(i,"detailMaxLength",1)};continue}typeof r=="string"&&A("SCHEMA_TYPE_UNSUPPORTED"),A("MANIFEST_INVALID");}return n}function Oa(e,n,t){let i=e[n];(!i||i.type!==t)&&A("MANIFEST_INVALID");}function xn(e,n,t){let i=Te(e,"field");return no.test(i)||A("MANIFEST_INVALID"),Oa(n,i,t),i}function Ra(e,n){G(e)||A("MANIFEST_INVALID");let t=e.primitive;switch(typeof t!="string"&&A("MANIFEST_INVALID"),ba.includes(t)||A("PRIMITIVE_UNKNOWN"),t){case "card-shell":return X(e,["primitive"]),{primitive:t};case "meta-banner":return X(e,["primitive","badgeToken","noticeToken"]),{primitive:t,badgeToken:en(Te(e,"badgeToken")),noticeToken:en(Te(e,"noticeToken"))};case "heading":return X(e,["primitive","field"]),{primitive:t,field:xn(e,n,"text")};case "labeled-text":return X(e,["primitive","titleToken","field","variant"]),e.variant!=="callout"&&A("MANIFEST_INVALID"),{primitive:t,titleToken:en(Te(e,"titleToken")),field:xn(e,n,"text"),variant:"callout"};case "step-flow":return X(e,["primitive","titleToken","field"]),{primitive:t,titleToken:en(Te(e,"titleToken")),field:xn(e,n,"step-list")};case "text-list":{X(e,["primitive","titleToken","field"],["emptyToken","hideWhenEmpty"]);let i={primitive:t,titleToken:en(Te(e,"titleToken")),field:xn(e,n,"text-list")};return k(e,"emptyToken")&&(i.emptyToken=en(Te(e,"emptyToken"))),k(e,"hideWhenEmpty")&&(typeof e.hideWhenEmpty!="boolean"&&A("MANIFEST_INVALID"),i.hideWhenEmpty=e.hideWhenEmpty),i}}return A("MANIFEST_INVALID")}function wa(e,n){return Array.isArray(e)||A("MANIFEST_INVALID"),e.map(t=>Ra(t,n))}function Y(e="v2 manifest exceeds a contract limit",n,t){return A("LIMIT_EXCEEDED",e,n,t)}function Ie(e="initial state is not projection-safe"){return A("INITIAL_STATE_INVALID",e)}function Ji(e,n){return (typeof e!="string"||e.length===0||e.length>4096||e.trim().length===0||Pa.test(e)||Na.test(e))&&A("MANIFEST_INVALID",`${n} is invalid`),(Fn(e,true,true)||aa.test(e)||ca.test(e)||da.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 Ca(e){return (typeof e!="string"||!Et.test(e)||e==="*"||e==="all")&&A("MANIFEST_INVALID","action capability is invalid"),e}function to(e){return (typeof e!="string"||!Ta.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&&Y("v2 manifest string is too long",i,"string-too-long");return}if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){Number.isFinite(e)||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&&Y("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&&Y("v2 manifest array is too long",i,"array-too-long"),e.forEach((o,r)=>xt(o,n,t+1,yn(i,`[${r}]`)));return}G(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,yn(i,o));}finally{n.delete(e);}}}function io(e){return (typeof e!="string"||e.length>4096||!un.test(e))&&(typeof e=="string"&&e.length>4096&&Y("projection path is too long"),A("MANIFEST_INVALID","projection paths must be canonical exact paths")),e.split(".").some(t=>Ze(t))&&A("MANIFEST_INVALID","projection paths cannot address reserved state keys"),e}function vt(e){G(e)||A("MANIFEST_INVALID","projection policy must be an object"),X(e,["allow"]),Array.isArray(e.allow)||A("MANIFEST_INVALID","projection allow must be an array"),e.allow.length>128&&Y("projection allowlist is too long");let n=[],t=new Set;for(let i of e.allow){let o=io(i);t.has(o)&&A("MANIFEST_INVALID","projection allowlist contains a duplicate path"),t.add(o),n.push(o);}return {allow:n}}function Ua(e,n){if(e===void 0)return;Array.isArray(e)||A("MANIFEST_INVALID","dataPaths must be an array"),e.length>Da&&Y("dataPaths exceed the v2 limit");let t=[],i=new Set;for(let o of e){let r=io(o);i.has(r)&&A("MANIFEST_INVALID","dataPaths contain a duplicate path"),n.some(s=>Ye(r,s))||A("MANIFEST_INVALID","dataPaths must be projection-allowed"),i.add(r),t.push(r);}return t}function nn(e,n,t=Number.MAX_SAFE_INTEGER){return (!Number.isSafeInteger(e)||e<0||e>t)&&A("MANIFEST_INVALID",`${n} is invalid`),e}function Ki(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||Fn(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)&&Y("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&&Y("schema enum array is too long"),e.map(o=>jt(o,n+1,t));G(e)||A("MANIFEST_INVALID","schema enum contains a non-plain object");let i={};for(let[o,r]of Object.entries(e))Ze(o)&&A("MANIFEST_INVALID","schema enum contains a reserved key"),i[o]=jt(r,n+1,t);return i}finally{t.delete(e);}}function ka(e,n){if(e===void 0)return;Array.isArray(e)||A("MANIFEST_INVALID","schema required must be an array"),e.length>64&&Y("schema required list is too long");let t=[],i=new Set;for(let o of e)(typeof o!="string"||!un.test(o))&&A("MANIFEST_INVALID","schema required contains an invalid key"),o.length>4096&&Y("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 xa(e,n){let t=n?un:Cn;return e.length>4096&&Y("schema property name is too long"),(!t.test(e)||e.split(".").some(i=>Ze(i)))&&A("MANIFEST_INVALID","schema property name is invalid"),e}function Ft(e,n=0,t=false){G(e)||A("MANIFEST_INVALID","action inputSchema must be an object"),n>8&&Y("action inputSchema is too deep");let i=e.type;i!=="object"&&i!=="string"&&i!=="number"&&i!=="integer"&&i!=="boolean"&&i!=="array"&&i!=="null"&&(typeof i=="string"&&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"),X(e,["type"],o.filter(a=>a!=="type"));let r={type:i};if(k(e,"enum")&&(Array.isArray(e.enum)||A("MANIFEST_INVALID","schema enum must be an array"),e.enum.length>128&&Y("schema enum is too long"),r.enum=e.enum.map(a=>jt(a))),i==="string"&&(k(e,"minLength")&&(r.minLength=nn(e.minLength,"schema minLength",4096)),k(e,"maxLength")&&(r.maxLength=nn(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")&&(k(e,"minimum")&&(r.minimum=Ki(e.minimum,"schema minimum")),k(e,"maximum")&&(r.maximum=Ki(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"&&(k(e,"minItems")&&(r.minItems=nn(e.minItems,"schema minItems",128)),k(e,"maxItems")&&(r.maxItems=nn(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"),k(e,"items")&&(r.items=Ft(e.items,n+1,false))),i==="object"){let a;if(k(e,"properties")){G(e.properties)||A("MANIFEST_INVALID","schema properties must be an object");let c=Object.entries(e.properties);c.length>64&&Y("schema properties are too many"),a={};for(let[l,p]of c){let u=xa(l,t);a[u]=Ft(p,n+1,false);}r.properties=a;}k(e,"minProperties")&&(r.minProperties=nn(e.minProperties,"schema minProperties",64)),k(e,"maxProperties")&&(r.maxProperties=nn(e.maxProperties,"schema maxProperties",64)),r.minProperties!==void 0&&r.maxProperties!==void 0&&r.minProperties>r.maxProperties&&A("MANIFEST_INVALID","schema object property bounds are inverted");let d=ka(e.required,a);d!==void 0&&(r.required=d),k(e,"additionalProperties")&&(e.additionalProperties!==false&&A("MANIFEST_INVALID","schema additionalProperties must be false"),r.additionalProperties=false);}let s=JSON.stringify(r);return (s===void 0||Buffer.byteLength(s,"utf8")>65536)&&Y("action inputSchema subtree is too large"),r}function va(e){let n=Ft(e,0,true);return (n.type!=="object"||!n.properties)&&A("MANIFEST_INVALID","action inputSchema must declare object properties"),n}function ja(e){if(G(e)||A("MANIFEST_INVALID","action backend must be an object"),e.type==="core"){X(e,Ia);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"&&k(e,"entry"))return X(e,ha),e.entry!==Qe&&A("MANIFEST_INVALID",`skill backend entry must be ${Qe}`),{type:"skill",entry:Qe};if(e.type==="skill"){X(e,ga,ma),(!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=k(e,"env")?Va(e.env):void 0;return {type:"skill",command:n,...t===void 0?{}:{env:t}}}A("MANIFEST_INVALID","action backend type is unsupported");}function Fa(e){G(e)||A("MANIFEST_INVALID","action must be an object"),X(e,fa,ya),k(e,"_meta")&&$("_meta",()=>oo(e._meta));let n=$("actionId",()=>kt(e.actionId,"actionId"));mt(n)&&A("MANIFEST_INVALID",`actionId "${n}" is not projection-safe`,"actionId");let t=$("capability",()=>Ca(e.capability)),i=e.mutation;typeof i!="boolean"&&A("MANIFEST_INVALID","action mutation must be boolean","mutation");let o=$("inputSchema",()=>va(e.inputSchema)),r;if(k(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"||!k(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=$("resultProjection",()=>vt(e.resultProjection)),a=$("backend",()=>ja(e.backend)),d;k(e,"content")&&((a.type!=="skill"||!Un(e.content))&&A("MANIFEST_INVALID","action content declaration is invalid","content"),d=Ba(e.content));let c;if(k(e,"confirmation")){let l=e.confirmation;l!=="none"&&l!=="native"&&A("MANIFEST_INVALID","action confirmation is invalid","confirmation"),c=l;}return {actionId:n,capability:t,mutation:i,inputSchema:o,resultProjection:s,backend:a,...d===void 0?{}:{content:d},...r===void 0?{}:{dataInputs:r},...c===void 0?{}:{confirmation:c}}}function Va(e){return ki(e)||A("MANIFEST_INVALID","skill backend env is invalid"),Object.freeze([...e])}function Ba(e){return Object.freeze({...e.in===void 0?{}:{in:Object.freeze({...e.in})},...e.out===void 0?{}:{out:Object.freeze({...e.out})}})}function Ha(e){return G(e)||A("INITIAL_STATE_INVALID","initialState must be an object"),X(e,_a,Ea),e.path!=="ui/state.json"&&A("MANIFEST_INVALID","initialState path is not fixed"),k(e,"hash")?{path:"ui/state.json",hash:to(e.hash)}:{path:"ui/state.json"}}function za(e){let n=["wasm","terminal","htmlDocuments"];return (!G(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 $a(e,n){let t;try{t=$i(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 Ga(e,n){jn(G(e)&&k(e,"csp")?Sa(e,"csp"):e,new Set,0,true,true),xt(e),G(e)||A("MANIFEST_INVALID"),X(e,la,ua),k(e,"_meta")&&$("_meta",()=>oo(e._meta)),e.manifestVersion!==2&&A("MANIFEST_INVALID");let t;k(e,"runtime")&&(t=$("runtime",()=>za(e.runtime)));let i;k(e,"csp")&&(i=$("csp",()=>$a(e.csp,t)));let o=$("pluginId",()=>kt(e.pluginId,"pluginId")),r=$("definitionId",()=>kt(e.definitionId,"definitionId")),s=$("version",()=>ge(e,"version",1)),a=$("name",()=>Ji(e.name,"name")),d=$("description",()=>Ji(e.description,"description")),c;k(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;k(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;k(e,"entryHash")&&(p=$("entryHash",()=>to(e.entryHash)));let u;k(e,"initialState")&&(u=$("initialState",()=>Ha(e.initialState)));let f;k(e,"usage")&&(e.usage!=="card"&&e.usage!=="window"&&A("MANIFEST_INVALID","usage is invalid","usage"),f=e.usage);let g;k(e,"detailPanel")&&(typeof e.detailPanel!="boolean"&&A("MANIFEST_INVALID","detailPanel is invalid","detailPanel"),g=e.detailPanel);let E;if(k(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=e.displayModes;}(f??ke)===ke&&g!==void 0&&A("MANIFEST_INVALID","detailPanel is card-only","detailPanel");let O=n.mode??"local";O!=="local"&&O!=="installed"&&O!=="published"&&A("MANIFEST_INVALID","manifest mode is invalid"),O!=="local"&&p===void 0&&A("MANIFEST_INVALID","installed manifests require entryHash","entryHash","required-when-installed"),O!=="local"&&u!==void 0&&u.hash===void 0&&A("MANIFEST_INVALID","installed manifests require initialState.hash","initialState.hash","required-when-installed"),(!Array.isArray(e.surfaces)||e.surfaces.length===0)&&A("MANIFEST_INVALID","surfaces are invalid","surfaces"),e.surfaces.length>2&&Y("surfaces exceed the v2 limit","surfaces","too-many-items");let V=[],v=new Set;for(let y of e.surfaces)(typeof y!="string"||!Dt.includes(y))&&A("MANIFEST_INVALID","surface is unsupported","surfaces"),v.has(y)&&A("MANIFEST_INVALID","surfaces contain a duplicate","surfaces","duplicate-item"),v.add(y),V.push(y);G(e.size)||A("MANIFEST_INVALID","size must be an object","size"),$("size",()=>X(e.size,["height"]));let N=$("size",()=>ge(e.size,"height",1));N>720&&Y("size.height exceeds the v2 limit","size.height","too-large");let C=$("stateProjection",()=>vt(e.stateProjection)),j=e.summaryProjection===void 0?void 0:$("summaryProjection",()=>vt(e.summaryProjection));j!==void 0&&j.allow.some(y=>!C.allow.includes(y))&&A("MANIFEST_INVALID","summaryProjection must be a subset of stateProjection.allow","summaryProjection");let T=$("dataPaths",()=>Ua(e.dataPaths,C.allow));Array.isArray(e.actions)||A("MANIFEST_INVALID","actions must be an array","actions"),e.actions.length>32&&Y("actions exceed the v2 limit","actions","too-many-items");let D=[],L=new Set;for(let[y,I]of e.actions.entries()){let h=`actions[${y}]`,_=$(h,()=>Fa(I));if(L.has(_.actionId)&&A("MANIFEST_INVALID","actions contain a duplicate actionId",`${h}.actionId`,"duplicate-item"),_.backend.type==="core"&&_.backend.handler==="state.set"){_.mutation||A("MANIFEST_INVALID","state.set actions must be mutations",`${h}.mutation`);for(let M of Object.keys(_.inputSchema.properties))C.allow.includes(M)||A("MANIFEST_INVALID","state.set input paths must be projection-allowed",`${h}.inputSchema.properties`);}L.add(_.actionId),D.push(_);}return {manifestVersion:2,pluginId:o,definitionId:r,version:s,name:a,description:d,...c===void 0?{}:{icon:c},...l===void 0?{}:{tone:l},entry:"ui/index.html",...p===void 0?{}:{entryHash:p},...t===void 0?{}:{runtime:t},...i===void 0?{}:{csp:i},...u===void 0?{}:{initialState:u},...f===void 0?{}:{usage:f},...g===void 0?{}:{detailPanel:g},...E===void 0?{}:{displayModes:E},surfaces:V,size:{height:N},stateProjection:C,...j===void 0?{}:{summaryProjection:j},...T===void 0?{}:{dataPaths:T},actions:D}}function oo(e){G(e)||A("MANIFEST_INVALID","_meta must be an object");let n=JSON.stringify(e);(n===void 0||Buffer.byteLength(n,"utf8")>Aa)&&Y("_meta exceeds the 4 KiB limit",void 0,"meta-too-large");}function Wa(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=>Ye(o.join("."),a));return (e.length>4096||Fn(e,false,false,s))&&Ie("state contains an unsafe string"),e}if(e===null||typeof e=="boolean")return e;if(typeof e=="number")return Number.isFinite(e)||Ie("state contains a non-finite number"),e;(e===void 0||typeof e!="object"||typeof e=="function"||typeof e=="bigint")&&Ie("state contains a non-JSON value"),t>8&&Ie("state is too deep"),n.has(e)&&Ie("state contains a cycle"),n.add(e);try{let s;if(Array.isArray(e))e.length>128&&Ie("state array is too long"),s=e.map(d=>Vt(d,n,t+1,65536,o,r));else {G(e)||Ie("state contains a non-plain object");let d={};for(let[c,l]of Object.entries(e))(c.length>4096||!Cn.test(c)||Ze(c))&&(c.length>4096&&Ie("state key is too long"),Ie("state contains a reserved or invalid key")),d[c]=Vt(l,n,t+1,65536,[...o,c],r);s=d;}let a=JSON.stringify(s);return (a===void 0||Buffer.byteLength(a,"utf8")>i)&&Ie("state subtree is too large"),s}finally{n.delete(e);}}function Ht(e,n=[]){G(e)||Ie("initial state must be a JSON object");let t=Vt(e,new Set,0,65536,[],n);return (t===null||Array.isArray(t)||typeof t!="object")&&Ie(),t}function Ja(e,n={}){jn(e),G(e)||A("MANIFEST_INVALID"),X(e,pa),e.manifestVersion!==1&&A("MANIFEST_INVALID");let t=Ut(Te(e,"pluginId")),i=Ut(Te(e,"definitionId")),o=ge(e,"version",1),r=ge(e,"primitiveSet",1),s=n.supportedPrimitiveSet??ea;(!Number.isSafeInteger(s)||s<1)&&A("MANIFEST_INVALID"),r>s&&A("PRIMITIVE_SET_UNSUPPORTED"),G(e.activation)||A("MANIFEST_INVALID"),X(e.activation,["kind","language"]),e.activation.kind!=="fenced-code"&&A("MANIFEST_INVALID");let a=Ut(Te(e.activation,"language")),d=La(e.schema),c=wa(e.layout,d);return {manifestVersion:1,pluginId:t,definitionId:i,version:o,primitiveSet:r,activation:{kind:"fenced-code",language:a},schema:d,layout:c}}function Ka(e,n={}){return G(e)||A("MANIFEST_INVALID"),Object.hasOwn(e,"lineage")&&A("MANIFEST_INVALID","lineage is only allowed in product bundle indexes"),e.manifestVersion===2?Ga(e,n):Ja(e,n)}function ze(e,n={}){try{return Ka(e,n)}catch(t){if(t instanceof se)throw t;return A("MANIFEST_INVALID")}}function An(e,n={}){let t=ze(e,n);return t.manifestVersion===2?Wa(t):t}var ea,na,ta,no,ia,oa,ra,sa,Wi,aa,ca,da,pa,la,ua,fa,ya,Aa,Ia,ga,ma,ha,_a,Ea,Ta,Pa,Na,Da,ba,se,zt=B(()=>{m();wt();Me();Mt();xi();Rt();Gi();Ve();ea=1,na=/^[a-z][a-zA-Z0-9]*(\.[a-zA-Z0-9]+)+$/,ta=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,no=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,ia=/<\/?[A-Za-z][^>]*>/,oa=/^(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)/,ra=/^(?:https?|file|ftp|ws|wss):\/\//i,sa=/^\s*(?:javascript|data):/i,Wi=/data:[^,\s]*,/i,aa=/(?:https?|file|ftp|ws|wss):\/\//i,ca=/javascript:/i,da=/(?:^[\s]*|[\s"'(=])(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)(?=[^\s"'<>])[^\s"'<>]*/,pa=["manifestVersion","pluginId","definitionId","version","primitiveSet","activation","schema","layout"],la=["manifestVersion","pluginId","definitionId","version","name","description","entry","surfaces","size","stateProjection","actions"],ua=["_meta","icon","tone","entryHash","runtime","csp","initialState","usage","detailPanel","displayModes","summaryProjection","dataPaths","focusedAiDataPaths"],fa=["actionId","capability","mutation","inputSchema","resultProjection","backend"],ya=["confirmation","dataInputs","content","_meta"],Aa=4*1024,Ia=["type","handler"],ga=["type","command"],ma=["env"],ha=["type","entry"],_a=["path"],Ea=["hash"],Ta=/^[0-9a-f]{64}$/,Pa=/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/,Na=/[\r\n]/,Da=16,ba=["card-shell","meta-banner","heading","labeled-text","step-flow","text-list"],se=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,yn(t,this.path),this.rule)}};});function lo(e){return typeof e=="string"&&e.length<=Ya&&Xa.test(e)}function x(e,n,t,i,o){throw new Ne(e,{path:n,rule:t,...i===void 0?{}:{message:i},...o===void 0?{}:{file:o}})}function ie(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;try{let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}catch{return false}}function q(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function he(e){let n=`_meta["${xe}"]`;return e===void 0||e===""?n:e.startsWith("[")?`${n}${e}`:`${n}.${e}`}function ec(e){return e.toLowerCase().replace(/_/g,"-")}function nc(e){if(e===void 0||e==="")return "";let n=/^([^.[]+)(.*)$/.exec(e);if(!n)return he(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 he("definitionVersion");case "definitionId":return he("definitionId");default:return he(`${t}${i}`)}}function uo(e,n,t){return {path:t(e.path),rule:e.rule??ec(e.code),...e.message!==e.code?{message:e.message}:{},file:n}}function fo(e){return JSON.parse(JSON.stringify(e))}function Wt(e,n,t=0,i=new Set){if(typeof e=="string"){e.length>4096&&x("LIMIT_EXCEEDED",n,"string-too-long"),(qa.test(e)||Za.test(e)||Qa.test(e))&&x("UNSAFE_VALUE",n,"unsafe-value");return}if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){Number.isFinite(e)||x("MANIFEST_INVALID",n,"non-finite-number");return}typeof e!="object"&&x("MANIFEST_INVALID",n,"non-json-value"),t>8&&x("LIMIT_EXCEEDED",n,"too-deep"),i.has(e)&&x("MANIFEST_INVALID",n,"cycle"),i.add(e);try{if(Array.isArray(e)){e.length>128&&x("LIMIT_EXCEEDED",n,"array-too-long"),e.forEach((o,r)=>Wt(o,`${n}[${r}]`,t+1,i));return}ie(e)||x("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 me(e,n){return (typeof e!="string"||e.length===0)&&x("MANIFEST_INVALID",n,"string"),e}function on(e,n){return ie(e)||x("MANIFEST_INVALID",n,"object"),e}function tc(e,n){Array.isArray(e)||x("MANIFEST_INVALID",n,"array"),e.forEach((t,i)=>me(t,`${n}[${i}]`));}function ic(e,n){typeof e!="boolean"&&x("MANIFEST_INVALID",n,"boolean");}function In(e,n,t,i){for(let o of Object.keys(e))!t.includes(o)&&!i.includes(o)&&x("MANIFEST_INVALID",`${n}.${o}`,"unknown-key");for(let o of t)q(e,o)||x("MANIFEST_INVALID",`${n}.${o}`,"missing-key");}function oc(e,n){switch(Wt(n,e),e){case "long_description":case "homepage":case "documentation":case "support":case "icon":case "license":me(n,e);return;case "author":{let t=on(n,e);In(t,e,["name"],["email","url"]);for(let i of Object.keys(t))me(t[i],`${e}.${i}`);return}case "repository":{let t=on(n,e);In(t,e,[],["type","url"]);for(let i of Object.keys(t))me(t[i],`${e}.${i}`);return}case "icons":{Array.isArray(n)||x("MANIFEST_INVALID",e,"array"),n.forEach((t,i)=>{let o=`${e}[${i}]`,r=on(t,o);In(r,o,["src","size"],["theme"]),me(r.src,`${o}.src`),me(r.size,`${o}.size`),q(r,"theme")&&me(r.theme,`${o}.theme`);});return}case "screenshots":case "keywords":case "privacy_policies":tc(n,e);return;case "tools":{Array.isArray(n)||x("MANIFEST_INVALID",e,"array"),n.forEach((t,i)=>{let o=`${e}[${i}]`,r=on(t,o);In(r,o,["name"],["description"]),me(r.name,`${o}.name`),q(r,"description")&&me(r.description,`${o}.description`);});return}case "prompts":{Array.isArray(n)||x("MANIFEST_INVALID",e,"array"),n.forEach((t,i)=>{let o=`${e}[${i}]`,r=on(t,o);In(r,o,["name","text"],["description","arguments"]),me(r.name,`${o}.name`),me(r.text,`${o}.text`);});return}case "tools_generated":case "prompts_generated":ic(n,e);return;case "localization":case "compatibility":case "user_config":on(n,e);return;default:x("MANIFEST_INVALID",e,"unknown-key");}}function Vn(e){return typeof e=="string"&&Ee.test(e)?e:void 0}function yo(e){return Number.isSafeInteger(e)&&e>=1?e:void 0}function rc(e){let n=Vn(e.name);if(n===void 0)return;let t=e._meta,i=ie(t)?t[xe]:void 0,o=ie(i)?i:{},r=q(o,"definitionId")?Vn(o.definitionId):n,s=q(o,"definitionVersion")?yo(o.definitionVersion):1;return {pluginId:n,...r===void 0?{}:{definitionId:r},...s===void 0?{}:{definitionVersion:s}}}function sc(e){let n=Vn(e.pluginId);if(n===void 0)return;let t=Vn(e.definitionId),i=yo(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(!ie(n))return !1;let t=n._meta;return ie(t)&&q(t,xe)}catch{return false}}function ac(e,n){if(e===de)return n.builtinOnly===true;let t=n._meta,i=ie(t)?t[xe]:void 0;return ie(i)&&i.builtinOnly===true}function cc(e,n){q(e,"server")&&x("MANIFEST_INVALID","server","server-unsupported","phase 1 runs CrewX-owned Apps only");for(let a of Object.keys(e))Jt.includes(a)||x("MANIFEST_INVALID",a,"unknown-key");for(let a of Kt)q(e,a)||x("MANIFEST_INVALID",a,"missing-key");e.manifest_version!==$t&&x("MANIFEST_INVALID","manifest_version","unsupported-version",`manifest_version must be "${$t}"`),lo(e.version)||x("MANIFEST_INVALID","version","semver","version must be a semver.org version such as 0.1.0");let t=e._meta;ie(t)||x("MANIFEST_INVALID","_meta","object"),q(t,xe)||x("MANIFEST_INVALID",he(),"missing-key");let i=t[xe];ie(i)||x("MANIFEST_INVALID",he(),"object");for(let a of Object.keys(i))Gt.includes(a)||po.includes(a)||x("MANIFEST_INVALID",he(a),"unknown-key");for(let a of Gt)a==="actions"&&n!==void 0||q(i,a)||x("MANIFEST_INVALID",he(a),"missing-key");if(n!==void 0&&q(i,"actions")&&x("MANIFEST_INVALID",he("actions"),"two-truths",`actions are declared in both ${W} and ${H}; a server.ts App keeps them in the tools file only`),dc(i.actions),q(i,"definitionVersion")){let a=i.definitionVersion;(!Number.isSafeInteger(a)||a<1)&&x("MANIFEST_INVALID",he("definitionVersion"),"positive-integer");}let o={};for(let a of co)q(e,a)&&(oc(a,e[a]),o[a]=fo(e[a]));let r={};for(let[a,d]of Object.entries(t))a!==xe&&(r[a]=d);let s={manifestVersion:2,pluginId:e.name,definitionId:q(i,"definitionId")?i.definitionId:e.name,version:q(i,"definitionVersion")?i.definitionVersion:1,name:e.display_name,description:e.description};for(let[a,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:Qe}}))),Object.keys(r).length>0&&(s._meta=r),{v2Input:s,...Object.keys(r).length>0?{vendorMeta:r}:{},passthrough:o}}function dc(e){Array.isArray(e)&&e.forEach((n,t)=>{let i=ie(n)?n.backend:void 0;ie(i)&&q(i,"entry")&&x("MANIFEST_INVALID",he(`actions[${t}].backend.entry`),"entry-not-authorable",`an action in ${W} cannot name an entry; a server.ts App declares its actions in ${H}`);});}function pc(e,n,t){ie(e)||x("MANIFEST_INVALID","","not-object","manifest.json must be a JSON object",W);let i;try{i=cc(e,t);}catch(s){throw s instanceof Ne?new Ne(s.code,{...s.reason,file:W}):s}let o;try{let s=ze(i.v2Input,{mode:n.mode??"local"});s.manifestVersion!==2&&x("MANIFEST_INVALID","","v2-required"),o=s;}catch(s){throw s instanceof se?new Ne(s.code,uo(s,W,nc)):s}let r=e.tools;if(Array.isArray(r)){let s=new Set(o.actions.map(a=>a.actionId));r.forEach((a,d)=>{let c=a.name;if(!s.has(c))throw new Ne("MANIFEST_INVALID",{path:`tools[${d}].name`,rule:"tool-not-action",message:"every tools[].name must be an action id",file:W})});}return {file:W,manifest:o,v2Input:i.v2Input,releaseVersion:e.version,...Object.keys(i.passthrough).length>0?{mcpb:i.passthrough}:{}}}function lc(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:de});return {file:de,manifest:t,v2Input:e}}catch(t){throw t instanceof se?new Ne(t.code,uo(t,de,i=>i??"")):t}}function rn(e){return le(An(e).definition)}function so(e){let{entryHash:n,initialState:t,...i}=e,o={...i};return t!==void 0&&(o.initialState={path:t.path}),fo(o)}function uc(e,n){let t=so(e),i=so(n);return [...new Set([...Object.keys(t),...Object.keys(i)])].sort().filter(r=>te(t[r]??null)!==te(i[r]??null))}function fc(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 yc(e,n){let t=uc(e,n),i=fc(e,n),o="";try{let r=rn(e),s=rn(n);i=i||r!==s,o=` (definition hash ${r.slice(0,12)} vs ${s.slice(0,12)})`;}catch{i=true;}t.length===0&&!i||x("MANIFEST_DUAL_MISMATCH","","dual-manifest-mismatch",`${W} and ${de} 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:H},files:[]}}function ao(e){return {...Pe("","tools-needs-manifest-json","MANIFEST_INVALID",`${H} is read with ${W} only`),files:e}}function Ac(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(!ie(t))return {failure:Pe("","not-object","MANIFEST_INVALID",`${H} 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(!q(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(!ie(r))return {failure:Pe(`actions[${o}]`,"object")};if(q(r,"backend"))return {failure:Pe(`actions[${o}].backend`,"tools-backend","MANIFEST_INVALID",`an action in ${H} cannot carry a backend`)}}return {actions:i}}function Ic(e,n){let t=n.maxBytes??262144,i=[],o=new TextDecoder("utf-8",{fatal:true});for(let r of Z){let s=e[r];if(s===void 0)continue;if(s.byteLength>t)return {parsed:i,failure:{code:"LIMIT_EXCEEDED",reason:{path:"",rule:"file-too-large",file:r},files:[r]}};let a;try{a=JSON.parse(o.decode(s));}catch{return {parsed:i,failure:{code:"MANIFEST_INVALID",reason:{path:"",rule:"invalid-json",file:r},files:[r]}}}if(!ie(a))return {parsed:i,failure:{code:"MANIFEST_INVALID",reason:{path:"",rule:"not-object",message:`${r} must be a JSON object`,file:r},files:[r]}};i.push({file:r,raw:a});}return {parsed:i}}function $e(e,n={}){let{parsed:t,failure:i}=Ic(e,n),o=Z.filter(f=>e[f]!==void 0);if(i!==void 0)return {ok:false,rejection:i,parseFailure:true,builtinOnly:false};let r=e[H],s=r===void 0?void 0:Ac(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:[]}:ao(o),parseFailure:true,builtinOnly:false};let a=t[0],d=a.file===W?rc(a.raw):sc(a.raw),c=t.some(f=>ac(f.file,f.raw)),l;if(s!==void 0){let f=t.some(g=>g.file===W)?s.failure:ao(o);if(f!==void 0)return {ok:false,rejection:f,parseFailure:false,...d===void 0?{}:{identity:d},builtinOnly:c};l=s.actions;}let p=[];try{for(let f of t)p.push(f.file===W?pc(f.raw,n,l):lc(f.raw,n));p.length===2&&yc(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"?[...Z]:f.reason.file===void 0||f.reason.file===H?o:[f.reason.file]},parseFailure:false,...d===void 0?{}:{identity:d},builtinOnly:c};throw f}let u=p[0];return {ok:true,...u,identity:d??{pluginId:u.manifest.pluginId},files:o}}var W,de,Z,$t,xe,Jt,Kt,co,Gt,po,Xa,Ya,qa,Za,Qa,Ne,Bn=B(()=>{m();Be();Me();Rt();Ve();zt();W="manifest.json",de="ui-plugin.json",Z=[W,de],$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"]),co=Object.freeze(Jt.filter(e=>e!=="server"&&!Kt.includes(e))),Gt=Object.freeze(["entry","surfaces","size","stateProjection","actions"]),po=Object.freeze(["definitionId","definitionVersion","icon","tone","entryHash","runtime","initialState","usage","detailPanel","displayModes","summaryProjection","dataPaths","focusedAiDataPaths","csp"]),Xa=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/,Ya=256,qa=/<\/?[A-Za-z][^>]*>/,Za=/^\s*javascript:/i,Qa=/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=B(()=>{m();Ri();Bn();zt();Ve();});function b(e,n=e){throw new De(e,n)}var De,zn=B(()=>{m();De=class extends Error{constructor(t,i=t){super(i);this.code=t;}code;name="McpAppContractError"};});var Do=B(()=>{m();});var bo=B(()=>{m();Be();Me();zn();Do();});function Mo(e,n){return So.add(e),n!==void 0&&Mc.set(e,n),e}function sn(e){return e!==null&&typeof e=="object"&&So.has(e)}var So,Mc,$n=B(()=>{m();So=new WeakSet,Mc=new WeakMap;});function _n(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 Ro(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let n of Object.values(e))Ro(n);return Object.freeze(e)}function oe(e){throw new be("LINEAGE_INVALID",e)}function kc(e){throw new be("LINEAGE_STALE",e)}function wo(e){if(!_n(e)||!Zt(e,Rc,wc)||!_n(e.actions))return oe("Lineage definition shape is invalid");for(let n of Object.values(e.actions))if(!_n(n)||!Zt(n,Cc,Uc))return oe("Lineage action definition shape is invalid");return e}function xc(e){if(!_n(e)||!Zt(e,Lc,Oc))return oe("Lineage entry shape is invalid");if(!Number.isSafeInteger(e.version)||e.version<1||typeof e.hash!="string"||!Lo.test(e.hash))return oe("Lineage entry identity is invalid");if(e.sourceHash!==void 0&&(typeof e.sourceHash!="string"||!Lo.test(e.sourceHash)))return oe("Lineage source hash is invalid");if(e.compat!==void 0&&e.compat!=="break")return oe("Lineage compatibility marker is invalid");let n=wo(e.definition);if(n.version!==e.version)return oe("Lineage version does not match its definition");if(e.sourceHash!==void 0&&n.sourceHash!==e.sourceHash)return oe("Lineage source hash does not match its definition");let t;try{t=le(n),Ae({...n,hash:e.hash});}catch{return oe("Lineage definition is invalid")}return t!==e.hash?oe("Lineage definition hash does not match"):Ro({version:e.version,hash:e.hash,definition:n,...e.sourceHash===void 0?{}:{sourceHash:e.sourceHash},...e.compat===void 0?{}:{compat:e.compat}})}function Oo(e){return e.stateProjection?.allow??[]}function vc(e,n){let t=[],i=new Set(Oo(n));Oo(e).some(a=>!i.has(a))&&t.push("S1_STATE_PROJECTION");let o=new Set(n.dataPaths??[]);(e.dataPaths??[]).some(a=>!o.has(a))&&t.push("S2_DATA_PATHS");for(let[a,d]of Object.entries(e.actions)){let c=n.actions[a];if(c&&(d.confirmation??"native")==="native"&&(c.confirmation??"native")!=="native"){t.push("S3_ACTION_CONFIRMATION");break}}Object.keys(e.legacy?.agentAccess??{}).some(a=>!Object.hasOwn(n.actions,a))&&t.push("S4_LEGACY_AGENT_ACTIONS");let s=e.summaryProjection?.allow;if(s!==void 0){let a=new Set(n.summaryProjection?.allow??[]);s.some(d=>!a.has(d))&&t.push("S5_SUMMARY_PROJECTION");}return t}function jc(e,n){return te(e)===te(n)}function Qt(e,n){if(!Array.isArray(e)||e.length===0)return oe("Definition lineage is missing");if(!_n(n)||typeof n.hash!="string")return oe("Current definition is invalid");let t,i;try{let{hash:a,...d}=n;i=wo(d),t={...i,hash:a},Ae(t);}catch{return oe("Current definition is invalid")}let o=e.map(xc),r=o[0].definition.id;if(o.some(a=>a.definition.id!==r))return oe("Lineage definition ids do not match");if(o.some((a,d)=>d>0&&a.version<=o[d-1].version))return oe("Lineage generations are not in increasing version order");if(o.some((a,d)=>o.findIndex(c=>c.hash===a.hash)!==d))return oe("Lineage contains a duplicate hash");let s=o[o.length-1];if(s.version!==t.version||s.hash!==t.hash||s.definition.id!==t.id||!jc(s.definition,i))return kc("The last lineage generation does not match the current package");if(t.legacy!==void 0){let a=new Set(Object.keys(t.actions)),d=new Set;for(let l of o)if(l.sourceHash===void 0)for(let p of Object.keys(l.definition.actions))a.has(p)&&d.add(p);let c=Object.keys(t.legacy.agentAccess??{});if(c.length!==d.size||c.some(l=>!d.has(l))){let l="S4_LEGACY_AGENT_ACCESS_COMPLETE";throw new 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 c=vc(o[a].definition,t);if(c.length>0)throw new be("LINEAGE_INVALID",`Lineage compatibility failed: ${c.join(", ")}`,c)}return Object.freeze({entries:Object.freeze(o),current:t})}var be,Lo,Lc,Oc,Rc,wc,Cc,Uc,ei=B(()=>{m();Be();Me();be=class extends Error{constructor(t,i=t,o=[]){super(i);this.code=t;this.violations=o;}code;violations;name="UiDefinitionLineageError"},Lo=/^[0-9a-f]{64}$/,Lc=["version","hash","definition"],Oc=["sourceHash","compat"],Rc=["id","version","actions"],wc=["sourceHash","usage","detailPanel","displayModes","renderer","surfaces","stateProjection","dataPaths","summaryProjection","legacy"],Cc=["capabilities"],Uc=["inputKeys","dataInputs","confirmation","resultProjection","content","env"];});var Co,Uo,ko,ni,xo=B(()=>{m();Co="text/html;profile=mcp-app",Uo=["crewx_app_terminal_connect","crewx_app_html_viewer_open"],ko=["crewx_listWorkspaces","crewx_queryAgent","crewx_executeAgent","crewx_getTaskResult","crewx_listTasks","crewx_listAgents","callBrowser","openTab","listTabs","closeTab"],ni="text/html";});function vo(e,n=[],t){if(e.content!==void 0||e.confirmation!=="none")return "denied";let i=Fc();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 Fc(e){return;}var jo=B(()=>{m();Be();$n();});function Kc(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))&&b(n,`${t} must be a safe identifier`),e}function En(e,n,t){let i=e??t;return (typeof i!="string"||i.trim().length===0||i.length>Hc)&&b("TOOL_INVALID",`${n} must be a meaningful description`),i}function ii(e){return (typeof e!="string"||e.length===0||e.length>an||!/<html(?:\s|>)/i.test(e)||!/<\/html\s*>/i.test(e))&&b("HTML_INVALID","MCP App HTML must be a non-empty HTML document"),e}function Tn(e,n=0){try{let t=ye(e,n);return t.type!==void 0&&t.type!=="object"&&b("TOOL_INVALID","MCP App inputSchema must describe an object"),t}catch(t){if(t instanceof De)throw t;b("TOOL_INVALID","MCP App inputSchema must be projection-safe JSON");}}function Xc(e){return (typeof e!="string"||e.trim().length===0||e.length>zc)&&b("TOOL_INVALID","MCP App tools require a meaningful text fallback"),e}function Yc(e){e===void 0&&b("TOOL_INVALID","MCP App tool visibility is required");let n=[...e];return (n.length===0||n.some(t=>t!=="model"&&t!=="app")||new Set(n).size!==n.length)&&b("TOOL_INVALID","MCP App tool visibility must contain model and/or app once"),n}function zo(e){return (typeof e!="string"||!Bo.test(e))&&b("RESOURCE_URI_INVALID","MCP App resource URI is not a registered ui:// URI"),e}function $o(e){let n=Fe(e.appId,"APP_ID_INVALID","Local App id"),t=En(e.name,"Local App name",n),i=En(e.description,"Local App description",`${t} interactive view`),o=Kn(e.definition),r=ii(e.html),s=Gn(e.entryHash,"Local App entry hash"),a=e.entryBytes===void 0?Array.from(new TextEncoder().encode(r)):Jn(e.entryBytes,"Local App entry bytes");(Wn(a)!==s||Jo(a)!==r)&&b("HTML_INVALID","Local App entry bytes do not match the HTML hash");let d=qc(e),c=[];Array.isArray(e.actions)||b("TOOL_INVALID","Local App actions must be an array");for(let N of e.actions){let C=Fe(N.actionId,"TOOL_ID_INVALID","Local App action id");(c.includes(C)||!Object.prototype.hasOwnProperty.call(o.actions,C))&&b("TOOL_INVALID",`Local App action is not declared by the UI definition: ${C}`),c.push(C);}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&&b("TOOL_INVALID","A static local App cannot register an action tool"),c.length>0&&p===void 0&&b("TOOL_INVALID","A stateful local App requires an action tool name"),p!==void 0&&p===l&&b("TOOL_ID_CONFLICT",`Local App read and action tools share a name: ${l}`);let u=Kc(e.runtime);u.some(N=>N.name===l||N.name===p)&&b("TOOL_ID_CONFLICT","Local App read or action tool conflicts with a requested Host capability");let f={name:l,description:`${t} current state`,inputSchema:Jc,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:oi(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 E=[],O=new Set(g.map(N=>N.name));if(p!==void 0)for(let N of e.actions){let C=`${p}__${N.actionId}`;if(C.length>128||!Vo.test(C)){E.push(Object.freeze({toolName:C,actionId:N.actionId,reason:"name_too_long"}));continue}if(O.has(C)){E.push(Object.freeze({toolName:C,actionId:N.actionId,reason:"name_collision"}));continue}let j=vo({actionId:N.actionId,confirmation:o.actions[N.actionId]?.confirmation,content:o.actions[N.actionId]?.content,backend:N.backend},e.modelActions),T=Object.freeze(j==="denied"?["app"]:["model","app"]),D={name:C,description:`${C} action`,inputSchema:Tn(N.inputSchema),textFallback:`${C} action requests are handled by the open App instance.`,visibility:T,kind:"action",resourceBinding:je,actionId:N.actionId,actionIds:Object.freeze([N.actionId]),_meta:Object.freeze({ui:Object.freeze({visibility:T})})};g.push(Object.freeze(D)),O.add(C);}let V={mimeType:ni,entryHash:s,html:r,bytes:Object.freeze([...a]),...d===void 0?{}:{initialState:Object.freeze({hash:d.hash,bytes:Object.freeze([...d.bytes])})}},v={appId:n,name:t,description:i,...e.icon===void 0?{}:{icon:Ko(e.icon)},...e.tone===void 0?{}:{tone:Xo(e.tone)},builtinOnly:false,definition:o,...e.runtime===void 0?{}:{runtime:Object.freeze({...e.runtime})},resourceBinding:je,resource:Object.freeze(V),tools:Object.freeze(g),toolDiagnostics:Object.freeze(E)};return Q(v)}function Go(e={}){return new ti(e)}function oi(e){if(e.length===0)return Tn({type:"object",properties:{},additionalProperties:false});let n=e.map(i=>i.actionId),t=new Map;for(let i of e)t.set(i.actionId,Tn(i.inputSchema));return Tn(Zc(n,t),Ho)}function qc(e){let n=e.definition.dataPaths??[];if(e.initialStateBytes===void 0){e.initialStateHash!==void 0&&b("STATE_INVALID","Initial state hash has no bytes"),e.initialState!==void 0&&ye(e.initialState,0,n);return}e.initialStateHash===void 0&&b("STATE_INVALID","Initial state bytes require a hash");let t=Gn(e.initialStateHash,"Initial state hash"),i=Jn(e.initialStateBytes,"Initial state bytes");Wn(i)!==t&&b("STATE_INVALID","Initial state bytes do not match the hash");let o;try{let r=new TextDecoder("utf-8",{fatal:!0}).decode(Uint8Array.from(i));o=ye(JSON.parse(r),0,n);}catch{b("STATE_INVALID","Initial state bytes are not projection-safe JSON");}return e.initialState!==void 0&&te(o)!==te(ye(e.initialState,0,n))&&b("STATE_INVALID","Initial state bytes do not match the state value"),{hash:t,bytes:Object.freeze([...i])}}function Zc(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 Qc(e){let n=Pn(e),t=Fe(n.appId,"APP_ID_INVALID","MCP App id"),i=ii(n.html);zo(n.uiUri);let o=n.definition===void 0?void 0:Kn(n.definition),r=e.provenance;r!==void 0&&(!sn(r)||r.appId!==t||r.definitionId!==o?.id||r.version!==o?.version||r.definitionHash!==o?.hash)&&b("TOOL_INVALID","Product App built-in registration provenance is not verified");let s=Object.freeze(n.tools.map(c=>Q(Pn(c)))),a=Q({...n,appId:t,html:i,...o===void 0?{}:{definition:o},...r===void 0?{}:{provenance:r},tools:s}),d=Q({uri:a.uiUri,mimeType:Co,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:d,tools:s,descriptor:a})}function ed(e){(e.resourceBinding.kind!=="instance"||e.builtinOnly!==false)&&b("STATE_INVALID","Local App registration binding is invalid"),Object.prototype.hasOwnProperty.call(e,"uiUri")&&b("STATE_INVALID","Local App registration cannot contain uiUri");let n=Fe(e.appId,"APP_ID_INVALID","Local App id"),t=Kn(e.definition),i=e.provenance;i!==void 0&&(!sn(i)||i.appId!==n||i.definitionId!==t.id||i.version!==t.version||i.definitionHash!==t.hash)&&b("TOOL_INVALID","Product App local registration provenance is not verified");let o=ii(e.resource.html),r=Gn(e.resource.entryHash,"Local App entry hash"),s=Jn(e.resource.bytes,"Local App entry bytes");(Wn(s)!==r||Jo(s)!==o)&&b("HTML_INVALID","Local App entry bytes do not match the HTML hash");let a=e.resource.initialState===void 0?void 0:{hash:Gn(e.resource.initialState.hash,"Initial state hash"),bytes:Jn(e.resource.initialState.bytes,"Initial state bytes")};a&&Wn(a.bytes)!==a.hash&&b("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"),En(c.description,"Local App tool description","Local App tool"),Xc(c.textFallback);let l=Tn(c.inputSchema,c.kind==="action"&&!("actionId"in c)?Ho:0);if((c.resourceBinding.kind!=="instance"||Object.prototype.hasOwnProperty.call(c,"resourceUri"))&&b("TOOL_INVALID","Local App tools cannot carry an MCP resource URI"),c.kind==="host")return (!Wc.has(c.name)||c.visibility.length!==1||c.visibility[0]!=="app"||Object.prototype.hasOwnProperty.call(c,"actionId"))&&b("TOOL_INVALID","Local App Host tools must use an allow-listed name and app-only visibility"),Q({...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)||b("TOOL_INVALID","Local App action tool references an undeclared action");let f=Yc(c._meta.ui.visibility);return JSON.stringify(f)!==JSON.stringify(c.visibility)&&b("TOOL_INVALID","Local App action metadata visibility must match the tool visibility"),Q({...c,actionId:u,actionIds:Object.freeze([u]),inputSchema:l,visibility:f,_meta:{ui:{visibility:f}}})}let p=[...c.actionIds];return (p.length===0||p.some(u=>!Object.prototype.hasOwnProperty.call(t.actions,u)))&&b("TOOL_INVALID","Local App action tool references an undeclared action"),Q({...c,inputSchema:l,actionIds:Object.freeze(p)})}return Q({...c,inputSchema:l})});return Q({appId:n,name:En(e.name,"Local App name",e.appId),description:En(e.description,"Local App description",e.name),...e.icon===void 0?{}:{icon:Ko(e.icon)},...e.tone===void 0?{}:{tone:Xo(e.tone)},builtinOnly:false,definition:t,...e.runtime===void 0?{}:{runtime:Object.freeze({...e.runtime})},...i===void 0?{}:{provenance:i},resourceBinding:je,resource:Q({mimeType:ni,entryHash:r,html:o,bytes:Object.freeze([...s]),...a===void 0?{}:{initialState:Object.freeze({hash:a.hash,bytes:Object.freeze([...a.bytes])})}}),tools:Object.freeze(d),toolDiagnostics:Object.freeze([...e.toolDiagnostics??[]])})}function nd(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:Wo(e.definition),...e.provenance===void 0?{}:{provenance:e.provenance},entryHash:e.resource.entryHash,resourceBinding:je,tools:e.tools})}function td(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:Wo(e.definition)},resourceBinding:Object.freeze({kind:"mcp",uri:e.uiUri}),tools:e.tools})}function Kn(e){try{if(Object.isFrozen(e))return Ae(e),Q(e);let n=Pn(e);return Ae(n),Q(n)}catch(n){if(n instanceof De)throw n;b("STATE_INVALID","UI definition is not a valid immutable definition");}}function Wo(e){return Q({id:e.id,version:e.version,hash:e.hash})}function id(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 Gn(e,n){return (typeof e!="string"||!Bc.test(e))&&b("SERIALIZATION_INVALID",`${n} is invalid`),e}function Wn(e){return createHash("sha256").update(Uint8Array.from(e)).digest("hex")}function Jn(e,n){return (!Array.isArray(e)||e.some(t=>!Number.isInteger(t)||t<0||t>255))&&b("SERIALIZATION_INVALID",`${n} is invalid`),[...e]}function Jo(e){try{return new TextDecoder("utf-8",{fatal:!0}).decode(Uint8Array.from(e))}catch{b("SERIALIZATION_INVALID","UTF-8 bytes are invalid");}}function Ko(e){return (typeof e!="string"||!$c.test(e))&&b("TOOL_INVALID","MCP App icon is invalid"),e}function Xo(e){return (typeof e!="string"||!Gc.has(e))&&b("TOOL_INVALID","MCP App tone is invalid"),e}function Pn(e,n=new Map){if(e===null||typeof e!="object")return e;let t=e;if(n.has(t)&&b("SERIALIZATION_INVALID","MCP App value contains a cycle"),Array.isArray(e)){let r=[];n.set(t,r);for(let s of e)r.push(Pn(s,n));return n.delete(t),r}let i;try{i=Object.getPrototypeOf(e);}catch{b("SERIALIZATION_INVALID","MCP App value cannot be cloned");}i!==Object.prototype&&i!==null&&b("SERIALIZATION_INVALID","MCP App value must be plain JSON");let o={};n.set(t,o);for(let[r,s]of Object.entries(e))Object.defineProperty(o,r,{configurable:true,enumerable:true,value:Pn(s,n),writable:true});return n.delete(t),o}function Q(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))Q(t,n);return Object.freeze(e),e}var Vo,Bo,Bc,an,Hc,zc,$c,Gc,Wc,je,Jc,Ho,ti,Xn=B(()=>{m();bo();Be();Me();$n();zn();ei();xo();jo();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})$/,Bc=/^[0-9a-f]{64}$/,an=8*1024*1024,Hc=8*1024,zc=16*1024,$c=/^[a-z][a-z0-9-]{0,63}$/,Gc=new Set(["blue","violet","emerald","amber","rose","sky","slate","indigo"]),Wc=new Set(Uo),new Set(ko),je=Object.freeze({kind:"instance"}),Jc=Object.freeze({type:"object",properties:Object.freeze({}),additionalProperties:false});Ho=4;ti=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=Qc(p);s.has(u.appId)&&b("APP_ID_CONFLICT",`MCP App id is already registered: ${u.appId}`),s.add(u.appId);let f=u.tools;for(let g of f)a.has(g.name)&&b("TOOL_ID_CONFLICT",`MCP App tool name is already registered: ${g.name}`),a.add(g.name),this.mcpToolByName.set(g.name,g),r.push(g);this.mcpResources.set(u.resource.uri,u.resource),i.push(u),o.push(u.descriptor);}let d=(n.localApps??n.locals??[]).map(ed),c=new Set(d.flatMap(p=>p.tools.filter(u=>!(u.kind==="action"&&"actionId"in u)).map(u=>u.name))),l=[];for(let p of d){let u=p;s.has(u.appId)&&b("APP_ID_CONFLICT",`MCP App id is already registered: ${u.appId}`),s.add(u.appId);let f=[],g=[...u.toolDiagnostics??[]];for(let E of u.tools){if(a.has(E.name)){if(E.kind==="host"&&this.localToolByName.get(E.name)?.kind==="host"){f.push(E);continue}if(E.kind==="action"&&"actionId"in E){g.push(Object.freeze({toolName:E.name,actionId:E.actionId,reason:"name_collision"}));continue}b("TOOL_ID_CONFLICT",`MCP App tool name is already registered: ${E.name}`);}if(E.kind==="action"&&"actionId"in E&&c.has(E.name)){g.push(Object.freeze({toolName:E.name,actionId:E.actionId,reason:"name_collision"}));continue}a.add(E.name),this.localToolByName.set(E.name,E),f.push(E);}(f.length!==u.tools.length||g.length!==(u.toolDiagnostics?.length??0))&&(u=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,td(p)),p.definition&&this.addDefinition(p.definition);for(let p of l)this.registrationById.set(p.appId,p),this.launcherById.set(p.appId,nd(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){zo(n);let t=this.mcpResources.get(n);return t||b("RESOURCE_NOT_FOUND",`MCP App resource is not registered: ${n}`),t}listLocalMcpApps(){return this.localApps}getLocalMcpApp(n){return this.localById.get(n)??null}listLocalMcpAppTools(){return Object.freeze([...this.localToolByName.values()])}resolveLocalMcpAppTool(n){return this.localToolByName.get(n)??null}resolveLocalMcpAppResource(n,t){let i=this.localById.get(n);return !i||t!==void 0&&i.definition.hash!==t?null:i.resource}listRegistrations(){return Object.freeze([...this.builtinApps,...this.localApps])}getRegistration(n){return this.registrationById.get(n)??null}listLaunchers(){return Object.freeze([...this.launcherById.values()].filter(n=>{let t=this.registrationById.get(n.appId),i=t?"descriptor"in t?t.descriptor.provenance:t.provenance:void 0,o=sn(i)&&i.launcher===false;return t?.definition?.usage!=="card"&&!o}))}getLauncher(n){return this.launcherById.get(n)??null}resolveDefinition(n){if(!id(n))return null;let t=this.definitionByKey.get(Ot(n));if(!t||t.hash!==n.hash)return null;try{return le(t)===t.hash?t:null}catch{return null}}resolveActionHandler(n,t,i){return typeof n!="string"||typeof i!="string"||!Number.isSafeInteger(t)?null:this.handlerByKey.get(Fo(n,t,i))??null}addDefinition(n){let t=Kn(n),i=Ot(t),o=this.definitionByKey.get(i);o&&o.hash!==t.hash&&b("STATE_INVALID",`UI definition generation conflicts: ${i}`),o||this.definitionByKey.set(i,t);}addHandler(n){(!n||typeof n.definitionId!="string"||typeof n.actionId!="string"||!Number.isSafeInteger(n.version)||n.version<1||typeof n.handle!="function")&&b("STATE_INVALID","UI action handler registration is invalid");let t=Fo(n.definitionId,n.version,n.actionId);this.handlerByKey.has(t)&&b("TOOL_INVALID",`Duplicate UI action handler registration: ${t}`),this.handlerByKey.set(t,Object.freeze({...n}));}};});function od(e){let n=$o({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 Yo(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=od(e);Go({localApps:[t],definitions:[e.definition]});}var qo=B(()=>{m();Xn();});function rd(e){if(e===null||typeof e!="object"||!(Zo in e))throw new TypeError("scanCache must be created by createWorkspaceAppScanCache");return e[Zo]}function Qo(e,n){let t=rd(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 Zo,er=B(()=>{m();Zo=Symbol("crewx.workspace-app-scan-cache.state");});function ue(e){let n=typeof e=="object"&&e!==null&&"code"in e?String(e.code):"";return n==="ENOENT"?new S("NOT_FOUND"):n==="ELOOP"?new S("PATH_ESCAPED"):n==="EFBIG"||n==="EOVERFLOW"?new S("LIMIT_EXCEEDED"):n==="EACCES"||n==="EPERM"||n==="ENOTDIR"?new S("READ_DENIED"):new S("READ_DENIED")}function dd(e){if(typeof e!="string"||e.length===0||!isAbsolute(e))throw new S("READ_DENIED")}function ri(e){if(typeof e!="string"||isAbsolute(e)||/[\\\u0000]/.test(e))throw new S("PATH_ESCAPED");if(e==="")return [];let n=e.split("/");if(n.some(t=>t.length===0||t==="."||t===".."))throw new S("PATH_ESCAPED");return n}function Qn(e,n){let t=relative(e,n);return t===""||t!==".."&&!t.startsWith(`..${sep}`)&&!isAbsolute(t)}function dn(e){return {dev:e.dev,ino:e.ino,size:e.size,mtimeNs:e.mtimeNs,ctimeNs:e.ctimeNs}}function di(e,n){return e.dev===n.dev&&e.ino===n.ino}function pi(e,n){return di(e,n)&&e.size===n.size&&e.mtimeNs===n.mtimeNs&&e.ctimeNs===n.ctimeNs}async function Yn(e){dd(e);let n,t;try{n=await realpath(e),t=await stat(n,{bigint:!0});}catch(i){throw ue(i)}if(!t.isDirectory())throw new S("READ_DENIED");return {realRoot:n,identity:dn(t)}}async function ir(e,n,t){if(t.length<2||t[0]!=="apps"&&t[0]!=="skills")return;let i,o;try{if(i=resolve(e,t[0],t[1]),o=await realpath(i),!(await stat(o,{bigint:!0})).isDirectory())throw new S("READ_DENIED")}catch(r){throw r instanceof S?r:ue(r)}if(!Qn(n,o))throw new S("PATH_ESCAPED");return o}async function qn(e,n,t,i){let o,r,s;try{o=await lstat(e,{bigint:!0}),r=await realpath(e),s=await stat(r,{bigint:!0});}catch(a){throw ue(a)}if(!Qn(n,r)||t!==void 0&&!Qn(t,r))throw new S("PATH_ESCAPED");if(!o.isFile()||!s.isFile())throw new S("READ_DENIED");if(!di(i,o)||!di(i,s)||i.dev!==s.dev)throw new S("PATH_ESCAPED")}async function cn(e,n){let t,i;try{t=await realpath(e),i=await stat(t,{bigint:!0});}catch{throw new S("PATH_ESCAPED")}if(t!==n.realRoot||!pi(n.identity,dn(i)))throw new S("PATH_ESCAPED")}function pd(e){return e.isSymbolicLink()?{name:e.name,kind:"symlink"}:e.isDirectory()?{name:e.name,kind:"directory"}:e.isFile()?{name:e.name,kind:"file"}:{name:e.name,kind:"other"}}var S,ci,cd,tr,et,or,ui=B(()=>{m();S=class extends Error{constructor(t){super(t);this.code=t;}code;name="AppDiscoveryFsError"},ci=constants.O_NOFOLLOW,cd=constants.O_NONBLOCK,tr=constants.O_RDONLY|(ci??0)|(cd??0);et=class{async getRootIdentity(n){let t=await Yn(n);return await cn(n,t),{dev:t.identity.dev,ino:t.identity.ino,realPath:t.realRoot}}async listDirectory(n,t){let i=ri(t),o=await Yn(n),r=resolve(n,...i),s,a;try{s=await realpath(r),a=await stat(s,{bigint:!0});}catch(d){let c=ue(d);if(c.code==="NOT_FOUND")return [];throw c}if(!Qn(o.realRoot,s)||!a.isDirectory())throw new S("PATH_ESCAPED");try{let d=await readdir(s,{withFileTypes:!0,encoding:"utf8"});return await cn(n,o),d.map(pd)}catch(d){let c=ue(d);if(c.code==="NOT_FOUND")return [];throw c}}async readdir(n,t){return this.listDirectory(n,t)}async readDirectory(n,t){return this.listDirectory(n,t)}async readVerifiedFile(n,t,i){if(!Number.isSafeInteger(i)||i<0)throw new S("READ_DENIED");if(ci===void 0)throw new S("UNSUPPORTED");let o=ri(t),r=await Yn(n),s=resolve(n,...o),a=relative(n,s);if(a===".."||a.startsWith(`..${sep}`)||isAbsolute(a))throw new S("PATH_ESCAPED");let d;try{d=await open(s,tr);}catch(c){throw ue(c)}try{let c;try{let g=await d.stat({bigint:!0});c=dn(g);}catch(g){throw ue(g)}if(c.size>BigInt(i))throw new S("LIMIT_EXCEEDED");if(c.size>BigInt(Number.MAX_SAFE_INTEGER))throw new S("LIMIT_EXCEEDED");await cn(n,r);let l=await ir(n,r.realRoot,o);await qn(s,r.realRoot,l,c);let p=new Uint8Array(new ArrayBuffer(Number(c.size))),u=0;for(;u<p.byteLength;){let g;try{g=(await d.read(p,u,p.byteLength-u,u)).bytesRead;}catch(E){throw ue(E)}if(g<=0)throw new S("IDENTITY_CHANGED");u+=g;}let f;try{let g=await d.stat({bigint:!0});f=dn(g);}catch(g){throw ue(g)}if(!pi(c,f))throw new S("IDENTITY_CHANGED");return await qn(s,r.realRoot,l,f),await cn(n,r),new Uint8Array(p)}finally{await d.close().catch(()=>{});}}async fingerprintVerifiedFile(n,t,i){if(!Number.isSafeInteger(i)||i<0)throw new S("READ_DENIED");if(ci===void 0)throw new S("UNSUPPORTED");let o=ri(t),r=await Yn(n),s=resolve(n,...o),a=relative(n,s);if(a===".."||a.startsWith(`..${sep}`)||isAbsolute(a))throw new S("PATH_ESCAPED");let d;try{d=await open(s,tr);}catch(c){throw ue(c)}try{let c;try{let u=await d.stat({bigint:!0});c=dn(u);}catch(u){throw ue(u)}if(c.size>BigInt(i)||c.size>BigInt(Number.MAX_SAFE_INTEGER))throw new S("LIMIT_EXCEEDED");await cn(n,r);let l=await ir(n,r.realRoot,o);await qn(s,r.realRoot,l,c);let p;try{let u=await d.stat({bigint:!0});p=dn(u);}catch(u){throw ue(u)}if(!pi(c,p))throw new S("IDENTITY_CHANGED");return await qn(s,r.realRoot,l,p),await cn(n,r),{...p,candidateRealPath:l??r.realRoot}}catch(c){throw c instanceof S?c:ue(c)}finally{await d.close().catch(()=>{});}}async readFileVerified(n,t,i){return this.readVerifiedFile(n,t,i)}},or=new et;});function Sn(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 sr(e){return typeof e=="string"&&Ee.test(e)?e:void 0}function gd(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 md(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 hd(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 _d(e){return Ad.decode(e)}function Ed(e){return JSON.parse(_d(e))}function ar(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 Td(e){if(e instanceof S)return ar(e.code);if(e!==null&&typeof e=="object"&&"code"in e){let n=e.code;if(typeof n=="string")return ar(n)}}function Oe(e,n){let t=n();return Number.isFinite(t)&&Number.isFinite(e)&&t-e<=5e3}function Pd(e){if(typeof e.readVerifiedFile=="function")return e.readVerifiedFile;if(typeof e.readFileVerified=="function")return e.readFileVerified}function Nd(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 cr(e,n,t,i){let o=Pd(e);if(!o)throw new S("READ_DENIED");return hd(await o.call(e,n,t,i))}async function Ai(e,n,t){let i=Nd(e);if(!i)throw new S("READ_DENIED");let o=await i.call(e,n,t);if(!Array.isArray(o))throw new S("READ_DENIED");return o.map(md).filter(r=>r!==null)}function Dd(e,n,t,i){return Object.freeze({code:e,...{},source:n,relativePath:t})}function bd(e){if(!Sn(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 Sd(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 tt(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 nt(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 dr(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 Md(e){let n;try{n=Ed(e);}catch{return}if(!Sn(n)||!nt(n,["version","packages"])||n.version!==1||!Array.isArray(n.packages)||n.packages.length>Ii)return;let t=new Set,i=new Set,o=0,r=[];for(let s of n.packages){if(!Sn(s))return;let a=["packageDir","appId","definition","files"],d=Object.hasOwn(s,"lineage"),c=Object.hasOwn(s,"launcher"),l=[...d?["lineage"]:[],...c?["launcher"]:[]];if(!nt(s,[...a,...l])||c&&s.launcher!==false)return;let p=dr(s.packageDir),u=sr(s.appId);if(!p||p.length!==2||p[0]!=="apps"||!gd(p[1])||!u||t.has(s.packageDir)||!Sn(s.definition)||!nt(s.definition,["id","version","hash"]))return;let f=sr(s.definition.id),g=s.definition.version,E=s.definition.hash;if(!f||!Number.isSafeInteger(g)||g<1||typeof E!="string"||!yi.test(E)||!Array.isArray(s.files)||s.files.length<2||s.files.length>gi)return;let O=new Set,V=[];for(let v of s.files){if(!Sn(v)||!nt(v,["path","sha256"]))return;let N=dr(v.path);if(!N||typeof v.sha256!="string"||!yi.test(v.sha256))return;let C=N.join("/"),j=`${s.packageDir}/${C}`;if(O.has(C)||i.has(j))return;O.add(C),i.add(j),V.push(Object.freeze({path:C,sha256:v.sha256}));}if(!Z.some(v=>O.has(v))||!O.has("ui/index.html")||(o+=V.length,o>ud))return;t.add(s.packageDir),r.push(Object.freeze({packageDir:s.packageDir,...c?{launcher:false}:{},appId:u,definition:Object.freeze({id:f,version:g,hash:E}),lineage:Array.isArray(s.lineage)?s.lineage:[],files:Object.freeze(V.sort((v,N)=>We(v.path,N.path)))}));}return Object.freeze({version:1,packages:Object.freeze(r)})}function Ge(e){let n=Td(e);return n==="PATH_ESCAPED"||n==="IDENTITY_CHANGED"||n==="TOCTOU"?"PATH_ESCAPED":n==="LIMIT_EXCEEDED"?"LIMIT_EXCEEDED":"BUNDLE_INTEGRITY"}async function Ld(e,n,t,i,o){let r=[],s=async(a,d)=>{if(!Oe(i,o))throw new S("LIMIT_EXCEEDED");if(d>2)throw new S("LIMIT_EXCEEDED");let c=await Ai(e,n,a);for(let l of c){if(typeof l.name!="string"||l.name.length===0||l.name==="."||l.name===".."||/[\\/\u0000]/.test(l.name))throw new S("PATH_ESCAPED");let p=`${a}/${l.name}`;if(l.kind==="file"){if(r.push(p.slice(t.length+1)),r.length>gi)throw new S("LIMIT_EXCEEDED")}else if(l.kind==="directory")await s(p,d+1);else throw l.kind==="symlink"?new S("PATH_ESCAPED"):new S("READ_DENIED")}};return await s(t,0),r.sort(We)}function Od(e){return Z.includes(e)?262144:e==="ui/index.html"?an:e==="ui/state.json"?65536:e.startsWith("ui/assets/")?yd:fd}async function pr(e,n,t,i){if(e===void 0)return {packages:[],diagnostics:[],incomplete:false,reservedIds:Id};let o=bd(e.reservedIds),r=[],s=(y,I,h)=>Dd(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"||!yi.test(e.expectedIndexHash))return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a();let d;try{d=await cr(n,e.root,"bundle-index.json",ld);}catch(y){return r.push(s(Ge(y),"bundle-index.json")),a()}let c=createHash("sha256").update(d).digest("hex");if(c!==e.expectedIndexHash)return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a();let l=Md(d);if(l===void 0)return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a();if(!Sd(tt(l.packages),o))return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a([],false,c);if(!Oe(t,i))return r.push(s("LIMIT_EXCEEDED","bundle-index.json")),a(l.packages.map(y=>({indexEntry:y,failureCode:"LIMIT_EXCEEDED"})),true,c);let p;try{p=await Ai(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,c)}if(!Oe(t,i))return r.push(s("LIMIT_EXCEEDED","bundle-index.json")),a(l.packages.map(y=>({indexEntry:y,failureCode:"LIMIT_EXCEEDED"})),true,c);let u=p.find(y=>y.name==="bundle-index.json"&&y.kind==="file"),f=p.find(y=>y.name==="apps"&&y.kind==="directory"),g=y=>l.packages.map(I=>({indexEntry:I,failureCode:y}));if(!u)return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a(g("BUNDLE_INTEGRITY"),false,c);let E=p.filter(y=>y.name!=="bundle-index.json"&&y.name!=="apps");if(E.length>0){let y=E.some(I=>I.kind==="symlink")?"PATH_ESCAPED":"BUNDLE_INTEGRITY";return r.push(s(y,"bundle-index.json")),a(g("BUNDLE_INTEGRITY"),false,c)}if(p.some(y=>y.name==="apps"&&y.kind!=="directory"))return r.push(s("PATH_ESCAPED","apps")),a(g("PATH_ESCAPED"),false,c);let O=[];if(f)try{O=await Ai(n,e.root,"apps");}catch(y){return r.push(s(Ge(y),"apps")),a(g(Ge(y)),false,c)}if(!Oe(t,i)||O.length>Ii)return r.push(s("LIMIT_EXCEEDED","apps")),a(g("LIMIT_EXCEEDED"),true,c);let V=new Map(l.packages.map(y=>[y.packageDir.slice(5),y])),v=O.filter(y=>!V.has(y.name));for(let y of v)r.push(s(y.kind==="symlink"?"PATH_ESCAPED":"BUNDLE_INTEGRITY",`apps/${y.name}`));if(v.length>0){let y=v.some(I=>I.kind==="symlink")?"PATH_ESCAPED":"BUNDLE_INTEGRITY";return a(g(y),false,c)}let N=new Set,C=new Map,j=new Map;for(let y of l.packages){let I=C.get(y.appId)??[];I.push(y),C.set(y.appId,I);let h=`${y.definition.id}\0${String(y.definition.version)}`,_=j.get(h)??[];_.push(y),j.set(h,_);}for(let y of [...C.values(),...j.values()])if(y.length>1)for(let I of y)N.add(I);let T=[],D=d.byteLength,L=false;for(let y of l.packages){if(!Oe(t,i)){L=true,T.push({indexEntry:y,failureCode:"LIMIT_EXCEEDED"});continue}let I;try{let M=y.lineage[y.lineage.length-1];if(!M)throw new be("LINEAGE_INVALID","Definition lineage is missing");if(M.definition.id!==y.definition.id||M.version!==y.definition.version||M.hash!==y.definition.hash)throw new be("LINEAGE_STALE","Last lineage generation does not match bundle identity");I=Qt(y.lineage,{...M.definition,hash:M.hash}).entries;}catch(M){let J=M instanceof be?M.code:"LINEAGE_INVALID";r.push(s(J,y.packageDir)),T.push({indexEntry:y,failureCode:J});continue}let h=O.find(M=>M.name===y.packageDir.slice(5));if(!f||!h){T.push({indexEntry:y,failureCode:"BUNDLE_INTEGRITY"});continue}if(h.kind!=="directory"){T.push({indexEntry:y,failureCode:h.kind==="symlink"?"PATH_ESCAPED":"BUNDLE_INTEGRITY"});continue}let _;try{let M=await Ld(n,e.root,y.packageDir,t,i);if(!Oe(t,i)){L=!0,T.push({indexEntry:y,failureCode:"LIMIT_EXCEEDED"});continue}let J=y.files.map(K=>K.path);if(M.length!==J.length||M.some((K,Se)=>K!==J[Se])){T.push({indexEntry:y,failureCode:"BUNDLE_INTEGRITY"});continue}_=new Map;let pe;for(let K of y.files){if(!Oe(t,i)){pe="LIMIT_EXCEEDED",L=!0;break}if(D>=fi){pe="LIMIT_EXCEEDED";break}let Se;try{Se=await cr(n,e.root,`${y.packageDir}/${K.path}`,Od(K.path));}catch(As){pe=Ge(As);break}if(!Oe(t,i)){pe="LIMIT_EXCEEDED",L=!0;break}if(D+Se.byteLength>fi){D=fi,pe="LIMIT_EXCEEDED";break}if(D+=Se.byteLength,createHash("sha256").update(Se).digest("hex")!==K.sha256){pe="BUNDLE_INTEGRITY";break}_.set(K.path,Se);}if(pe!==void 0){T.push({indexEntry:y,failureCode:pe});continue}}catch(M){Oe(t,i)||(L=true),T.push({indexEntry:y,failureCode:Ge(M)});continue}T.push({indexEntry:y,lineage:I,files:_,...N.has(y)?{failureCode:"DUPLICATE_ID"}:{}});}return a(T,L,c)}var ld,Ii,gi,ud,fd,yd,fi,yi,Ad,Id,mi=B(()=>{m();ei();Ve();Bn();Xn();ui();ld=256*1024,Ii=64,gi=128,ud=Ii*gi,fd=2*1024*1024,yd=8*1024*1024,fi=32*1024*1024,yi=/^[0-9a-f]{64}$/,Ad=new TextDecoder("utf-8",{fatal:true}),Id=Object.freeze({appIds:Object.freeze([]),definitionIds:Object.freeze([])});});function wd(e){if(typeof e!="string"||!Ee.test(e))throw new TypeError("pluginId must be a safe UI plugin identifier");let n=`${hi}${e}`.length+7<=128?e:`hash_${createHash("sha256").update(e,"utf8").digest("hex")}`;return {read:`${hi}${n}_read`,action:`${hi}${n}_action`}}function ur(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;try{let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}catch{return false}}function Ud(e,n){return n.length===0||n==="."||n===".."||/[\\/\u0000]/.test(n)?e==="skills"?"skills":"apps":`${e==="skills"?"skills":"apps"}/${n}`}function kd(e){return e.length>0&&e!=="."&&e!==".."&&!/[\\/\u0000]/.test(e)}function Mn(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 Pr(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 xd(e){if(e instanceof Uint8Array)return new Uint8Array(e);if(e instanceof ArrayBuffer)return new Uint8Array(e.slice(0));if(Array.isArray(e)&&e.every(n=>Number.isInteger(n)&&n>=0&&n<=255))return Uint8Array.from(e);throw new TypeError("filesystem port returned an invalid byte array")}function Nr(e){return Cd.decode(e)}function vd(e){return JSON.parse(Nr(e))}function jd(e){if(e===void 0)return;let n=e.definitionId!==void 0&&e.definitionVersion!==void 0?`${e.definitionId}\0${String(e.definitionVersion)}`:void 0;return {pluginId:e.pluginId,...n===void 0?{}:{definitionKey:n}}}function ot(e,n,t,i,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 fr(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 ae(e){if(e instanceof S)return fr(e.code);if(e!==null&&typeof e=="object"&&"code"in e){let n=e.code;if(typeof n=="string")return fr(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 yr(e){return {reason:e.reason,...e.code==="MANIFEST_DUAL_MISMATCH"?{files:e.files}:{}}}function Ar(e){return e==="MANIFEST_DUAL_MISMATCH"?e:Dr(e)}function Fd(e){return Dr(e.code)}function Dr(e){switch(e){case "MANIFEST_INVALID":case "PRIMITIVE_UNKNOWN":case "PRIMITIVE_SET_UNSUPPORTED":case "SCHEMA_TYPE_UNSUPPORTED":case "TOKEN_INVALID":case "UNSAFE_VALUE":return "MANIFEST_INVALID";case "LIMIT_EXCEEDED":return "LIMIT_EXCEEDED";case "INITIAL_STATE_INVALID":return "INITIAL_STATE_INVALID";default:return br("UiPluginValidationError",e)}}function br(e,n){throw new Error(`Unmapped ${e} code: ${String(n)}`)}function Sr(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 br("McpAppContractError",e)}}function Re(e,n){let t=n();return Number.isFinite(t)&&Number.isFinite(e)&&t-e<=5e3}function Vd(e){return {pluginId:e.appId,definitionKey:`${e.definition.id}\0${String(e.definition.version)}`}}function Bd(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(ur(o)){let r=o.bin,s=typeof r=="string"?r:ur(r)?Object.values(r).find(a=>typeof a=="string"):void 0;for(let a of [s,o.main]){if(typeof a!="string")continue;let d=Hd(a);if(d&&n.has(d))return d}}}catch{}return [`${e.slice(e.lastIndexOf("/")+1)}.js`,"index.js","main.js"].find(o=>n.has(o))}function Hd(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 zd(){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 Ir(e){return Object.freeze(Array.from(e))}async function rt(e,n,t,i){if(n.pinnedFiles!==void 0){let a=n.pinnedFiles.get(t);if(a===void 0)throw new S("NOT_FOUND");if(a.byteLength>i)throw new S("LIMIT_EXCEEDED");return new Uint8Array(a)}let o=`${n.relativePath}/${t}`,r=n.scanContext,s=e.fingerprintVerifiedFile;if(r===void 0||!r.cacheable||typeof s!="function")return _r(e,n.root,o,i);try{let a=r.priorFingerprints.get(o)??await s.call(e,r.workspaceRoot,o,i);r.candidateRealPath=a.candidateRealPath;let d=await _r(e,n.root,o,i),c=await s.call(e,r.workspaceRoot,o,i);return r.candidateRealPath=c.candidateRealPath,Lr(a,c)&&c.size===BigInt(d.byteLength)&&!Or(c,r.scanStartedAtNs)?r.files.set(o,{relativePath:o,byteLimit:i,fingerprint:c}):r.cacheable=!1,d}catch(a){let d=Z.includes(t)&&ae(a)==="NOT_FOUND"&&r.directoryListings.some(l=>l.relativePath===n.relativePath&&!st(l.key,t)),c=t===H&&ae(a)==="NOT_FOUND"&&$d(r.directoryListings,n.relativePath);throw !d&&!c&&(r.cacheable=false),a}}function $d(e,n){let t=e.find(o=>o.relativePath===n);if(t===void 0)return false;if(!st(t.key,"dist"))return true;let i=e.find(o=>o.relativePath===`${n}/dist`);return i!==void 0&&!st(i.key,"tools.json")}function Mr(e,n){return JSON.stringify([e.realPath,n.source,n.relativePath])}async function Wd(e,n,t,i,o,r,s,a){let d=e.fingerprintVerifiedFile,c=Mr(t,i),l=o.candidates.get(c),p=i.relativePath,u;try{u=await hr(e,n,p);}catch(L){if(ae(L)!=="NOT_FOUND")throw L}let f=u===void 0?void 0:{relativePath:p,key:u};if(f!==void 0&&(i.source==="apps"||i.source==="skills")&&!Z.some(L=>st(f.key,L)))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:o,cacheKey:c,workspaceRoot:n,scanStartedAtNs:r,directoryListings:Object.freeze([f]),priorFingerprints:new Map,files:new Map,cacheable:true}}:{timeLimitReached:true};let g=async L=>{if(L==="")return f;let y=`${i.relativePath}${L}`;try{let I=await hr(e,n,y);return I===void 0?void 0:{relativePath:y,key:I}}catch(I){if(ae(I)==="NOT_FOUND")return;throw I}},E=await Promise.all(gr.map(g)),O=await Promise.all(Gd.map(g));if(!Re(s,a))return {timeLimitReached:true};let V=typeof d=="function"&&E.every(L=>L!==void 0),v=E.filter(L=>L!==void 0),N=[...v,...O.filter(L=>L!==void 0)],C=new Map,j=l!==void 0&&V,T;if(l!==void 0&&typeof d=="function"){let L=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 ae(I)==="NOT_FOUND"?{kind:"missing",file:y}:{kind:"error",file:y,error:I}}}));if(L.some(y=>y.kind==="time"))return {timeLimitReached:true};for(let y of L){if(y.kind==="error")throw y.error;if(y.kind==="missing"){j=false;continue}if(y.kind!=="fingerprint")continue;let{file:I,current:h}=y;C.set(I.relativePath,h),T??=h.candidateRealPath,(h.candidateRealPath!==l.candidateRealPath||!Lr(h,I.fingerprint)||Or(h,r))&&(j=false);}}let D=l!==void 0&&l.directoryListings.length===N.length&&l.directoryListings.every((L,y)=>L.relativePath===N[y]?.relativePath&&L.key===N[y]?.key);return l!==void 0&&V&&D&&j&&T===l.candidateRealPath?{memo:l}:!V||v.length!==gr.length?{}:{context:{state:o,cacheKey:c,workspaceRoot:n,scanStartedAtNs:r,directoryListings:Object.freeze(N),priorFingerprints:C,files:new Map,...T===void 0?{}:{candidateRealPath:T},cacheable:true}}}function st(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 hr(e,n,t){let i=Rr(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(Pr);if(!r.some(s=>s===null))return JSON.stringify(r.slice().sort((s,a)=>Mn(s.name,a.name)||Mn(s.kind,a.kind)).map(s=>[s.name,s.kind]))}function Lr(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>=-mr&&t<=mr}function _i(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 Jd(e,n,t){let i=createHash("sha256"),o=new TextEncoder().encode(te(e)),r=s=>{let a=new Uint8Array(8);new DataView(a.buffer).setBigUint64(0,BigInt(s)),i.update(a);};return r(o.byteLength),i.update(o),r(n.byteLength),i.update(n),r(t.byteLength),i.update(t),i.digest("hex")}function Kd(e,n){let t={...e.definition,sourceHash:n},i;try{i=le(t);}catch(r){throw r instanceof U&&r.code==="INPUT_INVALID"?new se("MANIFEST_INVALID","normalized definition is invalid"):r}let o={...t,hash:i};try{Ae(o);}catch{throw new se("MANIFEST_INVALID","normalized definition is invalid")}return o}function Xd(e){return e.actions.some(n=>n.backend.type==="core"&&n.backend.handler!=="state.set")}function Yd(e){if(typeof e.readVerifiedFile=="function")return e.readVerifiedFile;if(typeof e.readFileVerified=="function")return e.readFileVerified}function Rr(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 _r(e,n,t,i){let o=Yd(e);if(!o)throw new S("READ_DENIED");return xd(await o.call(e,n,t,i))}async function qd(e,n,t){let i=Rr(e);if(!i)throw new S("READ_DENIED");let o=await i.call(e,n,t);if(!Array.isArray(o))throw new S("READ_DENIED");return o.map(Pr).filter(r=>r!==null)}function Zd(e){let n=[];for(let t of [e.reserved,e.builtin])t&&n.push(t);return e.builtins&&"listMcpApps"in e.builtins?n.push(Er(e.builtins)):e.builtins&&n.push(e.builtins),e.builtinCatalog&&n.push(Er(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 Er(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 _e(e,n){e.diagnostic||(e.diagnostic=ot(n,e.source,e.relativePath,e.identity?.pluginId));}function Qd(e,n){let t=new Set,i=new Map;for(let r of e){let s=r.identity?.pluginId;if(s===void 0)continue;let a=i.get(s)??[];a.push(r),i.set(s,a);}for(let r of i.values()){if(r.length<2)continue;let s=r.filter(d=>d.provenance!==void 0);if(s.length>0){let d=r.find(c=>n.has(c));if(d){for(let c of s)t.add(c);for(let c of r)c!==d&&c.provenance===void 0&&_e(c,"RESERVED_ID");continue}for(let c of r)c.provenance===void 0&&_e(c,"RESERVED_ID");if(s.length>1)for(let c of s)_e(c,"DUPLICATE_ID");continue}let a=r.filter(d=>d.source==="apps");if(a.length>1){for(let d of a)_e(d,"DUPLICATE_ID");for(let d of r.filter(c=>c.source==="skills"))_e(d,"DUPLICATE_ID");}else for(let d of r.filter(c=>c.source==="skills"))_e(d,"DUPLICATE_ID");}let o=new Map;for(let r of e){if(r.diagnostic?.code==="RESERVED_ID"||t.has(r)||r.provenance===void 0&&!n.has(r)&&i.get(r.identity?.pluginId??"")?.some(d=>d.provenance!==void 0))continue;let s=r.identity?.definitionKey;if(s===void 0)continue;let a=o.get(s)??[];a.push(r),o.set(s,a);}for(let r of o.values())if(r.length>1)for(let s of r)_e(s,"DUPLICATE_ID");return t}function ep(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 Zd(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)){_e(l,"RESERVED_ID");continue}[p.toolNames.read,p.toolNames.action].filter(f=>f!==void 0).some(f=>r.has(f))&&_e(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{Yo(p),c.add(l);}catch(u){_e(l,u instanceof De?Sr(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))&&_e(l,"RESERVED_ID");}return c}function np(e){return [...e].sort((n,t)=>{let i=lr.indexOf(n.source)-lr.indexOf(t.source);return i!==0?i:Mn(n.relativePath,t.relativePath)})}function F(e,n,t){e.diagnostic=ot(n,e.source,e.relativePath,e.identity?.pluginId,t);}async function Tr(e,n,t){let i=$e(t,{mode:"local"});if(!i.ok&&i.parseFailure){F(n,Ar(i.rejection.code),yr(i.rejection));return}let o=jd(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,Ar(i.rejection.code),yr(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{oi(r.actions.map(M=>({actionId:M.actionId,inputSchema:M.inputSchema})));}catch(M){if(M instanceof De){F(n,Sr(M.code));return}throw M}let a;try{a=await rt(e,n,"ui/index.html",an);}catch(M){F(n,Ke(ae(M),"entry"));return}if(a.byteLength>an){F(n,"LIMIT_EXCEEDED");return}let d;try{d=Nr(a);}catch{F(n,"ENTRY_INVALID");return}if(a.byteLength===0||d.length===0){F(n,"ENTRY_INVALID");return}let c=createHash("sha256").update(a).digest("hex");if(r.entryHash!==void 0&&r.entryHash!==c){F(n,"ENTRY_INVALID");return}let l={},p,u;if(r.initialState!==void 0){try{p=await rt(e,n,"ui/state.json",65536);}catch(M){F(n,Ke(ae(M),"initial"));return}if(p.byteLength>65536){F(n,"LIMIT_EXCEEDED");return}try{let M=vd(p),J=r.dataPaths??[],pe=Ht(M,J);l=ye(pe,0,J),qe(l);}catch{F(n,"INITIAL_STATE_INVALID");return}if(u=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:c,...r.initialState===void 0?{}:{initialState:{path:"ui/state.json",hash:u}}},g=An(f),E=Jd(f,a,p??new Uint8Array),O;try{O=Kd(g,E);}catch(M){if(M instanceof se){F(n,Fd(M));return}throw M}let V;if(n.bundleLineage!==void 0){let M=n.bundleLineage[n.bundleLineage.length-1];if(!M){F(n,"LINEAGE_INVALID");return}let{legacy:J,...pe}=M.definition,{hash:K,...Se}=O;if(te(pe)!==te(Se)){F(n,"LINEAGE_STALE");return}if(J!==void 0&&(O={...O,legacy:J}),J!==void 0)try{O={...O,hash:le(O)},Ae(O);}catch{F(n,"LINEAGE_INVALID");return}V=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!==O.id||n.bundleIdentity.version!==O.version||n.bundleIdentity.definitionHash!==O.hash)){F(n,"LINEAGE_STALE");return}let v=wd(r.pluginId),N=r.actions.length===0?{read:v.read}:v,C=Je(g),j=Je(f),T=Je(O),D=Je({...g.handlers}),L=Ir(a),y=p===void 0?void 0:Ir(p),I=Object.freeze({...n.provenance===void 0?{}:{provenance:n.provenance},entry:Object.freeze({path:"ui/index.html",hash:c,bytes:L}),...y===void 0?{}:{initialState:Object.freeze({path:"ui/state.json",hash:u,bytes:y})}}),h={appId:r.pluginId,pluginId:r.pluginId,definitionId:r.definitionId,version:r.version,...i.releaseVersion===void 0?{}:{releaseVersion:i.releaseVersion},manifestFile:i.file,...i.mcpb===void 0?{}:{mcpb:Je(i.mcpb)},relativePath:n.relativePath,manifest:j,normalized:C,name:r.name,description:r.description,...r.icon===void 0?{}:{icon:r.icon},...r.tone===void 0?{}:{tone:r.tone},definition:T,handlers:D,resources:I,html:d,entryBytes:L,entryHash:c,initialState:Je(l),...y===void 0?{}:{initialStateBytes:y},...u===void 0?{}:{initialStateHash:u},sourceHash:E,toolNames:Object.freeze(N)},_=n.provenance===void 0?{...h,source:n.source}:{...h,provenance:n.provenance,lineage:V??[]};n.candidate=Object.freeze(_),Xd(r)&&F(n,"EXEC_DENIED");}async function wr(e,n){let t={};for(let i of Z)try{t[i]=await rt(e,n,i,262144);}catch(o){if(ae(o)==="NOT_FOUND")continue;return {files:t,failure:Ke(ae(o),"manifest")}}if(t[W]!==void 0)try{t[H]=await rt(e,n,H,262144);}catch(i){if(ae(i)!=="NOT_FOUND")return {files:t,failure:Ke(ae(i),"manifest")}}return {files:t}}function Ei(e){return Z.some(n=>e[n]!==void 0)}async function tp(e,n){let{files:t,failure:i}=await wr(e,n);if(i!==void 0){F(n,i);return}let o=t[W];return o!==void 0&&!Xt(o)&&(delete t[W],delete t[H]),Ei(t)?t:void 0}function ip(e,n,t,i=Rd,o=false,r=new Set){let s=np(e),a=Qd(s,r),d=Object.freeze(s.filter(u=>u.candidate!==void 0&&u.diagnostic===void 0&&!a.has(u)).map(u=>u.candidate)),c=Object.freeze(s.filter(u=>u.diagnostic!==void 0).map(u=>u.diagnostic)),l=o?Object.freeze({...t===void 0?{}:{indexHash:t},candidates:Object.freeze(s.filter(u=>u.source==="bundled"&&u.diagnostic===void 0&&t!==void 0&&u.candidate?.provenance?.indexHash===t).map(u=>u.candidate)),diagnostics:Object.freeze(c.filter(u=>u.source==="bundled").map(u=>Object.freeze({...u}))),reservedAppIds:Object.freeze([...i.appIds]),reservedDefinitionIds:Object.freeze([...i.definitionIds])}):void 0,p={apps:d,diagnostics:c,complete:n===void 0,...n===void 0?{}:{incompleteReason:n},...t===void 0?{}:{productBundleIndexHash:t},...l===void 0?{}:{productBundleSnapshotMetadata:l}};return Object.defineProperty(p,"candidates",{configurable:false,enumerable:false,get:()=>d}),Object.freeze(p)}function op(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 rp(e,n){if(op(e))return {fs:e,options:{}};let t=e??n??{};return {fs:t.filesystem??t.fileSystem??t.fs??or,options:t}}async function Cr(e,n,t){if(typeof e!="string"||e.length===0)throw new TypeError("workspaceRoot must be explicit");let{fs:i,options:o}=rp(n,t),r=o.clock??zd,s=r(),a=await pr(o.productBundle,i,s,r),d=r(),c=BigInt(Date.now())*1000000n,l=[],p=0,u,f=false,g,E;if(o.scanCache!==void 0&&typeof i.getRootIdentity=="function"&&typeof i.fingerprintVerifiedFile=="function")try{E=await i.getRootIdentity(e),g=Qo(o.scanCache,E),g.scanStartedAtNs=c;}catch(T){if(ae(T)!=="NOT_FOUND")throw T}let O=g!==void 0&&o.productBundle===void 0&&a.packages.length===0&&a.diagnostics.length===0,V=new Set,v=true;l.push(...a.diagnostics.map(T=>({source:T.source,root:o.productBundle?.root??e,name:"",relativePath:T.relativePath,diagnostic:T})));let N=a.reservedIds;a.incomplete&&(u="time_limit");for(let T of a.packages){if(!Re(d,r)){f=true,u="time_limit";break}let D=T.indexEntry,L=D.packageDir,y=T.files===void 0?void 0:Bd(L,T.files),I=a.indexHash===void 0?void 0:Mo(Object.freeze({kind:"bundled",launcher:D.launcher!==false,indexHash:a.indexHash,packageDir:L,appId:D.appId,definitionId:D.definition.id,version:D.definition.version,definitionHash:D.definition.hash,files:D.files}),y),h={source:"bundled",root:o.productBundle?.root??e,name:L.slice(5),relativePath:L,...I===void 0?{}:{provenance:I},...T.files===void 0?{}:{pinnedFiles:T.files},...T.lineage===void 0?{}:{bundleLineage:T.lineage},bundleIdentity:{appId:D.appId,definitionId:D.definition.id,version:D.definition.version,definitionHash:D.definition.hash},identity:Vd(D)};if(l.push(h),p+=1,T.failureCode!==void 0){F(h,T.failureCode);continue}if(T.files?.has(H)===true){F(h,"EXEC_DENIED",{reason:{path:"",rule:"bundled-tool-mode-unsupported",file:H}});continue}let _={};for(let M of Z){let J=T.files?.get(M);J!==void 0&&(_[M]=J);}if(!Ei(_)){F(h,"BUNDLE_INTEGRITY");continue}if(await Tr(i,h,_),!Re(d,r)){f=true,u="time_limit";break}}let C=[{source:"apps",directory:"apps"},{source:"skills",directory:"skills"}];e:for(let T of C){let{source:D,directory:L}=T,y;try{y=await qd(i,e,L);}catch(h){if(ae(h)==="NOT_FOUND")continue;O=false,v=false,l.push({source:D,root:e,name:"",relativePath:D,diagnostic:ot(Ke(ae(h),"manifest"),D,D)});continue}let I=y.filter(h=>h.kind==="directory"||h.kind==="symlink").filter(h=>kd(h.name)).map(h=>({source:D,root:e,name:h.name,relativePath:Ud(D,h.name)})).sort((h,_)=>Mn(h.relativePath,_.relativePath));for(let h of I){let _={...h};if(l.push(_),E!==void 0?V.add(Mr(E,_)):O=false,!Re(d,r)){f=true,u="time_limit";break e}let M;if(g!==void 0&&E!==void 0){try{let K=await Wd(i,e,E,_,g,c,d,r);if(K.timeLimitReached){f=!0,u="time_limit";break e}_.scanContext=K.context,M=K.memo;}catch(K){O=false,F(_,Ke(ae(K),"manifest"));continue}M===void 0&&(O=false);}if(M!==void 0){if(_.candidate=M.candidate,_.diagnostic=M.diagnostic,_.identity=M.identity,D==="skills"&&M.candidate===void 0&&M.diagnostic===void 0)continue;if(p>=64){F(_,"LIMIT_EXCEEDED");continue}if(h.relativePath.split("/").length-1>2){F(_,"LIMIT_EXCEEDED");continue}if(p+=1,!Re(d,r)){f=true,u="time_limit";break e}continue}let J;if(D==="skills"&&(J=await tp(i,_),J===void 0)){_.diagnostic===void 0&&_i(_);continue}if(p>=64){F(_,"LIMIT_EXCEEDED");continue}if(h.relativePath.split("/").length-1>2){F(_,"LIMIT_EXCEEDED");continue}if(!Re(d,r)){f=true,u="time_limit";break e}if(p+=1,J===void 0){let K=await wr(i,_);if(K.failure!==void 0||!Ei(K.files)){F(_,K.failure??Ke("NOT_FOUND","manifest")),_i(_);continue}J=K.files;}if(await Tr(i,_,J),_i(_),!Re(d,r)){f=true,u="time_limit";break e}}}if(g!==void 0&&E!==void 0){let T=[...V].sort(Mn),D=g.lastCandidateKeys,L=D!==void 0&&D.length===T.length&&D.every((I,h)=>I===T[h]);if(O=O&&L,v&&!f&&u===void 0)for(let I of g.candidates.keys())try{JSON.parse(I)[0]===E.realPath&&!V.has(I)&&g.candidates.delete(I);}catch{g.candidates.delete(I);}let y=[...g.candidates.keys()].filter(I=>{try{return JSON.parse(I)[0]===E.realPath}catch{return false}});O=O&&y.length===V.size&&y.every(I=>V.has(I))&&!f&&u===void 0,g.lastCandidateScanUnchanged=O,v&&!f&&u===void 0&&(g.lastCandidateKeys=Object.freeze(T));}f&&l.push({source:"apps",root:e,name:"",relativePath:"apps",diagnostic:ot("DISCOVERY_TIME_LIMIT","apps","apps")});let j=ep(l,o,N);return ip(l,u,a.indexHash,N,o.productBundle!==void 0,j)}var Rd,hi,lr,Cd,gr,Gd,mr,Ur=B(()=>{m();Be();Rn();Me();Yt();Ve();Xn();qo();zn();er();ui();$n();mi();mi();Rd=tt([]),hi="crewx_local_app_";lr=["bundled","apps","skills"],Cd=new TextDecoder("utf-8",{fatal:true});gr=["","/ui"],Gd=["/dist"],mr=2000000000n;});m();Yt();m();wt();m();var Ao="SKILL.md",Ec=/^---\s*\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;function Io(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function Tc(e){return e.isDirectory()||e.isSymbolicLink()}function Eo(e){try{return existsSync(e)&&statSync(e).isDirectory()}catch{return false}}function qt(e){let n;try{n=readFileSync(e,"utf8");}catch{return {frontmatter:{},readable:false,valid:false,hasFrontmatter:false}}let t=n.match(Ec);if(!t)return {frontmatter:{},readable:true,valid:true,hasFrontmatter:false};try{let i=load(t[1]??"");if(!Io(i))return {frontmatter:{},readable:!0,valid:!1,hasFrontmatter:!0};let o=Io(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 Pc(e){return [join(e,Ao),join(e,"skill",Ao)]}function go(e,n){if(!Eo(e))return null;for(let t of Pc(e)){if(!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 mo(e){try{return readdirSync(e,{withFileTypes:!0}).filter(Tc)}catch{return []}}function ho(e,n,t){!e||n.has(e.name)||(n.add(e.name),t.push(e));}function To(e){let n=[],t=new Set;for(let i of e)if(Eo(i))for(let o of mo(i)){if(o.name.startsWith("@")){let r=join(i,o.name);for(let s of mo(r))ho(go(join(r,s.name),s.name),t,n);continue}ho(go(join(i,o.name),o.name),t,n);}return n.sort((i,o)=>i.name.localeCompare(o.name))}m();Bn();var Nc=/^[A-Za-z0-9_$.[\]"-]{0,200}$/,Dc=/^[a-z][a-z0-9-]{0,63}$/,bc="<unknown>";function Sc(e){return typeof e=="string"&&(Z.includes(e)||e===H)}function Po(e){if(typeof e!="object"||e===null)return;let{file:n,path:t,rule:i}=e;if(!(typeof i!="string"||!Dc.test(i)))return {...Sc(n)?{file:n}:{},path:typeof t=="string"&&Nc.test(t)?t:bc,rule:i}}function No(e){if(!Array.isArray(e))return;let n=Z.filter(t=>e.includes(t));return n.length>0?n:void 0}Ur();var ap=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/;function dt(e){let n="screenHash"in e?e.screenHash:void 0,i=("skillHash"in e?e.skillHash:void 0)??(e.relativePath!==void 0&&e.fileBytes!==void 0?cp(e.relativePath,e.fileBytes):void 0);if(n!==void 0&&i!==void 0){let o=JSON.stringify({screenHash:n,skillHash:i});return 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 cp(e,n){let t=new TextEncoder().encode(pt(e)),i=dp(n),o=new Uint8Array(t.byteLength+1+i.byteLength);return o.set(t,0),o[t.byteLength]=0,o.set(i,t.byteLength+1),createHash("sha256").update(o).digest("hex")}function dp(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 pt(e){if(typeof e!="string"||e.length===0||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 at(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 vr(e,n){let t=relative(e,n).split(sep).join("/");return !t||t===".."||t.startsWith("../")||isAbsolute(t)?null:pt(t)}function pp(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 jr(e){return Object.freeze({packageRoot:e})}function lp(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 Fr(e){return {capabilities:Object.freeze([...e]),origin:"local",ownership:"unknown",shareability:"unknown",sharingAvailability:"unavailable"}}function up(e,n){let t=e.candidate,i=t.provenance!==void 0,o=n&&!i?["screen","skill"]:["screen"],r=lp(t),s=dt(n?{screenHash:r.hash,skillHash:n.skillHash}:{screenHash:r.hash}),a=t.description||n?.skill.description||"",d=t.releaseVersion??String(t.version),c={appId:t.pluginId,name:t.name,description:a,version:d,...Fr(o),definition:r,...n===void 0||i?{}:{skillName:n.skill.name},...i?{provenance:t.provenance}:{localDefinitionRef:jr(e.packageRoot)},definitionHash:s,...t.manifest.csp===void 0?{}:{connectDomains:Object.freeze([...t.manifest.csp.connectDomains])}};return {...i?{}:{packageRoot:e.packageRoot},source:i?"bundled":t.source,appId:c.appId,capabilities:o,summary:Object.freeze(c)}}function fp(e){let n=yp(e.skill.name),t={appId:n,name:e.skill.name,description:e.skill.description??"",...e.skill.version===void 0?{}:{version:e.skill.version},...Fr(["skill"]),skillName:e.skill.name,localDefinitionRef:jr(e.packageRoot),definitionHash:dt({skillHash:e.skillHash})};return {packageRoot:e.packageRoot,source:e.source,appId:n,capabilities:["skill"],summary:Object.freeze(t)}}function yp(e){return `skill.${e.replace(/^@/,"").replace(/\//g,".").replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,122)||"unnamed"}`}function ee(e,n,t,i,o){let r=Po(o?.reason),s=No(o?.files);return Object.freeze({code:e,source:n,relativePath:Ap(t),...i===void 0?{}:{appId:i},...r===void 0?{}:{reason:r},...s===void 0?{}:{files:s}})}function Ap(e){if(typeof e!="string"||e.length===0||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 Vr(e){return ee(e.code,e.source,e.relativePath,e.pluginId,e)}function Ip(e,n){let t=vr(e,n.dir);if(!t)return {diagnostic:ee("PATH_ESCAPED","node_modules","node_modules")};let i=pp(t);if(!i)return {diagnostic:ee("PATH_ESCAPED","node_modules",t)};let o=qt(n.skillMdPath);if(!o.readable)return {diagnostic:ee("SKILL_READ_FAILED",i,t)};if(!o.valid)return {diagnostic:ee("SKILL_INVALID",i,t)};let r=gp(n.dir,n.skillMdPath);if(!r)return {diagnostic:ee("PATH_ESCAPED",i,t)};try{let s=new Uint8Array(readFileSync(n.skillMdPath));return {skill:n,packageRoot:t,relativeSkillPath:r,skillHash:dt({relativePath:r,fileBytes:s}),source:i}}catch{return {diagnostic:ee("SKILL_READ_FAILED",i,t)}}}function gp(e,n){let t=relative(e,n).split(sep).join("/");try{return pt(t)}catch{return null}}function mp(e){if(!ap.test(e.appId))return {diagnostic:ee("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??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 hp(e){return e.builtinCatalog}function _p(e){let n=e.packageRoot??e.relativePath??e.packageRootPath;if(n===void 0)return null;try{return pt(n)}catch{return null}}function Ep(e){let n=e.marketplaceContentId;return typeof n=="string"&&n.length>0?n:void 0}function Tp(e,n,t){let i=n.installed??[],o=new Map;for(let s of i){let a=_p(s);if(!a){t.push(ee("INSTALLED_IDENTITY_MISMATCH","installed","installed"));continue}let d=o.get(a);if(d&&JSON.stringify(d)!==JSON.stringify(s)){t.push(ee("INSTALLED_IDENTITY_MISMATCH","installed",a));continue}o.set(a,s);}let r=new Map;for(let s of e)s.packageRoot!==void 0&&r.set(s.packageRoot,s);for(let[s,a]of o){let d=r.get(s);if(!d){t.push(ee("INSTALLED_MISSING","installed",s,a.appId));continue}let c=Ep(a);if(!c){t.push(ee("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(ee("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 Pp(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(ee("RESERVED_ID",a.source,ct(a),a.appId)));continue}}if(r!==void 0){let s=o.filter(a=>a.source===r);for(let a of o.filter(d=>d.source!==r))i.add(a),n.push(ee("RESERVED_ID",a.source,ct(a),a.appId));if(s.length>1)for(let a of s)i.add(a),n.push(ee("DUPLICATE_ID",a.source,ct(a),a.appId));continue}for(let s of o)i.add(s),n.push(ee("DUPLICATE_ID",s.source,ct(s),s.appId));}return e.filter(o=>!i.has(o))}function ct(e){return e.packageRoot??e.summary.provenance?.packageDir??`builtin/${e.appId}`}function Np(e,n){return e.filter(t=>!(t.code==="MANIFEST_MISSING"&&n.has(t.relativePath))).map(Vr)}function Dp(e){return e.filesystem}function bp(e,n){let t=Dp(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 Br(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=hp(n),i=await Cr(e,bp(n,t)),o=n.registeredProductBundle??i.productBundleSnapshotMetadata,r=[join(e,"skills"),join(e,"node_modules"),join(e,"apps")],s=[],a=[],d=[],c=new Set;for(let I of r)for(let h of To([I])){let _=vr(e,h.dir);(_===null||!c.has(_))&&(d.push(h),_!==null&&c.add(_));}for(let I of d){let h=Ip(e,I);"diagnostic"in h?s.push(h.diagnostic):a.push(h);}let l=new Map,p=n.registeredProductBundle?.indexHash,u=(n.registeredProductBundle?.candidates??[]).filter(I=>p!==void 0&&I.provenance?.indexHash===p),f=[...new Set([...i.apps??i.candidates??[],...i.productBundleSnapshotMetadata?.candidates??[]]),...u],g=new Set(u),E=new Set(p===void 0?[]:(t?.listMcpApps()??[]).filter(I=>I.provenance?.indexHash===p).map(I=>I.appId));for(let I of f){if(g.has(I)&&I.provenance?.indexHash===p&&E.has(I.appId))continue;let h=I.provenance===void 0?`workspace\0${I.relativePath}`:`bundled\0${I.provenance.indexHash}\0${I.provenance.packageDir}`;l.set(h,{candidate:I,packageRoot:I.relativePath});}let O=new Map(a.map(I=>[I.packageRoot,I])),V=[];for(let I of l.values()){let h=I.candidate.provenance===void 0?O.get(I.packageRoot):void 0,_=up(I,h);V.push({..._.packageRoot===void 0?{}:{packageRoot:_.packageRoot},source:_.source,appId:_.appId,summary:_.summary});}let v=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)),C=new Set(o?.reservedAppIds??[]);for(let I of a){let h=fp(I);if(!(v.has(I.packageRoot)||N.has(I.packageRoot))){if(C.has(h.appId)){s.push(ee("RESERVED_ID",I.source,I.packageRoot,h.appId));continue}V.push({packageRoot:h.packageRoot,source:h.source,appId:h.appId,summary:h.summary});}}let j=[...Np(i.diagnostics,new Set(a.map(I=>I.packageRoot))),...s,...n.registeredProductBundle?.diagnostics.filter(I=>I.source==="bundled").map(Vr)??[]],T=[];if(t)for(let I of t.listMcpApps()){let h=mp(I);"diagnostic"in h?j.push(h.diagnostic):T.push(h);}let D=Pp([...V,...T],j);Tp(D,n,j);let L=D.map(I=>I.summary).sort((I,h)=>at(I.appId,h.appId)),y=[...j].sort((I,h)=>at(I.relativePath,h.relativePath)||at(I.code,h.code)||at(I.appId??"",h.appId??""));return Object.freeze({items:Object.freeze(L),diagnostics:Object.freeze(y)})}m();m();m();function Sp(e){let n=o=>o.replace(/[.+^${}()|[\]\\]/g,"\\$&"),i=e.split("/").map(o=>o==="**"?".*":o.split("*").map(n).join("[^/]*"));return new RegExp(`^${i.join("\\/")}$`)}function pn(e,n){try{return Sp(n).test(e)}catch{return false}}function lt(e,...n){let t=e.split("/");if(t.length<n.length)return false;let i=t.length-n.length;return n.every((o,r)=>pn(t[i+r],o))}function Mp(e,n){return e.split("/").some(t=>pn(t,n))}var Hr=[{label:".env*",test:e=>pn(e,".env*")},{label:".git/",test:(e,n,t)=>t&&e===".git"},{label:"memory/",test:(e,n,t)=>t&&e==="memory"},{label:"*.key",test:e=>pn(e,"*.key")},{label:"*.pem",test:e=>pn(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&<(n,".crewx","threads")},{label:".crewx/crewx.db",test:(e,n,t)=>!t&<(n,".crewx","crewx.db")},{label:".crewx/*.log",test:(e,n,t)=>!t&<(n,".crewx","*.log")},{label:".crewx/publish/",test:(e,n,t)=>t&<(n,".crewx","publish")},{label:".crewx/",test:(e,n)=>Mp(n,".crewx")}];function ut(e,n,t){for(let i of Hr)if(i.test(e,n,t))return i.label;return null}function Di(e){let n=[],t=[];function i(o,r,s){let a;try{a=ne.readdirSync(o,{withFileTypes:!0});}catch{return}a.sort((d,c)=>d.name.localeCompare(c.name));for(let d of a){let c=r?`${r}/${d.name}`:d.name,l=ce.join(o,d.name);if(d.isSymbolicLink()){let p;try{p=ne.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??ut(d.name,c,false);u?t.push({path:c,rule:u}):t.push({path:c,rule:"symlink"});continue}if(d.isDirectory()){let p=s??ut(d.name,c,true);i(l,c,p);continue}if(d.isFile()){let p=s??ut(d.name,c,false);p?t.push({path:c,rule:p}):n.push(c);}}}return i(e,"",null),n.sort(),t.sort((o,r)=>o.path<r.path?-1:o.path>r.path?1:0),{included:n,excluded:t}}m();var Lp=[{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 Op(e){return e.includes(0)}function bi(e,n,t){let i=[];for(let o of n){let r=ce.join(e,o),s;try{let d=t?.get(o);s=d===void 0?ne.readFileSync(r):Buffer.from(d);}catch{continue}if(Op(s))continue;s.toString("utf8").split(/\r\n|\r|\n/).forEach((d,c)=>{for(let{rule:l,regex:p}of Lp)p.test(d)&&i.push({path:o,line:c+1,rule:l});});}return i}m();m();var we=class extends Error{constructor(t,i){super(`publish: [${t}]${i?` ${i}`:""}`);this.code=t;}code;name="PublishError"};function P(e,n){return new we(e,n)}var Wr=/^[a-z0-9-]+$/,Rp=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/,wp=/^[A-Za-z_][A-Za-z0-9_]*$/;function Cp(e){let n=ce.join(e,"crewx.yaml");if(!ne.existsSync(n))return {};let t;try{t=Jr.load(ne.readFileSync(n,"utf8"));}catch{return {}}if(!t||typeof t!="object")return {};let i=t.metadata;if(!i||typeof i!="object")return {};let o=i;return {name:typeof o.name=="string"?o.name:void 0,version:typeof o.version=="string"?o.version:void 0,description:typeof o.description=="string"?o.description:void 0,requiredEnv:o.requiredEnv,crewxMinVersion:typeof o.crewxMinVersion=="string"?o.crewxMinVersion:void 0}}function Up(e){return Si.createHash("sha256").update(e).digest("hex")}function Kr(e){let n;try{n=ne.lstatSync(e);}catch{throw P("PACKAGE_FILE_INVALID",`file is not readable: ${ce.basename(e)}`)}if(n.isSymbolicLink())throw P("PACKAGE_SYMLINK","symlink content is not publishable");if(!n.isFile())throw P("PACKAGE_FILE_INVALID","only regular files are publishable");return Si.createHash("sha256").update(new Uint8Array(ne.readFileSync(e))).digest("hex")}function kp(e,n){let t=new TextEncoder().encode(e),i=new TextEncoder().encode(n),o=Math.min(t.byteLength,i.byteLength);for(let r=0;r<o;r+=1){let s=t[r]-i[r];if(s!==0)return s}return t.byteLength-i.byteLength}function Xr(e){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||ce.posix.isAbsolute(e)||e.split("/").some(n=>n===".."||n.length===0))throw P("PACKAGE_PATH_TRAVERSAL","manifest file path must be a non-empty POSIX relative path")}function xp(e){if(!/^(?:apps|skills)\/[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(e))throw P("APP_PACKAGE_ROOT_INVALID","packageRoot must be apps/<safe-id> or skills/<safe-id>")}function Yr(e){if(!Rp.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=Cp(e),o=i.name??ce.basename(e);if(!Wr.test(o))throw new Error(`publish: invalid name "${o}" \u2014 must match ${Wr} (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");Yr(r);let s=Array.isArray(i.requiredEnv)?i.requiredEnv:[],a=[];for(let l of s){if(typeof l!="string"||!wp.test(l))throw new Error(`publish: requiredEnv must contain names only (no values), got "${String(l)}"`);a.push(l);}let d=n.map(l=>(Xr(l),{path:l,sha256:Kr(ce.join(e,l))})).sort((l,p)=>l.path<p.path?-1:l.path>p.path?1:0),c={name:o,version:r,type:"template",description:i.description??"",files:d,requiredEnv:a};return i.crewxMinVersion&&(c.crewxMinVersion=i.crewxMinVersion),c}function vp(e){let n=e.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"");if(!n)throw P("APP_PACKAGE_ROOT_INVALID","appId cannot produce a marketplace name");return n}function Zr(e,n){if(xp(n.packageRoot),!n.version)throw new Error("publish: version is required for App publishing \u2014 pass opts.version");if(Yr(n.version),typeof n.description!="string")throw new Error("publish: App description must be a string");let t=[...new Set(n.capabilities)].sort();if(t.length===0||t.some(s=>s!=="screen"&&s!=="skill"))throw new Error("publish: App capabilities must contain screen or skill");let i=`${n.packageRoot}/`;if(t.includes("screen")){if(typeof n.definitionId!="string"||n.definitionId.length===0)throw P("APP_UI_MANIFEST_INVALID","screen App manifests require definitionId");let s=n.includedFiles.includes(`${i}manifest.json`),a=n.includedFiles.includes(`${i}ui-plugin.json`);if(!s&&!a)throw P("APP_UI_MANIFEST_INVALID","screen App is missing manifest.json or ui-plugin.json");if(s&&!a)throw P("APP_UI_MANIFEST_INVALID","a manifest.json App must also ship a generated ui-plugin.json");if(!n.includedFiles.includes(`${i}ui/index.html`))throw P("APP_UI_MANIFEST_INVALID","screen App is missing ui/index.html")}if(t.includes("skill")&&!n.includedFiles.includes(`${i}SKILL.md`))throw P("APP_SKILL_MISSING","skill capability requires package-root SKILL.md");let o=new Set,r=n.includedFiles.map(s=>{if(Xr(s),!s.startsWith(i))throw P("PACKAGE_PATH_TRAVERSAL","App manifest file is outside packageRoot");let a=n.generatedFiles?.get(s);return a!==void 0&&o.add(s),{path:s,sha256:a===void 0?Kr(ce.join(e,s)):Up(a),...a===void 0?{}:{generated:true}}}).sort((s,a)=>kp(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:vp(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 Qr(e){return Si.createHash("sha256").update(e).digest("hex")}function os(e,n){if(typeof n!="string"||n.length===0||n.includes("\\")||n.includes("\0")||ce.posix.isAbsolute(n)||n.split("/").some(o=>o===".."||o.length===0))throw P("PACKAGE_PATH_TRAVERSAL","archive paths must be non-empty POSIX relative paths");let t=ce.resolve(e),i=ce.resolve(t,...n.split("/"));if(i!==t&&!i.startsWith(`${t}${ce.sep}`))throw P("PACKAGE_PATH_TRAVERSAL","archive path escaped its root");return i}function es(e,n){let t=os(e,n),i;try{i=ne.lstatSync(t);}catch{throw P("PACKAGE_FILE_INVALID","manifest file is missing")}if(i.isSymbolicLink())throw P("PACKAGE_SYMLINK","symlink content is not publishable");if(!i.isFile())throw P("PACKAGE_FILE_INVALID","only regular files are publishable");return new Uint8Array(ne.readFileSync(t))}async function rs(e,n,t={}){let i=ce.join(e,".crewx","publish");ne.mkdirSync(i,{recursive:true});let o=ce.join(i,`${n.name}-${n.version}.tgz`),r=ce.join(i,`.${n.name}-${n.version}.${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}.tmp.tgz`),s=ne.mkdtempSync(ce.join(ns.tmpdir(),"crewx-publish-"));try{let a=new Set,d=[];for(let c of n.files){if(a.has(c.path))throw P("PACKAGE_PATH_TRAVERSAL","manifest contains duplicate file paths");a.add(c.path);let l=t.generatedFiles?.get(c.path);if(c.generated===!0&&l===void 0)throw P("PACKAGE_GENERATED_FILE_MISSING","generated manifest file bytes are missing");if(t.sourceFileHashes?.has(c.path)){let f=es(e,c.path);if(t.sourceFileHashes.get(c.path)!==Qr(f))throw P("PACKAGE_STAGED_BYTES_MISMATCH","workspace source changed before staging")}let p=l??es(e,c.path);if(Qr(p)!==c.sha256)throw P("PACKAGE_STAGED_BYTES_MISMATCH",`staged bytes differ for ${c.path}`);let u=os(s,c.path);ne.mkdirSync(ce.dirname(u),{recursive:!0}),ne.writeFileSync(u,new Uint8Array(p)),d.push(c.path);}ne.writeFileSync(ce.join(s,"manifest.json"),JSON.stringify(n,null,2)),await is.create({gzip:!0,file:r,cwd:s,portable:!0,noMtime:!0},["manifest.json",...d]),ne.renameSync(r,o);}finally{try{ne.rmSync(r,{force:!0});}catch{}ne.rmSync(s,{recursive:true,force:true});}return o}m();m();var ln="/api/v1";var Vp=201,Bp=200,Hp=409,Mi=401,ss={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 zp(){return process.env.WI013_FAKE_UPLOAD==="1"}function $p(e){let n=gunzipSync(new Uint8Array(e)),t=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 Gp(e){return e.replace(/\/+$/,"")}async function Ln(e){try{return await e.json()}catch{return null}}function as(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 Wp(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 Jp(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 cs(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(ss,r))continue;let s=r,a=s==="APP_NAME_CONFLICT"?`marketplace name is already in use: ${n}`:void 0;return P(ss[s],a)}}async function Kp(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=Gp(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}${ln}/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 Ln(a),c=Wp(d),l=Jp(d),p=r&&l!==void 0?l:i,u;if(a.status===Vp)u="created";else if(r&&a.status===Bp){if(c===void 0)throw P("PUBLISH_CONTENT_ID_MISSING","App republish did not return an opaque contentId");u="existing";}else if(a.status===Hp){if(r)throw cs(d,i)??P("APP_NAME_CONFLICT",`marketplace name is already in use: ${i}`);u="existing";}else throw a.status===Mi?new Error("publish: [E_AUTH_EXPIRED] Authentication is expired or missing \u2014 please log in again (HTTP 401)"):new Error(`publish: [E_HTTP] Submit request failed \u2014 HTTP ${a.status}`);let f="not-needed",g=null;if(u==="existing"&&!r){let D;try{D=await fetch(`${n}${ln}/publisher/items`,{method:"GET",headers:{Authorization:`Bearer ${e.accessToken}`}});}catch{throw new Error("publish: [E_NETWORK] Publisher items request failed (network)")}let L=await Ln(D);if(D.status!==200)throw new Error(`publish: [E_HTTP] Publisher items request failed \u2014 HTTP ${D.status}`);let I=as(L,"publisher items",D.status)?.items;if(!Array.isArray(I))throw new Error(`publish: [E_MALFORMED] Publisher items response is malformed (expected data.items[]) \u2014 HTTP ${D.status}`);let h=I.find(_=>!_||typeof _!="object"?false:_.slug===i);if(!h||typeof h.version!="string")throw new Error(`publish: [E_MALFORMED] Publisher items response does not contain slug "${i}" \u2014 HTTP ${D.status}`);if(g=h.version,g!==e.manifest.version){let _;try{_=await fetch(`${n}${ln}/publisher/items/${encodeURIComponent(i)}`,{method:"PUT",headers:{Authorization:`Bearer ${e.accessToken}`,"Content-Type":"application/json"},body:JSON.stringify({version:e.manifest.version})});}catch{throw new Error("publish: [E_NETWORK] Version update request failed (network)")}if(!_.ok)throw await Ln(_),_.status===Mi?new Error(`publish: [E_AUTH_EXPIRED] Authentication is expired or missing \u2014 please log in again (HTTP ${_.status})`):_.status===403?new Error(`publish: [E_FORBIDDEN] Version update is forbidden; only the item owner can update an existing item (HTTP ${_.status})`):new Error(`publish: [E_HTTP] Version update failed \u2014 HTTP ${_.status}`);f="applied";}}let E=ne.readFileSync(e.tgzPath),O=zp()?$p(E):E,V=new FormData;V.set("archive",new Blob([new Uint8Array(O)],{type:"application/gzip"}),`${p}-${e.manifest.version}.tgz`);let v=r&&c!==void 0?c:i,N;try{N=await fetch(`${n}${ln}/publisher/items/${encodeURIComponent(v)}/upload`,{method:"POST",headers:{Authorization:`Bearer ${e.accessToken}`},body:V});}catch{throw new Error("publish: [E_NETWORK] Upload request failed (network)")}if(N.status===Mi)throw new Error("publish: [E_AUTH_EXPIRED] Authentication is expired or missing \u2014 please log in again (HTTP 401)");if(!N.ok){let D=await Ln(N);if(r){let L=cs(D,p);if(L)throw L}throw new Error(`publish: [E_HTTP] Upload request failed \u2014 HTTP ${N.status}`)}let C=await Ln(N),j=as(C,"upload",N.status),T=typeof j.contentId=="string"&&j.contentId.length>0?j.contentId:c;if(r&&T===void 0)throw P("PUBLISH_CONTENT_ID_MISSING","App upload did not return an opaque contentId");return {slug:p,version:e.manifest.version,...T===void 0?{}:{contentId:T},artifactChecksum:j.artifactChecksum,artifactSizeBytes:j.artifactSizeBytes,submitOutcome:u,versionUpdate:f,serverVersionBefore:g}}var Xp=1e4,Yp=100*1024*1024;function Li(e){return Si.createHash("sha256").update(e).digest("hex")}function qp(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function On(e,n){if(!n||n.includes("\\")||n.includes("\0")||ce.posix.isAbsolute(n)||n.split("/").some(r=>r===".."||r.length===0))throw P("PACKAGE_PATH_TRAVERSAL","workspace file path is not a safe relative path");let t=ce.resolve(e,...n.split("/")),i=ce.resolve(e);if(t!==i&&!t.startsWith(`${i}${ce.sep}`))throw P("PACKAGE_PATH_TRAVERSAL","workspace file path escaped the workspace root");let o;try{o=ne.lstatSync(t);}catch{throw P("PACKAGE_FILE_INVALID",`workspace file is missing: ${n}`)}if(o.isSymbolicLink())throw P("PACKAGE_SYMLINK",`symlink is not publishable: ${n}`);if(!o.isFile())throw P("PACKAGE_FILE_INVALID",`not a regular file: ${n}`);return new Uint8Array(ne.readFileSync(t))}function yt(e,n){return e===n||e.startsWith(`${n}/`)}function Zp(e,n){return e.path<n.path?-1:e.path>n.path?1:e.rule.localeCompare(n.rule)}function ps(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 us(e,n,t,i){let o=ps(t.maxFileCount??t.maxFiles,Xp,"max file count"),r=ps(t.maxTotalBytes??t.maxBytes,Yp,"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 d=i?.get(a);if(d!==void 0?s+=d.byteLength:s+=On(e,a).byteLength,s>r)throw new we("PACKAGE_SIZE_LIMIT",`package exceeds byte limit (${r})`)}}function Qp(e){return e.appId!==void 0||e.expectedDefinitionHash!==void 0}function el(e){let n=e.appId!==void 0,t=e.expectedDefinitionHash!==void 0;if(!n&&t)throw P("APP_ID_REQUIRED","appId is required with expectedDefinitionHash");if(n&&!t)throw P("APP_DEFINITION_HASH_REQUIRED","expectedDefinitionHash is required with appId");if(!n||!t)throw P("APP_ID_REQUIRED")}function nl(e,n){let t=e.filter(i=>i.appId===n);if(t.length===0)throw P("APP_NOT_FOUND",`no publishable App matches ${n}`);if(t.length!==1)throw P("APP_AMBIGUOUS",`more than one App matches ${n}`);return t[0]}function tl(e){let n=e.localDefinitionRef?.packageRoot;if(!n||!/^(?:apps|skills)\/[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(n))throw P("APP_PACKAGE_ROOT_INVALID","selected App is not rooted in apps/<safe-id> or skills/<safe-id>");return n}function il(e,n){let t=[];for(let i of e.excluded)t.push(yt(i.path,n)?i:{path:i.path,rule:"out-of-app-scope"});for(let i of e.included)yt(i,n)||t.push({path:i,rule:"out-of-app-scope"});return t.sort(Zp)}function Oi(e){let{path:n,rule:t}=e.reason;return `${e.code} at ${n===""?"<file>":n} (${t})`+(e.files.length>0?` [${e.files.join(", ")}]`:"")}function ol(e,n,t){let i=$e({[de]:t},{mode:"published"});if(!i.ok)throw P("APP_UI_MANIFEST_INVALID",`generated ${de} does not read: ${Oi(i.rejection)}`);if(rn(i.manifest)!==rn(n))throw P("APP_UI_MANIFEST_INVALID",`generated ${de} normalizes to a different definition hash than the source`);let o=e[W];if(o===void 0)return;let r=e[H],s=$e({[W]:o,[de]:t,...r===void 0?{}:{[H]:r}},{mode:"local"});if(!s.ok)throw P("APP_UI_MANIFEST_INVALID",Oi(s.rejection))}function rl(e,n,t,i){let o={};for(let f of Z){let g=`${t}/${f}`;i.includes(g)&&(o[f]=On(e,g));}let r=`${t}/${H}`;if(o[W]!==void 0&&i.includes(r)&&(o[H]=On(e,r)),Object.keys(o).length===0)throw P("APP_UI_MANIFEST_INVALID","selected screen App has no package manifest.json or ui-plugin.json");let s=$e(o,{mode:"local"});if(!s.ok)throw P("APP_UI_MANIFEST_INVALID",Oi(s.rejection));if(s.manifest.pluginId!==n.appId)throw P("APP_DEFINITION_CONFLICT",`${s.file} identity no longer matches the selected App`);let a=o[de],d=a===void 0?void 0:Li(a),c=`${t}/ui/index.html`;if(!i.includes(c))throw P("APP_UI_MANIFEST_INVALID","screen entry is outside package scope");let l=Li(On(e,c)),p=JSON.parse(JSON.stringify(s.v2Input));if(p.entryHash=l,Object.prototype.hasOwnProperty.call(p,"initialState")){let f=p.initialState;if(!qp(f)||f.path!=="ui/state.json")throw P("APP_INITIAL_STATE_OUT_OF_SCOPE","initialState must reference ui/state.json inside the package");let g=`${t}/ui/state.json`;if(!i.includes(g))throw P("APP_INITIAL_STATE_OUT_OF_SCOPE","initialState reference is outside the selected package");let E=On(e,g);p.initialState={...f,hash:Li(E)};}let u;try{let f=ze(p,{mode:"published"});u=new Uint8Array(Buffer.from(JSON.stringify(f),"utf8"));}catch(f){throw f instanceof se?P("APP_UI_MANIFEST_INVALID",f.code):P("APP_UI_MANIFEST_INVALID")}return ol(o,s.manifest,u),{bytes:u,...d===void 0?{}:{legacySourceHash:d}}}async function sl(e,n){let{included:t,excluded:i}=Di(e);us(e,t,n);let o=qr(e,t,{version:n.version}),r=bi(e,t);return {plan:{manifest:o,included:t,excluded:i,secretFindings:r},archiveOptions:{}}}async function al(e,n){el(n);let t=await Br(e),i=nl(t.items,n.appId);if(i.definitionHash!==n.expectedDefinitionHash)throw P("APP_DEFINITION_CONFLICT",`definitionHash changed for ${n.appId}`);let o=tl(i),r=Di(e);if(r.excluded.some(f=>yt(f.path,o)&&(f.rule==="symlink"||f.rule==="symlink-dir")))throw P("PACKAGE_SYMLINK","selected App package contains a symlink");let s=r.included.filter(f=>yt(f,o)),a=il(r,o),d=new Map,c=new Map;if(i.capabilities.includes("screen")){let f=rl(e,i,o,s),g=`${o}/${de}`;d.set(g,f.bytes),f.legacySourceHash!==void 0?c.set(g,f.legacySourceHash):(s.push(g),s.sort());}if(i.capabilities.includes("skill")&&!s.includes(`${o}/SKILL.md`))throw P("APP_SKILL_MISSING","skill capability requires package-root SKILL.md");us(e,s,n,d);let l={appId:i.appId,version:n.version??"",description:i.description,capabilities:i.capabilities,packageRoot:o,...i.definition?.id===void 0?{}:{definitionId:i.definition.id},definitionHash:i.definitionHash,includedFiles:s,generatedFiles:d},p=Zr(e,l),u=bi(e,s,d);return {plan:{manifest:p,included:s,excluded:a,secretFindings:u},archiveOptions:{generatedFiles:d,sourceFileHashes:c}}}async function fs(e,n){let t=ce.resolve(e);if(Qp(n))return al(t,n);if(n.expectedDefinitionHash!==void 0)throw P("APP_ID_REQUIRED");return sl(t,n)}async function oA(e,n={}){return (await fs(e,n)).plan}function cl(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 ys(e,n={}){let t=ce.resolve(e),i=await fs(t,n);i.plan.secretFindings.length>0&&cl(i.plan.secretFindings);let o=await rs(t,i.plan.manifest,i.archiveOptions);return {manifest:i.plan.manifest,tgzPath:o}}async function rA(e,n={}){return ys(e,n)}async function sA(e,n){let t=await ys(e,n);if(t.manifest.type!=="app")throw new Error("publish: App pack unexpectedly produced a template manifest");return t}
|
|
2
|
+
export{Yp as DEFAULT_PUBLISH_MAX_BYTES,Xp as DEFAULT_PUBLISH_MAX_FILES,Hr as EXCLUDE_RULES,ln as MARKETPLACE_API_PREFIX,we as PublishError,sA as packApp,ys as packPublish,rA as packTemplate,oA as planPublish,Kp as uploadToMarketplace};
|