@crewx/sdk 0.9.0-rc.131 → 0.9.0-rc.133

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