@crewx/sdk 0.9.0-rc.129 → 0.9.0-rc.130

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- import*as J from'path';import {resolve,relative,sep,isAbsolute,join}from'path';import'url';import*as Dt from'crypto';import {createHash}from'crypto';import*as G from'fs';import {constants,readFileSync,existsSync,statSync,readdirSync}from'fs';import {realpath,stat,readdir,open,lstat}from'fs/promises';import*as Yi from'js-yaml';import {load}from'js-yaml';import*as oo from'os';import*as so from'tar';import {gunzipSync,gzipSync}from'zlib';var j=(e,n)=>()=>(e&&(n=e(e=0)),n);var y=j(()=>{});var N,Dn=j(()=>{y();N=class extends Error{constructor(t,i=t,o){super(i);this.code=t;this.currentRevision=o;}code;currentRevision;name="UiRuntimeError"};});function X(){throw new N("INPUT_INVALID","JSON value is not projection-safe")}function bo(e){let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function Pn(e,n,t,i,o,r){if(n>i&&X(),e===null||typeof e=="string"||typeof e=="boolean")return typeof e=="string"&&(To.test(e)||Po.test(e)&&!Mo(o,r)||Do.test(e))&&X(),e;if(typeof e=="number")return Number.isFinite(e)||X(),e;(typeof e!="object"||e===void 0||typeof e=="function"||typeof e=="bigint")&&X();let s=e;t.has(s)&&X(),t.add(s);try{if(Array.isArray(e))return e.map(p=>Pn(p,n+1,t,i,o,r));bo(s)||X();let a={};for(let[p,c]of Object.entries(e))(Eo.test(p)||_o.test(p))&&X(),a[p]=Pn(c,n+1,t,i,[...o,p],r);return a}finally{t.delete(s);}}function oe(e,n=0,t=[]){(!Number.isInteger(n)||n<0||n>So)&&X(),(!Array.isArray(t)||t.some(o=>typeof o!="string"))&&X();let i=Pn(e,0,new Set,No+n,[],t);return (i===null||Array.isArray(i)||typeof i!="object")&&X(),i}function be(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 Mo(e,n){if(e.length===0)return false;let t=e.join(".");return n.some(i=>be(t,i))}function Ne(e){try{let n=JSON.stringify(e);return n===void 0&&X(),n}catch{X();}}function bn(e){return Array.isArray(e)?e.map(bn):e!==null&&typeof e=="object"?Object.fromEntries(Object.keys(e).sort().map(n=>[n,bn(e[n])])):e}function Y(e){return Ne(bn(e))}function Nn(e){return Buffer.byteLength(e,"utf8")}var Eo,_o,To,Do,Po,No,So,Ae=j(()=>{y();Dn();Eo=/(?:proof|token|secret|password|cookie|authorization|private[_-]?key|stack|exception|plugin[_-]?text)/i,_o=/(?:url|uri|endpoint|path|file(?:name|path)?|cwd|shell|directory|dir|folder)$/i,To=/<\/?[A-Za-z][^>]*>/,Do=/^(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)/,Po=/^(?:https?|file|ftp|ws|wss):\/\//i;No=8,So=4;});function Sn(e){return Y(e)}var Nt=j(()=>{y();Ae();});var Ie,Mn=j(()=>{y();Ie="window";});function Se(e){return Lo.has(e)||Oo.test(e)||Ro.test(e)}var St,Lo,Oo,Ro,Ke,ve,re,Ln,On,Rn,Un,wn,Me=j(()=>{y();St=["__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"],Lo=new Set(St),Oo=/(?:proof|token|secret|password|cookie|authorization|private[_-]?key|stack|exception|plugin[_-]?text)/i,Ro=/(?:url|uri|endpoint|path|file(?:name|path)?|cwd|shell|directory|dir|folder)$/i;Ke=/^[A-Za-z0-9_]+$/,ve=/^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)*$/,re=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,Ln=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/,On=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,Rn=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/,Un=["blue","violet","emerald","amber","rose","sky","slate","indigo"],wn=["inline","panel"];});function kn(e){return typeof e=="string"&&Mt.includes(e)}var Mt,Lt=j(()=>{y();Me();Mt=["text/plain","application/json"];});function Xe(e){if(!Cn(e))return false;let n=Object.keys(e);return !(n.some(t=>t!=="in"&&t!=="out")||n.length===0||Object.hasOwn(e,"in")&&!Uo(e.in)||Object.hasOwn(e,"out")&&!wo(e.out))}function Uo(e){return Cn(e)?Object.keys(e).every(t=>t==="mediaType"||t==="required")&&Object.hasOwn(e,"mediaType")&&kn(e.mediaType)&&(!Object.hasOwn(e,"required")||typeof e.required=="boolean"):false}function wo(e){return Cn(e)?Object.keys(e).every(t=>t==="mediaType"||t==="range")&&Object.hasOwn(e,"mediaType")&&kn(e.mediaType)&&(!Object.hasOwn(e,"range")||typeof e.range=="boolean"):false}function Cn(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}var xn=j(()=>{y();Lt();new TextDecoder("utf-8",{fatal:true,ignoreBOM:true});});function d(e,n=e){throw new K(e,n)}function V(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;try{let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}catch{return false}}function L(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function F(e,n,t=[]){let i=new Set([...n,...t]);Object.keys(e).some(o=>!i.has(o))&&d("MANIFEST_INVALID"),n.some(o=>!L(e,o))&&d("MANIFEST_INVALID");}function en(e,n=false,t=false,i=false){return vo.test(e)||!i&&Vo.test(e)||jo.test(e)||t&&Ot.test(e)||Fo.test(e)&&!(n&&/^\s*data:/i.test(e)&&!Ot.test(e))}function Ze(e,n=new Set,t=0,i=false,o=false){if(typeof e=="string"){en(e,i,o)&&d("UNSAFE_VALUE");return}if(!(e===null||typeof e!="object")){(t>8||n.has(e))&&d("MANIFEST_INVALID"),n.add(e);try{if(Array.isArray(e)){for(let r of e)Ze(r,n,t+1);return}V(e)||d("MANIFEST_INVALID");for(let[r,s]of Object.entries(e))Ze(s,n,t+1,i&&t===0&&(r==="name"||r==="description"),o);}finally{n.delete(e);}}}function ee(e,n){let t=e[n];return typeof t!="string"&&d("MANIFEST_INVALID"),t}function Z(e,n,t){let i=e[n];return (!Number.isSafeInteger(i)||i<t)&&d("MANIFEST_INVALID"),i}function vn(e){return xo.test(e)||d("MANIFEST_INVALID"),e}function Le(e){return Co.test(e)||d("TOKEN_INVALID"),e}function sr(e){return Vt.test(e)||d("MANIFEST_INVALID"),e}function ar(e){V(e)||d("MANIFEST_INVALID");let n={};for(let[t,i]of Object.entries(e)){let o=sr(t);V(i)||d("MANIFEST_INVALID");let r=i.type;if(r==="text"){F(i,["type","maxLength"]),n[o]={type:r,maxLength:Z(i,"maxLength",1)};continue}if(r==="text-list"){F(i,["type","max","itemMaxLength"]),n[o]={type:r,max:Z(i,"max",0),itemMaxLength:Z(i,"itemMaxLength",1)};continue}if(r==="step-list"){F(i,["type","min","max","labelMaxLength","detailMaxLength"]);let s=Z(i,"min",0),a=Z(i,"max",1);s>a&&d("MANIFEST_INVALID"),n[o]={type:r,min:s,max:a,labelMaxLength:Z(i,"labelMaxLength",1),detailMaxLength:Z(i,"detailMaxLength",1)};continue}typeof r=="string"&&d("SCHEMA_TYPE_UNSUPPORTED"),d("MANIFEST_INVALID");}return n}function cr(e,n,t){let i=e[n];(!i||i.type!==t)&&d("MANIFEST_INVALID");}function Ye(e,n,t){let i=ee(e,"field");return Vt.test(i)||d("MANIFEST_INVALID"),cr(n,i,t),i}function pr(e,n){V(e)||d("MANIFEST_INVALID");let t=e.primitive;switch(typeof t!="string"&&d("MANIFEST_INVALID"),rr.includes(t)||d("PRIMITIVE_UNKNOWN"),t){case "card-shell":return F(e,["primitive"]),{primitive:t};case "meta-banner":return F(e,["primitive","badgeToken","noticeToken"]),{primitive:t,badgeToken:Le(ee(e,"badgeToken")),noticeToken:Le(ee(e,"noticeToken"))};case "heading":return F(e,["primitive","field"]),{primitive:t,field:Ye(e,n,"text")};case "labeled-text":return F(e,["primitive","titleToken","field","variant"]),e.variant!=="callout"&&d("MANIFEST_INVALID"),{primitive:t,titleToken:Le(ee(e,"titleToken")),field:Ye(e,n,"text"),variant:"callout"};case "step-flow":return F(e,["primitive","titleToken","field"]),{primitive:t,titleToken:Le(ee(e,"titleToken")),field:Ye(e,n,"step-list")};case "text-list":{F(e,["primitive","titleToken","field"],["emptyToken","hideWhenEmpty"]);let i={primitive:t,titleToken:Le(ee(e,"titleToken")),field:Ye(e,n,"text-list")};return L(e,"emptyToken")&&(i.emptyToken=Le(ee(e,"emptyToken"))),L(e,"hideWhenEmpty")&&(typeof e.hideWhenEmpty!="boolean"&&d("MANIFEST_INVALID"),i.hideWhenEmpty=e.hideWhenEmpty),i}}return d("MANIFEST_INVALID")}function dr(e,n){return Array.isArray(e)||d("MANIFEST_INVALID"),e.map(t=>pr(t,n))}function B(e="v2 manifest exceeds a contract limit"){return d("LIMIT_EXCEEDED",e)}function q(e="initial state is not projection-safe"){return d("INITIAL_STATE_INVALID",e)}function Rt(e,n){return (typeof e!="string"||e.length===0||e.length>4096||e.trim().length===0||tr.test(e)||ir.test(e))&&d("MANIFEST_INVALID",`${n} is invalid`),(en(e,true,true)||Bo.test(e)||Ho.test(e)||zo.test(e))&&d("UNSAFE_VALUE",`${n} contains an unsafe value`),e}function jn(e,n){return (typeof e!="string"||!re.test(e))&&d("MANIFEST_INVALID",`${n} is invalid`),e}function lr(e){return (typeof e!="string"||!Ln.test(e)||e==="*"||e==="all")&&d("MANIFEST_INVALID","action capability is invalid"),e}function Ft(e){return (typeof e!="string"||!nr.test(e))&&d("MANIFEST_INVALID","resource hash is invalid"),e}function Vn(e,n=new Set,t=0){if(typeof e=="string"){e.length>4096&&B("v2 manifest string is too long");return}if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){Number.isFinite(e)||d("MANIFEST_INVALID","v2 manifest contains a non-finite number");return}(e===void 0||typeof e=="function"||typeof e=="bigint")&&d("MANIFEST_INVALID","v2 manifest contains a non-JSON value"),typeof e!="object"&&d("MANIFEST_INVALID"),t>8&&B("v2 manifest nesting is too deep"),n.has(e)&&d("MANIFEST_INVALID","v2 manifest contains a cycle"),n.add(e);try{if(Array.isArray(e)){e.length>128&&B("v2 manifest array is too long");for(let i of e)Vn(i,n,t+1);return}V(e)||d("MANIFEST_INVALID","v2 manifest contains a non-plain object");for(let i of Object.values(e))Vn(i,n,t+1);}finally{n.delete(e);}}}function Bt(e){return (typeof e!="string"||e.length>4096||!ve.test(e))&&(typeof e=="string"&&e.length>4096&&B("projection path is too long"),d("MANIFEST_INVALID","projection paths must be canonical exact paths")),e.split(".").some(t=>Se(t))&&d("MANIFEST_INVALID","projection paths cannot address reserved state keys"),e}function Fn(e){V(e)||d("MANIFEST_INVALID","projection policy must be an object"),F(e,["allow"]),Array.isArray(e.allow)||d("MANIFEST_INVALID","projection allow must be an array"),e.allow.length>128&&B("projection allowlist is too long");let n=[],t=new Set;for(let i of e.allow){let o=Bt(i);t.has(o)&&d("MANIFEST_INVALID","projection allowlist contains a duplicate path"),t.add(o),n.push(o);}return {allow:n}}function ur(e,n){if(e===void 0)return;Array.isArray(e)||d("MANIFEST_INVALID","dataPaths must be an array"),e.length>or&&B("dataPaths exceed the v2 limit");let t=[],i=new Set;for(let o of e){let r=Bt(o);i.has(r)&&d("MANIFEST_INVALID","dataPaths contain a duplicate path"),n.some(s=>be(r,s))||d("MANIFEST_INVALID","dataPaths must be projection-allowed"),i.add(r),t.push(r);}return t}function Oe(e,n,t=Number.MAX_SAFE_INTEGER){return (!Number.isSafeInteger(e)||e<0||e>t)&&d("MANIFEST_INVALID",`${n} is invalid`),e}function Ut(e,n){return (typeof e!="number"||!Number.isFinite(e))&&d("MANIFEST_INVALID",`${n} is invalid`),e}function Bn(e,n=0,t=new Set){if(typeof e=="string")return (e.length>4096||en(e))&&d("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)||d("MANIFEST_INVALID","schema enum contains a non-finite number"),e;(n>8||typeof e!="object"||e===void 0)&&B("schema enum is too deep"),t.has(e)&&d("MANIFEST_INVALID","schema enum contains a cycle"),t.add(e);try{if(Array.isArray(e))return e.length>128&&B("schema enum array is too long"),e.map(o=>Bn(o,n+1,t));V(e)||d("MANIFEST_INVALID","schema enum contains a non-plain object");let i={};for(let[o,r]of Object.entries(e))Se(o)&&d("MANIFEST_INVALID","schema enum contains a reserved key"),i[o]=Bn(r,n+1,t);return i}finally{t.delete(e);}}function fr(e,n){if(e===void 0)return;Array.isArray(e)||d("MANIFEST_INVALID","schema required must be an array"),e.length>64&&B("schema required list is too long");let t=[],i=new Set;for(let o of e)(typeof o!="string"||!ve.test(o))&&d("MANIFEST_INVALID","schema required contains an invalid key"),o.length>4096&&B("schema required key is too long"),i.has(o)&&d("MANIFEST_INVALID","schema required contains a duplicate key"),n&&!Object.prototype.hasOwnProperty.call(n,o)&&d("MANIFEST_INVALID","schema required references an undeclared property"),i.add(o),t.push(o);return t}function yr(e,n){let t=n?ve:Ke;return e.length>4096&&B("schema property name is too long"),(!t.test(e)||e.split(".").some(i=>Se(i)))&&d("MANIFEST_INVALID","schema property name is invalid"),e}function Hn(e,n=0,t=false){V(e)||d("MANIFEST_INVALID","action inputSchema must be an object"),n>8&&B("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"&&d("SCHEMA_TYPE_UNSUPPORTED","action inputSchema type is unsupported"),d("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"),F(e,["type"],o.filter(a=>a!=="type"));let r={type:i};if(L(e,"enum")&&(Array.isArray(e.enum)||d("MANIFEST_INVALID","schema enum must be an array"),e.enum.length>128&&B("schema enum is too long"),r.enum=e.enum.map(a=>Bn(a))),i==="string"&&(L(e,"minLength")&&(r.minLength=Oe(e.minLength,"schema minLength",4096)),L(e,"maxLength")&&(r.maxLength=Oe(e.maxLength,"schema maxLength",4096)),r.minLength!==void 0&&r.maxLength!==void 0&&r.minLength>r.maxLength&&d("MANIFEST_INVALID","schema string length bounds are inverted")),(i==="number"||i==="integer")&&(L(e,"minimum")&&(r.minimum=Ut(e.minimum,"schema minimum")),L(e,"maximum")&&(r.maximum=Ut(e.maximum,"schema maximum")),r.minimum!==void 0&&r.maximum!==void 0&&r.minimum>r.maximum&&d("MANIFEST_INVALID","schema numeric bounds are inverted")),i==="array"&&(L(e,"minItems")&&(r.minItems=Oe(e.minItems,"schema minItems",128)),L(e,"maxItems")&&(r.maxItems=Oe(e.maxItems,"schema maxItems",128)),r.minItems!==void 0&&r.maxItems!==void 0&&r.minItems>r.maxItems&&d("MANIFEST_INVALID","schema array length bounds are inverted"),L(e,"items")&&(r.items=Hn(e.items,n+1,false))),i==="object"){let a;if(L(e,"properties")){V(e.properties)||d("MANIFEST_INVALID","schema properties must be an object");let c=Object.entries(e.properties);c.length>64&&B("schema properties are too many"),a={};for(let[l,f]of c){let I=yr(l,t);a[I]=Hn(f,n+1,false);}r.properties=a;}L(e,"minProperties")&&(r.minProperties=Oe(e.minProperties,"schema minProperties",64)),L(e,"maxProperties")&&(r.maxProperties=Oe(e.maxProperties,"schema maxProperties",64)),r.minProperties!==void 0&&r.maxProperties!==void 0&&r.minProperties>r.maxProperties&&d("MANIFEST_INVALID","schema object property bounds are inverted");let p=fr(e.required,a);p!==void 0&&(r.required=p),L(e,"additionalProperties")&&(e.additionalProperties!==false&&d("MANIFEST_INVALID","schema additionalProperties must be false"),r.additionalProperties=false);}let s=JSON.stringify(r);return (s===void 0||Buffer.byteLength(s,"utf8")>65536)&&B("action inputSchema subtree is too large"),r}function Ar(e){let n=Hn(e,0,true);return (n.type!=="object"||!n.properties)&&d("MANIFEST_INVALID","action inputSchema must declare object properties"),n}function Ir(e){if(V(e)||d("MANIFEST_INVALID","action backend must be an object"),e.type==="core"){F(e,Yo);let n=e.handler;return (typeof n!="string"||!On.test(n))&&d("MANIFEST_INVALID","core backend handler is invalid"),{type:"core",handler:n}}if(e.type==="skill"){F(e,qo,Zo),(!Array.isArray(e.command)||e.command.length===0||e.command.length>16)&&d("MANIFEST_INVALID","skill backend command is invalid");let n=[];for(let i of e.command)(typeof i!="string"||i.length===0||i.length>256||!Rn.test(i))&&d("MANIFEST_INVALID","skill backend command token is invalid"),n.push(i);let t=L(e,"env")?mr(e.env):void 0;return {type:"skill",command:n,...t===void 0?{}:{env:t}}}d("MANIFEST_INVALID","action backend type is unsupported");}function gr(e){V(e)||d("MANIFEST_INVALID","action must be an object"),F(e,Wo,Ko),L(e,"_meta")&&Ht(e._meta);let n=jn(e.actionId,"actionId"),t=lr(e.capability),i=e.mutation;typeof i!="boolean"&&d("MANIFEST_INVALID","action mutation must be boolean");let o=Ar(e.inputSchema),r;if(L(e,"dataInputs")){Array.isArray(e.dataInputs)||d("MANIFEST_INVALID","action dataInputs must be an array");let l=o.properties,f=new Set,I=[];for(let g of e.dataInputs)(typeof g!="string"||!L(l,g)||f.has(g))&&d("MANIFEST_INVALID","action dataInputs must be unique declared properties"),f.add(g),I.push(g);r=I;}let s=Fn(e.resultProjection),a=Ir(e.backend),p;L(e,"content")&&((a.type!=="skill"||!Xe(e.content))&&d("MANIFEST_INVALID","action content declaration is invalid"),p=hr(e.content));let c;if(L(e,"confirmation")){let l=e.confirmation;l!=="none"&&l!=="native"&&d("MANIFEST_INVALID","action confirmation is invalid"),c=l;}return {actionId:n,capability:t,mutation:i,inputSchema:o,resultProjection:s,backend:a,...p===void 0?{}:{content:p},...r===void 0?{}:{dataInputs:r},...c===void 0?{}:{confirmation:c}}}function mr(e){(!Array.isArray(e)||e.length===0)&&d("MANIFEST_INVALID","skill backend env is invalid");let n=new Set,t=[];for(let i of e)(i!=="CREWX_APP_INSTANCE_ID"&&i!=="CREWX_THREAD_ID"||n.has(i))&&d("MANIFEST_INVALID","skill backend env is invalid"),n.add(i),t.push(i);return Object.freeze(t)}function hr(e){return Object.freeze({...e.in===void 0?{}:{in:Object.freeze({...e.in})},...e.out===void 0?{}:{out:Object.freeze({...e.out})}})}function Er(e){return V(e)||d("INITIAL_STATE_INVALID","initialState must be an object"),F(e,Qo,er),e.path!=="ui/state.json"&&d("MANIFEST_INVALID","initialState path is not fixed"),L(e,"hash")?{path:"ui/state.json",hash:Ft(e.hash)}:{path:"ui/state.json"}}function _r(e){return (!V(e)||Object.keys(e).length!==1||!L(e,"wasm")||e.wasm!==true)&&d("MANIFEST_INVALID",'runtime must be exactly { "wasm": true }'),{wasm:true}}function Tr(e,n){Ze(e,new Set,0,true,true),Vn(e),V(e)||d("MANIFEST_INVALID"),F(e,$o,Jo),L(e,"_meta")&&Ht(e._meta),e.manifestVersion!==2&&d("MANIFEST_INVALID");let t;L(e,"runtime")&&(t=_r(e.runtime));let i=jn(e.pluginId,"pluginId"),o=jn(e.definitionId,"definitionId"),r=Z(e,"version",1),s=Rt(e.name,"name"),a=Rt(e.description,"description"),p;L(e,"icon")&&((typeof e.icon!="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(e.icon))&&d("MANIFEST_INVALID","icon is invalid"),p=e.icon);let c;L(e,"tone")&&((typeof e.tone!="string"||!Un.includes(e.tone))&&d("MANIFEST_INVALID","tone is invalid"),c=e.tone),e.entry!=="ui/index.html"&&d("MANIFEST_INVALID","entry path is not fixed");let l;L(e,"entryHash")&&(l=Ft(e.entryHash));let f;L(e,"initialState")&&(f=Er(e.initialState));let I;L(e,"usage")&&(e.usage!=="card"&&e.usage!=="window"&&d("MANIFEST_INVALID","usage is invalid"),I=e.usage);let g;L(e,"detailPanel")&&(typeof e.detailPanel!="boolean"&&d("MANIFEST_INVALID","detailPanel is invalid"),g=e.detailPanel);let m;if(L(e,"displayModes")){((I??Ie)!==Ie||!Array.isArray(e.displayModes)||e.displayModes.length===0)&&d("MANIFEST_INVALID","displayModes are only valid for window Apps");let U=new Set(["inline","floating","focused"]);(new Set(e.displayModes).size!==e.displayModes.length||e.displayModes.some(u=>typeof u!="string"||!U.has(u)))&&d("MANIFEST_INVALID","displayModes are invalid"),m=e.displayModes;}(I??Ie)===Ie&&g!==void 0&&d("MANIFEST_INVALID","detailPanel is card-only");let P=n.mode??"local";P!=="local"&&P!=="installed"&&P!=="published"&&d("MANIFEST_INVALID","manifest mode is invalid"),P!=="local"&&l===void 0&&d("MANIFEST_INVALID","installed manifests require entryHash"),P!=="local"&&f!==void 0&&f.hash===void 0&&d("MANIFEST_INVALID","installed manifests require initialState.hash"),(!Array.isArray(e.surfaces)||e.surfaces.length===0)&&d("MANIFEST_INVALID","surfaces are invalid"),e.surfaces.length>2&&B("surfaces exceed the v2 limit");let w=[],v=new Set;for(let U of e.surfaces)(typeof U!="string"||!wn.includes(U))&&d("MANIFEST_INVALID","surface is unsupported"),v.has(U)&&d("MANIFEST_INVALID","surfaces contain a duplicate"),v.add(U),w.push(U);V(e.size)||d("MANIFEST_INVALID","size must be an object"),F(e.size,["height"]);let T=Z(e.size,"height",1);T>720&&B("size.height exceeds the v2 limit");let b=Fn(e.stateProjection),C=e.summaryProjection===void 0?void 0:Fn(e.summaryProjection);C!==void 0&&C.allow.some(U=>!b.allow.includes(U))&&d("MANIFEST_INVALID","summaryProjection must be a subset of stateProjection.allow");let A=ur(e.dataPaths,b.allow);Array.isArray(e.actions)||d("MANIFEST_INVALID","actions must be an array"),e.actions.length>32&&B("actions exceed the v2 limit");let _=[],O=new Set;for(let U of e.actions){let u=gr(U);if(O.has(u.actionId)&&d("MANIFEST_INVALID","actions contain a duplicate actionId"),u.backend.type==="core"&&u.backend.handler==="state.set"){u.mutation||d("MANIFEST_INVALID","state.set actions must be mutations");for(let k of Object.keys(u.inputSchema.properties))b.allow.includes(k)||d("MANIFEST_INVALID","state.set input paths must be projection-allowed");}O.add(u.actionId),_.push(u);}return {manifestVersion:2,pluginId:i,definitionId:o,version:r,name:s,description:a,...p===void 0?{}:{icon:p},...c===void 0?{}:{tone:c},entry:"ui/index.html",...l===void 0?{}:{entryHash:l},...t===void 0?{}:{runtime:t},...f===void 0?{}:{initialState:f},...I===void 0?{}:{usage:I},...g===void 0?{}:{detailPanel:g},...m===void 0?{}:{displayModes:m},surfaces:w,size:{height:T},stateProjection:b,...C===void 0?{}:{summaryProjection:C},...A===void 0?{}:{dataPaths:A},actions:_}}function Ht(e){V(e)||d("MANIFEST_INVALID","_meta must be an object");let n=JSON.stringify(e);(n===void 0||Buffer.byteLength(n,"utf8")>Xo)&&B("_meta exceeds the 4 KiB limit");}function Dr(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 zn(e,n,t,i,o,r){if(typeof e=="string"){let s=o.length>0&&r.some(a=>be(o.join("."),a));return (e.length>4096||en(e,false,false,s))&&q("state contains an unsafe string"),e}if(e===null||typeof e=="boolean")return e;if(typeof e=="number")return Number.isFinite(e)||q("state contains a non-finite number"),e;(e===void 0||typeof e!="object"||typeof e=="function"||typeof e=="bigint")&&q("state contains a non-JSON value"),t>8&&q("state is too deep"),n.has(e)&&q("state contains a cycle"),n.add(e);try{let s;if(Array.isArray(e))e.length>128&&q("state array is too long"),s=e.map(p=>zn(p,n,t+1,65536,o,r));else {V(e)||q("state contains a non-plain object");let p={};for(let[c,l]of Object.entries(e))(c.length>4096||!Ke.test(c)||Se(c))&&(c.length>4096&&q("state key is too long"),q("state contains a reserved or invalid key")),p[c]=zn(l,n,t+1,65536,[...o,c],r);s=p;}let a=JSON.stringify(s);return (a===void 0||Buffer.byteLength(a,"utf8")>i)&&q("state subtree is too large"),s}finally{n.delete(e);}}function $n(e,n=[]){V(e)||q("initial state must be a JSON object");let t=zn(e,new Set,0,65536,[],n);return (t===null||Array.isArray(t)||typeof t!="object")&&q(),t}function Pr(e,n={}){Ze(e),V(e)||d("MANIFEST_INVALID"),F(e,Go),e.manifestVersion!==1&&d("MANIFEST_INVALID");let t=vn(ee(e,"pluginId")),i=vn(ee(e,"definitionId")),o=Z(e,"version",1),r=Z(e,"primitiveSet",1),s=n.supportedPrimitiveSet??ko;(!Number.isSafeInteger(s)||s<1)&&d("MANIFEST_INVALID"),r>s&&d("PRIMITIVE_SET_UNSUPPORTED"),V(e.activation)||d("MANIFEST_INVALID"),F(e.activation,["kind","language"]),e.activation.kind!=="fenced-code"&&d("MANIFEST_INVALID");let a=vn(ee(e.activation,"language")),p=ar(e.schema),c=dr(e.layout,p);return {manifestVersion:1,pluginId:t,definitionId:i,version:o,primitiveSet:r,activation:{kind:"fenced-code",language:a},schema:p,layout:c}}function br(e,n={}){return V(e)||d("MANIFEST_INVALID"),Object.hasOwn(e,"lineage")&&d("MANIFEST_INVALID","lineage is only allowed in product bundle indexes"),e.manifestVersion===2?Tr(e,n):Pr(e,n)}function Ee(e,n={}){try{return br(e,n)}catch(t){if(t instanceof K)throw t;return d("MANIFEST_INVALID")}}function Jn(e,n={}){let t=Ee(e,n);return t.manifestVersion===2?Dr(t):t}var ko,Co,xo,Vt,vo,jo,Vo,Fo,Ot,Bo,Ho,zo,Go,$o,Jo,Wo,Ko,Xo,Yo,qo,Zo,Qo,er,nr,tr,ir,or,rr,K,zt=j(()=>{y();Mn();Ae();xn();Me();ko=1,Co=/^[a-z][a-zA-Z0-9]*(\.[a-zA-Z0-9]+)+$/,xo=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,Vt=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,vo=/<\/?[A-Za-z][^>]*>/,jo=/^(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)/,Vo=/^(?:https?|file|ftp|ws|wss):\/\//i,Fo=/^\s*(?:javascript|data):/i,Ot=/data:[^,\s]*,/i,Bo=/(?:https?|file|ftp|ws|wss):\/\//i,Ho=/javascript:/i,zo=/(?:^[\s]*|[\s"'(=])(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)(?=[^\s"'<>])[^\s"'<>]*/,Go=["manifestVersion","pluginId","definitionId","version","primitiveSet","activation","schema","layout"],$o=["manifestVersion","pluginId","definitionId","version","name","description","entry","surfaces","size","stateProjection","actions"],Jo=["_meta","icon","tone","entryHash","runtime","initialState","usage","detailPanel","displayModes","summaryProjection","dataPaths","focusedAiDataPaths"],Wo=["actionId","capability","mutation","inputSchema","resultProjection","backend"],Ko=["confirmation","dataInputs","content","_meta"],Xo=4*1024,Yo=["type","handler"],qo=["type","command"],Zo=["env"],Qo=["path"],er=["hash"],nr=/^[0-9a-f]{64}$/,tr=/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/,ir=/[\r\n]/,or=16,rr=["card-shell","meta-banner","heading","labeled-text","step-flow","text-list"],K=class extends Error{constructor(t,i=t){super(i);this.code=t;}code;name="UiPluginValidationError"};});var Wn=j(()=>{y();Nt();zt();Me();});function se(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=oe(t);return createHash("sha256").update(Y(i)).digest("hex")}function ae(e){if(!/^\d+$/.test(String(e.version))||e.version<1||e.id.length<1||e.id.length>128)throw new N("DEFINITION_UNSUPPORTED","UI definition is invalid");if(e.sourceHash!==void 0&&(typeof e.sourceHash!="string"||!kr.test(e.sourceHash)))throw new N("DEFINITION_UNSUPPORTED","UI definition source hash is invalid");if(!/^[0-9a-f]{64}$/.test(e.hash)||se(e)!==e.hash)throw new N("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=>!xr(i)))throw new N("DEFINITION_UNSUPPORTED","UI action declaration is invalid");if(t.confirmation!==void 0&&t.confirmation!=="none"&&t.confirmation!=="native")throw new N("DEFINITION_UNSUPPORTED","UI action confirmation is invalid");if(t.inputKeys&&(!Array.isArray(t.inputKeys)||t.inputKeys.some(i=>typeof i!="string"||!i)))throw new N("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 N("DEFINITION_UNSUPPORTED","UI action data input declaration is invalid");if(t.resultProjection&&Xn(t.resultProjection),t.content!==void 0&&!Xe(t.content))throw new N("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 N("DEFINITION_UNSUPPORTED","UI action environment declaration is invalid")}if(e.renderer!==void 0&&(!e.renderer||e.renderer.length>128))throw new N("DEFINITION_UNSUPPORTED","UI definition renderer is invalid");if(e.surfaces&&(!Array.isArray(e.surfaces)||e.surfaces.some(n=>!n||n.length>64)))throw new N("DEFINITION_UNSUPPORTED","UI definition surfaces are invalid");if(e.usage!==void 0&&e.usage!=="card"&&e.usage!=="window")throw new N("DEFINITION_UNSUPPORTED","UI definition usage is invalid");if(e.detailPanel!==void 0&&typeof e.detailPanel!="boolean")throw new N("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 N("DEFINITION_UNSUPPORTED","UI definition displayModes are invalid");if(e.usage==="card"&&e.displayModes!==void 0)throw new N("DEFINITION_UNSUPPORTED","Card definitions cannot declare displayModes");if(e.usage==="window"&&e.detailPanel!==void 0)throw new N("DEFINITION_UNSUPPORTED","Window definitions cannot declare detailPanel");if(e.stateProjection&&Xn(e.stateProjection),e.summaryProjection){Xn(e.summaryProjection);let n=new Set(e.stateProjection?.allow??[]);if(e.summaryProjection.allow.some(t=>!n.has(t)))throw new N("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 N("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(Cr(r,o==="readTool"),n.has(r.name))throw new N("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 N("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 N("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 N("DEFINITION_UNSUPPORTED","UI legacy agent access is invalid");if(e.legacy.actionTool!==void 0&&(!i||Object.keys(i).length===0))throw new N("DEFINITION_UNSUPPORTED","UI legacy action tool requires its complete agent access map")}if(e.dataPaths!==void 0){let n=new Set(["__proto__","prototype","constructor"]);if(!Array.isArray(e.dataPaths)||e.dataPaths.length>16||new Set(e.dataPaths).size!==e.dataPaths.length||e.dataPaths.some(t=>typeof t!="string"||!/^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)*$/.test(t)||t.split(".").some(i=>n.has(i))||!(e.stateProjection?.allow??[]).some(i=>be(t,i))))throw new N("DEFINITION_UNSUPPORTED","UI definition dataPaths are invalid")}}function Cr(e,n){if(!e||typeof e!="object"||Array.isArray(e))throw new N("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 N("DEFINITION_UNSUPPORTED","UI legacy tool metadata is invalid");try{let r=oe(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 p=oe(a.structuredContent);if(Nn(Ne(p))>4*1024)throw new Error("fixed result size")}}catch{throw new N("DEFINITION_UNSUPPORTED","UI legacy tool metadata is not projection-safe")}}function Xn(e){if(!Array.isArray(e.allow)||e.allow.some(n=>!/^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)*$/.test(n)))throw new N("DEFINITION_UNSUPPORTED","UI projection policy is invalid")}function xr(e){return e.length>0&&e.length<=128&&e!=="*"&&e!=="all"&&!/[/*]/.test(e)}var kr,we=j(()=>{y();Ae();Dn();xn();kr=/^[0-9a-f]{64}$/;});function on(e,n=e){throw new ce(e,n)}var ce,rn=j(()=>{y();ce=class extends Error{constructor(t,i=t){super(i);this.code=t;}code;name="McpAppContractError"};});var Zt=j(()=>{y();});var Qt=j(()=>{y();we();Ae();rn();Zt();});function ei(e,n){return vr.add(e),n!==void 0&&jr.set(e,n),e}var vr,jr,sn=j(()=>{y();vr=new WeakSet,jr=new WeakMap;});function Fe(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Yn(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 ii(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let n of Object.values(e))ii(n);return Object.freeze(e)}function $(e){throw new ne("LINEAGE_INVALID",e)}function $r(e){throw new ne("LINEAGE_STALE",e)}function oi(e){if(!Fe(e)||!Yn(e,Br,Hr)||!Fe(e.actions))return $("Lineage definition shape is invalid");for(let n of Object.values(e.actions))if(!Fe(n)||!Yn(n,zr,Gr))return $("Lineage action definition shape is invalid");return e}function Jr(e){if(!Fe(e)||!Yn(e,Vr,Fr))return $("Lineage entry shape is invalid");if(!Number.isSafeInteger(e.version)||e.version<1||typeof e.hash!="string"||!ni.test(e.hash))return $("Lineage entry identity is invalid");if(e.sourceHash!==void 0&&(typeof e.sourceHash!="string"||!ni.test(e.sourceHash)))return $("Lineage source hash is invalid");if(e.compat!==void 0&&e.compat!=="break")return $("Lineage compatibility marker is invalid");let n=oi(e.definition);if(n.version!==e.version)return $("Lineage version does not match its definition");if(e.sourceHash!==void 0&&n.sourceHash!==e.sourceHash)return $("Lineage source hash does not match its definition");let t;try{t=se(n),ae({...n,hash:e.hash});}catch{return $("Lineage definition is invalid")}return t!==e.hash?$("Lineage definition hash does not match"):ii({version:e.version,hash:e.hash,definition:n,...e.sourceHash===void 0?{}:{sourceHash:e.sourceHash},...e.compat===void 0?{}:{compat:e.compat}})}function ti(e){return e.stateProjection?.allow??[]}function Wr(e,n){let t=[],i=new Set(ti(n));ti(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,p]of Object.entries(e.actions)){let c=n.actions[a];if(c&&(p.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(p=>!a.has(p))&&t.push("S5_SUMMARY_PROJECTION");}return t}function Kr(e,n){return Y(e)===Y(n)}function qn(e,n){if(!Array.isArray(e)||e.length===0)return $("Definition lineage is missing");if(!Fe(n)||typeof n.hash!="string")return $("Current definition is invalid");let t,i;try{let{hash:a,...p}=n;i=oi(p),t={...i,hash:a},ae(t);}catch{return $("Current definition is invalid")}let o=e.map(Jr),r=o[0].definition.id;if(o.some(a=>a.definition.id!==r))return $("Lineage definition ids do not match");if(o.some((a,p)=>p>0&&a.version<=o[p-1].version))return $("Lineage generations are not in increasing version order");if(o.some((a,p)=>o.findIndex(c=>c.hash===a.hash)!==p))return $("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||!Kr(s.definition,i))return $r("The last lineage generation does not match the current package");if(t.legacy!==void 0){let a=new Set(Object.keys(t.actions)),p=new Set;for(let l of o)if(l.sourceHash===void 0)for(let f of Object.keys(l.definition.actions))a.has(f)&&p.add(f);let c=Object.keys(t.legacy.agentAccess??{});if(c.length!==p.size||c.some(l=>!p.has(l))){let l="S4_LEGACY_AGENT_ACCESS_COMPLETE";throw new ne("LINEAGE_INVALID",`Lineage compatibility failed: ${l}`,[l])}}for(let a=0;a<o.length-1;a+=1){if(o.slice(a,-1).some(l=>l.compat==="break"))continue;let c=Wr(o[a].definition,t);if(c.length>0)throw new ne("LINEAGE_INVALID",`Lineage compatibility failed: ${c.join(", ")}`,c)}return Object.freeze({entries:Object.freeze(o),current:t})}var ne,ni,Vr,Fr,Br,Hr,zr,Gr,Zn=j(()=>{y();we();Ae();ne=class extends Error{constructor(t,i=t,o=[]){super(i);this.code=t;this.violations=o;}code;violations;name="UiDefinitionLineageError"},ni=/^[0-9a-f]{64}$/,Vr=["version","hash","definition"],Fr=["sourceHash","compat"],Br=["id","version","actions"],Hr=["sourceHash","usage","detailPanel","displayModes","renderer","surfaces","stateProjection","dataPaths","summaryProjection","legacy"],zr=["capabilities"],Gr=["inputKeys","dataInputs","confirmation","resultProjection","content","env"];});var ri,si,ai=j(()=>{y();ri=["crewx_app_terminal_connect","crewx_app_html_viewer_open"],si=["crewx_listWorkspaces","crewx_queryAgent","crewx_executeAgent","crewx_getTaskResult","crewx_listTasks","crewx_listAgents","callBrowser","openTab","listTabs","closeTab"];});var ci=j(()=>{y();we();sn();});function Qn(e,n=0){try{let t=oe(e,n);return t.type!==void 0&&t.type!=="object"&&on("TOOL_INVALID","MCP App inputSchema must describe an object"),t}catch(t){if(t instanceof ce)throw t;on("TOOL_INVALID","MCP App inputSchema must be projection-safe JSON");}}function pi(e){if(e.length===0)return Qn({type:"object",properties:{},additionalProperties:false});let n=e.map(i=>i.actionId),t=new Map;for(let i of e)t.set(i.actionId,Qn(i.inputSchema));return Qn(qr(n,t),Yr)}function qr(e,n){let t=e.map(i=>({type:"object",properties:{actionId:{type:"string",const:i},input:n.get(i)??{type:"object"}},required:["actionId","input"],additionalProperties:false}));return Object.freeze({type:"object",oneOf:Object.freeze(t),properties:Object.freeze({actionId:Object.freeze({type:"string",enum:Object.freeze([...e])}),input:Object.freeze({type:"object"})}),required:Object.freeze(["actionId","input"]),additionalProperties:false})}var Be,Yr,et=j(()=>{y();Qt();we();Ae();sn();rn();Zn();ai();ci();Be=8*1024*1024,new Set(ri),new Set(si),Yr=4;});function pe(e){let n=typeof e=="object"&&e!==null&&"code"in e?String(e.code):"";return n==="ENOENT"?new D("NOT_FOUND"):n==="ELOOP"?new D("PATH_ESCAPED"):n==="EFBIG"||n==="EOVERFLOW"?new D("LIMIT_EXCEEDED"):n==="EACCES"||n==="EPERM"||n==="ENOTDIR"?new D("READ_DENIED"):new D("READ_DENIED")}function is(e){if(typeof e!="string"||e.length===0||!isAbsolute(e))throw new D("READ_DENIED")}function di(e){if(typeof e!="string"||isAbsolute(e)||/[\\\u0000]/.test(e))throw new D("PATH_ESCAPED");if(e==="")return [];let n=e.split("/");if(n.some(t=>t.length===0||t==="."||t===".."))throw new D("PATH_ESCAPED");return n}function an(e,n){let t=relative(e,n);return t===""||t!==".."&&!t.startsWith(`..${sep}`)&&!isAbsolute(t)}function cn(e){return {dev:e.dev,ino:e.ino,size:e.size,mtimeNs:e.mtimeNs,ctimeNs:e.ctimeNs}}function it(e,n){return e.dev===n.dev&&e.ino===n.ino}function Ii(e,n){return it(e,n)&&e.size===n.size&&e.mtimeNs===n.mtimeNs&&e.ctimeNs===n.ctimeNs}async function li(e){is(e);let n,t;try{n=await realpath(e),t=await stat(n,{bigint:!0});}catch(i){throw pe(i)}if(!t.isDirectory())throw new D("READ_DENIED");return {realRoot:n,identity:cn(t)}}async function os(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 D("READ_DENIED")}catch(r){throw r instanceof D?r:pe(r)}if(!an(n,o))throw new D("PATH_ESCAPED");return o}async function ui(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 pe(a)}if(!an(n,r)||t!==void 0&&!an(t,r))throw new D("PATH_ESCAPED");if(!o.isFile()||!s.isFile())throw new D("READ_DENIED");if(!it(i,o)||!it(i,s)||i.dev!==s.dev)throw new D("PATH_ESCAPED")}async function nt(e,n){let t,i;try{t=await realpath(e),i=await stat(t,{bigint:!0});}catch{throw new D("PATH_ESCAPED")}if(t!==n.realRoot||!Ii(n.identity,cn(i)))throw new D("PATH_ESCAPED")}function rs(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 D,Ai,ns,ts,pn,gi,rt=j(()=>{y();D=class extends Error{constructor(t){super(t);this.code=t;}code;name="AppDiscoveryFsError"},Ai=constants.O_NOFOLLOW,ns=constants.O_NONBLOCK,ts=constants.O_RDONLY|(Ai??0)|(ns??0);pn=class{async listDirectory(n,t){let i=di(t),o=await li(n),r=resolve(n,...i),s,a;try{s=await realpath(r),a=await stat(s,{bigint:!0});}catch(p){let c=pe(p);if(c.code==="NOT_FOUND")return [];throw c}if(!an(o.realRoot,s)||!a.isDirectory())throw new D("PATH_ESCAPED");try{let p=await readdir(s,{withFileTypes:!0,encoding:"utf8"});return await nt(n,o),p.map(rs)}catch(p){let c=pe(p);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 D("READ_DENIED");if(Ai===void 0)throw new D("UNSUPPORTED");let o=di(t),r=await li(n),s=resolve(n,...o),a=relative(n,s);if(a===".."||a.startsWith(`..${sep}`)||isAbsolute(a))throw new D("PATH_ESCAPED");let p;try{p=await open(s,ts);}catch(c){throw pe(c)}try{let c;try{let m=await p.stat({bigint:!0});c=cn(m);}catch(m){throw pe(m)}if(c.size>BigInt(i))throw new D("LIMIT_EXCEEDED");if(c.size>BigInt(Number.MAX_SAFE_INTEGER))throw new D("LIMIT_EXCEEDED");await nt(n,r);let l=await os(n,r.realRoot,o);await ui(s,r.realRoot,l,c);let f=new Uint8Array(new ArrayBuffer(Number(c.size))),I=0;for(;I<f.byteLength;){let m;try{m=(await p.read(f,I,f.byteLength-I,I)).bytesRead;}catch(P){throw pe(P)}if(m<=0)throw new D("IDENTITY_CHANGED");I+=m;}let g;try{let m=await p.stat({bigint:!0});g=cn(m);}catch(m){throw pe(m)}if(!Ii(c,g))throw new D("IDENTITY_CHANGED");return await ui(s,r.realRoot,l,g),await nt(n,r),new Uint8Array(f)}finally{await p.close().catch(()=>{});}}async readFileVerified(n,t,i){return this.readVerifiedFile(n,t,i)}},gi=new pn;});function Ge(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 hi(e){return typeof e=="string"&&re.test(e)?e:void 0}function us(e){return e.length>0&&e!=="."&&e!==".."&&!/[\\/\u0000]/.test(e)}function Te(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 fs(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 ys(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 As(e){return ds.decode(e)}function Is(e){return JSON.parse(As(e))}function Ei(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 gs(e){if(e instanceof D)return Ei(e.code);if(e!==null&&typeof e=="object"&&"code"in e){let n=e.code;if(typeof n=="string")return Ei(n)}}function de(e,n){let t=n();return Number.isFinite(t)&&Number.isFinite(e)&&t-e<=5e3}function ms(e){if(typeof e.readVerifiedFile=="function")return e.readVerifiedFile;if(typeof e.readFileVerified=="function")return e.readFileVerified}function hs(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 _i(e,n,t,i){let o=ms(e);if(!o)throw new D("READ_DENIED");return ys(await o.call(e,n,t,i))}async function ct(e,n,t){let i=hs(e);if(!i)throw new D("READ_DENIED");let o=await i.call(e,n,t);if(!Array.isArray(o))throw new D("READ_DENIED");return o.map(fs).filter(r=>r!==null)}function Es(e,n,t,i){return Object.freeze({code:e,...{},source:n,relativePath:t})}function _s(e){if(!Ge(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(Te))};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 Ts(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 un(e){return Object.freeze({appIds:Object.freeze([...new Set(e.map(n=>n.appId))].sort(Te)),definitionIds:Object.freeze([...new Set(e.map(n=>n.definition.id))].sort(Te))})}function ln(e,n){let t=Object.keys(e).sort(Te),i=[...n].sort(Te);return t.length===i.length&&t.every((o,r)=>o===i[r])}function Ti(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 Ds(e){let n;try{n=Is(e);}catch{return}if(!Ge(n)||!ln(n,["version","packages"])||n.version!==1||!Array.isArray(n.packages)||n.packages.length>pt)return;let t=new Set,i=new Set,o=0,r=[];for(let s of n.packages){if(!Ge(s))return;let a=["packageDir","appId","definition","files"],p=Object.hasOwn(s,"lineage"),c=Object.hasOwn(s,"launcher"),l=[...p?["lineage"]:[],...c?["launcher"]:[]];if(!ln(s,[...a,...l])||c&&s.launcher!==false)return;let f=Ti(s.packageDir),I=hi(s.appId);if(!f||f.length!==2||f[0]!=="apps"||!us(f[1])||!I||t.has(s.packageDir)||!Ge(s.definition)||!ln(s.definition,["id","version","hash"]))return;let g=hi(s.definition.id),m=s.definition.version,P=s.definition.hash;if(!g||!Number.isSafeInteger(m)||m<1||typeof P!="string"||!at.test(P)||!Array.isArray(s.files)||s.files.length<2||s.files.length>dt)return;let w=new Set,v=[];for(let T of s.files){if(!Ge(T)||!ln(T,["path","sha256"]))return;let b=Ti(T.path);if(!b||typeof T.sha256!="string"||!at.test(T.sha256))return;let C=b.join("/"),A=`${s.packageDir}/${C}`;if(w.has(C)||i.has(A))return;w.add(C),i.add(A),v.push(Object.freeze({path:C,sha256:T.sha256}));}if(!w.has("ui-plugin.json")||!w.has("ui/index.html")||(o+=v.length,o>as))return;t.add(s.packageDir),r.push(Object.freeze({packageDir:s.packageDir,...c?{launcher:false}:{},appId:I,definition:Object.freeze({id:g,version:m,hash:P}),lineage:Array.isArray(s.lineage)?s.lineage:[],files:Object.freeze(v.sort((T,b)=>Te(T.path,b.path)))}));}return Object.freeze({version:1,packages:Object.freeze(r)})}function _e(e){let n=gs(e);return n==="PATH_ESCAPED"||n==="IDENTITY_CHANGED"||n==="TOCTOU"?"PATH_ESCAPED":n==="LIMIT_EXCEEDED"?"LIMIT_EXCEEDED":"BUNDLE_INTEGRITY"}async function Ps(e,n,t,i,o){let r=[],s=async(a,p)=>{if(!de(i,o))throw new D("LIMIT_EXCEEDED");if(p>2)throw new D("LIMIT_EXCEEDED");let c=await ct(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 D("PATH_ESCAPED");let f=`${a}/${l.name}`;if(l.kind==="file"){if(r.push(f.slice(t.length+1)),r.length>dt)throw new D("LIMIT_EXCEEDED")}else if(l.kind==="directory")await s(f,p+1);else throw l.kind==="symlink"?new D("PATH_ESCAPED"):new D("READ_DENIED")}};return await s(t,0),r.sort(Te)}function bs(e){return e==="ui-plugin.json"?262144:e==="ui/index.html"?Be:e==="ui/state.json"?65536:e.startsWith("ui/assets/")?ps:cs}async function Di(e,n,t,i){if(e===void 0)return {packages:[],diagnostics:[],incomplete:false,reservedIds:ls};let o=_s(e.reservedIds),r=[],s=(u,k,H)=>Es(u,"bundled",k),a=(u=[],k=false,H)=>({...H===void 0?{}:{indexHash:H},packages:u,diagnostics:r,incomplete:k,reservedIds:o});if(typeof e.root!="string"||e.root.length===0||typeof e.expectedIndexHash!="string"||!at.test(e.expectedIndexHash))return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a();let p;try{p=await _i(n,e.root,"bundle-index.json",ss);}catch(u){return r.push(s(_e(u),"bundle-index.json")),a()}let c=createHash("sha256").update(p).digest("hex");if(c!==e.expectedIndexHash)return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a();let l=Ds(p);if(l===void 0)return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a();if(!Ts(un(l.packages),o))return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a([],false,c);if(!de(t,i))return r.push(s("LIMIT_EXCEEDED","bundle-index.json")),a(l.packages.map(u=>({indexEntry:u,failureCode:"LIMIT_EXCEEDED"})),true,c);let f;try{f=await ct(n,e.root,"");}catch(u){return r.push(s(_e(u),"bundle-index.json")),a(l.packages.map(k=>({indexEntry:k,failureCode:_e(u)})),false,c)}if(!de(t,i))return r.push(s("LIMIT_EXCEEDED","bundle-index.json")),a(l.packages.map(u=>({indexEntry:u,failureCode:"LIMIT_EXCEEDED"})),true,c);let I=f.find(u=>u.name==="bundle-index.json"&&u.kind==="file"),g=f.find(u=>u.name==="apps"&&u.kind==="directory"),m=u=>l.packages.map(k=>({indexEntry:k,failureCode:u}));if(!I)return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a(m("BUNDLE_INTEGRITY"),false,c);let P=f.filter(u=>u.name!=="bundle-index.json"&&u.name!=="apps");if(P.length>0){let u=P.some(k=>k.kind==="symlink")?"PATH_ESCAPED":"BUNDLE_INTEGRITY";return r.push(s(u,"bundle-index.json")),a(m("BUNDLE_INTEGRITY"),false,c)}if(f.some(u=>u.name==="apps"&&u.kind!=="directory"))return r.push(s("PATH_ESCAPED","apps")),a(m("PATH_ESCAPED"),false,c);let w=[];if(g)try{w=await ct(n,e.root,"apps");}catch(u){return r.push(s(_e(u),"apps")),a(m(_e(u)),false,c)}if(!de(t,i)||w.length>pt)return r.push(s("LIMIT_EXCEEDED","apps")),a(m("LIMIT_EXCEEDED"),true,c);let v=new Map(l.packages.map(u=>[u.packageDir.slice(5),u])),T=w.filter(u=>!v.has(u.name));for(let u of T)r.push(s(u.kind==="symlink"?"PATH_ESCAPED":"BUNDLE_INTEGRITY",`apps/${u.name}`));if(T.length>0){let u=T.some(k=>k.kind==="symlink")?"PATH_ESCAPED":"BUNDLE_INTEGRITY";return a(m(u),false,c)}let b=new Set,C=new Map,A=new Map;for(let u of l.packages){let k=C.get(u.appId)??[];k.push(u),C.set(u.appId,k);let H=`${u.definition.id}\0${String(u.definition.version)}`,E=A.get(H)??[];E.push(u),A.set(H,E);}for(let u of [...C.values(),...A.values()])if(u.length>1)for(let k of u)b.add(k);let _=[],O=p.byteLength,U=false;for(let u of l.packages){if(!de(t,i)){U=true,_.push({indexEntry:u,failureCode:"LIMIT_EXCEEDED"});continue}let k;try{let x=u.lineage[u.lineage.length-1];if(!x)throw new ne("LINEAGE_INVALID","Definition lineage is missing");if(x.definition.id!==u.definition.id||x.version!==u.definition.version||x.hash!==u.definition.hash)throw new ne("LINEAGE_STALE","Last lineage generation does not match bundle identity");k=qn(u.lineage,{...x.definition,hash:x.hash}).entries;}catch(x){let te=x instanceof ne?x.code:"LINEAGE_INVALID";r.push(s(te,u.packageDir)),_.push({indexEntry:u,failureCode:te});continue}let H=w.find(x=>x.name===u.packageDir.slice(5));if(!g||!H){_.push({indexEntry:u,failureCode:"BUNDLE_INTEGRITY"});continue}if(H.kind!=="directory"){_.push({indexEntry:u,failureCode:H.kind==="symlink"?"PATH_ESCAPED":"BUNDLE_INTEGRITY"});continue}let E;try{let x=await Ps(n,e.root,u.packageDir,t,i);if(!de(t,i)){U=!0,_.push({indexEntry:u,failureCode:"LIMIT_EXCEEDED"});continue}let te=u.files.map(Q=>Q.path);if(x.length!==te.length||x.some((Q,ge)=>Q!==te[ge])){_.push({indexEntry:u,failureCode:"BUNDLE_INTEGRITY"});continue}E=new Map;let ie;for(let Q of u.files){if(!de(t,i)){ie="LIMIT_EXCEEDED",U=!0;break}if(O>=st){ie="LIMIT_EXCEEDED";break}let ge;try{ge=await _i(n,e.root,`${u.packageDir}/${Q.path}`,bs(Q.path));}catch(ho){ie=_e(ho);break}if(!de(t,i)){ie="LIMIT_EXCEEDED",U=!0;break}if(O+ge.byteLength>st){O=st,ie="LIMIT_EXCEEDED";break}if(O+=ge.byteLength,createHash("sha256").update(ge).digest("hex")!==Q.sha256){ie="BUNDLE_INTEGRITY";break}E.set(Q.path,ge);}if(ie!==void 0){_.push({indexEntry:u,failureCode:ie});continue}}catch(x){de(t,i)||(U=true),_.push({indexEntry:u,failureCode:_e(x)});continue}_.push({indexEntry:u,lineage:k,files:E,...b.has(u)?{failureCode:"DUPLICATE_ID"}:{}});}return a(_,U,c)}var ss,pt,dt,as,cs,ps,st,at,ds,ls,lt=j(()=>{y();Zn();Me();et();rt();ss=256*1024,pt=64,dt=128,as=pt*dt,cs=2*1024*1024,ps=8*1024*1024,st=32*1024*1024,at=/^[0-9a-f]{64}$/,ds=new TextDecoder("utf-8",{fatal:true}),ls=Object.freeze({appIds:Object.freeze([]),definitionIds:Object.freeze([])});});function Ss(e){if(typeof e!="string"||!re.test(e))throw new TypeError("pluginId must be a safe UI plugin identifier");let n=`${ut}${e}`.length+7<=128?e:`hash_${createHash("sha256").update(e,"utf8").digest("hex")}`;return {read:`${ut}${n}_read`,action:`${ut}${n}_action`}}function $e(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 bi(e){return typeof e=="string"&&re.test(e)?e:void 0}function Ls(e,n){return n.length===0||n==="."||n===".."||/[\\/\u0000]/.test(n)?e==="skills"?"skills":"apps":`${e==="skills"?"skills":"apps"}/${n}`}function Os(e){return e.length>0&&e!=="."&&e!==".."&&!/[\\/\u0000]/.test(e)}function Ri(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 Rs(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 Us(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 Ui(e){return Ms.decode(e)}function wi(e){return JSON.parse(Ui(e))}function ws(e){if(!$e(e))return;let n=bi(e.pluginId);if(!n)return;let t=bi(e.definitionId),i=e.version,o=t&&Number.isSafeInteger(i)&&i>=1?`${t}\0${String(i)}`:void 0;return {pluginId:n,...o===void 0?{}:{definitionKey:o}}}function ks(e){let n=wi(e);return {value:n,identity:ws(n)}}function It(e,n,t,i){let o={code:e,...i===void 0?{}:{pluginId:i},source:n,relativePath:t};return Object.freeze(o)}function Ni(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 De(e){if(e instanceof D)return Ni(e.code);if(e!==null&&typeof e=="object"&&"code"in e){let n=e.code;if(typeof n=="string")return Ni(n)}}function Je(e,n){return e==="PATH_ESCAPED"||e==="IDENTITY_CHANGED"||e==="TOCTOU"?"PATH_ESCAPED":e==="LIMIT_EXCEEDED"?"LIMIT_EXCEEDED":n==="manifest"&&e==="NOT_FOUND"?"MANIFEST_MISSING":n==="entry"?"ENTRY_INVALID":n==="initial"?"INITIAL_STATE_INVALID":"MANIFEST_INVALID"}function Si(e){switch(e.code){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 ki("UiPluginValidationError",e.code)}}function ki(e,n){throw new Error(`Unmapped ${e} code: ${String(n)}`)}function ft(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 ki("McpAppContractError",e)}}function yt(e,n){let t=n();return Number.isFinite(t)&&Number.isFinite(e)&&t-e<=5e3}function Cs(e){return {pluginId:e.appId,definitionKey:`${e.definition.id}\0${String(e.definition.version)}`}}function xs(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($e(o)){let r=o.bin,s=typeof r=="string"?r:$e(r)?Object.values(r).find(a=>typeof a=="string"):void 0;for(let a of [s,o.main]){if(typeof a!="string")continue;let p=vs(a);if(p&&n.has(p))return p}}}catch{}return [`${e.slice(e.lastIndexOf("/")+1)}.js`,"index.js","main.js"].find(o=>n.has(o))}function vs(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 js(){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 Mi(e){return Object.freeze(Array.from(e))}async function At(e,n,t,i){if(n.pinnedFiles!==void 0){let o=n.pinnedFiles.get(t);if(o===void 0)throw new D("NOT_FOUND");if(o.byteLength>i)throw new D("LIMIT_EXCEEDED");return new Uint8Array(o)}return Ci(e,n.root,`${n.relativePath}/${t}`,i)}function Vs(e,n,t){let i=createHash("sha256"),o=new TextEncoder().encode(Y(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 Fs(e,n){let t={...e.definition,sourceHash:n},i={...t,hash:se(t)};try{ae(i);}catch{throw new K("MANIFEST_INVALID","normalized definition is invalid")}return i}function Bs(e){return e.actions.some(n=>n.backend.type==="core"&&n.backend.handler!=="state.set")}function Hs(e){if(typeof e.readVerifiedFile=="function")return e.readVerifiedFile;if(typeof e.readFileVerified=="function")return e.readFileVerified}function zs(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 Ci(e,n,t,i){let o=Hs(e);if(!o)throw new D("READ_DENIED");return Us(await o.call(e,n,t,i))}async function Gs(e,n,t){let i=zs(e);if(!i)throw new D("READ_DENIED");let o=await i.call(e,n,t);if(!Array.isArray(o))throw new D("READ_DENIED");return o.map(Rs).filter(r=>r!==null)}function $s(e){let n=[];for(let t of [e.reserved,e.builtin])t&&n.push(t);return e.builtins&&"listMcpApps"in e.builtins?n.push(Li(e.builtins)):e.builtins&&n.push(e.builtins),e.builtinCatalog&&n.push(Li(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 Li(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 le(e,n){e.diagnostic||(e.diagnostic=It(n,e.source,e.relativePath,e.identity?.pluginId));}function Js(e){let n=new Map;for(let i of e){let o=i.identity?.pluginId;if(o===void 0)continue;let r=n.get(o)??[];r.push(i),n.set(o,r);}for(let i of n.values()){if(i.length<2)continue;let o=i.filter(s=>s.provenance!==void 0);if(o.length>0){for(let s of i)s.provenance===void 0&&le(s,"RESERVED_ID");if(o.length>1)for(let s of o)le(s,"DUPLICATE_ID");continue}let r=i.filter(s=>s.source==="apps");if(r.length>1){for(let s of r)le(s,"DUPLICATE_ID");for(let s of i.filter(a=>a.source==="skills"))le(s,"DUPLICATE_ID");}else for(let s of i.filter(a=>a.source==="skills"))le(s,"DUPLICATE_ID");}let t=new Map;for(let i of e){if(i.diagnostic?.code==="RESERVED_ID")continue;let o=i.identity?.definitionKey;if(o===void 0)continue;let r=t.get(o)??[];r.push(i),t.set(o,r);}for(let i of t.values())if(i.length>1)for(let o of i)le(o,"DUPLICATE_ID");}function Ws(e,n,t){let i=new Set,o=new Set,r=new Set,s=new Set(t.appIds),a=new Set(t.definitionIds);for(let p of $s(n)){for(let c of p.appIds??[])typeof c=="string"&&i.add(c);for(let c of p.definitionIds??[])typeof c=="string"&&o.add(c);for(let c of p.toolNames??[])typeof c=="string"&&r.add(c);}for(let p of e){let c=p.candidate;if(!c)continue;if(i.has(c.pluginId)||o.has(c.definitionId)){le(p,"RESERVED_ID");continue}if(p.provenance===void 0&&(s.has(c.pluginId)||a.has(c.definitionId))){le(p,"RESERVED_ID");continue}[c.toolNames.read,c.toolNames.action].filter(f=>f!==void 0).some(f=>r.has(f))&&le(p,"DUPLICATE_ID");}}function Ks(e){return [...e].sort((n,t)=>{let i=Pi.indexOf(n.source)-Pi.indexOf(t.source);return i!==0?i:Ri(n.relativePath,t.relativePath)})}function R(e,n){e.diagnostic=It(n,e.source,e.relativePath,e.identity?.pluginId);}async function Oi(e,n,t){if(t.byteLength>262144){R(n,"LIMIT_EXCEEDED");return}let i;try{i=ks(t);}catch{R(n,"MANIFEST_INVALID");return}if(n.bundleIdentity===void 0)n.identity=i.identity;else if(i.identity?.pluginId!==n.bundleIdentity.appId||i.identity.definitionKey!==`${n.bundleIdentity.definitionId}\0${String(n.bundleIdentity.version)}`){R(n,"BUNDLE_INTEGRITY");return}if($e(i.value)&&i.value.builtinOnly===true){R(n,"RESERVED_ID");return}let o;try{let E=Ee(i.value,{mode:"local"});if(E.manifestVersion!==2)throw new K("MANIFEST_INVALID","workspace App requires v2");o=E;}catch(E){if(E instanceof K){R(n,Si(E));return}if(E instanceof ce){R(n,ft(E.code));return}if($e(E)&&typeof E.code=="string"){R(n,ft(E.code));return}throw E}let r={pluginId:o.pluginId,definitionKey:`${o.definitionId}\0${String(o.version)}`};if(n.bundleIdentity===void 0&&(n.identity=r),o.actions.length>0)try{pi(o.actions.map(E=>({actionId:E.actionId,inputSchema:E.inputSchema})));}catch(E){if(E instanceof ce){R(n,ft(E.code));return}throw E}let s;try{s=await At(e,n,"ui/index.html",Be);}catch(E){R(n,Je(De(E),"entry"));return}if(s.byteLength>Be){R(n,"LIMIT_EXCEEDED");return}let a;try{a=Ui(s);}catch{R(n,"ENTRY_INVALID");return}if(s.byteLength===0||a.length===0){R(n,"ENTRY_INVALID");return}let p=createHash("sha256").update(s).digest("hex");if(o.entryHash!==void 0&&o.entryHash!==p){R(n,"ENTRY_INVALID");return}let c={},l,f;if(o.initialState!==void 0){try{l=await At(e,n,"ui/state.json",65536);}catch(E){R(n,Je(De(E),"initial"));return}if(l.byteLength>65536){R(n,"LIMIT_EXCEEDED");return}try{let E=wi(l),x=o.dataPaths??[],te=$n(E,x);c=oe(te,0,x),Ne(c);}catch{R(n,"INITIAL_STATE_INVALID");return}if(f=createHash("sha256").update(l).digest("hex"),o.initialState.hash!==void 0&&o.initialState.hash!==f){R(n,"INITIAL_STATE_INVALID");return}}let I={...o,entryHash:p,...o.initialState===void 0?{}:{initialState:{path:"ui/state.json",hash:f}}},g=Jn(I),m=Vs(I,s,l??new Uint8Array),P;try{P=Fs(g,m);}catch(E){if(E instanceof K){R(n,Si(E));return}throw E}let w;if(n.bundleLineage!==void 0){let E=n.bundleLineage[n.bundleLineage.length-1];if(!E){R(n,"LINEAGE_INVALID");return}let{legacy:x,...te}=E.definition,{hash:ie,...Q}=P;if(Y(te)!==Y(Q)){R(n,"LINEAGE_STALE");return}if(x!==void 0&&(P={...P,legacy:x}),x!==void 0)try{P={...P,hash:se(P)},ae(P);}catch{R(n,"LINEAGE_INVALID");return}w=n.bundleLineage;}if(n.bundleIdentity!==void 0&&n.bundleIdentity.appId!==o.pluginId){R(n,"BUNDLE_INTEGRITY");return}if(n.bundleIdentity!==void 0&&(n.bundleIdentity.definitionId!==P.id||n.bundleIdentity.version!==P.version||n.bundleIdentity.definitionHash!==P.hash)){R(n,"LINEAGE_STALE");return}let v=Ss(o.pluginId),T=o.actions.length===0?{read:v.read}:v,b=ke(g),C=ke(I),A=ke(P),_=ke({...g.handlers}),O=Mi(s),U=l===void 0?void 0:Mi(l),u=Object.freeze({...n.provenance===void 0?{}:{provenance:n.provenance},entry:Object.freeze({path:"ui/index.html",hash:p,bytes:O}),...U===void 0?{}:{initialState:Object.freeze({path:"ui/state.json",hash:f,bytes:U})}}),k={appId:o.pluginId,pluginId:o.pluginId,definitionId:o.definitionId,version:o.version,relativePath:n.relativePath,manifest:C,normalized:b,name:o.name,description:o.description,...o.icon===void 0?{}:{icon:o.icon},...o.tone===void 0?{}:{tone:o.tone},definition:A,handlers:_,resources:u,html:a,entryBytes:O,entryHash:p,initialState:ke(c),...U===void 0?{}:{initialStateBytes:U},...f===void 0?{}:{initialStateHash:f},sourceHash:m,toolNames:Object.freeze(T)},H=n.provenance===void 0?{...k,source:n.source}:{...k,provenance:n.provenance,lineage:w??[]};n.candidate=Object.freeze(H),Bs(o)&&R(n,"EXEC_DENIED");}async function Xs(e,n){try{return await At(e,n,"ui-plugin.json",262144)}catch(t){if(De(t)==="NOT_FOUND")return;R(n,Je(De(t),"manifest"));return}}function Ys(e,n,t,i=Ns,o=false){let r=Ks(e);Js(r);let s=Object.freeze(r.filter(l=>l.candidate!==void 0&&l.diagnostic===void 0).map(l=>l.candidate)),a=Object.freeze(r.filter(l=>l.diagnostic!==void 0).map(l=>l.diagnostic)),p=o?Object.freeze({...t===void 0?{}:{indexHash:t},diagnostics:Object.freeze(a.filter(l=>l.source==="bundled").map(l=>Object.freeze({...l}))),reservedAppIds:Object.freeze([...i.appIds]),reservedDefinitionIds:Object.freeze([...i.definitionIds])}):void 0,c={apps:s,diagnostics:a,complete:n===void 0,...n===void 0?{}:{incompleteReason:n},...t===void 0?{}:{productBundleIndexHash:t},...p===void 0?{}:{productBundleSnapshotMetadata:p}};return Object.defineProperty(c,"candidates",{configurable:false,enumerable:false,get:()=>s}),Object.freeze(c)}function qs(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 Zs(e,n){if(qs(e))return {fs:e,options:{}};let t=e??n??{};return {fs:t.filesystem??t.fileSystem??t.fs??gi,options:t}}async function xi(e,n,t){if(typeof e!="string"||e.length===0)throw new TypeError("workspaceRoot must be explicit");let{fs:i,options:o}=Zs(n,t),r=o.clock??js,s=r(),a=[],p=0,c,l=await Di(o.productBundle,i,s,r);a.push(...l.diagnostics.map(g=>({source:g.source,root:o.productBundle?.root??e,name:"",relativePath:g.relativePath,diagnostic:g})));let f=l.reservedIds;l.incomplete&&(c="time_limit");for(let g of l.packages){let m=g.indexEntry,P=m.packageDir,w=g.files===void 0?void 0:xs(P,g.files),v=l.indexHash===void 0?void 0:ei(Object.freeze({kind:"bundled",launcher:m.launcher!==false,indexHash:l.indexHash,packageDir:P,appId:m.appId,definitionId:m.definition.id,version:m.definition.version,definitionHash:m.definition.hash,files:m.files}),w),T={source:"bundled",root:o.productBundle?.root??e,name:P.slice(5),relativePath:P,...v===void 0?{}:{provenance:v},...g.files===void 0?{}:{pinnedFiles:g.files},...g.lineage===void 0?{}:{bundleLineage:g.lineage},bundleIdentity:{appId:m.appId,definitionId:m.definition.id,version:m.definition.version,definitionHash:m.definition.hash},identity:Cs(m)};if(a.push(T),p+=1,g.failureCode!==void 0){R(T,g.failureCode);continue}let b=g.files?.get("ui-plugin.json");if(b===void 0){R(T,"BUNDLE_INTEGRITY");continue}await Oi(i,T,b),T.candidate!==void 0&&T.diagnostic===void 0&&p<64&&!yt(s,r)&&(c="time_limit");}let I=[{source:"apps",directory:"apps"},{source:"skills",directory:"skills"}];for(let g of I){let{source:m,directory:P}=g,w;try{w=await Gs(i,e,P);}catch(T){if(De(T)==="NOT_FOUND")continue;a.push({source:m,root:e,name:"",relativePath:m,diagnostic:It(Je(De(T),"manifest"),m,m)});continue}let v=w.filter(T=>T.kind==="directory"||T.kind==="symlink").filter(T=>Os(T.name)).map(T=>({source:m,root:e,name:T.name,relativePath:Ls(m,T.name)})).sort((T,b)=>Ri(T.relativePath,b.relativePath));for(let T of v){let b={...T};a.push(b);let C;if(m==="skills"&&(C=await Xs(i,b),C===void 0))continue;if(p>=64){R(b,"LIMIT_EXCEEDED");continue}if(T.relativePath.split("/").length-1>2){R(b,"LIMIT_EXCEEDED");continue}if(c!==void 0||!yt(s,r)){R(b,"LIMIT_EXCEEDED"),c="time_limit";continue}if(p+=1,C===void 0)try{C=await Ci(i,b.root,`${b.relativePath}/ui-plugin.json`,262144);}catch(_){R(b,Je(De(_),"manifest"));continue}await Oi(i,b,C),b.diagnostic===void 0&&p<64&&!yt(s,r)&&(c="time_limit");}}return Ws(a,o,f),Ys(a,c,l.indexHash,f,o.productBundle!==void 0)}var Ns,ut,Pi,Ms,vi=j(()=>{y();we();Ae();Wn();Me();et();rn();rt();sn();lt();lt();Ns=un([]),ut="crewx_local_app_";Pi=["bundled","apps","skills"],Ms=new TextDecoder("utf-8",{fatal:true});});y();Wn();y();Mn();y();var Gt="SKILL.md",Or=/^---\s*\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;function $t(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function Rr(e){return e.isDirectory()||e.isSymbolicLink()}function Yt(e){try{return existsSync(e)&&statSync(e).isDirectory()}catch{return false}}function Kn(e){let n;try{n=readFileSync(e,"utf8");}catch{return {frontmatter:{},readable:false,valid:false,hasFrontmatter:false}}let t=n.match(Or);if(!t)return {frontmatter:{},readable:true,valid:true,hasFrontmatter:false};try{let i=load(t[1]??"");if(!$t(i))return {frontmatter:{},readable:!0,valid:!1,hasFrontmatter:!0};let o=$t(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 Ur(e){return [join(e,Gt),join(e,"skill",Gt)]}function Jt(e,n){if(!Yt(e))return null;for(let t of Ur(e)){if(!existsSync(t))continue;let o=Kn(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 Wt(e){try{return readdirSync(e,{withFileTypes:!0}).filter(Rr)}catch{return []}}function Kt(e,n,t){!e||n.has(e.name)||(n.add(e.name),t.push(e));}function qt(e){let n=[],t=new Set;for(let i of e)if(Yt(i))for(let o of Wt(i)){if(o.name.startsWith("@")){let r=join(i,o.name);for(let s of Wt(r))Kt(Jt(join(r,s.name),s.name),t,n);continue}Kt(Jt(join(i,o.name),o.name),t,n);}return n.sort((i,o)=>i.name.localeCompare(o.name))}vi();var ea=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/;function An(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?na(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 na(e,n){let t=new TextEncoder().encode(In(e)),i=ta(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 ta(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 In(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 yn(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 Fi(e,n){let t=relative(e,n).split(sep).join("/");return !t||t===".."||t.startsWith("../")||isAbsolute(t)?null:In(t)}function ia(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 Bi(e){return Object.freeze({packageRoot:e})}function oa(e){return Object.freeze({id:e.definition.id,version:e.definition.version,hash:e.definition.hash,usage:e.definition.usage??Ie,...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 Hi(e){return {capabilities:Object.freeze([...e]),origin:"local",ownership:"unknown",shareability:"unknown",sharingAvailability:"unavailable"}}function ra(e,n){let t=e.candidate,i=t.provenance!==void 0,o=n&&!i?["screen","skill"]:["screen"],r=oa(t),s=An(n?{screenHash:r.hash,skillHash:n.skillHash}:{screenHash:r.hash}),a=t.description||n?.skill.description||"",p=String(t.version),c={appId:t.pluginId,name:t.name,description:a,version:p,...Hi(o),definition:r,...n===void 0||i?{}:{skillName:n.skill.name},...i?{provenance:t.provenance}:{localDefinitionRef:Bi(e.packageRoot)},definitionHash:s};return {...i?{}:{packageRoot:e.packageRoot},source:i?"bundled":t.source,appId:c.appId,capabilities:o,summary:Object.freeze(c)}}function sa(e){let n=aa(e.skill.name),t={appId:n,name:e.skill.name,description:e.skill.description??"",...e.skill.version===void 0?{}:{version:e.skill.version},...Hi(["skill"]),skillName:e.skill.name,localDefinitionRef:Bi(e.packageRoot),definitionHash:An({skillHash:e.skillHash})};return {packageRoot:e.packageRoot,source:e.source,appId:n,capabilities:["skill"],summary:Object.freeze(t)}}function aa(e){return `skill.${e.replace(/^@/,"").replace(/\//g,".").replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,122)||"unnamed"}`}function z(e,n,t,i){return Object.freeze({code:e,source:n,relativePath:ca(t),...i===void 0?{}:{appId:i}})}function ca(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 zi(e){return z(e.code,e.source,e.relativePath,e.pluginId)}function pa(e,n){let t=Fi(e,n.dir);if(!t)return {diagnostic:z("PATH_ESCAPED","node_modules","node_modules")};let i=ia(t);if(!i)return {diagnostic:z("PATH_ESCAPED","node_modules",t)};let o=Kn(n.skillMdPath);if(!o.readable)return {diagnostic:z("SKILL_READ_FAILED",i,t)};if(!o.valid)return {diagnostic:z("SKILL_INVALID",i,t)};let r=da(n.dir,n.skillMdPath);if(!r)return {diagnostic:z("PATH_ESCAPED",i,t)};try{let s=new Uint8Array(readFileSync(n.skillMdPath));return {skill:n,packageRoot:t,relativeSkillPath:r,skillHash:An({relativePath:r,fileBytes:s}),source:i}}catch{return {diagnostic:z("SKILL_READ_FAILED",i,t)}}}function da(e,n){let t=relative(e,n).split(sep).join("/");try{return In(t)}catch{return null}}function la(e){if(!ea.test(e.appId))return {diagnostic:z("BUILTIN_INVALID","builtin",`builtin/${e.appId||"unknown"}`)};let n=e.definition===void 0?void 0:{id:e.definition.id,version:e.definition.version,hash:e.definition.hash,usage:e.definition.usage??Ie,...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 ua(e){return e.builtinCatalog}function fa(e){let n=e.packageRoot??e.relativePath??e.packageRootPath;if(n===void 0)return null;try{return In(n)}catch{return null}}function ya(e){let n=e.marketplaceContentId;return typeof n=="string"&&n.length>0?n:void 0}function Aa(e,n,t){let i=n.installed??[],o=new Map;for(let s of i){let a=fa(s);if(!a){t.push(z("INSTALLED_IDENTITY_MISMATCH","installed","installed"));continue}let p=o.get(a);if(p&&JSON.stringify(p)!==JSON.stringify(s)){t.push(z("INSTALLED_IDENTITY_MISMATCH","installed",a));continue}o.set(a,s);}let r=new Map;for(let s of e)s.packageRoot!==void 0&&r.set(s.packageRoot,s);for(let[s,a]of o){let p=r.get(s);if(!p){t.push(z("INSTALLED_MISSING","installed",s,a.appId));continue}let c=ya(a);if(!c){t.push(z("INSTALLED_CONTENT_ID_MISSING","installed",s,a.appId));continue}if(a.appId!==void 0&&a.appId!==p.appId||a.definitionHash!==void 0&&a.definitionHash!==p.summary.definitionHash){t.push(z("INSTALLED_IDENTITY_MISMATCH","installed",s,a.appId));continue}let l={...p.summary,origin:"installed",...a.slug===void 0?{}:{slug:a.slug},marketplaceContentId:c},f=e.indexOf(p);f>=0&&(e[f]={...p,summary:Object.freeze(l)});}}function Ia(e,n){let t=new Map;for(let o of e){let r=t.get(o.appId)??[];r.push(o),t.set(o.appId,r);}let i=new Set;for(let o of t.values()){if(o.length<2)continue;let r=o.some(s=>s.source==="builtin")?"builtin":o.some(s=>s.source==="bundled")?"bundled":void 0;if(r!==void 0){let s=o.filter(a=>a.source===r);for(let a of o.filter(p=>p.source!==r))i.add(a),n.push(z("RESERVED_ID",a.source,mt(a),a.appId));if(s.length>1)for(let a of s)i.add(a),n.push(z("DUPLICATE_ID",a.source,mt(a),a.appId));continue}for(let s of o)i.add(s),n.push(z("DUPLICATE_ID",s.source,mt(s),s.appId));}return e.filter(o=>!i.has(o))}function mt(e){return e.packageRoot??e.summary.provenance?.packageDir??`builtin/${e.appId}`}function ga(e,n){return e.filter(t=>!(t.code==="MANIFEST_MISSING"&&n.has(t.relativePath))).map(zi)}function ma(e){return e.filesystem}function ha(e,n){let t=ma(e),i=e.registeredProductBundle;return {...t===void 0?{}:{filesystem:t},...e.productBundle===void 0?{}:{productBundle:e.productBundle},...n===void 0?{}:{builtinCatalog:n},...i===void 0?{}:{reservedAppIds:i.reservedAppIds,reservedDefinitionIds:i.reservedDefinitionIds}}}async function Gi(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=ua(n),i=await xi(e,ha(n,t)),o=n.registeredProductBundle??i.productBundleSnapshotMetadata,r=[join(e,"skills"),join(e,"node_modules"),join(e,"apps")],s=[],a=[],p=[],c=new Set;for(let A of r)for(let _ of qt([A])){let O=Fi(e,_.dir);(O===null||!c.has(O))&&(p.push(_),O!==null&&c.add(O));}for(let A of p){let _=pa(e,A);"diagnostic"in _?s.push(_.diagnostic):a.push(_);}let l=new Map;for(let A of i.apps??i.candidates??[]){let _=A.provenance===void 0?`workspace\0${A.relativePath}`:`bundled\0${A.provenance.indexHash}\0${A.provenance.packageDir}`;l.set(_,{candidate:A,packageRoot:A.relativePath});}let f=new Map(a.map(A=>[A.packageRoot,A])),I=[];for(let A of l.values()){let _=A.candidate.provenance===void 0?f.get(A.packageRoot):void 0,O=ra(A,_);I.push({...O.packageRoot===void 0?{}:{packageRoot:O.packageRoot},source:O.source,appId:O.appId,summary:O.summary});}let g=new Set([...l.values()].filter(A=>A.candidate.provenance===void 0).map(A=>A.packageRoot)),m=o===void 0?new Set:new Set(i.diagnostics.filter(A=>A.code==="RESERVED_ID"&&A.source!=="bundled").map(A=>A.relativePath)),P=new Set(o?.reservedAppIds??[]);for(let A of a){let _=sa(A);if(!(g.has(A.packageRoot)||m.has(A.packageRoot))){if(P.has(_.appId)){s.push(z("RESERVED_ID",A.source,A.packageRoot,_.appId));continue}I.push({packageRoot:_.packageRoot,source:_.source,appId:_.appId,summary:_.summary});}}let w=[...ga(i.diagnostics,new Set(a.map(A=>A.packageRoot))),...s,...n.registeredProductBundle?.diagnostics.filter(A=>A.source==="bundled").map(zi)??[]],v=[];if(t)for(let A of t.listMcpApps()){let _=la(A);"diagnostic"in _?w.push(_.diagnostic):v.push(_);}let T=Ia([...I,...v],w);Aa(T,n,w);let b=T.map(A=>A.summary).sort((A,_)=>yn(A.appId,_.appId)),C=[...w].sort((A,_)=>yn(A.relativePath,_.relativePath)||yn(A.code,_.code)||yn(A.appId??"",_.appId??""));return Object.freeze({items:Object.freeze(b),diagnostics:Object.freeze(C)})}y();y();y();function Ea(e){let n=o=>o.replace(/[.+^${}()|[\]\\]/g,"\\$&"),i=e.split("/").map(o=>o==="**"?".*":o.split("*").map(n).join("[^/]*"));return new RegExp(`^${i.join("\\/")}$`)}function Ce(e,n){try{return Ea(n).test(e)}catch{return false}}function gn(e,...n){let t=e.split("/");if(t.length<n.length)return false;let i=t.length-n.length;return n.every((o,r)=>Ce(t[i+r],o))}function _a(e,n){return e.split("/").some(t=>Ce(t,n))}var $i=[{label:".env*",test:e=>Ce(e,".env*")},{label:".git/",test:(e,n,t)=>t&&e===".git"},{label:"memory/",test:(e,n,t)=>t&&e==="memory"},{label:"*.key",test:e=>Ce(e,"*.key")},{label:"*.pem",test:e=>Ce(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&&gn(n,".crewx","threads")},{label:".crewx/crewx.db",test:(e,n,t)=>!t&&gn(n,".crewx","crewx.db")},{label:".crewx/*.log",test:(e,n,t)=>!t&&gn(n,".crewx","*.log")},{label:".crewx/publish/",test:(e,n,t)=>t&&gn(n,".crewx","publish")},{label:".crewx/",test:(e,n)=>_a(n,".crewx")}];function mn(e,n,t){for(let i of $i)if(i.test(e,n,t))return i.label;return null}function _t(e){let n=[],t=[];function i(o,r,s){let a;try{a=G.readdirSync(o,{withFileTypes:!0});}catch{return}a.sort((p,c)=>p.name.localeCompare(c.name));for(let p of a){let c=r?`${r}/${p.name}`:p.name,l=J.join(o,p.name);if(p.isSymbolicLink()){let f;try{f=G.statSync(l);}catch{t.push({path:c,rule:"symlink"});continue}if(f.isDirectory()){t.push({path:c,rule:s??"symlink-dir"});continue}let I=s??mn(p.name,c,false);I?t.push({path:c,rule:I}):t.push({path:c,rule:"symlink"});continue}if(p.isDirectory()){let f=s??mn(p.name,c,true);i(l,c,f);continue}if(p.isFile()){let f=s??mn(p.name,c,false);f?t.push({path:c,rule:f}):n.push(c);}}}return i(e,"",null),n.sort(),t.sort((o,r)=>o.path<r.path?-1:o.path>r.path?1:0),{included:n,excluded:t}}y();var Ta=[{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 Da(e){return e.includes(0)}function Tt(e,n,t){let i=[];for(let o of n){let r=J.join(e,o),s;try{let p=t?.get(o);s=p===void 0?G.readFileSync(r):Buffer.from(p);}catch{continue}if(Da(s))continue;s.toString("utf8").split(/\r\n|\r|\n/).forEach((p,c)=>{for(let{rule:l,regex:f}of Ta)f.test(p)&&i.push({path:o,line:c+1,rule:l});});}return i}y();y();var ue=class extends Error{constructor(t,i){super(`publish: [${t}]${i?` ${i}`:""}`);this.code=t;}code;name="PublishError"};function h(e,n){return new ue(e,n)}var Xi=/^[a-z0-9-]+$/,Pa=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/,ba=/^[A-Za-z_][A-Za-z0-9_]*$/;function Na(e){let n=J.join(e,"crewx.yaml");if(!G.existsSync(n))return {};let t;try{t=Yi.load(G.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 Sa(e){return Dt.createHash("sha256").update(e).digest("hex")}function qi(e){let n;try{n=G.lstatSync(e);}catch{throw h("PACKAGE_FILE_INVALID",`file is not readable: ${J.basename(e)}`)}if(n.isSymbolicLink())throw h("PACKAGE_SYMLINK","symlink content is not publishable");if(!n.isFile())throw h("PACKAGE_FILE_INVALID","only regular files are publishable");return Dt.createHash("sha256").update(new Uint8Array(G.readFileSync(e))).digest("hex")}function Ma(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 Zi(e){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||J.posix.isAbsolute(e)||e.split("/").some(n=>n===".."||n.length===0))throw h("PACKAGE_PATH_TRAVERSAL","manifest file path must be a non-empty POSIX relative path")}function La(e){if(!/^(?:apps|skills)\/[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(e))throw h("APP_PACKAGE_ROOT_INVALID","packageRoot must be apps/<safe-id> or skills/<safe-id>")}function Qi(e){if(!Pa.test(e))throw new Error(`publish: invalid version "${e}" \u2014 must be semver (e.g. 1.0.0)`)}function eo(e,n,t={}){let i=Na(e),o=i.name??J.basename(e);if(!Xi.test(o))throw new Error(`publish: invalid name "${o}" \u2014 must match ${Xi} (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");Qi(r);let s=Array.isArray(i.requiredEnv)?i.requiredEnv:[],a=[];for(let l of s){if(typeof l!="string"||!ba.test(l))throw new Error(`publish: requiredEnv must contain names only (no values), got "${String(l)}"`);a.push(l);}let p=n.map(l=>(Zi(l),{path:l,sha256:qi(J.join(e,l))})).sort((l,f)=>l.path<f.path?-1:l.path>f.path?1:0),c={name:o,version:r,type:"template",description:i.description??"",files:p,requiredEnv:a};return i.crewxMinVersion&&(c.crewxMinVersion=i.crewxMinVersion),c}function Oa(e){let n=e.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"");if(!n)throw h("APP_PACKAGE_ROOT_INVALID","appId cannot produce a marketplace name");return n}function no(e,n){if(La(n.packageRoot),!n.version)throw new Error("publish: version is required for App publishing \u2014 pass opts.version");if(Qi(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 h("APP_UI_MANIFEST_INVALID","screen App manifests require definitionId");for(let s of ["ui-plugin.json","ui/index.html"])if(!n.includedFiles.includes(`${i}${s}`))throw h("APP_UI_MANIFEST_INVALID",`screen App is missing ${s}`)}if(t.includes("skill")&&!n.includedFiles.includes(`${i}SKILL.md`))throw h("APP_SKILL_MISSING","skill capability requires package-root SKILL.md");let o=new Set,r=n.includedFiles.map(s=>{if(Zi(s),!s.startsWith(i))throw h("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?qi(J.join(e,s)):Sa(a),...a===void 0?{}:{generated:true}}}).sort((s,a)=>Ma(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:Oa(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:[]}}y();function to(e){return Dt.createHash("sha256").update(e).digest("hex")}function ao(e,n){if(typeof n!="string"||n.length===0||n.includes("\\")||n.includes("\0")||J.posix.isAbsolute(n)||n.split("/").some(o=>o===".."||o.length===0))throw h("PACKAGE_PATH_TRAVERSAL","archive paths must be non-empty POSIX relative paths");let t=J.resolve(e),i=J.resolve(t,...n.split("/"));if(i!==t&&!i.startsWith(`${t}${J.sep}`))throw h("PACKAGE_PATH_TRAVERSAL","archive path escaped its root");return i}function io(e,n){let t=ao(e,n),i;try{i=G.lstatSync(t);}catch{throw h("PACKAGE_FILE_INVALID","manifest file is missing")}if(i.isSymbolicLink())throw h("PACKAGE_SYMLINK","symlink content is not publishable");if(!i.isFile())throw h("PACKAGE_FILE_INVALID","only regular files are publishable");return new Uint8Array(G.readFileSync(t))}async function co(e,n,t={}){let i=J.join(e,".crewx","publish");G.mkdirSync(i,{recursive:true});let o=J.join(i,`${n.name}-${n.version}.tgz`),r=J.join(i,`.${n.name}-${n.version}.${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}.tmp.tgz`),s=G.mkdtempSync(J.join(oo.tmpdir(),"crewx-publish-"));try{let a=new Set,p=[];for(let c of n.files){if(a.has(c.path))throw h("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 h("PACKAGE_GENERATED_FILE_MISSING","generated manifest file bytes are missing");if(t.sourceFileHashes?.has(c.path)){let g=io(e,c.path);if(t.sourceFileHashes.get(c.path)!==to(g))throw h("PACKAGE_STAGED_BYTES_MISMATCH","workspace source changed before staging")}let f=l??io(e,c.path);if(to(f)!==c.sha256)throw h("PACKAGE_STAGED_BYTES_MISMATCH",`staged bytes differ for ${c.path}`);let I=ao(s,c.path);G.mkdirSync(J.dirname(I),{recursive:!0}),G.writeFileSync(I,new Uint8Array(f)),p.push(c.path);}G.writeFileSync(J.join(s,"manifest.json"),JSON.stringify(n,null,2)),await so.create({gzip:!0,file:r,cwd:s,portable:!0,noMtime:!0},["manifest.json",...p]),G.renameSync(r,o);}finally{try{G.rmSync(r,{force:!0});}catch{}G.rmSync(s,{recursive:true,force:true});}return o}y();y();var xe="/api/v1";var wa=201,ka=200,Ca=409,Pt=401,po={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 xa(){return process.env.WI013_FAKE_UPLOAD==="1"}function va(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 ja(e){return e.replace(/\/+$/,"")}async function We(e){try{return await e.json()}catch{return null}}function lo(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 Va(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 Fa(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 uo(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(po,r))continue;let s=r,a=s==="APP_NAME_CONFLICT"?`marketplace name is already in use: ${n}`:void 0;return h(po[s],a)}}async function Ba(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=ja(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}${xe}/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 p=await We(a),c=Va(p),l=Fa(p),f=r&&l!==void 0?l:i,I;if(a.status===wa)I="created";else if(r&&a.status===ka){if(c===void 0)throw h("PUBLISH_CONTENT_ID_MISSING","App republish did not return an opaque contentId");I="existing";}else if(a.status===Ca){if(r)throw uo(p,i)??h("APP_NAME_CONFLICT",`marketplace name is already in use: ${i}`);I="existing";}else throw a.status===Pt?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 g="not-needed",m=null;if(I==="existing"&&!r){let O;try{O=await fetch(`${n}${xe}/publisher/items`,{method:"GET",headers:{Authorization:`Bearer ${e.accessToken}`}});}catch{throw new Error("publish: [E_NETWORK] Publisher items request failed (network)")}let U=await We(O);if(O.status!==200)throw new Error(`publish: [E_HTTP] Publisher items request failed \u2014 HTTP ${O.status}`);let k=lo(U,"publisher items",O.status)?.items;if(!Array.isArray(k))throw new Error(`publish: [E_MALFORMED] Publisher items response is malformed (expected data.items[]) \u2014 HTTP ${O.status}`);let H=k.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 ${O.status}`);if(m=H.version,m!==e.manifest.version){let E;try{E=await fetch(`${n}${xe}/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 We(E),E.status===Pt?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}`);g="applied";}}let P=G.readFileSync(e.tgzPath),w=xa()?va(P):P,v=new FormData;v.set("archive",new Blob([new Uint8Array(w)],{type:"application/gzip"}),`${f}-${e.manifest.version}.tgz`);let T=r&&c!==void 0?c:i,b;try{b=await fetch(`${n}${xe}/publisher/items/${encodeURIComponent(T)}/upload`,{method:"POST",headers:{Authorization:`Bearer ${e.accessToken}`},body:v});}catch{throw new Error("publish: [E_NETWORK] Upload request failed (network)")}if(b.status===Pt)throw new Error("publish: [E_AUTH_EXPIRED] Authentication is expired or missing \u2014 please log in again (HTTP 401)");if(!b.ok){let O=await We(b);if(r){let U=uo(O,f);if(U)throw U}throw new Error(`publish: [E_HTTP] Upload request failed \u2014 HTTP ${b.status}`)}let C=await We(b),A=lo(C,"upload",b.status),_=typeof A.contentId=="string"&&A.contentId.length>0?A.contentId:c;if(r&&_===void 0)throw h("PUBLISH_CONTENT_ID_MISSING","App upload did not return an opaque contentId");return {slug:f,version:e.manifest.version,..._===void 0?{}:{contentId:_},artifactChecksum:A.artifactChecksum,artifactSizeBytes:A.artifactSizeBytes,submitOutcome:I,versionUpdate:g,serverVersionBefore:m}}var Ha=1e4,za=100*1024*1024;function bt(e){return Dt.createHash("sha256").update(e).digest("hex")}function Ga(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function En(e,n){if(!n||n.includes("\\")||n.includes("\0")||J.posix.isAbsolute(n)||n.split("/").some(r=>r===".."||r.length===0))throw h("PACKAGE_PATH_TRAVERSAL","workspace file path is not a safe relative path");let t=J.resolve(e,...n.split("/")),i=J.resolve(e);if(t!==i&&!t.startsWith(`${i}${J.sep}`))throw h("PACKAGE_PATH_TRAVERSAL","workspace file path escaped the workspace root");let o;try{o=G.lstatSync(t);}catch{throw h("PACKAGE_FILE_INVALID",`workspace file is missing: ${n}`)}if(o.isSymbolicLink())throw h("PACKAGE_SYMLINK",`symlink is not publishable: ${n}`);if(!o.isFile())throw h("PACKAGE_FILE_INVALID",`not a regular file: ${n}`);return new Uint8Array(G.readFileSync(t))}function _n(e,n){return e===n||e.startsWith(`${n}/`)}function $a(e,n){return e.path<n.path?-1:e.path>n.path?1:e.rule.localeCompare(n.rule)}function yo(e,n,t){let i=e??n;if(!Number.isSafeInteger(i)||i<=0)throw new ue("PACKAGE_SIZE_LIMIT",`${t} must be a positive integer`);return i}function Io(e,n,t,i){let o=yo(t.maxFileCount??t.maxFiles,Ha,"max file count"),r=yo(t.maxTotalBytes??t.maxBytes,za,"max total bytes");if(n.length>o)throw new ue("PACKAGE_SIZE_LIMIT",`package exceeds file count limit (${o})`);let s=0;for(let a of n){let p=i?.get(a);if(p!==void 0?s+=p.byteLength:s+=En(e,a).byteLength,s>r)throw new ue("PACKAGE_SIZE_LIMIT",`package exceeds byte limit (${r})`)}}function Ja(e){return e.appId!==void 0||e.expectedDefinitionHash!==void 0}function Wa(e){let n=e.appId!==void 0,t=e.expectedDefinitionHash!==void 0;if(!n&&t)throw h("APP_ID_REQUIRED","appId is required with expectedDefinitionHash");if(n&&!t)throw h("APP_DEFINITION_HASH_REQUIRED","expectedDefinitionHash is required with appId");if(!n||!t)throw h("APP_ID_REQUIRED")}function Ka(e,n){let t=e.filter(i=>i.appId===n);if(t.length===0)throw h("APP_NOT_FOUND",`no publishable App matches ${n}`);if(t.length!==1)throw h("APP_AMBIGUOUS",`more than one App matches ${n}`);return t[0]}function Xa(e){let n=e.localDefinitionRef?.packageRoot;if(!n||!/^(?:apps|skills)\/[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(n))throw h("APP_PACKAGE_ROOT_INVALID","selected App is not rooted in apps/<safe-id> or skills/<safe-id>");return n}function Ya(e,n){let t=[];for(let i of e.excluded)t.push(_n(i.path,n)?i:{path:i.path,rule:"out-of-app-scope"});for(let i of e.included)_n(i,n)||t.push({path:i,rule:"out-of-app-scope"});return t.sort($a)}function qa(e,n,t,i){let o=`${t}/ui-plugin.json`;if(!i.includes(o))throw h("APP_UI_MANIFEST_INVALID","selected screen App has no package ui-plugin.json");let r=En(e,o),s=bt(r),a;try{a=JSON.parse(Buffer.from(r).toString("utf8"));}catch{throw h("APP_UI_MANIFEST_INVALID","ui-plugin.json is not valid JSON")}let p;try{let I=Ee(a,{mode:"local"});if(I.manifestVersion!==2)throw new Error("screen App requires manifestVersion 2");p=I;}catch(I){throw I instanceof K?h("APP_UI_MANIFEST_INVALID",I.code):h("APP_UI_MANIFEST_INVALID")}if(p.pluginId!==n.appId)throw h("APP_DEFINITION_CONFLICT","ui-plugin.json pluginId no longer matches the selected App");let c=`${t}/ui/index.html`;if(!i.includes(c))throw h("APP_UI_MANIFEST_INVALID","screen entry is outside package scope");let l=bt(En(e,c)),f=JSON.parse(JSON.stringify(a));if(f.entryHash=l,Object.prototype.hasOwnProperty.call(f,"initialState")){let I=f.initialState;if(!Ga(I)||I.path!=="ui/state.json")throw h("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 h("APP_INITIAL_STATE_OUT_OF_SCOPE","initialState reference is outside the selected package");let m=En(e,g);f.initialState={...I,hash:bt(m)};}try{let I=Ee(f,{mode:"published"});return {bytes:new Uint8Array(Buffer.from(Sn(I),"utf8")),sourceHash:s}}catch(I){throw I instanceof K?h("APP_UI_MANIFEST_INVALID",I.code):h("APP_UI_MANIFEST_INVALID")}}async function Za(e,n){let{included:t,excluded:i}=_t(e);Io(e,t,n);let o=eo(e,t,{version:n.version}),r=Tt(e,t);return {plan:{manifest:o,included:t,excluded:i,secretFindings:r},archiveOptions:{}}}async function Qa(e,n){Wa(n);let t=await Gi(e),i=Ka(t.items,n.appId);if(i.definitionHash!==n.expectedDefinitionHash)throw h("APP_DEFINITION_CONFLICT",`definitionHash changed for ${n.appId}`);let o=Xa(i),r=_t(e);if(r.excluded.some(g=>_n(g.path,o)&&(g.rule==="symlink"||g.rule==="symlink-dir")))throw h("PACKAGE_SYMLINK","selected App package contains a symlink");let s=r.included.filter(g=>_n(g,o)),a=Ya(r,o),p=new Map,c=new Map;if(i.capabilities.includes("screen")){let g=qa(e,i,o,s);p.set(`${o}/ui-plugin.json`,g.bytes),c.set(`${o}/ui-plugin.json`,g.sourceHash);}if(i.capabilities.includes("skill")&&!s.includes(`${o}/SKILL.md`))throw h("APP_SKILL_MISSING","skill capability requires package-root SKILL.md");Io(e,s,n,p);let l={appId:i.appId,version:n.version??"",description:i.description,capabilities:i.capabilities,packageRoot:o,...i.definition?.id===void 0?{}:{definitionId:i.definition.id},definitionHash:i.definitionHash,includedFiles:s,generatedFiles:p},f=no(e,l),I=Tt(e,s,p);return {plan:{manifest:f,included:s,excluded:a,secretFindings:I},archiveOptions:{generatedFiles:p,sourceFileHashes:c}}}async function go(e,n){let t=J.resolve(e);if(Ja(n))return Qa(t,n);if(n.expectedDefinitionHash!==void 0)throw h("APP_ID_REQUIRED");return Za(t,n)}async function Al(e,n={}){return (await go(e,n)).plan}function ec(e){let n=e.map(t=>`${t.path}:${t.line} (${t.rule})`).join(", ");throw new ue("PUBLISH_SECRET_FINDINGS",`aborted \u2014 secret findings must be resolved before packing: ${n}`)}async function mo(e,n={}){let t=J.resolve(e),i=await go(t,n);i.plan.secretFindings.length>0&&ec(i.plan.secretFindings);let o=await co(t,i.plan.manifest,i.archiveOptions);return {manifest:i.plan.manifest,tgzPath:o}}async function Il(e,n={}){return mo(e,n)}async function gl(e,n){let t=await mo(e,n);if(t.manifest.type!=="app")throw new Error("publish: App pack unexpectedly produced a template manifest");return t}
2
- export{za as DEFAULT_PUBLISH_MAX_BYTES,Ha as DEFAULT_PUBLISH_MAX_FILES,$i as EXCLUDE_RULES,xe as MARKETPLACE_API_PREFIX,ue as PublishError,gl as packApp,mo as packPublish,Il as packTemplate,Al as planPublish,Ba as uploadToMarketplace};
1
+ import*as J from'path';import {resolve,relative,sep,isAbsolute,join}from'path';import'url';import*as bt from'crypto';import {createHash}from'crypto';import*as G from'fs';import {constants,readFileSync,existsSync,statSync,readdirSync}from'fs';import {realpath,stat,readdir,open,lstat}from'fs/promises';import*as qi from'js-yaml';import {load}from'js-yaml';import*as ro from'os';import*as ao from'tar';import {gunzipSync,gzipSync}from'zlib';var j=(e,n)=>()=>(e&&(n=e(e=0)),n);var y=j(()=>{});var N,Ke=j(()=>{y();N=class extends Error{constructor(t,i=t,o){super(i);this.code=t;this.currentRevision=o;}code;currentRevision;name="UiRuntimeError"};});function Nn(e){return Eo.test(e)||To.test(e)}function X(){throw new N("INPUT_INVALID","JSON value is not projection-safe")}function No(e){let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function bn(e,n,t,i,o,r){if(n>i&&X(),e===null||typeof e=="string"||typeof e=="boolean")return typeof e=="string"&&(Do.test(e)||Po.test(e)&&!Lo(o,r)||bo.test(e))&&X(),e;if(typeof e=="number")return Number.isFinite(e)||X(),e;(typeof e!="object"||e===void 0||typeof e=="function"||typeof e=="bigint")&&X();let s=e;t.has(s)&&X(),t.add(s);try{if(Array.isArray(e))return e.map(p=>bn(p,n+1,t,i,o,r));No(s)||X();let a={};for(let[p,c]of Object.entries(e))Nn(p)&&X(),a[p]=bn(c,n+1,t,i,[...o,p],r);return a}finally{t.delete(s);}}function oe(e,n=0,t=[]){(!Number.isInteger(n)||n<0||n>Mo)&&X(),(!Array.isArray(t)||t.some(o=>typeof o!="string"))&&X();let i=bn(e,0,new Set,So+n,[],t);return (i===null||Array.isArray(i)||typeof i!="object")&&X(),i}function Pe(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 Lo(e,n){if(e.length===0)return false;let t=e.join(".");return n.some(i=>Pe(t,i))}function Ne(e){try{let n=JSON.stringify(e);return n===void 0&&X(),n}catch{X();}}function Pn(e){return Array.isArray(e)?e.map(Pn):e!==null&&typeof e=="object"?Object.fromEntries(Object.keys(e).sort().map(n=>[n,Pn(e[n])])):e}function Y(e){return Ne(Pn(e))}function Sn(e){return Buffer.byteLength(e,"utf8")}var Eo,To,Do,bo,Po,So,Mo,Ae=j(()=>{y();Ke();Eo=/(?:proof|token|secret|password|cookie|authorization|private[_-]?key|stack|exception|plugin[_-]?text)/i,To=/(?:url|uri|endpoint|path|file(?:name|path)?|cwd|shell|directory|dir|folder)$/i,Do=/<\/?[A-Za-z][^>]*>/,bo=/^(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)/,Po=/^(?:https?|file|ftp|ws|wss):\/\//i;So=8,Mo=4;});function Mn(e){return Y(e)}var St=j(()=>{y();Ae();});var Ie,Ln=j(()=>{y();Ie="window";});function Se(e){return Oo.has(e)||Uo.test(e)||Ro.test(e)}var Mt,Oo,Uo,Ro,Xe,ve,re,On,Un,Rn,wn,kn,Me=j(()=>{y();Mt=["__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"],Oo=new Set(Mt),Uo=/(?:proof|token|secret|password|cookie|authorization|private[_-]?key|stack|exception|plugin[_-]?text)/i,Ro=/(?:url|uri|endpoint|path|file(?:name|path)?|cwd|shell|directory|dir|folder)$/i;Xe=/^[A-Za-z0-9_]+$/,ve=/^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)*$/,re=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,On=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/,Un=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,Rn=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/,wn=["blue","violet","emerald","amber","rose","sky","slate","indigo"],kn=["inline","panel"];});function Cn(e){return typeof e=="string"&&Lt.includes(e)}var Lt,Ot=j(()=>{y();Me();Lt=["text/plain","application/json"];});function Ye(e){if(!xn(e))return false;let n=Object.keys(e);return !(n.some(t=>t!=="in"&&t!=="out")||n.length===0||Object.hasOwn(e,"in")&&!wo(e.in)||Object.hasOwn(e,"out")&&!ko(e.out))}function wo(e){return xn(e)?Object.keys(e).every(t=>t==="mediaType"||t==="required")&&Object.hasOwn(e,"mediaType")&&Cn(e.mediaType)&&(!Object.hasOwn(e,"required")||typeof e.required=="boolean"):false}function ko(e){return xn(e)?Object.keys(e).every(t=>t==="mediaType"||t==="range")&&Object.hasOwn(e,"mediaType")&&Cn(e.mediaType)&&(!Object.hasOwn(e,"range")||typeof e.range=="boolean"):false}function xn(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}var vn=j(()=>{y();Ot();new TextDecoder("utf-8",{fatal:true,ignoreBOM:true});});function d(e,n=e){throw new W(e,n)}function V(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;try{let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}catch{return false}}function O(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function F(e,n,t=[]){let i=new Set([...n,...t]);Object.keys(e).some(o=>!i.has(o))&&d("MANIFEST_INVALID"),n.some(o=>!O(e,o))&&d("MANIFEST_INVALID");}function nn(e,n=false,t=false,i=false){return jo.test(e)||!i&&Fo.test(e)||Vo.test(e)||t&&Ut.test(e)||Bo.test(e)&&!(n&&/^\s*data:/i.test(e)&&!Ut.test(e))}function Qe(e,n=new Set,t=0,i=false,o=false){if(typeof e=="string"){nn(e,i,o)&&d("UNSAFE_VALUE");return}if(!(e===null||typeof e!="object")){(t>8||n.has(e))&&d("MANIFEST_INVALID"),n.add(e);try{if(Array.isArray(e)){for(let r of e)Qe(r,n,t+1);return}V(e)||d("MANIFEST_INVALID");for(let[r,s]of Object.entries(e))Qe(s,n,t+1,i&&t===0&&(r==="name"||r==="description"),o);}finally{n.delete(e);}}}function ee(e,n){let t=e[n];return typeof t!="string"&&d("MANIFEST_INVALID"),t}function Z(e,n,t){let i=e[n];return (!Number.isSafeInteger(i)||i<t)&&d("MANIFEST_INVALID"),i}function jn(e){return vo.test(e)||d("MANIFEST_INVALID"),e}function Le(e){return xo.test(e)||d("TOKEN_INVALID"),e}function ar(e){return Ft.test(e)||d("MANIFEST_INVALID"),e}function cr(e){V(e)||d("MANIFEST_INVALID");let n={};for(let[t,i]of Object.entries(e)){let o=ar(t);V(i)||d("MANIFEST_INVALID");let r=i.type;if(r==="text"){F(i,["type","maxLength"]),n[o]={type:r,maxLength:Z(i,"maxLength",1)};continue}if(r==="text-list"){F(i,["type","max","itemMaxLength"]),n[o]={type:r,max:Z(i,"max",0),itemMaxLength:Z(i,"itemMaxLength",1)};continue}if(r==="step-list"){F(i,["type","min","max","labelMaxLength","detailMaxLength"]);let s=Z(i,"min",0),a=Z(i,"max",1);s>a&&d("MANIFEST_INVALID"),n[o]={type:r,min:s,max:a,labelMaxLength:Z(i,"labelMaxLength",1),detailMaxLength:Z(i,"detailMaxLength",1)};continue}typeof r=="string"&&d("SCHEMA_TYPE_UNSUPPORTED"),d("MANIFEST_INVALID");}return n}function pr(e,n,t){let i=e[n];(!i||i.type!==t)&&d("MANIFEST_INVALID");}function qe(e,n,t){let i=ee(e,"field");return Ft.test(i)||d("MANIFEST_INVALID"),pr(n,i,t),i}function dr(e,n){V(e)||d("MANIFEST_INVALID");let t=e.primitive;switch(typeof t!="string"&&d("MANIFEST_INVALID"),sr.includes(t)||d("PRIMITIVE_UNKNOWN"),t){case "card-shell":return F(e,["primitive"]),{primitive:t};case "meta-banner":return F(e,["primitive","badgeToken","noticeToken"]),{primitive:t,badgeToken:Le(ee(e,"badgeToken")),noticeToken:Le(ee(e,"noticeToken"))};case "heading":return F(e,["primitive","field"]),{primitive:t,field:qe(e,n,"text")};case "labeled-text":return F(e,["primitive","titleToken","field","variant"]),e.variant!=="callout"&&d("MANIFEST_INVALID"),{primitive:t,titleToken:Le(ee(e,"titleToken")),field:qe(e,n,"text"),variant:"callout"};case "step-flow":return F(e,["primitive","titleToken","field"]),{primitive:t,titleToken:Le(ee(e,"titleToken")),field:qe(e,n,"step-list")};case "text-list":{F(e,["primitive","titleToken","field"],["emptyToken","hideWhenEmpty"]);let i={primitive:t,titleToken:Le(ee(e,"titleToken")),field:qe(e,n,"text-list")};return O(e,"emptyToken")&&(i.emptyToken=Le(ee(e,"emptyToken"))),O(e,"hideWhenEmpty")&&(typeof e.hideWhenEmpty!="boolean"&&d("MANIFEST_INVALID"),i.hideWhenEmpty=e.hideWhenEmpty),i}}return d("MANIFEST_INVALID")}function lr(e,n){return Array.isArray(e)||d("MANIFEST_INVALID"),e.map(t=>dr(t,n))}function B(e="v2 manifest exceeds a contract limit"){return d("LIMIT_EXCEEDED",e)}function q(e="initial state is not projection-safe"){return d("INITIAL_STATE_INVALID",e)}function Rt(e,n){return (typeof e!="string"||e.length===0||e.length>4096||e.trim().length===0||ir.test(e)||or.test(e))&&d("MANIFEST_INVALID",`${n} is invalid`),(nn(e,true,true)||Ho.test(e)||zo.test(e)||Go.test(e))&&d("UNSAFE_VALUE",`${n} contains an unsafe value`),e}function Vn(e,n){return (typeof e!="string"||!re.test(e))&&d("MANIFEST_INVALID",`${n} is invalid`),e}function ur(e){return (typeof e!="string"||!On.test(e)||e==="*"||e==="all")&&d("MANIFEST_INVALID","action capability is invalid"),e}function Bt(e){return (typeof e!="string"||!tr.test(e))&&d("MANIFEST_INVALID","resource hash is invalid"),e}function Fn(e,n=new Set,t=0){if(typeof e=="string"){e.length>4096&&B("v2 manifest string is too long");return}if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){Number.isFinite(e)||d("MANIFEST_INVALID","v2 manifest contains a non-finite number");return}(e===void 0||typeof e=="function"||typeof e=="bigint")&&d("MANIFEST_INVALID","v2 manifest contains a non-JSON value"),typeof e!="object"&&d("MANIFEST_INVALID"),t>8&&B("v2 manifest nesting is too deep"),n.has(e)&&d("MANIFEST_INVALID","v2 manifest contains a cycle"),n.add(e);try{if(Array.isArray(e)){e.length>128&&B("v2 manifest array is too long");for(let i of e)Fn(i,n,t+1);return}V(e)||d("MANIFEST_INVALID","v2 manifest contains a non-plain object");for(let i of Object.values(e))Fn(i,n,t+1);}finally{n.delete(e);}}}function Ht(e){return (typeof e!="string"||e.length>4096||!ve.test(e))&&(typeof e=="string"&&e.length>4096&&B("projection path is too long"),d("MANIFEST_INVALID","projection paths must be canonical exact paths")),e.split(".").some(t=>Se(t))&&d("MANIFEST_INVALID","projection paths cannot address reserved state keys"),e}function Bn(e){V(e)||d("MANIFEST_INVALID","projection policy must be an object"),F(e,["allow"]),Array.isArray(e.allow)||d("MANIFEST_INVALID","projection allow must be an array"),e.allow.length>128&&B("projection allowlist is too long");let n=[],t=new Set;for(let i of e.allow){let o=Ht(i);t.has(o)&&d("MANIFEST_INVALID","projection allowlist contains a duplicate path"),t.add(o),n.push(o);}return {allow:n}}function fr(e,n){if(e===void 0)return;Array.isArray(e)||d("MANIFEST_INVALID","dataPaths must be an array"),e.length>rr&&B("dataPaths exceed the v2 limit");let t=[],i=new Set;for(let o of e){let r=Ht(o);i.has(r)&&d("MANIFEST_INVALID","dataPaths contain a duplicate path"),n.some(s=>Pe(r,s))||d("MANIFEST_INVALID","dataPaths must be projection-allowed"),i.add(r),t.push(r);}return t}function Oe(e,n,t=Number.MAX_SAFE_INTEGER){return (!Number.isSafeInteger(e)||e<0||e>t)&&d("MANIFEST_INVALID",`${n} is invalid`),e}function wt(e,n){return (typeof e!="number"||!Number.isFinite(e))&&d("MANIFEST_INVALID",`${n} is invalid`),e}function Hn(e,n=0,t=new Set){if(typeof e=="string")return (e.length>4096||nn(e))&&d("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)||d("MANIFEST_INVALID","schema enum contains a non-finite number"),e;(n>8||typeof e!="object"||e===void 0)&&B("schema enum is too deep"),t.has(e)&&d("MANIFEST_INVALID","schema enum contains a cycle"),t.add(e);try{if(Array.isArray(e))return e.length>128&&B("schema enum array is too long"),e.map(o=>Hn(o,n+1,t));V(e)||d("MANIFEST_INVALID","schema enum contains a non-plain object");let i={};for(let[o,r]of Object.entries(e))Se(o)&&d("MANIFEST_INVALID","schema enum contains a reserved key"),i[o]=Hn(r,n+1,t);return i}finally{t.delete(e);}}function yr(e,n){if(e===void 0)return;Array.isArray(e)||d("MANIFEST_INVALID","schema required must be an array"),e.length>64&&B("schema required list is too long");let t=[],i=new Set;for(let o of e)(typeof o!="string"||!ve.test(o))&&d("MANIFEST_INVALID","schema required contains an invalid key"),o.length>4096&&B("schema required key is too long"),i.has(o)&&d("MANIFEST_INVALID","schema required contains a duplicate key"),n&&!Object.prototype.hasOwnProperty.call(n,o)&&d("MANIFEST_INVALID","schema required references an undeclared property"),i.add(o),t.push(o);return t}function Ar(e,n){let t=n?ve:Xe;return e.length>4096&&B("schema property name is too long"),(!t.test(e)||e.split(".").some(i=>Se(i)))&&d("MANIFEST_INVALID","schema property name is invalid"),e}function zn(e,n=0,t=false){V(e)||d("MANIFEST_INVALID","action inputSchema must be an object"),n>8&&B("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"&&d("SCHEMA_TYPE_UNSUPPORTED","action inputSchema type is unsupported"),d("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"),F(e,["type"],o.filter(a=>a!=="type"));let r={type:i};if(O(e,"enum")&&(Array.isArray(e.enum)||d("MANIFEST_INVALID","schema enum must be an array"),e.enum.length>128&&B("schema enum is too long"),r.enum=e.enum.map(a=>Hn(a))),i==="string"&&(O(e,"minLength")&&(r.minLength=Oe(e.minLength,"schema minLength",4096)),O(e,"maxLength")&&(r.maxLength=Oe(e.maxLength,"schema maxLength",4096)),r.minLength!==void 0&&r.maxLength!==void 0&&r.minLength>r.maxLength&&d("MANIFEST_INVALID","schema string length bounds are inverted")),(i==="number"||i==="integer")&&(O(e,"minimum")&&(r.minimum=wt(e.minimum,"schema minimum")),O(e,"maximum")&&(r.maximum=wt(e.maximum,"schema maximum")),r.minimum!==void 0&&r.maximum!==void 0&&r.minimum>r.maximum&&d("MANIFEST_INVALID","schema numeric bounds are inverted")),i==="array"&&(O(e,"minItems")&&(r.minItems=Oe(e.minItems,"schema minItems",128)),O(e,"maxItems")&&(r.maxItems=Oe(e.maxItems,"schema maxItems",128)),r.minItems!==void 0&&r.maxItems!==void 0&&r.minItems>r.maxItems&&d("MANIFEST_INVALID","schema array length bounds are inverted"),O(e,"items")&&(r.items=zn(e.items,n+1,false))),i==="object"){let a;if(O(e,"properties")){V(e.properties)||d("MANIFEST_INVALID","schema properties must be an object");let c=Object.entries(e.properties);c.length>64&&B("schema properties are too many"),a={};for(let[l,f]of c){let I=Ar(l,t);a[I]=zn(f,n+1,false);}r.properties=a;}O(e,"minProperties")&&(r.minProperties=Oe(e.minProperties,"schema minProperties",64)),O(e,"maxProperties")&&(r.maxProperties=Oe(e.maxProperties,"schema maxProperties",64)),r.minProperties!==void 0&&r.maxProperties!==void 0&&r.minProperties>r.maxProperties&&d("MANIFEST_INVALID","schema object property bounds are inverted");let p=yr(e.required,a);p!==void 0&&(r.required=p),O(e,"additionalProperties")&&(e.additionalProperties!==false&&d("MANIFEST_INVALID","schema additionalProperties must be false"),r.additionalProperties=false);}let s=JSON.stringify(r);return (s===void 0||Buffer.byteLength(s,"utf8")>65536)&&B("action inputSchema subtree is too large"),r}function Ir(e){let n=zn(e,0,true);return (n.type!=="object"||!n.properties)&&d("MANIFEST_INVALID","action inputSchema must declare object properties"),n}function gr(e){if(V(e)||d("MANIFEST_INVALID","action backend must be an object"),e.type==="core"){F(e,qo);let n=e.handler;return (typeof n!="string"||!Un.test(n))&&d("MANIFEST_INVALID","core backend handler is invalid"),{type:"core",handler:n}}if(e.type==="skill"){F(e,Zo,Qo),(!Array.isArray(e.command)||e.command.length===0||e.command.length>16)&&d("MANIFEST_INVALID","skill backend command is invalid");let n=[];for(let i of e.command)(typeof i!="string"||i.length===0||i.length>256||!Rn.test(i))&&d("MANIFEST_INVALID","skill backend command token is invalid"),n.push(i);let t=O(e,"env")?hr(e.env):void 0;return {type:"skill",command:n,...t===void 0?{}:{env:t}}}d("MANIFEST_INVALID","action backend type is unsupported");}function mr(e){V(e)||d("MANIFEST_INVALID","action must be an object"),F(e,Ko,Xo),O(e,"_meta")&&zt(e._meta);let n=Vn(e.actionId,"actionId");Nn(n)&&d("MANIFEST_INVALID",`actionId "${n}" is not projection-safe`);let t=ur(e.capability),i=e.mutation;typeof i!="boolean"&&d("MANIFEST_INVALID","action mutation must be boolean");let o=Ir(e.inputSchema),r;if(O(e,"dataInputs")){Array.isArray(e.dataInputs)||d("MANIFEST_INVALID","action dataInputs must be an array");let l=o.properties,f=new Set,I=[];for(let g of e.dataInputs)(typeof g!="string"||!O(l,g)||f.has(g))&&d("MANIFEST_INVALID","action dataInputs must be unique declared properties"),f.add(g),I.push(g);r=I;}let s=Bn(e.resultProjection),a=gr(e.backend),p;O(e,"content")&&((a.type!=="skill"||!Ye(e.content))&&d("MANIFEST_INVALID","action content declaration is invalid"),p=_r(e.content));let c;if(O(e,"confirmation")){let l=e.confirmation;l!=="none"&&l!=="native"&&d("MANIFEST_INVALID","action confirmation is invalid"),c=l;}return {actionId:n,capability:t,mutation:i,inputSchema:o,resultProjection:s,backend:a,...p===void 0?{}:{content:p},...r===void 0?{}:{dataInputs:r},...c===void 0?{}:{confirmation:c}}}function hr(e){(!Array.isArray(e)||e.length===0)&&d("MANIFEST_INVALID","skill backend env is invalid");let n=new Set,t=[];for(let i of e)(i!=="CREWX_APP_INSTANCE_ID"&&i!=="CREWX_THREAD_ID"||n.has(i))&&d("MANIFEST_INVALID","skill backend env is invalid"),n.add(i),t.push(i);return Object.freeze(t)}function _r(e){return Object.freeze({...e.in===void 0?{}:{in:Object.freeze({...e.in})},...e.out===void 0?{}:{out:Object.freeze({...e.out})}})}function Er(e){return V(e)||d("INITIAL_STATE_INVALID","initialState must be an object"),F(e,er,nr),e.path!=="ui/state.json"&&d("MANIFEST_INVALID","initialState path is not fixed"),O(e,"hash")?{path:"ui/state.json",hash:Bt(e.hash)}:{path:"ui/state.json"}}function Tr(e){let n=["wasm","terminal","htmlDocuments"];return (!V(e)||Object.keys(e).length===0||Object.keys(e).some(t=>!n.includes(t)||e[t]!==true))&&d("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 Dr(e,n){Qe(e,new Set,0,true,true),Fn(e),V(e)||d("MANIFEST_INVALID"),F(e,Jo,Wo),O(e,"_meta")&&zt(e._meta),e.manifestVersion!==2&&d("MANIFEST_INVALID");let t;O(e,"runtime")&&(t=Tr(e.runtime));let i=Vn(e.pluginId,"pluginId"),o=Vn(e.definitionId,"definitionId"),r=Z(e,"version",1),s=Rt(e.name,"name"),a=Rt(e.description,"description"),p;O(e,"icon")&&((typeof e.icon!="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(e.icon))&&d("MANIFEST_INVALID","icon is invalid"),p=e.icon);let c;O(e,"tone")&&((typeof e.tone!="string"||!wn.includes(e.tone))&&d("MANIFEST_INVALID","tone is invalid"),c=e.tone),e.entry!=="ui/index.html"&&d("MANIFEST_INVALID","entry path is not fixed");let l;O(e,"entryHash")&&(l=Bt(e.entryHash));let f;O(e,"initialState")&&(f=Er(e.initialState));let I;O(e,"usage")&&(e.usage!=="card"&&e.usage!=="window"&&d("MANIFEST_INVALID","usage is invalid"),I=e.usage);let g;O(e,"detailPanel")&&(typeof e.detailPanel!="boolean"&&d("MANIFEST_INVALID","detailPanel is invalid"),g=e.detailPanel);let m;if(O(e,"displayModes")){((I??Ie)!==Ie||!Array.isArray(e.displayModes)||e.displayModes.length===0)&&d("MANIFEST_INVALID","displayModes are only valid for window Apps");let R=new Set(["inline","floating","focused"]);(new Set(e.displayModes).size!==e.displayModes.length||e.displayModes.some(u=>typeof u!="string"||!R.has(u)))&&d("MANIFEST_INVALID","displayModes are invalid"),m=e.displayModes;}(I??Ie)===Ie&&g!==void 0&&d("MANIFEST_INVALID","detailPanel is card-only");let b=n.mode??"local";b!=="local"&&b!=="installed"&&b!=="published"&&d("MANIFEST_INVALID","manifest mode is invalid"),b!=="local"&&l===void 0&&d("MANIFEST_INVALID","installed manifests require entryHash"),b!=="local"&&f!==void 0&&f.hash===void 0&&d("MANIFEST_INVALID","installed manifests require initialState.hash"),(!Array.isArray(e.surfaces)||e.surfaces.length===0)&&d("MANIFEST_INVALID","surfaces are invalid"),e.surfaces.length>2&&B("surfaces exceed the v2 limit");let w=[],v=new Set;for(let R of e.surfaces)(typeof R!="string"||!kn.includes(R))&&d("MANIFEST_INVALID","surface is unsupported"),v.has(R)&&d("MANIFEST_INVALID","surfaces contain a duplicate"),v.add(R),w.push(R);V(e.size)||d("MANIFEST_INVALID","size must be an object"),F(e.size,["height"]);let T=Z(e.size,"height",1);T>720&&B("size.height exceeds the v2 limit");let P=Bn(e.stateProjection),C=e.summaryProjection===void 0?void 0:Bn(e.summaryProjection);C!==void 0&&C.allow.some(R=>!P.allow.includes(R))&&d("MANIFEST_INVALID","summaryProjection must be a subset of stateProjection.allow");let A=fr(e.dataPaths,P.allow);Array.isArray(e.actions)||d("MANIFEST_INVALID","actions must be an array"),e.actions.length>32&&B("actions exceed the v2 limit");let E=[],L=new Set;for(let R of e.actions){let u=mr(R);if(L.has(u.actionId)&&d("MANIFEST_INVALID","actions contain a duplicate actionId"),u.backend.type==="core"&&u.backend.handler==="state.set"){u.mutation||d("MANIFEST_INVALID","state.set actions must be mutations");for(let k of Object.keys(u.inputSchema.properties))P.allow.includes(k)||d("MANIFEST_INVALID","state.set input paths must be projection-allowed");}L.add(u.actionId),E.push(u);}return {manifestVersion:2,pluginId:i,definitionId:o,version:r,name:s,description:a,...p===void 0?{}:{icon:p},...c===void 0?{}:{tone:c},entry:"ui/index.html",...l===void 0?{}:{entryHash:l},...t===void 0?{}:{runtime:t},...f===void 0?{}:{initialState:f},...I===void 0?{}:{usage:I},...g===void 0?{}:{detailPanel:g},...m===void 0?{}:{displayModes:m},surfaces:w,size:{height:T},stateProjection:P,...C===void 0?{}:{summaryProjection:C},...A===void 0?{}:{dataPaths:A},actions:E}}function zt(e){V(e)||d("MANIFEST_INVALID","_meta must be an object");let n=JSON.stringify(e);(n===void 0||Buffer.byteLength(n,"utf8")>Yo)&&B("_meta exceeds the 4 KiB limit");}function br(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 Gn(e,n,t,i,o,r){if(typeof e=="string"){let s=o.length>0&&r.some(a=>Pe(o.join("."),a));return (e.length>4096||nn(e,false,false,s))&&q("state contains an unsafe string"),e}if(e===null||typeof e=="boolean")return e;if(typeof e=="number")return Number.isFinite(e)||q("state contains a non-finite number"),e;(e===void 0||typeof e!="object"||typeof e=="function"||typeof e=="bigint")&&q("state contains a non-JSON value"),t>8&&q("state is too deep"),n.has(e)&&q("state contains a cycle"),n.add(e);try{let s;if(Array.isArray(e))e.length>128&&q("state array is too long"),s=e.map(p=>Gn(p,n,t+1,65536,o,r));else {V(e)||q("state contains a non-plain object");let p={};for(let[c,l]of Object.entries(e))(c.length>4096||!Xe.test(c)||Se(c))&&(c.length>4096&&q("state key is too long"),q("state contains a reserved or invalid key")),p[c]=Gn(l,n,t+1,65536,[...o,c],r);s=p;}let a=JSON.stringify(s);return (a===void 0||Buffer.byteLength(a,"utf8")>i)&&q("state subtree is too large"),s}finally{n.delete(e);}}function Jn(e,n=[]){V(e)||q("initial state must be a JSON object");let t=Gn(e,new Set,0,65536,[],n);return (t===null||Array.isArray(t)||typeof t!="object")&&q(),t}function Pr(e,n={}){Qe(e),V(e)||d("MANIFEST_INVALID"),F(e,$o),e.manifestVersion!==1&&d("MANIFEST_INVALID");let t=jn(ee(e,"pluginId")),i=jn(ee(e,"definitionId")),o=Z(e,"version",1),r=Z(e,"primitiveSet",1),s=n.supportedPrimitiveSet??Co;(!Number.isSafeInteger(s)||s<1)&&d("MANIFEST_INVALID"),r>s&&d("PRIMITIVE_SET_UNSUPPORTED"),V(e.activation)||d("MANIFEST_INVALID"),F(e.activation,["kind","language"]),e.activation.kind!=="fenced-code"&&d("MANIFEST_INVALID");let a=jn(ee(e.activation,"language")),p=cr(e.schema),c=lr(e.layout,p);return {manifestVersion:1,pluginId:t,definitionId:i,version:o,primitiveSet:r,activation:{kind:"fenced-code",language:a},schema:p,layout:c}}function Nr(e,n={}){return V(e)||d("MANIFEST_INVALID"),Object.hasOwn(e,"lineage")&&d("MANIFEST_INVALID","lineage is only allowed in product bundle indexes"),e.manifestVersion===2?Dr(e,n):Pr(e,n)}function _e(e,n={}){try{return Nr(e,n)}catch(t){if(t instanceof W)throw t;return d("MANIFEST_INVALID")}}function Wn(e,n={}){let t=_e(e,n);return t.manifestVersion===2?br(t):t}var Co,xo,vo,Ft,jo,Vo,Fo,Bo,Ut,Ho,zo,Go,$o,Jo,Wo,Ko,Xo,Yo,qo,Zo,Qo,er,nr,tr,ir,or,rr,sr,W,Gt=j(()=>{y();Ln();Ae();vn();Me();Co=1,xo=/^[a-z][a-zA-Z0-9]*(\.[a-zA-Z0-9]+)+$/,vo=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,Ft=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,jo=/<\/?[A-Za-z][^>]*>/,Vo=/^(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)/,Fo=/^(?:https?|file|ftp|ws|wss):\/\//i,Bo=/^\s*(?:javascript|data):/i,Ut=/data:[^,\s]*,/i,Ho=/(?:https?|file|ftp|ws|wss):\/\//i,zo=/javascript:/i,Go=/(?:^[\s]*|[\s"'(=])(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)(?=[^\s"'<>])[^\s"'<>]*/,$o=["manifestVersion","pluginId","definitionId","version","primitiveSet","activation","schema","layout"],Jo=["manifestVersion","pluginId","definitionId","version","name","description","entry","surfaces","size","stateProjection","actions"],Wo=["_meta","icon","tone","entryHash","runtime","initialState","usage","detailPanel","displayModes","summaryProjection","dataPaths","focusedAiDataPaths"],Ko=["actionId","capability","mutation","inputSchema","resultProjection","backend"],Xo=["confirmation","dataInputs","content","_meta"],Yo=4*1024,qo=["type","handler"],Zo=["type","command"],Qo=["env"],er=["path"],nr=["hash"],tr=/^[0-9a-f]{64}$/,ir=/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/,or=/[\r\n]/,rr=16,sr=["card-shell","meta-banner","heading","labeled-text","step-flow","text-list"],W=class extends Error{constructor(t,i=t){super(i);this.code=t;}code;name="UiPluginValidationError"};});var Kn=j(()=>{y();St();Gt();Me();});function se(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=oe(t);return createHash("sha256").update(Y(i)).digest("hex")}function ae(e){if(!/^\d+$/.test(String(e.version))||e.version<1||e.id.length<1||e.id.length>128)throw new N("DEFINITION_UNSUPPORTED","UI definition is invalid");if(e.sourceHash!==void 0&&(typeof e.sourceHash!="string"||!Cr.test(e.sourceHash)))throw new N("DEFINITION_UNSUPPORTED","UI definition source hash is invalid");if(!/^[0-9a-f]{64}$/.test(e.hash)||se(e)!==e.hash)throw new N("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=>!vr(i)))throw new N("DEFINITION_UNSUPPORTED","UI action declaration is invalid");if(t.confirmation!==void 0&&t.confirmation!=="none"&&t.confirmation!=="native")throw new N("DEFINITION_UNSUPPORTED","UI action confirmation is invalid");if(t.inputKeys&&(!Array.isArray(t.inputKeys)||t.inputKeys.some(i=>typeof i!="string"||!i)))throw new N("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 N("DEFINITION_UNSUPPORTED","UI action data input declaration is invalid");if(t.resultProjection&&Yn(t.resultProjection),t.content!==void 0&&!Ye(t.content))throw new N("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 N("DEFINITION_UNSUPPORTED","UI action environment declaration is invalid")}if(e.renderer!==void 0&&(!e.renderer||e.renderer.length>128))throw new N("DEFINITION_UNSUPPORTED","UI definition renderer is invalid");if(e.surfaces&&(!Array.isArray(e.surfaces)||e.surfaces.some(n=>!n||n.length>64)))throw new N("DEFINITION_UNSUPPORTED","UI definition surfaces are invalid");if(e.usage!==void 0&&e.usage!=="card"&&e.usage!=="window")throw new N("DEFINITION_UNSUPPORTED","UI definition usage is invalid");if(e.detailPanel!==void 0&&typeof e.detailPanel!="boolean")throw new N("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 N("DEFINITION_UNSUPPORTED","UI definition displayModes are invalid");if(e.usage==="card"&&e.displayModes!==void 0)throw new N("DEFINITION_UNSUPPORTED","Card definitions cannot declare displayModes");if(e.usage==="window"&&e.detailPanel!==void 0)throw new N("DEFINITION_UNSUPPORTED","Window definitions cannot declare detailPanel");if(e.stateProjection&&Yn(e.stateProjection),e.summaryProjection){Yn(e.summaryProjection);let n=new Set(e.stateProjection?.allow??[]);if(e.summaryProjection.allow.some(t=>!n.has(t)))throw new N("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 N("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(xr(r,o==="readTool"),n.has(r.name))throw new N("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 N("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 N("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 N("DEFINITION_UNSUPPORTED","UI legacy agent access is invalid");if(e.legacy.actionTool!==void 0&&(!i||Object.keys(i).length===0))throw new N("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=>Pe(t,i))))throw new N("DEFINITION_UNSUPPORTED","UI definition dataPaths are invalid")}}function xr(e,n){if(!e||typeof e!="object"||Array.isArray(e))throw new N("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 N("DEFINITION_UNSUPPORTED","UI legacy tool metadata is invalid");try{let r=oe(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 p=oe(a.structuredContent);if(Sn(Ne(p))>4*1024)throw new Error("fixed result size")}}catch{throw new N("DEFINITION_UNSUPPORTED","UI legacy tool metadata is not projection-safe")}}function Yn(e){if(!Array.isArray(e.allow)||e.allow.some(n=>!/^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)*$/.test(n)))throw new N("DEFINITION_UNSUPPORTED","UI projection policy is invalid")}function vr(e){return e.length>0&&e.length<=128&&e!=="*"&&e!=="all"&&!/[/*]/.test(e)}var Cr,we=j(()=>{y();Ae();Ke();vn();Cr=/^[0-9a-f]{64}$/;});function rn(e,n=e){throw new ce(e,n)}var ce,sn=j(()=>{y();ce=class extends Error{constructor(t,i=t){super(i);this.code=t;}code;name="McpAppContractError"};});var Qt=j(()=>{y();});var ei=j(()=>{y();we();Ae();sn();Qt();});function ni(e,n){return jr.add(e),n!==void 0&&Vr.set(e,n),e}var jr,Vr,an=j(()=>{y();jr=new WeakSet,Vr=new WeakMap;});function Fe(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function qn(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 oi(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let n of Object.values(e))oi(n);return Object.freeze(e)}function $(e){throw new ne("LINEAGE_INVALID",e)}function Jr(e){throw new ne("LINEAGE_STALE",e)}function ri(e){if(!Fe(e)||!qn(e,Hr,zr)||!Fe(e.actions))return $("Lineage definition shape is invalid");for(let n of Object.values(e.actions))if(!Fe(n)||!qn(n,Gr,$r))return $("Lineage action definition shape is invalid");return e}function Wr(e){if(!Fe(e)||!qn(e,Fr,Br))return $("Lineage entry shape is invalid");if(!Number.isSafeInteger(e.version)||e.version<1||typeof e.hash!="string"||!ti.test(e.hash))return $("Lineage entry identity is invalid");if(e.sourceHash!==void 0&&(typeof e.sourceHash!="string"||!ti.test(e.sourceHash)))return $("Lineage source hash is invalid");if(e.compat!==void 0&&e.compat!=="break")return $("Lineage compatibility marker is invalid");let n=ri(e.definition);if(n.version!==e.version)return $("Lineage version does not match its definition");if(e.sourceHash!==void 0&&n.sourceHash!==e.sourceHash)return $("Lineage source hash does not match its definition");let t;try{t=se(n),ae({...n,hash:e.hash});}catch{return $("Lineage definition is invalid")}return t!==e.hash?$("Lineage definition hash does not match"):oi({version:e.version,hash:e.hash,definition:n,...e.sourceHash===void 0?{}:{sourceHash:e.sourceHash},...e.compat===void 0?{}:{compat:e.compat}})}function ii(e){return e.stateProjection?.allow??[]}function Kr(e,n){let t=[],i=new Set(ii(n));ii(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,p]of Object.entries(e.actions)){let c=n.actions[a];if(c&&(p.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(p=>!a.has(p))&&t.push("S5_SUMMARY_PROJECTION");}return t}function Xr(e,n){return Y(e)===Y(n)}function Zn(e,n){if(!Array.isArray(e)||e.length===0)return $("Definition lineage is missing");if(!Fe(n)||typeof n.hash!="string")return $("Current definition is invalid");let t,i;try{let{hash:a,...p}=n;i=ri(p),t={...i,hash:a},ae(t);}catch{return $("Current definition is invalid")}let o=e.map(Wr),r=o[0].definition.id;if(o.some(a=>a.definition.id!==r))return $("Lineage definition ids do not match");if(o.some((a,p)=>p>0&&a.version<=o[p-1].version))return $("Lineage generations are not in increasing version order");if(o.some((a,p)=>o.findIndex(c=>c.hash===a.hash)!==p))return $("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||!Xr(s.definition,i))return Jr("The last lineage generation does not match the current package");if(t.legacy!==void 0){let a=new Set(Object.keys(t.actions)),p=new Set;for(let l of o)if(l.sourceHash===void 0)for(let f of Object.keys(l.definition.actions))a.has(f)&&p.add(f);let c=Object.keys(t.legacy.agentAccess??{});if(c.length!==p.size||c.some(l=>!p.has(l))){let l="S4_LEGACY_AGENT_ACCESS_COMPLETE";throw new ne("LINEAGE_INVALID",`Lineage compatibility failed: ${l}`,[l])}}for(let a=0;a<o.length-1;a+=1){if(o.slice(a,-1).some(l=>l.compat==="break"))continue;let c=Kr(o[a].definition,t);if(c.length>0)throw new ne("LINEAGE_INVALID",`Lineage compatibility failed: ${c.join(", ")}`,c)}return Object.freeze({entries:Object.freeze(o),current:t})}var ne,ti,Fr,Br,Hr,zr,Gr,$r,Qn=j(()=>{y();we();Ae();ne=class extends Error{constructor(t,i=t,o=[]){super(i);this.code=t;this.violations=o;}code;violations;name="UiDefinitionLineageError"},ti=/^[0-9a-f]{64}$/,Fr=["version","hash","definition"],Br=["sourceHash","compat"],Hr=["id","version","actions"],zr=["sourceHash","usage","detailPanel","displayModes","renderer","surfaces","stateProjection","dataPaths","summaryProjection","legacy"],Gr=["capabilities"],$r=["inputKeys","dataInputs","confirmation","resultProjection","content","env"];});var si,ai,ci=j(()=>{y();si=["crewx_app_terminal_connect","crewx_app_html_viewer_open"],ai=["crewx_listWorkspaces","crewx_queryAgent","crewx_executeAgent","crewx_getTaskResult","crewx_listTasks","crewx_listAgents","callBrowser","openTab","listTabs","closeTab"];});var pi=j(()=>{y();we();an();});function et(e,n=0){try{let t=oe(e,n);return t.type!==void 0&&t.type!=="object"&&rn("TOOL_INVALID","MCP App inputSchema must describe an object"),t}catch(t){if(t instanceof ce)throw t;rn("TOOL_INVALID","MCP App inputSchema must be projection-safe JSON");}}function di(e){if(e.length===0)return et({type:"object",properties:{},additionalProperties:false});let n=e.map(i=>i.actionId),t=new Map;for(let i of e)t.set(i.actionId,et(i.inputSchema));return et(Zr(n,t),qr)}function Zr(e,n){let t=e.map(i=>({type:"object",properties:{actionId:{type:"string",const:i},input:n.get(i)??{type:"object"}},required:["actionId","input"],additionalProperties:false}));return Object.freeze({type:"object",oneOf:Object.freeze(t),properties:Object.freeze({actionId:Object.freeze({type:"string",enum:Object.freeze([...e])}),input:Object.freeze({type:"object"})}),required:Object.freeze(["actionId","input"]),additionalProperties:false})}var Be,qr,nt=j(()=>{y();ei();we();Ae();an();sn();Qn();ci();pi();Be=8*1024*1024,new Set(si),new Set(ai),qr=4;});function pe(e){let n=typeof e=="object"&&e!==null&&"code"in e?String(e.code):"";return n==="ENOENT"?new D("NOT_FOUND"):n==="ELOOP"?new D("PATH_ESCAPED"):n==="EFBIG"||n==="EOVERFLOW"?new D("LIMIT_EXCEEDED"):n==="EACCES"||n==="EPERM"||n==="ENOTDIR"?new D("READ_DENIED"):new D("READ_DENIED")}function os(e){if(typeof e!="string"||e.length===0||!isAbsolute(e))throw new D("READ_DENIED")}function li(e){if(typeof e!="string"||isAbsolute(e)||/[\\\u0000]/.test(e))throw new D("PATH_ESCAPED");if(e==="")return [];let n=e.split("/");if(n.some(t=>t.length===0||t==="."||t===".."))throw new D("PATH_ESCAPED");return n}function cn(e,n){let t=relative(e,n);return t===""||t!==".."&&!t.startsWith(`..${sep}`)&&!isAbsolute(t)}function pn(e){return {dev:e.dev,ino:e.ino,size:e.size,mtimeNs:e.mtimeNs,ctimeNs:e.ctimeNs}}function ot(e,n){return e.dev===n.dev&&e.ino===n.ino}function gi(e,n){return ot(e,n)&&e.size===n.size&&e.mtimeNs===n.mtimeNs&&e.ctimeNs===n.ctimeNs}async function ui(e){os(e);let n,t;try{n=await realpath(e),t=await stat(n,{bigint:!0});}catch(i){throw pe(i)}if(!t.isDirectory())throw new D("READ_DENIED");return {realRoot:n,identity:pn(t)}}async function rs(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 D("READ_DENIED")}catch(r){throw r instanceof D?r:pe(r)}if(!cn(n,o))throw new D("PATH_ESCAPED");return o}async function fi(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 pe(a)}if(!cn(n,r)||t!==void 0&&!cn(t,r))throw new D("PATH_ESCAPED");if(!o.isFile()||!s.isFile())throw new D("READ_DENIED");if(!ot(i,o)||!ot(i,s)||i.dev!==s.dev)throw new D("PATH_ESCAPED")}async function tt(e,n){let t,i;try{t=await realpath(e),i=await stat(t,{bigint:!0});}catch{throw new D("PATH_ESCAPED")}if(t!==n.realRoot||!gi(n.identity,pn(i)))throw new D("PATH_ESCAPED")}function ss(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 D,Ii,ts,is,dn,mi,st=j(()=>{y();D=class extends Error{constructor(t){super(t);this.code=t;}code;name="AppDiscoveryFsError"},Ii=constants.O_NOFOLLOW,ts=constants.O_NONBLOCK,is=constants.O_RDONLY|(Ii??0)|(ts??0);dn=class{async listDirectory(n,t){let i=li(t),o=await ui(n),r=resolve(n,...i),s,a;try{s=await realpath(r),a=await stat(s,{bigint:!0});}catch(p){let c=pe(p);if(c.code==="NOT_FOUND")return [];throw c}if(!cn(o.realRoot,s)||!a.isDirectory())throw new D("PATH_ESCAPED");try{let p=await readdir(s,{withFileTypes:!0,encoding:"utf8"});return await tt(n,o),p.map(ss)}catch(p){let c=pe(p);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 D("READ_DENIED");if(Ii===void 0)throw new D("UNSUPPORTED");let o=li(t),r=await ui(n),s=resolve(n,...o),a=relative(n,s);if(a===".."||a.startsWith(`..${sep}`)||isAbsolute(a))throw new D("PATH_ESCAPED");let p;try{p=await open(s,is);}catch(c){throw pe(c)}try{let c;try{let m=await p.stat({bigint:!0});c=pn(m);}catch(m){throw pe(m)}if(c.size>BigInt(i))throw new D("LIMIT_EXCEEDED");if(c.size>BigInt(Number.MAX_SAFE_INTEGER))throw new D("LIMIT_EXCEEDED");await tt(n,r);let l=await rs(n,r.realRoot,o);await fi(s,r.realRoot,l,c);let f=new Uint8Array(new ArrayBuffer(Number(c.size))),I=0;for(;I<f.byteLength;){let m;try{m=(await p.read(f,I,f.byteLength-I,I)).bytesRead;}catch(b){throw pe(b)}if(m<=0)throw new D("IDENTITY_CHANGED");I+=m;}let g;try{let m=await p.stat({bigint:!0});g=pn(m);}catch(m){throw pe(m)}if(!gi(c,g))throw new D("IDENTITY_CHANGED");return await fi(s,r.realRoot,l,g),await tt(n,r),new Uint8Array(f)}finally{await p.close().catch(()=>{});}}async readFileVerified(n,t,i){return this.readVerifiedFile(n,t,i)}},mi=new dn;});function Ge(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 _i(e){return typeof e=="string"&&re.test(e)?e:void 0}function fs(e){return e.length>0&&e!=="."&&e!==".."&&!/[\\/\u0000]/.test(e)}function Te(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 ys(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 As(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 Is(e){return ls.decode(e)}function gs(e){return JSON.parse(Is(e))}function Ei(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 ms(e){if(e instanceof D)return Ei(e.code);if(e!==null&&typeof e=="object"&&"code"in e){let n=e.code;if(typeof n=="string")return Ei(n)}}function de(e,n){let t=n();return Number.isFinite(t)&&Number.isFinite(e)&&t-e<=5e3}function hs(e){if(typeof e.readVerifiedFile=="function")return e.readVerifiedFile;if(typeof e.readFileVerified=="function")return e.readFileVerified}function _s(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 Ti(e,n,t,i){let o=hs(e);if(!o)throw new D("READ_DENIED");return As(await o.call(e,n,t,i))}async function pt(e,n,t){let i=_s(e);if(!i)throw new D("READ_DENIED");let o=await i.call(e,n,t);if(!Array.isArray(o))throw new D("READ_DENIED");return o.map(ys).filter(r=>r!==null)}function Es(e,n,t,i){return Object.freeze({code:e,...{},source:n,relativePath:t})}function Ts(e){if(!Ge(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(Te))};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 Ds(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 fn(e){return Object.freeze({appIds:Object.freeze([...new Set(e.map(n=>n.appId))].sort(Te)),definitionIds:Object.freeze([...new Set(e.map(n=>n.definition.id))].sort(Te))})}function un(e,n){let t=Object.keys(e).sort(Te),i=[...n].sort(Te);return t.length===i.length&&t.every((o,r)=>o===i[r])}function Di(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 bs(e){let n;try{n=gs(e);}catch{return}if(!Ge(n)||!un(n,["version","packages"])||n.version!==1||!Array.isArray(n.packages)||n.packages.length>dt)return;let t=new Set,i=new Set,o=0,r=[];for(let s of n.packages){if(!Ge(s))return;let a=["packageDir","appId","definition","files"],p=Object.hasOwn(s,"lineage"),c=Object.hasOwn(s,"launcher"),l=[...p?["lineage"]:[],...c?["launcher"]:[]];if(!un(s,[...a,...l])||c&&s.launcher!==false)return;let f=Di(s.packageDir),I=_i(s.appId);if(!f||f.length!==2||f[0]!=="apps"||!fs(f[1])||!I||t.has(s.packageDir)||!Ge(s.definition)||!un(s.definition,["id","version","hash"]))return;let g=_i(s.definition.id),m=s.definition.version,b=s.definition.hash;if(!g||!Number.isSafeInteger(m)||m<1||typeof b!="string"||!ct.test(b)||!Array.isArray(s.files)||s.files.length<2||s.files.length>lt)return;let w=new Set,v=[];for(let T of s.files){if(!Ge(T)||!un(T,["path","sha256"]))return;let P=Di(T.path);if(!P||typeof T.sha256!="string"||!ct.test(T.sha256))return;let C=P.join("/"),A=`${s.packageDir}/${C}`;if(w.has(C)||i.has(A))return;w.add(C),i.add(A),v.push(Object.freeze({path:C,sha256:T.sha256}));}if(!w.has("ui-plugin.json")||!w.has("ui/index.html")||(o+=v.length,o>cs))return;t.add(s.packageDir),r.push(Object.freeze({packageDir:s.packageDir,...c?{launcher:false}:{},appId:I,definition:Object.freeze({id:g,version:m,hash:b}),lineage:Array.isArray(s.lineage)?s.lineage:[],files:Object.freeze(v.sort((T,P)=>Te(T.path,P.path)))}));}return Object.freeze({version:1,packages:Object.freeze(r)})}function Ee(e){let n=ms(e);return n==="PATH_ESCAPED"||n==="IDENTITY_CHANGED"||n==="TOCTOU"?"PATH_ESCAPED":n==="LIMIT_EXCEEDED"?"LIMIT_EXCEEDED":"BUNDLE_INTEGRITY"}async function Ps(e,n,t,i,o){let r=[],s=async(a,p)=>{if(!de(i,o))throw new D("LIMIT_EXCEEDED");if(p>2)throw new D("LIMIT_EXCEEDED");let c=await pt(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 D("PATH_ESCAPED");let f=`${a}/${l.name}`;if(l.kind==="file"){if(r.push(f.slice(t.length+1)),r.length>lt)throw new D("LIMIT_EXCEEDED")}else if(l.kind==="directory")await s(f,p+1);else throw l.kind==="symlink"?new D("PATH_ESCAPED"):new D("READ_DENIED")}};return await s(t,0),r.sort(Te)}function Ns(e){return e==="ui-plugin.json"?262144:e==="ui/index.html"?Be:e==="ui/state.json"?65536:e.startsWith("ui/assets/")?ds:ps}async function bi(e,n,t,i){if(e===void 0)return {packages:[],diagnostics:[],incomplete:false,reservedIds:us};let o=Ts(e.reservedIds),r=[],s=(u,k,H)=>Es(u,"bundled",k),a=(u=[],k=false,H)=>({...H===void 0?{}:{indexHash:H},packages:u,diagnostics:r,incomplete:k,reservedIds:o});if(typeof e.root!="string"||e.root.length===0||typeof e.expectedIndexHash!="string"||!ct.test(e.expectedIndexHash))return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a();let p;try{p=await Ti(n,e.root,"bundle-index.json",as);}catch(u){return r.push(s(Ee(u),"bundle-index.json")),a()}let c=createHash("sha256").update(p).digest("hex");if(c!==e.expectedIndexHash)return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a();let l=bs(p);if(l===void 0)return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a();if(!Ds(fn(l.packages),o))return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a([],false,c);if(!de(t,i))return r.push(s("LIMIT_EXCEEDED","bundle-index.json")),a(l.packages.map(u=>({indexEntry:u,failureCode:"LIMIT_EXCEEDED"})),true,c);let f;try{f=await pt(n,e.root,"");}catch(u){return r.push(s(Ee(u),"bundle-index.json")),a(l.packages.map(k=>({indexEntry:k,failureCode:Ee(u)})),false,c)}if(!de(t,i))return r.push(s("LIMIT_EXCEEDED","bundle-index.json")),a(l.packages.map(u=>({indexEntry:u,failureCode:"LIMIT_EXCEEDED"})),true,c);let I=f.find(u=>u.name==="bundle-index.json"&&u.kind==="file"),g=f.find(u=>u.name==="apps"&&u.kind==="directory"),m=u=>l.packages.map(k=>({indexEntry:k,failureCode:u}));if(!I)return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a(m("BUNDLE_INTEGRITY"),false,c);let b=f.filter(u=>u.name!=="bundle-index.json"&&u.name!=="apps");if(b.length>0){let u=b.some(k=>k.kind==="symlink")?"PATH_ESCAPED":"BUNDLE_INTEGRITY";return r.push(s(u,"bundle-index.json")),a(m("BUNDLE_INTEGRITY"),false,c)}if(f.some(u=>u.name==="apps"&&u.kind!=="directory"))return r.push(s("PATH_ESCAPED","apps")),a(m("PATH_ESCAPED"),false,c);let w=[];if(g)try{w=await pt(n,e.root,"apps");}catch(u){return r.push(s(Ee(u),"apps")),a(m(Ee(u)),false,c)}if(!de(t,i)||w.length>dt)return r.push(s("LIMIT_EXCEEDED","apps")),a(m("LIMIT_EXCEEDED"),true,c);let v=new Map(l.packages.map(u=>[u.packageDir.slice(5),u])),T=w.filter(u=>!v.has(u.name));for(let u of T)r.push(s(u.kind==="symlink"?"PATH_ESCAPED":"BUNDLE_INTEGRITY",`apps/${u.name}`));if(T.length>0){let u=T.some(k=>k.kind==="symlink")?"PATH_ESCAPED":"BUNDLE_INTEGRITY";return a(m(u),false,c)}let P=new Set,C=new Map,A=new Map;for(let u of l.packages){let k=C.get(u.appId)??[];k.push(u),C.set(u.appId,k);let H=`${u.definition.id}\0${String(u.definition.version)}`,_=A.get(H)??[];_.push(u),A.set(H,_);}for(let u of [...C.values(),...A.values()])if(u.length>1)for(let k of u)P.add(k);let E=[],L=p.byteLength,R=false;for(let u of l.packages){if(!de(t,i)){R=true,E.push({indexEntry:u,failureCode:"LIMIT_EXCEEDED"});continue}let k;try{let x=u.lineage[u.lineage.length-1];if(!x)throw new ne("LINEAGE_INVALID","Definition lineage is missing");if(x.definition.id!==u.definition.id||x.version!==u.definition.version||x.hash!==u.definition.hash)throw new ne("LINEAGE_STALE","Last lineage generation does not match bundle identity");k=Zn(u.lineage,{...x.definition,hash:x.hash}).entries;}catch(x){let te=x instanceof ne?x.code:"LINEAGE_INVALID";r.push(s(te,u.packageDir)),E.push({indexEntry:u,failureCode:te});continue}let H=w.find(x=>x.name===u.packageDir.slice(5));if(!g||!H){E.push({indexEntry:u,failureCode:"BUNDLE_INTEGRITY"});continue}if(H.kind!=="directory"){E.push({indexEntry:u,failureCode:H.kind==="symlink"?"PATH_ESCAPED":"BUNDLE_INTEGRITY"});continue}let _;try{let x=await Ps(n,e.root,u.packageDir,t,i);if(!de(t,i)){R=!0,E.push({indexEntry:u,failureCode:"LIMIT_EXCEEDED"});continue}let te=u.files.map(Q=>Q.path);if(x.length!==te.length||x.some((Q,ge)=>Q!==te[ge])){E.push({indexEntry:u,failureCode:"BUNDLE_INTEGRITY"});continue}_=new Map;let ie;for(let Q of u.files){if(!de(t,i)){ie="LIMIT_EXCEEDED",R=!0;break}if(L>=at){ie="LIMIT_EXCEEDED";break}let ge;try{ge=await Ti(n,e.root,`${u.packageDir}/${Q.path}`,Ns(Q.path));}catch(_o){ie=Ee(_o);break}if(!de(t,i)){ie="LIMIT_EXCEEDED",R=!0;break}if(L+ge.byteLength>at){L=at,ie="LIMIT_EXCEEDED";break}if(L+=ge.byteLength,createHash("sha256").update(ge).digest("hex")!==Q.sha256){ie="BUNDLE_INTEGRITY";break}_.set(Q.path,ge);}if(ie!==void 0){E.push({indexEntry:u,failureCode:ie});continue}}catch(x){de(t,i)||(R=true),E.push({indexEntry:u,failureCode:Ee(x)});continue}E.push({indexEntry:u,lineage:k,files:_,...P.has(u)?{failureCode:"DUPLICATE_ID"}:{}});}return a(E,R,c)}var as,dt,lt,cs,ps,ds,at,ct,ls,us,ut=j(()=>{y();Qn();Me();nt();st();as=256*1024,dt=64,lt=128,cs=dt*lt,ps=2*1024*1024,ds=8*1024*1024,at=32*1024*1024,ct=/^[0-9a-f]{64}$/,ls=new TextDecoder("utf-8",{fatal:true}),us=Object.freeze({appIds:Object.freeze([]),definitionIds:Object.freeze([])});});function Ms(e){if(typeof e!="string"||!re.test(e))throw new TypeError("pluginId must be a safe UI plugin identifier");let n=`${ft}${e}`.length+7<=128?e:`hash_${createHash("sha256").update(e,"utf8").digest("hex")}`;return {read:`${ft}${n}_read`,action:`${ft}${n}_action`}}function $e(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 Ni(e){return typeof e=="string"&&re.test(e)?e:void 0}function Os(e,n){return n.length===0||n==="."||n===".."||/[\\/\u0000]/.test(n)?e==="skills"?"skills":"apps":`${e==="skills"?"skills":"apps"}/${n}`}function Us(e){return e.length>0&&e!=="."&&e!==".."&&!/[\\/\u0000]/.test(e)}function Ri(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 Rs(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 ws(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 wi(e){return Ls.decode(e)}function ki(e){return JSON.parse(wi(e))}function ks(e){if(!$e(e))return;let n=Ni(e.pluginId);if(!n)return;let t=Ni(e.definitionId),i=e.version,o=t&&Number.isSafeInteger(i)&&i>=1?`${t}\0${String(i)}`:void 0;return {pluginId:n,...o===void 0?{}:{definitionKey:o}}}function Cs(e){let n=ki(e);return {value:n,identity:ks(n)}}function gt(e,n,t,i){let o={code:e,...i===void 0?{}:{pluginId:i},source:n,relativePath:t};return Object.freeze(o)}function Si(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 De(e){if(e instanceof D)return Si(e.code);if(e!==null&&typeof e=="object"&&"code"in e){let n=e.code;if(typeof n=="string")return Si(n)}}function Je(e,n){return e==="PATH_ESCAPED"||e==="IDENTITY_CHANGED"||e==="TOCTOU"?"PATH_ESCAPED":e==="LIMIT_EXCEEDED"?"LIMIT_EXCEEDED":n==="manifest"&&e==="NOT_FOUND"?"MANIFEST_MISSING":n==="entry"?"ENTRY_INVALID":n==="initial"?"INITIAL_STATE_INVALID":"MANIFEST_INVALID"}function Mi(e){switch(e.code){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 Ci("UiPluginValidationError",e.code)}}function Ci(e,n){throw new Error(`Unmapped ${e} code: ${String(n)}`)}function yt(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 Ci("McpAppContractError",e)}}function At(e,n){let t=n();return Number.isFinite(t)&&Number.isFinite(e)&&t-e<=5e3}function xs(e){return {pluginId:e.appId,definitionKey:`${e.definition.id}\0${String(e.definition.version)}`}}function vs(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($e(o)){let r=o.bin,s=typeof r=="string"?r:$e(r)?Object.values(r).find(a=>typeof a=="string"):void 0;for(let a of [s,o.main]){if(typeof a!="string")continue;let p=js(a);if(p&&n.has(p))return p}}}catch{}return [`${e.slice(e.lastIndexOf("/")+1)}.js`,"index.js","main.js"].find(o=>n.has(o))}function js(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 Vs(){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 Li(e){return Object.freeze(Array.from(e))}async function It(e,n,t,i){if(n.pinnedFiles!==void 0){let o=n.pinnedFiles.get(t);if(o===void 0)throw new D("NOT_FOUND");if(o.byteLength>i)throw new D("LIMIT_EXCEEDED");return new Uint8Array(o)}return xi(e,n.root,`${n.relativePath}/${t}`,i)}function Fs(e,n,t){let i=createHash("sha256"),o=new TextEncoder().encode(Y(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 Bs(e,n){let t={...e.definition,sourceHash:n},i;try{i=se(t);}catch(r){throw r instanceof N&&r.code==="INPUT_INVALID"?new W("MANIFEST_INVALID","normalized definition is invalid"):r}let o={...t,hash:i};try{ae(o);}catch{throw new W("MANIFEST_INVALID","normalized definition is invalid")}return o}function Hs(e){return e.actions.some(n=>n.backend.type==="core"&&n.backend.handler!=="state.set")}function zs(e){if(typeof e.readVerifiedFile=="function")return e.readVerifiedFile;if(typeof e.readFileVerified=="function")return e.readFileVerified}function Gs(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 xi(e,n,t,i){let o=zs(e);if(!o)throw new D("READ_DENIED");return ws(await o.call(e,n,t,i))}async function $s(e,n,t){let i=Gs(e);if(!i)throw new D("READ_DENIED");let o=await i.call(e,n,t);if(!Array.isArray(o))throw new D("READ_DENIED");return o.map(Rs).filter(r=>r!==null)}function Js(e){let n=[];for(let t of [e.reserved,e.builtin])t&&n.push(t);return e.builtins&&"listMcpApps"in e.builtins?n.push(Oi(e.builtins)):e.builtins&&n.push(e.builtins),e.builtinCatalog&&n.push(Oi(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 Oi(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 le(e,n){e.diagnostic||(e.diagnostic=gt(n,e.source,e.relativePath,e.identity?.pluginId));}function Ws(e){let n=new Map;for(let i of e){let o=i.identity?.pluginId;if(o===void 0)continue;let r=n.get(o)??[];r.push(i),n.set(o,r);}for(let i of n.values()){if(i.length<2)continue;let o=i.filter(s=>s.provenance!==void 0);if(o.length>0){for(let s of i)s.provenance===void 0&&le(s,"RESERVED_ID");if(o.length>1)for(let s of o)le(s,"DUPLICATE_ID");continue}let r=i.filter(s=>s.source==="apps");if(r.length>1){for(let s of r)le(s,"DUPLICATE_ID");for(let s of i.filter(a=>a.source==="skills"))le(s,"DUPLICATE_ID");}else for(let s of i.filter(a=>a.source==="skills"))le(s,"DUPLICATE_ID");}let t=new Map;for(let i of e){if(i.diagnostic?.code==="RESERVED_ID")continue;let o=i.identity?.definitionKey;if(o===void 0)continue;let r=t.get(o)??[];r.push(i),t.set(o,r);}for(let i of t.values())if(i.length>1)for(let o of i)le(o,"DUPLICATE_ID");}function Ks(e,n,t){let i=new Set,o=new Set,r=new Set,s=new Set(t.appIds),a=new Set(t.definitionIds);for(let p of Js(n)){for(let c of p.appIds??[])typeof c=="string"&&i.add(c);for(let c of p.definitionIds??[])typeof c=="string"&&o.add(c);for(let c of p.toolNames??[])typeof c=="string"&&r.add(c);}for(let p of e){let c=p.candidate;if(!c)continue;if(i.has(c.pluginId)||o.has(c.definitionId)){le(p,"RESERVED_ID");continue}if(p.provenance===void 0&&(s.has(c.pluginId)||a.has(c.definitionId))){le(p,"RESERVED_ID");continue}[c.toolNames.read,c.toolNames.action].filter(f=>f!==void 0).some(f=>r.has(f))&&le(p,"DUPLICATE_ID");}}function Xs(e){return [...e].sort((n,t)=>{let i=Pi.indexOf(n.source)-Pi.indexOf(t.source);return i!==0?i:Ri(n.relativePath,t.relativePath)})}function U(e,n){e.diagnostic=gt(n,e.source,e.relativePath,e.identity?.pluginId);}async function Ui(e,n,t){if(t.byteLength>262144){U(n,"LIMIT_EXCEEDED");return}let i;try{i=Cs(t);}catch{U(n,"MANIFEST_INVALID");return}if(n.bundleIdentity===void 0)n.identity=i.identity;else if(i.identity?.pluginId!==n.bundleIdentity.appId||i.identity.definitionKey!==`${n.bundleIdentity.definitionId}\0${String(n.bundleIdentity.version)}`){U(n,"BUNDLE_INTEGRITY");return}if($e(i.value)&&i.value.builtinOnly===true){U(n,"RESERVED_ID");return}let o;try{let _=_e(i.value,{mode:"local"});if(_.manifestVersion!==2)throw new W("MANIFEST_INVALID","workspace App requires v2");o=_;}catch(_){if(_ instanceof W){U(n,Mi(_));return}if(_ instanceof ce){U(n,yt(_.code));return}if($e(_)&&typeof _.code=="string"){U(n,yt(_.code));return}throw _}let r={pluginId:o.pluginId,definitionKey:`${o.definitionId}\0${String(o.version)}`};if(n.bundleIdentity===void 0&&(n.identity=r),o.actions.length>0)try{di(o.actions.map(_=>({actionId:_.actionId,inputSchema:_.inputSchema})));}catch(_){if(_ instanceof ce){U(n,yt(_.code));return}throw _}let s;try{s=await It(e,n,"ui/index.html",Be);}catch(_){U(n,Je(De(_),"entry"));return}if(s.byteLength>Be){U(n,"LIMIT_EXCEEDED");return}let a;try{a=wi(s);}catch{U(n,"ENTRY_INVALID");return}if(s.byteLength===0||a.length===0){U(n,"ENTRY_INVALID");return}let p=createHash("sha256").update(s).digest("hex");if(o.entryHash!==void 0&&o.entryHash!==p){U(n,"ENTRY_INVALID");return}let c={},l,f;if(o.initialState!==void 0){try{l=await It(e,n,"ui/state.json",65536);}catch(_){U(n,Je(De(_),"initial"));return}if(l.byteLength>65536){U(n,"LIMIT_EXCEEDED");return}try{let _=ki(l),x=o.dataPaths??[],te=Jn(_,x);c=oe(te,0,x),Ne(c);}catch{U(n,"INITIAL_STATE_INVALID");return}if(f=createHash("sha256").update(l).digest("hex"),o.initialState.hash!==void 0&&o.initialState.hash!==f){U(n,"INITIAL_STATE_INVALID");return}}let I={...o,entryHash:p,...o.initialState===void 0?{}:{initialState:{path:"ui/state.json",hash:f}}},g=Wn(I),m=Fs(I,s,l??new Uint8Array),b;try{b=Bs(g,m);}catch(_){if(_ instanceof W){U(n,Mi(_));return}throw _}let w;if(n.bundleLineage!==void 0){let _=n.bundleLineage[n.bundleLineage.length-1];if(!_){U(n,"LINEAGE_INVALID");return}let{legacy:x,...te}=_.definition,{hash:ie,...Q}=b;if(Y(te)!==Y(Q)){U(n,"LINEAGE_STALE");return}if(x!==void 0&&(b={...b,legacy:x}),x!==void 0)try{b={...b,hash:se(b)},ae(b);}catch{U(n,"LINEAGE_INVALID");return}w=n.bundleLineage;}if(n.bundleIdentity!==void 0&&n.bundleIdentity.appId!==o.pluginId){U(n,"BUNDLE_INTEGRITY");return}if(n.bundleIdentity!==void 0&&(n.bundleIdentity.definitionId!==b.id||n.bundleIdentity.version!==b.version||n.bundleIdentity.definitionHash!==b.hash)){U(n,"LINEAGE_STALE");return}let v=Ms(o.pluginId),T=o.actions.length===0?{read:v.read}:v,P=ke(g),C=ke(I),A=ke(b),E=ke({...g.handlers}),L=Li(s),R=l===void 0?void 0:Li(l),u=Object.freeze({...n.provenance===void 0?{}:{provenance:n.provenance},entry:Object.freeze({path:"ui/index.html",hash:p,bytes:L}),...R===void 0?{}:{initialState:Object.freeze({path:"ui/state.json",hash:f,bytes:R})}}),k={appId:o.pluginId,pluginId:o.pluginId,definitionId:o.definitionId,version:o.version,relativePath:n.relativePath,manifest:C,normalized:P,name:o.name,description:o.description,...o.icon===void 0?{}:{icon:o.icon},...o.tone===void 0?{}:{tone:o.tone},definition:A,handlers:E,resources:u,html:a,entryBytes:L,entryHash:p,initialState:ke(c),...R===void 0?{}:{initialStateBytes:R},...f===void 0?{}:{initialStateHash:f},sourceHash:m,toolNames:Object.freeze(T)},H=n.provenance===void 0?{...k,source:n.source}:{...k,provenance:n.provenance,lineage:w??[]};n.candidate=Object.freeze(H),Hs(o)&&U(n,"EXEC_DENIED");}async function Ys(e,n){try{return await It(e,n,"ui-plugin.json",262144)}catch(t){if(De(t)==="NOT_FOUND")return;U(n,Je(De(t),"manifest"));return}}function qs(e,n,t,i=Ss,o=false){let r=Xs(e);Ws(r);let s=Object.freeze(r.filter(l=>l.candidate!==void 0&&l.diagnostic===void 0).map(l=>l.candidate)),a=Object.freeze(r.filter(l=>l.diagnostic!==void 0).map(l=>l.diagnostic)),p=o?Object.freeze({...t===void 0?{}:{indexHash:t},diagnostics:Object.freeze(a.filter(l=>l.source==="bundled").map(l=>Object.freeze({...l}))),reservedAppIds:Object.freeze([...i.appIds]),reservedDefinitionIds:Object.freeze([...i.definitionIds])}):void 0,c={apps:s,diagnostics:a,complete:n===void 0,...n===void 0?{}:{incompleteReason:n},...t===void 0?{}:{productBundleIndexHash:t},...p===void 0?{}:{productBundleSnapshotMetadata:p}};return Object.defineProperty(c,"candidates",{configurable:false,enumerable:false,get:()=>s}),Object.freeze(c)}function Zs(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 Qs(e,n){if(Zs(e))return {fs:e,options:{}};let t=e??n??{};return {fs:t.filesystem??t.fileSystem??t.fs??mi,options:t}}async function vi(e,n,t){if(typeof e!="string"||e.length===0)throw new TypeError("workspaceRoot must be explicit");let{fs:i,options:o}=Qs(n,t),r=o.clock??Vs,s=r(),a=[],p=0,c,l=await bi(o.productBundle,i,s,r);a.push(...l.diagnostics.map(g=>({source:g.source,root:o.productBundle?.root??e,name:"",relativePath:g.relativePath,diagnostic:g})));let f=l.reservedIds;l.incomplete&&(c="time_limit");for(let g of l.packages){let m=g.indexEntry,b=m.packageDir,w=g.files===void 0?void 0:vs(b,g.files),v=l.indexHash===void 0?void 0:ni(Object.freeze({kind:"bundled",launcher:m.launcher!==false,indexHash:l.indexHash,packageDir:b,appId:m.appId,definitionId:m.definition.id,version:m.definition.version,definitionHash:m.definition.hash,files:m.files}),w),T={source:"bundled",root:o.productBundle?.root??e,name:b.slice(5),relativePath:b,...v===void 0?{}:{provenance:v},...g.files===void 0?{}:{pinnedFiles:g.files},...g.lineage===void 0?{}:{bundleLineage:g.lineage},bundleIdentity:{appId:m.appId,definitionId:m.definition.id,version:m.definition.version,definitionHash:m.definition.hash},identity:xs(m)};if(a.push(T),p+=1,g.failureCode!==void 0){U(T,g.failureCode);continue}let P=g.files?.get("ui-plugin.json");if(P===void 0){U(T,"BUNDLE_INTEGRITY");continue}await Ui(i,T,P),T.candidate!==void 0&&T.diagnostic===void 0&&p<64&&!At(s,r)&&(c="time_limit");}let I=[{source:"apps",directory:"apps"},{source:"skills",directory:"skills"}];for(let g of I){let{source:m,directory:b}=g,w;try{w=await $s(i,e,b);}catch(T){if(De(T)==="NOT_FOUND")continue;a.push({source:m,root:e,name:"",relativePath:m,diagnostic:gt(Je(De(T),"manifest"),m,m)});continue}let v=w.filter(T=>T.kind==="directory"||T.kind==="symlink").filter(T=>Us(T.name)).map(T=>({source:m,root:e,name:T.name,relativePath:Os(m,T.name)})).sort((T,P)=>Ri(T.relativePath,P.relativePath));for(let T of v){let P={...T};a.push(P);let C;if(m==="skills"&&(C=await Ys(i,P),C===void 0))continue;if(p>=64){U(P,"LIMIT_EXCEEDED");continue}if(T.relativePath.split("/").length-1>2){U(P,"LIMIT_EXCEEDED");continue}if(c!==void 0||!At(s,r)){U(P,"LIMIT_EXCEEDED"),c="time_limit";continue}if(p+=1,C===void 0)try{C=await xi(i,P.root,`${P.relativePath}/ui-plugin.json`,262144);}catch(E){U(P,Je(De(E),"manifest"));continue}await Ui(i,P,C),P.diagnostic===void 0&&p<64&&!At(s,r)&&(c="time_limit");}}return Ks(a,o,f),qs(a,c,l.indexHash,f,o.productBundle!==void 0)}var Ss,ft,Pi,Ls,ji=j(()=>{y();we();Ke();Ae();Kn();Me();nt();sn();st();an();ut();ut();Ss=fn([]),ft="crewx_local_app_";Pi=["bundled","apps","skills"],Ls=new TextDecoder("utf-8",{fatal:true});});y();Kn();y();Ln();y();var $t="SKILL.md",Ur=/^---\s*\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;function Jt(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function Rr(e){return e.isDirectory()||e.isSymbolicLink()}function qt(e){try{return existsSync(e)&&statSync(e).isDirectory()}catch{return false}}function Xn(e){let n;try{n=readFileSync(e,"utf8");}catch{return {frontmatter:{},readable:false,valid:false,hasFrontmatter:false}}let t=n.match(Ur);if(!t)return {frontmatter:{},readable:true,valid:true,hasFrontmatter:false};try{let i=load(t[1]??"");if(!Jt(i))return {frontmatter:{},readable:!0,valid:!1,hasFrontmatter:!0};let o=Jt(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 wr(e){return [join(e,$t),join(e,"skill",$t)]}function Wt(e,n){if(!qt(e))return null;for(let t of wr(e)){if(!existsSync(t))continue;let o=Xn(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 Kt(e){try{return readdirSync(e,{withFileTypes:!0}).filter(Rr)}catch{return []}}function Xt(e,n,t){!e||n.has(e.name)||(n.add(e.name),t.push(e));}function Zt(e){let n=[],t=new Set;for(let i of e)if(qt(i))for(let o of Kt(i)){if(o.name.startsWith("@")){let r=join(i,o.name);for(let s of Kt(r))Xt(Wt(join(r,s.name),s.name),t,n);continue}Xt(Wt(join(i,o.name),o.name),t,n);}return n.sort((i,o)=>i.name.localeCompare(o.name))}ji();var na=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/;function In(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?ta(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 ta(e,n){let t=new TextEncoder().encode(gn(e)),i=ia(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 ia(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 gn(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 An(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 Bi(e,n){let t=relative(e,n).split(sep).join("/");return !t||t===".."||t.startsWith("../")||isAbsolute(t)?null:gn(t)}function oa(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 Hi(e){return Object.freeze({packageRoot:e})}function ra(e){return Object.freeze({id:e.definition.id,version:e.definition.version,hash:e.definition.hash,usage:e.definition.usage??Ie,...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 zi(e){return {capabilities:Object.freeze([...e]),origin:"local",ownership:"unknown",shareability:"unknown",sharingAvailability:"unavailable"}}function sa(e,n){let t=e.candidate,i=t.provenance!==void 0,o=n&&!i?["screen","skill"]:["screen"],r=ra(t),s=In(n?{screenHash:r.hash,skillHash:n.skillHash}:{screenHash:r.hash}),a=t.description||n?.skill.description||"",p=String(t.version),c={appId:t.pluginId,name:t.name,description:a,version:p,...zi(o),definition:r,...n===void 0||i?{}:{skillName:n.skill.name},...i?{provenance:t.provenance}:{localDefinitionRef:Hi(e.packageRoot)},definitionHash:s};return {...i?{}:{packageRoot:e.packageRoot},source:i?"bundled":t.source,appId:c.appId,capabilities:o,summary:Object.freeze(c)}}function aa(e){let n=ca(e.skill.name),t={appId:n,name:e.skill.name,description:e.skill.description??"",...e.skill.version===void 0?{}:{version:e.skill.version},...zi(["skill"]),skillName:e.skill.name,localDefinitionRef:Hi(e.packageRoot),definitionHash:In({skillHash:e.skillHash})};return {packageRoot:e.packageRoot,source:e.source,appId:n,capabilities:["skill"],summary:Object.freeze(t)}}function ca(e){return `skill.${e.replace(/^@/,"").replace(/\//g,".").replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,122)||"unnamed"}`}function z(e,n,t,i){return Object.freeze({code:e,source:n,relativePath:pa(t),...i===void 0?{}:{appId:i}})}function pa(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 Gi(e){return z(e.code,e.source,e.relativePath,e.pluginId)}function da(e,n){let t=Bi(e,n.dir);if(!t)return {diagnostic:z("PATH_ESCAPED","node_modules","node_modules")};let i=oa(t);if(!i)return {diagnostic:z("PATH_ESCAPED","node_modules",t)};let o=Xn(n.skillMdPath);if(!o.readable)return {diagnostic:z("SKILL_READ_FAILED",i,t)};if(!o.valid)return {diagnostic:z("SKILL_INVALID",i,t)};let r=la(n.dir,n.skillMdPath);if(!r)return {diagnostic:z("PATH_ESCAPED",i,t)};try{let s=new Uint8Array(readFileSync(n.skillMdPath));return {skill:n,packageRoot:t,relativeSkillPath:r,skillHash:In({relativePath:r,fileBytes:s}),source:i}}catch{return {diagnostic:z("SKILL_READ_FAILED",i,t)}}}function la(e,n){let t=relative(e,n).split(sep).join("/");try{return gn(t)}catch{return null}}function ua(e){if(!na.test(e.appId))return {diagnostic:z("BUILTIN_INVALID","builtin",`builtin/${e.appId||"unknown"}`)};let n=e.definition===void 0?void 0:{id:e.definition.id,version:e.definition.version,hash:e.definition.hash,usage:e.definition.usage??Ie,...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 fa(e){return e.builtinCatalog}function ya(e){let n=e.packageRoot??e.relativePath??e.packageRootPath;if(n===void 0)return null;try{return gn(n)}catch{return null}}function Aa(e){let n=e.marketplaceContentId;return typeof n=="string"&&n.length>0?n:void 0}function Ia(e,n,t){let i=n.installed??[],o=new Map;for(let s of i){let a=ya(s);if(!a){t.push(z("INSTALLED_IDENTITY_MISMATCH","installed","installed"));continue}let p=o.get(a);if(p&&JSON.stringify(p)!==JSON.stringify(s)){t.push(z("INSTALLED_IDENTITY_MISMATCH","installed",a));continue}o.set(a,s);}let r=new Map;for(let s of e)s.packageRoot!==void 0&&r.set(s.packageRoot,s);for(let[s,a]of o){let p=r.get(s);if(!p){t.push(z("INSTALLED_MISSING","installed",s,a.appId));continue}let c=Aa(a);if(!c){t.push(z("INSTALLED_CONTENT_ID_MISSING","installed",s,a.appId));continue}if(a.appId!==void 0&&a.appId!==p.appId||a.definitionHash!==void 0&&a.definitionHash!==p.summary.definitionHash){t.push(z("INSTALLED_IDENTITY_MISMATCH","installed",s,a.appId));continue}let l={...p.summary,origin:"installed",...a.slug===void 0?{}:{slug:a.slug},marketplaceContentId:c},f=e.indexOf(p);f>=0&&(e[f]={...p,summary:Object.freeze(l)});}}function ga(e,n){let t=new Map;for(let o of e){let r=t.get(o.appId)??[];r.push(o),t.set(o.appId,r);}let i=new Set;for(let o of t.values()){if(o.length<2)continue;let r=o.some(s=>s.source==="builtin")?"builtin":o.some(s=>s.source==="bundled")?"bundled":void 0;if(r!==void 0){let s=o.filter(a=>a.source===r);for(let a of o.filter(p=>p.source!==r))i.add(a),n.push(z("RESERVED_ID",a.source,ht(a),a.appId));if(s.length>1)for(let a of s)i.add(a),n.push(z("DUPLICATE_ID",a.source,ht(a),a.appId));continue}for(let s of o)i.add(s),n.push(z("DUPLICATE_ID",s.source,ht(s),s.appId));}return e.filter(o=>!i.has(o))}function ht(e){return e.packageRoot??e.summary.provenance?.packageDir??`builtin/${e.appId}`}function ma(e,n){return e.filter(t=>!(t.code==="MANIFEST_MISSING"&&n.has(t.relativePath))).map(Gi)}function ha(e){return e.filesystem}function _a(e,n){let t=ha(e),i=e.registeredProductBundle;return {...t===void 0?{}:{filesystem:t},...e.productBundle===void 0?{}:{productBundle:e.productBundle},...n===void 0?{}:{builtinCatalog:n},...i===void 0?{}:{reservedAppIds:i.reservedAppIds,reservedDefinitionIds:i.reservedDefinitionIds}}}async function $i(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=fa(n),i=await vi(e,_a(n,t)),o=n.registeredProductBundle??i.productBundleSnapshotMetadata,r=[join(e,"skills"),join(e,"node_modules"),join(e,"apps")],s=[],a=[],p=[],c=new Set;for(let A of r)for(let E of Zt([A])){let L=Bi(e,E.dir);(L===null||!c.has(L))&&(p.push(E),L!==null&&c.add(L));}for(let A of p){let E=da(e,A);"diagnostic"in E?s.push(E.diagnostic):a.push(E);}let l=new Map;for(let A of i.apps??i.candidates??[]){let E=A.provenance===void 0?`workspace\0${A.relativePath}`:`bundled\0${A.provenance.indexHash}\0${A.provenance.packageDir}`;l.set(E,{candidate:A,packageRoot:A.relativePath});}let f=new Map(a.map(A=>[A.packageRoot,A])),I=[];for(let A of l.values()){let E=A.candidate.provenance===void 0?f.get(A.packageRoot):void 0,L=sa(A,E);I.push({...L.packageRoot===void 0?{}:{packageRoot:L.packageRoot},source:L.source,appId:L.appId,summary:L.summary});}let g=new Set([...l.values()].filter(A=>A.candidate.provenance===void 0).map(A=>A.packageRoot)),m=o===void 0?new Set:new Set(i.diagnostics.filter(A=>A.code==="RESERVED_ID"&&A.source!=="bundled").map(A=>A.relativePath)),b=new Set(o?.reservedAppIds??[]);for(let A of a){let E=aa(A);if(!(g.has(A.packageRoot)||m.has(A.packageRoot))){if(b.has(E.appId)){s.push(z("RESERVED_ID",A.source,A.packageRoot,E.appId));continue}I.push({packageRoot:E.packageRoot,source:E.source,appId:E.appId,summary:E.summary});}}let w=[...ma(i.diagnostics,new Set(a.map(A=>A.packageRoot))),...s,...n.registeredProductBundle?.diagnostics.filter(A=>A.source==="bundled").map(Gi)??[]],v=[];if(t)for(let A of t.listMcpApps()){let E=ua(A);"diagnostic"in E?w.push(E.diagnostic):v.push(E);}let T=ga([...I,...v],w);Ia(T,n,w);let P=T.map(A=>A.summary).sort((A,E)=>An(A.appId,E.appId)),C=[...w].sort((A,E)=>An(A.relativePath,E.relativePath)||An(A.code,E.code)||An(A.appId??"",E.appId??""));return Object.freeze({items:Object.freeze(P),diagnostics:Object.freeze(C)})}y();y();y();function Ea(e){let n=o=>o.replace(/[.+^${}()|[\]\\]/g,"\\$&"),i=e.split("/").map(o=>o==="**"?".*":o.split("*").map(n).join("[^/]*"));return new RegExp(`^${i.join("\\/")}$`)}function Ce(e,n){try{return Ea(n).test(e)}catch{return false}}function mn(e,...n){let t=e.split("/");if(t.length<n.length)return false;let i=t.length-n.length;return n.every((o,r)=>Ce(t[i+r],o))}function Ta(e,n){return e.split("/").some(t=>Ce(t,n))}var Ji=[{label:".env*",test:e=>Ce(e,".env*")},{label:".git/",test:(e,n,t)=>t&&e===".git"},{label:"memory/",test:(e,n,t)=>t&&e==="memory"},{label:"*.key",test:e=>Ce(e,"*.key")},{label:"*.pem",test:e=>Ce(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&&mn(n,".crewx","threads")},{label:".crewx/crewx.db",test:(e,n,t)=>!t&&mn(n,".crewx","crewx.db")},{label:".crewx/*.log",test:(e,n,t)=>!t&&mn(n,".crewx","*.log")},{label:".crewx/publish/",test:(e,n,t)=>t&&mn(n,".crewx","publish")},{label:".crewx/",test:(e,n)=>Ta(n,".crewx")}];function hn(e,n,t){for(let i of Ji)if(i.test(e,n,t))return i.label;return null}function Tt(e){let n=[],t=[];function i(o,r,s){let a;try{a=G.readdirSync(o,{withFileTypes:!0});}catch{return}a.sort((p,c)=>p.name.localeCompare(c.name));for(let p of a){let c=r?`${r}/${p.name}`:p.name,l=J.join(o,p.name);if(p.isSymbolicLink()){let f;try{f=G.statSync(l);}catch{t.push({path:c,rule:"symlink"});continue}if(f.isDirectory()){t.push({path:c,rule:s??"symlink-dir"});continue}let I=s??hn(p.name,c,false);I?t.push({path:c,rule:I}):t.push({path:c,rule:"symlink"});continue}if(p.isDirectory()){let f=s??hn(p.name,c,true);i(l,c,f);continue}if(p.isFile()){let f=s??hn(p.name,c,false);f?t.push({path:c,rule:f}):n.push(c);}}}return i(e,"",null),n.sort(),t.sort((o,r)=>o.path<r.path?-1:o.path>r.path?1:0),{included:n,excluded:t}}y();var Da=[{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 ba(e){return e.includes(0)}function Dt(e,n,t){let i=[];for(let o of n){let r=J.join(e,o),s;try{let p=t?.get(o);s=p===void 0?G.readFileSync(r):Buffer.from(p);}catch{continue}if(ba(s))continue;s.toString("utf8").split(/\r\n|\r|\n/).forEach((p,c)=>{for(let{rule:l,regex:f}of Da)f.test(p)&&i.push({path:o,line:c+1,rule:l});});}return i}y();y();var ue=class extends Error{constructor(t,i){super(`publish: [${t}]${i?` ${i}`:""}`);this.code=t;}code;name="PublishError"};function h(e,n){return new ue(e,n)}var Yi=/^[a-z0-9-]+$/,Pa=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/,Na=/^[A-Za-z_][A-Za-z0-9_]*$/;function Sa(e){let n=J.join(e,"crewx.yaml");if(!G.existsSync(n))return {};let t;try{t=qi.load(G.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 Ma(e){return bt.createHash("sha256").update(e).digest("hex")}function Zi(e){let n;try{n=G.lstatSync(e);}catch{throw h("PACKAGE_FILE_INVALID",`file is not readable: ${J.basename(e)}`)}if(n.isSymbolicLink())throw h("PACKAGE_SYMLINK","symlink content is not publishable");if(!n.isFile())throw h("PACKAGE_FILE_INVALID","only regular files are publishable");return bt.createHash("sha256").update(new Uint8Array(G.readFileSync(e))).digest("hex")}function La(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 Qi(e){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||J.posix.isAbsolute(e)||e.split("/").some(n=>n===".."||n.length===0))throw h("PACKAGE_PATH_TRAVERSAL","manifest file path must be a non-empty POSIX relative path")}function Oa(e){if(!/^(?:apps|skills)\/[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(e))throw h("APP_PACKAGE_ROOT_INVALID","packageRoot must be apps/<safe-id> or skills/<safe-id>")}function eo(e){if(!Pa.test(e))throw new Error(`publish: invalid version "${e}" \u2014 must be semver (e.g. 1.0.0)`)}function no(e,n,t={}){let i=Sa(e),o=i.name??J.basename(e);if(!Yi.test(o))throw new Error(`publish: invalid name "${o}" \u2014 must match ${Yi} (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");eo(r);let s=Array.isArray(i.requiredEnv)?i.requiredEnv:[],a=[];for(let l of s){if(typeof l!="string"||!Na.test(l))throw new Error(`publish: requiredEnv must contain names only (no values), got "${String(l)}"`);a.push(l);}let p=n.map(l=>(Qi(l),{path:l,sha256:Zi(J.join(e,l))})).sort((l,f)=>l.path<f.path?-1:l.path>f.path?1:0),c={name:o,version:r,type:"template",description:i.description??"",files:p,requiredEnv:a};return i.crewxMinVersion&&(c.crewxMinVersion=i.crewxMinVersion),c}function Ua(e){let n=e.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"");if(!n)throw h("APP_PACKAGE_ROOT_INVALID","appId cannot produce a marketplace name");return n}function to(e,n){if(Oa(n.packageRoot),!n.version)throw new Error("publish: version is required for App publishing \u2014 pass opts.version");if(eo(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 h("APP_UI_MANIFEST_INVALID","screen App manifests require definitionId");for(let s of ["ui-plugin.json","ui/index.html"])if(!n.includedFiles.includes(`${i}${s}`))throw h("APP_UI_MANIFEST_INVALID",`screen App is missing ${s}`)}if(t.includes("skill")&&!n.includedFiles.includes(`${i}SKILL.md`))throw h("APP_SKILL_MISSING","skill capability requires package-root SKILL.md");let o=new Set,r=n.includedFiles.map(s=>{if(Qi(s),!s.startsWith(i))throw h("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?Zi(J.join(e,s)):Ma(a),...a===void 0?{}:{generated:true}}}).sort((s,a)=>La(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:Ua(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:[]}}y();function io(e){return bt.createHash("sha256").update(e).digest("hex")}function co(e,n){if(typeof n!="string"||n.length===0||n.includes("\\")||n.includes("\0")||J.posix.isAbsolute(n)||n.split("/").some(o=>o===".."||o.length===0))throw h("PACKAGE_PATH_TRAVERSAL","archive paths must be non-empty POSIX relative paths");let t=J.resolve(e),i=J.resolve(t,...n.split("/"));if(i!==t&&!i.startsWith(`${t}${J.sep}`))throw h("PACKAGE_PATH_TRAVERSAL","archive path escaped its root");return i}function oo(e,n){let t=co(e,n),i;try{i=G.lstatSync(t);}catch{throw h("PACKAGE_FILE_INVALID","manifest file is missing")}if(i.isSymbolicLink())throw h("PACKAGE_SYMLINK","symlink content is not publishable");if(!i.isFile())throw h("PACKAGE_FILE_INVALID","only regular files are publishable");return new Uint8Array(G.readFileSync(t))}async function po(e,n,t={}){let i=J.join(e,".crewx","publish");G.mkdirSync(i,{recursive:true});let o=J.join(i,`${n.name}-${n.version}.tgz`),r=J.join(i,`.${n.name}-${n.version}.${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}.tmp.tgz`),s=G.mkdtempSync(J.join(ro.tmpdir(),"crewx-publish-"));try{let a=new Set,p=[];for(let c of n.files){if(a.has(c.path))throw h("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 h("PACKAGE_GENERATED_FILE_MISSING","generated manifest file bytes are missing");if(t.sourceFileHashes?.has(c.path)){let g=oo(e,c.path);if(t.sourceFileHashes.get(c.path)!==io(g))throw h("PACKAGE_STAGED_BYTES_MISMATCH","workspace source changed before staging")}let f=l??oo(e,c.path);if(io(f)!==c.sha256)throw h("PACKAGE_STAGED_BYTES_MISMATCH",`staged bytes differ for ${c.path}`);let I=co(s,c.path);G.mkdirSync(J.dirname(I),{recursive:!0}),G.writeFileSync(I,new Uint8Array(f)),p.push(c.path);}G.writeFileSync(J.join(s,"manifest.json"),JSON.stringify(n,null,2)),await ao.create({gzip:!0,file:r,cwd:s,portable:!0,noMtime:!0},["manifest.json",...p]),G.renameSync(r,o);}finally{try{G.rmSync(r,{force:!0});}catch{}G.rmSync(s,{recursive:true,force:true});}return o}y();y();var xe="/api/v1";var ka=201,Ca=200,xa=409,Pt=401,lo={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 va(){return process.env.WI013_FAKE_UPLOAD==="1"}function ja(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 Va(e){return e.replace(/\/+$/,"")}async function We(e){try{return await e.json()}catch{return null}}function uo(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 Fa(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 Ba(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 fo(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(lo,r))continue;let s=r,a=s==="APP_NAME_CONFLICT"?`marketplace name is already in use: ${n}`:void 0;return h(lo[s],a)}}async function Ha(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=Va(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}${xe}/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 p=await We(a),c=Fa(p),l=Ba(p),f=r&&l!==void 0?l:i,I;if(a.status===ka)I="created";else if(r&&a.status===Ca){if(c===void 0)throw h("PUBLISH_CONTENT_ID_MISSING","App republish did not return an opaque contentId");I="existing";}else if(a.status===xa){if(r)throw fo(p,i)??h("APP_NAME_CONFLICT",`marketplace name is already in use: ${i}`);I="existing";}else throw a.status===Pt?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 g="not-needed",m=null;if(I==="existing"&&!r){let L;try{L=await fetch(`${n}${xe}/publisher/items`,{method:"GET",headers:{Authorization:`Bearer ${e.accessToken}`}});}catch{throw new Error("publish: [E_NETWORK] Publisher items request failed (network)")}let R=await We(L);if(L.status!==200)throw new Error(`publish: [E_HTTP] Publisher items request failed \u2014 HTTP ${L.status}`);let k=uo(R,"publisher items",L.status)?.items;if(!Array.isArray(k))throw new Error(`publish: [E_MALFORMED] Publisher items response is malformed (expected data.items[]) \u2014 HTTP ${L.status}`);let H=k.find(_=>!_||typeof _!="object"?false:_.slug===i);if(!H||typeof H.version!="string")throw new Error(`publish: [E_MALFORMED] Publisher items response does not contain slug "${i}" \u2014 HTTP ${L.status}`);if(m=H.version,m!==e.manifest.version){let _;try{_=await fetch(`${n}${xe}/publisher/items/${encodeURIComponent(i)}`,{method:"PUT",headers:{Authorization:`Bearer ${e.accessToken}`,"Content-Type":"application/json"},body:JSON.stringify({version:e.manifest.version})});}catch{throw new Error("publish: [E_NETWORK] Version update request failed (network)")}if(!_.ok)throw await We(_),_.status===Pt?new Error(`publish: [E_AUTH_EXPIRED] Authentication is expired or missing \u2014 please log in again (HTTP ${_.status})`):_.status===403?new Error(`publish: [E_FORBIDDEN] Version update is forbidden; only the item owner can update an existing item (HTTP ${_.status})`):new Error(`publish: [E_HTTP] Version update failed \u2014 HTTP ${_.status}`);g="applied";}}let b=G.readFileSync(e.tgzPath),w=va()?ja(b):b,v=new FormData;v.set("archive",new Blob([new Uint8Array(w)],{type:"application/gzip"}),`${f}-${e.manifest.version}.tgz`);let T=r&&c!==void 0?c:i,P;try{P=await fetch(`${n}${xe}/publisher/items/${encodeURIComponent(T)}/upload`,{method:"POST",headers:{Authorization:`Bearer ${e.accessToken}`},body:v});}catch{throw new Error("publish: [E_NETWORK] Upload request failed (network)")}if(P.status===Pt)throw new Error("publish: [E_AUTH_EXPIRED] Authentication is expired or missing \u2014 please log in again (HTTP 401)");if(!P.ok){let L=await We(P);if(r){let R=fo(L,f);if(R)throw R}throw new Error(`publish: [E_HTTP] Upload request failed \u2014 HTTP ${P.status}`)}let C=await We(P),A=uo(C,"upload",P.status),E=typeof A.contentId=="string"&&A.contentId.length>0?A.contentId:c;if(r&&E===void 0)throw h("PUBLISH_CONTENT_ID_MISSING","App upload did not return an opaque contentId");return {slug:f,version:e.manifest.version,...E===void 0?{}:{contentId:E},artifactChecksum:A.artifactChecksum,artifactSizeBytes:A.artifactSizeBytes,submitOutcome:I,versionUpdate:g,serverVersionBefore:m}}var za=1e4,Ga=100*1024*1024;function Nt(e){return bt.createHash("sha256").update(e).digest("hex")}function $a(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function En(e,n){if(!n||n.includes("\\")||n.includes("\0")||J.posix.isAbsolute(n)||n.split("/").some(r=>r===".."||r.length===0))throw h("PACKAGE_PATH_TRAVERSAL","workspace file path is not a safe relative path");let t=J.resolve(e,...n.split("/")),i=J.resolve(e);if(t!==i&&!t.startsWith(`${i}${J.sep}`))throw h("PACKAGE_PATH_TRAVERSAL","workspace file path escaped the workspace root");let o;try{o=G.lstatSync(t);}catch{throw h("PACKAGE_FILE_INVALID",`workspace file is missing: ${n}`)}if(o.isSymbolicLink())throw h("PACKAGE_SYMLINK",`symlink is not publishable: ${n}`);if(!o.isFile())throw h("PACKAGE_FILE_INVALID",`not a regular file: ${n}`);return new Uint8Array(G.readFileSync(t))}function Tn(e,n){return e===n||e.startsWith(`${n}/`)}function Ja(e,n){return e.path<n.path?-1:e.path>n.path?1:e.rule.localeCompare(n.rule)}function Ao(e,n,t){let i=e??n;if(!Number.isSafeInteger(i)||i<=0)throw new ue("PACKAGE_SIZE_LIMIT",`${t} must be a positive integer`);return i}function go(e,n,t,i){let o=Ao(t.maxFileCount??t.maxFiles,za,"max file count"),r=Ao(t.maxTotalBytes??t.maxBytes,Ga,"max total bytes");if(n.length>o)throw new ue("PACKAGE_SIZE_LIMIT",`package exceeds file count limit (${o})`);let s=0;for(let a of n){let p=i?.get(a);if(p!==void 0?s+=p.byteLength:s+=En(e,a).byteLength,s>r)throw new ue("PACKAGE_SIZE_LIMIT",`package exceeds byte limit (${r})`)}}function Wa(e){return e.appId!==void 0||e.expectedDefinitionHash!==void 0}function Ka(e){let n=e.appId!==void 0,t=e.expectedDefinitionHash!==void 0;if(!n&&t)throw h("APP_ID_REQUIRED","appId is required with expectedDefinitionHash");if(n&&!t)throw h("APP_DEFINITION_HASH_REQUIRED","expectedDefinitionHash is required with appId");if(!n||!t)throw h("APP_ID_REQUIRED")}function Xa(e,n){let t=e.filter(i=>i.appId===n);if(t.length===0)throw h("APP_NOT_FOUND",`no publishable App matches ${n}`);if(t.length!==1)throw h("APP_AMBIGUOUS",`more than one App matches ${n}`);return t[0]}function Ya(e){let n=e.localDefinitionRef?.packageRoot;if(!n||!/^(?:apps|skills)\/[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(n))throw h("APP_PACKAGE_ROOT_INVALID","selected App is not rooted in apps/<safe-id> or skills/<safe-id>");return n}function qa(e,n){let t=[];for(let i of e.excluded)t.push(Tn(i.path,n)?i:{path:i.path,rule:"out-of-app-scope"});for(let i of e.included)Tn(i,n)||t.push({path:i,rule:"out-of-app-scope"});return t.sort(Ja)}function Za(e,n,t,i){let o=`${t}/ui-plugin.json`;if(!i.includes(o))throw h("APP_UI_MANIFEST_INVALID","selected screen App has no package ui-plugin.json");let r=En(e,o),s=Nt(r),a;try{a=JSON.parse(Buffer.from(r).toString("utf8"));}catch{throw h("APP_UI_MANIFEST_INVALID","ui-plugin.json is not valid JSON")}let p;try{let I=_e(a,{mode:"local"});if(I.manifestVersion!==2)throw new Error("screen App requires manifestVersion 2");p=I;}catch(I){throw I instanceof W?h("APP_UI_MANIFEST_INVALID",I.code):h("APP_UI_MANIFEST_INVALID")}if(p.pluginId!==n.appId)throw h("APP_DEFINITION_CONFLICT","ui-plugin.json pluginId no longer matches the selected App");let c=`${t}/ui/index.html`;if(!i.includes(c))throw h("APP_UI_MANIFEST_INVALID","screen entry is outside package scope");let l=Nt(En(e,c)),f=JSON.parse(JSON.stringify(a));if(f.entryHash=l,Object.prototype.hasOwnProperty.call(f,"initialState")){let I=f.initialState;if(!$a(I)||I.path!=="ui/state.json")throw h("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 h("APP_INITIAL_STATE_OUT_OF_SCOPE","initialState reference is outside the selected package");let m=En(e,g);f.initialState={...I,hash:Nt(m)};}try{let I=_e(f,{mode:"published"});return {bytes:new Uint8Array(Buffer.from(Mn(I),"utf8")),sourceHash:s}}catch(I){throw I instanceof W?h("APP_UI_MANIFEST_INVALID",I.code):h("APP_UI_MANIFEST_INVALID")}}async function Qa(e,n){let{included:t,excluded:i}=Tt(e);go(e,t,n);let o=no(e,t,{version:n.version}),r=Dt(e,t);return {plan:{manifest:o,included:t,excluded:i,secretFindings:r},archiveOptions:{}}}async function ec(e,n){Ka(n);let t=await $i(e),i=Xa(t.items,n.appId);if(i.definitionHash!==n.expectedDefinitionHash)throw h("APP_DEFINITION_CONFLICT",`definitionHash changed for ${n.appId}`);let o=Ya(i),r=Tt(e);if(r.excluded.some(g=>Tn(g.path,o)&&(g.rule==="symlink"||g.rule==="symlink-dir")))throw h("PACKAGE_SYMLINK","selected App package contains a symlink");let s=r.included.filter(g=>Tn(g,o)),a=qa(r,o),p=new Map,c=new Map;if(i.capabilities.includes("screen")){let g=Za(e,i,o,s);p.set(`${o}/ui-plugin.json`,g.bytes),c.set(`${o}/ui-plugin.json`,g.sourceHash);}if(i.capabilities.includes("skill")&&!s.includes(`${o}/SKILL.md`))throw h("APP_SKILL_MISSING","skill capability requires package-root SKILL.md");go(e,s,n,p);let l={appId:i.appId,version:n.version??"",description:i.description,capabilities:i.capabilities,packageRoot:o,...i.definition?.id===void 0?{}:{definitionId:i.definition.id},definitionHash:i.definitionHash,includedFiles:s,generatedFiles:p},f=to(e,l),I=Dt(e,s,p);return {plan:{manifest:f,included:s,excluded:a,secretFindings:I},archiveOptions:{generatedFiles:p,sourceFileHashes:c}}}async function mo(e,n){let t=J.resolve(e);if(Wa(n))return ec(t,n);if(n.expectedDefinitionHash!==void 0)throw h("APP_ID_REQUIRED");return Qa(t,n)}async function gl(e,n={}){return (await mo(e,n)).plan}function nc(e){let n=e.map(t=>`${t.path}:${t.line} (${t.rule})`).join(", ");throw new ue("PUBLISH_SECRET_FINDINGS",`aborted \u2014 secret findings must be resolved before packing: ${n}`)}async function ho(e,n={}){let t=J.resolve(e),i=await mo(t,n);i.plan.secretFindings.length>0&&nc(i.plan.secretFindings);let o=await po(t,i.plan.manifest,i.archiveOptions);return {manifest:i.plan.manifest,tgzPath:o}}async function ml(e,n={}){return ho(e,n)}async function hl(e,n){let t=await ho(e,n);if(t.manifest.type!=="app")throw new Error("publish: App pack unexpectedly produced a template manifest");return t}
2
+ export{Ga as DEFAULT_PUBLISH_MAX_BYTES,za as DEFAULT_PUBLISH_MAX_FILES,Ji as EXCLUDE_RULES,xe as MARKETPLACE_API_PREFIX,ue as PublishError,hl as packApp,ho as packPublish,ml as packTemplate,gl as planPublish,Ha as uploadToMarketplace};