@crewx/sdk 0.9.0-rc.154 → 0.9.0-rc.155
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/app/index.js +1 -1
- package/dist/app/protocol.d.ts +2 -2
- package/dist/esm/app/index.js +1 -1
- 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 +216 -216
- package/dist/mcp-app/model-context.d.ts +1 -1
- package/dist/mcp-app/workspace-app-scan-cache.d.ts +3 -0
- package/dist/publish/index.js +2 -2
- package/dist/skills/index.js +2 -2
- package/dist/ui-instance/runtime.d.ts +1 -1
- package/dist/ui-plugin/limits.d.ts +2 -2
- package/package.json +1 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import*as ce from'path';import {resolve,relative,sep,isAbsolute,join}from'path';import'url';import*as bi 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 x,Un=B(()=>{m();x=class extends Error{constructor(t,i=t,r){super(i);this.code=t;this.currentRevision=r;}code;currentRevision;name="UiRuntimeError"};});function mt(e){return Is.test(e)||gs.test(e)}function fe(){throw new x("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,r,o){if(n>i&&fe(),e===null||typeof e=="string"||typeof e=="boolean")return typeof e=="string"&&(ms.test(e)||_s.test(e)&&!Ns(r,o)||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,r,o));Es(s)||fe();let a={};for(let[d,c]of Object.entries(e))mt(d)&&fe(),a[d]=It(c,n+1,t,i,[...r,d],o);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(r=>typeof r!="string"))&&fe();let i=It(e,0,new Set,Ts+n,[],t);return (i===null||Array.isArray(i)||typeof i!="object")&&fe(),i}function Ze(e,n){if(!e||!n)return false;let t=e.split("."),i=n.split(".");return t.length>=i.length&&i.every((r,o)=>t[o]===r)}function Ns(e,n){if(e.length===0)return false;let t=e.join(".");return n.some(i=>Ze(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,Le=B(()=>{m();Un();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 Oi=B(()=>{m();Le();});var kn,_t=B(()=>{m();kn=["text/plain","application/json"];});var Ri=B(()=>{m();_t();});function en(e){return bs.has(e)||Ss.test(e)||Ms.test(e)}var wi,bs,Ss,Ms,xn,An,Te,Et,Tt,Pt,Nt,Dt,Be=B(()=>{m();wi=["__proto__","prototype","constructor","proof","token","secret","password","cookie","authorization","private_key","private-key","stack","exception","plugin_text","url","uri","endpoint","path","filename","filepath","cwd","shell","directory","dir","folder"],bs=new Set(wi),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;xn=/^[A-Za-z0-9_]+$/,An=/^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)*$/,Te=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,Et=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/,Tt=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,Pt=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/,Nt=["blue","violet","emerald","amber","rose","sky","slate","indigo"],Dt=["inline","panel"];});function bt(e){return typeof e=="string"&&kn.includes(e)}var Ci=B(()=>{m();_t();Be();});function vn(e){if(!St(e))return false;let n=Object.keys(e);return !(n.some(t=>t!=="in"&&t!=="out")||n.length===0||Object.hasOwn(e,"in")&&!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();Ri();Ci();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(r=>r.resultProjection!==void 0)?{id:e.id,version:e.version,...e.renderer===void 0?{}:{renderer:e.renderer},...e.surfaces===void 0?{}:{surfaces:e.surfaces},...e.stateProjection===void 0?{}:{stateProjection:e.stateProjection},...e.dataPaths===void 0?{}:{dataPaths:e.dataPaths},...e.summaryProjection===void 0?{}:{summaryProjection:e.summaryProjection},...e.legacy===void 0?{}:{legacy:e.legacy},...e.usage===void 0?{}:{usage:e.usage},...e.detailPanel===void 0?{}:{detailPanel:e.detailPanel},...e.displayModes===void 0?{}:{displayModes:e.displayModes},...e.sourceHash===void 0?{}:{sourceHash:e.sourceHash},actions:e.actions}:e.sourceHash===void 0?{id:e.id,version:e.version,actions:e.actions}:{id:e.id,version:e.version,sourceHash:e.sourceHash,actions:e.actions},i=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 x("DEFINITION_UNSUPPORTED","UI definition is invalid");if(e.sourceHash!==void 0&&(typeof e.sourceHash!="string"||!ws.test(e.sourceHash)))throw new x("DEFINITION_UNSUPPORTED","UI definition source hash is invalid");if(!/^[0-9a-f]{64}$/.test(e.hash)||le(e)!==e.hash)throw new x("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 x("DEFINITION_UNSUPPORTED","UI action declaration is invalid");if(t.confirmation!==void 0&&t.confirmation!=="none"&&t.confirmation!=="native")throw new x("DEFINITION_UNSUPPORTED","UI action confirmation is invalid");if(t.inputKeys&&(!Array.isArray(t.inputKeys)||t.inputKeys.some(i=>typeof i!="string"||!i)))throw new x("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 x("DEFINITION_UNSUPPORTED","UI action data input declaration is invalid");if(t.resultProjection&&Lt(t.resultProjection),t.content!==void 0&&!vn(t.content))throw new x("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 x("DEFINITION_UNSUPPORTED","UI action environment declaration is invalid")}if(e.renderer!==void 0&&(!e.renderer||e.renderer.length>128))throw new x("DEFINITION_UNSUPPORTED","UI definition renderer is invalid");if(e.surfaces&&(!Array.isArray(e.surfaces)||e.surfaces.some(n=>!n||n.length>64)))throw new x("DEFINITION_UNSUPPORTED","UI definition surfaces are invalid");if(e.usage!==void 0&&e.usage!=="card"&&e.usage!=="window")throw new x("DEFINITION_UNSUPPORTED","UI definition usage is invalid");if(e.detailPanel!==void 0&&typeof e.detailPanel!="boolean")throw new x("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 x("DEFINITION_UNSUPPORTED","UI definition displayModes are invalid");if(e.usage==="card"&&e.displayModes!==void 0)throw new x("DEFINITION_UNSUPPORTED","Card definitions cannot declare displayModes");if(e.usage==="window"&&e.detailPanel!==void 0)throw new x("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 x("DEFINITION_UNSUPPORTED","UI summary projection exceeds state projection")}if(e.legacy!==void 0){if(!e.legacy||typeof e.legacy!="object"||Array.isArray(e.legacy)||Object.keys(e.legacy).some(r=>!["readTool","actionTool","hostTools","agentAccess"].includes(r)))throw new x("DEFINITION_UNSUPPORTED","UI legacy metadata is invalid");let n=new Set;for(let[r,o]of [["readTool",e.legacy.readTool],["actionTool",e.legacy.actionTool]])if(o!==void 0){if(Cs(o,r==="readTool"),n.has(o.name))throw new x("DEFINITION_UNSUPPORTED","UI legacy tool names collide");n.add(o.name);}let t=e.legacy.hostTools;if(t!==void 0){if(!t||typeof t!="object"||Array.isArray(t))throw new x("DEFINITION_UNSUPPORTED","UI legacy host tools are invalid");let r={"doc.open":"crewx_app_html_viewer_open","pty.connect":"crewx_app_terminal_connect"};for(let[o,s]of Object.entries(t)){if(!Object.hasOwn(r,o)||r[o]!==s||typeof s!="string"||!/^[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(s)||n.has(s))throw new x("DEFINITION_UNSUPPORTED","UI legacy host tools are invalid");n.add(s);}}let i=e.legacy.agentAccess;if(i!==void 0&&(!i||typeof i!="object"||Array.isArray(i)||Object.entries(i).some(([r,o])=>!r||!Object.hasOwn(e.actions,r)||o!=="allowed"&&o!=="denied")))throw new x("DEFINITION_UNSUPPORTED","UI legacy agent access is invalid");if(e.legacy.actionTool!==void 0&&(!i||Object.keys(i).length===0))throw new x("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=>Ze(t,i))))throw new x("DEFINITION_UNSUPPORTED","UI definition dataPaths are invalid")}}function Cs(e,n){if(!e||typeof e!="object"||Array.isArray(e))throw new x("DEFINITION_UNSUPPORTED","UI legacy tool metadata is invalid");let t=e,i=["name","description","inputSchema","textFallback","visibility"],r=Object.hasOwn(t,"fixedResult");if(Object.keys(t).some(o=>!i.includes(o)&&!(n&&o==="fixedResult"))||i.some(o=>!Object.hasOwn(t,o))||typeof t.name!="string"||!/^[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(t.name)||typeof t.description!="string"||t.description.trim().length===0||t.description.length>8192||typeof t.textFallback!="string"||t.textFallback.trim().length===0||t.textFallback.length>16384||!t.inputSchema||typeof t.inputSchema!="object"||Array.isArray(t.inputSchema)||!Array.isArray(t.visibility)||t.visibility.length===0||t.visibility.some(o=>o!=="model"&&o!=="app")||new Set(t.visibility).size!==t.visibility.length)throw new x("DEFINITION_UNSUPPORTED","UI legacy tool metadata is invalid");try{let o=ye(t.inputSchema);if(o.type!==void 0&&o.type!=="object")throw new Error("schema type");if(r){if(!n)throw new Error("fixed result location");let s=t.fixedResult;if(!s||typeof s!="object"||Array.isArray(s))throw new Error("fixed result");let a=s;if(Object.keys(a).sort().join(",")!=="argsPolicy,structuredContent"||a.argsPolicy!=="empty-only"&&a.argsPolicy!=="ignore"||!a.structuredContent||typeof a.structuredContent!="object"||Array.isArray(a.structuredContent))throw new Error("fixed result");let d=ye(a.structuredContent);if(ht(Qe(d))>4*1024)throw new Error("fixed result size")}}catch{throw new x("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 x("DEFINITION_UNSUPPORTED","UI projection policy is invalid")}function Us(e){return e.length>0&&e.length<=128&&e!=="*"&&e!=="all"&&!/[/*]/.test(e)}var ws,He=B(()=>{m();Le();Un();Mt();ws=/^[0-9a-f]{64}$/;});var H,nn,Rt=B(()=>{m();H="dist/tools.json",nn="dist/main.mjs";});var xe,wt=B(()=>{m();xe="window";});function Ui(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,ki=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 jn(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(o=>typeof o!="string"||o!=="length"&&!/^(?:0|[1-9][0-9]*)$/.test(o))&&z("CSP_ORIGIN_INVALID");let r=[];for(let o=0;o<t.length;o+=1)(!Object.prototype.hasOwnProperty.call(t,o)||typeof t[o]!="string")&&z("CSP_ORIGIN_INVALID"),r.push(t[o]);return Object.keys(t).length!==t.length&&z("CSP_ORIGIN_INVALID"),r}function 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 ji(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(),r=t[2];(r.includes("@")||r.includes("%")||r.includes("*"))&&z("CSP_ORIGIN_INVALID"),(r.startsWith("[")?zs:$s).test(r)||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 Fi(e,n,t){let i=4294967295<<32-t>>>0;return (e&i)===(n&i)}function Hi(e){let n=Ys(e);return Fi(n,3221225472,24)?n!==3221225481&&n!==3221225482:Ws.some(([t,i])=>Fi(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((o,s)=>o<<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 r=Number(n&0xffffffffn);return Hi([r>>>24&255,r>>>16&255,r>>>8&255,r&255].join("."))}return t<8192||t>16383||t===8193&&i<=511||t===8193&&i===3512||t===8194||t===16383&&i<=4095}function Qs(e,n){let t=e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e,i=isIP(t);if(i===4)return Hi(t);if(i===6)return Zs(t);let r=e.toLowerCase().replace(/\.$/,"");return !r||!r.includes(".")||n.has(r)?true:Bs.some(o=>r===o||r.endsWith(`.${o}`))}function Vi(e){return Object.freeze([...new Set(e.map(n=>n.origin))].sort())}function Bi(e){return JSON.stringify({baseUriDomains:[],connectDomains:e.connectDomains,declared:e.declared,frameDomains:e.frameDomains,resourceDomains:[]})}function zi(e,n={}){if(e===void 0){let f=Bi({declared:false,connectDomains:[],frameDomains:[]});return Object.freeze({declared:false,connectDomains:Object.freeze([]),frameDomains:Object.freeze([]),resourceDomains:Object.freeze([]),baseUriDomains:Object.freeze([]),cspHash: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=jn(e,"connectDomains"),r=jn(e,"frameDomains"),o=jn(e,"resourceDomains"),s=jn(e,"baseUriDomains");(o.length>0||s.length>0)&&z("CSP_AXIS_UNSUPPORTED"),(Xs(e)>vs||i.length>vi||r.length>vi||i.length+r.length>js||[...i,...r].some(f=>new TextEncoder().encode(f).byteLength>Fs))&&z("CSP_LIMIT_EXCEEDED");let d=i.map(f=>ji(f,"connectDomains")),c=r.map(f=>ji(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:Vi(d),frameDomains:Vi(c)},u=Bi(p);return Object.freeze({...p,resourceDomains:Object.freeze([]),baseUriDomains:Object.freeze([]),cspHash:createHash("sha256").update(u,"utf8").digest("hex")})}var vs,vi,js,Fs,Vs,Bs,Hs,zs,$s,Gs,Ws,Ct,$i=B(()=>{m();vs=4096,vi=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 gn(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 v(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function Sa(e,n){let t={};for(let[i,r]of Object.entries(e))i!==n&&(t[i]=r);return t}function X(e,n,t=[]){let i=new Set([...n,...t]),r=Object.keys(e).find(s=>!i.has(s));r!==void 0&&A("MANIFEST_INVALID","MANIFEST_INVALID",r,"unknown-key");let o=n.find(s=>!v(e,s));o!==void 0&&A("MANIFEST_INVALID","MANIFEST_INVALID",o,"missing-key");}function Hn(e,n=false,t=false,i=false){return ia.test(e)||!i&&ra.test(e)||oa.test(e)||t&&Gi.test(e)||sa.test(e)&&!(n&&/^\s*data:/i.test(e)&&!Gi.test(e))}function Bn(e,n=new Set,t=0,i=false,r=false,o=""){if(typeof e=="string"){Hn(e,i,r)&&A("UNSAFE_VALUE","UNSAFE_VALUE",o,"unsafe-value");return}if(!(e===null||typeof e!="object")){(t>8||n.has(e))&&A("MANIFEST_INVALID","MANIFEST_INVALID",o),n.add(e);try{if(Array.isArray(e)){e.forEach((s,a)=>Bn(s,n,t+1,!1,!1,gn(o,`[${a}]`)));return}G(e)||A("MANIFEST_INVALID","MANIFEST_INVALID",o);for(let[s,a]of Object.entries(e))Bn(a,n,t+1,i&&t===0&&(s==="name"||s==="description"),r,gn(o,s));}finally{n.delete(e);}}}function Pe(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 tn(e){return na.test(e)||A("TOKEN_INVALID"),e}function Ma(e){return eo.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 r=Ma(t);G(i)||A("MANIFEST_INVALID");let o=i.type;if(o==="text"){X(i,["type","maxLength"]),n[r]={type:o,maxLength:ge(i,"maxLength",1)};continue}if(o==="text-list"){X(i,["type","max","itemMaxLength"]),n[r]={type:o,max:ge(i,"max",0),itemMaxLength:ge(i,"itemMaxLength",1)};continue}if(o==="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[r]={type:o,min:s,max:a,labelMaxLength:ge(i,"labelMaxLength",1),detailMaxLength:ge(i,"detailMaxLength",1)};continue}typeof o=="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 Fn(e,n,t){let i=Pe(e,"field");return eo.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:tn(Pe(e,"badgeToken")),noticeToken:tn(Pe(e,"noticeToken"))};case "heading":return X(e,["primitive","field"]),{primitive:t,field:Fn(e,n,"text")};case "labeled-text":return X(e,["primitive","titleToken","field","variant"]),e.variant!=="callout"&&A("MANIFEST_INVALID"),{primitive:t,titleToken:tn(Pe(e,"titleToken")),field:Fn(e,n,"text"),variant:"callout"};case "step-flow":return X(e,["primitive","titleToken","field"]),{primitive:t,titleToken:tn(Pe(e,"titleToken")),field:Fn(e,n,"step-list")};case "text-list":{X(e,["primitive","titleToken","field"],["emptyToken","hideWhenEmpty"]);let i={primitive:t,titleToken:tn(Pe(e,"titleToken")),field:Fn(e,n,"text-list")};return v(e,"emptyToken")&&(i.emptyToken=tn(Pe(e,"emptyToken"))),v(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 Wi(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`),(Hn(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"||!Te.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 no(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((r,o)=>xt(r,n,t+1,gn(i,`[${o}]`)));return}G(e)||A("MANIFEST_INVALID","v2 manifest contains a non-plain object",i,"non-plain-object");for(let[r,o]of Object.entries(e))xt(o,n,t+1,gn(i,r));}finally{n.delete(e);}}}function to(e){return (typeof e!="string"||e.length>4096||!An.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=>en(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 r=to(i);t.has(r)&&A("MANIFEST_INVALID","projection allowlist contains a duplicate path"),t.add(r),n.push(r);}return {allow:n}}function Ua(e,n){if(e===void 0)return;Array.isArray(e)||A("MANIFEST_INVALID","dataPaths must be an array"),e.length>Da&&Y("dataPaths exceed the v2 limit");let t=[],i=new Set;for(let r of e){let o=to(r);i.has(o)&&A("MANIFEST_INVALID","dataPaths contain a duplicate path"),n.some(s=>Ze(o,s))||A("MANIFEST_INVALID","dataPaths must be projection-allowed"),i.add(o),t.push(o);}return t}function on(e,n,t=Number.MAX_SAFE_INTEGER){return (!Number.isSafeInteger(e)||e<0||e>t)&&A("MANIFEST_INVALID",`${n} is invalid`),e}function Ji(e,n){return (typeof e!="number"||!Number.isFinite(e))&&A("MANIFEST_INVALID",`${n} is invalid`),e}function jt(e,n=0,t=new Set){if(typeof e=="string")return (e.length>4096||Hn(e))&&A("UNSAFE_VALUE","schema enum contains an unsafe string"),e;if(e===null||typeof e=="boolean")return e;if(typeof e=="number")return Number.isFinite(e)||A("MANIFEST_INVALID","schema enum contains a non-finite number"),e;(n>8||typeof e!="object"||e===void 0)&&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(r=>jt(r,n+1,t));G(e)||A("MANIFEST_INVALID","schema enum contains a non-plain object");let i={};for(let[r,o]of Object.entries(e))en(r)&&A("MANIFEST_INVALID","schema enum contains a reserved key"),i[r]=jt(o,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 r of e)(typeof r!="string"||!An.test(r))&&A("MANIFEST_INVALID","schema required contains an invalid key"),r.length>4096&&Y("schema required key is too long"),i.has(r)&&A("MANIFEST_INVALID","schema required contains a duplicate key"),n&&!Object.prototype.hasOwnProperty.call(n,r)&&A("MANIFEST_INVALID","schema required references an undeclared property"),i.add(r),t.push(r);return t}function xa(e,n){let t=n?An:xn;return e.length>4096&&Y("schema property name is too long"),(!t.test(e)||e.split(".").some(i=>en(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 r=["type","enum"];i==="string"&&r.push("minLength","maxLength"),i==="array"&&r.push("minItems","maxItems","items"),i==="object"&&r.push("minProperties","maxProperties","properties","required","additionalProperties"),(i==="number"||i==="integer")&&r.push("minimum","maximum"),X(e,["type"],r.filter(a=>a!=="type"));let o={type:i};if(v(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"),o.enum=e.enum.map(a=>jt(a))),i==="string"&&(v(e,"minLength")&&(o.minLength=on(e.minLength,"schema minLength",4096)),v(e,"maxLength")&&(o.maxLength=on(e.maxLength,"schema maxLength",4096)),o.minLength!==void 0&&o.maxLength!==void 0&&o.minLength>o.maxLength&&A("MANIFEST_INVALID","schema string length bounds are inverted")),(i==="number"||i==="integer")&&(v(e,"minimum")&&(o.minimum=Ji(e.minimum,"schema minimum")),v(e,"maximum")&&(o.maximum=Ji(e.maximum,"schema maximum")),o.minimum!==void 0&&o.maximum!==void 0&&o.minimum>o.maximum&&A("MANIFEST_INVALID","schema numeric bounds are inverted")),i==="array"&&(v(e,"minItems")&&(o.minItems=on(e.minItems,"schema minItems",128)),v(e,"maxItems")&&(o.maxItems=on(e.maxItems,"schema maxItems",128)),o.minItems!==void 0&&o.maxItems!==void 0&&o.minItems>o.maxItems&&A("MANIFEST_INVALID","schema array length bounds are inverted"),v(e,"items")&&(o.items=Ft(e.items,n+1,false))),i==="object"){let a;if(v(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);}o.properties=a;}v(e,"minProperties")&&(o.minProperties=on(e.minProperties,"schema minProperties",64)),v(e,"maxProperties")&&(o.maxProperties=on(e.maxProperties,"schema maxProperties",64)),o.minProperties!==void 0&&o.maxProperties!==void 0&&o.minProperties>o.maxProperties&&A("MANIFEST_INVALID","schema object property bounds are inverted");let d=ka(e.required,a);d!==void 0&&(o.required=d),v(e,"additionalProperties")&&(e.additionalProperties!==false&&A("MANIFEST_INVALID","schema additionalProperties must be false"),o.additionalProperties=false);}let s=JSON.stringify(o);return (s===void 0||Buffer.byteLength(s,"utf8")>1048576)&&Y("action inputSchema subtree is too large"),o}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"&&v(e,"entry"))return X(e,ha),e.entry!==nn&&A("MANIFEST_INVALID",`skill backend entry must be ${nn}`),{type:"skill",entry:nn};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=v(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),v(e,"_meta")&&$("_meta",()=>io(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 r=$("inputSchema",()=>va(e.inputSchema)),o;if(v(e,"dataInputs")){Array.isArray(e.dataInputs)||A("MANIFEST_INVALID","action dataInputs must be an array","dataInputs");let l=r.properties,p=new Set,u=[];for(let f of e.dataInputs)(typeof f!="string"||!v(l,f)||p.has(f))&&A("MANIFEST_INVALID","action dataInputs must be unique declared properties","dataInputs"),p.add(f),u.push(f);o=u;}let s=$("resultProjection",()=>vt(e.resultProjection)),a=$("backend",()=>ja(e.backend)),d;v(e,"content")&&((a.type!=="skill"||!vn(e.content))&&A("MANIFEST_INVALID","action content declaration is invalid","content"),d=Ba(e.content));let c;if(v(e,"confirmation")){let l=e.confirmation;l!=="none"&&l!=="native"&&A("MANIFEST_INVALID","action confirmation is invalid","confirmation"),c=l;}return {actionId:n,capability:t,mutation:i,inputSchema:r,resultProjection:s,backend:a,...d===void 0?{}:{content:d},...o===void 0?{}:{dataInputs:o},...c===void 0?{}:{confirmation:c}}}function Va(e){return Ui(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"),v(e,"hash")?{path:"ui/state.json",hash:no(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=zi(e);}catch(i){let r=i!==null&&typeof i=="object"&&"code"in i&&typeof i.code=="string"?i.code:"CSP_ORIGIN_INVALID";return A("MANIFEST_INVALID",r,void 0,r.toLowerCase().replace(/_/g,"-"))}if(t.frameDomains.length>0&&A("MANIFEST_INVALID","external origins in csp are not enabled in this rollout",void 0,"csp-not-enabled"),t.connectDomains.length!==0)return n?.terminal===true&&A("MANIFEST_INVALID","runtime.terminal cannot be combined with csp.connectDomains","connectDomains","terminal-with-connect-domains"),Object.freeze({connectDomains:t.connectDomains})}function Ga(e,n){Bn(G(e)&&v(e,"csp")?Sa(e,"csp"):e,new Set,0,true,true),xt(e),G(e)||A("MANIFEST_INVALID"),X(e,la,ua),v(e,"_meta")&&$("_meta",()=>io(e._meta)),e.manifestVersion!==2&&A("MANIFEST_INVALID");let t;v(e,"runtime")&&(t=$("runtime",()=>za(e.runtime)));let i;v(e,"csp")&&(i=$("csp",()=>$a(e.csp,t)));let r=$("pluginId",()=>kt(e.pluginId,"pluginId")),o=$("definitionId",()=>kt(e.definitionId,"definitionId")),s=$("version",()=>ge(e,"version",1)),a=$("name",()=>Wi(e.name,"name")),d=$("description",()=>Wi(e.description,"description")),c;v(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;v(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;v(e,"entryHash")&&(p=$("entryHash",()=>no(e.entryHash)));let u;v(e,"initialState")&&(u=$("initialState",()=>Ha(e.initialState)));let f;v(e,"usage")&&(e.usage!=="card"&&e.usage!=="window"&&A("MANIFEST_INVALID","usage is invalid","usage"),f=e.usage);let g;v(e,"detailPanel")&&(typeof e.detailPanel!="boolean"&&A("MANIFEST_INVALID","detailPanel is invalid","detailPanel"),g=e.detailPanel);let _;if(v(e,"displayModes")){((f??xe)!==xe||!Array.isArray(e.displayModes)||e.displayModes.length===0)&&A("MANIFEST_INVALID","displayModes are only valid for window Apps","displayModes");let y=new Set(["inline","floating","focused"]);(new Set(e.displayModes).size!==e.displayModes.length||e.displayModes.some(I=>typeof I!="string"||!y.has(I)))&&A("MANIFEST_INVALID","displayModes are invalid","displayModes"),_=e.displayModes;}(f??xe)===xe&&g!==void 0&&A("MANIFEST_INVALID","detailPanel is card-only","detailPanel");let P=n.mode??"local";P!=="local"&&P!=="installed"&&P!=="published"&&A("MANIFEST_INVALID","manifest mode is invalid"),P!=="local"&&p===void 0&&A("MANIFEST_INVALID","installed manifests require entryHash","entryHash","required-when-installed"),P!=="local"&&u!==void 0&&u.hash===void 0&&A("MANIFEST_INVALID","installed manifests require initialState.hash","initialState.hash","required-when-installed"),(!Array.isArray(e.surfaces)||e.surfaces.length===0)&&A("MANIFEST_INVALID","surfaces are invalid","surfaces"),e.surfaces.length>2&&Y("surfaces exceed the v2 limit","surfaces","too-many-items");let U=[],k=new Set;for(let y of e.surfaces)(typeof y!="string"||!Dt.includes(y))&&A("MANIFEST_INVALID","surface is unsupported","surfaces"),k.has(y)&&A("MANIFEST_INVALID","surfaces contain a duplicate","surfaces","duplicate-item"),k.add(y),U.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)),F=e.summaryProjection===void 0?void 0:$("summaryProjection",()=>vt(e.summaryProjection));F!==void 0&&F.allow.some(y=>!C.allow.includes(y))&&A("MANIFEST_INVALID","summaryProjection must be a subset of stateProjection.allow","summaryProjection");let D=$("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 b=[],O=new Set;for(let[y,I]of e.actions.entries()){let h=`actions[${y}]`,E=$(h,()=>Fa(I));if(O.has(E.actionId)&&A("MANIFEST_INVALID","actions contain a duplicate actionId",`${h}.actionId`,"duplicate-item"),E.backend.type==="core"&&E.backend.handler==="state.set"){E.mutation||A("MANIFEST_INVALID","state.set actions must be mutations",`${h}.mutation`);for(let L of Object.keys(E.inputSchema.properties))C.allow.includes(L)||A("MANIFEST_INVALID","state.set input paths must be projection-allowed",`${h}.inputSchema.properties`);}O.add(E.actionId),b.push(E);}return {manifestVersion:2,pluginId:r,definitionId:o,version:s,name:a,description:d,...c===void 0?{}:{icon:c},...l===void 0?{}:{tone:l},entry:"ui/index.html",...p===void 0?{}:{entryHash:p},...t===void 0?{}:{runtime:t},...i===void 0?{}:{csp:i},...u===void 0?{}:{initialState:u},...f===void 0?{}:{usage:f},...g===void 0?{}:{detailPanel:g},..._===void 0?{}:{displayModes:_},surfaces:U,size:{height:N},stateProjection:C,...F===void 0?{}:{summaryProjection:F},...D===void 0?{}:{dataPaths:D},actions:b}}function io(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 o of e.actions){n[o.actionId]={capabilities:[o.capability],inputKeys:Object.keys(o.inputSchema.properties??{}),...o.dataInputs===void 0?{}:{dataInputs:o.dataInputs},resultProjection:o.resultProjection,...o.confirmation===void 0?{}:{confirmation:o.confirmation},...o.content===void 0?{}:{content:o.content},...o.backend.type!=="skill"||o.backend.env===void 0?{}:{env:o.backend.env}};let s=o.backend.type==="skill"||o.backend.type==="core"&&o.backend.handler==="state.set";t[o.actionId]={actionId:o.actionId,mutation:o.mutation,backend:o.backend,launchPolicy:s?"allowed":"denied",...s?{}:{denialCode:"EXEC_DENIED"}};}let i={id:e.definitionId,version:e.version,renderer:"sandbox-html",...e.usage===void 0?{}:{usage:e.usage},...e.detailPanel===void 0?{}:{detailPanel:e.detailPanel},...e.displayModes===void 0?{}:{displayModes:e.displayModes},surfaces:e.surfaces,stateProjection:e.stateProjection,...e.summaryProjection===void 0?{}:{summaryProjection:e.summaryProjection},...e.dataPaths===void 0?{}:{dataPaths:e.dataPaths},actions:n},r={entry:{path:"ui/index.html",...e.entryHash===void 0?{}:{hash:e.entryHash}},...e.initialState===void 0?{}:{initialState:e.initialState}};return {manifest:e,definition:i,handlers:t,resources:r}}function Vt(e,n,t,i,r,o){if(typeof e=="string"){let s=r.length>0&&o.some(a=>Ze(r.join("."),a));return (e.length>4096||Hn(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,1048576,r,o));else {G(e)||Ie("state contains a non-plain object");let d={};for(let[c,l]of Object.entries(e))(c.length>4096||!xn.test(c)||en(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,1048576,[...r,c],o);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,1048576,[],n);return (t===null||Array.isArray(t)||typeof t!="object")&&Ie(),t}function Ja(e,n={}){Bn(e),G(e)||A("MANIFEST_INVALID"),X(e,pa),e.manifestVersion!==1&&A("MANIFEST_INVALID");let t=Ut(Pe(e,"pluginId")),i=Ut(Pe(e,"definitionId")),r=ge(e,"version",1),o=ge(e,"primitiveSet",1),s=n.supportedPrimitiveSet??ea;(!Number.isSafeInteger(s)||s<1)&&A("MANIFEST_INVALID"),o>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(Pe(e.activation,"language")),d=La(e.schema),c=wa(e.layout,d);return {manifestVersion:1,pluginId:t,definitionId:i,version:r,primitiveSet:o,activation:{kind:"fenced-code",language:a},schema:d,layout:c}}function 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 $e(e,n={}){try{return Ka(e,n)}catch(t){if(t instanceof se)throw t;return A("MANIFEST_INVALID")}}function mn(e,n={}){let t=$e(e,n);return t.manifestVersion===2?Wa(t):t}var ea,na,ta,eo,ia,oa,ra,sa,Gi,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();Le();Mt();ki();Rt();$i();Be();ea=1,na=/^[a-z][a-zA-Z0-9]*(\.[a-zA-Z0-9]+)+$/,ta=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,eo=/^[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,Gi=/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,r,o){super(i);this.code=t;this.path=r;this.rule=o;}code;path;rule;name="UiPluginValidationError";withPathPrefix(t){return new e(this.code,this.message,gn(t,this.path),this.rule)}};});function po(e){return typeof e=="string"&&e.length<=Ya&&Xa.test(e)}function j(e,n,t,i,r){throw new De(e,{path:n,rule:t,...i===void 0?{}:{message:i},...r===void 0?{}:{file:r}})}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["${ve}"]`;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 lo(e,n,t){return {path:t(e.path),rule:e.rule??ec(e.code),...e.message!==e.code?{message:e.message}:{},file:n}}function uo(e){return JSON.parse(JSON.stringify(e))}function Wt(e,n,t=0,i=new Set){if(typeof e=="string"){e.length>4096&&j("LIMIT_EXCEEDED",n,"string-too-long"),(qa.test(e)||Za.test(e)||Qa.test(e))&&j("UNSAFE_VALUE",n,"unsafe-value");return}if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){Number.isFinite(e)||j("MANIFEST_INVALID",n,"non-finite-number");return}typeof e!="object"&&j("MANIFEST_INVALID",n,"non-json-value"),t>8&&j("LIMIT_EXCEEDED",n,"too-deep"),i.has(e)&&j("MANIFEST_INVALID",n,"cycle"),i.add(e);try{if(Array.isArray(e)){e.length>128&&j("LIMIT_EXCEEDED",n,"array-too-long"),e.forEach((r,o)=>Wt(r,`${n}[${o}]`,t+1,i));return}ie(e)||j("MANIFEST_INVALID",n,"non-plain-object");for(let[r,o]of Object.entries(e))Wt(o,n===""?r:`${n}.${r}`,t+1,i);}finally{i.delete(e);}}}function me(e,n){return (typeof e!="string"||e.length===0)&&j("MANIFEST_INVALID",n,"string"),e}function sn(e,n){return ie(e)||j("MANIFEST_INVALID",n,"object"),e}function tc(e,n){Array.isArray(e)||j("MANIFEST_INVALID",n,"array"),e.forEach((t,i)=>me(t,`${n}[${i}]`));}function ic(e,n){typeof e!="boolean"&&j("MANIFEST_INVALID",n,"boolean");}function hn(e,n,t,i){for(let r of Object.keys(e))!t.includes(r)&&!i.includes(r)&&j("MANIFEST_INVALID",`${n}.${r}`,"unknown-key");for(let r of t)q(e,r)||j("MANIFEST_INVALID",`${n}.${r}`,"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=sn(n,e);hn(t,e,["name"],["email","url"]);for(let i of Object.keys(t))me(t[i],`${e}.${i}`);return}case "repository":{let t=sn(n,e);hn(t,e,[],["type","url"]);for(let i of Object.keys(t))me(t[i],`${e}.${i}`);return}case "icons":{Array.isArray(n)||j("MANIFEST_INVALID",e,"array"),n.forEach((t,i)=>{let r=`${e}[${i}]`,o=sn(t,r);hn(o,r,["src","size"],["theme"]),me(o.src,`${r}.src`),me(o.size,`${r}.size`),q(o,"theme")&&me(o.theme,`${r}.theme`);});return}case "screenshots":case "keywords":case "privacy_policies":tc(n,e);return;case "tools":{Array.isArray(n)||j("MANIFEST_INVALID",e,"array"),n.forEach((t,i)=>{let r=`${e}[${i}]`,o=sn(t,r);hn(o,r,["name"],["description"]),me(o.name,`${r}.name`),q(o,"description")&&me(o.description,`${r}.description`);});return}case "prompts":{Array.isArray(n)||j("MANIFEST_INVALID",e,"array"),n.forEach((t,i)=>{let r=`${e}[${i}]`,o=sn(t,r);hn(o,r,["name","text"],["description","arguments"]),me(o.name,`${r}.name`),me(o.text,`${r}.text`);});return}case "tools_generated":case "prompts_generated":ic(n,e);return;case "localization":case "compatibility":case "user_config":sn(n,e);return;default:j("MANIFEST_INVALID",e,"unknown-key");}}function zn(e){return typeof e=="string"&&Te.test(e)?e:void 0}function fo(e){return Number.isSafeInteger(e)&&e>=1?e:void 0}function rc(e){let n=zn(e.name);if(n===void 0)return;let t=e._meta,i=ie(t)?t[ve]:void 0,r=ie(i)?i:{},o=q(r,"definitionId")?zn(r.definitionId):n,s=q(r,"definitionVersion")?fo(r.definitionVersion):1;return {pluginId:n,...o===void 0?{}:{definitionId:o},...s===void 0?{}:{definitionVersion:s}}}function sc(e){let n=zn(e.pluginId);if(n===void 0)return;let t=zn(e.definitionId),i=fo(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,ve)}catch{return false}}function ac(e,n){if(e===de)return n.builtinOnly===true;let t=n._meta,i=ie(t)?t[ve]:void 0;return ie(i)&&i.builtinOnly===true}function cc(e,n){q(e,"server")&&j("MANIFEST_INVALID","server","server-unsupported","phase 1 runs CrewX-owned Apps only");for(let a of Object.keys(e))Jt.includes(a)||j("MANIFEST_INVALID",a,"unknown-key");for(let a of Kt)q(e,a)||j("MANIFEST_INVALID",a,"missing-key");e.manifest_version!==$t&&j("MANIFEST_INVALID","manifest_version","unsupported-version",`manifest_version must be "${$t}"`),po(e.version)||j("MANIFEST_INVALID","version","semver","version must be a semver.org version such as 0.1.0");let t=e._meta;ie(t)||j("MANIFEST_INVALID","_meta","object"),q(t,ve)||j("MANIFEST_INVALID",he(),"missing-key");let i=t[ve];ie(i)||j("MANIFEST_INVALID",he(),"object");for(let a of Object.keys(i))Gt.includes(a)||co.includes(a)||j("MANIFEST_INVALID",he(a),"unknown-key");for(let a of Gt)a==="actions"&&n!==void 0||q(i,a)||j("MANIFEST_INVALID",he(a),"missing-key");if(n!==void 0&&q(i,"actions")&&j("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)&&j("MANIFEST_INVALID",he("definitionVersion"),"positive-integer");}let r={};for(let a of ao)q(e,a)&&(oc(a,e[a]),r[a]=uo(e[a]));let o={};for(let[a,d]of Object.entries(t))a!==ve&&(o[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:nn}}))),Object.keys(o).length>0&&(s._meta=o),{v2Input:s,...Object.keys(o).length>0?{vendorMeta:o}:{},passthrough:r}}function dc(e){Array.isArray(e)&&e.forEach((n,t)=>{let i=ie(n)?n.backend:void 0;ie(i)&&q(i,"entry")&&j("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)||j("MANIFEST_INVALID","","not-object","manifest.json must be a JSON object",W);let i;try{i=cc(e,t);}catch(s){throw s instanceof De?new De(s.code,{...s.reason,file:W}):s}let r;try{let s=$e(i.v2Input,{mode:n.mode??"local"});s.manifestVersion!==2&&j("MANIFEST_INVALID","","v2-required"),r=s;}catch(s){throw s instanceof se?new De(s.code,lo(s,W,nc)):s}let o=e.tools;if(Array.isArray(o)){let s=new Set(r.actions.map(a=>a.actionId));o.forEach((a,d)=>{let c=a.name;if(!s.has(c))throw new De("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:r,v2Input:i.v2Input,releaseVersion:e.version,...Object.keys(i.passthrough).length>0?{mcpb:i.passthrough}:{}}}function lc(e,n){try{let t=$e(e,{mode:n.mode??"local"});if(t.manifestVersion!==2)throw new De("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 De(t.code,lo(t,de,i=>i??"")):t}}function an(e){return le(mn(e).definition)}function ro(e){let{entryHash:n,initialState:t,...i}=e,r={...i};return t!==void 0&&(r.initialState={path:t.path}),uo(r)}function uc(e,n){let t=ro(e),i=ro(n);return [...new Set([...Object.keys(t),...Object.keys(i)])].sort().filter(o=>te(t[o]??null)!==te(i[o]??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),r="";try{let o=an(e),s=an(n);i=i||o!==s,r=` (definition hash ${o.slice(0,12)} vs ${s.slice(0,12)})`;}catch{i=true;}t.length===0&&!i||j("MANIFEST_DUAL_MISMATCH","","dual-manifest-mismatch",`${W} and ${de} normalize to different definitions${r}`+(t.length>0?`; differing fields: ${t.join(", ")}`:""));}function Ne(e,n,t="MANIFEST_INVALID",i){return {code:t,reason:{path:e,rule:n,...i===void 0?{}:{message:i},file:H},files:[]}}function so(e){return {...Ne("","tools-needs-manifest-json","MANIFEST_INVALID",`${H} is read with ${W} only`),files:e}}function Ac(e,n){if(e.byteLength>n)return {failure:Ne("","file-too-large","LIMIT_EXCEEDED")};let t;try{t=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e));}catch{return {failure:Ne("","invalid-json")}}if(!ie(t))return {failure:Ne("","not-object","MANIFEST_INVALID",`${H} must be a JSON object`)};for(let r of Object.keys(t))if(r!=="schemaVersion"&&r!=="actions")return {failure:Ne(r,"unknown-key")};for(let r of ["schemaVersion","actions"])if(!q(t,r))return {failure:Ne(r,"missing-key")};if(t.schemaVersion!==1)return {failure:Ne("schemaVersion","unsupported-version","MANIFEST_INVALID",`schemaVersion must be ${1}`)};let i=t.actions;if(!Array.isArray(i))return {failure:Ne("actions","array")};for(let[r,o]of i.entries()){if(!ie(o))return {failure:Ne(`actions[${r}]`,"object")};if(q(o,"backend"))return {failure:Ne(`actions[${r}].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=[],r=new TextDecoder("utf-8",{fatal:true});for(let o of Z){let s=e[o];if(s===void 0)continue;if(s.byteLength>t)return {parsed:i,failure:{code:"LIMIT_EXCEEDED",reason:{path:"",rule:"file-too-large",file:o},files:[o]}};let a;try{a=JSON.parse(r.decode(s));}catch{return {parsed:i,failure:{code:"MANIFEST_INVALID",reason:{path:"",rule:"invalid-json",file:o},files:[o]}}}if(!ie(a))return {parsed:i,failure:{code:"MANIFEST_INVALID",reason:{path:"",rule:"not-object",message:`${o} must be a JSON object`,file:o},files:[o]}};i.push({file:o,raw:a});}return {parsed:i}}function Ge(e,n={}){let{parsed:t,failure:i}=Ic(e,n),r=Z.filter(f=>e[f]!==void 0);if(i!==void 0)return {ok:false,rejection:i,parseFailure:true,builtinOnly:false};let o=e[H],s=o===void 0?void 0:Ac(o,n.maxBytes??262144);if(t.length===0)return {ok:false,rejection:s===void 0?{code:"MANIFEST_INVALID",reason:{path:"",rule:"no-manifest-file",message:"neither manifest.json nor ui-plugin.json is present"},files:[]}:so(r),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:so(r);if(f!==void 0)return {ok:false,rejection:f,parseFailure:false,...d===void 0?{}:{identity:d},builtinOnly:c};l=s.actions;}let p=[];try{for(let f of t)p.push(f.file===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 De)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?r:[f.reason.file]},parseFailure:false,...d===void 0?{}:{identity:d},builtinOnly:c};throw f}let u=p[0];return {ok:true,...u,identity:d??{pluginId:u.manifest.pluginId},files:r}}var W,de,Z,$t,ve,Jt,Kt,ao,Gt,co,Xa,Ya,qa,Za,Qa,De,$n=B(()=>{m();He();Le();Rt();Be();zt();W="manifest.json",de="ui-plugin.json",Z=[W,de],$t="0.3",ve="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"]),ao=Object.freeze(Jt.filter(e=>e!=="server"&&!Kt.includes(e))),Gt=Object.freeze(["entry","surfaces","size","stateProjection","actions"]),co=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;De=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();Oi();$n();zt();Be();});function S(e,n=e){throw new be(e,n)}var be,Wn=B(()=>{m();be=class extends Error{constructor(t,i=t){super(i);this.code=t;}code;name="McpAppContractError"};});var No=B(()=>{m();});var Do=B(()=>{m();He();Le();Wn();No();});function So(e,n){return bo.add(e),n!==void 0&&Mc.set(e,n),e}function cn(e){return e!==null&&typeof e=="object"&&bo.has(e)}var bo,Mc,Jn=B(()=>{m();bo=new WeakSet,Mc=new WeakMap;});function Pn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Zt(e,n,t=[]){let i=new Set([...n,...t]),r=Object.keys(e);return n.every(o=>Object.hasOwn(e,o))&&r.every(o=>i.has(o))}function Oo(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let n of Object.values(e))Oo(n);return Object.freeze(e)}function oe(e){throw new Se("LINEAGE_INVALID",e)}function kc(e){throw new Se("LINEAGE_STALE",e)}function Ro(e){if(!Pn(e)||!Zt(e,Rc,wc)||!Pn(e.actions))return oe("Lineage definition shape is invalid");for(let n of Object.values(e.actions))if(!Pn(n)||!Zt(n,Cc,Uc))return oe("Lineage action definition shape is invalid");return e}function xc(e){if(!Pn(e)||!Zt(e,Lc,Oc))return oe("Lineage entry shape is invalid");if(!Number.isSafeInteger(e.version)||e.version<1||typeof e.hash!="string"||!Mo.test(e.hash))return oe("Lineage entry identity is invalid");if(e.sourceHash!==void 0&&(typeof e.sourceHash!="string"||!Mo.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=Ro(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"):Oo({version:e.version,hash:e.hash,definition:n,...e.sourceHash===void 0?{}:{sourceHash:e.sourceHash},...e.compat===void 0?{}:{compat:e.compat}})}function Lo(e){return e.stateProjection?.allow??[]}function vc(e,n){let t=[],i=new Set(Lo(n));Lo(e).some(a=>!i.has(a))&&t.push("S1_STATE_PROJECTION");let r=new Set(n.dataPaths??[]);(e.dataPaths??[]).some(a=>!r.has(a))&&t.push("S2_DATA_PATHS");for(let[a,d]of Object.entries(e.actions)){let c=n.actions[a];if(c&&(d.confirmation??"native")==="native"&&(c.confirmation??"native")!=="native"){t.push("S3_ACTION_CONFIRMATION");break}}Object.keys(e.legacy?.agentAccess??{}).some(a=>!Object.hasOwn(n.actions,a))&&t.push("S4_LEGACY_AGENT_ACTIONS");let s=e.summaryProjection?.allow;if(s!==void 0){let a=new Set(n.summaryProjection?.allow??[]);s.some(d=>!a.has(d))&&t.push("S5_SUMMARY_PROJECTION");}return t}function 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(!Pn(n)||typeof n.hash!="string")return oe("Current definition is invalid");let t,i;try{let{hash:a,...d}=n;i=Ro(d),t={...i,hash:a},Ae(t);}catch{return oe("Current definition is invalid")}let r=e.map(xc),o=r[0].definition.id;if(r.some(a=>a.definition.id!==o))return oe("Lineage definition ids do not match");if(r.some((a,d)=>d>0&&a.version<=r[d-1].version))return oe("Lineage generations are not in increasing version order");if(r.some((a,d)=>r.findIndex(c=>c.hash===a.hash)!==d))return oe("Lineage contains a duplicate hash");let s=r[r.length-1];if(s.version!==t.version||s.hash!==t.hash||s.definition.id!==t.id||!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 r)if(l.sourceHash===void 0)for(let p of Object.keys(l.definition.actions))a.has(p)&&d.add(p);let c=Object.keys(t.legacy.agentAccess??{});if(c.length!==d.size||c.some(l=>!d.has(l))){let l="S4_LEGACY_AGENT_ACCESS_COMPLETE";throw new Se("LINEAGE_INVALID",`Lineage compatibility failed: ${l}`,[l])}}for(let a=0;a<r.length-1;a+=1){if(r.slice(a,-1).some(l=>l.compat==="break"))continue;let c=vc(r[a].definition,t);if(c.length>0)throw new Se("LINEAGE_INVALID",`Lineage compatibility failed: ${c.join(", ")}`,c)}return Object.freeze({entries:Object.freeze(r),current:t})}var Se,Mo,Lc,Oc,Rc,wc,Cc,Uc,ei=B(()=>{m();He();Le();Se=class extends Error{constructor(t,i=t,r=[]){super(i);this.code=t;this.violations=r;}code;violations;name="UiDefinitionLineageError"},Mo=/^[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 wo,Co,Uo,ni,ko=B(()=>{m();wo="text/html;profile=mcp-app",Co=["crewx_app_terminal_connect","crewx_app_html_viewer_open"],Uo=["crewx_listWorkspaces","crewx_queryAgent","crewx_executeAgent","crewx_getTaskResult","crewx_listTasks","crewx_listAgents","callBrowser","openTab","listTabs","closeTab"],ni="text/html";});function xo(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 vo=B(()=>{m();He();Jn();});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:Fe}),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:Fe}),n}function Ve(e,n,t){return (typeof e!="string"||!Fo.test(e))&&S(n,`${t} must be a safe identifier`),e}function Nn(e,n,t){let i=e??t;return (typeof i!="string"||i.trim().length===0||i.length>Hc)&&S("TOOL_INVALID",`${n} must be a meaningful description`),i}function ii(e){return (typeof e!="string"||e.length===0||e.length>dn||!/<html(?:\s|>)/i.test(e)||!/<\/html\s*>/i.test(e))&&S("HTML_INVALID","MCP App HTML must be a non-empty HTML document"),e}function Dn(e,n=0){try{let t=ye(e,n);return t.type!==void 0&&t.type!=="object"&&S("TOOL_INVALID","MCP App inputSchema must describe an object"),t}catch(t){if(t instanceof be)throw t;S("TOOL_INVALID","MCP App inputSchema must be projection-safe JSON");}}function Xc(e){return (typeof e!="string"||e.trim().length===0||e.length>zc)&&S("TOOL_INVALID","MCP App tools require a meaningful text fallback"),e}function Yc(e){e===void 0&&S("TOOL_INVALID","MCP App tool visibility is required");let n=[...e];return (n.length===0||n.some(t=>t!=="model"&&t!=="app")||new Set(n).size!==n.length)&&S("TOOL_INVALID","MCP App tool visibility must contain model and/or app once"),n}function Ho(e){return (typeof e!="string"||!Vo.test(e))&&S("RESOURCE_URI_INVALID","MCP App resource URI is not a registered ui:// URI"),e}function zo(e){let n=Ve(e.appId,"APP_ID_INVALID","Local App id"),t=Nn(e.name,"Local App name",n),i=Nn(e.description,"Local App description",`${t} interactive view`),r=qn(e.definition),o=ii(e.html),s=Kn(e.entryHash,"Local App entry hash"),a=e.entryBytes===void 0?Array.from(new TextEncoder().encode(o)):Yn(e.entryBytes,"Local App entry bytes");(Xn(a)!==s||Wo(a)!==o)&&S("HTML_INVALID","Local App entry bytes do not match the HTML hash");let d=qc(e),c=[];Array.isArray(e.actions)||S("TOOL_INVALID","Local App actions must be an array");for(let N of e.actions){let C=Ve(N.actionId,"TOOL_ID_INVALID","Local App action id");(c.includes(C)||!Object.prototype.hasOwnProperty.call(r.actions,C))&&S("TOOL_INVALID",`Local App action is not declared by the UI definition: ${C}`),c.push(C);}let l=Ve(e.readToolName,"TOOL_ID_INVALID","Local App read tool name"),p=e.actionToolName===void 0?void 0:Ve(e.actionToolName,"TOOL_ID_INVALID","Local App action tool name");c.length===0&&p!==void 0&&S("TOOL_INVALID","A static local App cannot register an action tool"),c.length>0&&p===void 0&&S("TOOL_INVALID","A stateful local App requires an action tool name"),p!==void 0&&p===l&&S("TOOL_ID_CONFLICT",`Local App read and action tools share a name: ${l}`);let u=Kc(e.runtime);u.some(N=>N.name===l||N.name===p)&&S("TOOL_ID_CONFLICT","Local App read or action tool conflicts with a requested Host capability");let f={name:l,description:`${t} current state`,inputSchema:Jc,textFallback:`${t} current state is available through its open instance.`,visibility:Object.freeze(["model","app"]),kind:"read",resourceBinding:Fe},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:Fe,actionIds:Object.freeze([...c])};g.push(Object.freeze(N));}let _=[],P=new Set(g.map(N=>N.name));if(p!==void 0)for(let N of e.actions){let C=`${p}__${N.actionId}`;if(C.length>128||!Fo.test(C)){_.push(Object.freeze({toolName:C,actionId:N.actionId,reason:"name_too_long"}));continue}if(P.has(C)){_.push(Object.freeze({toolName:C,actionId:N.actionId,reason:"name_collision"}));continue}let F=xo({actionId:N.actionId,confirmation:r.actions[N.actionId]?.confirmation,content:r.actions[N.actionId]?.content,backend:N.backend},e.modelActions),D=Object.freeze(F==="denied"?["app"]:["model","app"]),b={name:C,description:`${C} action`,inputSchema:Dn(N.inputSchema),textFallback:`${C} action requests are handled by the open App instance.`,visibility:D,kind:"action",resourceBinding:Fe,actionId:N.actionId,actionIds:Object.freeze([N.actionId]),_meta:Object.freeze({ui:Object.freeze({visibility:D})})};g.push(Object.freeze(b)),P.add(C);}let U={mimeType:ni,entryHash:s,html:o,bytes:Object.freeze([...a]),...d===void 0?{}:{initialState:Object.freeze({hash:d.hash,bytes:Object.freeze([...d.bytes])})}},k={appId:n,name:t,description:i,...e.icon===void 0?{}:{icon:Jo(e.icon)},...e.tone===void 0?{}:{tone:Ko(e.tone)},builtinOnly:false,definition:r,...e.runtime===void 0?{}:{runtime:Object.freeze({...e.runtime})},resourceBinding:Fe,resource:Object.freeze(U),tools:Object.freeze(g),toolDiagnostics:Object.freeze(_)};return Q(k)}function $o(e={}){return new ti(e)}function oi(e){if(e.length===0)return Dn({type:"object",properties:{},additionalProperties:false});let n=e.map(i=>i.actionId),t=new Map;for(let i of e)t.set(i.actionId,Dn(i.inputSchema));return Dn(Zc(n,t),Bo)}function qc(e){let n=e.definition.dataPaths??[];if(e.initialStateBytes===void 0){e.initialStateHash!==void 0&&S("STATE_INVALID","Initial state hash has no bytes"),e.initialState!==void 0&&ye(e.initialState,0,n);return}e.initialStateHash===void 0&&S("STATE_INVALID","Initial state bytes require a hash");let t=Kn(e.initialStateHash,"Initial state hash"),i=Yn(e.initialStateBytes,"Initial state bytes");Xn(i)!==t&&S("STATE_INVALID","Initial state bytes do not match the hash");let r;try{let o=new TextDecoder("utf-8",{fatal:!0}).decode(Uint8Array.from(i));r=ye(JSON.parse(o),0,n);}catch{S("STATE_INVALID","Initial state bytes are not projection-safe JSON");}return e.initialState!==void 0&&te(r)!==te(ye(e.initialState,0,n))&&S("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=bn(e),t=Ve(n.appId,"APP_ID_INVALID","MCP App id"),i=ii(n.html);Ho(n.uiUri);let r=n.definition===void 0?void 0:qn(n.definition),o=e.provenance;o!==void 0&&(!cn(o)||o.appId!==t||o.definitionId!==r?.id||o.version!==r?.version||o.definitionHash!==r?.hash)&&S("TOOL_INVALID","Product App built-in registration provenance is not verified");let s=Object.freeze(n.tools.map(c=>Q(bn(c)))),a=Q({...n,appId:t,html:i,...r===void 0?{}:{definition:r},...o===void 0?{}:{provenance:o},tools:s}),d=Q({uri:a.uiUri,mimeType:wo,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,...r===void 0?{}:{definition:r},resourceBinding:Object.freeze({kind:"mcp",uri:a.uiUri}),resource:d,tools:s,descriptor:a})}function ed(e){(e.resourceBinding.kind!=="instance"||e.builtinOnly!==false)&&S("STATE_INVALID","Local App registration binding is invalid"),Object.prototype.hasOwnProperty.call(e,"uiUri")&&S("STATE_INVALID","Local App registration cannot contain uiUri");let n=Ve(e.appId,"APP_ID_INVALID","Local App id"),t=qn(e.definition),i=e.provenance;i!==void 0&&(!cn(i)||i.appId!==n||i.definitionId!==t.id||i.version!==t.version||i.definitionHash!==t.hash)&&S("TOOL_INVALID","Product App local registration provenance is not verified");let r=ii(e.resource.html),o=Kn(e.resource.entryHash,"Local App entry hash"),s=Yn(e.resource.bytes,"Local App entry bytes");(Xn(s)!==o||Wo(s)!==r)&&S("HTML_INVALID","Local App entry bytes do not match the HTML hash");let a=e.resource.initialState===void 0?void 0:{hash:Kn(e.resource.initialState.hash,"Initial state hash"),bytes:Yn(e.resource.initialState.bytes,"Initial state bytes")};a&&Xn(a.bytes)!==a.hash&&S("STATE_INVALID","Initial state bytes do not match the hash");let d=e.tools.map(c=>{Ve(c.name,"TOOL_ID_INVALID","Local App tool name"),Nn(c.description,"Local App tool description","Local App tool"),Xc(c.textFallback);let l=Dn(c.inputSchema,c.kind==="action"&&!("actionId"in c)?Bo:0);if((c.resourceBinding.kind!=="instance"||Object.prototype.hasOwnProperty.call(c,"resourceUri"))&&S("TOOL_INVALID","Local App tools cannot carry an MCP resource URI"),c.kind==="host")return (!Wc.has(c.name)||c.visibility.length!==1||c.visibility[0]!=="app"||Object.prototype.hasOwnProperty.call(c,"actionId"))&&S("TOOL_INVALID","Local App Host tools must use an allow-listed name and app-only visibility"),Q({...c,inputSchema:l,visibility:Object.freeze(["app"])});if(c.kind==="action"){if("actionId"in c){let u=Ve(c.actionId,"TOOL_ID_INVALID","Local App action id");Object.prototype.hasOwnProperty.call(t.actions,u)||S("TOOL_INVALID","Local App action tool references an undeclared action");let f=Yc(c._meta.ui.visibility);return JSON.stringify(f)!==JSON.stringify(c.visibility)&&S("TOOL_INVALID","Local App action metadata visibility must match the tool visibility"),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)))&&S("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:Nn(e.name,"Local App name",e.appId),description:Nn(e.description,"Local App description",e.name),...e.icon===void 0?{}:{icon:Jo(e.icon)},...e.tone===void 0?{}:{tone:Ko(e.tone)},builtinOnly:false,definition:t,...e.runtime===void 0?{}:{runtime:Object.freeze({...e.runtime})},...i===void 0?{}:{provenance:i},resourceBinding:Fe,resource:Q({mimeType:ni,entryHash:o,html:r,bytes:Object.freeze([...s]),...a===void 0?{}:{initialState:Object.freeze({hash:a.hash,bytes:Object.freeze([...a.bytes])})}}),tools:Object.freeze(d),toolDiagnostics:Object.freeze([...e.toolDiagnostics??[]])})}function 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:Go(e.definition),...e.provenance===void 0?{}:{provenance:e.provenance},entryHash:e.resource.entryHash,resourceBinding:Fe,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:Go(e.definition)},resourceBinding:Object.freeze({kind:"mcp",uri:e.uiUri}),tools:e.tools})}function qn(e){try{if(Object.isFrozen(e))return Ae(e),Q(e);let n=bn(e);return Ae(n),Q(n)}catch(n){if(n instanceof be)throw n;S("STATE_INVALID","UI definition is not a valid immutable definition");}}function Go(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 jo(e,n,t){return `${e}\0${n}\0${t}`}function Kn(e,n){return (typeof e!="string"||!Bc.test(e))&&S("SERIALIZATION_INVALID",`${n} is invalid`),e}function Xn(e){return createHash("sha256").update(Uint8Array.from(e)).digest("hex")}function Yn(e,n){return (!Array.isArray(e)||e.some(t=>!Number.isInteger(t)||t<0||t>255))&&S("SERIALIZATION_INVALID",`${n} is invalid`),[...e]}function Wo(e){try{return new TextDecoder("utf-8",{fatal:!0}).decode(Uint8Array.from(e))}catch{S("SERIALIZATION_INVALID","UTF-8 bytes are invalid");}}function Jo(e){return (typeof e!="string"||!$c.test(e))&&S("TOOL_INVALID","MCP App icon is invalid"),e}function Ko(e){return (typeof e!="string"||!Gc.has(e))&&S("TOOL_INVALID","MCP App tone is invalid"),e}function bn(e,n=new Map){if(e===null||typeof e!="object")return e;let t=e;if(n.has(t)&&S("SERIALIZATION_INVALID","MCP App value contains a cycle"),Array.isArray(e)){let o=[];n.set(t,o);for(let s of e)o.push(bn(s,n));return n.delete(t),o}let i;try{i=Object.getPrototypeOf(e);}catch{S("SERIALIZATION_INVALID","MCP App value cannot be cloned");}i!==Object.prototype&&i!==null&&S("SERIALIZATION_INVALID","MCP App value must be plain JSON");let r={};n.set(t,r);for(let[o,s]of Object.entries(e))Object.defineProperty(r,o,{configurable:true,enumerable:true,value:bn(s,n),writable:true});return n.delete(t),r}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 Fo,Vo,Bc,dn,Hc,zc,$c,Gc,Wc,Fe,Jc,Bo,ti,Zn=B(()=>{m();Do();He();Le();Jn();Wn();ei();ko();vo();Fo=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,Vo=/^ui:\/\/crewx\/([A-Za-z][A-Za-z0-9._-]{0,127})\/([0-9a-f]{12})$/,Bc=/^[0-9a-f]{64}$/,dn=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(Co),new Set(Uo),Fe=Object.freeze({kind:"instance"}),Jc=Object.freeze({type:"object",properties:Object.freeze({}),additionalProperties:false});Bo=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=[],r=[],o=[],s=new Set,a=new Set;for(let p of t?.listMcpApps()??[]){let u=Qc(p);s.has(u.appId)&&S("APP_ID_CONFLICT",`MCP App id is already registered: ${u.appId}`),s.add(u.appId);let f=u.tools;for(let g of f)a.has(g.name)&&S("TOOL_ID_CONFLICT",`MCP App tool name is already registered: ${g.name}`),a.add(g.name),this.mcpToolByName.set(g.name,g),o.push(g);this.mcpResources.set(u.resource.uri,u.resource),i.push(u),r.push(u.descriptor);}let d=(n.localApps??n.locals??[]).map(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)&&S("APP_ID_CONFLICT",`MCP App id is already registered: ${u.appId}`),s.add(u.appId);let f=[],g=[...u.toolDiagnostics??[]];for(let _ of u.tools){if(a.has(_.name)){if(_.kind==="host"&&this.localToolByName.get(_.name)?.kind==="host"){f.push(_);continue}if(_.kind==="action"&&"actionId"in _){g.push(Object.freeze({toolName:_.name,actionId:_.actionId,reason:"name_collision"}));continue}S("TOOL_ID_CONFLICT",`MCP App tool name is already registered: ${_.name}`);}if(_.kind==="action"&&"actionId"in _&&c.has(_.name)){g.push(Object.freeze({toolName:_.name,actionId:_.actionId,reason:"name_collision"}));continue}a.add(_.name),this.localToolByName.set(_.name,_),f.push(_);}(f.length!==u.tools.length||g.length!==(u.toolDiagnostics?.length??0))&&(u=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(r),this.builtinTools=Object.freeze(o);}getMcpApp(n){return this.builtinApps.find(t=>t.appId===n)?.descriptor??null}listMcpApps(){return this.builtinDescriptors}listMcpAppTools(){return this.builtinTools}resolveMcpAppTool(n){return this.mcpToolByName.get(n)??null}resolveMcpAppResource(n){return typeof n!="string"||!Vo.test(n)?null:this.mcpResources.get(n)??null}requireMcpAppResource(n){Ho(n);let t=this.mcpResources.get(n);return t||S("RESOURCE_NOT_FOUND",`MCP App resource is not registered: ${n}`),t}listLocalMcpApps(){return this.localApps}getLocalMcpApp(n){return this.localById.get(n)??null}listLocalMcpAppTools(){return Object.freeze([...this.localToolByName.values()])}resolveLocalMcpAppTool(n){return this.localToolByName.get(n)??null}resolveLocalMcpAppResource(n,t){let i=this.localById.get(n);return !i||t!==void 0&&i.definition.hash!==t?null:i.resource}listRegistrations(){return Object.freeze([...this.builtinApps,...this.localApps])}getRegistration(n){return this.registrationById.get(n)??null}listLaunchers(){return Object.freeze([...this.launcherById.values()].filter(n=>{let t=this.registrationById.get(n.appId),i=t?"descriptor"in t?t.descriptor.provenance:t.provenance:void 0,r=cn(i)&&i.launcher===false;return t?.definition?.usage!=="card"&&!r}))}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(jo(n,t,i))??null}addDefinition(n){let t=qn(n),i=Ot(t),r=this.definitionByKey.get(i);r&&r.hash!==t.hash&&S("STATE_INVALID",`UI definition generation conflicts: ${i}`),r||this.definitionByKey.set(i,t);}addHandler(n){(!n||typeof n.definitionId!="string"||typeof n.actionId!="string"||!Number.isSafeInteger(n.version)||n.version<1||typeof n.handle!="function")&&S("STATE_INVALID","UI action handler registration is invalid");let t=jo(n.definitionId,n.version,n.actionId);this.handlerByKey.has(t)&&S("TOOL_INVALID",`Duplicate UI action handler registration: ${t}`),this.handlerByKey.set(t,Object.freeze({...n}));}};});function od(e){let n=zo({appId:e.appId,name:e.name,description:e.description,...e.icon===void 0?{}:{icon:e.icon},...e.tone===void 0?{}:{tone:e.tone},...e.normalized.manifest.runtime===void 0?{}:{runtime:e.normalized.manifest.runtime},definition:e.definition,html:e.html,entryHash:e.entryHash,entryBytes:e.entryBytes,initialState:e.initialState,...e.initialStateHash===void 0?{}:{initialStateHash:e.initialStateHash},...e.initialStateBytes===void 0?{}:{initialStateBytes:e.initialStateBytes},readToolName:e.toolNames.read,...e.toolNames.action===void 0?{}:{actionToolName:e.toolNames.action},actions:e.normalized.manifest.actions.map(i=>({actionId:i.actionId,inputSchema:i.inputSchema,backend:i.backend}))});return e.provenance===void 0?n:Object.freeze({...n,provenance:e.provenance})}function Xo(e){let n=e.normalized.manifest.actions;if(n.some(i=>i.backend.type==="skill")&&n.some(i=>i.backend.type==="core"))throw new Error("Mixed workspace App execution models");let t=od(e);$o({localApps:[t],definitions:[e.definition]});}var Yo=B(()=>{m();Zn();});function rd(e){if(e===null||typeof e!="object"||!(qo in e))throw new TypeError("scanCache must be created by createWorkspaceAppScanCache");return e[qo]}function Zo(e,n){let t=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 qo,Qo=B(()=>{m();qo=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 M("NOT_FOUND"):n==="ELOOP"?new M("PATH_ESCAPED"):n==="EFBIG"||n==="EOVERFLOW"?new M("LIMIT_EXCEEDED"):n==="EACCES"||n==="EPERM"||n==="ENOTDIR"?new M("READ_DENIED"):new M("READ_DENIED")}function dd(e){if(typeof e!="string"||e.length===0||!isAbsolute(e))throw new M("READ_DENIED")}function ri(e){if(typeof e!="string"||isAbsolute(e)||/[\\\u0000]/.test(e))throw new M("PATH_ESCAPED");if(e==="")return [];let n=e.split("/");if(n.some(t=>t.length===0||t==="."||t===".."))throw new M("PATH_ESCAPED");return n}function tt(e,n){let t=relative(e,n);return t===""||t!==".."&&!t.startsWith(`..${sep}`)&&!isAbsolute(t)}function ln(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 Qn(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 M("READ_DENIED");return {realRoot:n,identity:ln(t)}}async function tr(e,n,t){if(t.length<2||t[0]!=="apps"&&t[0]!=="skills")return;let i,r;try{if(i=resolve(e,t[0],t[1]),r=await realpath(i),!(await stat(r,{bigint:!0})).isDirectory())throw new M("READ_DENIED")}catch(o){throw o instanceof M?o:ue(o)}if(!tt(n,r))throw new M("PATH_ESCAPED");return r}async function et(e,n,t,i){let r,o,s;try{r=await lstat(e,{bigint:!0}),o=await realpath(e),s=await stat(o,{bigint:!0});}catch(a){throw ue(a)}if(!tt(n,o)||t!==void 0&&!tt(t,o))throw new M("PATH_ESCAPED");if(!r.isFile()||!s.isFile())throw new M("READ_DENIED");if(!di(i,r)||!di(i,s)||i.dev!==s.dev)throw new M("PATH_ESCAPED")}async function pn(e,n){let t,i;try{t=await realpath(e),i=await stat(t,{bigint:!0});}catch{throw new M("PATH_ESCAPED")}if(t!==n.realRoot||!pi(n.identity,ln(i)))throw new M("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 M,ci,cd,nr,it,ir,ui=B(()=>{m();M=class extends Error{constructor(t){super(t);this.code=t;}code;name="AppDiscoveryFsError"},ci=constants.O_NOFOLLOW,cd=constants.O_NONBLOCK,nr=constants.O_RDONLY|(ci??0)|(cd??0);it=class{async getRootIdentity(n){let t=await Qn(n);return await pn(n,t),{dev:t.identity.dev,ino:t.identity.ino,realPath:t.realRoot}}async listDirectory(n,t){let i=ri(t),r=await Qn(n),o=resolve(n,...i),s,a;try{s=await realpath(o),a=await stat(s,{bigint:!0});}catch(d){let c=ue(d);if(c.code==="NOT_FOUND")return [];throw c}if(!tt(r.realRoot,s)||!a.isDirectory())throw new M("PATH_ESCAPED");try{let d=await readdir(s,{withFileTypes:!0,encoding:"utf8"});return await pn(n,r),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 M("READ_DENIED");if(ci===void 0)throw new M("UNSUPPORTED");let r=ri(t),o=await Qn(n),s=resolve(n,...r),a=relative(n,s);if(a===".."||a.startsWith(`..${sep}`)||isAbsolute(a))throw new M("PATH_ESCAPED");let d;try{d=await open(s,nr);}catch(c){throw ue(c)}try{let c;try{let g=await d.stat({bigint:!0});c=ln(g);}catch(g){throw ue(g)}if(c.size>BigInt(i))throw new M("LIMIT_EXCEEDED");if(c.size>BigInt(Number.MAX_SAFE_INTEGER))throw new M("LIMIT_EXCEEDED");await pn(n,o);let l=await tr(n,o.realRoot,r);await et(s,o.realRoot,l,c);let p=new Uint8Array(new ArrayBuffer(Number(c.size))),u=0;for(;u<p.byteLength;){let g;try{g=(await d.read(p,u,p.byteLength-u,u)).bytesRead;}catch(_){throw ue(_)}if(g<=0)throw new M("IDENTITY_CHANGED");u+=g;}let f;try{let g=await d.stat({bigint:!0});f=ln(g);}catch(g){throw ue(g)}if(!pi(c,f))throw new M("IDENTITY_CHANGED");return await et(s,o.realRoot,l,f),await pn(n,o),new Uint8Array(p)}finally{await d.close().catch(()=>{});}}async fingerprintVerifiedFile(n,t,i){if(!Number.isSafeInteger(i)||i<0)throw new M("READ_DENIED");if(ci===void 0)throw new M("UNSUPPORTED");let r=ri(t),o=await Qn(n),s=resolve(n,...r),a=relative(n,s);if(a===".."||a.startsWith(`..${sep}`)||isAbsolute(a))throw new M("PATH_ESCAPED");let d;try{d=await open(s,nr);}catch(c){throw ue(c)}try{let c;try{let u=await d.stat({bigint:!0});c=ln(u);}catch(u){throw ue(u)}if(c.size>BigInt(i)||c.size>BigInt(Number.MAX_SAFE_INTEGER))throw new M("LIMIT_EXCEEDED");await pn(n,o);let l=await tr(n,o.realRoot,r);await et(s,o.realRoot,l,c);let p;try{let u=await d.stat({bigint:!0});p=ln(u);}catch(u){throw ue(u)}if(!pi(c,p))throw new M("IDENTITY_CHANGED");return await et(s,o.realRoot,l,p),await pn(n,o),{...p,candidateRealPath:l??o.realRoot}}catch(c){throw c instanceof M?c:ue(c)}finally{await d.close().catch(()=>{});}}async readFileVerified(n,t,i){return this.readVerifiedFile(n,t,i)}},ir=new it;});function On(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;try{let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}catch{return false}}function rr(e){return typeof e=="string"&&Te.test(e)?e:void 0}function gd(e){return e.length>0&&e!=="."&&e!==".."&&!/[\\/\u0000]/.test(e)}function Je(e,n){let t=new TextEncoder().encode(e),i=new TextEncoder().encode(n),r=Math.min(t.byteLength,i.byteLength);for(let o=0;o<r;o+=1){let s=t[o]-i[o];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 r=n.isFile;return typeof r=="function"&&r.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 sr(e){switch(e){case "ENOENT":return "NOT_FOUND";case "ELOOP":case "EXDEV":return "PATH_ESCAPED";case "EFBIG":case "EOVERFLOW":return "LIMIT_EXCEEDED";case "EACCES":case "EPERM":case "ENOTDIR":return "READ_DENIED";default:return e}}function Td(e){if(e instanceof M)return sr(e.code);if(e!==null&&typeof e=="object"&&"code"in e){let n=e.code;if(typeof n=="string")return sr(n)}}function Re(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 ar(e,n,t,i){let r=Pd(e);if(!r)throw new M("READ_DENIED");return hd(await r.call(e,n,t,i))}async function Ai(e,n,t){let i=Nd(e);if(!i)throw new M("READ_DENIED");let r=await i.call(e,n,t);if(!Array.isArray(r))throw new M("READ_DENIED");return r.map(md).filter(o=>o!==null)}function Dd(e,n,t,i){return Object.freeze({code:e,...{},source:n,relativePath:t})}function bd(e){if(!On(e))throw new TypeError("productBundle.reservedIds must be an object with appIds and definitionIds arrays");try{let n=Reflect.ownKeys(e);if(n.length!==2||!n.includes("appIds")||!n.includes("definitionIds"))throw new TypeError("productBundle.reservedIds must contain exactly appIds and definitionIds");let t=(i,r)=>{if(!Array.isArray(i))throw new TypeError("productBundle.reservedIds."+r+" must be an array");let o=[];for(let s=0;s<i.length;s+=1){let a=i[s];if(typeof a!="string"||a.length===0)throw new TypeError("productBundle.reservedIds."+r+" must contain non-empty strings");o.push(a);}return Object.freeze([...new Set(o)].sort(Je))};return Object.freeze({appIds:t(e.appIds,"appIds"),definitionIds:t(e.definitionIds,"definitionIds")})}catch(n){throw n instanceof TypeError?n:new TypeError("productBundle.reservedIds must be a valid reservation object")}}function 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 rt(e){return Object.freeze({appIds:Object.freeze([...new Set(e.map(n=>n.appId))].sort(Je)),definitionIds:Object.freeze([...new Set(e.map(n=>n.definition.id))].sort(Je))})}function ot(e,n){let t=Object.keys(e).sort(Je),i=[...n].sort(Je);return t.length===i.length&&t.every((r,o)=>r===i[o])}function cr(e){if(typeof e!="string"||e.length===0||e.startsWith("/")||/[\\\u0000]/.test(e))return;let n=e.split("/");if(!n.some(t=>t.length===0||t==="."||t===".."))return n}function Md(e){let n;try{n=Ed(e);}catch{return}if(!On(n)||!ot(n,["version","packages"])||n.version!==1||!Array.isArray(n.packages)||n.packages.length>Ii)return;let t=new Set,i=new Set,r=0,o=[];for(let s of n.packages){if(!On(s))return;let a=["packageDir","appId","definition","files"],d=Object.hasOwn(s,"lineage"),c=Object.hasOwn(s,"launcher"),l=[...d?["lineage"]:[],...c?["launcher"]:[]];if(!ot(s,[...a,...l])||c&&s.launcher!==false)return;let p=cr(s.packageDir),u=rr(s.appId);if(!p||p.length!==2||p[0]!=="apps"||!gd(p[1])||!u||t.has(s.packageDir)||!On(s.definition)||!ot(s.definition,["id","version","hash"]))return;let f=rr(s.definition.id),g=s.definition.version,_=s.definition.hash;if(!f||!Number.isSafeInteger(g)||g<1||typeof _!="string"||!yi.test(_)||!Array.isArray(s.files)||s.files.length<2||s.files.length>gi)return;let P=new Set,U=[];for(let k of s.files){if(!On(k)||!ot(k,["path","sha256"]))return;let N=cr(k.path);if(!N||typeof k.sha256!="string"||!yi.test(k.sha256))return;let C=N.join("/"),F=`${s.packageDir}/${C}`;if(P.has(C)||i.has(F))return;P.add(C),i.add(F),U.push(Object.freeze({path:C,sha256:k.sha256}));}if(!Z.some(k=>P.has(k))||!P.has("ui/index.html")||(r+=U.length,r>ud))return;t.add(s.packageDir),o.push(Object.freeze({packageDir:s.packageDir,...c?{launcher:false}:{},appId:u,definition:Object.freeze({id:f,version:g,hash:_}),lineage:Array.isArray(s.lineage)?s.lineage:[],files:Object.freeze(U.sort((k,N)=>Je(k.path,N.path)))}));}return Object.freeze({version:1,packages:Object.freeze(o)})}function We(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,r){let o=[],s=async(a,d)=>{if(!Re(i,r))throw new M("LIMIT_EXCEEDED");if(d>2)throw new M("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 M("PATH_ESCAPED");let p=`${a}/${l.name}`;if(l.kind==="file"){if(o.push(p.slice(t.length+1)),o.length>gi)throw new M("LIMIT_EXCEEDED")}else if(l.kind==="directory")await s(p,d+1);else throw l.kind==="symlink"?new M("PATH_ESCAPED"):new M("READ_DENIED")}};return await s(t,0),o.sort(Je)}function Od(e){return Z.includes(e)?262144:e==="ui/index.html"?dn:e==="ui/state.json"?1048576:e.startsWith("ui/assets/")?yd:fd}async function dr(e,n,t,i){if(e===void 0)return {packages:[],diagnostics:[],incomplete:false,reservedIds:Id};let r=bd(e.reservedIds),o=[],s=(y,I,h)=>Dd(y,"bundled",I),a=(y=[],I=false,h)=>({...h===void 0?{}:{indexHash:h},packages:y,diagnostics:o,incomplete:I,reservedIds:r});if(typeof e.root!="string"||e.root.length===0||typeof e.expectedIndexHash!="string"||!yi.test(e.expectedIndexHash))return o.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a();let d;try{d=await ar(n,e.root,"bundle-index.json",ld);}catch(y){return o.push(s(We(y),"bundle-index.json")),a()}let c=createHash("sha256").update(d).digest("hex");if(c!==e.expectedIndexHash)return o.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a();let l=Md(d);if(l===void 0)return o.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a();if(!Sd(rt(l.packages),r))return o.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a([],false,c);if(!Re(t,i))return o.push(s("LIMIT_EXCEEDED","bundle-index.json")),a(l.packages.map(y=>({indexEntry:y,failureCode:"LIMIT_EXCEEDED"})),true,c);let p;try{p=await Ai(n,e.root,"");}catch(y){return o.push(s(We(y),"bundle-index.json")),a(l.packages.map(I=>({indexEntry:I,failureCode:We(y)})),false,c)}if(!Re(t,i))return o.push(s("LIMIT_EXCEEDED","bundle-index.json")),a(l.packages.map(y=>({indexEntry:y,failureCode:"LIMIT_EXCEEDED"})),true,c);let u=p.find(y=>y.name==="bundle-index.json"&&y.kind==="file"),f=p.find(y=>y.name==="apps"&&y.kind==="directory"),g=y=>l.packages.map(I=>({indexEntry:I,failureCode:y}));if(!u)return o.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a(g("BUNDLE_INTEGRITY"),false,c);let _=p.filter(y=>y.name!=="bundle-index.json"&&y.name!=="apps");if(_.length>0){let y=_.some(I=>I.kind==="symlink")?"PATH_ESCAPED":"BUNDLE_INTEGRITY";return o.push(s(y,"bundle-index.json")),a(g("BUNDLE_INTEGRITY"),false,c)}if(p.some(y=>y.name==="apps"&&y.kind!=="directory"))return o.push(s("PATH_ESCAPED","apps")),a(g("PATH_ESCAPED"),false,c);let P=[];if(f)try{P=await Ai(n,e.root,"apps");}catch(y){return o.push(s(We(y),"apps")),a(g(We(y)),false,c)}if(!Re(t,i)||P.length>Ii)return o.push(s("LIMIT_EXCEEDED","apps")),a(g("LIMIT_EXCEEDED"),true,c);let U=new Map(l.packages.map(y=>[y.packageDir.slice(5),y])),k=P.filter(y=>!U.has(y.name));for(let y of k)o.push(s(y.kind==="symlink"?"PATH_ESCAPED":"BUNDLE_INTEGRITY",`apps/${y.name}`));if(k.length>0){let y=k.some(I=>I.kind==="symlink")?"PATH_ESCAPED":"BUNDLE_INTEGRITY";return a(g(y),false,c)}let N=new Set,C=new Map,F=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)}`,E=F.get(h)??[];E.push(y),F.set(h,E);}for(let y of [...C.values(),...F.values()])if(y.length>1)for(let I of y)N.add(I);let D=[],b=d.byteLength,O=false;for(let y of l.packages){if(!Re(t,i)){O=true,D.push({indexEntry:y,failureCode:"LIMIT_EXCEEDED"});continue}let I;try{let L=y.lineage[y.lineage.length-1];if(!L)throw new Se("LINEAGE_INVALID","Definition lineage is missing");if(L.definition.id!==y.definition.id||L.version!==y.definition.version||L.hash!==y.definition.hash)throw new Se("LINEAGE_STALE","Last lineage generation does not match bundle identity");I=Qt(y.lineage,{...L.definition,hash:L.hash}).entries;}catch(L){let J=L instanceof Se?L.code:"LINEAGE_INVALID";o.push(s(J,y.packageDir)),D.push({indexEntry:y,failureCode:J});continue}let h=P.find(L=>L.name===y.packageDir.slice(5));if(!f||!h){D.push({indexEntry:y,failureCode:"BUNDLE_INTEGRITY"});continue}if(h.kind!=="directory"){D.push({indexEntry:y,failureCode:h.kind==="symlink"?"PATH_ESCAPED":"BUNDLE_INTEGRITY"});continue}let E;try{let L=await Ld(n,e.root,y.packageDir,t,i);if(!Re(t,i)){O=!0,D.push({indexEntry:y,failureCode:"LIMIT_EXCEEDED"});continue}let J=y.files.map(K=>K.path);if(L.length!==J.length||L.some((K,Me)=>K!==J[Me])){D.push({indexEntry:y,failureCode:"BUNDLE_INTEGRITY"});continue}E=new Map;let pe;for(let K of y.files){if(!Re(t,i)){pe="LIMIT_EXCEEDED",O=!0;break}if(b>=fi){pe="LIMIT_EXCEEDED";break}let Me;try{Me=await ar(n,e.root,`${y.packageDir}/${K.path}`,Od(K.path));}catch(As){pe=We(As);break}if(!Re(t,i)){pe="LIMIT_EXCEEDED",O=!0;break}if(b+Me.byteLength>fi){b=fi,pe="LIMIT_EXCEEDED";break}if(b+=Me.byteLength,createHash("sha256").update(Me).digest("hex")!==K.sha256){pe="BUNDLE_INTEGRITY";break}E.set(K.path,Me);}if(pe!==void 0){D.push({indexEntry:y,failureCode:pe});continue}}catch(L){Re(t,i)||(O=true),D.push({indexEntry:y,failureCode:We(L)});continue}D.push({indexEntry:y,lineage:I,files:E,...N.has(y)?{failureCode:"DUPLICATE_ID"}:{}});}return a(D,O,c)}var ld,Ii,gi,ud,fd,yd,fi,yi,Ad,Id,mi=B(()=>{m();ei();Be();$n();Zn();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"||!Te.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 lr(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;try{let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}catch{return false}}function Ud(e,n){return n.length===0||n==="."||n===".."||/[\\/\u0000]/.test(n)?e==="skills"?"skills":"apps":`${e==="skills"?"skills":"apps"}/${n}`}function kd(e){return e.length>0&&e!=="."&&e!==".."&&!/[\\/\u0000]/.test(e)}function Rn(e,n){let t=new TextEncoder().encode(e),i=new TextEncoder().encode(n),r=Math.min(t.byteLength,i.byteLength);for(let o=0;o<r;o+=1){let s=t[o]-i[o];if(s!==0)return s}return t.byteLength-i.byteLength}function Tr(e){if(typeof e=="string")return {name:e,kind:"directory"};if(e===null||typeof e!="object")return null;let n=e;if(typeof n.name!="string")return null;if(n.kind==="file"||n.kind==="directory"||n.kind==="symlink"||n.kind==="other")return {name:n.name,kind:n.kind};if(n.type==="file"||n.type==="directory"||n.type==="symlink"||n.type==="other")return {name:n.name,kind:n.type};let t=n.isDirectory;if(typeof t=="function"&&t.call(e))return {name:n.name,kind:"directory"};let i=n.isSymbolicLink;if(typeof i=="function"&&i.call(e))return {name:n.name,kind:"symlink"};let r=n.isFile;return typeof r=="function"&&r.call(e)?{name:n.name,kind:"file"}:{name:n.name,kind:"other"}}function 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 Pr(e){return Cd.decode(e)}function vd(e){return JSON.parse(Pr(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 at(e,n,t,i,r){let o={code:e,...i===void 0?{}:{pluginId:i},source:n,relativePath:t,...r?.reason===void 0?{}:{reason:Object.freeze({...r.reason})},...r?.files===void 0?{}:{files:Object.freeze([...r.files])}};return Object.freeze(o)}function ur(e){switch(e){case "ENOENT":return "NOT_FOUND";case "ELOOP":case "EXDEV":return "PATH_ESCAPED";case "EFBIG":case "EOVERFLOW":return "LIMIT_EXCEEDED";case "EACCES":case "EPERM":case "ENOTDIR":return "READ_DENIED";default:return e}}function ae(e){if(e instanceof M)return ur(e.code);if(e!==null&&typeof e=="object"&&"code"in e){let n=e.code;if(typeof n=="string")return ur(n)}}function Xe(e,n){return e==="PATH_ESCAPED"||e==="IDENTITY_CHANGED"||e==="TOCTOU"?"PATH_ESCAPED":e==="LIMIT_EXCEEDED"?"LIMIT_EXCEEDED":n==="manifest"&&e==="NOT_FOUND"?"MANIFEST_MISSING":n==="entry"?"ENTRY_INVALID":n==="initial"?"INITIAL_STATE_INVALID":"MANIFEST_INVALID"}function fr(e){return {reason:e.reason,...e.code==="MANIFEST_DUAL_MISMATCH"?{files:e.files}:{}}}function yr(e){return e==="MANIFEST_DUAL_MISMATCH"?e:Nr(e)}function Fd(e){return Nr(e.code)}function Nr(e){switch(e){case "MANIFEST_INVALID":case "PRIMITIVE_UNKNOWN":case "PRIMITIVE_SET_UNSUPPORTED":case "SCHEMA_TYPE_UNSUPPORTED":case "TOKEN_INVALID":case "UNSAFE_VALUE":return "MANIFEST_INVALID";case "LIMIT_EXCEEDED":return "LIMIT_EXCEEDED";case "INITIAL_STATE_INVALID":return "INITIAL_STATE_INVALID";default:return Dr("UiPluginValidationError",e)}}function Dr(e,n){throw new Error(`Unmapped ${e} code: ${String(n)}`)}function br(e){switch(e){case "APP_ID_INVALID":case "TOOL_ID_INVALID":case "RESOURCE_URI_INVALID":case "TOOL_INVALID":case "SERIALIZATION_INVALID":return "MANIFEST_INVALID";case "APP_ID_CONFLICT":case "TOOL_ID_CONFLICT":return "DUPLICATE_ID";case "RESOURCE_NOT_FOUND":case "HTML_INVALID":return "ENTRY_INVALID";case "STATE_INVALID":case "STATE_PROJECTION_INVALID":case "BUTTON_INVALID":return "INITIAL_STATE_INVALID";default:return Dr("McpAppContractError",e)}}function we(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 r=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(t));if(lr(r)){let o=r.bin,s=typeof o=="string"?o:lr(o)?Object.values(o).find(a=>typeof a=="string"):void 0;for(let a of [s,r.main]){if(typeof a!="string")continue;let d=Hd(a);if(d&&n.has(d))return d}}}catch{}return [`${e.slice(e.lastIndexOf("/")+1)}.js`,"index.js","main.js"].find(r=>n.has(r))}function 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 Ke(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let n of Object.values(e))Ke(n);return Object.freeze(e)}function Ar(e){return Object.freeze(Array.from(e))}async function ct(e,n,t,i){if(n.pinnedFiles!==void 0){let a=n.pinnedFiles.get(t);if(a===void 0)throw new M("NOT_FOUND");if(a.byteLength>i)throw new M("LIMIT_EXCEEDED");return new Uint8Array(a)}let r=`${n.relativePath}/${t}`,o=n.scanContext,s=e.fingerprintVerifiedFile;if(o===void 0||!o.cacheable||typeof s!="function")return hr(e,n.root,r,i);try{let a=o.priorFingerprints.get(r)??await s.call(e,o.workspaceRoot,r,i);o.candidateRealPath=a.candidateRealPath;let d=await hr(e,n.root,r,i),c=await s.call(e,o.workspaceRoot,r,i);return o.candidateRealPath=c.candidateRealPath,Mr(a,c)&&c.size===BigInt(d.byteLength)&&!Lr(c,o.scanStartedAtNs)?o.files.set(r,{relativePath:r,byteLimit:i,fingerprint:c}):o.cacheable=!1,d}catch(a){let d=Z.includes(t)&&ae(a)==="NOT_FOUND"&&o.directoryListings.some(l=>l.relativePath===n.relativePath&&!dt(l.key,t)),c=t===H&&ae(a)==="NOT_FOUND"&&$d(o.directoryListings,n.relativePath);throw !d&&!c&&(o.cacheable=false),a}}function $d(e,n){let t=e.find(r=>r.relativePath===n);if(t===void 0)return false;if(!dt(t.key,"dist"))return true;let i=e.find(r=>r.relativePath===`${n}/dist`);return i!==void 0&&!dt(i.key,"tools.json")}function Sr(e,n){return JSON.stringify([e.realPath,n.source,n.relativePath])}async function Wd(e,n,t,i,r,o,s,a){let d=e.fingerprintVerifiedFile,c=Sr(t,i),l=r.candidates.get(c),p=i.relativePath,u;try{u=await mr(e,n,p);}catch(O){if(ae(O)!=="NOT_FOUND")throw O}let f=u===void 0?void 0:{relativePath:p,key:u};if(f!==void 0&&(i.source==="apps"||i.source==="skills")&&!Z.some(O=>dt(f.key,O)))return we(s,a)?l!==void 0&&l.candidate===void 0&&l.candidateRealPath===void 0&&l.files.length===0&&l.directoryListings.length===1&&l.directoryListings[0]?.relativePath===f.relativePath&&l.directoryListings[0]?.key===f.key&&(i.source==="apps"?l.diagnostic?.code==="MANIFEST_MISSING":l.diagnostic===void 0)&&typeof d=="function"?{memo:l}:typeof d!="function"?{}:{context:{state:r,cacheKey:c,workspaceRoot:n,scanStartedAtNs:o,directoryListings:Object.freeze([f]),priorFingerprints:new Map,files:new Map,cacheable:true}}:{timeLimitReached:true};let g=async O=>{if(O==="")return f;let y=`${i.relativePath}${O}`;try{let I=await mr(e,n,y);return I===void 0?void 0:{relativePath:y,key:I}}catch(I){if(ae(I)==="NOT_FOUND")return;throw I}},_=await Promise.all(Ir.map(g)),P=await Promise.all(Gd.map(g));if(!we(s,a))return {timeLimitReached:true};let U=typeof d=="function"&&_.every(O=>O!==void 0),k=_.filter(O=>O!==void 0),N=[...k,...P.filter(O=>O!==void 0)],C=new Map,F=l!==void 0&&U,D;if(l!==void 0&&typeof d=="function"){let O=await Promise.all(l.files.map(async y=>{if(!we(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(O.some(y=>y.kind==="time"))return {timeLimitReached:true};for(let y of O){if(y.kind==="error")throw y.error;if(y.kind==="missing"){F=false;continue}if(y.kind!=="fingerprint")continue;let{file:I,current:h}=y;C.set(I.relativePath,h),D??=h.candidateRealPath,(h.candidateRealPath!==l.candidateRealPath||!Mr(h,I.fingerprint)||Lr(h,o))&&(F=false);}}let b=l!==void 0&&l.directoryListings.length===N.length&&l.directoryListings.every((O,y)=>O.relativePath===N[y]?.relativePath&&O.key===N[y]?.key);return l!==void 0&&U&&b&&F&&D===l.candidateRealPath?{memo:l}:!U||k.length!==Ir.length?{}:{context:{state:r,cacheKey:c,workspaceRoot:n,scanStartedAtNs:o,directoryListings:Object.freeze(N),priorFingerprints:C,files:new Map,...D===void 0?{}:{candidateRealPath:D},cacheable:true}}}function dt(e,n){try{let t=JSON.parse(e);return Array.isArray(t)&&t.some(i=>Array.isArray(i)&&i[0]===n)}catch{return true}}async function mr(e,n,t){let i=Or(e);if(typeof i!="function")return;let r=await i.call(e,n,t);if(!Array.isArray(r)||r.some(s=>typeof s=="string"))return;let o=r.map(Tr);if(!o.some(s=>s===null))return JSON.stringify(o.slice().sort((s,a)=>Rn(s.name,a.name)||Rn(s.kind,a.kind)).map(s=>[s.name,s.kind]))}function Mr(e,n){return e.dev===n.dev&&e.ino===n.ino&&e.size===n.size&&e.mtimeNs===n.mtimeNs&&e.ctimeNs===n.ctimeNs}function Lr(e,n){let t=e.mtimeNs-n;return t>=-gr&&t<=gr}function _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,r=t||i;if(n===void 0||!n.cacheable||n.candidateRealPath===void 0&&!r||n.files.size===0&&!r)return;let o=Object.freeze({...!r&&n.candidateRealPath!==void 0?{candidateRealPath:n.candidateRealPath}:{},directoryListings:n.directoryListings,files:Object.freeze([...n.files.values()]),...e.candidate===void 0?{}:{candidate:e.candidate},...e.diagnostic===void 0?{}:{diagnostic:e.diagnostic},...e.identity===void 0?{}:{identity:e.identity},...e.provenance===void 0?{}:{provenance:e.provenance}});n.state.candidates.set(n.cacheKey,o);}function Jd(e,n,t){let i=createHash("sha256"),r=new TextEncoder().encode(te(e)),o=s=>{let a=new Uint8Array(8);new DataView(a.buffer).setBigUint64(0,BigInt(s)),i.update(a);};return o(r.byteLength),i.update(r),o(n.byteLength),i.update(n),o(t.byteLength),i.update(t),i.digest("hex")}function Kd(e,n){let t={...e.definition,sourceHash:n},i;try{i=le(t);}catch(o){throw o instanceof x&&o.code==="INPUT_INVALID"?new se("MANIFEST_INVALID","normalized definition is invalid"):o}let r={...t,hash:i};try{Ae(r);}catch{throw new se("MANIFEST_INVALID","normalized definition is invalid")}return r}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 Or(e){if(typeof e.listDirectory=="function")return e.listDirectory;if(typeof e.readDirectory=="function")return e.readDirectory;if(typeof e.readdir=="function")return e.readdir}async function hr(e,n,t,i){let r=Yd(e);if(!r)throw new M("READ_DENIED");return xd(await r.call(e,n,t,i))}async function qd(e,n,t){let i=Or(e);if(!i)throw new M("READ_DENIED");let r=await i.call(e,n,t);if(!Array.isArray(r))throw new M("READ_DENIED");return r.map(Tr).filter(o=>o!==null)}function Zd(e){let n=[];for(let t of [e.reserved,e.builtin])t&&n.push(t);return e.builtins&&"listMcpApps"in e.builtins?n.push(_r(e.builtins)):e.builtins&&n.push(e.builtins),e.builtinCatalog&&n.push(_r(e.builtinCatalog)),n.push({...e.reservedAppIds===void 0?{}:{appIds:e.reservedAppIds},...e.reservedDefinitionIds===void 0?{}:{definitionIds:e.reservedDefinitionIds},...e.reservedToolNames===void 0?{}:{toolNames:e.reservedToolNames}}),n}function _r(e){let n=[],t=[],i=[];for(let r of e.listMcpApps())typeof r.appId=="string"&&n.push(r.appId),r.definition&&typeof r.definition.id=="string"&&t.push(r.definition.id);for(let r of e.listMcpAppTools())typeof r.name=="string"&&i.push(r.name);return {appIds:n,definitionIds:t,toolNames:i}}function _e(e,n){e.diagnostic||(e.diagnostic=at(n,e.source,e.relativePath,e.identity?.pluginId));}function Qd(e,n){let t=new Set,i=new Map;for(let o of e){let s=o.identity?.pluginId;if(s===void 0)continue;let a=i.get(s)??[];a.push(o),i.set(s,a);}for(let o of i.values()){if(o.length<2)continue;let s=o.filter(d=>d.provenance!==void 0);if(s.length>0){let d=o.find(c=>n.has(c));if(d){for(let c of s)t.add(c);for(let c of o)c!==d&&c.provenance===void 0&&_e(c,"RESERVED_ID");continue}for(let c of o)c.provenance===void 0&&_e(c,"RESERVED_ID");if(s.length>1)for(let c of s)_e(c,"DUPLICATE_ID");continue}let a=o.filter(d=>d.source==="apps");if(a.length>1){for(let d of a)_e(d,"DUPLICATE_ID");for(let d of o.filter(c=>c.source==="skills"))_e(d,"DUPLICATE_ID");}else for(let d of o.filter(c=>c.source==="skills"))_e(d,"DUPLICATE_ID");}let r=new Map;for(let o of e){if(o.diagnostic?.code==="RESERVED_ID"||t.has(o)||o.provenance===void 0&&!n.has(o)&&i.get(o.identity?.pluginId??"")?.some(d=>d.provenance!==void 0))continue;let s=o.identity?.definitionKey;if(s===void 0)continue;let a=r.get(s)??[];a.push(o),r.set(s,a);}for(let o of r.values())if(o.length>1)for(let s of o)_e(s,"DUPLICATE_ID");return t}function ep(e,n,t){let i=new Set,r=new Set,o=new Set,s=new Set([...t.appIds,...n.productBundleReservationMetadata?.reservedAppIds??[]]),a=new Set([...t.definitionIds,...n.productBundleReservationMetadata?.reservedDefinitionIds??[]]);for(let l of Zd(n)){for(let p of l.appIds??[])typeof p=="string"&&i.add(p);for(let p of l.definitionIds??[])typeof p=="string"&&r.add(p);for(let p of l.toolNames??[])typeof p=="string"&&o.add(p);}for(let l of e){let p=l.candidate;if(!p)continue;if(i.has(p.pluginId)||r.has(p.definitionId)){_e(l,"RESERVED_ID");continue}[p.toolNames.read,p.toolNames.action].filter(f=>f!==void 0).some(f=>o.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{Xo(p),c.add(l);}catch(u){_e(l,u instanceof be?br(u.code):"EXEC_DENIED");}}for(let l of e){let p=l.candidate;p&&l.provenance===void 0&&!c.has(l)&&(s.has(p.pluginId)||a.has(p.definitionId))&&_e(l,"RESERVED_ID");}return c}function np(e){return [...e].sort((n,t)=>{let i=pr.indexOf(n.source)-pr.indexOf(t.source);return i!==0?i:Rn(n.relativePath,t.relativePath)})}function V(e,n,t){e.diagnostic=at(n,e.source,e.relativePath,e.identity?.pluginId,t);}async function Er(e,n,t){let i=Ge(t,{mode:"local"});if(!i.ok&&i.parseFailure){V(n,yr(i.rejection.code),fr(i.rejection));return}let r=jd(i.identity);if(n.bundleIdentity===void 0)n.identity=r;else if(r?.pluginId!==n.bundleIdentity.appId||r.definitionKey!==`${n.bundleIdentity.definitionId}\0${String(n.bundleIdentity.version)}`){V(n,"BUNDLE_INTEGRITY");return}if(!i.ok&&i.builtinOnly){V(n,"RESERVED_ID");return}if(!i.ok){V(n,yr(i.rejection.code),fr(i.rejection));return}let o=i.manifest,s={pluginId:o.pluginId,definitionKey:`${o.definitionId}\0${String(o.version)}`};if(n.bundleIdentity===void 0&&(n.identity=s),o.actions.length>0)try{oi(o.actions.map(L=>({actionId:L.actionId,inputSchema:L.inputSchema})));}catch(L){if(L instanceof be){V(n,br(L.code));return}throw L}let a;try{a=await ct(e,n,"ui/index.html",dn);}catch(L){V(n,Xe(ae(L),"entry"));return}if(a.byteLength>dn){V(n,"LIMIT_EXCEEDED");return}let d;try{d=Pr(a);}catch{V(n,"ENTRY_INVALID");return}if(a.byteLength===0||d.length===0){V(n,"ENTRY_INVALID");return}let c=createHash("sha256").update(a).digest("hex");if(o.entryHash!==void 0&&o.entryHash!==c){V(n,"ENTRY_INVALID");return}let l={},p,u;if(o.initialState!==void 0){try{p=await ct(e,n,"ui/state.json",1048576);}catch(L){V(n,Xe(ae(L),"initial"));return}if(p.byteLength>1048576){V(n,"LIMIT_EXCEEDED");return}try{let L=vd(p),J=o.dataPaths??[],pe=Ht(L,J);l=ye(pe,0,J),Qe(l);}catch{V(n,"INITIAL_STATE_INVALID");return}if(u=createHash("sha256").update(p).digest("hex"),o.initialState.hash!==void 0&&o.initialState.hash!==u){V(n,"INITIAL_STATE_INVALID");return}}let f={...o,entryHash:c,...o.initialState===void 0?{}:{initialState:{path:"ui/state.json",hash:u}}},g=mn(f),_=Jd(f,a,p??new Uint8Array),P;try{P=Kd(g,_);}catch(L){if(L instanceof se){V(n,Fd(L));return}throw L}let U;if(n.bundleLineage!==void 0){let L=n.bundleLineage[n.bundleLineage.length-1];if(!L){V(n,"LINEAGE_INVALID");return}let{legacy:J,...pe}=L.definition,{hash:K,...Me}=P;if(te(pe)!==te(Me)){V(n,"LINEAGE_STALE");return}if(J!==void 0&&(P={...P,legacy:J}),J!==void 0)try{P={...P,hash:le(P)},Ae(P);}catch{V(n,"LINEAGE_INVALID");return}U=n.bundleLineage;}if(n.bundleIdentity!==void 0&&n.bundleIdentity.appId!==o.pluginId){V(n,"BUNDLE_INTEGRITY");return}if(n.bundleIdentity!==void 0&&(n.bundleIdentity.definitionId!==P.id||n.bundleIdentity.version!==P.version||n.bundleIdentity.definitionHash!==P.hash)){V(n,"LINEAGE_STALE");return}let k=wd(o.pluginId),N=o.actions.length===0?{read:k.read}:k,C=Ke(g),F=Ke(f),D=Ke(P),b=Ke({...g.handlers}),O=Ar(a),y=p===void 0?void 0:Ar(p),I=Object.freeze({...n.provenance===void 0?{}:{provenance:n.provenance},entry:Object.freeze({path:"ui/index.html",hash:c,bytes:O}),...y===void 0?{}:{initialState:Object.freeze({path:"ui/state.json",hash:u,bytes:y})}}),h={appId:o.pluginId,pluginId:o.pluginId,definitionId:o.definitionId,version:o.version,...i.releaseVersion===void 0?{}:{releaseVersion:i.releaseVersion},manifestFile:i.file,...i.mcpb===void 0?{}:{mcpb:Ke(i.mcpb)},relativePath:n.relativePath,manifest:F,normalized:C,name:o.name,description:o.description,...o.icon===void 0?{}:{icon:o.icon},...o.tone===void 0?{}:{tone:o.tone},definition:D,handlers:b,resources:I,html:d,entryBytes:O,entryHash:c,initialState:Ke(l),...y===void 0?{}:{initialStateBytes:y},...u===void 0?{}:{initialStateHash:u},sourceHash:_,toolNames:Object.freeze(N)},E=n.provenance===void 0?{...h,source:n.source}:{...h,provenance:n.provenance,lineage:U??[]};n.candidate=Object.freeze(E),Xd(o)&&V(n,"EXEC_DENIED");}async function Rr(e,n){let t={};for(let i of Z)try{t[i]=await ct(e,n,i,262144);}catch(r){if(ae(r)==="NOT_FOUND")continue;return {files:t,failure:Xe(ae(r),"manifest")}}if(t[W]!==void 0)try{t[H]=await ct(e,n,H,262144);}catch(i){if(ae(i)!=="NOT_FOUND")return {files:t,failure:Xe(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 Rr(e,n);if(i!==void 0){V(n,i);return}let r=t[W];return r!==void 0&&!Xt(r)&&(delete t[W],delete t[H]),Ei(t)?t:void 0}function ip(e,n,t,i=Rd,r=false,o=new Set){let s=np(e),a=Qd(s,o),d=Object.freeze(s.filter(u=>u.candidate!==void 0&&u.diagnostic===void 0&&!a.has(u)).map(u=>u.candidate)),c=Object.freeze(s.filter(u=>u.diagnostic!==void 0).map(u=>u.diagnostic)),l=r?Object.freeze({...t===void 0?{}:{indexHash:t},candidates:Object.freeze(s.filter(u=>u.source==="bundled"&&u.diagnostic===void 0&&t!==void 0&&u.candidate?.provenance?.indexHash===t).map(u=>u.candidate)),diagnostics:Object.freeze(c.filter(u=>u.source==="bundled").map(u=>Object.freeze({...u}))),reservedAppIds:Object.freeze([...i.appIds]),reservedDefinitionIds:Object.freeze([...i.definitionIds])}):void 0,p={apps:d,diagnostics:c,complete:n===void 0,...n===void 0?{}:{incompleteReason:n},...t===void 0?{}:{productBundleIndexHash:t},...l===void 0?{}:{productBundleSnapshotMetadata:l}};return Object.defineProperty(p,"candidates",{configurable:false,enumerable:false,get:()=>d}),Object.freeze(p)}function 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??ir,options:t}}async function wr(e,n,t){if(typeof e!="string"||e.length===0)throw new TypeError("workspaceRoot must be explicit");let{fs:i,options:r}=rp(n,t),o=r.clock??zd,s=o(),a=await dr(r.productBundle,i,s,o),d=o(),c=BigInt(Date.now())*1000000n,l=[],p=0,u,f=false,g,_;if(r.scanCache!==void 0&&typeof i.getRootIdentity=="function"&&typeof i.fingerprintVerifiedFile=="function")try{_=await i.getRootIdentity(e),g=Zo(r.scanCache,_),g.scanStartedAtNs=c;}catch(D){if(ae(D)!=="NOT_FOUND")throw D}let P=g!==void 0&&r.productBundle===void 0&&a.packages.length===0&&a.diagnostics.length===0,U=new Set,k=true;l.push(...a.diagnostics.map(D=>({source:D.source,root:r.productBundle?.root??e,name:"",relativePath:D.relativePath,diagnostic:D})));let N=a.reservedIds;a.incomplete&&(u="time_limit");for(let D of a.packages){if(!we(d,o)){f=true,u="time_limit";break}let b=D.indexEntry,O=b.packageDir,y=D.files===void 0?void 0:Bd(O,D.files),I=a.indexHash===void 0?void 0:So(Object.freeze({kind:"bundled",launcher:b.launcher!==false,indexHash:a.indexHash,packageDir:O,appId:b.appId,definitionId:b.definition.id,version:b.definition.version,definitionHash:b.definition.hash,files:b.files}),y),h={source:"bundled",root:r.productBundle?.root??e,name:O.slice(5),relativePath:O,...I===void 0?{}:{provenance:I},...D.files===void 0?{}:{pinnedFiles:D.files},...D.lineage===void 0?{}:{bundleLineage:D.lineage},bundleIdentity:{appId:b.appId,definitionId:b.definition.id,version:b.definition.version,definitionHash:b.definition.hash},identity:Vd(b)};if(l.push(h),p+=1,D.failureCode!==void 0){V(h,D.failureCode);continue}if(D.files?.has(H)===true){V(h,"EXEC_DENIED",{reason:{path:"",rule:"bundled-tool-mode-unsupported",file:H}});continue}let E={};for(let L of Z){let J=D.files?.get(L);J!==void 0&&(E[L]=J);}if(!Ei(E)){V(h,"BUNDLE_INTEGRITY");continue}if(await Er(i,h,E),!we(d,o)){f=true,u="time_limit";break}}let C=[{source:"apps",directory:"apps"},{source:"skills",directory:"skills"}];e:for(let D of C){let{source:b,directory:O}=D,y;try{y=await qd(i,e,O);}catch(h){if(ae(h)==="NOT_FOUND")continue;P=false,k=false,l.push({source:b,root:e,name:"",relativePath:b,diagnostic:at(Xe(ae(h),"manifest"),b,b)});continue}let I=y.filter(h=>h.kind==="directory"||h.kind==="symlink").filter(h=>kd(h.name)).map(h=>({source:b,root:e,name:h.name,relativePath:Ud(b,h.name)})).sort((h,E)=>Rn(h.relativePath,E.relativePath));for(let h of I){let E={...h};if(l.push(E),_!==void 0?U.add(Sr(_,E)):P=false,!we(d,o)){f=true,u="time_limit";break e}let L;if(g!==void 0&&_!==void 0){try{let K=await Wd(i,e,_,E,g,c,d,o);if(K.timeLimitReached){f=!0,u="time_limit";break e}E.scanContext=K.context,L=K.memo;}catch(K){P=false,V(E,Xe(ae(K),"manifest"));continue}L===void 0&&(P=false);}if(L!==void 0){if(E.candidate=L.candidate,E.diagnostic=L.diagnostic,E.identity=L.identity,b==="skills"&&L.candidate===void 0&&L.diagnostic===void 0)continue;if(p>=64){V(E,"LIMIT_EXCEEDED");continue}if(h.relativePath.split("/").length-1>2){V(E,"LIMIT_EXCEEDED");continue}if(p+=1,!we(d,o)){f=true,u="time_limit";break e}continue}let J;if(b==="skills"&&(J=await tp(i,E),J===void 0)){E.diagnostic===void 0&&_i(E);continue}if(p>=64){V(E,"LIMIT_EXCEEDED");continue}if(h.relativePath.split("/").length-1>2){V(E,"LIMIT_EXCEEDED");continue}if(!we(d,o)){f=true,u="time_limit";break e}if(p+=1,J===void 0){let K=await Rr(i,E);if(K.failure!==void 0||!Ei(K.files)){V(E,K.failure??Xe("NOT_FOUND","manifest")),_i(E);continue}J=K.files;}if(await Er(i,E,J),_i(E),!we(d,o)){f=true,u="time_limit";break e}}}if(g!==void 0&&_!==void 0){let D=[...U].sort(Rn),b=g.lastCandidateKeys,O=b!==void 0&&b.length===D.length&&b.every((I,h)=>I===D[h]);if(P=P&&O,k&&!f&&u===void 0)for(let I of g.candidates.keys())try{JSON.parse(I)[0]===_.realPath&&!U.has(I)&&g.candidates.delete(I);}catch{g.candidates.delete(I);}let y=[...g.candidates.keys()].filter(I=>{try{return JSON.parse(I)[0]===_.realPath}catch{return false}});P=P&&y.length===U.size&&y.every(I=>U.has(I))&&!f&&u===void 0,g.lastCandidateScanUnchanged=P,k&&!f&&u===void 0&&(g.lastCandidateKeys=Object.freeze(D));}f&&l.push({source:"apps",root:e,name:"",relativePath:"apps",diagnostic:at("DISCOVERY_TIME_LIMIT","apps","apps")});let F=ep(l,r,N);return ip(l,u,a.indexHash,N,r.productBundle!==void 0,F)}var Rd,hi,pr,Cd,Ir,Gd,gr,Cr=B(()=>{m();He();Un();Le();Yt();Be();Zn();Yo();Wn();Qo();ui();Jn();mi();mi();Rd=rt([]),hi="crewx_local_app_";pr=["bundled","apps","skills"],Cd=new TextDecoder("utf-8",{fatal:true});Ir=["","/ui"],Gd=["/dist"],gr=2000000000n;});m();Yt();m();wt();m();var yo="SKILL.md",Ec=/^---\s*\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;function Ao(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function Tc(e){return e.isDirectory()||e.isSymbolicLink()}function _o(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(!Ao(i))return {frontmatter:{},readable:!0,valid:!1,hasFrontmatter:!0};let r=Ao(i.metadata)?i.metadata:void 0;return {frontmatter:{...typeof i.name=="string"?{name:i.name}:{},...typeof(r?.version??i.version)=="string"?{version:r?.version??i.version}:{},...typeof i.description=="string"?{description:i.description}:{}},readable:!0,valid:!0,hasFrontmatter:!0}}catch{return {frontmatter:{},readable:true,valid:false,hasFrontmatter:true}}}function Pc(e){return [join(e,yo),join(e,"skill",yo)]}function Io(e,n){if(!_o(e))return null;for(let t of Pc(e)){if(!existsSync(t))continue;let r=qt(t).frontmatter;return {name:r.name??n,...r.version===void 0?{}:{version:r.version},...r.description===void 0?{}:{description:r.description},skillMdPath:t,dir:e}}return null}function go(e){try{return readdirSync(e,{withFileTypes:!0}).filter(Tc)}catch{return []}}function mo(e,n,t){!e||n.has(e.name)||(n.add(e.name),t.push(e));}function Eo(e){let n=[],t=new Set;for(let i of e)if(_o(i))for(let r of go(i)){if(r.name.startsWith("@")){let o=join(i,r.name);for(let s of go(o))mo(Io(join(o,s.name),s.name),t,n);continue}mo(Io(join(i,r.name),r.name),t,n);}return n.sort((i,r)=>i.name.localeCompare(r.name))}m();$n();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 To(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 Po(e){if(!Array.isArray(e))return;let n=Z.filter(t=>e.includes(t));return n.length>0?n:void 0}Cr();var ap=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/;function ut(e){let n="screenHash"in e?e.screenHash:void 0,i=("skillHash"in e?e.skillHash:void 0)??(e.relativePath!==void 0&&e.fileBytes!==void 0?cp(e.relativePath,e.fileBytes):void 0);if(n!==void 0&&i!==void 0){let r=JSON.stringify({screenHash:n,skillHash:i});return createHash("sha256").update(r,"utf8").digest("hex")}if(n!==void 0)return n;if(i!==void 0)return i;throw new TypeError("App definition hash input must contain a screenHash or skill bytes")}function cp(e,n){let t=new TextEncoder().encode(ft(e)),i=dp(n),r=new Uint8Array(t.byteLength+1+i.byteLength);return r.set(t,0),r[t.byteLength]=0,r.set(i,t.byteLength+1),createHash("sha256").update(r).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 ft(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 pt(e,n){let t=new TextEncoder().encode(e),i=new TextEncoder().encode(n),r=Math.min(t.byteLength,i.byteLength);for(let o=0;o<r;o+=1){let s=t[o]-i[o];if(s!==0)return s}return t.byteLength-i.byteLength}function xr(e,n){let t=relative(e,n).split(sep).join("/");return !t||t===".."||t.startsWith("../")||isAbsolute(t)?null:ft(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 vr(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??xe,...e.definition.detailPanel===void 0?{}:{detailPanel:e.definition.detailPanel},...e.definition.displayModes===void 0?{}:{displayModes:e.definition.displayModes},...e.definition.summaryProjection===void 0?{}:{summaryProjection:e.definition.summaryProjection}})}function jr(e){return {capabilities:Object.freeze([...e]),origin:"local",ownership:"unknown",shareability:"unknown",sharingAvailability:"unavailable"}}function up(e,n){let t=e.candidate,i=t.provenance!==void 0,r=n&&!i?["screen","skill"]:["screen"],o=lp(t),s=ut(n?{screenHash:o.hash,skillHash:n.skillHash}:{screenHash:o.hash}),a=t.description||n?.skill.description||"",d=t.releaseVersion??String(t.version),c={appId:t.pluginId,name:t.name,description:a,version:d,...jr(r),definition:o,...n===void 0||i?{}:{skillName:n.skill.name},...i?{provenance:t.provenance}:{localDefinitionRef:vr(e.packageRoot)},definitionHash:s,...t.manifest.csp===void 0?{}:{connectDomains:Object.freeze([...t.manifest.csp.connectDomains])}};return {...i?{}:{packageRoot:e.packageRoot},source:i?"bundled":t.source,appId:c.appId,capabilities:r,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},...jr(["skill"]),skillName:e.skill.name,localDefinitionRef:vr(e.packageRoot),definitionHash:ut({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,r){let o=To(r?.reason),s=Po(r?.files);return Object.freeze({code:e,source:n,relativePath:Ap(t),...i===void 0?{}:{appId:i},...o===void 0?{}:{reason:o},...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 Fr(e){return ee(e.code,e.source,e.relativePath,e.pluginId,e)}function Ip(e,n){let t=xr(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 r=qt(n.skillMdPath);if(!r.readable)return {diagnostic:ee("SKILL_READ_FAILED",i,t)};if(!r.valid)return {diagnostic:ee("SKILL_INVALID",i,t)};let o=gp(n.dir,n.skillMdPath);if(!o)return {diagnostic:ee("PATH_ESCAPED",i,t)};try{let s=new Uint8Array(readFileSync(n.skillMdPath));return {skill:n,packageRoot:t,relativeSkillPath:o,skillHash:ut({relativePath:o,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 ft(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??xe,...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 ft(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??[],r=new Map;for(let s of i){let a=_p(s);if(!a){t.push(ee("INSTALLED_IDENTITY_MISMATCH","installed","installed"));continue}let d=r.get(a);if(d&&JSON.stringify(d)!==JSON.stringify(s)){t.push(ee("INSTALLED_IDENTITY_MISMATCH","installed",a));continue}r.set(a,s);}let o=new Map;for(let s of e)s.packageRoot!==void 0&&o.set(s.packageRoot,s);for(let[s,a]of r){let d=o.get(s);if(!d){t.push(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 r of e){let o=t.get(r.appId)??[];o.push(r),t.set(r.appId,o);}let i=new Set;for(let r of t.values()){if(r.length<2)continue;let o=r.some(s=>s.source==="builtin")?"builtin":r.some(s=>s.source==="bundled")?"bundled":void 0;if(o==="bundled"){let s=r.filter(a=>a.source==="apps"&&a.summary.definition!==void 0);if(s.length===1){for(let a of r)a.source==="bundled"?i.add(a):a!==s[0]&&(i.add(a),n.push(ee("RESERVED_ID",a.source,lt(a),a.appId)));continue}}if(o!==void 0){let s=r.filter(a=>a.source===o);for(let a of r.filter(d=>d.source!==o))i.add(a),n.push(ee("RESERVED_ID",a.source,lt(a),a.appId));if(s.length>1)for(let a of s)i.add(a),n.push(ee("DUPLICATE_ID",a.source,lt(a),a.appId));continue}for(let s of r)i.add(s),n.push(ee("DUPLICATE_ID",s.source,lt(s),s.appId));}return e.filter(r=>!i.has(r))}function lt(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(Fr)}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 Vr(e,n={}){if(typeof e!="string"||e.length===0)throw new TypeError("workspaceRoot must be explicit");if(n.productBundle!==void 0&&n.registeredProductBundle!==void 0)throw new TypeError("registeredProductBundle cannot be combined with product bundle discovery");let t=hp(n),i=await wr(e,bp(n,t)),r=n.registeredProductBundle??i.productBundleSnapshotMetadata,o=[join(e,"skills"),join(e,"node_modules"),join(e,"apps")],s=[],a=[],d=[],c=new Set;for(let I of o)for(let h of Eo([I])){let E=xr(e,h.dir);(E===null||!c.has(E))&&(d.push(h),E!==null&&c.add(E));}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),_=new Set(p===void 0?[]:(t?.listMcpApps()??[]).filter(I=>I.provenance?.indexHash===p).map(I=>I.appId));for(let I of f){if(g.has(I)&&I.provenance?.indexHash===p&&_.has(I.appId))continue;let h=I.provenance===void 0?`workspace\0${I.relativePath}`:`bundled\0${I.provenance.indexHash}\0${I.provenance.packageDir}`;l.set(h,{candidate:I,packageRoot:I.relativePath});}let P=new Map(a.map(I=>[I.packageRoot,I])),U=[];for(let I of l.values()){let h=I.candidate.provenance===void 0?P.get(I.packageRoot):void 0,E=up(I,h);U.push({...E.packageRoot===void 0?{}:{packageRoot:E.packageRoot},source:E.source,appId:E.appId,summary:E.summary});}let k=new Set([...l.values()].filter(I=>I.candidate.provenance===void 0).map(I=>I.packageRoot)),N=r===void 0?new Set:new Set(i.diagnostics.filter(I=>I.code==="RESERVED_ID"&&I.source!=="bundled").map(I=>I.relativePath)),C=new Set(r?.reservedAppIds??[]);for(let I of a){let h=fp(I);if(!(k.has(I.packageRoot)||N.has(I.packageRoot))){if(C.has(h.appId)){s.push(ee("RESERVED_ID",I.source,I.packageRoot,h.appId));continue}U.push({packageRoot:h.packageRoot,source:h.source,appId:h.appId,summary:h.summary});}}let F=[...Np(i.diagnostics,new Set(a.map(I=>I.packageRoot))),...s,...n.registeredProductBundle?.diagnostics.filter(I=>I.source==="bundled").map(Fr)??[]],D=[];if(t)for(let I of t.listMcpApps()){let h=mp(I);"diagnostic"in h?F.push(h.diagnostic):D.push(h);}let b=Pp([...U,...D],F);Tp(b,n,F);let O=b.map(I=>I.summary).sort((I,h)=>pt(I.appId,h.appId)),y=[...F].sort((I,h)=>pt(I.relativePath,h.relativePath)||pt(I.code,h.code)||pt(I.appId??"",h.appId??""));return Object.freeze({items:Object.freeze(O),diagnostics:Object.freeze(y)})}m();m();m();function Sp(e){let n=r=>r.replace(/[.+^${}()|[\]\\]/g,"\\$&"),i=e.split("/").map(r=>r==="**"?".*":r.split("*").map(n).join("[^/]*"));return new RegExp(`^${i.join("\\/")}$`)}function un(e,n){try{return Sp(n).test(e)}catch{return false}}function yt(e,...n){let t=e.split("/");if(t.length<n.length)return false;let i=t.length-n.length;return n.every((r,o)=>un(t[i+o],r))}function Mp(e,n){return e.split("/").some(t=>un(t,n))}var Br=[{label:".env*",test:e=>un(e,".env*")},{label:".git/",test:(e,n,t)=>t&&e===".git"},{label:"memory/",test:(e,n,t)=>t&&e==="memory"},{label:"*.key",test:e=>un(e,"*.key")},{label:"*.pem",test:e=>un(e,"*.pem")},{label:"auth.json",test:e=>e==="auth.json"},{label:"node_modules/",test:(e,n,t)=>t&&e==="node_modules"},{label:"conversations/",test:(e,n,t)=>t&&e==="conversations"},{label:".crewx/threads/",test:(e,n,t)=>t&&yt(n,".crewx","threads")},{label:".crewx/crewx.db",test:(e,n,t)=>!t&&yt(n,".crewx","crewx.db")},{label:".crewx/*.log",test:(e,n,t)=>!t&&yt(n,".crewx","*.log")},{label:".crewx/publish/",test:(e,n,t)=>t&&yt(n,".crewx","publish")},{label:".crewx/",test:(e,n)=>Mp(n,".crewx")}];function fn(e,n,t){for(let i of Br)if(i.test(e,n,t))return i.label;return null}m();var Ce=class extends Error{constructor(t,i){super(`publish: [${t}]${i?` ${i}`:""}`);this.code=t;}code;name="PublishError"};function T(e,n){return new Ce(e,n)}function Hr(e,n){if(!n||/[\\\u0000]/.test(n)||ce.posix.isAbsolute(n)||n.split("/").some(f=>!f||f==="."||f===".."))throw T("PACKAGE_PATH_TRAVERSAL","package root must be a safe workspace-relative path");let t=ce.resolve(e),i=ce.resolve(t,...n.split("/"));if(!i.startsWith(`${t}${ce.sep}`))throw T("PACKAGE_PATH_TRAVERSAL","package root escaped the workspace");function r(f,g){let _;try{_=ne.lstatSync(f);}catch{throw T("PACKAGE_FILE_INVALID",`package directory is missing: ${g}`)}if(_.isSymbolicLink())throw T("PACKAGE_SYMLINK",`symlink is not publishable: ${g}`);if(!_.isDirectory())throw T("PACKAGE_FILE_INVALID",`not a package directory: ${g}`)}r(t,".");let o=t,s="",a=null;for(let f of n.split("/"))o=ce.join(o,f),s=s?`${s}/${f}`:f,r(o,s),a??=fn(f,s,true);let d=[],c=[];function l(f,g){r(f,g);let _=ne.readdirSync(f,{withFileTypes:true});for(let P of _){let U=`${g}/${P.name}`,k=ce.join(f,P.name);if(P.isSymbolicLink())throw T("PACKAGE_SYMLINK",`symlink is not publishable: ${U}`);let N=fn(P.name,U,P.isDirectory());N?c.push({path:U,rule:N}):P.isDirectory()?l(k,U):P.isFile()&&d.push(U);}}a?c.push({path:n,rule:a}):l(i,n);let p=new TextEncoder,u=(f,g)=>Buffer.compare(p.encode(f),p.encode(g));return d.sort(u),c.sort((f,g)=>u(f.path,g.path)),{included:d,excluded:c}}function zr(e){let n=[],t=[];function i(r,o,s){let a;try{a=ne.readdirSync(r,{withFileTypes:!0});}catch{return}a.sort((d,c)=>d.name.localeCompare(c.name));for(let d of a){let c=o?`${o}/${d.name}`:d.name,l=ce.join(r,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??fn(d.name,c,false);u?t.push({path:c,rule:u}):t.push({path:c,rule:"symlink"});continue}if(d.isDirectory()){let p=s??fn(d.name,c,true);i(l,c,p);continue}if(d.isFile()){let p=s??fn(d.name,c,false);p?t.push({path:c,rule:p}):n.push(c);}}}return i(e,"",null),n.sort(),t.sort((r,o)=>r.path<o.path?-1:r.path>o.path?1:0),{included:n,excluded:t}}m();var 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 Di(e,n,t){let i=[];for(let r of n){let o=ce.join(e,r),s;try{let d=t?.get(r);s=d===void 0?ne.readFileSync(o):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:r,line:c+1,rule:l});});}return i}m();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 r=i;return {name:typeof r.name=="string"?r.name:void 0,version:typeof r.version=="string"?r.version:void 0,description:typeof r.description=="string"?r.description:void 0,requiredEnv:r.requiredEnv,crewxMinVersion:typeof r.crewxMinVersion=="string"?r.crewxMinVersion:void 0}}function Up(e){return bi.createHash("sha256").update(e).digest("hex")}function Kr(e){let n;try{n=ne.lstatSync(e);}catch{throw T("PACKAGE_FILE_INVALID",`file is not readable: ${ce.basename(e)}`)}if(n.isSymbolicLink())throw T("PACKAGE_SYMLINK","symlink content is not publishable");if(!n.isFile())throw T("PACKAGE_FILE_INVALID","only regular files are publishable");return bi.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),r=Math.min(t.byteLength,i.byteLength);for(let o=0;o<r;o+=1){let s=t[o]-i[o];if(s!==0)return s}return t.byteLength-i.byteLength}function 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 T("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 T("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),r=i.name??ce.basename(e);if(!Wr.test(r))throw new Error(`publish: invalid name "${r}" \u2014 must match ${Wr} (lowercase letters, numbers, hyphen only)`);let o=t.version??i.version;if(!o)throw new Error("publish: version is required \u2014 set crewx.yaml metadata.version or pass opts.version");Yr(o);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:r,version:o,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 T("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 T("APP_UI_MANIFEST_INVALID","screen App manifests require definitionId");let s=n.includedFiles.includes(`${i}manifest.json`),a=n.includedFiles.includes(`${i}ui-plugin.json`);if(!s&&!a)throw T("APP_UI_MANIFEST_INVALID","screen App is missing manifest.json or ui-plugin.json");if(s&&!a)throw T("APP_UI_MANIFEST_INVALID","a manifest.json App must also ship a generated ui-plugin.json");if(!n.includedFiles.includes(`${i}ui/index.html`))throw T("APP_UI_MANIFEST_INVALID","screen App is missing ui/index.html")}if(t.includes("skill")&&!n.includedFiles.includes(`${i}SKILL.md`))throw T("APP_SKILL_MISSING","skill capability requires package-root SKILL.md");let r=new Set,o=n.includedFiles.map(s=>{if(Xr(s),!s.startsWith(i))throw T("PACKAGE_PATH_TRAVERSAL","App manifest file is outside packageRoot");let a=n.generatedFiles?.get(s);return a!==void 0&&r.add(s),{path:s,sha256:a===void 0?Kr(ce.join(e,s)):Up(a),...a===void 0?{}:{generated:true}}}).sort((s,a)=>kp(s.path,a.path));if(r.size>0&&(r.size!==1||!r.has(`${i}ui-plugin.json`)))throw new Error("publish: only the generated ui-plugin.json may be present in an App package");return {manifestVersion:1,name: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:o,requiredEnv:[]}}m();function Qr(e){return bi.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(r=>r===".."||r.length===0))throw T("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 T("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 T("PACKAGE_FILE_INVALID","manifest file is missing")}if(i.isSymbolicLink())throw T("PACKAGE_SYMLINK","symlink content is not publishable");if(!i.isFile())throw T("PACKAGE_FILE_INVALID","only regular files are publishable");return new Uint8Array(ne.readFileSync(t))}async function rs(e,n,t={}){let i=ce.join(e,".crewx","publish");ne.mkdirSync(i,{recursive:true});let r=ce.join(i,`${n.name}-${n.version}.tgz`),o=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 T("PACKAGE_PATH_TRAVERSAL","manifest contains duplicate file paths");a.add(c.path);let l=t.generatedFiles?.get(c.path);if(c.generated===!0&&l===void 0)throw T("PACKAGE_GENERATED_FILE_MISSING","generated manifest file bytes are missing");if(t.sourceFileHashes?.has(c.path)){let f=es(e,c.path);if(t.sourceFileHashes.get(c.path)!==Qr(f))throw T("PACKAGE_STAGED_BYTES_MISMATCH","workspace source changed before staging")}let p=l??es(e,c.path);if(Qr(p)!==c.sha256)throw T("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:o,cwd:s,portable:!0,noMtime:!0},["manifest.json",...d]),ne.renameSync(o,r);}finally{try{ne.rmSync(o,{force:!0});}catch{}ne.rmSync(s,{recursive:true,force:true});}return r}m();m();var yn="/api/v1";var Vp=201,Bp=200,Hp=409,Si=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 wn(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,r=[t.code,t.message,i?.code,i?.message];for(let o of r){if(typeof o!="string"||!Object.prototype.hasOwnProperty.call(ss,o))continue;let s=o,a=s==="APP_NAME_CONFLICT"?`marketplace name is already in use: ${n}`:void 0;return T(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,r=e.manifest.type==="app"?e.manifest:void 0,o=r!==void 0,s=r?.appId,a;try{a=await fetch(`${n}${yn}/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 wn(a),c=Wp(d),l=Jp(d),p=o&&l!==void 0?l:i,u;if(a.status===Vp)u="created";else if(o&&a.status===Bp){if(c===void 0)throw T("PUBLISH_CONTENT_ID_MISSING","App republish did not return an opaque contentId");u="existing";}else if(a.status===Hp){if(o)throw cs(d,i)??T("APP_NAME_CONFLICT",`marketplace name is already in use: ${i}`);u="existing";}else throw a.status===Si?new Error("publish: [E_AUTH_EXPIRED] Authentication is expired or missing \u2014 please log in again (HTTP 401)"):new Error(`publish: [E_HTTP] Submit request failed \u2014 HTTP ${a.status}`);let f="not-needed",g=null;if(u==="existing"&&!o){let b;try{b=await fetch(`${n}${yn}/publisher/items`,{method:"GET",headers:{Authorization:`Bearer ${e.accessToken}`}});}catch{throw new Error("publish: [E_NETWORK] Publisher items request failed (network)")}let O=await wn(b);if(b.status!==200)throw new Error(`publish: [E_HTTP] Publisher items request failed \u2014 HTTP ${b.status}`);let I=as(O,"publisher items",b.status)?.items;if(!Array.isArray(I))throw new Error(`publish: [E_MALFORMED] Publisher items response is malformed (expected data.items[]) \u2014 HTTP ${b.status}`);let h=I.find(E=>!E||typeof E!="object"?false:E.slug===i);if(!h||typeof h.version!="string")throw new Error(`publish: [E_MALFORMED] Publisher items response does not contain slug "${i}" \u2014 HTTP ${b.status}`);if(g=h.version,g!==e.manifest.version){let E;try{E=await fetch(`${n}${yn}/publisher/items/${encodeURIComponent(i)}`,{method:"PUT",headers:{Authorization:`Bearer ${e.accessToken}`,"Content-Type":"application/json"},body:JSON.stringify({version:e.manifest.version})});}catch{throw new Error("publish: [E_NETWORK] Version update request failed (network)")}if(!E.ok)throw await wn(E),E.status===Si?new Error(`publish: [E_AUTH_EXPIRED] Authentication is expired or missing \u2014 please log in again (HTTP ${E.status})`):E.status===403?new Error(`publish: [E_FORBIDDEN] Version update is forbidden; only the item owner can update an existing item (HTTP ${E.status})`):new Error(`publish: [E_HTTP] Version update failed \u2014 HTTP ${E.status}`);f="applied";}}let _=ne.readFileSync(e.tgzPath),P=zp()?$p(_):_,U=new FormData;U.set("archive",new Blob([new Uint8Array(P)],{type:"application/gzip"}),`${p}-${e.manifest.version}.tgz`);let k=o&&c!==void 0?c:i,N;try{N=await fetch(`${n}${yn}/publisher/items/${encodeURIComponent(k)}/upload`,{method:"POST",headers:{Authorization:`Bearer ${e.accessToken}`},body:U});}catch{throw new Error("publish: [E_NETWORK] Upload request failed (network)")}if(N.status===Si)throw new Error("publish: [E_AUTH_EXPIRED] Authentication is expired or missing \u2014 please log in again (HTTP 401)");if(!N.ok){let b=await wn(N);if(o){let O=cs(b,p);if(O)throw O}throw new Error(`publish: [E_HTTP] Upload request failed \u2014 HTTP ${N.status}`)}let C=await wn(N),F=as(C,"upload",N.status),D=typeof F.contentId=="string"&&F.contentId.length>0?F.contentId:c;if(o&&D===void 0)throw T("PUBLISH_CONTENT_ID_MISSING","App upload did not return an opaque contentId");return {slug:p,version:e.manifest.version,...D===void 0?{}:{contentId:D},artifactChecksum:F.artifactChecksum,artifactSizeBytes:F.artifactSizeBytes,submitOutcome:u,versionUpdate:f,serverVersionBefore:g}}var Xp=1e4,Yp=100*1024*1024;function Mi(e){return bi.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 Cn(e,n){if(!n||n.includes("\\")||n.includes("\0")||ce.posix.isAbsolute(n)||n.split("/").some(o=>o===".."||o.length===0))throw T("PACKAGE_PATH_TRAVERSAL","workspace file path is not a safe relative path");let t=ce.resolve(e,...n.split("/")),i=ce.resolve(e);if(t!==i&&!t.startsWith(`${i}${ce.sep}`))throw T("PACKAGE_PATH_TRAVERSAL","workspace file path escaped the workspace root");let r;try{r=ne.lstatSync(t);}catch{throw T("PACKAGE_FILE_INVALID",`workspace file is missing: ${n}`)}if(r.isSymbolicLink())throw T("PACKAGE_SYMLINK",`symlink is not publishable: ${n}`);if(!r.isFile())throw T("PACKAGE_FILE_INVALID",`not a regular file: ${n}`);return new Uint8Array(ne.readFileSync(t))}function ps(e,n,t){let i=e??n;if(!Number.isSafeInteger(i)||i<=0)throw new Ce("PACKAGE_SIZE_LIMIT",`${t} must be a positive integer`);return i}function us(e,n,t,i){let r=ps(t.maxFileCount??t.maxFiles,Xp,"max file count"),o=ps(t.maxTotalBytes??t.maxBytes,Yp,"max total bytes");if(n.length>r)throw new Ce("PACKAGE_SIZE_LIMIT",`package exceeds file count limit (${r})`);let s=0;for(let a of n){let d=i?.get(a);if(d!==void 0?s+=d.byteLength:s+=Cn(e,a).byteLength,s>o)throw new Ce("PACKAGE_SIZE_LIMIT",`package exceeds byte limit (${o})`)}}function Zp(e){return e.appId!==void 0||e.expectedDefinitionHash!==void 0}function Qp(e){let n=e.appId!==void 0,t=e.expectedDefinitionHash!==void 0;if(!n&&t)throw T("APP_ID_REQUIRED","appId is required with expectedDefinitionHash");if(n&&!t)throw T("APP_DEFINITION_HASH_REQUIRED","expectedDefinitionHash is required with appId");if(!n||!t)throw T("APP_ID_REQUIRED")}function el(e,n){let t=e.filter(i=>i.appId===n);if(t.length===0)throw T("APP_NOT_FOUND",`no publishable App matches ${n}`);if(t.length!==1)throw T("APP_AMBIGUOUS",`more than one App matches ${n}`);return t[0]}function nl(e){let n=e.localDefinitionRef?.packageRoot;if(!n||!/^(?:apps|skills)\/[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(n))throw T("APP_PACKAGE_ROOT_INVALID","selected App is not rooted in apps/<safe-id> or skills/<safe-id>");return n}function Li(e){let{path:n,rule:t}=e.reason;return `${e.code} at ${n===""?"<file>":n} (${t})`+(e.files.length>0?` [${e.files.join(", ")}]`:"")}function tl(e,n,t){let i=Ge({[de]:t},{mode:"published"});if(!i.ok)throw T("APP_UI_MANIFEST_INVALID",`generated ${de} does not read: ${Li(i.rejection)}`);if(an(i.manifest)!==an(n))throw T("APP_UI_MANIFEST_INVALID",`generated ${de} normalizes to a different definition hash than the source`);let r=e[W];if(r===void 0)return;let o=e[H],s=Ge({[W]:r,[de]:t,...o===void 0?{}:{[H]:o}},{mode:"local"});if(!s.ok)throw T("APP_UI_MANIFEST_INVALID",Li(s.rejection))}function il(e,n,t,i){let r={};for(let f of Z){let g=`${t}/${f}`;i.includes(g)&&(r[f]=Cn(e,g));}let o=`${t}/${H}`;if(r[W]!==void 0&&i.includes(o)&&(r[H]=Cn(e,o)),Object.keys(r).length===0)throw T("APP_UI_MANIFEST_INVALID","selected screen App has no package manifest.json or ui-plugin.json");let s=Ge(r,{mode:"local"});if(!s.ok)throw T("APP_UI_MANIFEST_INVALID",Li(s.rejection));if(s.manifest.pluginId!==n.appId)throw T("APP_DEFINITION_CONFLICT",`${s.file} identity no longer matches the selected App`);let a=r[de],d=a===void 0?void 0:Mi(a),c=`${t}/ui/index.html`;if(!i.includes(c))throw T("APP_UI_MANIFEST_INVALID","screen entry is outside package scope");let l=Mi(Cn(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 T("APP_INITIAL_STATE_OUT_OF_SCOPE","initialState must reference ui/state.json inside the package");let g=`${t}/ui/state.json`;if(!i.includes(g))throw T("APP_INITIAL_STATE_OUT_OF_SCOPE","initialState reference is outside the selected package");let _=Cn(e,g);p.initialState={...f,hash:Mi(_)};}let u;try{let f=$e(p,{mode:"published"});u=new Uint8Array(Buffer.from(JSON.stringify(f),"utf8"));}catch(f){throw f instanceof se?T("APP_UI_MANIFEST_INVALID",f.code):T("APP_UI_MANIFEST_INVALID")}return tl(r,s.manifest,u),{bytes:u,...d===void 0?{}:{legacySourceHash:d}}}async function ol(e,n){let{included:t,excluded:i}=zr(e);us(e,t,n);let r=qr(e,t,{version:n.version}),o=Di(e,t);return {plan:{manifest:r,included:t,excluded:i,secretFindings:o},archiveOptions:{}}}async function rl(e,n){Qp(n);let t=await Vr(e),i=el(t.items,n.appId);if(i.definitionHash!==n.expectedDefinitionHash)throw T("APP_DEFINITION_CONFLICT",`definitionHash changed for ${n.appId}`);let r=nl(i),{included:o,excluded:s}=Hr(e,r),a=new Map,d=new Map;if(i.capabilities.includes("screen")){let u=il(e,i,r,o),f=`${r}/${de}`;if(a.set(f,u.bytes),u.legacySourceHash!==void 0)d.set(f,u.legacySourceHash);else {o.push(f);let g=new TextEncoder;o.sort((_,P)=>Buffer.compare(g.encode(_),g.encode(P)));}}if(i.capabilities.includes("skill")&&!o.includes(`${r}/SKILL.md`))throw T("APP_SKILL_MISSING","skill capability requires package-root SKILL.md");us(e,o,n,a);let c={appId:i.appId,version:n.version??"",description:i.description,capabilities:i.capabilities,packageRoot:r,...i.definition?.id===void 0?{}:{definitionId:i.definition.id},definitionHash:i.definitionHash,includedFiles:o,generatedFiles:a},l=Zr(e,c),p=Di(e,o,a);return {plan:{manifest:l,included:o,excluded:s,secretFindings:p},archiveOptions:{generatedFiles:a,sourceFileHashes:d}}}async function fs(e,n){let t=ce.resolve(e);if(Zp(n))return rl(t,n);if(n.expectedDefinitionHash!==void 0)throw T("APP_ID_REQUIRED");return ol(t,n)}async function iA(e,n={}){return (await fs(e,n)).plan}function sl(e){let n=e.map(t=>`${t.path}:${t.line} (${t.rule})`).join(", ");throw new Ce("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&&sl(i.plan.secretFindings);let r=await rs(t,i.plan.manifest,i.archiveOptions);return {manifest:i.plan.manifest,tgzPath:r}}async function oA(e,n={}){return ys(e,n)}async function rA(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{
|
|
1
|
+
import*as ce from'path';import {resolve,relative,sep,isAbsolute,join}from'path';import'url';import*as bi 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 Yr from'js-yaml';import {load}from'js-yaml';import*as os from'os';import*as ss from'tar';import {gunzipSync,gzipSync}from'zlib';var B=(e,n)=>()=>(e&&(n=e(e=0)),n);var m=B(()=>{});var x,kn=B(()=>{m();x=class extends Error{constructor(t,i=t,o){super(i);this.code=t;this.currentRevision=o;}code;currentRevision;name="UiRuntimeError"};});function ht(e){return hs.test(e)||_s.test(e)}function fe(){throw new x("INPUT_INVALID","JSON value is not projection-safe")}function Ns(e){let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function gt(e,n,t,i,o,r){if(n>i&&fe(),e===null||typeof e=="string"||typeof e=="boolean")return typeof e=="string"&&(Es.test(e)||Ps.test(e)&&!Ss(o,r)||Ts.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(c=>gt(c,n+1,t,i,o,r));Ns(s)||fe();let a={};for(let[c,d]of Object.entries(e))ht(c)&&fe(),a[c]=gt(d,n+1,t,i,[...o,c],r);return a}finally{t.delete(s);}}function ye(e,n=0,t=[]){(!Number.isInteger(n)||n<0||n>bs)&&fe(),(!Array.isArray(t)||t.some(o=>typeof o!="string"))&&fe();let i=gt(e,0,new Set,Ds+n,[],t);return (i===null||Array.isArray(i)||typeof i!="object")&&fe(),i}function Ze(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 Ss(e,n){if(e.length===0)return false;let t=e.join(".");return n.some(i=>Ze(t,i))}function Qe(e){try{let n=JSON.stringify(e);return n===void 0&&fe(),n}catch{fe();}}function mt(e){return Array.isArray(e)?e.map(mt):e!==null&&typeof e=="object"?Object.fromEntries(Object.keys(e).sort().map(n=>[n,mt(e[n])])):e}function te(e){return Qe(mt(e))}function _t(e){return Buffer.byteLength(e,"utf8")}var hs,_s,Es,Ts,Ps,Ds,bs,Le=B(()=>{m();kn();hs=/(?:proof|token|secret|password|cookie|authorization|private[_-]?key|stack|exception|plugin[_-]?text)/i,_s=/(?:url|uri|endpoint|path|file(?:name|path)?|cwd|shell|directory|dir|folder)$/i,Es=/<\/?[A-Za-z][^>]*>/,Ts=/^(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)/,Ps=/^(?:https?|file|ftp|ws|wss):\/\//i;Ds=8,bs=4;});var Ri=B(()=>{m();Le();});var xn,Et=B(()=>{m();xn=["text/plain","application/json"];});var Oi=B(()=>{m();Et();});function en(e){return Ls.has(e)||Rs.test(e)||Os.test(e)}var wi,Ls,Rs,Os,vn,An,Te,Tt,Pt,Nt,Dt,bt,Be=B(()=>{m();wi=["__proto__","prototype","constructor","proof","token","secret","password","cookie","authorization","private_key","private-key","stack","exception","plugin_text","url","uri","endpoint","path","filename","filepath","cwd","shell","directory","dir","folder"],Ls=new Set(wi),Rs=/(?:proof|token|secret|password|cookie|authorization|private[_-]?key|stack|exception|plugin[_-]?text)/i,Os=/(?:url|uri|endpoint|path|file(?:name|path)?|cwd|shell|directory|dir|folder)$/i;vn=/^[A-Za-z0-9_]+$/,An=/^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)*$/,Te=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,Tt=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/,Pt=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,Nt=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/,Dt=["blue","violet","emerald","amber","rose","sky","slate","indigo"],bt=["inline","panel"];});function St(e){return typeof e=="string"&&xn.includes(e)}var Ci=B(()=>{m();Et();Be();});function jn(e){if(!Mt(e))return false;let n=Object.keys(e);return !(n.some(t=>t!=="in"&&t!=="out")||n.length===0||Object.hasOwn(e,"in")&&!ws(e.in)||Object.hasOwn(e,"out")&&!Cs(e.out))}function ws(e){return Mt(e)?Object.keys(e).every(t=>t==="mediaType"||t==="required")&&Object.hasOwn(e,"mediaType")&&St(e.mediaType)&&(!Object.hasOwn(e,"required")||typeof e.required=="boolean"):false}function Cs(e){return Mt(e)?Object.keys(e).every(t=>t==="mediaType"||t==="range")&&Object.hasOwn(e,"mediaType")&&St(e.mediaType)&&(!Object.hasOwn(e,"range")||typeof e.range=="boolean"):false}function Mt(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}var Lt=B(()=>{m();Oi();Ci();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 x("DEFINITION_UNSUPPORTED","UI definition is invalid");if(e.sourceHash!==void 0&&(typeof e.sourceHash!="string"||!ks.test(e.sourceHash)))throw new x("DEFINITION_UNSUPPORTED","UI definition source hash is invalid");if(!/^[0-9a-f]{64}$/.test(e.hash)||le(e)!==e.hash)throw new x("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=>!vs(i)))throw new x("DEFINITION_UNSUPPORTED","UI action declaration is invalid");if(t.confirmation!==void 0&&t.confirmation!=="none"&&t.confirmation!=="native")throw new x("DEFINITION_UNSUPPORTED","UI action confirmation is invalid");if(t.inputKeys&&(!Array.isArray(t.inputKeys)||t.inputKeys.some(i=>typeof i!="string"||!i)))throw new x("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 x("DEFINITION_UNSUPPORTED","UI action data input declaration is invalid");if(t.resultProjection&&Rt(t.resultProjection),t.content!==void 0&&!jn(t.content))throw new x("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 x("DEFINITION_UNSUPPORTED","UI action environment declaration is invalid")}if(e.renderer!==void 0&&(!e.renderer||e.renderer.length>128))throw new x("DEFINITION_UNSUPPORTED","UI definition renderer is invalid");if(e.surfaces&&(!Array.isArray(e.surfaces)||e.surfaces.some(n=>!n||n.length>64)))throw new x("DEFINITION_UNSUPPORTED","UI definition surfaces are invalid");if(e.usage!==void 0&&e.usage!=="card"&&e.usage!=="window")throw new x("DEFINITION_UNSUPPORTED","UI definition usage is invalid");if(e.detailPanel!==void 0&&typeof e.detailPanel!="boolean")throw new x("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 x("DEFINITION_UNSUPPORTED","UI definition displayModes are invalid");if(e.usage==="card"&&e.displayModes!==void 0)throw new x("DEFINITION_UNSUPPORTED","Card definitions cannot declare displayModes");if(e.usage==="window"&&e.detailPanel!==void 0)throw new x("DEFINITION_UNSUPPORTED","Window definitions cannot declare detailPanel");if(e.stateProjection&&Rt(e.stateProjection),e.summaryProjection){Rt(e.summaryProjection);let n=new Set(e.stateProjection?.allow??[]);if(e.summaryProjection.allow.some(t=>!n.has(t)))throw new x("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 x("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(xs(r,o==="readTool"),n.has(r.name))throw new x("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 x("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 x("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 x("DEFINITION_UNSUPPORTED","UI legacy agent access is invalid");if(e.legacy.actionTool!==void 0&&(!i||Object.keys(i).length===0))throw new x("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=>Ze(t,i))))throw new x("DEFINITION_UNSUPPORTED","UI definition dataPaths are invalid")}}function xs(e,n){if(!e||typeof e!="object"||Array.isArray(e))throw new x("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 x("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 c=ye(a.structuredContent);if(_t(Qe(c))>4*1024)throw new Error("fixed result size")}}catch{throw new x("DEFINITION_UNSUPPORTED","UI legacy tool metadata is not projection-safe")}}function Rt(e){if(!Array.isArray(e.allow)||e.allow.some(n=>!/^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)*$/.test(n)))throw new x("DEFINITION_UNSUPPORTED","UI projection policy is invalid")}function vs(e){return e.length>0&&e.length<=128&&e!=="*"&&e!=="all"&&!/[/*]/.test(e)}var ks,He=B(()=>{m();Le();kn();Lt();ks=/^[0-9a-f]{64}$/;});var H,nn,wt=B(()=>{m();H="dist/tools.json",nn="dist/main.mjs";});var xe,Ct=B(()=>{m();xe="window";});function Ui(e){if(!Array.isArray(e)||e.length===0)return false;let n=new Set;for(let t of e){if(!js.some(i=>i===t)||n.has(t))return false;n.add(t);}return true}var js,ki=B(()=>{m();js=["CREWX_APP_INSTANCE_ID","CREWX_THREAD_ID"];});function z(e){throw new Ut(e)}function Ys(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 qs(e,n){let t=Object.getOwnPropertyDescriptor(e,n);return (!t||!("value"in t))&&z("CSP_ORIGIN_INVALID"),t.value}function Fn(e,n){if(!Object.prototype.hasOwnProperty.call(e,n))return [];let t=qs(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 Zs(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 ji(e,n){/\s|\\/u.test(e)&&z("CSP_ORIGIN_INVALID");let t=Gs.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("[")?Ws:Js).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 d=a.endsWith(".")?a.slice(0,-1):a;(d.length===0||d.length>253)&&z("CSP_ORIGIN_INVALID"),d.split(".").some(p=>p.length>63||!Ks.test(p))&&z("CSP_ORIGIN_INVALID");}let c=s.origin;return (c==="null"||!c.startsWith(`${i}://`))&&z("CSP_ORIGIN_INVALID"),{origin:c,hostname:a}}function Qs(e){let n=e.split(".").map(Number);return ((n[0]*256+n[1])*256+n[2])*256+n[3]}function Fi(e,n,t){let i=4294967295<<32-t>>>0;return (e&i)===(n&i)}function Hi(e){let n=Qs(e);return Fi(n,3221225472,24)?n!==3221225481&&n!==3221225482:Xs.some(([t,i])=>Fi(n,t,i))}function ea(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 na(e){let n=ea(e),t=Number(n>>112n),i=Number(n>>96n&0xffffn);if(n>>32n===0xffffn){let o=Number(n&0xffffffffn);return Hi([o>>>24&255,o>>>16&255,o>>>8&255,o&255].join("."))}return t<8192||t>16383||t===8193&&i<=511||t===8193&&i===3512||t===8194||t===16383&&i<=4095}function ta(e,n){let t=e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e,i=isIP(t);if(i===4)return Hi(t);if(i===6)return na(t);let o=e.toLowerCase().replace(/\.$/,"");return !o||!o.includes(".")||n.has(o)?true:$s.some(r=>o===r||o.endsWith(`.${r}`))}function Vi(e){return Object.freeze([...new Set(e.map(n=>n.origin))].sort())}function Bi(e){return JSON.stringify({baseUriDomains:[],connectDomains:e.connectDomains,declared:e.declared,frameDomains:e.frameDomains,resourceDomains:[]})}function zi(e,n={}){if(e===void 0){let f=Bi({declared:false,connectDomains:[],frameDomains:[]});return Object.freeze({declared:false,connectDomains:Object.freeze([]),frameDomains:Object.freeze([]),resourceDomains:Object.freeze([]),baseUriDomains:Object.freeze([]),cspHash:createHash("sha256").update(f,"utf8").digest("hex")})}Ys(e)||z("CSP_ORIGIN_INVALID");let t=Reflect.ownKeys(e);t.some(f=>typeof f!="string")&&z("CSP_ORIGIN_INVALID"),t.some(f=>!zs.has(f))&&z("CSP_AXIS_UNKNOWN");let i=Fn(e,"connectDomains"),o=Fn(e,"frameDomains"),r=Fn(e,"resourceDomains"),s=Fn(e,"baseUriDomains");(r.length>0||s.length>0)&&z("CSP_AXIS_UNSUPPORTED"),(Zs(e)>Vs||i.length>vi||o.length>vi||i.length+o.length>Bs||[...i,...o].some(f=>new TextEncoder().encode(f).byteLength>Hs))&&z("CSP_LIMIT_EXCEEDED");let c=i.map(f=>ji(f,"connectDomains")),d=o.map(f=>ji(f,"frameDomains")),l=new Set((n.runtimeHostnames??[]).map(f=>f.toLowerCase().replace(/\.$/,"")));[...c,...d].some(f=>ta(f.hostname,l))&&z("CSP_ORIGIN_FORBIDDEN");let p={declared:true,connectDomains:Vi(c),frameDomains:Vi(d)},u=Bi(p);return Object.freeze({...p,resourceDomains:Object.freeze([]),baseUriDomains:Object.freeze([]),cspHash:createHash("sha256").update(u,"utf8").digest("hex")})}var Vs,vi,Bs,Hs,zs,$s,Gs,Ws,Js,Ks,Xs,Ut,$i=B(()=>{m();Vs=4096,vi=16,Bs=32,Hs=512,zs=new Set(["connectDomains","frameDomains","resourceDomains","baseUriDomains"]),$s=["localhost","local","internal","home.arpa","test","example","invalid","onion","lan","corp","home","intranet","private","localdomain"],Gs=/^(https|wss):\/\/([^/?#]+)$/i,Ws=/^\[[^\]]+\](?::[0-9]+)?$/,Js=/^[^:\[\]]+(?::[0-9]+)?$/,Ks=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/,Xs=[[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]],Ut=class extends Error{constructor(t){super(t);this.code=t;}code;name="UiPluginCspNormalizationError"};});function gn(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 v(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function Ra(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=>!v(e,s));r!==void 0&&A("MANIFEST_INVALID","MANIFEST_INVALID",r,"missing-key");}function zn(e,n=false,t=false,i=false){return sa.test(e)||!i&&ca.test(e)||aa.test(e)||t&&Gi.test(e)||da.test(e)&&!(n&&/^\s*data:/i.test(e)&&!Gi.test(e))}function Hn(e,n=new Set,t=0,i=false,o=false,r=""){if(typeof e=="string"){zn(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)=>Hn(s,n,t+1,!1,!1,gn(r,`[${a}]`)));return}G(e)||A("MANIFEST_INVALID","MANIFEST_INVALID",r);for(let[s,a]of Object.entries(e))Hn(a,n,t+1,i&&t===0&&(s==="name"||s==="description"),o,gn(r,s));}finally{n.delete(e);}}}function Pe(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 kt(e){return ra.test(e)||A("MANIFEST_INVALID"),e}function tn(e){return oa.test(e)||A("TOKEN_INVALID"),e}function Oa(e){return eo.test(e)||A("MANIFEST_INVALID"),e}function wa(e){G(e)||A("MANIFEST_INVALID");let n={};for(let[t,i]of Object.entries(e)){let o=Oa(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 Ca(e,n,t){let i=e[n];(!i||i.type!==t)&&A("MANIFEST_INVALID");}function Vn(e,n,t){let i=Pe(e,"field");return eo.test(i)||A("MANIFEST_INVALID"),Ca(n,i,t),i}function Ua(e,n){G(e)||A("MANIFEST_INVALID");let t=e.primitive;switch(typeof t!="string"&&A("MANIFEST_INVALID"),La.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:tn(Pe(e,"badgeToken")),noticeToken:tn(Pe(e,"noticeToken"))};case "heading":return X(e,["primitive","field"]),{primitive:t,field:Vn(e,n,"text")};case "labeled-text":return X(e,["primitive","titleToken","field","variant"]),e.variant!=="callout"&&A("MANIFEST_INVALID"),{primitive:t,titleToken:tn(Pe(e,"titleToken")),field:Vn(e,n,"text"),variant:"callout"};case "step-flow":return X(e,["primitive","titleToken","field"]),{primitive:t,titleToken:tn(Pe(e,"titleToken")),field:Vn(e,n,"step-list")};case "text-list":{X(e,["primitive","titleToken","field"],["emptyToken","hideWhenEmpty"]);let i={primitive:t,titleToken:tn(Pe(e,"titleToken")),field:Vn(e,n,"text-list")};return v(e,"emptyToken")&&(i.emptyToken=tn(Pe(e,"emptyToken"))),v(e,"hideWhenEmpty")&&(typeof e.hideWhenEmpty!="boolean"&&A("MANIFEST_INVALID"),i.hideWhenEmpty=e.hideWhenEmpty),i}}return A("MANIFEST_INVALID")}function ka(e,n){return Array.isArray(e)||A("MANIFEST_INVALID"),e.map(t=>Ua(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 Wi(e,n){return (typeof e!="string"||e.length===0||e.length>4096||e.trim().length===0||ba.test(e)||Sa.test(e))&&A("MANIFEST_INVALID",`${n} is invalid`),(zn(e,true,true)||pa.test(e)||la.test(e)||ua.test(e))&&A("UNSAFE_VALUE",`${n} contains an unsafe value`),e}function xt(e,n){return (typeof e!="string"||!Te.test(e))&&A("MANIFEST_INVALID",`${n} is invalid`),e}function xa(e){return (typeof e!="string"||!Tt.test(e)||e==="*"||e==="all")&&A("MANIFEST_INVALID","action capability is invalid"),e}function no(e){return (typeof e!="string"||!Da.test(e))&&A("MANIFEST_INVALID","resource hash is invalid"),e}function vt(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)=>vt(o,n,t+1,gn(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))vt(r,n,t+1,gn(i,o));}finally{n.delete(e);}}}function to(e){return (typeof e!="string"||e.length>4096||!An.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=>en(t))&&A("MANIFEST_INVALID","projection paths cannot address reserved state keys"),e}function jt(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=to(i);t.has(o)&&A("MANIFEST_INVALID","projection allowlist contains a duplicate path"),t.add(o),n.push(o);}return {allow:n}}function va(e,n){if(e===void 0)return;Array.isArray(e)||A("MANIFEST_INVALID","dataPaths must be an array"),e.length>Ma&&Y("dataPaths exceed the v2 limit");let t=[],i=new Set;for(let o of e){let r=to(o);i.has(r)&&A("MANIFEST_INVALID","dataPaths contain a duplicate path"),n.some(s=>Ze(r,s))||A("MANIFEST_INVALID","dataPaths must be projection-allowed"),i.add(r),t.push(r);}return t}function on(e,n,t=Number.MAX_SAFE_INTEGER){return (!Number.isSafeInteger(e)||e<0||e>t)&&A("MANIFEST_INVALID",`${n} is invalid`),e}function Ji(e,n){return (typeof e!="number"||!Number.isFinite(e))&&A("MANIFEST_INVALID",`${n} is invalid`),e}function Ft(e,n=0,t=new Set){if(typeof e=="string")return (e.length>4096||zn(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=>Ft(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))en(o)&&A("MANIFEST_INVALID","schema enum contains a reserved key"),i[o]=Ft(r,n+1,t);return i}finally{t.delete(e);}}function ja(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"||!An.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 Fa(e,n){let t=n?An:vn;return e.length>4096&&Y("schema property name is too long"),(!t.test(e)||e.split(".").some(i=>en(i)))&&A("MANIFEST_INVALID","schema property name is invalid"),e}function Vt(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(v(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=>Ft(a))),i==="string"&&(v(e,"minLength")&&(r.minLength=on(e.minLength,"schema minLength",4096)),v(e,"maxLength")&&(r.maxLength=on(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")&&(v(e,"minimum")&&(r.minimum=Ji(e.minimum,"schema minimum")),v(e,"maximum")&&(r.maximum=Ji(e.maximum,"schema maximum")),r.minimum!==void 0&&r.maximum!==void 0&&r.minimum>r.maximum&&A("MANIFEST_INVALID","schema numeric bounds are inverted")),i==="array"&&(v(e,"minItems")&&(r.minItems=on(e.minItems,"schema minItems",128)),v(e,"maxItems")&&(r.maxItems=on(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"),v(e,"items")&&(r.items=Vt(e.items,n+1,false))),i==="object"){let a;if(v(e,"properties")){G(e.properties)||A("MANIFEST_INVALID","schema properties must be an object");let d=Object.entries(e.properties);d.length>64&&Y("schema properties are too many"),a={};for(let[l,p]of d){let u=Fa(l,t);a[u]=Vt(p,n+1,false);}r.properties=a;}v(e,"minProperties")&&(r.minProperties=on(e.minProperties,"schema minProperties",64)),v(e,"maxProperties")&&(r.maxProperties=on(e.maxProperties,"schema maxProperties",64)),r.minProperties!==void 0&&r.maxProperties!==void 0&&r.minProperties>r.maxProperties&&A("MANIFEST_INVALID","schema object property bounds are inverted");let c=ja(e.required,a);c!==void 0&&(r.required=c),v(e,"additionalProperties")&&(e.additionalProperties!==false&&A("MANIFEST_INVALID","schema additionalProperties must be false"),r.additionalProperties=false);}let s=JSON.stringify(r);return (s===void 0||Buffer.byteLength(s,"utf8")>2097152)&&Y("action inputSchema subtree is too large"),r}function Va(e){let n=Vt(e,0,true);return (n.type!=="object"||!n.properties)&&A("MANIFEST_INVALID","action inputSchema must declare object properties"),n}function Ba(e){if(G(e)||A("MANIFEST_INVALID","action backend must be an object"),e.type==="core"){X(e,ha);let n=e.handler;return (typeof n!="string"||!Pt.test(n))&&A("MANIFEST_INVALID","core backend handler is invalid"),{type:"core",handler:n}}if(e.type==="skill"&&v(e,"entry"))return X(e,Ta),e.entry!==nn&&A("MANIFEST_INVALID",`skill backend entry must be ${nn}`),{type:"skill",entry:nn};if(e.type==="skill"){X(e,_a,Ea),(!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||!Nt.test(i))&&A("MANIFEST_INVALID","skill backend command token is invalid"),n.push(i);let t=v(e,"env")?za(e.env):void 0;return {type:"skill",command:n,...t===void 0?{}:{env:t}}}A("MANIFEST_INVALID","action backend type is unsupported");}function Ha(e){G(e)||A("MANIFEST_INVALID","action must be an object"),X(e,Ia,ga),v(e,"_meta")&&$("_meta",()=>io(e._meta));let n=$("actionId",()=>xt(e.actionId,"actionId"));ht(n)&&A("MANIFEST_INVALID",`actionId "${n}" is not projection-safe`,"actionId");let t=$("capability",()=>xa(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(v(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"||!v(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",()=>jt(e.resultProjection)),a=$("backend",()=>Ba(e.backend)),c;v(e,"content")&&((a.type!=="skill"||!jn(e.content))&&A("MANIFEST_INVALID","action content declaration is invalid","content"),c=$a(e.content));let d;if(v(e,"confirmation")){let l=e.confirmation;l!=="none"&&l!=="native"&&A("MANIFEST_INVALID","action confirmation is invalid","confirmation"),d=l;}return {actionId:n,capability:t,mutation:i,inputSchema:o,resultProjection:s,backend:a,...c===void 0?{}:{content:c},...r===void 0?{}:{dataInputs:r},...d===void 0?{}:{confirmation:d}}}function za(e){return Ui(e)||A("MANIFEST_INVALID","skill backend env is invalid"),Object.freeze([...e])}function $a(e){return Object.freeze({...e.in===void 0?{}:{in:Object.freeze({...e.in})},...e.out===void 0?{}:{out:Object.freeze({...e.out})}})}function Ga(e){return G(e)||A("INITIAL_STATE_INVALID","initialState must be an object"),X(e,Pa,Na),e.path!=="ui/state.json"&&A("MANIFEST_INVALID","initialState path is not fixed"),v(e,"hash")?{path:"ui/state.json",hash:no(e.hash)}:{path:"ui/state.json"}}function Wa(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 Ja(e,n){let t;try{t=zi(e);}catch(i){let o=i!==null&&typeof i=="object"&&"code"in i&&typeof i.code=="string"?i.code:"CSP_ORIGIN_INVALID";return A("MANIFEST_INVALID",o,void 0,o.toLowerCase().replace(/_/g,"-"))}if(t.frameDomains.length>0&&A("MANIFEST_INVALID","external origins in csp are not enabled in this rollout",void 0,"csp-not-enabled"),t.connectDomains.length!==0)return n?.terminal===true&&A("MANIFEST_INVALID","runtime.terminal cannot be combined with csp.connectDomains","connectDomains","terminal-with-connect-domains"),Object.freeze({connectDomains:t.connectDomains})}function Ka(e,n){Hn(G(e)&&v(e,"csp")?Ra(e,"csp"):e,new Set,0,true,true),vt(e),G(e)||A("MANIFEST_INVALID"),X(e,ya,Aa),v(e,"_meta")&&$("_meta",()=>io(e._meta)),e.manifestVersion!==2&&A("MANIFEST_INVALID");let t;v(e,"runtime")&&(t=$("runtime",()=>Wa(e.runtime)));let i;v(e,"csp")&&(i=$("csp",()=>Ja(e.csp,t)));let o=$("pluginId",()=>xt(e.pluginId,"pluginId")),r=$("definitionId",()=>xt(e.definitionId,"definitionId")),s=$("version",()=>ge(e,"version",1)),a=$("name",()=>Wi(e.name,"name")),c=$("description",()=>Wi(e.description,"description")),d;v(e,"icon")&&((typeof e.icon!="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(e.icon))&&A("MANIFEST_INVALID","icon is invalid","icon"),d=e.icon);let l;v(e,"tone")&&((typeof e.tone!="string"||!Dt.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;v(e,"entryHash")&&(p=$("entryHash",()=>no(e.entryHash)));let u;v(e,"initialState")&&(u=$("initialState",()=>Ga(e.initialState)));let f;v(e,"usage")&&(e.usage!=="card"&&e.usage!=="window"&&A("MANIFEST_INVALID","usage is invalid","usage"),f=e.usage);let g;v(e,"detailPanel")&&(typeof e.detailPanel!="boolean"&&A("MANIFEST_INVALID","detailPanel is invalid","detailPanel"),g=e.detailPanel);let _;if(v(e,"displayModes")){((f??xe)!==xe||!Array.isArray(e.displayModes)||e.displayModes.length===0)&&A("MANIFEST_INVALID","displayModes are only valid for window Apps","displayModes");let y=new Set(["inline","floating","focused"]);(new Set(e.displayModes).size!==e.displayModes.length||e.displayModes.some(I=>typeof I!="string"||!y.has(I)))&&A("MANIFEST_INVALID","displayModes are invalid","displayModes"),_=e.displayModes;}(f??xe)===xe&&g!==void 0&&A("MANIFEST_INVALID","detailPanel is card-only","detailPanel");let P=n.mode??"local";P!=="local"&&P!=="installed"&&P!=="published"&&A("MANIFEST_INVALID","manifest mode is invalid"),P!=="local"&&p===void 0&&A("MANIFEST_INVALID","installed manifests require entryHash","entryHash","required-when-installed"),P!=="local"&&u!==void 0&&u.hash===void 0&&A("MANIFEST_INVALID","installed manifests require initialState.hash","initialState.hash","required-when-installed"),(!Array.isArray(e.surfaces)||e.surfaces.length===0)&&A("MANIFEST_INVALID","surfaces are invalid","surfaces"),e.surfaces.length>2&&Y("surfaces exceed the v2 limit","surfaces","too-many-items");let U=[],k=new Set;for(let y of e.surfaces)(typeof y!="string"||!bt.includes(y))&&A("MANIFEST_INVALID","surface is unsupported","surfaces"),k.has(y)&&A("MANIFEST_INVALID","surfaces contain a duplicate","surfaces","duplicate-item"),k.add(y),U.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",()=>jt(e.stateProjection)),F=e.summaryProjection===void 0?void 0:$("summaryProjection",()=>jt(e.summaryProjection));F!==void 0&&F.allow.some(y=>!C.allow.includes(y))&&A("MANIFEST_INVALID","summaryProjection must be a subset of stateProjection.allow","summaryProjection");let D=$("dataPaths",()=>va(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 b=[],R=new Set;for(let[y,I]of e.actions.entries()){let h=`actions[${y}]`,E=$(h,()=>Ha(I));if(R.has(E.actionId)&&A("MANIFEST_INVALID","actions contain a duplicate actionId",`${h}.actionId`,"duplicate-item"),E.backend.type==="core"&&E.backend.handler==="state.set"){E.mutation||A("MANIFEST_INVALID","state.set actions must be mutations",`${h}.mutation`);for(let L of Object.keys(E.inputSchema.properties))C.allow.includes(L)||A("MANIFEST_INVALID","state.set input paths must be projection-allowed",`${h}.inputSchema.properties`);}R.add(E.actionId),b.push(E);}return {manifestVersion:2,pluginId:o,definitionId:r,version:s,name:a,description:c,...d===void 0?{}:{icon:d},...l===void 0?{}:{tone:l},entry:"ui/index.html",...p===void 0?{}:{entryHash:p},...t===void 0?{}:{runtime:t},...i===void 0?{}:{csp:i},...u===void 0?{}:{initialState:u},...f===void 0?{}:{usage:f},...g===void 0?{}:{detailPanel:g},..._===void 0?{}:{displayModes:_},surfaces:U,size:{height:N},stateProjection:C,...F===void 0?{}:{summaryProjection:F},...D===void 0?{}:{dataPaths:D},actions:b}}function io(e){G(e)||A("MANIFEST_INVALID","_meta must be an object");let n=JSON.stringify(e);(n===void 0||Buffer.byteLength(n,"utf8")>ma)&&Y("_meta exceeds the 4 KiB limit",void 0,"meta-too-large");}function Xa(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=>Ze(o.join("."),a));return (e.length>4096||zn(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(c=>Bt(c,n,t+1,2097152,o,r));else {G(e)||Ie("state contains a non-plain object");let c={};for(let[d,l]of Object.entries(e))(d.length>4096||!vn.test(d)||en(d))&&(d.length>4096&&Ie("state key is too long"),Ie("state contains a reserved or invalid key")),c[d]=Bt(l,n,t+1,2097152,[...o,d],r);s=c;}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 zt(e,n=[]){G(e)||Ie("initial state must be a JSON object");let t=Bt(e,new Set,0,2097152,[],n);return (t===null||Array.isArray(t)||typeof t!="object")&&Ie(),t}function Ya(e,n={}){Hn(e),G(e)||A("MANIFEST_INVALID"),X(e,fa),e.manifestVersion!==1&&A("MANIFEST_INVALID");let t=kt(Pe(e,"pluginId")),i=kt(Pe(e,"definitionId")),o=ge(e,"version",1),r=ge(e,"primitiveSet",1),s=n.supportedPrimitiveSet??ia;(!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=kt(Pe(e.activation,"language")),c=wa(e.schema),d=ka(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 qa(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?Ka(e,n):Ya(e,n)}function $e(e,n={}){try{return qa(e,n)}catch(t){if(t instanceof se)throw t;return A("MANIFEST_INVALID")}}function mn(e,n={}){let t=$e(e,n);return t.manifestVersion===2?Xa(t):t}var ia,oa,ra,eo,sa,aa,ca,da,Gi,pa,la,ua,fa,ya,Aa,Ia,ga,ma,ha,_a,Ea,Ta,Pa,Na,Da,ba,Sa,Ma,La,se,$t=B(()=>{m();Ct();Le();Lt();ki();wt();$i();Be();ia=1,oa=/^[a-z][a-zA-Z0-9]*(\.[a-zA-Z0-9]+)+$/,ra=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,eo=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,sa=/<\/?[A-Za-z][^>]*>/,aa=/^(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)/,ca=/^(?:https?|file|ftp|ws|wss):\/\//i,da=/^\s*(?:javascript|data):/i,Gi=/data:[^,\s]*,/i,pa=/(?:https?|file|ftp|ws|wss):\/\//i,la=/javascript:/i,ua=/(?:^[\s]*|[\s"'(=])(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)(?=[^\s"'<>])[^\s"'<>]*/,fa=["manifestVersion","pluginId","definitionId","version","primitiveSet","activation","schema","layout"],ya=["manifestVersion","pluginId","definitionId","version","name","description","entry","surfaces","size","stateProjection","actions"],Aa=["_meta","icon","tone","entryHash","runtime","csp","initialState","usage","detailPanel","displayModes","summaryProjection","dataPaths","focusedAiDataPaths"],Ia=["actionId","capability","mutation","inputSchema","resultProjection","backend"],ga=["confirmation","dataInputs","content","_meta"],ma=4*1024,ha=["type","handler"],_a=["type","command"],Ea=["env"],Ta=["type","entry"],Pa=["path"],Na=["hash"],Da=/^[0-9a-f]{64}$/,ba=/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/,Sa=/[\r\n]/,Ma=16,La=["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,gn(t,this.path),this.rule)}};});function po(e){return typeof e=="string"&&e.length<=Qa&&Za.test(e)}function j(e,n,t,i,o){throw new De(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["${ve}"]`;return e===void 0||e===""?n:e.startsWith("[")?`${n}${e}`:`${n}.${e}`}function ic(e){return e.toLowerCase().replace(/_/g,"-")}function oc(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 lo(e,n,t){return {path:t(e.path),rule:e.rule??ic(e.code),...e.message!==e.code?{message:e.message}:{},file:n}}function uo(e){return JSON.parse(JSON.stringify(e))}function Jt(e,n,t=0,i=new Set){if(typeof e=="string"){e.length>4096&&j("LIMIT_EXCEEDED",n,"string-too-long"),(ec.test(e)||nc.test(e)||tc.test(e))&&j("UNSAFE_VALUE",n,"unsafe-value");return}if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){Number.isFinite(e)||j("MANIFEST_INVALID",n,"non-finite-number");return}typeof e!="object"&&j("MANIFEST_INVALID",n,"non-json-value"),t>8&&j("LIMIT_EXCEEDED",n,"too-deep"),i.has(e)&&j("MANIFEST_INVALID",n,"cycle"),i.add(e);try{if(Array.isArray(e)){e.length>128&&j("LIMIT_EXCEEDED",n,"array-too-long"),e.forEach((o,r)=>Jt(o,`${n}[${r}]`,t+1,i));return}ie(e)||j("MANIFEST_INVALID",n,"non-plain-object");for(let[o,r]of Object.entries(e))Jt(r,n===""?o:`${n}.${o}`,t+1,i);}finally{i.delete(e);}}}function me(e,n){return (typeof e!="string"||e.length===0)&&j("MANIFEST_INVALID",n,"string"),e}function sn(e,n){return ie(e)||j("MANIFEST_INVALID",n,"object"),e}function rc(e,n){Array.isArray(e)||j("MANIFEST_INVALID",n,"array"),e.forEach((t,i)=>me(t,`${n}[${i}]`));}function sc(e,n){typeof e!="boolean"&&j("MANIFEST_INVALID",n,"boolean");}function hn(e,n,t,i){for(let o of Object.keys(e))!t.includes(o)&&!i.includes(o)&&j("MANIFEST_INVALID",`${n}.${o}`,"unknown-key");for(let o of t)q(e,o)||j("MANIFEST_INVALID",`${n}.${o}`,"missing-key");}function ac(e,n){switch(Jt(n,e),e){case "long_description":case "homepage":case "documentation":case "support":case "icon":case "license":me(n,e);return;case "author":{let t=sn(n,e);hn(t,e,["name"],["email","url"]);for(let i of Object.keys(t))me(t[i],`${e}.${i}`);return}case "repository":{let t=sn(n,e);hn(t,e,[],["type","url"]);for(let i of Object.keys(t))me(t[i],`${e}.${i}`);return}case "icons":{Array.isArray(n)||j("MANIFEST_INVALID",e,"array"),n.forEach((t,i)=>{let o=`${e}[${i}]`,r=sn(t,o);hn(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":rc(n,e);return;case "tools":{Array.isArray(n)||j("MANIFEST_INVALID",e,"array"),n.forEach((t,i)=>{let o=`${e}[${i}]`,r=sn(t,o);hn(r,o,["name"],["description"]),me(r.name,`${o}.name`),q(r,"description")&&me(r.description,`${o}.description`);});return}case "prompts":{Array.isArray(n)||j("MANIFEST_INVALID",e,"array"),n.forEach((t,i)=>{let o=`${e}[${i}]`,r=sn(t,o);hn(r,o,["name","text"],["description","arguments"]),me(r.name,`${o}.name`),me(r.text,`${o}.text`);});return}case "tools_generated":case "prompts_generated":sc(n,e);return;case "localization":case "compatibility":case "user_config":sn(n,e);return;default:j("MANIFEST_INVALID",e,"unknown-key");}}function $n(e){return typeof e=="string"&&Te.test(e)?e:void 0}function fo(e){return Number.isSafeInteger(e)&&e>=1?e:void 0}function cc(e){let n=$n(e.name);if(n===void 0)return;let t=e._meta,i=ie(t)?t[ve]:void 0,o=ie(i)?i:{},r=q(o,"definitionId")?$n(o.definitionId):n,s=q(o,"definitionVersion")?fo(o.definitionVersion):1;return {pluginId:n,...r===void 0?{}:{definitionId:r},...s===void 0?{}:{definitionVersion:s}}}function dc(e){let n=$n(e.pluginId);if(n===void 0)return;let t=$n(e.definitionId),i=fo(e.version);return {pluginId:n,...t===void 0?{}:{definitionId:t},...i===void 0?{}:{definitionVersion:i}}}function Yt(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,ve)}catch{return false}}function pc(e,n){if(e===de)return n.builtinOnly===true;let t=n._meta,i=ie(t)?t[ve]:void 0;return ie(i)&&i.builtinOnly===true}function lc(e,n){q(e,"server")&&j("MANIFEST_INVALID","server","server-unsupported","phase 1 runs CrewX-owned Apps only");for(let a of Object.keys(e))Kt.includes(a)||j("MANIFEST_INVALID",a,"unknown-key");for(let a of Xt)q(e,a)||j("MANIFEST_INVALID",a,"missing-key");e.manifest_version!==Gt&&j("MANIFEST_INVALID","manifest_version","unsupported-version",`manifest_version must be "${Gt}"`),po(e.version)||j("MANIFEST_INVALID","version","semver","version must be a semver.org version such as 0.1.0");let t=e._meta;ie(t)||j("MANIFEST_INVALID","_meta","object"),q(t,ve)||j("MANIFEST_INVALID",he(),"missing-key");let i=t[ve];ie(i)||j("MANIFEST_INVALID",he(),"object");for(let a of Object.keys(i))Wt.includes(a)||co.includes(a)||j("MANIFEST_INVALID",he(a),"unknown-key");for(let a of Wt)a==="actions"&&n!==void 0||q(i,a)||j("MANIFEST_INVALID",he(a),"missing-key");if(n!==void 0&&q(i,"actions")&&j("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`),uc(i.actions),q(i,"definitionVersion")){let a=i.definitionVersion;(!Number.isSafeInteger(a)||a<1)&&j("MANIFEST_INVALID",he("definitionVersion"),"positive-integer");}let o={};for(let a of ao)q(e,a)&&(ac(a,e[a]),o[a]=uo(e[a]));let r={};for(let[a,c]of Object.entries(t))a!==ve&&(r[a]=c);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,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:nn}}))),Object.keys(r).length>0&&(s._meta=r),{v2Input:s,...Object.keys(r).length>0?{vendorMeta:r}:{},passthrough:o}}function uc(e){Array.isArray(e)&&e.forEach((n,t)=>{let i=ie(n)?n.backend:void 0;ie(i)&&q(i,"entry")&&j("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 fc(e,n,t){ie(e)||j("MANIFEST_INVALID","","not-object","manifest.json must be a JSON object",W);let i;try{i=lc(e,t);}catch(s){throw s instanceof De?new De(s.code,{...s.reason,file:W}):s}let o;try{let s=$e(i.v2Input,{mode:n.mode??"local"});s.manifestVersion!==2&&j("MANIFEST_INVALID","","v2-required"),o=s;}catch(s){throw s instanceof se?new De(s.code,lo(s,W,oc)):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 De("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 yc(e,n){try{let t=$e(e,{mode:n.mode??"local"});if(t.manifestVersion!==2)throw new De("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 De(t.code,lo(t,de,i=>i??"")):t}}function an(e){return le(mn(e).definition)}function ro(e){let{entryHash:n,initialState:t,...i}=e,o={...i};return t!==void 0&&(o.initialState={path:t.path}),uo(o)}function Ac(e,n){let t=ro(e),i=ro(n);return [...new Set([...Object.keys(t),...Object.keys(i)])].sort().filter(r=>te(t[r]??null)!==te(i[r]??null))}function Ic(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 gc(e,n){let t=Ac(e,n),i=Ic(e,n),o="";try{let r=an(e),s=an(n);i=i||r!==s,o=` (definition hash ${r.slice(0,12)} vs ${s.slice(0,12)})`;}catch{i=true;}t.length===0&&!i||j("MANIFEST_DUAL_MISMATCH","","dual-manifest-mismatch",`${W} and ${de} normalize to different definitions${o}`+(t.length>0?`; differing fields: ${t.join(", ")}`:""));}function Ne(e,n,t="MANIFEST_INVALID",i){return {code:t,reason:{path:e,rule:n,...i===void 0?{}:{message:i},file:H},files:[]}}function so(e){return {...Ne("","tools-needs-manifest-json","MANIFEST_INVALID",`${H} is read with ${W} only`),files:e}}function mc(e,n){if(e.byteLength>n)return {failure:Ne("","file-too-large","LIMIT_EXCEEDED")};let t;try{t=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e));}catch{return {failure:Ne("","invalid-json")}}if(!ie(t))return {failure:Ne("","not-object","MANIFEST_INVALID",`${H} must be a JSON object`)};for(let o of Object.keys(t))if(o!=="schemaVersion"&&o!=="actions")return {failure:Ne(o,"unknown-key")};for(let o of ["schemaVersion","actions"])if(!q(t,o))return {failure:Ne(o,"missing-key")};if(t.schemaVersion!==1)return {failure:Ne("schemaVersion","unsupported-version","MANIFEST_INVALID",`schemaVersion must be ${1}`)};let i=t.actions;if(!Array.isArray(i))return {failure:Ne("actions","array")};for(let[o,r]of i.entries()){if(!ie(r))return {failure:Ne(`actions[${o}]`,"object")};if(q(r,"backend"))return {failure:Ne(`actions[${o}].backend`,"tools-backend","MANIFEST_INVALID",`an action in ${H} cannot carry a backend`)}}return {actions:i}}function hc(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 Ge(e,n={}){let{parsed:t,failure:i}=hc(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:mc(r,n.maxBytes??262144);if(t.length===0)return {ok:false,rejection:s===void 0?{code:"MANIFEST_INVALID",reason:{path:"",rule:"no-manifest-file",message:"neither manifest.json nor ui-plugin.json is present"},files:[]}:so(o),parseFailure:true,builtinOnly:false};let a=t[0],c=a.file===W?cc(a.raw):dc(a.raw),d=t.some(f=>pc(f.file,f.raw)),l;if(s!==void 0){let f=t.some(g=>g.file===W)?s.failure:so(o);if(f!==void 0)return {ok:false,rejection:f,parseFailure:false,...c===void 0?{}:{identity:c},builtinOnly:d};l=s.actions;}let p=[];try{for(let f of t)p.push(f.file===W?fc(f.raw,n,l):yc(f.raw,n));p.length===2&&gc(p[0].manifest,p[1].manifest);}catch(f){if(f instanceof De)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,...c===void 0?{}:{identity:c},builtinOnly:d};throw f}let u=p[0];return {ok:true,...u,identity:c??{pluginId:u.manifest.pluginId},files:o}}var W,de,Z,Gt,ve,Kt,Xt,ao,Wt,co,Za,Qa,ec,nc,tc,De,Gn=B(()=>{m();He();Le();wt();Be();$t();W="manifest.json",de="ui-plugin.json",Z=[W,de],Gt="0.3",ve="dev.crewx",Kt=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"]),Xt=Object.freeze(["manifest_version","name","display_name","version","description","_meta"]),ao=Object.freeze(Kt.filter(e=>e!=="server"&&!Xt.includes(e))),Wt=Object.freeze(["entry","surfaces","size","stateProjection","actions"]),co=Object.freeze(["definitionId","definitionVersion","icon","tone","entryHash","runtime","initialState","usage","detailPanel","displayModes","summaryProjection","dataPaths","focusedAiDataPaths","csp"]),Za=/^(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-]+)*))?$/,Qa=256,ec=/<\/?[A-Za-z][^>]*>/,nc=/^\s*javascript:/i,tc=/data:[^,\s]*,/i;De=class extends Error{constructor(t,i){super(`${t}: ${i.path||"<file>"} (${i.rule})`);this.code=t;this.reason=i;}code;reason};});var qt=B(()=>{m();Ri();Gn();$t();Be();});function S(e,n=e){throw new be(e,n)}var be,Jn=B(()=>{m();be=class extends Error{constructor(t,i=t){super(i);this.code=t;}code;name="McpAppContractError"};});var No=B(()=>{m();});var Do=B(()=>{m();He();Le();Jn();No();});function So(e,n){return bo.add(e),n!==void 0&&Oc.set(e,n),e}function cn(e){return e!==null&&typeof e=="object"&&bo.has(e)}var bo,Oc,Kn=B(()=>{m();bo=new WeakSet,Oc=new WeakMap;});function Pn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Qt(e,n,t=[]){let i=new Set([...n,...t]),o=Object.keys(e);return n.every(r=>Object.hasOwn(e,r))&&o.every(r=>i.has(r))}function 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 Se("LINEAGE_INVALID",e)}function jc(e){throw new Se("LINEAGE_STALE",e)}function Oo(e){if(!Pn(e)||!Qt(e,Uc,kc)||!Pn(e.actions))return oe("Lineage definition shape is invalid");for(let n of Object.values(e.actions))if(!Pn(n)||!Qt(n,xc,vc))return oe("Lineage action definition shape is invalid");return e}function Fc(e){if(!Pn(e)||!Qt(e,wc,Cc))return oe("Lineage entry shape is invalid");if(!Number.isSafeInteger(e.version)||e.version<1||typeof e.hash!="string"||!Mo.test(e.hash))return oe("Lineage entry identity is invalid");if(e.sourceHash!==void 0&&(typeof e.sourceHash!="string"||!Mo.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=Oo(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 Lo(e){return e.stateProjection?.allow??[]}function Vc(e,n){let t=[],i=new Set(Lo(n));Lo(e).some(a=>!i.has(a))&&t.push("S1_STATE_PROJECTION");let o=new Set(n.dataPaths??[]);(e.dataPaths??[]).some(a=>!o.has(a))&&t.push("S2_DATA_PATHS");for(let[a,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 Bc(e,n){return te(e)===te(n)}function ei(e,n){if(!Array.isArray(e)||e.length===0)return oe("Definition lineage is missing");if(!Pn(n)||typeof n.hash!="string")return oe("Current definition is invalid");let t,i;try{let{hash:a,...c}=n;i=Oo(c),t={...i,hash:a},Ae(t);}catch{return oe("Current definition is invalid")}let o=e.map(Fc),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,c)=>c>0&&a.version<=o[c-1].version))return oe("Lineage generations are not in increasing version order");if(o.some((a,c)=>o.findIndex(d=>d.hash===a.hash)!==c))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||!Bc(s.definition,i))return jc("The last lineage generation does not match the current package");if(t.legacy!==void 0){let a=new Set(Object.keys(t.actions)),c=new Set;for(let l of o)if(l.sourceHash===void 0)for(let p of Object.keys(l.definition.actions))a.has(p)&&c.add(p);let d=Object.keys(t.legacy.agentAccess??{});if(d.length!==c.size||d.some(l=>!c.has(l))){let l="S4_LEGACY_AGENT_ACCESS_COMPLETE";throw new Se("LINEAGE_INVALID",`Lineage compatibility failed: ${l}`,[l])}}for(let a=0;a<o.length-1;a+=1){if(o.slice(a,-1).some(l=>l.compat==="break"))continue;let d=Vc(o[a].definition,t);if(d.length>0)throw new Se("LINEAGE_INVALID",`Lineage compatibility failed: ${d.join(", ")}`,d)}return Object.freeze({entries:Object.freeze(o),current:t})}var Se,Mo,wc,Cc,Uc,kc,xc,vc,ni=B(()=>{m();He();Le();Se=class extends Error{constructor(t,i=t,o=[]){super(i);this.code=t;this.violations=o;}code;violations;name="UiDefinitionLineageError"},Mo=/^[0-9a-f]{64}$/,wc=["version","hash","definition"],Cc=["sourceHash","compat"],Uc=["id","version","actions"],kc=["sourceHash","usage","detailPanel","displayModes","renderer","surfaces","stateProjection","dataPaths","summaryProjection","legacy"],xc=["capabilities"],vc=["inputKeys","dataInputs","confirmation","resultProjection","content","env"];});var wo,Co,Uo,ko,xo=B(()=>{m();wo="text/html;profile=mcp-app",Co=["crewx_app_terminal_connect","crewx_app_html_viewer_open"],Uo=["crewx_listWorkspaces","crewx_queryAgent","crewx_executeAgent","crewx_getTaskResult","crewx_listTasks","crewx_listAgents","callBrowser","openTab","listTabs","closeTab"],ko="text/html";});function vo(e,n=[],t){if(e.content!==void 0||e.confirmation!=="none")return "denied";let i=Hc();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 Hc(e){return;}var jo=B(()=>{m();He();Kn();});function qc(e){return bn.has(e)&&(e.initialState===void 0||bn.has(e.initialState))}function zo(e,n,t,i){let o=i===void 0?void 0:Object.freeze({hash:i.hash,bytes:Object.freeze(i.bytes)}),r=Object.freeze({mimeType:ko,entryHash:e,html:n,bytes:Object.freeze(t),...o===void 0?{}:{initialState:o}});return o!==void 0&&bn.add(o),bn.add(r),r}function Zc(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:Fe}),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:Fe}),n}function Ve(e,n,t){return (typeof e!="string"||!Bo.test(e))&&S(n,`${t} must be a safe identifier`),e}function Nn(e,n,t){let i=e??t;return (typeof i!="string"||i.trim().length===0||i.length>Gc)&&S("TOOL_INVALID",`${n} must be a meaningful description`),i}function ii(e){return (typeof e!="string"||e.length===0||e.length>dn||!/<html(?:\s|>)/i.test(e)||!/<\/html\s*>/i.test(e))&&S("HTML_INVALID","MCP App HTML must be a non-empty HTML document"),e}function Dn(e,n=0){try{let t=ye(e,n);return t.type!==void 0&&t.type!=="object"&&S("TOOL_INVALID","MCP App inputSchema must describe an object"),t}catch(t){if(t instanceof be)throw t;S("TOOL_INVALID","MCP App inputSchema must be projection-safe JSON");}}function Qc(e){return (typeof e!="string"||e.trim().length===0||e.length>Wc)&&S("TOOL_INVALID","MCP App tools require a meaningful text fallback"),e}function ed(e){e===void 0&&S("TOOL_INVALID","MCP App tool visibility is required");let n=[...e];return (n.length===0||n.some(t=>t!=="model"&&t!=="app")||new Set(n).size!==n.length)&&S("TOOL_INVALID","MCP App tool visibility must contain model and/or app once"),n}function Go(e){return (typeof e!="string"||!Ho.test(e))&&S("RESOURCE_URI_INVALID","MCP App resource URI is not a registered ui:// URI"),e}function Wo(e){let n=Ve(e.appId,"APP_ID_INVALID","Local App id"),t=Nn(e.name,"Local App name",n),i=Nn(e.description,"Local App description",`${t} interactive view`),o=Zn(e.definition),r=ii(e.html),s=Xn(e.entryHash,"Local App entry hash"),a=e.entryBytes===void 0?Array.from(new TextEncoder().encode(r)):qn(e.entryBytes,"Local App entry bytes");(Yn(a)!==s||Xo(a)!==r)&&S("HTML_INVALID","Local App entry bytes do not match the HTML hash");let c=nd(e),d=[];Array.isArray(e.actions)||S("TOOL_INVALID","Local App actions must be an array");for(let N of e.actions){let C=Ve(N.actionId,"TOOL_ID_INVALID","Local App action id");(d.includes(C)||!Object.prototype.hasOwnProperty.call(o.actions,C))&&S("TOOL_INVALID",`Local App action is not declared by the UI definition: ${C}`),d.push(C);}let l=Ve(e.readToolName,"TOOL_ID_INVALID","Local App read tool name"),p=e.actionToolName===void 0?void 0:Ve(e.actionToolName,"TOOL_ID_INVALID","Local App action tool name");d.length===0&&p!==void 0&&S("TOOL_INVALID","A static local App cannot register an action tool"),d.length>0&&p===void 0&&S("TOOL_INVALID","A stateful local App requires an action tool name"),p!==void 0&&p===l&&S("TOOL_ID_CONFLICT",`Local App read and action tools share a name: ${l}`);let u=Zc(e.runtime);u.some(N=>N.name===l||N.name===p)&&S("TOOL_ID_CONFLICT","Local App read or action tool conflicts with a requested Host capability");let f={name:l,description:`${t} current state`,inputSchema:Yc,textFallback:`${t} current state is available through its open instance.`,visibility:Object.freeze(["model","app"]),kind:"read",resourceBinding:Fe},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:Fe,actionIds:Object.freeze([...d])};g.push(Object.freeze(N));}let _=[],P=new Set(g.map(N=>N.name));if(p!==void 0)for(let N of e.actions){let C=`${p}__${N.actionId}`;if(C.length>128||!Bo.test(C)){_.push(Object.freeze({toolName:C,actionId:N.actionId,reason:"name_too_long"}));continue}if(P.has(C)){_.push(Object.freeze({toolName:C,actionId:N.actionId,reason:"name_collision"}));continue}let F=vo({actionId:N.actionId,confirmation:o.actions[N.actionId]?.confirmation,content:o.actions[N.actionId]?.content,backend:N.backend},e.modelActions),D=Object.freeze(F==="denied"?["app"]:["model","app"]),b={name:C,description:`${C} action`,inputSchema:Dn(N.inputSchema),textFallback:`${C} action requests are handled by the open App instance.`,visibility:D,kind:"action",resourceBinding:Fe,actionId:N.actionId,actionIds:Object.freeze([N.actionId]),_meta:Object.freeze({ui:Object.freeze({visibility:D})})};g.push(Object.freeze(b)),P.add(C);}let U=zo(s,r,a,c===void 0?void 0:{hash:c.hash,bytes:[...c.bytes]}),k={appId:n,name:t,description:i,...e.icon===void 0?{}:{icon:Yo(e.icon)},...e.tone===void 0?{}:{tone:qo(e.tone)},builtinOnly:false,definition:o,...e.runtime===void 0?{}:{runtime:Object.freeze({...e.runtime})},resourceBinding:Fe,resource:U,tools:Object.freeze(g),toolDiagnostics:Object.freeze(_)};return ee(k)}function Jo(e={}){return new ti(e)}function oi(e){if(e.length===0)return Dn({type:"object",properties:{},additionalProperties:false});let n=e.map(i=>i.actionId),t=new Map;for(let i of e)t.set(i.actionId,Dn(i.inputSchema));return Dn(td(n,t),$o)}function nd(e){let n=e.definition.dataPaths??[];if(e.initialStateBytes===void 0){e.initialStateHash!==void 0&&S("STATE_INVALID","Initial state hash has no bytes"),e.initialState!==void 0&&ye(e.initialState,0,n);return}e.initialStateHash===void 0&&S("STATE_INVALID","Initial state bytes require a hash");let t=Xn(e.initialStateHash,"Initial state hash"),i=qn(e.initialStateBytes,"Initial state bytes");Yn(i)!==t&&S("STATE_INVALID","Initial state bytes do not match the hash");let o;try{let r=new TextDecoder("utf-8",{fatal:!0}).decode(Uint8Array.from(i));o=ye(JSON.parse(r),0,n);}catch{S("STATE_INVALID","Initial state bytes are not projection-safe JSON");}return e.initialState!==void 0&&te(o)!==te(ye(e.initialState,0,n))&&S("STATE_INVALID","Initial state bytes do not match the state value"),{hash:t,bytes:Object.freeze([...i])}}function td(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 id(e){let n=Sn(e),t=Ve(n.appId,"APP_ID_INVALID","MCP App id"),i=ii(n.html);Go(n.uiUri);let o=n.definition===void 0?void 0:Zn(n.definition),r=e.provenance;r!==void 0&&(!cn(r)||r.appId!==t||r.definitionId!==o?.id||r.version!==o?.version||r.definitionHash!==o?.hash)&&S("TOOL_INVALID","Product App built-in registration provenance is not verified");let s=Object.freeze(n.tools.map(d=>ee(Sn(d)))),a=ee({...n,appId:t,html:i,...o===void 0?{}:{definition:o},...r===void 0?{}:{provenance:r},tools:s}),c=ee({uri:a.uiUri,mimeType:wo,text:i,...a.csp===void 0?{}:{_meta:{ui:{csp:a.csp}}}});return ee({appId:t,name:a.name,description:a.description,...a.icon===void 0?{}:{icon:a.icon},...a.tone===void 0?{}:{tone:a.tone},builtinOnly:a.builtinOnly,uiUri:a.uiUri,...o===void 0?{}:{definition:o},resourceBinding:Object.freeze({kind:"mcp",uri:a.uiUri}),resource:c,tools:s,descriptor:a})}function od(e){(e.resourceBinding.kind!=="instance"||e.builtinOnly!==false)&&S("STATE_INVALID","Local App registration binding is invalid"),Object.prototype.hasOwnProperty.call(e,"uiUri")&&S("STATE_INVALID","Local App registration cannot contain uiUri");let n=Ve(e.appId,"APP_ID_INVALID","Local App id"),t=Zn(e.definition),i=e.provenance;i!==void 0&&(!cn(i)||i.appId!==n||i.definitionId!==t.id||i.version!==t.version||i.definitionHash!==t.hash)&&S("TOOL_INVALID","Product App local registration provenance is not verified");let o=rd(e.resource),r=e.tools.map(a=>{Ve(a.name,"TOOL_ID_INVALID","Local App tool name"),Nn(a.description,"Local App tool description","Local App tool"),Qc(a.textFallback);let c=Dn(a.inputSchema,a.kind==="action"&&!("actionId"in a)?$o:0);if((a.resourceBinding.kind!=="instance"||Object.prototype.hasOwnProperty.call(a,"resourceUri"))&&S("TOOL_INVALID","Local App tools cannot carry an MCP resource URI"),a.kind==="host")return (!Xc.has(a.name)||a.visibility.length!==1||a.visibility[0]!=="app"||Object.prototype.hasOwnProperty.call(a,"actionId"))&&S("TOOL_INVALID","Local App Host tools must use an allow-listed name and app-only visibility"),ee({...a,inputSchema:c,visibility:Object.freeze(["app"])});if(a.kind==="action"){if("actionId"in a){let l=Ve(a.actionId,"TOOL_ID_INVALID","Local App action id");Object.prototype.hasOwnProperty.call(t.actions,l)||S("TOOL_INVALID","Local App action tool references an undeclared action");let p=ed(a._meta.ui.visibility);return JSON.stringify(p)!==JSON.stringify(a.visibility)&&S("TOOL_INVALID","Local App action metadata visibility must match the tool visibility"),ee({...a,actionId:l,actionIds:Object.freeze([l]),inputSchema:c,visibility:p,_meta:{ui:{visibility:p}}})}let d=[...a.actionIds];return (d.length===0||d.some(l=>!Object.prototype.hasOwnProperty.call(t.actions,l)))&&S("TOOL_INVALID","Local App action tool references an undeclared action"),ee({...a,inputSchema:c,actionIds:Object.freeze(d)})}return ee({...a,inputSchema:c})}),s=ee({appId:n,name:Nn(e.name,"Local App name",e.appId),description:Nn(e.description,"Local App description",e.name),...e.icon===void 0?{}:{icon:Yo(e.icon)},...e.tone===void 0?{}:{tone:qo(e.tone)},builtinOnly:false,definition:t,...e.runtime===void 0?{}:{runtime:Object.freeze({...e.runtime})},...i===void 0?{}:{provenance:i},resourceBinding:Fe,resource:o,tools:Object.freeze(r),toolDiagnostics:Object.freeze([...e.toolDiagnostics??[]])});return Fo.has(e)?e:(Fo.add(s),s)}function rd(e){let n=ii(e.html),t=Xn(e.entryHash,"Local App entry hash");if(qc(e))return e;let i=qn(e.bytes,"Local App entry bytes");(Yn(i)!==t||Xo(i)!==n)&&S("HTML_INVALID","Local App entry bytes do not match the HTML hash");let o=e.initialState===void 0?void 0:{hash:Xn(e.initialState.hash,"Initial state hash"),bytes:qn(e.initialState.bytes,"Initial state bytes")};return o&&Yn(o.bytes)!==o.hash&&S("STATE_INVALID","Initial state bytes do not match the hash"),zo(t,n,i,o)}function sd(e){return ee({appId:e.appId,name:e.name,description:e.description,...e.icon===void 0?{}:{icon:e.icon},...e.tone===void 0?{}:{tone:e.tone},builtinOnly:false,definition:Ko(e.definition),...e.provenance===void 0?{}:{provenance:e.provenance},entryHash:e.resource.entryHash,resourceBinding:Fe,tools:e.tools})}function ad(e){return ee({appId:e.appId,name:e.name,description:e.description,...e.icon===void 0?{}:{icon:e.icon},...e.tone===void 0?{}:{tone:e.tone},builtinOnly:e.builtinOnly,uiUri:e.uiUri,...e.definition===void 0?{}:{definition:Ko(e.definition)},resourceBinding:Object.freeze({kind:"mcp",uri:e.uiUri}),tools:e.tools})}function Zn(e){try{if(Object.isFrozen(e))return Ae(e),ee(e);let n=Sn(e);return Ae(n),ee(n)}catch(n){if(n instanceof be)throw n;S("STATE_INVALID","UI definition is not a valid immutable definition");}}function Ko(e){return ee({id:e.id,version:e.version,hash:e.hash})}function cd(e){return e!==null&&typeof e=="object"&&typeof e.id=="string"&&Number.isSafeInteger(e.version)&&typeof e.hash=="string"}function Vo(e,n,t){return `${e}\0${n}\0${t}`}function Xn(e,n){return (typeof e!="string"||!$c.test(e))&&S("SERIALIZATION_INVALID",`${n} is invalid`),e}function Yn(e){return createHash("sha256").update(Uint8Array.from(e)).digest("hex")}function qn(e,n){return (!Array.isArray(e)||e.some(t=>!Number.isInteger(t)||t<0||t>255))&&S("SERIALIZATION_INVALID",`${n} is invalid`),[...e]}function Xo(e){try{return new TextDecoder("utf-8",{fatal:!0}).decode(Uint8Array.from(e))}catch{S("SERIALIZATION_INVALID","UTF-8 bytes are invalid");}}function Yo(e){return (typeof e!="string"||!Jc.test(e))&&S("TOOL_INVALID","MCP App icon is invalid"),e}function qo(e){return (typeof e!="string"||!Kc.has(e))&&S("TOOL_INVALID","MCP App tone is invalid"),e}function Sn(e,n=new Map){if(e===null||typeof e!="object")return e;let t=e;if(n.has(t)&&S("SERIALIZATION_INVALID","MCP App value contains a cycle"),Array.isArray(e)){let r=[];n.set(t,r);for(let s of e)r.push(Sn(s,n));return n.delete(t),r}let i;try{i=Object.getPrototypeOf(e);}catch{S("SERIALIZATION_INVALID","MCP App value cannot be cloned");}i!==Object.prototype&&i!==null&&S("SERIALIZATION_INVALID","MCP App value must be plain JSON");let o={};n.set(t,o);for(let[r,s]of Object.entries(e))Object.defineProperty(o,r,{configurable:true,enumerable:true,value:Sn(s,n),writable:true});return n.delete(t),o}function ee(e,n=new Set){if(e===null||typeof e!="object"||n.has(e)||bn.has(e))return e;n.add(e);for(let t of Object.values(e))ee(t,n);return Object.freeze(e),e}var Bo,Ho,$c,dn,Gc,Wc,Jc,Kc,Xc,Fe,Yc,bn,Fo,$o,ti,Qn=B(()=>{m();Do();He();Le();Kn();Jn();ni();xo();jo();Bo=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,Ho=/^ui:\/\/crewx\/([A-Za-z][A-Za-z0-9._-]{0,127})\/([0-9a-f]{12})$/,$c=/^[0-9a-f]{64}$/,dn=8*1024*1024,Gc=8*1024,Wc=16*1024,Jc=/^[a-z][a-z0-9-]{0,63}$/,Kc=new Set(["blue","violet","emerald","amber","rose","sky","slate","indigo"]),Xc=new Set(Co),new Set(Uo),Fe=Object.freeze({kind:"instance"}),Yc=Object.freeze({type:"object",properties:Object.freeze({}),additionalProperties:false}),bn=new WeakSet,Fo=new WeakSet;$o=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=id(p);s.has(u.appId)&&S("APP_ID_CONFLICT",`MCP App id is already registered: ${u.appId}`),s.add(u.appId);let f=u.tools;for(let g of f)a.has(g.name)&&S("TOOL_ID_CONFLICT",`MCP App tool name is already registered: ${g.name}`),a.add(g.name),this.mcpToolByName.set(g.name,g),r.push(g);this.mcpResources.set(u.resource.uri,u.resource),i.push(u),o.push(u.descriptor);}let c=(n.localApps??n.locals??[]).map(od),d=new Set(c.flatMap(p=>p.tools.filter(u=>!(u.kind==="action"&&"actionId"in u)).map(u=>u.name))),l=[];for(let p of c){let u=p;s.has(u.appId)&&S("APP_ID_CONFLICT",`MCP App id is already registered: ${u.appId}`),s.add(u.appId);let f=[],g=[...u.toolDiagnostics??[]];for(let _ of u.tools){if(a.has(_.name)){if(_.kind==="host"&&this.localToolByName.get(_.name)?.kind==="host"){f.push(_);continue}if(_.kind==="action"&&"actionId"in _){g.push(Object.freeze({toolName:_.name,actionId:_.actionId,reason:"name_collision"}));continue}S("TOOL_ID_CONFLICT",`MCP App tool name is already registered: ${_.name}`);}if(_.kind==="action"&&"actionId"in _&&d.has(_.name)){g.push(Object.freeze({toolName:_.name,actionId:_.actionId,reason:"name_collision"}));continue}a.add(_.name),this.localToolByName.set(_.name,_),f.push(_);}(f.length!==u.tools.length||g.length!==(u.toolDiagnostics?.length??0))&&(u=ee({...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,ad(p)),p.definition&&this.addDefinition(p.definition);for(let p of l)this.registrationById.set(p.appId,p),this.launcherById.set(p.appId,sd(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"||!Ho.test(n)?null:this.mcpResources.get(n)??null}requireMcpAppResource(n){Go(n);let t=this.mcpResources.get(n);return t||S("RESOURCE_NOT_FOUND",`MCP App resource is not registered: ${n}`),t}listLocalMcpApps(){return this.localApps}getLocalMcpApp(n){return this.localById.get(n)??null}listLocalMcpAppTools(){return Object.freeze([...this.localToolByName.values()])}resolveLocalMcpAppTool(n){return this.localToolByName.get(n)??null}resolveLocalMcpAppResource(n,t){let i=this.localById.get(n);return !i||t!==void 0&&i.definition.hash!==t?null:i.resource}listRegistrations(){return Object.freeze([...this.builtinApps,...this.localApps])}getRegistration(n){return this.registrationById.get(n)??null}listLaunchers(){return Object.freeze([...this.launcherById.values()].filter(n=>{let t=this.registrationById.get(n.appId),i=t?"descriptor"in t?t.descriptor.provenance:t.provenance:void 0,o=cn(i)&&i.launcher===false;return t?.definition?.usage!=="card"&&!o}))}getLauncher(n){return this.launcherById.get(n)??null}resolveDefinition(n){if(!cd(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(Vo(n,t,i))??null}addDefinition(n){let t=Zn(n),i=Ot(t),o=this.definitionByKey.get(i);o&&o.hash!==t.hash&&S("STATE_INVALID",`UI definition generation conflicts: ${i}`),o||this.definitionByKey.set(i,t);}addHandler(n){(!n||typeof n.definitionId!="string"||typeof n.actionId!="string"||!Number.isSafeInteger(n.version)||n.version<1||typeof n.handle!="function")&&S("STATE_INVALID","UI action handler registration is invalid");let t=Vo(n.definitionId,n.version,n.actionId);this.handlerByKey.has(t)&&S("TOOL_INVALID",`Duplicate UI action handler registration: ${t}`),this.handlerByKey.set(t,Object.freeze({...n}));}};});function dd(e){let n=Wo({appId:e.appId,name:e.name,description:e.description,...e.icon===void 0?{}:{icon:e.icon},...e.tone===void 0?{}:{tone:e.tone},...e.normalized.manifest.runtime===void 0?{}:{runtime:e.normalized.manifest.runtime},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 Zo(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=dd(e);Jo({localApps:[t],definitions:[e.definition]});}var Qo=B(()=>{m();Qn();});function pd(e){if(e===null||typeof e!="object"||!(er in e))throw new TypeError("scanCache must be created by createWorkspaceAppScanCache");return e[er]}function nr(e,n){let t=pd(e),i=t.rootIdentity;return i!==void 0&&(i.dev!==n.dev||i.ino!==n.ino||i.realPath!==n.realPath)&&(t.candidates.clear(),t.assetCatalogs.clear(),t.preparedCandidates.clear(),t.lastCandidateScanUnchanged=void 0,t.lastCandidateKeys=void 0,t.scanStartedAtNs=void 0,t.lastAssetCatalogsUnchanged=void 0,t.lastSnapshot=void 0,t.lastSnapshotBuildInputs=void 0,t.lastSnapshotCandidates=void 0,t.lastSnapshotCatalogFingerprint=void 0),t.rootIdentity=n,t}var er,tr=B(()=>{m();er=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 M("NOT_FOUND"):n==="ELOOP"?new M("PATH_ESCAPED"):n==="EFBIG"||n==="EOVERFLOW"?new M("LIMIT_EXCEEDED"):n==="EACCES"||n==="EPERM"||n==="ENOTDIR"?new M("READ_DENIED"):new M("READ_DENIED")}function yd(e){if(typeof e!="string"||e.length===0||!isAbsolute(e))throw new M("READ_DENIED")}function ri(e){if(typeof e!="string"||isAbsolute(e)||/[\\\u0000]/.test(e))throw new M("PATH_ESCAPED");if(e==="")return [];let n=e.split("/");if(n.some(t=>t.length===0||t==="."||t===".."))throw new M("PATH_ESCAPED");return n}function it(e,n){let t=relative(e,n);return t===""||t!==".."&&!t.startsWith(`..${sep}`)&&!isAbsolute(t)}function ln(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 et(e){yd(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 M("READ_DENIED");return {realRoot:n,identity:ln(t)}}async function rr(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 M("READ_DENIED")}catch(r){throw r instanceof M?r:ue(r)}if(!it(n,o))throw new M("PATH_ESCAPED");return o}async function nt(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(!it(n,r)||t!==void 0&&!it(t,r))throw new M("PATH_ESCAPED");if(!o.isFile()||!s.isFile())throw new M("READ_DENIED");if(!di(i,o)||!di(i,s)||i.dev!==s.dev)throw new M("PATH_ESCAPED")}async function pn(e,n){let t,i;try{t=await realpath(e),i=await stat(t,{bigint:!0});}catch{throw new M("PATH_ESCAPED")}if(t!==n.realRoot||!pi(n.identity,ln(i)))throw new M("PATH_ESCAPED")}function Ad(e){return e.isSymbolicLink()?{name:e.name,kind:"symlink"}:e.isDirectory()?{name:e.name,kind:"directory"}:e.isFile()?{name:e.name,kind:"file"}:{name:e.name,kind:"other"}}var M,ci,fd,or,ot,sr,ui=B(()=>{m();M=class extends Error{constructor(t){super(t);this.code=t;}code;name="AppDiscoveryFsError"},ci=constants.O_NOFOLLOW,fd=constants.O_NONBLOCK,or=constants.O_RDONLY|(ci??0)|(fd??0);ot=class{async getRootIdentity(n){let t=await et(n);return await pn(n,t),{dev:t.identity.dev,ino:t.identity.ino,realPath:t.realRoot}}async listDirectory(n,t){let i=ri(t),o=await et(n),r=resolve(n,...i),s,a;try{s=await realpath(r),a=await stat(s,{bigint:!0});}catch(c){let d=ue(c);if(d.code==="NOT_FOUND")return [];throw d}if(!it(o.realRoot,s)||!a.isDirectory())throw new M("PATH_ESCAPED");try{let c=await readdir(s,{withFileTypes:!0,encoding:"utf8"});return await pn(n,o),c.map(Ad)}catch(c){let d=ue(c);if(d.code==="NOT_FOUND")return [];throw d}}async readdir(n,t){return this.listDirectory(n,t)}async readDirectory(n,t){return this.listDirectory(n,t)}async readVerifiedFile(n,t,i){if(!Number.isSafeInteger(i)||i<0)throw new M("READ_DENIED");if(ci===void 0)throw new M("UNSUPPORTED");let o=ri(t),r=await et(n),s=resolve(n,...o),a=relative(n,s);if(a===".."||a.startsWith(`..${sep}`)||isAbsolute(a))throw new M("PATH_ESCAPED");let c;try{c=await open(s,or);}catch(d){throw ue(d)}try{let d;try{let g=await c.stat({bigint:!0});d=ln(g);}catch(g){throw ue(g)}if(d.size>BigInt(i))throw new M("LIMIT_EXCEEDED");if(d.size>BigInt(Number.MAX_SAFE_INTEGER))throw new M("LIMIT_EXCEEDED");await pn(n,r);let l=await rr(n,r.realRoot,o);await nt(s,r.realRoot,l,d);let p=new Uint8Array(new ArrayBuffer(Number(d.size))),u=0;for(;u<p.byteLength;){let g;try{g=(await c.read(p,u,p.byteLength-u,u)).bytesRead;}catch(_){throw ue(_)}if(g<=0)throw new M("IDENTITY_CHANGED");u+=g;}let f;try{let g=await c.stat({bigint:!0});f=ln(g);}catch(g){throw ue(g)}if(!pi(d,f))throw new M("IDENTITY_CHANGED");return await nt(s,r.realRoot,l,f),await pn(n,r),new Uint8Array(p)}finally{await c.close().catch(()=>{});}}async fingerprintVerifiedFile(n,t,i){if(!Number.isSafeInteger(i)||i<0)throw new M("READ_DENIED");if(ci===void 0)throw new M("UNSUPPORTED");let o=ri(t),r=await et(n),s=resolve(n,...o),a=relative(n,s);if(a===".."||a.startsWith(`..${sep}`)||isAbsolute(a))throw new M("PATH_ESCAPED");let c;try{c=await open(s,or);}catch(d){throw ue(d)}try{let d;try{let u=await c.stat({bigint:!0});d=ln(u);}catch(u){throw ue(u)}if(d.size>BigInt(i)||d.size>BigInt(Number.MAX_SAFE_INTEGER))throw new M("LIMIT_EXCEEDED");await pn(n,r);let l=await rr(n,r.realRoot,o);await nt(s,r.realRoot,l,d);let p;try{let u=await c.stat({bigint:!0});p=ln(u);}catch(u){throw ue(u)}if(!pi(d,p))throw new M("IDENTITY_CHANGED");return await nt(s,r.realRoot,l,p),await pn(n,r),{...p,candidateRealPath:l??r.realRoot}}catch(d){throw d instanceof M?d:ue(d)}finally{await c.close().catch(()=>{});}}async readFileVerified(n,t,i){return this.readVerifiedFile(n,t,i)}},sr=new ot;});function On(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 cr(e){return typeof e=="string"&&Te.test(e)?e:void 0}function Td(e){return e.length>0&&e!=="."&&e!==".."&&!/[\\/\u0000]/.test(e)}function Je(e,n){let t=new TextEncoder().encode(e),i=new TextEncoder().encode(n),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 Pd(e){if(typeof e=="string")return {name:e,kind:"directory"};if(e===null||typeof e!="object")return null;let n=e;if(typeof n.name!="string")return null;if(n.kind==="file"||n.kind==="directory"||n.kind==="symlink"||n.kind==="other")return {name:n.name,kind:n.kind};if(n.type==="file"||n.type==="directory"||n.type==="symlink"||n.type==="other")return {name:n.name,kind:n.type};let t=n.isDirectory;if(typeof t=="function"&&t.call(e))return {name:n.name,kind:"directory"};let i=n.isSymbolicLink;if(typeof i=="function"&&i.call(e))return {name:n.name,kind:"symlink"};let o=n.isFile;return typeof o=="function"&&o.call(e)?{name:n.name,kind:"file"}:{name:n.name,kind:"other"}}function Nd(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 Dd(e){return _d.decode(e)}function bd(e){return JSON.parse(Dd(e))}function dr(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 Sd(e){if(e instanceof M)return dr(e.code);if(e!==null&&typeof e=="object"&&"code"in e){let n=e.code;if(typeof n=="string")return dr(n)}}function Oe(e,n){let t=n();return Number.isFinite(t)&&Number.isFinite(e)&&t-e<=5e3}function Md(e){if(typeof e.readVerifiedFile=="function")return e.readVerifiedFile;if(typeof e.readFileVerified=="function")return e.readFileVerified}function Ld(e){if(typeof e.listDirectory=="function")return e.listDirectory;if(typeof e.readDirectory=="function")return e.readDirectory;if(typeof e.readdir=="function")return e.readdir}async function pr(e,n,t,i){let o=Md(e);if(!o)throw new M("READ_DENIED");return Nd(await o.call(e,n,t,i))}async function Ai(e,n,t){let i=Ld(e);if(!i)throw new M("READ_DENIED");let o=await i.call(e,n,t);if(!Array.isArray(o))throw new M("READ_DENIED");return o.map(Pd).filter(r=>r!==null)}function Rd(e,n,t,i){return Object.freeze({code:e,...{},source:n,relativePath:t})}function Od(e){if(!On(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(Je))};return Object.freeze({appIds:t(e.appIds,"appIds"),definitionIds:t(e.definitionIds,"definitionIds")})}catch(n){throw n instanceof TypeError?n:new TypeError("productBundle.reservedIds must be a valid reservation object")}}function wd(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 st(e){return Object.freeze({appIds:Object.freeze([...new Set(e.map(n=>n.appId))].sort(Je)),definitionIds:Object.freeze([...new Set(e.map(n=>n.definition.id))].sort(Je))})}function rt(e,n){let t=Object.keys(e).sort(Je),i=[...n].sort(Je);return t.length===i.length&&t.every((o,r)=>o===i[r])}function lr(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 Cd(e){let n;try{n=bd(e);}catch{return}if(!On(n)||!rt(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(!On(s))return;let a=["packageDir","appId","definition","files"],c=Object.hasOwn(s,"lineage"),d=Object.hasOwn(s,"launcher"),l=[...c?["lineage"]:[],...d?["launcher"]:[]];if(!rt(s,[...a,...l])||d&&s.launcher!==false)return;let p=lr(s.packageDir),u=cr(s.appId);if(!p||p.length!==2||p[0]!=="apps"||!Td(p[1])||!u||t.has(s.packageDir)||!On(s.definition)||!rt(s.definition,["id","version","hash"]))return;let f=cr(s.definition.id),g=s.definition.version,_=s.definition.hash;if(!f||!Number.isSafeInteger(g)||g<1||typeof _!="string"||!yi.test(_)||!Array.isArray(s.files)||s.files.length<2||s.files.length>gi)return;let P=new Set,U=[];for(let k of s.files){if(!On(k)||!rt(k,["path","sha256"]))return;let N=lr(k.path);if(!N||typeof k.sha256!="string"||!yi.test(k.sha256))return;let C=N.join("/"),F=`${s.packageDir}/${C}`;if(P.has(C)||i.has(F))return;P.add(C),i.add(F),U.push(Object.freeze({path:C,sha256:k.sha256}));}if(!Z.some(k=>P.has(k))||!P.has("ui/index.html")||(o+=U.length,o>gd))return;t.add(s.packageDir),r.push(Object.freeze({packageDir:s.packageDir,...d?{launcher:false}:{},appId:u,definition:Object.freeze({id:f,version:g,hash:_}),lineage:Array.isArray(s.lineage)?s.lineage:[],files:Object.freeze(U.sort((k,N)=>Je(k.path,N.path)))}));}return Object.freeze({version:1,packages:Object.freeze(r)})}function We(e){let n=Sd(e);return n==="PATH_ESCAPED"||n==="IDENTITY_CHANGED"||n==="TOCTOU"?"PATH_ESCAPED":n==="LIMIT_EXCEEDED"?"LIMIT_EXCEEDED":"BUNDLE_INTEGRITY"}async function Ud(e,n,t,i,o){let r=[],s=async(a,c)=>{if(!Oe(i,o))throw new M("LIMIT_EXCEEDED");if(c>2)throw new M("LIMIT_EXCEEDED");let d=await Ai(e,n,a);for(let l of d){if(typeof l.name!="string"||l.name.length===0||l.name==="."||l.name===".."||/[\\/\u0000]/.test(l.name))throw new M("PATH_ESCAPED");let p=`${a}/${l.name}`;if(l.kind==="file"){if(r.push(p.slice(t.length+1)),r.length>gi)throw new M("LIMIT_EXCEEDED")}else if(l.kind==="directory")await s(p,c+1);else throw l.kind==="symlink"?new M("PATH_ESCAPED"):new M("READ_DENIED")}};return await s(t,0),r.sort(Je)}function kd(e){return Z.includes(e)?262144:e==="ui/index.html"?dn:e==="ui/state.json"?2097152:e.startsWith("ui/assets/")?hd:md}async function ur(e,n,t,i){if(e===void 0)return {packages:[],diagnostics:[],incomplete:false,reservedIds:Ed};let o=Od(e.reservedIds),r=[],s=(y,I,h)=>Rd(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 c;try{c=await pr(n,e.root,"bundle-index.json",Id);}catch(y){return r.push(s(We(y),"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 l=Cd(c);if(l===void 0)return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a();if(!wd(st(l.packages),o))return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a([],false,d);if(!Oe(t,i))return r.push(s("LIMIT_EXCEEDED","bundle-index.json")),a(l.packages.map(y=>({indexEntry:y,failureCode:"LIMIT_EXCEEDED"})),true,d);let p;try{p=await Ai(n,e.root,"");}catch(y){return r.push(s(We(y),"bundle-index.json")),a(l.packages.map(I=>({indexEntry:I,failureCode:We(y)})),false,d)}if(!Oe(t,i))return r.push(s("LIMIT_EXCEEDED","bundle-index.json")),a(l.packages.map(y=>({indexEntry:y,failureCode:"LIMIT_EXCEEDED"})),true,d);let u=p.find(y=>y.name==="bundle-index.json"&&y.kind==="file"),f=p.find(y=>y.name==="apps"&&y.kind==="directory"),g=y=>l.packages.map(I=>({indexEntry:I,failureCode:y}));if(!u)return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a(g("BUNDLE_INTEGRITY"),false,d);let _=p.filter(y=>y.name!=="bundle-index.json"&&y.name!=="apps");if(_.length>0){let y=_.some(I=>I.kind==="symlink")?"PATH_ESCAPED":"BUNDLE_INTEGRITY";return r.push(s(y,"bundle-index.json")),a(g("BUNDLE_INTEGRITY"),false,d)}if(p.some(y=>y.name==="apps"&&y.kind!=="directory"))return r.push(s("PATH_ESCAPED","apps")),a(g("PATH_ESCAPED"),false,d);let P=[];if(f)try{P=await Ai(n,e.root,"apps");}catch(y){return r.push(s(We(y),"apps")),a(g(We(y)),false,d)}if(!Oe(t,i)||P.length>Ii)return r.push(s("LIMIT_EXCEEDED","apps")),a(g("LIMIT_EXCEEDED"),true,d);let U=new Map(l.packages.map(y=>[y.packageDir.slice(5),y])),k=P.filter(y=>!U.has(y.name));for(let y of k)r.push(s(y.kind==="symlink"?"PATH_ESCAPED":"BUNDLE_INTEGRITY",`apps/${y.name}`));if(k.length>0){let y=k.some(I=>I.kind==="symlink")?"PATH_ESCAPED":"BUNDLE_INTEGRITY";return a(g(y),false,d)}let N=new Set,C=new Map,F=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)}`,E=F.get(h)??[];E.push(y),F.set(h,E);}for(let y of [...C.values(),...F.values()])if(y.length>1)for(let I of y)N.add(I);let D=[],b=c.byteLength,R=false;for(let y of l.packages){if(!Oe(t,i)){R=true,D.push({indexEntry:y,failureCode:"LIMIT_EXCEEDED"});continue}let I;try{let L=y.lineage[y.lineage.length-1];if(!L)throw new Se("LINEAGE_INVALID","Definition lineage is missing");if(L.definition.id!==y.definition.id||L.version!==y.definition.version||L.hash!==y.definition.hash)throw new Se("LINEAGE_STALE","Last lineage generation does not match bundle identity");I=ei(y.lineage,{...L.definition,hash:L.hash}).entries;}catch(L){let J=L instanceof Se?L.code:"LINEAGE_INVALID";r.push(s(J,y.packageDir)),D.push({indexEntry:y,failureCode:J});continue}let h=P.find(L=>L.name===y.packageDir.slice(5));if(!f||!h){D.push({indexEntry:y,failureCode:"BUNDLE_INTEGRITY"});continue}if(h.kind!=="directory"){D.push({indexEntry:y,failureCode:h.kind==="symlink"?"PATH_ESCAPED":"BUNDLE_INTEGRITY"});continue}let E;try{let L=await Ud(n,e.root,y.packageDir,t,i);if(!Oe(t,i)){R=!0,D.push({indexEntry:y,failureCode:"LIMIT_EXCEEDED"});continue}let J=y.files.map(K=>K.path);if(L.length!==J.length||L.some((K,Me)=>K!==J[Me])){D.push({indexEntry:y,failureCode:"BUNDLE_INTEGRITY"});continue}E=new Map;let pe;for(let K of y.files){if(!Oe(t,i)){pe="LIMIT_EXCEEDED",R=!0;break}if(b>=fi){pe="LIMIT_EXCEEDED";break}let Me;try{Me=await pr(n,e.root,`${y.packageDir}/${K.path}`,kd(K.path));}catch(ms){pe=We(ms);break}if(!Oe(t,i)){pe="LIMIT_EXCEEDED",R=!0;break}if(b+Me.byteLength>fi){b=fi,pe="LIMIT_EXCEEDED";break}if(b+=Me.byteLength,createHash("sha256").update(Me).digest("hex")!==K.sha256){pe="BUNDLE_INTEGRITY";break}E.set(K.path,Me);}if(pe!==void 0){D.push({indexEntry:y,failureCode:pe});continue}}catch(L){Oe(t,i)||(R=true),D.push({indexEntry:y,failureCode:We(L)});continue}D.push({indexEntry:y,lineage:I,files:E,...N.has(y)?{failureCode:"DUPLICATE_ID"}:{}});}return a(D,R,d)}var Id,Ii,gi,gd,md,hd,fi,yi,_d,Ed,mi=B(()=>{m();ni();Be();Gn();Qn();ui();Id=256*1024,Ii=64,gi=128,gd=Ii*gi,md=2*1024*1024,hd=8*1024*1024,fi=32*1024*1024,yi=/^[0-9a-f]{64}$/,_d=new TextDecoder("utf-8",{fatal:true}),Ed=Object.freeze({appIds:Object.freeze([]),definitionIds:Object.freeze([])});});function vd(e){if(typeof e!="string"||!Te.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 yr(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 Fd(e,n){return n.length===0||n==="."||n===".."||/[\\/\u0000]/.test(n)?e==="skills"?"skills":"apps":`${e==="skills"?"skills":"apps"}/${n}`}function Vd(e){return e.length>0&&e!=="."&&e!==".."&&!/[\\/\u0000]/.test(e)}function wn(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 Dr(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 Bd(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 br(e){return jd.decode(e)}function Hd(e){return JSON.parse(br(e))}function zd(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 ct(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 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 ae(e){if(e instanceof M)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 Xe(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 Ir(e){return {reason:e.reason,...e.code==="MANIFEST_DUAL_MISMATCH"?{files:e.files}:{}}}function gr(e){return e==="MANIFEST_DUAL_MISMATCH"?e:Sr(e)}function $d(e){return Sr(e.code)}function Sr(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 Mr("UiPluginValidationError",e)}}function Mr(e,n){throw new Error(`Unmapped ${e} code: ${String(n)}`)}function Lr(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 Mr("McpAppContractError",e)}}function we(e,n){let t=n();return Number.isFinite(t)&&Number.isFinite(e)&&t-e<=5e3}function Gd(e){return {pluginId:e.appId,definitionKey:`${e.definition.id}\0${String(e.definition.version)}`}}function Wd(e,n){let t=n.get("package.json");if(t!==void 0)try{let o=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(t));if(yr(o)){let r=o.bin,s=typeof r=="string"?r:yr(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=Jd(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 Jd(e){if(e.startsWith("/")||e.includes("\\")||e.includes("\0"))return;let n=e.split("/").filter(t=>t!==".");if(!(n.length===0||n.some(t=>t.length===0||t==="..")))return n.join("/")}function Kd(){return globalThis.performance?.now()??Date.now()}function Ke(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let n of Object.values(e))Ke(n);return Object.freeze(e)}function mr(e){return Object.freeze(Array.from(e))}async function dt(e,n,t,i){if(n.pinnedFiles!==void 0){let a=n.pinnedFiles.get(t);if(a===void 0)throw new M("NOT_FOUND");if(a.byteLength>i)throw new M("LIMIT_EXCEEDED");return new Uint8Array(a)}let o=`${n.relativePath}/${t}`,r=n.scanContext,s=e.fingerprintVerifiedFile;if(r===void 0||!r.cacheable||typeof s!="function")return Tr(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 Tr(e,n.root,o,i),d=await s.call(e,r.workspaceRoot,o,i);return r.candidateRealPath=d.candidateRealPath,Or(a,d)&&d.size===BigInt(c.byteLength)&&!wr(d,r.scanStartedAtNs)?r.files.set(o,{relativePath:o,byteLimit:i,fingerprint:d}):r.cacheable=!1,c}catch(a){let c=Z.includes(t)&&ae(a)==="NOT_FOUND"&&r.directoryListings.some(l=>l.relativePath===n.relativePath&&!pt(l.key,t)),d=t===H&&ae(a)==="NOT_FOUND"&&Xd(r.directoryListings,n.relativePath);throw !c&&!d&&(r.cacheable=false),a}}function Xd(e,n){let t=e.find(o=>o.relativePath===n);if(t===void 0)return false;if(!pt(t.key,"dist"))return true;let i=e.find(o=>o.relativePath===`${n}/dist`);return i!==void 0&&!pt(i.key,"tools.json")}function Rr(e,n){return JSON.stringify([e.realPath,n.source,n.relativePath])}async function qd(e,n,t,i,o,r,s,a){let c=e.fingerprintVerifiedFile,d=Rr(t,i),l=o.candidates.get(d),p=i.relativePath,u;try{u=await Er(e,n,p);}catch(R){if(ae(R)!=="NOT_FOUND")throw R}let f=u===void 0?void 0:{relativePath:p,key:u};if(f!==void 0&&(i.source==="apps"||i.source==="skills")&&!Z.some(R=>pt(f.key,R)))return we(s,a)?l!==void 0&&l.candidate===void 0&&l.candidateRealPath===void 0&&l.files.length===0&&l.directoryListings.length===1&&l.directoryListings[0]?.relativePath===f.relativePath&&l.directoryListings[0]?.key===f.key&&(i.source==="apps"?l.diagnostic?.code==="MANIFEST_MISSING":l.diagnostic===void 0)&&typeof c=="function"?{memo:l}:typeof c!="function"?{}:{context:{state:o,cacheKey:d,workspaceRoot:n,scanStartedAtNs:r,directoryListings:Object.freeze([f]),priorFingerprints:new Map,files:new Map,cacheable:true}}:{timeLimitReached:true};let g=async R=>{if(R==="")return f;let y=`${i.relativePath}${R}`;try{let I=await Er(e,n,y);return I===void 0?void 0:{relativePath:y,key:I}}catch(I){if(ae(I)==="NOT_FOUND")return;throw I}},_=await Promise.all(hr.map(g)),P=await Promise.all(Yd.map(g));if(!we(s,a))return {timeLimitReached:true};let U=typeof c=="function"&&_.every(R=>R!==void 0),k=_.filter(R=>R!==void 0),N=[...k,...P.filter(R=>R!==void 0)],C=new Map,F=l!==void 0&&U,D;if(l!==void 0&&typeof c=="function"){let R=await Promise.all(l.files.map(async y=>{if(!we(s,a))return {kind:"time",file:y};try{let I=await c.call(e,n,y.relativePath,y.byteLimit);return {kind:"fingerprint",file:y,current:I}}catch(I){return ae(I)==="NOT_FOUND"?{kind:"missing",file:y}:{kind:"error",file:y,error:I}}}));if(R.some(y=>y.kind==="time"))return {timeLimitReached:true};for(let y of R){if(y.kind==="error")throw y.error;if(y.kind==="missing"){F=false;continue}if(y.kind!=="fingerprint")continue;let{file:I,current:h}=y;C.set(I.relativePath,h),D??=h.candidateRealPath,(h.candidateRealPath!==l.candidateRealPath||!Or(h,I.fingerprint)||wr(h,r))&&(F=false);}}let b=l!==void 0&&l.directoryListings.length===N.length&&l.directoryListings.every((R,y)=>R.relativePath===N[y]?.relativePath&&R.key===N[y]?.key);return l!==void 0&&U&&b&&F&&D===l.candidateRealPath?{memo:l}:!U||k.length!==hr.length?{}:{context:{state:o,cacheKey:d,workspaceRoot:n,scanStartedAtNs:r,directoryListings:Object.freeze(N),priorFingerprints:C,files:new Map,...D===void 0?{}:{candidateRealPath:D},cacheable:true}}}function pt(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 Er(e,n,t){let i=Cr(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(Dr);if(!r.some(s=>s===null))return JSON.stringify(r.slice().sort((s,a)=>wn(s.name,a.name)||wn(s.kind,a.kind)).map(s=>[s.name,s.kind]))}function Or(e,n){return e.dev===n.dev&&e.ino===n.ino&&e.size===n.size&&e.mtimeNs===n.mtimeNs&&e.ctimeNs===n.ctimeNs}function wr(e,n){let t=e.mtimeNs-n;return t>=-_r&&t<=_r}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 Zd(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 Qd(e,n){let t={...e.definition,sourceHash:n},i;try{i=le(t);}catch(r){throw r instanceof x&&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 ep(e){return e.actions.some(n=>n.backend.type==="core"&&n.backend.handler!=="state.set")}function np(e){if(typeof e.readVerifiedFile=="function")return e.readVerifiedFile;if(typeof e.readFileVerified=="function")return e.readFileVerified}function Cr(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 Tr(e,n,t,i){let o=np(e);if(!o)throw new M("READ_DENIED");return Bd(await o.call(e,n,t,i))}async function tp(e,n,t){let i=Cr(e);if(!i)throw new M("READ_DENIED");let o=await i.call(e,n,t);if(!Array.isArray(o))throw new M("READ_DENIED");return o.map(Dr).filter(r=>r!==null)}function ip(e){let n=[];for(let t of [e.reserved,e.builtin])t&&n.push(t);return e.builtins&&"listMcpApps"in e.builtins?n.push(Pr(e.builtins)):e.builtins&&n.push(e.builtins),e.builtinCatalog&&n.push(Pr(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 Pr(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=ct(n,e.source,e.relativePath,e.identity?.pluginId));}function op(e,n){let t=new Set,i=new Map;for(let r of e){let s=r.identity?.pluginId;if(s===void 0)continue;let a=i.get(s)??[];a.push(r),i.set(s,a);}for(let r of i.values()){if(r.length<2)continue;let s=r.filter(c=>c.provenance!==void 0);if(s.length>0){let c=r.find(d=>n.has(d));if(c){for(let d of s)t.add(d);for(let d of r)d!==c&&d.provenance===void 0&&_e(d,"RESERVED_ID");continue}for(let d of r)d.provenance===void 0&&_e(d,"RESERVED_ID");if(s.length>1)for(let d of s)_e(d,"DUPLICATE_ID");continue}let a=r.filter(c=>c.source==="apps");if(a.length>1){for(let c of a)_e(c,"DUPLICATE_ID");for(let c of r.filter(d=>d.source==="skills"))_e(c,"DUPLICATE_ID");}else for(let c of r.filter(d=>d.source==="skills"))_e(c,"DUPLICATE_ID");}let o=new Map;for(let r of e){if(r.diagnostic?.code==="RESERVED_ID"||t.has(r)||r.provenance===void 0&&!n.has(r)&&i.get(r.identity?.pluginId??"")?.some(c=>c.provenance!==void 0))continue;let s=r.identity?.definitionKey;if(s===void 0)continue;let a=o.get(s)??[];a.push(r),o.set(s,a);}for(let r of o.values())if(r.length>1)for(let s of r)_e(s,"DUPLICATE_ID");return t}function rp(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 ip(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 c=[...e.filter(l=>l.provenance!==void 0&&l.diagnostic===void 0).flatMap(l=>l.candidate?[l.candidate]:[]),...(n.productBundleReservationMetadata?.candidates??[]).filter(l=>n.productBundleReservationMetadata?.indexHash!==void 0&&l.provenance?.indexHash===n.productBundleReservationMetadata.indexHash)],d=new Set;for(let l of e){let p=l.candidate;if(!(!p||l.diagnostic||l.source!=="apps"||l.provenance!==void 0)&&e.filter(u=>u.source==="apps"&&u.identity?.pluginId===p.pluginId).length===1&&c.some(u=>u.pluginId===p.pluginId)&&!(a.has(p.definitionId)&&!c.some(u=>u.pluginId===p.pluginId&&u.definitionId===p.definitionId))&&!c.some(u=>u.pluginId!==p.pluginId&&u.definitionId===p.definitionId)&&!e.some(u=>u.identity?.pluginId!==p.pluginId&&u.identity?.definitionKey===`${p.definitionId}\0${p.version}`&&u.diagnostic?.code!=="RESERVED_ID"))try{Zo(p),d.add(l);}catch(u){_e(l,u instanceof be?Lr(u.code):"EXEC_DENIED");}}for(let l of e){let p=l.candidate;p&&l.provenance===void 0&&!d.has(l)&&(s.has(p.pluginId)||a.has(p.definitionId))&&_e(l,"RESERVED_ID");}return d}function sp(e){return [...e].sort((n,t)=>{let i=fr.indexOf(n.source)-fr.indexOf(t.source);return i!==0?i:wn(n.relativePath,t.relativePath)})}function V(e,n,t){e.diagnostic=ct(n,e.source,e.relativePath,e.identity?.pluginId,t);}async function Nr(e,n,t){let i=Ge(t,{mode:"local"});if(!i.ok&&i.parseFailure){V(n,gr(i.rejection.code),Ir(i.rejection));return}let o=zd(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)}`){V(n,"BUNDLE_INTEGRITY");return}if(!i.ok&&i.builtinOnly){V(n,"RESERVED_ID");return}if(!i.ok){V(n,gr(i.rejection.code),Ir(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(L=>({actionId:L.actionId,inputSchema:L.inputSchema})));}catch(L){if(L instanceof be){V(n,Lr(L.code));return}throw L}let a;try{a=await dt(e,n,"ui/index.html",dn);}catch(L){V(n,Xe(ae(L),"entry"));return}if(a.byteLength>dn){V(n,"LIMIT_EXCEEDED");return}let c;try{c=br(a);}catch{V(n,"ENTRY_INVALID");return}if(a.byteLength===0||c.length===0){V(n,"ENTRY_INVALID");return}let d=createHash("sha256").update(a).digest("hex");if(r.entryHash!==void 0&&r.entryHash!==d){V(n,"ENTRY_INVALID");return}let l={},p,u;if(r.initialState!==void 0){try{p=await dt(e,n,"ui/state.json",2097152);}catch(L){V(n,Xe(ae(L),"initial"));return}if(p.byteLength>2097152){V(n,"LIMIT_EXCEEDED");return}try{let L=Hd(p),J=r.dataPaths??[],pe=zt(L,J);l=ye(pe,0,J),Qe(l);}catch{V(n,"INITIAL_STATE_INVALID");return}if(u=createHash("sha256").update(p).digest("hex"),r.initialState.hash!==void 0&&r.initialState.hash!==u){V(n,"INITIAL_STATE_INVALID");return}}let f={...r,entryHash:d,...r.initialState===void 0?{}:{initialState:{path:"ui/state.json",hash:u}}},g=mn(f),_=Zd(f,a,p??new Uint8Array),P;try{P=Qd(g,_);}catch(L){if(L instanceof se){V(n,$d(L));return}throw L}let U;if(n.bundleLineage!==void 0){let L=n.bundleLineage[n.bundleLineage.length-1];if(!L){V(n,"LINEAGE_INVALID");return}let{legacy:J,...pe}=L.definition,{hash:K,...Me}=P;if(te(pe)!==te(Me)){V(n,"LINEAGE_STALE");return}if(J!==void 0&&(P={...P,legacy:J}),J!==void 0)try{P={...P,hash:le(P)},Ae(P);}catch{V(n,"LINEAGE_INVALID");return}U=n.bundleLineage;}if(n.bundleIdentity!==void 0&&n.bundleIdentity.appId!==r.pluginId){V(n,"BUNDLE_INTEGRITY");return}if(n.bundleIdentity!==void 0&&(n.bundleIdentity.definitionId!==P.id||n.bundleIdentity.version!==P.version||n.bundleIdentity.definitionHash!==P.hash)){V(n,"LINEAGE_STALE");return}let k=vd(r.pluginId),N=r.actions.length===0?{read:k.read}:k,C=Ke(g),F=Ke(f),D=Ke(P),b=Ke({...g.handlers}),R=mr(a),y=p===void 0?void 0:mr(p),I=Object.freeze({...n.provenance===void 0?{}:{provenance:n.provenance},entry:Object.freeze({path:"ui/index.html",hash:d,bytes:R}),...y===void 0?{}:{initialState:Object.freeze({path:"ui/state.json",hash:u,bytes:y})}}),h={appId:r.pluginId,pluginId:r.pluginId,definitionId:r.definitionId,version:r.version,...i.releaseVersion===void 0?{}:{releaseVersion:i.releaseVersion},manifestFile:i.file,...i.mcpb===void 0?{}:{mcpb:Ke(i.mcpb)},relativePath:n.relativePath,manifest:F,normalized:C,name:r.name,description:r.description,...r.icon===void 0?{}:{icon:r.icon},...r.tone===void 0?{}:{tone:r.tone},definition:D,handlers:b,resources:I,html:c,entryBytes:R,entryHash:d,initialState:Ke(l),...y===void 0?{}:{initialStateBytes:y},...u===void 0?{}:{initialStateHash:u},sourceHash:_,toolNames:Object.freeze(N)},E=n.provenance===void 0?{...h,source:n.source}:{...h,provenance:n.provenance,lineage:U??[]};n.candidate=Object.freeze(E),ep(r)&&V(n,"EXEC_DENIED");}async function Ur(e,n){let t={};for(let i of Z)try{t[i]=await dt(e,n,i,262144);}catch(o){if(ae(o)==="NOT_FOUND")continue;return {files:t,failure:Xe(ae(o),"manifest")}}if(t[W]!==void 0)try{t[H]=await dt(e,n,H,262144);}catch(i){if(ae(i)!=="NOT_FOUND")return {files:t,failure:Xe(ae(i),"manifest")}}return {files:t}}function Ei(e){return Z.some(n=>e[n]!==void 0)}async function ap(e,n){let{files:t,failure:i}=await Ur(e,n);if(i!==void 0){V(n,i);return}let o=t[W];return o!==void 0&&!Yt(o)&&(delete t[W],delete t[H]),Ei(t)?t:void 0}function cp(e,n,t,i=xd,o=false,r=new Set){let s=sp(e),a=op(s,r),c=Object.freeze(s.filter(u=>u.candidate!==void 0&&u.diagnostic===void 0&&!a.has(u)).map(u=>u.candidate)),d=Object.freeze(s.filter(u=>u.diagnostic!==void 0).map(u=>u.diagnostic)),l=o?Object.freeze({...t===void 0?{}:{indexHash:t},candidates:Object.freeze(s.filter(u=>u.source==="bundled"&&u.diagnostic===void 0&&t!==void 0&&u.candidate?.provenance?.indexHash===t).map(u=>u.candidate)),diagnostics:Object.freeze(d.filter(u=>u.source==="bundled").map(u=>Object.freeze({...u}))),reservedAppIds:Object.freeze([...i.appIds]),reservedDefinitionIds:Object.freeze([...i.definitionIds])}):void 0,p={apps:c,diagnostics:d,complete:n===void 0,...n===void 0?{}:{incompleteReason:n},...t===void 0?{}:{productBundleIndexHash:t},...l===void 0?{}:{productBundleSnapshotMetadata:l}};return Object.defineProperty(p,"candidates",{configurable:false,enumerable:false,get:()=>c}),Object.freeze(p)}function dp(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 pp(e,n){if(dp(e))return {fs:e,options:{}};let t=e??n??{};return {fs:t.filesystem??t.fileSystem??t.fs??sr,options:t}}async function kr(e,n,t){if(typeof e!="string"||e.length===0)throw new TypeError("workspaceRoot must be explicit");let{fs:i,options:o}=pp(n,t),r=o.clock??Kd,s=r(),a=await ur(o.productBundle,i,s,r),c=r(),d=BigInt(Date.now())*1000000n,l=[],p=0,u,f=false,g,_;if(o.scanCache!==void 0&&typeof i.getRootIdentity=="function"&&typeof i.fingerprintVerifiedFile=="function")try{_=await i.getRootIdentity(e),g=nr(o.scanCache,_),g.scanStartedAtNs=d;}catch(D){if(ae(D)!=="NOT_FOUND")throw D}let P=g!==void 0&&o.productBundle===void 0&&a.packages.length===0&&a.diagnostics.length===0,U=new Set,k=true;l.push(...a.diagnostics.map(D=>({source:D.source,root:o.productBundle?.root??e,name:"",relativePath:D.relativePath,diagnostic:D})));let N=a.reservedIds;a.incomplete&&(u="time_limit");for(let D of a.packages){if(!we(c,r)){f=true,u="time_limit";break}let b=D.indexEntry,R=b.packageDir,y=D.files===void 0?void 0:Wd(R,D.files),I=a.indexHash===void 0?void 0:So(Object.freeze({kind:"bundled",launcher:b.launcher!==false,indexHash:a.indexHash,packageDir:R,appId:b.appId,definitionId:b.definition.id,version:b.definition.version,definitionHash:b.definition.hash,files:b.files}),y),h={source:"bundled",root:o.productBundle?.root??e,name:R.slice(5),relativePath:R,...I===void 0?{}:{provenance:I},...D.files===void 0?{}:{pinnedFiles:D.files},...D.lineage===void 0?{}:{bundleLineage:D.lineage},bundleIdentity:{appId:b.appId,definitionId:b.definition.id,version:b.definition.version,definitionHash:b.definition.hash},identity:Gd(b)};if(l.push(h),p+=1,D.failureCode!==void 0){V(h,D.failureCode);continue}if(D.files?.has(H)===true){V(h,"EXEC_DENIED",{reason:{path:"",rule:"bundled-tool-mode-unsupported",file:H}});continue}let E={};for(let L of Z){let J=D.files?.get(L);J!==void 0&&(E[L]=J);}if(!Ei(E)){V(h,"BUNDLE_INTEGRITY");continue}if(await Nr(i,h,E),!we(c,r)){f=true,u="time_limit";break}}let C=[{source:"apps",directory:"apps"},{source:"skills",directory:"skills"}];e:for(let D of C){let{source:b,directory:R}=D,y;try{y=await tp(i,e,R);}catch(h){if(ae(h)==="NOT_FOUND")continue;P=false,k=false,l.push({source:b,root:e,name:"",relativePath:b,diagnostic:ct(Xe(ae(h),"manifest"),b,b)});continue}let I=y.filter(h=>h.kind==="directory"||h.kind==="symlink").filter(h=>Vd(h.name)).map(h=>({source:b,root:e,name:h.name,relativePath:Fd(b,h.name)})).sort((h,E)=>wn(h.relativePath,E.relativePath));for(let h of I){let E={...h};if(l.push(E),_!==void 0?U.add(Rr(_,E)):P=false,!we(c,r)){f=true,u="time_limit";break e}let L;if(g!==void 0&&_!==void 0){try{let K=await qd(i,e,_,E,g,d,c,r);if(K.timeLimitReached){f=!0,u="time_limit";break e}E.scanContext=K.context,L=K.memo;}catch(K){P=false,V(E,Xe(ae(K),"manifest"));continue}L===void 0&&(P=false);}if(L!==void 0){if(E.candidate=L.candidate,E.diagnostic=L.diagnostic,E.identity=L.identity,b==="skills"&&L.candidate===void 0&&L.diagnostic===void 0)continue;if(p>=64){V(E,"LIMIT_EXCEEDED");continue}if(h.relativePath.split("/").length-1>2){V(E,"LIMIT_EXCEEDED");continue}if(p+=1,!we(c,r)){f=true,u="time_limit";break e}continue}let J;if(b==="skills"&&(J=await ap(i,E),J===void 0)){E.diagnostic===void 0&&_i(E);continue}if(p>=64){V(E,"LIMIT_EXCEEDED");continue}if(h.relativePath.split("/").length-1>2){V(E,"LIMIT_EXCEEDED");continue}if(!we(c,r)){f=true,u="time_limit";break e}if(p+=1,J===void 0){let K=await Ur(i,E);if(K.failure!==void 0||!Ei(K.files)){V(E,K.failure??Xe("NOT_FOUND","manifest")),_i(E);continue}J=K.files;}if(await Nr(i,E,J),_i(E),!we(c,r)){f=true,u="time_limit";break e}}}if(g!==void 0&&_!==void 0){let D=[...U].sort(wn),b=g.lastCandidateKeys,R=b!==void 0&&b.length===D.length&&b.every((I,h)=>I===D[h]);if(P=P&&R,k&&!f&&u===void 0)for(let I of g.candidates.keys())try{JSON.parse(I)[0]===_.realPath&&!U.has(I)&&g.candidates.delete(I);}catch{g.candidates.delete(I);}let y=[...g.candidates.keys()].filter(I=>{try{return JSON.parse(I)[0]===_.realPath}catch{return false}});P=P&&y.length===U.size&&y.every(I=>U.has(I))&&!f&&u===void 0,g.lastCandidateScanUnchanged=P,k&&!f&&u===void 0&&(g.lastCandidateKeys=Object.freeze(D));}f&&l.push({source:"apps",root:e,name:"",relativePath:"apps",diagnostic:ct("DISCOVERY_TIME_LIMIT","apps","apps")});let F=rp(l,o,N);return cp(l,u,a.indexHash,N,o.productBundle!==void 0,F)}var xd,hi,fr,jd,hr,Yd,_r,xr=B(()=>{m();He();kn();Le();qt();Be();Qn();Qo();Jn();tr();ui();Kn();mi();mi();xd=st([]),hi="crewx_local_app_";fr=["bundled","apps","skills"],jd=new TextDecoder("utf-8",{fatal:true});hr=["","/ui"],Yd=["/dist"],_r=2000000000n;});m();qt();m();Ct();m();var yo="SKILL.md",Nc=/^---\s*\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;function Ao(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function Dc(e){return e.isDirectory()||e.isSymbolicLink()}function _o(e){try{return existsSync(e)&&statSync(e).isDirectory()}catch{return false}}function Zt(e){let n;try{n=readFileSync(e,"utf8");}catch{return {frontmatter:{},readable:false,valid:false,hasFrontmatter:false}}let t=n.match(Nc);if(!t)return {frontmatter:{},readable:true,valid:true,hasFrontmatter:false};try{let i=load(t[1]??"");if(!Ao(i))return {frontmatter:{},readable:!0,valid:!1,hasFrontmatter:!0};let o=Ao(i.metadata)?i.metadata:void 0;return {frontmatter:{...typeof i.name=="string"?{name:i.name}:{},...typeof(o?.version??i.version)=="string"?{version:o?.version??i.version}:{},...typeof i.description=="string"?{description:i.description}:{}},readable:!0,valid:!0,hasFrontmatter:!0}}catch{return {frontmatter:{},readable:true,valid:false,hasFrontmatter:true}}}function bc(e){return [join(e,yo),join(e,"skill",yo)]}function Io(e,n){if(!_o(e))return null;for(let t of bc(e)){if(!existsSync(t))continue;let o=Zt(t).frontmatter;return {name:o.name??n,...o.version===void 0?{}:{version:o.version},...o.description===void 0?{}:{description:o.description},skillMdPath:t,dir:e}}return null}function go(e){try{return readdirSync(e,{withFileTypes:!0}).filter(Dc)}catch{return []}}function mo(e,n,t){!e||n.has(e.name)||(n.add(e.name),t.push(e));}function Eo(e){let n=[],t=new Set;for(let i of e)if(_o(i))for(let o of go(i)){if(o.name.startsWith("@")){let r=join(i,o.name);for(let s of go(r))mo(Io(join(r,s.name),s.name),t,n);continue}mo(Io(join(i,o.name),o.name),t,n);}return n.sort((i,o)=>i.name.localeCompare(o.name))}m();Gn();var Sc=/^[A-Za-z0-9_$.[\]"-]{0,200}$/,Mc=/^[a-z][a-z0-9-]{0,63}$/,Lc="<unknown>";function Rc(e){return typeof e=="string"&&(Z.includes(e)||e===H)}function To(e){if(typeof e!="object"||e===null)return;let{file:n,path:t,rule:i}=e;if(!(typeof i!="string"||!Mc.test(i)))return {...Rc(n)?{file:n}:{},path:typeof t=="string"&&Sc.test(t)?t:Lc,rule:i}}function Po(e){if(!Array.isArray(e))return;let n=Z.filter(t=>e.includes(t));return n.length>0?n:void 0}xr();var up=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/;function ft(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?fp(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 fp(e,n){let t=new TextEncoder().encode(yt(e)),i=yp(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 yp(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 yt(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 lt(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 Fr(e,n){let t=relative(e,n).split(sep).join("/");return !t||t===".."||t.startsWith("../")||isAbsolute(t)?null:yt(t)}function Ap(e){return e==="apps"||e.startsWith("apps/")?"apps":e==="skills"||e.startsWith("skills/")?"skills":e==="node_modules"||e.startsWith("node_modules/")?"node_modules":null}function Vr(e){return Object.freeze({packageRoot:e})}function Ip(e){return Object.freeze({id:e.definition.id,version:e.definition.version,hash:e.definition.hash,usage:e.definition.usage??xe,...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 Br(e){return {capabilities:Object.freeze([...e]),origin:"local",ownership:"unknown",shareability:"unknown",sharingAvailability:"unavailable"}}function gp(e,n){let t=e.candidate,i=t.provenance!==void 0,o=n&&!i?["screen","skill"]:["screen"],r=Ip(t),s=ft(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,...Br(o),definition:r,...n===void 0||i?{}:{skillName:n.skill.name},...i?{provenance:t.provenance}:{localDefinitionRef:Vr(e.packageRoot)},definitionHash:s,...t.manifest.csp===void 0?{}:{connectDomains:Object.freeze([...t.manifest.csp.connectDomains])}};return {...i?{}:{packageRoot:e.packageRoot},source:i?"bundled":t.source,appId:d.appId,capabilities:o,summary:Object.freeze(d)}}function mp(e){let n=hp(e.skill.name),t={appId:n,name:e.skill.name,description:e.skill.description??"",...e.skill.version===void 0?{}:{version:e.skill.version},...Br(["skill"]),skillName:e.skill.name,localDefinitionRef:Vr(e.packageRoot),definitionHash:ft({skillHash:e.skillHash})};return {packageRoot:e.packageRoot,source:e.source,appId:n,capabilities:["skill"],summary:Object.freeze(t)}}function hp(e){return `skill.${e.replace(/^@/,"").replace(/\//g,".").replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,122)||"unnamed"}`}function Q(e,n,t,i,o){let r=To(o?.reason),s=Po(o?.files);return Object.freeze({code:e,source:n,relativePath:_p(t),...i===void 0?{}:{appId:i},...r===void 0?{}:{reason:r},...s===void 0?{}:{files:s}})}function _p(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 Hr(e){return Q(e.code,e.source,e.relativePath,e.pluginId,e)}function Ep(e,n){let t=Fr(e,n.dir);if(!t)return {diagnostic:Q("PATH_ESCAPED","node_modules","node_modules")};let i=Ap(t);if(!i)return {diagnostic:Q("PATH_ESCAPED","node_modules",t)};let o=Zt(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=Tp(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:ft({relativePath:r,fileBytes:s}),source:i}}catch{return {diagnostic:Q("SKILL_READ_FAILED",i,t)}}}function Tp(e,n){let t=relative(e,n).split(sep).join("/");try{return yt(t)}catch{return null}}function Pp(e){if(!up.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??xe,...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 Np(e){return e.builtinCatalog}function Dp(e){let n=e.packageRoot??e.relativePath??e.packageRootPath;if(n===void 0)return null;try{return yt(n)}catch{return null}}function bp(e){let n=e.marketplaceContentId;return typeof n=="string"&&n.length>0?n:void 0}function Sp(e,n,t){let i=n.installed??[],o=new Map;for(let s of i){let a=Dp(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=bp(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 l={...c.summary,origin:"installed",...a.slug===void 0?{}:{slug:a.slug},marketplaceContentId:d},p=e.indexOf(c);p>=0&&(e[p]={...c,summary:Object.freeze(l)});}}function Mp(e,n){let t=new Map;for(let o of e){let r=t.get(o.appId)??[];r.push(o),t.set(o.appId,r);}let i=new Set;for(let o of t.values()){if(o.length<2)continue;let r=o.some(s=>s.source==="builtin")?"builtin":o.some(s=>s.source==="bundled")?"bundled":void 0;if(r==="bundled"){let s=o.filter(a=>a.source==="apps"&&a.summary.definition!==void 0);if(s.length===1){for(let a of o)a.source==="bundled"?i.add(a):a!==s[0]&&(i.add(a),n.push(Q("RESERVED_ID",a.source,ut(a),a.appId)));continue}}if(r!==void 0){let s=o.filter(a=>a.source===r);for(let a of o.filter(c=>c.source!==r))i.add(a),n.push(Q("RESERVED_ID",a.source,ut(a),a.appId));if(s.length>1)for(let a of s)i.add(a),n.push(Q("DUPLICATE_ID",a.source,ut(a),a.appId));continue}for(let s of o)i.add(s),n.push(Q("DUPLICATE_ID",s.source,ut(s),s.appId));}return e.filter(o=>!i.has(o))}function ut(e){return e.packageRoot??e.summary.provenance?.packageDir??`builtin/${e.appId}`}function Lp(e,n){return e.filter(t=>!(t.code==="MANIFEST_MISSING"&&n.has(t.relativePath))).map(Hr)}function Rp(e){return e.filesystem}function Op(e,n){let t=Rp(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 zr(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=Np(n),i=await kr(e,Op(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 I of r)for(let h of Eo([I])){let E=Fr(e,h.dir);(E===null||!d.has(E))&&(c.push(h),E!==null&&d.add(E));}for(let I of c){let h=Ep(e,I);"diagnostic"in h?s.push(h.diagnostic):a.push(h);}let l=new Map,p=n.registeredProductBundle?.indexHash,u=(n.registeredProductBundle?.candidates??[]).filter(I=>p!==void 0&&I.provenance?.indexHash===p),f=[...new Set([...i.apps??i.candidates??[],...i.productBundleSnapshotMetadata?.candidates??[]]),...u],g=new Set(u),_=new Set(p===void 0?[]:(t?.listMcpApps()??[]).filter(I=>I.provenance?.indexHash===p).map(I=>I.appId));for(let I of f){if(g.has(I)&&I.provenance?.indexHash===p&&_.has(I.appId))continue;let h=I.provenance===void 0?`workspace\0${I.relativePath}`:`bundled\0${I.provenance.indexHash}\0${I.provenance.packageDir}`;l.set(h,{candidate:I,packageRoot:I.relativePath});}let P=new Map(a.map(I=>[I.packageRoot,I])),U=[];for(let I of l.values()){let h=I.candidate.provenance===void 0?P.get(I.packageRoot):void 0,E=gp(I,h);U.push({...E.packageRoot===void 0?{}:{packageRoot:E.packageRoot},source:E.source,appId:E.appId,summary:E.summary});}let k=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=mp(I);if(!(k.has(I.packageRoot)||N.has(I.packageRoot))){if(C.has(h.appId)){s.push(Q("RESERVED_ID",I.source,I.packageRoot,h.appId));continue}U.push({packageRoot:h.packageRoot,source:h.source,appId:h.appId,summary:h.summary});}}let F=[...Lp(i.diagnostics,new Set(a.map(I=>I.packageRoot))),...s,...n.registeredProductBundle?.diagnostics.filter(I=>I.source==="bundled").map(Hr)??[]],D=[];if(t)for(let I of t.listMcpApps()){let h=Pp(I);"diagnostic"in h?F.push(h.diagnostic):D.push(h);}let b=Mp([...U,...D],F);Sp(b,n,F);let R=b.map(I=>I.summary).sort((I,h)=>lt(I.appId,h.appId)),y=[...F].sort((I,h)=>lt(I.relativePath,h.relativePath)||lt(I.code,h.code)||lt(I.appId??"",h.appId??""));return Object.freeze({items:Object.freeze(R),diagnostics:Object.freeze(y)})}m();m();m();function wp(e){let n=o=>o.replace(/[.+^${}()|[\]\\]/g,"\\$&"),i=e.split("/").map(o=>o==="**"?".*":o.split("*").map(n).join("[^/]*"));return new RegExp(`^${i.join("\\/")}$`)}function un(e,n){try{return wp(n).test(e)}catch{return false}}function At(e,...n){let t=e.split("/");if(t.length<n.length)return false;let i=t.length-n.length;return n.every((o,r)=>un(t[i+r],o))}function Cp(e,n){return e.split("/").some(t=>un(t,n))}var $r=[{label:".env*",test:e=>un(e,".env*")},{label:".git/",test:(e,n,t)=>t&&e===".git"},{label:"memory/",test:(e,n,t)=>t&&e==="memory"},{label:"*.key",test:e=>un(e,"*.key")},{label:"*.pem",test:e=>un(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&&At(n,".crewx","threads")},{label:".crewx/crewx.db",test:(e,n,t)=>!t&&At(n,".crewx","crewx.db")},{label:".crewx/*.log",test:(e,n,t)=>!t&&At(n,".crewx","*.log")},{label:".crewx/publish/",test:(e,n,t)=>t&&At(n,".crewx","publish")},{label:".crewx/",test:(e,n)=>Cp(n,".crewx")}];function fn(e,n,t){for(let i of $r)if(i.test(e,n,t))return i.label;return null}m();var Ce=class extends Error{constructor(t,i){super(`publish: [${t}]${i?` ${i}`:""}`);this.code=t;}code;name="PublishError"};function T(e,n){return new Ce(e,n)}function Gr(e,n){if(!n||/[\\\u0000]/.test(n)||ce.posix.isAbsolute(n)||n.split("/").some(f=>!f||f==="."||f===".."))throw T("PACKAGE_PATH_TRAVERSAL","package root must be a safe workspace-relative path");let t=ce.resolve(e),i=ce.resolve(t,...n.split("/"));if(!i.startsWith(`${t}${ce.sep}`))throw T("PACKAGE_PATH_TRAVERSAL","package root escaped the workspace");function o(f,g){let _;try{_=ne.lstatSync(f);}catch{throw T("PACKAGE_FILE_INVALID",`package directory is missing: ${g}`)}if(_.isSymbolicLink())throw T("PACKAGE_SYMLINK",`symlink is not publishable: ${g}`);if(!_.isDirectory())throw T("PACKAGE_FILE_INVALID",`not a package directory: ${g}`)}o(t,".");let r=t,s="",a=null;for(let f of n.split("/"))r=ce.join(r,f),s=s?`${s}/${f}`:f,o(r,s),a??=fn(f,s,true);let c=[],d=[];function l(f,g){o(f,g);let _=ne.readdirSync(f,{withFileTypes:true});for(let P of _){let U=`${g}/${P.name}`,k=ce.join(f,P.name);if(P.isSymbolicLink())throw T("PACKAGE_SYMLINK",`symlink is not publishable: ${U}`);let N=fn(P.name,U,P.isDirectory());N?d.push({path:U,rule:N}):P.isDirectory()?l(k,U):P.isFile()&&c.push(U);}}a?d.push({path:n,rule:a}):l(i,n);let p=new TextEncoder,u=(f,g)=>Buffer.compare(p.encode(f),p.encode(g));return c.sort(u),d.sort((f,g)=>u(f.path,g.path)),{included:c,excluded:d}}function Wr(e){let n=[],t=[];function i(o,r,s){let a;try{a=ne.readdirSync(o,{withFileTypes:!0});}catch{return}a.sort((c,d)=>c.name.localeCompare(d.name));for(let c of a){let d=r?`${r}/${c.name}`:c.name,l=ce.join(o,c.name);if(c.isSymbolicLink()){let p;try{p=ne.statSync(l);}catch{t.push({path:d,rule:"symlink"});continue}if(p.isDirectory()){t.push({path:d,rule:s??"symlink-dir"});continue}let u=s??fn(c.name,d,false);u?t.push({path:d,rule:u}):t.push({path:d,rule:"symlink"});continue}if(c.isDirectory()){let p=s??fn(c.name,d,true);i(l,d,p);continue}if(c.isFile()){let p=s??fn(c.name,d,false);p?t.push({path:d,rule:p}):n.push(d);}}}return i(e,"",null),n.sort(),t.sort((o,r)=>o.path<r.path?-1:o.path>r.path?1:0),{included:n,excluded:t}}m();var Up=[{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 kp(e){return e.includes(0)}function Di(e,n,t){let i=[];for(let o of n){let r=ce.join(e,o),s;try{let c=t?.get(o);s=c===void 0?ne.readFileSync(r):Buffer.from(c);}catch{continue}if(kp(s))continue;s.toString("utf8").split(/\r\n|\r|\n/).forEach((c,d)=>{for(let{rule:l,regex:p}of Up)p.test(c)&&i.push({path:o,line:d+1,rule:l});});}return i}m();var Xr=/^[a-z0-9-]+$/,xp=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/,vp=/^[A-Za-z_][A-Za-z0-9_]*$/;function jp(e){let n=ce.join(e,"crewx.yaml");if(!ne.existsSync(n))return {};let t;try{t=Yr.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 Fp(e){return bi.createHash("sha256").update(e).digest("hex")}function qr(e){let n;try{n=ne.lstatSync(e);}catch{throw T("PACKAGE_FILE_INVALID",`file is not readable: ${ce.basename(e)}`)}if(n.isSymbolicLink())throw T("PACKAGE_SYMLINK","symlink content is not publishable");if(!n.isFile())throw T("PACKAGE_FILE_INVALID","only regular files are publishable");return bi.createHash("sha256").update(new Uint8Array(ne.readFileSync(e))).digest("hex")}function Vp(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 Zr(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 T("PACKAGE_PATH_TRAVERSAL","manifest file path must be a non-empty POSIX relative path")}function Bp(e){if(!/^(?:apps|skills)\/[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(e))throw T("APP_PACKAGE_ROOT_INVALID","packageRoot must be apps/<safe-id> or skills/<safe-id>")}function Qr(e){if(!xp.test(e))throw new Error(`publish: invalid version "${e}" \u2014 must be semver (e.g. 1.0.0)`)}function es(e,n,t={}){let i=jp(e),o=i.name??ce.basename(e);if(!Xr.test(o))throw new Error(`publish: invalid name "${o}" \u2014 must match ${Xr} (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");Qr(r);let s=Array.isArray(i.requiredEnv)?i.requiredEnv:[],a=[];for(let l of s){if(typeof l!="string"||!vp.test(l))throw new Error(`publish: requiredEnv must contain names only (no values), got "${String(l)}"`);a.push(l);}let c=n.map(l=>(Zr(l),{path:l,sha256:qr(ce.join(e,l))})).sort((l,p)=>l.path<p.path?-1:l.path>p.path?1:0),d={name:o,version:r,type:"template",description:i.description??"",files:c,requiredEnv:a};return i.crewxMinVersion&&(d.crewxMinVersion=i.crewxMinVersion),d}function Hp(e){let n=e.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"");if(!n)throw T("APP_PACKAGE_ROOT_INVALID","appId cannot produce a marketplace name");return n}function ns(e,n){if(Bp(n.packageRoot),!n.version)throw new Error("publish: version is required for App publishing \u2014 pass opts.version");if(Qr(n.version),typeof n.description!="string")throw new Error("publish: App description must be a string");let t=[...new Set(n.capabilities)].sort();if(t.length===0||t.some(s=>s!=="screen"&&s!=="skill"))throw new Error("publish: App capabilities must contain screen or skill");let i=`${n.packageRoot}/`;if(t.includes("screen")){if(typeof n.definitionId!="string"||n.definitionId.length===0)throw T("APP_UI_MANIFEST_INVALID","screen App manifests require definitionId");let s=n.includedFiles.includes(`${i}manifest.json`),a=n.includedFiles.includes(`${i}ui-plugin.json`);if(!s&&!a)throw T("APP_UI_MANIFEST_INVALID","screen App is missing manifest.json or ui-plugin.json");if(s&&!a)throw T("APP_UI_MANIFEST_INVALID","a manifest.json App must also ship a generated ui-plugin.json");if(!n.includedFiles.includes(`${i}ui/index.html`))throw T("APP_UI_MANIFEST_INVALID","screen App is missing ui/index.html")}if(t.includes("skill")&&!n.includedFiles.includes(`${i}SKILL.md`))throw T("APP_SKILL_MISSING","skill capability requires package-root SKILL.md");let o=new Set,r=n.includedFiles.map(s=>{if(Zr(s),!s.startsWith(i))throw T("PACKAGE_PATH_TRAVERSAL","App manifest file is outside packageRoot");let a=n.generatedFiles?.get(s);return a!==void 0&&o.add(s),{path:s,sha256:a===void 0?qr(ce.join(e,s)):Fp(a),...a===void 0?{}:{generated:true}}}).sort((s,a)=>Vp(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:Hp(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 ts(e){return bi.createHash("sha256").update(e).digest("hex")}function as(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 T("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 T("PACKAGE_PATH_TRAVERSAL","archive path escaped its root");return i}function is(e,n){let t=as(e,n),i;try{i=ne.lstatSync(t);}catch{throw T("PACKAGE_FILE_INVALID","manifest file is missing")}if(i.isSymbolicLink())throw T("PACKAGE_SYMLINK","symlink content is not publishable");if(!i.isFile())throw T("PACKAGE_FILE_INVALID","only regular files are publishable");return new Uint8Array(ne.readFileSync(t))}async function cs(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(os.tmpdir(),"crewx-publish-"));try{let a=new Set,c=[];for(let d of n.files){if(a.has(d.path))throw T("PACKAGE_PATH_TRAVERSAL","manifest contains duplicate file paths");a.add(d.path);let l=t.generatedFiles?.get(d.path);if(d.generated===!0&&l===void 0)throw T("PACKAGE_GENERATED_FILE_MISSING","generated manifest file bytes are missing");if(t.sourceFileHashes?.has(d.path)){let f=is(e,d.path);if(t.sourceFileHashes.get(d.path)!==ts(f))throw T("PACKAGE_STAGED_BYTES_MISMATCH","workspace source changed before staging")}let p=l??is(e,d.path);if(ts(p)!==d.sha256)throw T("PACKAGE_STAGED_BYTES_MISMATCH",`staged bytes differ for ${d.path}`);let u=as(s,d.path);ne.mkdirSync(ce.dirname(u),{recursive:!0}),ne.writeFileSync(u,new Uint8Array(p)),c.push(d.path);}ne.writeFileSync(ce.join(s,"manifest.json"),JSON.stringify(n,null,2)),await ss.create({gzip:!0,file:r,cwd:s,portable:!0,noMtime:!0},["manifest.json",...c]),ne.renameSync(r,o);}finally{try{ne.rmSync(r,{force:!0});}catch{}ne.rmSync(s,{recursive:true,force:true});}return o}m();m();var yn="/api/v1";var Gp=201,Wp=200,Jp=409,Si=401,ds={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 Kp(){return process.env.WI013_FAKE_UPLOAD==="1"}function Xp(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 Yp(e){return e.replace(/\/+$/,"")}async function Cn(e){try{return await e.json()}catch{return null}}function ps(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 qp(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 Zp(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 ls(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(ds,r))continue;let s=r,a=s==="APP_NAME_CONFLICT"?`marketplace name is already in use: ${n}`:void 0;return T(ds[s],a)}}async function Qp(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=Yp(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}${yn}/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 Cn(a),d=qp(c),l=Zp(c),p=r&&l!==void 0?l:i,u;if(a.status===Gp)u="created";else if(r&&a.status===Wp){if(d===void 0)throw T("PUBLISH_CONTENT_ID_MISSING","App republish did not return an opaque contentId");u="existing";}else if(a.status===Jp){if(r)throw ls(c,i)??T("APP_NAME_CONFLICT",`marketplace name is already in use: ${i}`);u="existing";}else throw a.status===Si?new Error("publish: [E_AUTH_EXPIRED] Authentication is expired or missing \u2014 please log in again (HTTP 401)"):new Error(`publish: [E_HTTP] Submit request failed \u2014 HTTP ${a.status}`);let f="not-needed",g=null;if(u==="existing"&&!r){let b;try{b=await fetch(`${n}${yn}/publisher/items`,{method:"GET",headers:{Authorization:`Bearer ${e.accessToken}`}});}catch{throw new Error("publish: [E_NETWORK] Publisher items request failed (network)")}let R=await Cn(b);if(b.status!==200)throw new Error(`publish: [E_HTTP] Publisher items request failed \u2014 HTTP ${b.status}`);let I=ps(R,"publisher items",b.status)?.items;if(!Array.isArray(I))throw new Error(`publish: [E_MALFORMED] Publisher items response is malformed (expected data.items[]) \u2014 HTTP ${b.status}`);let h=I.find(E=>!E||typeof E!="object"?false:E.slug===i);if(!h||typeof h.version!="string")throw new Error(`publish: [E_MALFORMED] Publisher items response does not contain slug "${i}" \u2014 HTTP ${b.status}`);if(g=h.version,g!==e.manifest.version){let E;try{E=await fetch(`${n}${yn}/publisher/items/${encodeURIComponent(i)}`,{method:"PUT",headers:{Authorization:`Bearer ${e.accessToken}`,"Content-Type":"application/json"},body:JSON.stringify({version:e.manifest.version})});}catch{throw new Error("publish: [E_NETWORK] Version update request failed (network)")}if(!E.ok)throw await Cn(E),E.status===Si?new Error(`publish: [E_AUTH_EXPIRED] Authentication is expired or missing \u2014 please log in again (HTTP ${E.status})`):E.status===403?new Error(`publish: [E_FORBIDDEN] Version update is forbidden; only the item owner can update an existing item (HTTP ${E.status})`):new Error(`publish: [E_HTTP] Version update failed \u2014 HTTP ${E.status}`);f="applied";}}let _=ne.readFileSync(e.tgzPath),P=Kp()?Xp(_):_,U=new FormData;U.set("archive",new Blob([new Uint8Array(P)],{type:"application/gzip"}),`${p}-${e.manifest.version}.tgz`);let k=r&&d!==void 0?d:i,N;try{N=await fetch(`${n}${yn}/publisher/items/${encodeURIComponent(k)}/upload`,{method:"POST",headers:{Authorization:`Bearer ${e.accessToken}`},body:U});}catch{throw new Error("publish: [E_NETWORK] Upload request failed (network)")}if(N.status===Si)throw new Error("publish: [E_AUTH_EXPIRED] Authentication is expired or missing \u2014 please log in again (HTTP 401)");if(!N.ok){let b=await Cn(N);if(r){let R=ls(b,p);if(R)throw R}throw new Error(`publish: [E_HTTP] Upload request failed \u2014 HTTP ${N.status}`)}let C=await Cn(N),F=ps(C,"upload",N.status),D=typeof F.contentId=="string"&&F.contentId.length>0?F.contentId:d;if(r&&D===void 0)throw T("PUBLISH_CONTENT_ID_MISSING","App upload did not return an opaque contentId");return {slug:p,version:e.manifest.version,...D===void 0?{}:{contentId:D},artifactChecksum:F.artifactChecksum,artifactSizeBytes:F.artifactSizeBytes,submitOutcome:u,versionUpdate:f,serverVersionBefore:g}}var el=1e4,nl=100*1024*1024;function Mi(e){return bi.createHash("sha256").update(e).digest("hex")}function tl(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function Un(e,n){if(!n||n.includes("\\")||n.includes("\0")||ce.posix.isAbsolute(n)||n.split("/").some(r=>r===".."||r.length===0))throw T("PACKAGE_PATH_TRAVERSAL","workspace file path is not a safe relative path");let t=ce.resolve(e,...n.split("/")),i=ce.resolve(e);if(t!==i&&!t.startsWith(`${i}${ce.sep}`))throw T("PACKAGE_PATH_TRAVERSAL","workspace file path escaped the workspace root");let o;try{o=ne.lstatSync(t);}catch{throw T("PACKAGE_FILE_INVALID",`workspace file is missing: ${n}`)}if(o.isSymbolicLink())throw T("PACKAGE_SYMLINK",`symlink is not publishable: ${n}`);if(!o.isFile())throw T("PACKAGE_FILE_INVALID",`not a regular file: ${n}`);return new Uint8Array(ne.readFileSync(t))}function fs(e,n,t){let i=e??n;if(!Number.isSafeInteger(i)||i<=0)throw new Ce("PACKAGE_SIZE_LIMIT",`${t} must be a positive integer`);return i}function As(e,n,t,i){let o=fs(t.maxFileCount??t.maxFiles,el,"max file count"),r=fs(t.maxTotalBytes??t.maxBytes,nl,"max total bytes");if(n.length>o)throw new Ce("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+=Un(e,a).byteLength,s>r)throw new Ce("PACKAGE_SIZE_LIMIT",`package exceeds byte limit (${r})`)}}function il(e){return e.appId!==void 0||e.expectedDefinitionHash!==void 0}function ol(e){let n=e.appId!==void 0,t=e.expectedDefinitionHash!==void 0;if(!n&&t)throw T("APP_ID_REQUIRED","appId is required with expectedDefinitionHash");if(n&&!t)throw T("APP_DEFINITION_HASH_REQUIRED","expectedDefinitionHash is required with appId");if(!n||!t)throw T("APP_ID_REQUIRED")}function rl(e,n){let t=e.filter(i=>i.appId===n);if(t.length===0)throw T("APP_NOT_FOUND",`no publishable App matches ${n}`);if(t.length!==1)throw T("APP_AMBIGUOUS",`more than one App matches ${n}`);return t[0]}function sl(e){let n=e.localDefinitionRef?.packageRoot;if(!n||!/^(?:apps|skills)\/[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(n))throw T("APP_PACKAGE_ROOT_INVALID","selected App is not rooted in apps/<safe-id> or skills/<safe-id>");return n}function Li(e){let{path:n,rule:t}=e.reason;return `${e.code} at ${n===""?"<file>":n} (${t})`+(e.files.length>0?` [${e.files.join(", ")}]`:"")}function al(e,n,t){let i=Ge({[de]:t},{mode:"published"});if(!i.ok)throw T("APP_UI_MANIFEST_INVALID",`generated ${de} does not read: ${Li(i.rejection)}`);if(an(i.manifest)!==an(n))throw T("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=Ge({[W]:o,[de]:t,...r===void 0?{}:{[H]:r}},{mode:"local"});if(!s.ok)throw T("APP_UI_MANIFEST_INVALID",Li(s.rejection))}function cl(e,n,t,i){let o={};for(let f of Z){let g=`${t}/${f}`;i.includes(g)&&(o[f]=Un(e,g));}let r=`${t}/${H}`;if(o[W]!==void 0&&i.includes(r)&&(o[H]=Un(e,r)),Object.keys(o).length===0)throw T("APP_UI_MANIFEST_INVALID","selected screen App has no package manifest.json or ui-plugin.json");let s=Ge(o,{mode:"local"});if(!s.ok)throw T("APP_UI_MANIFEST_INVALID",Li(s.rejection));if(s.manifest.pluginId!==n.appId)throw T("APP_DEFINITION_CONFLICT",`${s.file} identity no longer matches the selected App`);let a=o[de],c=a===void 0?void 0:Mi(a),d=`${t}/ui/index.html`;if(!i.includes(d))throw T("APP_UI_MANIFEST_INVALID","screen entry is outside package scope");let l=Mi(Un(e,d)),p=JSON.parse(JSON.stringify(s.v2Input));if(p.entryHash=l,Object.prototype.hasOwnProperty.call(p,"initialState")){let f=p.initialState;if(!tl(f)||f.path!=="ui/state.json")throw T("APP_INITIAL_STATE_OUT_OF_SCOPE","initialState must reference ui/state.json inside the package");let g=`${t}/ui/state.json`;if(!i.includes(g))throw T("APP_INITIAL_STATE_OUT_OF_SCOPE","initialState reference is outside the selected package");let _=Un(e,g);p.initialState={...f,hash:Mi(_)};}let u;try{let f=$e(p,{mode:"published"});u=new Uint8Array(Buffer.from(JSON.stringify(f),"utf8"));}catch(f){throw f instanceof se?T("APP_UI_MANIFEST_INVALID",f.code):T("APP_UI_MANIFEST_INVALID")}return al(o,s.manifest,u),{bytes:u,...c===void 0?{}:{legacySourceHash:c}}}async function dl(e,n){let{included:t,excluded:i}=Wr(e);As(e,t,n);let o=es(e,t,{version:n.version}),r=Di(e,t);return {plan:{manifest:o,included:t,excluded:i,secretFindings:r},archiveOptions:{}}}async function pl(e,n){ol(n);let t=await zr(e),i=rl(t.items,n.appId);if(i.definitionHash!==n.expectedDefinitionHash)throw T("APP_DEFINITION_CONFLICT",`definitionHash changed for ${n.appId}`);let o=sl(i),{included:r,excluded:s}=Gr(e,o),a=new Map,c=new Map;if(i.capabilities.includes("screen")){let u=cl(e,i,o,r),f=`${o}/${de}`;if(a.set(f,u.bytes),u.legacySourceHash!==void 0)c.set(f,u.legacySourceHash);else {r.push(f);let g=new TextEncoder;r.sort((_,P)=>Buffer.compare(g.encode(_),g.encode(P)));}}if(i.capabilities.includes("skill")&&!r.includes(`${o}/SKILL.md`))throw T("APP_SKILL_MISSING","skill capability requires package-root SKILL.md");As(e,r,n,a);let d={appId:i.appId,version:n.version??"",description:i.description,capabilities:i.capabilities,packageRoot:o,...i.definition?.id===void 0?{}:{definitionId:i.definition.id},definitionHash:i.definitionHash,includedFiles:r,generatedFiles:a},l=ns(e,d),p=Di(e,r,a);return {plan:{manifest:l,included:r,excluded:s,secretFindings:p},archiveOptions:{generatedFiles:a,sourceFileHashes:c}}}async function Is(e,n){let t=ce.resolve(e);if(il(n))return pl(t,n);if(n.expectedDefinitionHash!==void 0)throw T("APP_ID_REQUIRED");return dl(t,n)}async function cA(e,n={}){return (await Is(e,n)).plan}function ll(e){let n=e.map(t=>`${t.path}:${t.line} (${t.rule})`).join(", ");throw new Ce("PUBLISH_SECRET_FINDINGS",`aborted \u2014 secret findings must be resolved before packing: ${n}`)}async function gs(e,n={}){let t=ce.resolve(e),i=await Is(t,n);i.plan.secretFindings.length>0&&ll(i.plan.secretFindings);let o=await cs(t,i.plan.manifest,i.archiveOptions);return {manifest:i.plan.manifest,tgzPath:o}}async function dA(e,n={}){return gs(e,n)}async function pA(e,n){let t=await gs(e,n);if(t.manifest.type!=="app")throw new Error("publish: App pack unexpectedly produced a template manifest");return t}
|
|
2
|
+
export{nl as DEFAULT_PUBLISH_MAX_BYTES,el as DEFAULT_PUBLISH_MAX_FILES,$r as EXCLUDE_RULES,yn as MARKETPLACE_API_PREFIX,Ce as PublishError,pA as packApp,gs as packPublish,dA as packTemplate,cA as planPublish,Qp as uploadToMarketplace};
|