@crewx/sdk 0.9.0-rc.136 → 0.9.0-rc.137
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/app/app.d.ts +93 -0
- package/dist/app/entry.d.ts +7 -0
- package/dist/app/index.d.ts +6 -0
- package/dist/app/index.js +9 -0
- package/dist/app/runtime.d.ts +14 -0
- package/dist/esm/app/index.js +9 -0
- package/dist/esm/index.js +288 -281
- package/dist/esm/plugins/index.js +28 -28
- package/dist/esm/publish/index.js +2 -2
- package/dist/esm/skills/index.js +2 -2
- package/dist/facade/Crewx.d.ts +2 -0
- package/dist/index.browser.js +4 -4
- package/dist/index.d.ts +5 -4
- package/dist/index.js +289 -282
- package/dist/mcp-app/apps-context.d.ts +15 -1
- package/dist/mcp-app/discovery.d.ts +8 -2
- package/dist/mcp-app/index.d.ts +2 -2
- package/dist/mcp-app/types.d.ts +14 -1
- package/dist/plugins/index.js +27 -27
- package/dist/prompt/tag-names.d.ts +2 -0
- package/dist/publish/index.js +2 -2
- package/dist/skills/index.js +2 -2
- package/dist/types/index.d.ts +2 -0
- package/dist/ui-plugin/app-manifest.d.ts +59 -0
- package/dist/ui-plugin/index.d.ts +2 -0
- package/dist/ui-plugin/validator.d.ts +4 -1
- package/dist/utils/env-defaults.d.ts +1 -0
- package/package.json +9 -2
- package/templates/agents/default.yaml +17 -5
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import*as J from'path';import {resolve,relative,sep,isAbsolute,join}from'path';import'url';import*as Ut from'crypto';import {createHash}from'crypto';import*as $ from'fs';import {constants,readFileSync,existsSync,statSync,readdirSync}from'fs';import {realpath,stat,readdir,open,lstat}from'fs/promises';import*as yo from'js-yaml';import {load}from'js-yaml';import*as To from'os';import*as Po from'tar';import {gunzipSync,gzipSync}from'zlib';var V=(e,n)=>()=>(e&&(n=e(e=0)),n);var h=V(()=>{});var L,en=V(()=>{h();L=class extends Error{constructor(t,i=t,o){super(i);this.code=t;this.currentRevision=o;}code;currentRevision;name="UiRuntimeError"};});function kn(e){return vo.test(e)||jo.test(e)}function Z(){throw new L("INPUT_INVALID","JSON value is not projection-safe")}function Ho(e){let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function wn(e,n,t,i,o,r){if(n>i&&Z(),e===null||typeof e=="string"||typeof e=="boolean")return typeof e=="string"&&(Vo.test(e)||Bo.test(e)&&!$o(o,r)||Fo.test(e))&&Z(),e;if(typeof e=="number")return Number.isFinite(e)||Z(),e;(typeof e!="object"||e===void 0||typeof e=="function"||typeof e=="bigint")&&Z();let s=e;t.has(s)&&Z(),t.add(s);try{if(Array.isArray(e))return e.map(d=>wn(d,n+1,t,i,o,r));Ho(s)||Z();let a={};for(let[d,c]of Object.entries(e))kn(d)&&Z(),a[d]=wn(c,n+1,t,i,[...o,d],r);return a}finally{t.delete(s);}}function se(e,n=0,t=[]){(!Number.isInteger(n)||n<0||n>Go)&&Z(),(!Array.isArray(t)||t.some(o=>typeof o!="string"))&&Z();let i=wn(e,0,new Set,zo+n,[],t);return (i===null||Array.isArray(i)||typeof i!="object")&&Z(),i}function Ne(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 $o(e,n){if(e.length===0)return false;let t=e.join(".");return n.some(i=>Ne(t,i))}function Se(e){try{let n=JSON.stringify(e);return n===void 0&&Z(),n}catch{Z();}}function Un(e){return Array.isArray(e)?e.map(Un):e!==null&&typeof e=="object"?Object.fromEntries(Object.keys(e).sort().map(n=>[n,Un(e[n])])):e}function Q(e){return Se(Un(e))}function Cn(e){return Buffer.byteLength(e,"utf8")}var vo,jo,Vo,Fo,Bo,zo,Go,ge=V(()=>{h();en();vo=/(?: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,Vo=/<\/?[A-Za-z][^>]*>/,Fo=/^(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)/,Bo=/^(?:https?|file|ftp|ws|wss):\/\//i;zo=8,Go=4;});function xn(e){return Q(e)}var xt=V(()=>{h();ge();});var me,vn=V(()=>{h();me="window";});function Me(e){return Wo.has(e)||Jo.test(e)||Ko.test(e)}var vt,Wo,Jo,Ko,nn,Fe,ae,jn,Vn,Fn,Bn,Hn,Le=V(()=>{h();vt=["__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"],Wo=new Set(vt),Jo=/(?:proof|token|secret|password|cookie|authorization|private[_-]?key|stack|exception|plugin[_-]?text)/i,Ko=/(?:url|uri|endpoint|path|file(?:name|path)?|cwd|shell|directory|dir|folder)$/i;nn=/^[A-Za-z0-9_]+$/,Fe=/^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)*$/,ae=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,jn=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/,Vn=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,Fn=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/,Bn=["blue","violet","emerald","amber","rose","sky","slate","indigo"],Hn=["inline","panel"];});function zn(e){return typeof e=="string"&&jt.includes(e)}var jt,Vt=V(()=>{h();Le();jt=["text/plain","application/json"];});function tn(e){if(!Gn(e))return false;let n=Object.keys(e);return !(n.some(t=>t!=="in"&&t!=="out")||n.length===0||Object.hasOwn(e,"in")&&!Xo(e.in)||Object.hasOwn(e,"out")&&!Yo(e.out))}function Xo(e){return Gn(e)?Object.keys(e).every(t=>t==="mediaType"||t==="required")&&Object.hasOwn(e,"mediaType")&&zn(e.mediaType)&&(!Object.hasOwn(e,"required")||typeof e.required=="boolean"):false}function Yo(e){return Gn(e)?Object.keys(e).every(t=>t==="mediaType"||t==="range")&&Object.hasOwn(e,"mediaType")&&zn(e.mediaType)&&(!Object.hasOwn(e,"range")||typeof e.range=="boolean"):false}function Gn(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}var $n=V(()=>{h();Vt();new TextDecoder("utf-8",{fatal:true,ignoreBOM:true});});function l(e,n=e){throw new K(e,n)}function F(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;try{let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}catch{return false}}function k(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function B(e,n,t=[]){let i=new Set([...n,...t]);Object.keys(e).some(o=>!i.has(o))&&l("MANIFEST_INVALID"),n.some(o=>!k(e,o))&&l("MANIFEST_INVALID");}function cn(e,n=false,t=false,i=false){return er.test(e)||!i&&tr.test(e)||nr.test(e)||t&&Ft.test(e)||ir.test(e)&&!(n&&/^\s*data:/i.test(e)&&!Ft.test(e))}function sn(e,n=new Set,t=0,i=false,o=false){if(typeof e=="string"){cn(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)sn(r,n,t+1);return}F(e)||l("MANIFEST_INVALID");for(let[r,s]of Object.entries(e))sn(s,n,t+1,i&&t===0&&(r==="name"||r==="description"),o);}finally{n.delete(e);}}}function oe(e,n){let t=e[n];return typeof t!="string"&&l("MANIFEST_INVALID"),t}function ne(e,n,t){let i=e[n];return (!Number.isSafeInteger(i)||i<t)&&l("MANIFEST_INVALID"),i}function Wn(e){return Qo.test(e)||l("MANIFEST_INVALID"),e}function Oe(e){return Zo.test(e)||l("TOKEN_INVALID"),e}function br(e){return Xt.test(e)||l("MANIFEST_INVALID"),e}function Pr(e){F(e)||l("MANIFEST_INVALID");let n={};for(let[t,i]of Object.entries(e)){let o=br(t);F(i)||l("MANIFEST_INVALID");let r=i.type;if(r==="text"){B(i,["type","maxLength"]),n[o]={type:r,maxLength:ne(i,"maxLength",1)};continue}if(r==="text-list"){B(i,["type","max","itemMaxLength"]),n[o]={type:r,max:ne(i,"max",0),itemMaxLength:ne(i,"itemMaxLength",1)};continue}if(r==="step-list"){B(i,["type","min","max","labelMaxLength","detailMaxLength"]);let s=ne(i,"min",0),a=ne(i,"max",1);s>a&&l("MANIFEST_INVALID"),n[o]={type:r,min:s,max:a,labelMaxLength:ne(i,"labelMaxLength",1),detailMaxLength:ne(i,"detailMaxLength",1)};continue}typeof r=="string"&&l("SCHEMA_TYPE_UNSUPPORTED"),l("MANIFEST_INVALID");}return n}function Dr(e,n,t){let i=e[n];(!i||i.type!==t)&&l("MANIFEST_INVALID");}function on(e,n,t){let i=oe(e,"field");return Xt.test(i)||l("MANIFEST_INVALID"),Dr(n,i,t),i}function Nr(e,n){F(e)||l("MANIFEST_INVALID");let t=e.primitive;switch(typeof t!="string"&&l("MANIFEST_INVALID"),Tr.includes(t)||l("PRIMITIVE_UNKNOWN"),t){case "card-shell":return B(e,["primitive"]),{primitive:t};case "meta-banner":return B(e,["primitive","badgeToken","noticeToken"]),{primitive:t,badgeToken:Oe(oe(e,"badgeToken")),noticeToken:Oe(oe(e,"noticeToken"))};case "heading":return B(e,["primitive","field"]),{primitive:t,field:on(e,n,"text")};case "labeled-text":return B(e,["primitive","titleToken","field","variant"]),e.variant!=="callout"&&l("MANIFEST_INVALID"),{primitive:t,titleToken:Oe(oe(e,"titleToken")),field:on(e,n,"text"),variant:"callout"};case "step-flow":return B(e,["primitive","titleToken","field"]),{primitive:t,titleToken:Oe(oe(e,"titleToken")),field:on(e,n,"step-list")};case "text-list":{B(e,["primitive","titleToken","field"],["emptyToken","hideWhenEmpty"]);let i={primitive:t,titleToken:Oe(oe(e,"titleToken")),field:on(e,n,"text-list")};return k(e,"emptyToken")&&(i.emptyToken=Oe(oe(e,"emptyToken"))),k(e,"hideWhenEmpty")&&(typeof e.hideWhenEmpty!="boolean"&&l("MANIFEST_INVALID"),i.hideWhenEmpty=e.hideWhenEmpty),i}}return l("MANIFEST_INVALID")}function Sr(e,n){return Array.isArray(e)||l("MANIFEST_INVALID"),e.map(t=>Nr(t,n))}function H(e="v2 manifest exceeds a contract limit"){return l("LIMIT_EXCEEDED",e)}function ee(e="initial state is not projection-safe"){return l("INITIAL_STATE_INVALID",e)}function Bt(e,n){return (typeof e!="string"||e.length===0||e.length>4096||e.trim().length===0||hr.test(e)||Er.test(e))&&l("MANIFEST_INVALID",`${n} is invalid`),(cn(e,true,true)||or.test(e)||rr.test(e)||sr.test(e))&&l("UNSAFE_VALUE",`${n} contains an unsafe value`),e}function Jn(e,n){return (typeof e!="string"||!ae.test(e))&&l("MANIFEST_INVALID",`${n} is invalid`),e}function Mr(e){return (typeof e!="string"||!jn.test(e)||e==="*"||e==="all")&&l("MANIFEST_INVALID","action capability is invalid"),e}function Yt(e){return (typeof e!="string"||!mr.test(e))&&l("MANIFEST_INVALID","resource hash is invalid"),e}function Kn(e,n=new Set,t=0){if(typeof e=="string"){e.length>4096&&H("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&&H("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&&H("v2 manifest array is too long");for(let i of e)Kn(i,n,t+1);return}F(e)||l("MANIFEST_INVALID","v2 manifest contains a non-plain object");for(let i of Object.values(e))Kn(i,n,t+1);}finally{n.delete(e);}}}function qt(e){return (typeof e!="string"||e.length>4096||!Fe.test(e))&&(typeof e=="string"&&e.length>4096&&H("projection path is too long"),l("MANIFEST_INVALID","projection paths must be canonical exact paths")),e.split(".").some(t=>Me(t))&&l("MANIFEST_INVALID","projection paths cannot address reserved state keys"),e}function Xn(e){F(e)||l("MANIFEST_INVALID","projection policy must be an object"),B(e,["allow"]),Array.isArray(e.allow)||l("MANIFEST_INVALID","projection allow must be an array"),e.allow.length>128&&H("projection allowlist is too long");let n=[],t=new Set;for(let i of e.allow){let o=qt(i);t.has(o)&&l("MANIFEST_INVALID","projection allowlist contains a duplicate path"),t.add(o),n.push(o);}return {allow:n}}function Lr(e,n){if(e===void 0)return;Array.isArray(e)||l("MANIFEST_INVALID","dataPaths must be an array"),e.length>_r&&H("dataPaths exceed the v2 limit");let t=[],i=new Set;for(let o of e){let r=qt(o);i.has(r)&&l("MANIFEST_INVALID","dataPaths contain a duplicate path"),n.some(s=>Ne(r,s))||l("MANIFEST_INVALID","dataPaths must be projection-allowed"),i.add(r),t.push(r);}return t}function Re(e,n,t=Number.MAX_SAFE_INTEGER){return (!Number.isSafeInteger(e)||e<0||e>t)&&l("MANIFEST_INVALID",`${n} is invalid`),e}function Ht(e,n){return (typeof e!="number"||!Number.isFinite(e))&&l("MANIFEST_INVALID",`${n} is invalid`),e}function Yn(e,n=0,t=new Set){if(typeof e=="string")return (e.length>4096||cn(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)&&H("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&&H("schema enum array is too long"),e.map(o=>Yn(o,n+1,t));F(e)||l("MANIFEST_INVALID","schema enum contains a non-plain object");let i={};for(let[o,r]of Object.entries(e))Me(o)&&l("MANIFEST_INVALID","schema enum contains a reserved key"),i[o]=Yn(r,n+1,t);return i}finally{t.delete(e);}}function Or(e,n){if(e===void 0)return;Array.isArray(e)||l("MANIFEST_INVALID","schema required must be an array"),e.length>64&&H("schema required list is too long");let t=[],i=new Set;for(let o of e)(typeof o!="string"||!Fe.test(o))&&l("MANIFEST_INVALID","schema required contains an invalid key"),o.length>4096&&H("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 Rr(e,n){let t=n?Fe:nn;return e.length>4096&&H("schema property name is too long"),(!t.test(e)||e.split(".").some(i=>Me(i)))&&l("MANIFEST_INVALID","schema property name is invalid"),e}function qn(e,n=0,t=false){F(e)||l("MANIFEST_INVALID","action inputSchema must be an object"),n>8&&H("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"),B(e,["type"],o.filter(a=>a!=="type"));let r={type:i};if(k(e,"enum")&&(Array.isArray(e.enum)||l("MANIFEST_INVALID","schema enum must be an array"),e.enum.length>128&&H("schema enum is too long"),r.enum=e.enum.map(a=>Yn(a))),i==="string"&&(k(e,"minLength")&&(r.minLength=Re(e.minLength,"schema minLength",4096)),k(e,"maxLength")&&(r.maxLength=Re(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")&&(k(e,"minimum")&&(r.minimum=Ht(e.minimum,"schema minimum")),k(e,"maximum")&&(r.maximum=Ht(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"&&(k(e,"minItems")&&(r.minItems=Re(e.minItems,"schema minItems",128)),k(e,"maxItems")&&(r.maxItems=Re(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"),k(e,"items")&&(r.items=qn(e.items,n+1,false))),i==="object"){let a;if(k(e,"properties")){F(e.properties)||l("MANIFEST_INVALID","schema properties must be an object");let c=Object.entries(e.properties);c.length>64&&H("schema properties are too many"),a={};for(let[p,y]of c){let A=Rr(p,t);a[A]=qn(y,n+1,false);}r.properties=a;}k(e,"minProperties")&&(r.minProperties=Re(e.minProperties,"schema minProperties",64)),k(e,"maxProperties")&&(r.maxProperties=Re(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=Or(e.required,a);d!==void 0&&(r.required=d),k(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)&&H("action inputSchema subtree is too large"),r}function wr(e){let n=qn(e,0,true);return (n.type!=="object"||!n.properties)&&l("MANIFEST_INVALID","action inputSchema must declare object properties"),n}function Ur(e){if(F(e)||l("MANIFEST_INVALID","action backend must be an object"),e.type==="core"){B(e,fr);let n=e.handler;return (typeof n!="string"||!Vn.test(n))&&l("MANIFEST_INVALID","core backend handler is invalid"),{type:"core",handler:n}}if(e.type==="skill"){B(e,yr,Ar),(!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||!Fn.test(i))&&l("MANIFEST_INVALID","skill backend command token is invalid"),n.push(i);let t=k(e,"env")?Cr(e.env):void 0;return {type:"skill",command:n,...t===void 0?{}:{env:t}}}l("MANIFEST_INVALID","action backend type is unsupported");}function kr(e){F(e)||l("MANIFEST_INVALID","action must be an object"),B(e,pr,lr),k(e,"_meta")&&Zt(e._meta);let n=Jn(e.actionId,"actionId");kn(n)&&l("MANIFEST_INVALID",`actionId "${n}" is not projection-safe`);let t=Mr(e.capability),i=e.mutation;typeof i!="boolean"&&l("MANIFEST_INVALID","action mutation must be boolean");let o=wr(e.inputSchema),r;if(k(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"||!k(p,_)||y.has(_))&&l("MANIFEST_INVALID","action dataInputs must be unique declared properties"),y.add(_),A.push(_);r=A;}let s=Xn(e.resultProjection),a=Ur(e.backend),d;k(e,"content")&&((a.type!=="skill"||!tn(e.content))&&l("MANIFEST_INVALID","action content declaration is invalid"),d=xr(e.content));let c;if(k(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 Cr(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 xr(e){return Object.freeze({...e.in===void 0?{}:{in:Object.freeze({...e.in})},...e.out===void 0?{}:{out:Object.freeze({...e.out})}})}function vr(e){return F(e)||l("INITIAL_STATE_INVALID","initialState must be an object"),B(e,Ir,gr),e.path!=="ui/state.json"&&l("MANIFEST_INVALID","initialState path is not fixed"),k(e,"hash")?{path:"ui/state.json",hash:Yt(e.hash)}:{path:"ui/state.json"}}function jr(e){let n=["wasm","terminal","htmlDocuments"];return (!F(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){sn(e,new Set,0,true,true),Kn(e),F(e)||l("MANIFEST_INVALID"),B(e,cr,dr),k(e,"_meta")&&Zt(e._meta),e.manifestVersion!==2&&l("MANIFEST_INVALID");let t;k(e,"runtime")&&(t=jr(e.runtime));let i=Jn(e.pluginId,"pluginId"),o=Jn(e.definitionId,"definitionId"),r=ne(e,"version",1),s=Bt(e.name,"name"),a=Bt(e.description,"description"),d;k(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;k(e,"tone")&&((typeof e.tone!="string"||!Bn.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;k(e,"entryHash")&&(p=Yt(e.entryHash));let y;k(e,"initialState")&&(y=vr(e.initialState));let A;k(e,"usage")&&(e.usage!=="card"&&e.usage!=="window"&&l("MANIFEST_INVALID","usage is invalid"),A=e.usage);let _;k(e,"detailPanel")&&(typeof e.detailPanel!="boolean"&&l("MANIFEST_INVALID","detailPanel is invalid"),_=e.detailPanel);let T;if(k(e,"displayModes")){((A??me)!==me||!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??me)===me&&_!==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&&H("surfaces exceed the v2 limit");let M=[],v=new Set;for(let S of e.surfaces)(typeof S!="string"||!Hn.includes(S))&&l("MANIFEST_INVALID","surface is unsupported"),v.has(S)&&l("MANIFEST_INVALID","surfaces contain a duplicate"),v.add(S),M.push(S);F(e.size)||l("MANIFEST_INVALID","size must be an object"),B(e.size,["height"]);let C=ne(e.size,"height",1);C>720&&H("size.height exceeds the v2 limit");let U=Xn(e.stateProjection),j=e.summaryProjection===void 0?void 0:Xn(e.summaryProjection);j!==void 0&&j.allow.some(S=>!U.allow.includes(S))&&l("MANIFEST_INVALID","summaryProjection must be a subset of stateProjection.allow");let E=Lr(e.dataPaths,U.allow);Array.isArray(e.actions)||l("MANIFEST_INVALID","actions must be an array"),e.actions.length>32&&H("actions exceed the v2 limit");let m=[],N=new Set;for(let S of e.actions){let f=kr(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))U.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:C},stateProjection:U,...j===void 0?{}:{summaryProjection:j},...E===void 0?{}:{dataPaths:E},actions:m}}function Zt(e){F(e)||l("MANIFEST_INVALID","_meta must be an object");let n=JSON.stringify(e);(n===void 0||Buffer.byteLength(n,"utf8")>ur)&&H("_meta exceeds the 4 KiB limit");}function Fr(e){let n={},t={};for(let r of e.actions){n[r.actionId]={capabilities:[r.capability],inputKeys:Object.keys(r.inputSchema.properties??{}),...r.dataInputs===void 0?{}:{dataInputs:r.dataInputs},resultProjection:r.resultProjection,...r.confirmation===void 0?{}:{confirmation:r.confirmation},...r.content===void 0?{}:{content:r.content},...r.backend.type!=="skill"||r.backend.env===void 0?{}:{env:r.backend.env}};let s=r.backend.type==="skill"||r.backend.type==="core"&&r.backend.handler==="state.set";t[r.actionId]={actionId:r.actionId,mutation:r.mutation,backend:r.backend,launchPolicy:s?"allowed":"denied",...s?{}:{denialCode:"EXEC_DENIED"}};}let i={id:e.definitionId,version:e.version,renderer:"sandbox-html",...e.usage===void 0?{}:{usage:e.usage},...e.detailPanel===void 0?{}:{detailPanel:e.detailPanel},...e.displayModes===void 0?{}:{displayModes:e.displayModes},surfaces:e.surfaces,stateProjection:e.stateProjection,...e.summaryProjection===void 0?{}:{summaryProjection:e.summaryProjection},...e.dataPaths===void 0?{}:{dataPaths:e.dataPaths},actions:n},o={entry:{path:"ui/index.html",...e.entryHash===void 0?{}:{hash:e.entryHash}},...e.initialState===void 0?{}:{initialState:e.initialState}};return {manifest:e,definition:i,handlers:t,resources:o}}function Zn(e,n,t,i,o,r){if(typeof e=="string"){let s=o.length>0&&r.some(a=>Ne(o.join("."),a));return (e.length>4096||cn(e,false,false,s))&&ee("state contains an unsafe string"),e}if(e===null||typeof e=="boolean")return e;if(typeof e=="number")return Number.isFinite(e)||ee("state contains a non-finite number"),e;(e===void 0||typeof e!="object"||typeof e=="function"||typeof e=="bigint")&&ee("state contains a non-JSON value"),t>8&&ee("state is too deep"),n.has(e)&&ee("state contains a cycle"),n.add(e);try{let s;if(Array.isArray(e))e.length>128&&ee("state array is too long"),s=e.map(d=>Zn(d,n,t+1,65536,o,r));else {F(e)||ee("state contains a non-plain object");let d={};for(let[c,p]of Object.entries(e))(c.length>4096||!nn.test(c)||Me(c))&&(c.length>4096&&ee("state key is too long"),ee("state contains a reserved or invalid key")),d[c]=Zn(p,n,t+1,65536,[...o,c],r);s=d;}let a=JSON.stringify(s);return (a===void 0||Buffer.byteLength(a,"utf8")>i)&&ee("state subtree is too large"),s}finally{n.delete(e);}}function et(e,n=[]){F(e)||ee("initial state must be a JSON object");let t=Zn(e,new Set,0,65536,[],n);return (t===null||Array.isArray(t)||typeof t!="object")&&ee(),t}function Br(e,n={}){sn(e),F(e)||l("MANIFEST_INVALID"),B(e,ar),e.manifestVersion!==1&&l("MANIFEST_INVALID");let t=Wn(oe(e,"pluginId")),i=Wn(oe(e,"definitionId")),o=ne(e,"version",1),r=ne(e,"primitiveSet",1),s=n.supportedPrimitiveSet??qo;(!Number.isSafeInteger(s)||s<1)&&l("MANIFEST_INVALID"),r>s&&l("PRIMITIVE_SET_UNSUPPORTED"),F(e.activation)||l("MANIFEST_INVALID"),B(e.activation,["kind","language"]),e.activation.kind!=="fenced-code"&&l("MANIFEST_INVALID");let a=Wn(oe(e.activation,"language")),d=Pr(e.schema),c=Sr(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 Hr(e,n={}){return F(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):Br(e,n)}function Te(e,n={}){try{return Hr(e,n)}catch(t){if(t instanceof K)throw t;return l("MANIFEST_INVALID")}}function nt(e,n={}){let t=Te(e,n);return t.manifestVersion===2?Fr(t):t}var qo,Zo,Qo,Xt,er,nr,tr,ir,Ft,or,rr,sr,ar,cr,dr,pr,lr,ur,fr,yr,Ar,Ir,gr,mr,hr,Er,_r,Tr,K,Qt=V(()=>{h();vn();ge();$n();Le();qo=1,Zo=/^[a-z][a-zA-Z0-9]*(\.[a-zA-Z0-9]+)+$/,Qo=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,Xt=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,er=/<\/?[A-Za-z][^>]*>/,nr=/^(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)/,tr=/^(?:https?|file|ftp|ws|wss):\/\//i,ir=/^\s*(?:javascript|data):/i,Ft=/data:[^,\s]*,/i,or=/(?:https?|file|ftp|ws|wss):\/\//i,rr=/javascript:/i,sr=/(?:^[\s]*|[\s"'(=])(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)(?=[^\s"'<>])[^\s"'<>]*/,ar=["manifestVersion","pluginId","definitionId","version","primitiveSet","activation","schema","layout"],cr=["manifestVersion","pluginId","definitionId","version","name","description","entry","surfaces","size","stateProjection","actions"],dr=["_meta","icon","tone","entryHash","runtime","initialState","usage","detailPanel","displayModes","summaryProjection","dataPaths","focusedAiDataPaths"],pr=["actionId","capability","mutation","inputSchema","resultProjection","backend"],lr=["confirmation","dataInputs","content","_meta"],ur=4*1024,fr=["type","handler"],yr=["type","command"],Ar=["env"],Ir=["path"],gr=["hash"],mr=/^[0-9a-f]{64}$/,hr=/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/,Er=/[\r\n]/,_r=16,Tr=["card-shell","meta-banner","heading","labeled-text","step-flow","text-list"],K=class extends Error{constructor(t,i=t){super(i);this.code=t;}code;name="UiPluginValidationError"};});var tt=V(()=>{h();xt();Qt();Le();});function ce(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=se(t);return createHash("sha256").update(Q(i)).digest("hex")}function de(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"||!qr.test(e.sourceHash)))throw new L("DEFINITION_UNSUPPORTED","UI definition source hash is invalid");if(!/^[0-9a-f]{64}$/.test(e.hash)||ce(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&&ot(t.resultProjection),t.content!==void 0&&!tn(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&&ot(e.stateProjection),e.summaryProjection){ot(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(Zr(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=>Ne(t,i))))throw new L("DEFINITION_UNSUPPORTED","UI definition dataPaths are invalid")}}function Zr(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=se(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=se(a.structuredContent);if(Cn(Se(d))>4*1024)throw new Error("fixed result size")}}catch{throw new L("DEFINITION_UNSUPPORTED","UI legacy tool metadata is not projection-safe")}}function ot(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 qr,Ue=V(()=>{h();ge();en();$n();qr=/^[0-9a-f]{64}$/;});function pn(e,n=e){throw new pe(e,n)}var pe,ln=V(()=>{h();pe=class extends Error{constructor(t,i=t){super(i);this.code=t;}code;name="McpAppContractError"};});var ci=V(()=>{h();});var di=V(()=>{h();Ue();ge();ln();ci();});function pi(e,n){return es.add(e),n!==void 0&&ns.set(e,n),e}var es,ns,un=V(()=>{h();es=new WeakSet,ns=new WeakMap;});function $e(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function rt(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 fi(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let n of Object.values(e))fi(n);return Object.freeze(e)}function W(e){throw new re("LINEAGE_INVALID",e)}function cs(e){throw new re("LINEAGE_STALE",e)}function yi(e){if(!$e(e)||!rt(e,os,rs)||!$e(e.actions))return W("Lineage definition shape is invalid");for(let n of Object.values(e.actions))if(!$e(n)||!rt(n,ss,as))return W("Lineage action definition shape is invalid");return e}function ds(e){if(!$e(e)||!rt(e,ts,is))return W("Lineage entry shape is invalid");if(!Number.isSafeInteger(e.version)||e.version<1||typeof e.hash!="string"||!li.test(e.hash))return W("Lineage entry identity is invalid");if(e.sourceHash!==void 0&&(typeof e.sourceHash!="string"||!li.test(e.sourceHash)))return W("Lineage source hash is invalid");if(e.compat!==void 0&&e.compat!=="break")return W("Lineage compatibility marker is invalid");let n=yi(e.definition);if(n.version!==e.version)return W("Lineage version does not match its definition");if(e.sourceHash!==void 0&&n.sourceHash!==e.sourceHash)return W("Lineage source hash does not match its definition");let t;try{t=ce(n),de({...n,hash:e.hash});}catch{return W("Lineage definition is invalid")}return t!==e.hash?W("Lineage definition hash does not match"):fi({version:e.version,hash:e.hash,definition:n,...e.sourceHash===void 0?{}:{sourceHash:e.sourceHash},...e.compat===void 0?{}:{compat:e.compat}})}function ui(e){return e.stateProjection?.allow??[]}function ps(e,n){let t=[],i=new Set(ui(n));ui(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 ls(e,n){return Q(e)===Q(n)}function st(e,n){if(!Array.isArray(e)||e.length===0)return W("Definition lineage is missing");if(!$e(n)||typeof n.hash!="string")return W("Current definition is invalid");let t,i;try{let{hash:a,...d}=n;i=yi(d),t={...i,hash:a},de(t);}catch{return W("Current definition is invalid")}let o=e.map(ds),r=o[0].definition.id;if(o.some(a=>a.definition.id!==r))return W("Lineage definition ids do not match");if(o.some((a,d)=>d>0&&a.version<=o[d-1].version))return W("Lineage generations are not in increasing version order");if(o.some((a,d)=>o.findIndex(c=>c.hash===a.hash)!==d))return W("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||!ls(s.definition,i))return cs("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 re("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=ps(o[a].definition,t);if(c.length>0)throw new re("LINEAGE_INVALID",`Lineage compatibility failed: ${c.join(", ")}`,c)}return Object.freeze({entries:Object.freeze(o),current:t})}var re,li,ts,is,os,rs,ss,as,at=V(()=>{h();Ue();ge();re=class extends Error{constructor(t,i=t,o=[]){super(i);this.code=t;this.violations=o;}code;violations;name="UiDefinitionLineageError"},li=/^[0-9a-f]{64}$/,ts=["version","hash","definition"],is=["sourceHash","compat"],os=["id","version","actions"],rs=["sourceHash","usage","detailPanel","displayModes","renderer","surfaces","stateProjection","dataPaths","summaryProjection","legacy"],ss=["capabilities"],as=["inputKeys","dataInputs","confirmation","resultProjection","content","env"];});var Ai,Ii,gi=V(()=>{h();Ai=["crewx_app_terminal_connect","crewx_app_html_viewer_open"],Ii=["crewx_listWorkspaces","crewx_queryAgent","crewx_executeAgent","crewx_getTaskResult","crewx_listTasks","crewx_listAgents","callBrowser","openTab","listTabs","closeTab"];});var mi=V(()=>{h();Ue();un();});function ct(e,n=0){try{let t=se(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 hi(e){if(e.length===0)return ct({type:"object",properties:{},additionalProperties:false});let n=e.map(i=>i.actionId),t=new Map;for(let i of e)t.set(i.actionId,ct(i.inputSchema));return ct(ys(n,t),fs)}function ys(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 We,fs,dt=V(()=>{h();di();Ue();ge();un();ln();at();gi();mi();We=8*1024*1024,new Set(Ai),new Set(Ii),fs=4;});function As(e){if(e===null||typeof e!="object"||!(Ei in e))throw new TypeError("scanCache must be created by createWorkspaceAppScanCache");return e[Ei]}function _i(e,n){let t=As(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 Ei,Ti=V(()=>{h();Ei=Symbol("crewx.workspace-app-scan-cache.state");});function Y(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 hs(e){if(typeof e!="string"||e.length===0||!isAbsolute(e))throw new P("READ_DENIED")}function pt(e){if(typeof e!="string"||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 In(e,n){let t=relative(e,n);return t===""||t!==".."&&!t.startsWith(`..${sep}`)&&!isAbsolute(t)}function Ce(e){return {dev:e.dev,ino:e.ino,size:e.size,mtimeNs:e.mtimeNs,ctimeNs:e.ctimeNs}}function yt(e,n){return e.dev===n.dev&&e.ino===n.ino}function At(e,n){return yt(e,n)&&e.size===n.size&&e.mtimeNs===n.mtimeNs&&e.ctimeNs===n.ctimeNs}async function fn(e){hs(e);let n,t;try{n=await realpath(e),t=await stat(n,{bigint:!0});}catch(i){throw Y(i)}if(!t.isDirectory())throw new P("READ_DENIED");return {realRoot:n,identity:Ce(t)}}async function Di(e,n,t){if(t.length<2||t[0]!=="apps"&&t[0]!=="skills")return;let i,o;try{if(i=resolve(e,t[0],t[1]),o=await realpath(i),!(await stat(o,{bigint:!0})).isDirectory())throw new P("READ_DENIED")}catch(r){throw r instanceof P?r:Y(r)}if(!In(n,o))throw new P("PATH_ESCAPED");return o}async function yn(e,n,t,i){let o,r,s;try{o=await lstat(e,{bigint:!0}),r=await realpath(e),s=await stat(r,{bigint:!0});}catch(a){throw Y(a)}if(!In(n,r)||t!==void 0&&!In(t,r))throw new P("PATH_ESCAPED");if(!o.isFile()||!s.isFile())throw new P("READ_DENIED");if(!yt(i,o)||!yt(i,s)||i.dev!==s.dev)throw new P("PATH_ESCAPED")}async function ke(e,n){let t,i;try{t=await realpath(e),i=await stat(t,{bigint:!0});}catch{throw new P("PATH_ESCAPED")}if(t!==n.realRoot||!At(n.identity,Ce(i)))throw new P("PATH_ESCAPED")}function Es(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,ft,ms,Pi,gn,Ni,gt=V(()=>{h();P=class extends Error{constructor(t){super(t);this.code=t;}code;name="AppDiscoveryFsError"},ft=constants.O_NOFOLLOW,ms=constants.O_NONBLOCK,Pi=constants.O_RDONLY|(ft??0)|(ms??0);gn=class{async getRootIdentity(n){let t=await fn(n);return await ke(n,t),{dev:t.identity.dev,ino:t.identity.ino,realPath:t.realRoot}}async listDirectory(n,t){let i=pt(t),o=await fn(n),r=resolve(n,...i),s,a;try{s=await realpath(r),a=await stat(s,{bigint:!0});}catch(d){let c=Y(d);if(c.code==="NOT_FOUND")return [];throw c}if(!In(o.realRoot,s)||!a.isDirectory())throw new P("PATH_ESCAPED");try{let d=await readdir(s,{withFileTypes:!0,encoding:"utf8"});return await ke(n,o),d.map(Es)}catch(d){let c=Y(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(ft===void 0)throw new P("UNSUPPORTED");let o=pt(t),r=await fn(n),s=resolve(n,...o),a=relative(n,s);if(a===".."||a.startsWith(`..${sep}`)||isAbsolute(a))throw new P("PATH_ESCAPED");let d;try{d=await open(s,Pi);}catch(c){throw Y(c)}try{let c;try{let T=await d.stat({bigint:!0});c=Ce(T);}catch(T){throw Y(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 ke(n,r);let p=await Di(n,r.realRoot,o);await yn(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 Y(D)}if(T<=0)throw new P("IDENTITY_CHANGED");A+=T;}let _;try{let T=await d.stat({bigint:!0});_=Ce(T);}catch(T){throw Y(T)}if(!At(c,_))throw new P("IDENTITY_CHANGED");return await yn(s,r.realRoot,p,_),await ke(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(ft===void 0)throw new P("UNSUPPORTED");let o=pt(t),r=await fn(n),s=resolve(n,...o),a=relative(n,s);if(a===".."||a.startsWith(`..${sep}`)||isAbsolute(a))throw new P("PATH_ESCAPED");let d;try{d=await open(s,Pi);}catch(c){throw Y(c)}try{let c;try{let A=await d.stat({bigint:!0});c=Ce(A);}catch(A){throw Y(A)}if(c.size>BigInt(i)||c.size>BigInt(Number.MAX_SAFE_INTEGER))throw new P("LIMIT_EXCEEDED");await ke(n,r);let p=await Di(n,r.realRoot,o);await yn(s,r.realRoot,p,c);let y;try{let A=await d.stat({bigint:!0});y=Ce(A);}catch(A){throw Y(A)}if(!At(c,y))throw new P("IDENTITY_CHANGED");return await yn(s,r.realRoot,p,y),await ke(n,r),{...y,candidateRealPath:p??r.realRoot}}catch(c){throw c instanceof P?c:Y(c)}finally{await d.close().catch(()=>{});}}async readFileVerified(n,t,i){return this.readVerifiedFile(n,t,i)}},Ni=new gn;});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 Mi(e){return typeof e=="string"&&ae.test(e)?e:void 0}function Ss(e){return e.length>0&&e!=="."&&e!==".."&&!/[\\/\u0000]/.test(e)}function Pe(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 Ms(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 Ls(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 Os(e){return Ds.decode(e)}function Rs(e){return JSON.parse(Os(e))}function Li(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 ws(e){if(e instanceof P)return Li(e.code);if(e!==null&&typeof e=="object"&&"code"in e){let n=e.code;if(typeof n=="string")return Li(n)}}function le(e,n){let t=n();return Number.isFinite(t)&&Number.isFinite(e)&&t-e<=5e3}function Us(e){if(typeof e.readVerifiedFile=="function")return e.readVerifiedFile;if(typeof e.readFileVerified=="function")return e.readFileVerified}function ks(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 Oi(e,n,t,i){let o=Us(e);if(!o)throw new P("READ_DENIED");return Ls(await o.call(e,n,t,i))}async function Et(e,n,t){let i=ks(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(Ms).filter(r=>r!==null)}function Cs(e,n,t,i){return Object.freeze({code:e,...{},source:n,relativePath:t})}function xs(e){if(!Ye(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(Pe))};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 vs(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 hn(e){return Object.freeze({appIds:Object.freeze([...new Set(e.map(n=>n.appId))].sort(Pe)),definitionIds:Object.freeze([...new Set(e.map(n=>n.definition.id))].sort(Pe))})}function mn(e,n){let t=Object.keys(e).sort(Pe),i=[...n].sort(Pe);return t.length===i.length&&t.every((o,r)=>o===i[r])}function Ri(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 js(e){let n;try{n=Rs(e);}catch{return}if(!Ye(n)||!mn(n,["version","packages"])||n.version!==1||!Array.isArray(n.packages)||n.packages.length>_t)return;let t=new Set,i=new Set,o=0,r=[];for(let s of n.packages){if(!Ye(s))return;let a=["packageDir","appId","definition","files"],d=Object.hasOwn(s,"lineage"),c=Object.hasOwn(s,"launcher"),p=[...d?["lineage"]:[],...c?["launcher"]:[]];if(!mn(s,[...a,...p])||c&&s.launcher!==false)return;let y=Ri(s.packageDir),A=Mi(s.appId);if(!y||y.length!==2||y[0]!=="apps"||!Ss(y[1])||!A||t.has(s.packageDir)||!Ye(s.definition)||!mn(s.definition,["id","version","hash"]))return;let _=Mi(s.definition.id),T=s.definition.version,D=s.definition.hash;if(!_||!Number.isSafeInteger(T)||T<1||typeof D!="string"||!ht.test(D)||!Array.isArray(s.files)||s.files.length<2||s.files.length>Tt)return;let M=new Set,v=[];for(let C of s.files){if(!Ye(C)||!mn(C,["path","sha256"]))return;let U=Ri(C.path);if(!U||typeof C.sha256!="string"||!ht.test(C.sha256))return;let j=U.join("/"),E=`${s.packageDir}/${j}`;if(M.has(j)||i.has(E))return;M.add(j),i.add(E),v.push(Object.freeze({path:j,sha256:C.sha256}));}if(!M.has("ui-plugin.json")||!M.has("ui/index.html")||(o+=v.length,o>Ts))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(v.sort((C,U)=>Pe(C.path,U.path)))}));}return Object.freeze({version:1,packages:Object.freeze(r)})}function be(e){let n=ws(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,d)=>{if(!le(i,o))throw new P("LIMIT_EXCEEDED");if(d>2)throw new P("LIMIT_EXCEEDED");let c=await Et(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>Tt)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(Pe)}function Fs(e){return e==="ui-plugin.json"?262144:e==="ui/index.html"?We:e==="ui/state.json"?65536:e.startsWith("ui/assets/")?Ps:bs}async function wi(e,n,t,i){if(e===void 0)return {packages:[],diagnostics:[],incomplete:false,reservedIds:Ns};let o=xs(e.reservedIds),r=[],s=(f,u,I)=>Cs(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"||!ht.test(e.expectedIndexHash))return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a();let d;try{d=await Oi(n,e.root,"bundle-index.json",_s);}catch(f){return r.push(s(be(f),"bundle-index.json")),a()}let c=createHash("sha256").update(d).digest("hex");if(c!==e.expectedIndexHash)return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a();let p=js(d);if(p===void 0)return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a();if(!vs(hn(p.packages),o))return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a([],false,c);if(!le(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 Et(n,e.root,"");}catch(f){return r.push(s(be(f),"bundle-index.json")),a(p.packages.map(u=>({indexEntry:u,failureCode:be(f)})),false,c)}if(!le(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 Et(n,e.root,"apps");}catch(f){return r.push(s(be(f),"apps")),a(T(be(f)),false,c)}if(!le(t,i)||M.length>_t)return r.push(s("LIMIT_EXCEEDED","apps")),a(T("LIMIT_EXCEEDED"),true,c);let v=new Map(p.packages.map(f=>[f.packageDir.slice(5),f])),C=M.filter(f=>!v.has(f.name));for(let f of C)r.push(s(f.kind==="symlink"?"PATH_ESCAPED":"BUNDLE_INTEGRITY",`apps/${f.name}`));if(C.length>0){let f=C.some(u=>u.kind==="symlink")?"PATH_ESCAPED":"BUNDLE_INTEGRITY";return a(T(f),false,c)}let U=new Set,j=new Map,E=new Map;for(let f of p.packages){let u=j.get(f.appId)??[];u.push(f),j.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 [...j.values(),...E.values()])if(f.length>1)for(let u of f)U.add(u);let m=[],N=d.byteLength,S=false;for(let f of p.packages){if(!le(t,i)){S=true,m.push({indexEntry:f,failureCode:"LIMIT_EXCEEDED"});continue}let u;try{let x=f.lineage[f.lineage.length-1];if(!x)throw new re("LINEAGE_INVALID","Definition lineage is missing");if(x.definition.id!==f.definition.id||x.version!==f.definition.version||x.hash!==f.definition.hash)throw new re("LINEAGE_STALE","Last lineage generation does not match bundle identity");u=st(f.lineage,{...x.definition,hash:x.hash}).entries;}catch(x){let te=x instanceof re?x.code:"LINEAGE_INVALID";r.push(s(te,f.packageDir)),m.push({indexEntry:f,failureCode:te});continue}let I=M.find(x=>x.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 x=await Vs(n,e.root,f.packageDir,t,i);if(!le(t,i)){S=!0,m.push({indexEntry:f,failureCode:"LIMIT_EXCEEDED"});continue}let te=f.files.map(ie=>ie.path);if(x.length!==te.length||x.some((ie,he)=>ie!==te[he])){m.push({indexEntry:f,failureCode:"BUNDLE_INTEGRITY"});continue}g=new Map;let z;for(let ie of f.files){if(!le(t,i)){z="LIMIT_EXCEEDED",S=!0;break}if(N>=mt){z="LIMIT_EXCEEDED";break}let he;try{he=await Oi(n,e.root,`${f.packageDir}/${ie.path}`,Fs(ie.path));}catch(xo){z=be(xo);break}if(!le(t,i)){z="LIMIT_EXCEEDED",S=!0;break}if(N+he.byteLength>mt){N=mt,z="LIMIT_EXCEEDED";break}if(N+=he.byteLength,createHash("sha256").update(he).digest("hex")!==ie.sha256){z="BUNDLE_INTEGRITY";break}g.set(ie.path,he);}if(z!==void 0){m.push({indexEntry:f,failureCode:z});continue}}catch(x){le(t,i)||(S=true),m.push({indexEntry:f,failureCode:be(x)});continue}m.push({indexEntry:f,lineage:u,files:g,...U.has(f)?{failureCode:"DUPLICATE_ID"}:{}});}return a(m,S,c)}var _s,_t,Tt,Ts,bs,Ps,mt,ht,Ds,Ns,bt=V(()=>{h();at();Le();dt();gt();_s=256*1024,_t=64,Tt=128,Ts=_t*Tt,bs=2*1024*1024,Ps=8*1024*1024,mt=32*1024*1024,ht=/^[0-9a-f]{64}$/,Ds=new TextDecoder("utf-8",{fatal:true}),Ns=Object.freeze({appIds:Object.freeze([]),definitionIds:Object.freeze([])});});function Hs(e){if(typeof e!="string"||!ae.test(e))throw new TypeError("pluginId must be a safe UI plugin identifier");let n=`${Pt}${e}`.length+7<=128?e:`hash_${createHash("sha256").update(e,"utf8").digest("hex")}`;return {read:`${Pt}${n}_read`,action:`${Pt}${n}_action`}}function qe(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 ki(e){return typeof e=="string"&&ae.test(e)?e:void 0}function Gs(e,n){return n.length===0||n==="."||n===".."||/[\\/\u0000]/.test(n)?e==="skills"?"skills":"apps":`${e==="skills"?"skills":"apps"}/${n}`}function $s(e){return e.length>0&&e!=="."&&e!==".."&&!/[\\/\u0000]/.test(e)}function Ze(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 Gi(e){if(typeof e=="string")return {name:e,kind:"directory"};if(e===null||typeof e!="object")return null;let n=e;if(typeof n.name!="string")return null;if(n.kind==="file"||n.kind==="directory"||n.kind==="symlink"||n.kind==="other")return {name:n.name,kind:n.kind};if(n.type==="file"||n.type==="directory"||n.type==="symlink"||n.type==="other")return {name:n.name,kind:n.type};let t=n.isDirectory;if(typeof t=="function"&&t.call(e))return {name:n.name,kind:"directory"};let i=n.isSymbolicLink;if(typeof i=="function"&&i.call(e))return {name:n.name,kind:"symlink"};let o=n.isFile;return typeof o=="function"&&o.call(e)?{name:n.name,kind:"file"}:{name:n.name,kind:"other"}}function Ws(e){if(e instanceof Uint8Array)return new Uint8Array(e);if(e instanceof ArrayBuffer)return new Uint8Array(e.slice(0));if(Array.isArray(e)&&e.every(n=>Number.isInteger(n)&&n>=0&&n<=255))return Uint8Array.from(e);throw new TypeError("filesystem port returned an invalid byte array")}function $i(e){return zs.decode(e)}function Wi(e){return JSON.parse($i(e))}function Js(e){if(!qe(e))return;let n=ki(e.pluginId);if(!n)return;let t=ki(e.definitionId),i=e.version,o=t&&Number.isSafeInteger(i)&&i>=1?`${t}\0${String(i)}`:void 0;return {pluginId:n,...o===void 0?{}:{definitionKey:o}}}function Ks(e){let n=Wi(e);return {value:n,identity:Js(n)}}function _n(e,n,t,i){let o={code:e,...i===void 0?{}:{pluginId:i},source:n,relativePath:t};return Object.freeze(o)}function Ci(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 q(e){if(e instanceof P)return Ci(e.code);if(e!==null&&typeof e=="object"&&"code"in e){let n=e.code;if(typeof n=="string")return Ci(n)}}function ve(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 xi(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 Ji("UiPluginValidationError",e.code)}}function Ji(e,n){throw new Error(`Unmapped ${e} code: ${String(n)}`)}function Dt(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 Ji("McpAppContractError",e)}}function ue(e,n){let t=n();return Number.isFinite(t)&&Number.isFinite(e)&&t-e<=5e3}function Xs(e){return {pluginId:e.appId,definitionKey:`${e.definition.id}\0${String(e.definition.version)}`}}function Ys(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(qe(o)){let r=o.bin,s=typeof r=="string"?r:qe(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=qs(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 qs(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 Zs(){return globalThis.performance?.now()??Date.now()}function xe(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let n of Object.values(e))xe(n);return Object.freeze(e)}function vi(e){return Object.freeze(Array.from(e))}async function Tn(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 Bi(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 Bi(e,n.root,o,i),c=await s.call(e,r.workspaceRoot,o,i);return r.candidateRealPath=c.candidateRealPath,Yi(a,c)&&c.size===BigInt(d.byteLength)&&!qi(c,r.scanStartedAtNs)?r.files.set(o,{relativePath:o,byteLimit:i,fingerprint:c}):r.cacheable=!1,d}catch(a){throw t==="ui-plugin.json"&&q(a)==="NOT_FOUND"&&r.directoryListings.some(c=>c.relativePath===n.relativePath&&!Xi(c.key,"ui-plugin.json"))||(r.cacheable=false),a}}function Ki(e,n){return JSON.stringify([e.realPath,n.source,n.relativePath])}async function Qs(e,n,t,i,o,r,s,a){let d=e.fingerprintVerifiedFile,c=Ki(t,i),p=o.candidates.get(c),y=i.relativePath,A;try{A=await Fi(e,n,y);}catch(E){if(q(E)!=="NOT_FOUND")throw E}let _=A===void 0?void 0:{relativePath:y,key:A};if(_!==void 0&&(i.source==="apps"||i.source==="skills")&&!Xi(_.key,"ui-plugin.json"))return ue(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(ji.map(async E=>{if(E==="")return _;let m=`${i.relativePath}${E}`;try{let N=await Fi(e,n,m);return N===void 0?void 0:{relativePath:m,key:N}}catch(N){if(q(N)==="NOT_FOUND")return;throw N}}));if(!ue(s,a))return {timeLimitReached:true};let D=typeof d=="function"&&T.every(E=>E!==void 0),M=T.filter(E=>E!==void 0),v=new Map,C=p!==void 0&&D,U;if(p!==void 0&&typeof d=="function"){let E=await Promise.all(p.files.map(async m=>{if(!ue(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 q(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"){C=false;continue}if(m.kind!=="fingerprint")continue;let{file:N,current:S}=m;v.set(N.relativePath,S),U??=S.candidateRealPath,(S.candidateRealPath!==p.candidateRealPath||!Yi(S,N.fingerprint)||qi(S,r))&&(C=false);}}let j=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&&j&&C&&U===p.candidateRealPath?{memo:p}:!D||M.length!==ji.length?{}:{context:{state:o,cacheKey:c,workspaceRoot:n,scanStartedAtNs:r,directoryListings:Object.freeze(M),priorFingerprints:v,files:new Map,...U===void 0?{}:{candidateRealPath:U},cacheable:true}}}function Xi(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 Fi(e,n,t){let i=Zi(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(Gi);if(!r.some(s=>s===null))return JSON.stringify(r.slice().sort((s,a)=>Ze(s.name,a.name)||Ze(s.kind,a.kind)).map(s=>[s.name,s.kind]))}function Yi(e,n){return e.dev===n.dev&&e.ino===n.ino&&e.size===n.size&&e.mtimeNs===n.mtimeNs&&e.ctimeNs===n.ctimeNs}function qi(e,n){let t=e.mtimeNs-n;return t>=-Vi&&t<=Vi}function Nt(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 ea(e,n,t){let i=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 na(e,n){let t={...e.definition,sourceHash:n},i;try{i=ce(t);}catch(r){throw r instanceof L&&r.code==="INPUT_INVALID"?new K("MANIFEST_INVALID","normalized definition is invalid"):r}let o={...t,hash:i};try{de(o);}catch{throw new K("MANIFEST_INVALID","normalized definition is invalid")}return o}function ta(e){return e.actions.some(n=>n.backend.type==="core"&&n.backend.handler!=="state.set")}function ia(e){if(typeof e.readVerifiedFile=="function")return e.readVerifiedFile;if(typeof e.readFileVerified=="function")return e.readFileVerified}function Zi(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 Bi(e,n,t,i){let o=ia(e);if(!o)throw new P("READ_DENIED");return Ws(await o.call(e,n,t,i))}async function oa(e,n,t){let i=Zi(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(Gi).filter(r=>r!==null)}function ra(e){let n=[];for(let t of [e.reserved,e.builtin])t&&n.push(t);return e.builtins&&"listMcpApps"in e.builtins?n.push(Hi(e.builtins)):e.builtins&&n.push(e.builtins),e.builtinCatalog&&n.push(Hi(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 Hi(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 fe(e,n){e.diagnostic||(e.diagnostic=_n(n,e.source,e.relativePath,e.identity?.pluginId));}function sa(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&&fe(s,"RESERVED_ID");if(o.length>1)for(let s of o)fe(s,"DUPLICATE_ID");continue}let r=i.filter(s=>s.source==="apps");if(r.length>1){for(let s of r)fe(s,"DUPLICATE_ID");for(let s of i.filter(a=>a.source==="skills"))fe(s,"DUPLICATE_ID");}else for(let s of i.filter(a=>a.source==="skills"))fe(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)fe(o,"DUPLICATE_ID");}function aa(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 ra(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)){fe(d,"RESERVED_ID");continue}if(d.provenance===void 0&&(s.has(c.pluginId)||a.has(c.definitionId))){fe(d,"RESERVED_ID");continue}[c.toolNames.read,c.toolNames.action].filter(y=>y!==void 0).some(y=>r.has(y))&&fe(d,"DUPLICATE_ID");}}function ca(e){return [...e].sort((n,t)=>{let i=Ui.indexOf(n.source)-Ui.indexOf(t.source);return i!==0?i:Ze(n.relativePath,t.relativePath)})}function w(e,n){e.diagnostic=_n(n,e.source,e.relativePath,e.identity?.pluginId);}async function zi(e,n,t){if(t.byteLength>262144){w(n,"LIMIT_EXCEEDED");return}let i;try{i=Ks(t);}catch{w(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)}`){w(n,"BUNDLE_INTEGRITY");return}if(qe(i.value)&&i.value.builtinOnly===true){w(n,"RESERVED_ID");return}let o;try{let g=Te(i.value,{mode:"local"});if(g.manifestVersion!==2)throw new K("MANIFEST_INVALID","workspace App requires v2");o=g;}catch(g){if(g instanceof K){w(n,xi(g));return}if(g instanceof pe){w(n,Dt(g.code));return}if(qe(g)&&typeof g.code=="string"){w(n,Dt(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{hi(o.actions.map(g=>({actionId:g.actionId,inputSchema:g.inputSchema})));}catch(g){if(g instanceof pe){w(n,Dt(g.code));return}throw g}let s;try{s=await Tn(e,n,"ui/index.html",We);}catch(g){w(n,ve(q(g),"entry"));return}if(s.byteLength>We){w(n,"LIMIT_EXCEEDED");return}let a;try{a=$i(s);}catch{w(n,"ENTRY_INVALID");return}if(s.byteLength===0||a.length===0){w(n,"ENTRY_INVALID");return}let d=createHash("sha256").update(s).digest("hex");if(o.entryHash!==void 0&&o.entryHash!==d){w(n,"ENTRY_INVALID");return}let c={},p,y;if(o.initialState!==void 0){try{p=await Tn(e,n,"ui/state.json",65536);}catch(g){w(n,ve(q(g),"initial"));return}if(p.byteLength>65536){w(n,"LIMIT_EXCEEDED");return}try{let g=Wi(p),x=o.dataPaths??[],te=et(g,x);c=se(te,0,x),Se(c);}catch{w(n,"INITIAL_STATE_INVALID");return}if(y=createHash("sha256").update(p).digest("hex"),o.initialState.hash!==void 0&&o.initialState.hash!==y){w(n,"INITIAL_STATE_INVALID");return}}let A={...o,entryHash:d,...o.initialState===void 0?{}:{initialState:{path:"ui/state.json",hash:y}}},_=nt(A),T=ea(A,s,p??new Uint8Array),D;try{D=na(_,T);}catch(g){if(g instanceof K){w(n,xi(g));return}throw g}let M;if(n.bundleLineage!==void 0){let g=n.bundleLineage[n.bundleLineage.length-1];if(!g){w(n,"LINEAGE_INVALID");return}let{legacy:x,...te}=g.definition,{hash:z,...ie}=D;if(Q(te)!==Q(ie)){w(n,"LINEAGE_STALE");return}if(x!==void 0&&(D={...D,legacy:x}),x!==void 0)try{D={...D,hash:ce(D)},de(D);}catch{w(n,"LINEAGE_INVALID");return}M=n.bundleLineage;}if(n.bundleIdentity!==void 0&&n.bundleIdentity.appId!==o.pluginId){w(n,"BUNDLE_INTEGRITY");return}if(n.bundleIdentity!==void 0&&(n.bundleIdentity.definitionId!==D.id||n.bundleIdentity.version!==D.version||n.bundleIdentity.definitionHash!==D.hash)){w(n,"LINEAGE_STALE");return}let v=Hs(o.pluginId),C=o.actions.length===0?{read:v.read}:v,U=xe(_),j=xe(A),E=xe(D),m=xe({..._.handlers}),N=vi(s),S=p===void 0?void 0:vi(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:j,normalized:U,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:xe(c),...S===void 0?{}:{initialStateBytes:S},...y===void 0?{}:{initialStateHash:y},sourceHash:T,toolNames:Object.freeze(C)},I=n.provenance===void 0?{...u,source:n.source}:{...u,provenance:n.provenance,lineage:M??[]};n.candidate=Object.freeze(I),ta(o)&&w(n,"EXEC_DENIED");}async function da(e,n){try{return await Tn(e,n,"ui-plugin.json",262144)}catch(t){if(q(t)==="NOT_FOUND")return;w(n,ve(q(t),"manifest"));return}}function pa(e,n,t,i=Bs,o=false){let r=ca(e);sa(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 la(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 ua(e,n){if(la(e))return {fs:e,options:{}};let t=e??n??{};return {fs:t.filesystem??t.fileSystem??t.fs??Ni,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}=ua(n,t),r=o.clock??Zs,s=r(),a=await wi(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=_i(o.scanCache,D),T.scanStartedAtNs=c;}catch(E){if(q(E)!=="NOT_FOUND")throw E}let M=T!==void 0&&o.productBundle===void 0&&a.packages.length===0&&a.diagnostics.length===0,v=new Set,C=true;p.push(...a.diagnostics.map(E=>({source:E.source,root:o.productBundle?.root??e,name:"",relativePath:E.relativePath,diagnostic:E})));let U=a.reservedIds;a.incomplete&&(A="time_limit");for(let E of a.packages){if(!ue(d,r)){_=true,A="time_limit";break}let m=E.indexEntry,N=m.packageDir,S=E.files===void 0?void 0:Ys(N,E.files),f=a.indexHash===void 0?void 0:pi(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:Xs(m)};if(p.push(u),y+=1,E.failureCode!==void 0){w(u,E.failureCode);continue}let I=E.files?.get("ui-plugin.json");if(I===void 0){w(u,"BUNDLE_INTEGRITY");continue}if(await zi(i,u,I),!ue(d,r)){_=true,A="time_limit";break}}let j=[{source:"apps",directory:"apps"},{source:"skills",directory:"skills"}];e:for(let E of j){let{source:m,directory:N}=E,S;try{S=await oa(i,e,N);}catch(u){if(q(u)==="NOT_FOUND")continue;M=false,C=false,p.push({source:m,root:e,name:"",relativePath:m,diagnostic:_n(ve(q(u),"manifest"),m,m)});continue}let f=S.filter(u=>u.kind==="directory"||u.kind==="symlink").filter(u=>$s(u.name)).map(u=>({source:m,root:e,name:u.name,relativePath:Gs(m,u.name)})).sort((u,I)=>Ze(u.relativePath,I.relativePath));for(let u of f){let I={...u};if(p.push(I),D!==void 0?v.add(Ki(D,I)):M=false,!ue(d,r)){_=true,A="time_limit";break e}let g;if(T!==void 0&&D!==void 0){try{let z=await Qs(i,e,D,I,T,c,d,r);if(z.timeLimitReached){_=!0,A="time_limit";break e}I.scanContext=z.context,g=z.memo;}catch(z){M=false,w(I,ve(q(z),"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){w(I,"LIMIT_EXCEEDED");continue}if(u.relativePath.split("/").length-1>2){w(I,"LIMIT_EXCEEDED");continue}if(y+=1,!ue(d,r)){_=true,A="time_limit";break e}continue}let x;if(m==="skills"&&(x=await da(i,I),x===void 0)){I.diagnostic===void 0&&Nt(I);continue}if(y>=64){w(I,"LIMIT_EXCEEDED");continue}if(u.relativePath.split("/").length-1>2){w(I,"LIMIT_EXCEEDED");continue}if(!ue(d,r)){_=true,A="time_limit";break e}if(y+=1,x===void 0)try{x=await Tn(i,I,"ui-plugin.json",262144);}catch(z){w(I,ve(q(z),"manifest")),Nt(I);continue}if(await zi(i,I,x),Nt(I),!ue(d,r)){_=true,A="time_limit";break e}}}if(T!==void 0&&D!==void 0){let E=[...v].sort(Ze),m=T.lastCandidateKeys,N=m!==void 0&&m.length===E.length&&m.every((f,u)=>f===E[u]);if(M=M&&N,C&&!_&&A===void 0)for(let f of T.candidates.keys())try{JSON.parse(f)[0]===D.realPath&&!v.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===v.size&&S.every(f=>v.has(f))&&!_&&A===void 0,T.lastCandidateScanUnchanged=M,C&&!_&&A===void 0&&(T.lastCandidateKeys=Object.freeze(E));}return _&&p.push({source:"apps",root:e,name:"",relativePath:"apps",diagnostic:_n("DISCOVERY_TIME_LIMIT","apps","apps")}),aa(p,o,U),pa(p,A,a.indexHash,U,o.productBundle!==void 0)}var Bs,Pt,Ui,zs,ji,Vi,eo=V(()=>{h();Ue();en();ge();tt();Le();dt();ln();Ti();gt();un();bt();bt();Bs=hn([]),Pt="crewx_local_app_";Ui=["bundled","apps","skills"],zs=new TextDecoder("utf-8",{fatal:true});ji=["","/ui"],Vi=2000000000n;});h();tt();h();vn();h();var ei="SKILL.md",Jr=/^---\s*\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;function ni(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function Kr(e){return e.isDirectory()||e.isSymbolicLink()}function si(e){try{return existsSync(e)&&statSync(e).isDirectory()}catch{return false}}function it(e){let n;try{n=readFileSync(e,"utf8");}catch{return {frontmatter:{},readable:false,valid:false,hasFrontmatter:false}}let t=n.match(Jr);if(!t)return {frontmatter:{},readable:true,valid:true,hasFrontmatter:false};try{let i=load(t[1]??"");if(!ni(i))return {frontmatter:{},readable:!0,valid:!1,hasFrontmatter:!0};let o=ni(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 Xr(e){return [join(e,ei),join(e,"skill",ei)]}function ti(e,n){if(!si(e))return null;for(let t of Xr(e)){if(!existsSync(t))continue;let o=it(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 ii(e){try{return readdirSync(e,{withFileTypes:!0}).filter(Kr)}catch{return []}}function oi(e,n,t){!e||n.has(e.name)||(n.add(e.name),t.push(e));}function ai(e){let n=[],t=new Set;for(let i of e)if(si(i))for(let o of ii(i)){if(o.name.startsWith("@")){let r=join(i,o.name);for(let s of ii(r))oi(ti(join(r,s.name),s.name),t,n);continue}oi(ti(join(i,o.name),o.name),t,n);}return n.sort((i,o)=>i.name.localeCompare(o.name))}eo();var ya=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/;function Pn(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?Aa(e.relativePath,e.fileBytes):void 0);if(n!==void 0&&i!==void 0){let o=JSON.stringify({screenHash:n,skillHash:i});return createHash("sha256").update(o,"utf8").digest("hex")}if(n!==void 0)return n;if(i!==void 0)return i;throw new TypeError("App definition hash input must contain a screenHash or skill bytes")}function Aa(e,n){let t=new TextEncoder().encode(Dn(e)),i=Ia(n),o=new Uint8Array(t.byteLength+1+i.byteLength);return o.set(t,0),o[t.byteLength]=0,o.set(i,t.byteLength+1),createHash("sha256").update(o).digest("hex")}function Ia(e){if(typeof e=="string")return new TextEncoder().encode(e);if(e instanceof Uint8Array)return new Uint8Array(e);if(e instanceof ArrayBuffer)return new Uint8Array(e.slice(0));if(Array.isArray(e)&&e.every(n=>Number.isInteger(n)&&n>=0&&n<=255))return Uint8Array.from(e);throw new TypeError("fileBytes must be UTF-8 text or bytes")}function Dn(e){if(typeof e!="string"||e.length===0||isAbsolute(e)||/[\\\u0000]/.test(e))throw new TypeError("relative path must be package-relative");let n=e.split("/").filter(t=>t.length>0&&t!==".").join("/");if(!n||n.split("/").some(t=>t===".."))throw new TypeError("relative path must stay inside the package");return n}function bn(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 io(e,n){let t=relative(e,n).split(sep).join("/");return !t||t===".."||t.startsWith("../")||isAbsolute(t)?null:Dn(t)}function ga(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 oo(e){return Object.freeze({packageRoot:e})}function ma(e){return Object.freeze({id:e.definition.id,version:e.definition.version,hash:e.definition.hash,usage:e.definition.usage??me,...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 ro(e){return {capabilities:Object.freeze([...e]),origin:"local",ownership:"unknown",shareability:"unknown",sharingAvailability:"unavailable"}}function ha(e,n){let t=e.candidate,i=t.provenance!==void 0,o=n&&!i?["screen","skill"]:["screen"],r=ma(t),s=Pn(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,...ro(o),definition:r,...n===void 0||i?{}:{skillName:n.skill.name},...i?{provenance:t.provenance}:{localDefinitionRef:oo(e.packageRoot)},definitionHash:s};return {...i?{}:{packageRoot:e.packageRoot},source:i?"bundled":t.source,appId:c.appId,capabilities:o,summary:Object.freeze(c)}}function Ea(e){let n=_a(e.skill.name),t={appId:n,name:e.skill.name,description:e.skill.description??"",...e.skill.version===void 0?{}:{version:e.skill.version},...ro(["skill"]),skillName:e.skill.name,localDefinitionRef:oo(e.packageRoot),definitionHash:Pn({skillHash:e.skillHash})};return {packageRoot:e.packageRoot,source:e.source,appId:n,capabilities:["skill"],summary:Object.freeze(t)}}function _a(e){return `skill.${e.replace(/^@/,"").replace(/\//g,".").replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,122)||"unnamed"}`}function G(e,n,t,i){return Object.freeze({code:e,source:n,relativePath:Ta(t),...i===void 0?{}:{appId:i}})}function Ta(e){if(typeof e!="string"||e.length===0||isAbsolute(e)||/[\\\u0000]/.test(e))return "<unknown>";let n=e.split("/").filter(t=>t.length>0&&t!==".").join("/");return n.split("/").some(t=>t==="..")?"<unknown>":n}function so(e){return G(e.code,e.source,e.relativePath,e.pluginId)}function ba(e,n){let t=io(e,n.dir);if(!t)return {diagnostic:G("PATH_ESCAPED","node_modules","node_modules")};let i=ga(t);if(!i)return {diagnostic:G("PATH_ESCAPED","node_modules",t)};let o=it(n.skillMdPath);if(!o.readable)return {diagnostic:G("SKILL_READ_FAILED",i,t)};if(!o.valid)return {diagnostic:G("SKILL_INVALID",i,t)};let r=Pa(n.dir,n.skillMdPath);if(!r)return {diagnostic:G("PATH_ESCAPED",i,t)};try{let s=new Uint8Array(readFileSync(n.skillMdPath));return {skill:n,packageRoot:t,relativeSkillPath:r,skillHash:Pn({relativePath:r,fileBytes:s}),source:i}}catch{return {diagnostic:G("SKILL_READ_FAILED",i,t)}}}function Pa(e,n){let t=relative(e,n).split(sep).join("/");try{return Dn(t)}catch{return null}}function Da(e){if(!ya.test(e.appId))return {diagnostic:G("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??me,...e.definition.detailPanel===void 0?{}:{detailPanel:e.definition.detailPanel},...e.definition.displayModes===void 0?{}:{displayModes:e.definition.displayModes},...e.definition.summaryProjection===void 0?{}:{summaryProjection:e.definition.summaryProjection}},t=n?.hash??createHash("sha256").update(JSON.stringify({appId:e.appId,name:e.name,description:e.description}),"utf8").digest("hex"),i={appId:e.appId,name:e.name,description:e.description,...n===void 0?{}:{version:String(n.version),definition:n},capabilities:["screen"],origin:"builtin",ownership:"unknown",shareability:"forbidden",sharingAvailability:"unavailable",definitionHash:t};return {source:"builtin",appId:e.appId,summary:Object.freeze(i)}}function Na(e){return e.builtinCatalog}function Sa(e){let n=e.packageRoot??e.relativePath??e.packageRootPath;if(n===void 0)return null;try{return Dn(n)}catch{return null}}function Ma(e){let n=e.marketplaceContentId;return typeof n=="string"&&n.length>0?n:void 0}function La(e,n,t){let i=n.installed??[],o=new Map;for(let s of i){let a=Sa(s);if(!a){t.push(G("INSTALLED_IDENTITY_MISMATCH","installed","installed"));continue}let d=o.get(a);if(d&&JSON.stringify(d)!==JSON.stringify(s)){t.push(G("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(G("INSTALLED_MISSING","installed",s,a.appId));continue}let c=Ma(a);if(!c){t.push(G("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(G("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 Oa(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(G("RESERVED_ID",a.source,Mt(a),a.appId));if(s.length>1)for(let a of s)i.add(a),n.push(G("DUPLICATE_ID",a.source,Mt(a),a.appId));continue}for(let s of o)i.add(s),n.push(G("DUPLICATE_ID",s.source,Mt(s),s.appId));}return e.filter(o=>!i.has(o))}function Mt(e){return e.packageRoot??e.summary.provenance?.packageDir??`builtin/${e.appId}`}function Ra(e,n){return e.filter(t=>!(t.code==="MANIFEST_MISSING"&&n.has(t.relativePath))).map(so)}function wa(e){return e.filesystem}function Ua(e,n){let t=wa(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 ao(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=Na(n),i=await Qi(e,Ua(n,t)),o=n.registeredProductBundle??i.productBundleSnapshotMetadata,r=[join(e,"skills"),join(e,"node_modules"),join(e,"apps")],s=[],a=[],d=[],c=new Set;for(let u of r)for(let I of ai([u])){let g=io(e,I.dir);(g===null||!c.has(g))&&(d.push(I),g!==null&&c.add(g));}for(let u of d){let I=ba(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])),v=[];for(let u of p.values()){let I=u.candidate.provenance===void 0?M.get(u.packageRoot):void 0,g=ha(u,I);v.push({...g.packageRoot===void 0?{}:{packageRoot:g.packageRoot},source:g.source,appId:g.appId,summary:g.summary});}let C=new Set([...p.values()].filter(u=>u.candidate.provenance===void 0).map(u=>u.packageRoot)),U=o===void 0?new Set:new Set(i.diagnostics.filter(u=>u.code==="RESERVED_ID"&&u.source!=="bundled").map(u=>u.relativePath)),j=new Set(o?.reservedAppIds??[]);for(let u of a){let I=Ea(u);if(!(C.has(u.packageRoot)||U.has(u.packageRoot))){if(j.has(I.appId)){s.push(G("RESERVED_ID",u.source,u.packageRoot,I.appId));continue}v.push({packageRoot:I.packageRoot,source:I.source,appId:I.appId,summary:I.summary});}}let E=[...Ra(i.diagnostics,new Set(a.map(u=>u.packageRoot))),...s,...n.registeredProductBundle?.diagnostics.filter(u=>u.source==="bundled").map(so)??[]],m=[];if(t)for(let u of t.listMcpApps()){let I=Da(u);"diagnostic"in I?E.push(I.diagnostic):m.push(I);}let N=Oa([...v,...m],E);La(N,n,E);let S=N.map(u=>u.summary).sort((u,I)=>bn(u.appId,I.appId)),f=[...E].sort((u,I)=>bn(u.relativePath,I.relativePath)||bn(u.code,I.code)||bn(u.appId??"",I.appId??""));return Object.freeze({items:Object.freeze(S),diagnostics:Object.freeze(f)})}h();h();h();function ka(e){let n=o=>o.replace(/[.+^${}()|[\]\\]/g,"\\$&"),i=e.split("/").map(o=>o==="**"?".*":o.split("*").map(n).join("[^/]*"));return new RegExp(`^${i.join("\\/")}$`)}function je(e,n){try{return ka(n).test(e)}catch{return false}}function Nn(e,...n){let t=e.split("/");if(t.length<n.length)return false;let i=t.length-n.length;return n.every((o,r)=>je(t[i+r],o))}function Ca(e,n){return e.split("/").some(t=>je(t,n))}var co=[{label:".env*",test:e=>je(e,".env*")},{label:".git/",test:(e,n,t)=>t&&e===".git"},{label:"memory/",test:(e,n,t)=>t&&e==="memory"},{label:"*.key",test:e=>je(e,"*.key")},{label:"*.pem",test:e=>je(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&&Nn(n,".crewx","threads")},{label:".crewx/crewx.db",test:(e,n,t)=>!t&&Nn(n,".crewx","crewx.db")},{label:".crewx/*.log",test:(e,n,t)=>!t&&Nn(n,".crewx","*.log")},{label:".crewx/publish/",test:(e,n,t)=>t&&Nn(n,".crewx","publish")},{label:".crewx/",test:(e,n)=>Ca(n,".crewx")}];function Sn(e,n,t){for(let i of co)if(i.test(e,n,t))return i.label;return null}function Rt(e){let n=[],t=[];function i(o,r,s){let a;try{a=$.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=J.join(o,d.name);if(d.isSymbolicLink()){let y;try{y=$.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??Sn(d.name,c,false);A?t.push({path:c,rule:A}):t.push({path:c,rule:"symlink"});continue}if(d.isDirectory()){let y=s??Sn(d.name,c,true);i(p,c,y);continue}if(d.isFile()){let y=s??Sn(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 xa=[{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 va(e){return e.includes(0)}function wt(e,n,t){let i=[];for(let o of n){let r=J.join(e,o),s;try{let d=t?.get(o);s=d===void 0?$.readFileSync(r):Buffer.from(d);}catch{continue}if(va(s))continue;s.toString("utf8").split(/\r\n|\r|\n/).forEach((d,c)=>{for(let{rule:p,regex:y}of xa)y.test(d)&&i.push({path:o,line:c+1,rule:p});});}return i}h();h();var ye=class extends Error{constructor(t,i){super(`publish: [${t}]${i?` ${i}`:""}`);this.code=t;}code;name="PublishError"};function b(e,n){return new ye(e,n)}var fo=/^[a-z0-9-]+$/,ja=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/,Va=/^[A-Za-z_][A-Za-z0-9_]*$/;function Fa(e){let n=J.join(e,"crewx.yaml");if(!$.existsSync(n))return {};let t;try{t=yo.load($.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 Ba(e){return Ut.createHash("sha256").update(e).digest("hex")}function Ao(e){let n;try{n=$.lstatSync(e);}catch{throw b("PACKAGE_FILE_INVALID",`file is not readable: ${J.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 Ut.createHash("sha256").update(new Uint8Array($.readFileSync(e))).digest("hex")}function Ha(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 Io(e){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||J.posix.isAbsolute(e)||e.split("/").some(n=>n===".."||n.length===0))throw b("PACKAGE_PATH_TRAVERSAL","manifest file path must be a non-empty POSIX relative path")}function za(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 go(e){if(!ja.test(e))throw new Error(`publish: invalid version "${e}" \u2014 must be semver (e.g. 1.0.0)`)}function mo(e,n,t={}){let i=Fa(e),o=i.name??J.basename(e);if(!fo.test(o))throw new Error(`publish: invalid name "${o}" \u2014 must match ${fo} (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");go(r);let s=Array.isArray(i.requiredEnv)?i.requiredEnv:[],a=[];for(let p of s){if(typeof p!="string"||!Va.test(p))throw new Error(`publish: requiredEnv must contain names only (no values), got "${String(p)}"`);a.push(p);}let d=n.map(p=>(Io(p),{path:p,sha256:Ao(J.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 Ga(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 ho(e,n){if(za(n.packageRoot),!n.version)throw new Error("publish: version is required for App publishing \u2014 pass opts.version");if(go(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(Io(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?Ao(J.join(e,s)):Ba(a),...a===void 0?{}:{generated:true}}}).sort((s,a)=>Ha(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:Ga(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 Eo(e){return Ut.createHash("sha256").update(e).digest("hex")}function Do(e,n){if(typeof n!="string"||n.length===0||n.includes("\\")||n.includes("\0")||J.posix.isAbsolute(n)||n.split("/").some(o=>o===".."||o.length===0))throw b("PACKAGE_PATH_TRAVERSAL","archive paths must be non-empty POSIX relative paths");let t=J.resolve(e),i=J.resolve(t,...n.split("/"));if(i!==t&&!i.startsWith(`${t}${J.sep}`))throw b("PACKAGE_PATH_TRAVERSAL","archive path escaped its root");return i}function _o(e,n){let t=Do(e,n),i;try{i=$.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($.readFileSync(t))}async function No(e,n,t={}){let i=J.join(e,".crewx","publish");$.mkdirSync(i,{recursive:true});let o=J.join(i,`${n.name}-${n.version}.tgz`),r=J.join(i,`.${n.name}-${n.version}.${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}.tmp.tgz`),s=$.mkdtempSync(J.join(To.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 _=_o(e,c.path);if(t.sourceFileHashes.get(c.path)!==Eo(_))throw b("PACKAGE_STAGED_BYTES_MISMATCH","workspace source changed before staging")}let y=p??_o(e,c.path);if(Eo(y)!==c.sha256)throw b("PACKAGE_STAGED_BYTES_MISMATCH",`staged bytes differ for ${c.path}`);let A=Do(s,c.path);$.mkdirSync(J.dirname(A),{recursive:!0}),$.writeFileSync(A,new Uint8Array(y)),d.push(c.path);}$.writeFileSync(J.join(s,"manifest.json"),JSON.stringify(n,null,2)),await Po.create({gzip:!0,file:r,cwd:s,portable:!0,noMtime:!0},["manifest.json",...d]),$.renameSync(r,o);}finally{try{$.rmSync(r,{force:!0});}catch{}$.rmSync(s,{recursive:true,force:true});}return o}h();h();var Ve="/api/v1";var Ja=201,Ka=200,Xa=409,kt=401,So={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 Ya(){return process.env.WI013_FAKE_UPLOAD==="1"}function qa(e){let n=gunzipSync(new Uint8Array(e)),t=gzipSync(new Uint8Array(n),{level:1});if(Buffer.compare(new Uint8Array(t),new Uint8Array(e))===0)throw new Error("publish: [E_MALFORMED] Re-gzipped upload bytes are identical to the original \u2014 tamper is a no-op");return t}function Za(e){return e.replace(/\/+$/,"")}async function Qe(e){try{return await e.json()}catch{return null}}function Mo(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 Qa(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 ec(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 Lo(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(So,r))continue;let s=r,a=s==="APP_NAME_CONFLICT"?`marketplace name is already in use: ${n}`:void 0;return b(So[s],a)}}async function nc(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=Za(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}${Ve}/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 Qe(a),c=Qa(d),p=ec(d),y=r&&p!==void 0?p:i,A;if(a.status===Ja)A="created";else if(r&&a.status===Ka){if(c===void 0)throw b("PUBLISH_CONTENT_ID_MISSING","App republish did not return an opaque contentId");A="existing";}else if(a.status===Xa){if(r)throw Lo(d,i)??b("APP_NAME_CONFLICT",`marketplace name is already in use: ${i}`);A="existing";}else throw a.status===kt?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}${Ve}/publisher/items`,{method:"GET",headers:{Authorization:`Bearer ${e.accessToken}`}});}catch{throw new Error("publish: [E_NETWORK] Publisher items request failed (network)")}let S=await Qe(N);if(N.status!==200)throw new Error(`publish: [E_HTTP] Publisher items request failed \u2014 HTTP ${N.status}`);let u=Mo(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}${Ve}/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 Qe(g),g.status===kt?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=$.readFileSync(e.tgzPath),M=Ya()?qa(D):D,v=new FormData;v.set("archive",new Blob([new Uint8Array(M)],{type:"application/gzip"}),`${y}-${e.manifest.version}.tgz`);let C=r&&c!==void 0?c:i,U;try{U=await fetch(`${n}${Ve}/publisher/items/${encodeURIComponent(C)}/upload`,{method:"POST",headers:{Authorization:`Bearer ${e.accessToken}`},body:v});}catch{throw new Error("publish: [E_NETWORK] Upload request failed (network)")}if(U.status===kt)throw new Error("publish: [E_AUTH_EXPIRED] Authentication is expired or missing \u2014 please log in again (HTTP 401)");if(!U.ok){let N=await Qe(U);if(r){let S=Lo(N,y);if(S)throw S}throw new Error(`publish: [E_HTTP] Upload request failed \u2014 HTTP ${U.status}`)}let j=await Qe(U),E=Mo(j,"upload",U.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 tc=1e4,ic=100*1024*1024;function Ct(e){return Ut.createHash("sha256").update(e).digest("hex")}function oc(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function Ln(e,n){if(!n||n.includes("\\")||n.includes("\0")||J.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=J.resolve(e,...n.split("/")),i=J.resolve(e);if(t!==i&&!t.startsWith(`${i}${J.sep}`))throw b("PACKAGE_PATH_TRAVERSAL","workspace file path escaped the workspace root");let o;try{o=$.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($.readFileSync(t))}function On(e,n){return e===n||e.startsWith(`${n}/`)}function rc(e,n){return e.path<n.path?-1:e.path>n.path?1:e.rule.localeCompare(n.rule)}function Ro(e,n,t){let i=e??n;if(!Number.isSafeInteger(i)||i<=0)throw new ye("PACKAGE_SIZE_LIMIT",`${t} must be a positive integer`);return i}function Uo(e,n,t,i){let o=Ro(t.maxFileCount??t.maxFiles,tc,"max file count"),r=Ro(t.maxTotalBytes??t.maxBytes,ic,"max total bytes");if(n.length>o)throw new ye("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+=Ln(e,a).byteLength,s>r)throw new ye("PACKAGE_SIZE_LIMIT",`package exceeds byte limit (${r})`)}}function sc(e){return e.appId!==void 0||e.expectedDefinitionHash!==void 0}function ac(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 cc(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 dc(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(On(i.path,n)?i:{path:i.path,rule:"out-of-app-scope"});for(let i of e.included)On(i,n)||t.push({path:i,rule:"out-of-app-scope"});return t.sort(rc)}function lc(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=Ln(e,o),s=Ct(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=Te(a,{mode:"local"});if(A.manifestVersion!==2)throw new Error("screen App requires manifestVersion 2");d=A;}catch(A){throw A instanceof K?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=Ct(Ln(e,c)),y=JSON.parse(JSON.stringify(a));if(y.entryHash=p,Object.prototype.hasOwnProperty.call(y,"initialState")){let A=y.initialState;if(!oc(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=Ln(e,_);y.initialState={...A,hash:Ct(T)};}try{let A=Te(y,{mode:"published"});return {bytes:new Uint8Array(Buffer.from(xn(A),"utf8")),sourceHash:s}}catch(A){throw A instanceof K?b("APP_UI_MANIFEST_INVALID",A.code):b("APP_UI_MANIFEST_INVALID")}}async function uc(e,n){let{included:t,excluded:i}=Rt(e);Uo(e,t,n);let o=mo(e,t,{version:n.version}),r=wt(e,t);return {plan:{manifest:o,included:t,excluded:i,secretFindings:r},archiveOptions:{}}}async function fc(e,n){ac(n);let t=await ao(e),i=cc(t.items,n.appId);if(i.definitionHash!==n.expectedDefinitionHash)throw b("APP_DEFINITION_CONFLICT",`definitionHash changed for ${n.appId}`);let o=dc(i),r=Rt(e);if(r.excluded.some(_=>On(_.path,o)&&(_.rule==="symlink"||_.rule==="symlink-dir")))throw b("PACKAGE_SYMLINK","selected App package contains a symlink");let s=r.included.filter(_=>On(_,o)),a=pc(r,o),d=new Map,c=new Map;if(i.capabilities.includes("screen")){let _=lc(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");Uo(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=ho(e,p),A=wt(e,s,d);return {plan:{manifest:y,included:s,excluded:a,secretFindings:A},archiveOptions:{generatedFiles:d,sourceFileHashes:c}}}async function ko(e,n){let t=J.resolve(e);if(sc(n))return fc(t,n);if(n.expectedDefinitionHash!==void 0)throw b("APP_ID_REQUIRED");return uc(t,n)}async function Cl(e,n={}){return (await ko(e,n)).plan}function yc(e){let n=e.map(t=>`${t.path}:${t.line} (${t.rule})`).join(", ");throw new ye("PUBLISH_SECRET_FINDINGS",`aborted \u2014 secret findings must be resolved before packing: ${n}`)}async function Co(e,n={}){let t=J.resolve(e),i=await ko(t,n);i.plan.secretFindings.length>0&&yc(i.plan.secretFindings);let o=await No(t,i.plan.manifest,i.archiveOptions);return {manifest:i.plan.manifest,tgzPath:o}}async function xl(e,n={}){return Co(e,n)}async function vl(e,n){let t=await Co(e,n);if(t.manifest.type!=="app")throw new Error("publish: App pack unexpectedly produced a template manifest");return t}
|
|
2
|
-
export{
|
|
1
|
+
import*as ne from'path';import {resolve,relative,sep,isAbsolute,join}from'path';import'url';import*as si from'crypto';import {createHash}from'crypto';import {isIP}from'net';import*as K from'fs';import {constants,readFileSync,existsSync,statSync,readdirSync}from'fs';import {realpath,stat,readdir,open,lstat}from'fs/promises';import*as or from'js-yaml';import {load}from'js-yaml';import*as ur from'os';import*as yr from'tar';import {gunzipSync,gzipSync}from'zlib';var V=(e,n)=>()=>(e&&(n=e(e=0)),n);var g=V(()=>{});var O,mn=V(()=>{g();O=class extends Error{constructor(t,i=t,r){super(i);this.code=t;this.currentRevision=r;}code;currentRevision;name="UiRuntimeError"};});function qn(e){return Sr.test(e)||Mr.test(e)}function re(){throw new O("INPUT_INVALID","JSON value is not projection-safe")}function wr(e){let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function Xn(e,n,t,i,r,o){if(n>i&&re(),e===null||typeof e=="string"||typeof e=="boolean")return typeof e=="string"&&(Lr.test(e)||Rr.test(e)&&!kr(r,o)||Or.test(e))&&re(),e;if(typeof e=="number")return Number.isFinite(e)||re(),e;(typeof e!="object"||e===void 0||typeof e=="function"||typeof e=="bigint")&&re();let s=e;t.has(s)&&re(),t.add(s);try{if(Array.isArray(e))return e.map(d=>Xn(d,n+1,t,i,r,o));wr(s)||re();let a={};for(let[d,c]of Object.entries(e))qn(d)&&re(),a[d]=Xn(c,n+1,t,i,[...r,d],o);return a}finally{t.delete(s);}}function _e(e,n=0,t=[]){(!Number.isInteger(n)||n<0||n>Cr)&&re(),(!Array.isArray(t)||t.some(r=>typeof r!="string"))&&re();let i=Xn(e,0,new Set,Ur+n,[],t);return (i===null||Array.isArray(i)||typeof i!="object")&&re(),i}function Be(e,n){if(!e||!n)return false;let t=e.split("."),i=n.split(".");return t.length>=i.length&&i.every((r,o)=>t[o]===r)}function kr(e,n){if(e.length===0)return false;let t=e.join(".");return n.some(i=>Be(t,i))}function He(e){try{let n=JSON.stringify(e);return n===void 0&&re(),n}catch{re();}}function Yn(e){return Array.isArray(e)?e.map(Yn):e!==null&&typeof e=="object"?Object.fromEntries(Object.keys(e).sort().map(n=>[n,Yn(e[n])])):e}function Y(e){return He(Yn(e))}function Zn(e){return Buffer.byteLength(e,"utf8")}var Sr,Mr,Lr,Or,Rr,Ur,Cr,Ee=V(()=>{g();mn();Sr=/(?:proof|token|secret|password|cookie|authorization|private[_-]?key|stack|exception|plugin[_-]?text)/i,Mr=/(?:url|uri|endpoint|path|file(?:name|path)?|cwd|shell|directory|dir|folder)$/i,Lr=/<\/?[A-Za-z][^>]*>/,Or=/^(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)/,Rr=/^(?:https?|file|ftp|ws|wss):\/\//i;Ur=8,Cr=4;});function Qn(e){return Y(e)}var di=V(()=>{g();Ee();});function ze(e){return xr.has(e)||vr.test(e)||jr.test(e)}var pi,xr,vr,jr,hn,en,ue,et,nt,tt,it,ot,Ue=V(()=>{g();pi=["__proto__","prototype","constructor","proof","token","secret","password","cookie","authorization","private_key","private-key","stack","exception","plugin_text","url","uri","endpoint","path","filename","filepath","cwd","shell","directory","dir","folder"],xr=new Set(pi),vr=/(?:proof|token|secret|password|cookie|authorization|private[_-]?key|stack|exception|plugin[_-]?text)/i,jr=/(?:url|uri|endpoint|path|file(?:name|path)?|cwd|shell|directory|dir|folder)$/i;hn=/^[A-Za-z0-9_]+$/,en=/^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)*$/,ue=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,et=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/,nt=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,tt=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/,it=["blue","violet","emerald","amber","rose","sky","slate","indigo"],ot=["inline","panel"];});function rt(e){return typeof e=="string"&&li.includes(e)}var li,ui=V(()=>{g();Ue();li=["text/plain","application/json"];});function _n(e){if(!st(e))return false;let n=Object.keys(e);return !(n.some(t=>t!=="in"&&t!=="out")||n.length===0||Object.hasOwn(e,"in")&&!Vr(e.in)||Object.hasOwn(e,"out")&&!Fr(e.out))}function Vr(e){return st(e)?Object.keys(e).every(t=>t==="mediaType"||t==="required")&&Object.hasOwn(e,"mediaType")&&rt(e.mediaType)&&(!Object.hasOwn(e,"required")||typeof e.required=="boolean"):false}function Fr(e){return st(e)?Object.keys(e).every(t=>t==="mediaType"||t==="range")&&Object.hasOwn(e,"mediaType")&&rt(e.mediaType)&&(!Object.hasOwn(e,"range")||typeof e.range=="boolean"):false}function st(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}var at=V(()=>{g();ui();new TextDecoder("utf-8",{fatal:true,ignoreBOM:true});});function de(e){let t=e.renderer!==void 0||e.surfaces!==void 0||e.stateProjection!==void 0||e.dataPaths!==void 0||e.usage!==void 0||e.detailPanel!==void 0||e.displayModes!==void 0||e.summaryProjection!==void 0||e.legacy!==void 0||Object.values(e.actions).some(r=>r.resultProjection!==void 0)?{id:e.id,version:e.version,...e.renderer===void 0?{}:{renderer:e.renderer},...e.surfaces===void 0?{}:{surfaces:e.surfaces},...e.stateProjection===void 0?{}:{stateProjection:e.stateProjection},...e.dataPaths===void 0?{}:{dataPaths:e.dataPaths},...e.summaryProjection===void 0?{}:{summaryProjection:e.summaryProjection},...e.legacy===void 0?{}:{legacy:e.legacy},...e.usage===void 0?{}:{usage:e.usage},...e.detailPanel===void 0?{}:{detailPanel:e.detailPanel},...e.displayModes===void 0?{}:{displayModes:e.displayModes},...e.sourceHash===void 0?{}:{sourceHash:e.sourceHash},actions:e.actions}:e.sourceHash===void 0?{id:e.id,version:e.version,actions:e.actions}:{id:e.id,version:e.version,sourceHash:e.sourceHash,actions:e.actions},i=_e(t);return createHash("sha256").update(Y(i)).digest("hex")}function Te(e){if(!/^\d+$/.test(String(e.version))||e.version<1||e.id.length<1||e.id.length>128)throw new O("DEFINITION_UNSUPPORTED","UI definition is invalid");if(e.sourceHash!==void 0&&(typeof e.sourceHash!="string"||!Hr.test(e.sourceHash)))throw new O("DEFINITION_UNSUPPORTED","UI definition source hash is invalid");if(!/^[0-9a-f]{64}$/.test(e.hash)||de(e)!==e.hash)throw new O("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=>!$r(i)))throw new O("DEFINITION_UNSUPPORTED","UI action declaration is invalid");if(t.confirmation!==void 0&&t.confirmation!=="none"&&t.confirmation!=="native")throw new O("DEFINITION_UNSUPPORTED","UI action confirmation is invalid");if(t.inputKeys&&(!Array.isArray(t.inputKeys)||t.inputKeys.some(i=>typeof i!="string"||!i)))throw new O("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 O("DEFINITION_UNSUPPORTED","UI action data input declaration is invalid");if(t.resultProjection&&ct(t.resultProjection),t.content!==void 0&&!_n(t.content))throw new O("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 O("DEFINITION_UNSUPPORTED","UI action environment declaration is invalid")}if(e.renderer!==void 0&&(!e.renderer||e.renderer.length>128))throw new O("DEFINITION_UNSUPPORTED","UI definition renderer is invalid");if(e.surfaces&&(!Array.isArray(e.surfaces)||e.surfaces.some(n=>!n||n.length>64)))throw new O("DEFINITION_UNSUPPORTED","UI definition surfaces are invalid");if(e.usage!==void 0&&e.usage!=="card"&&e.usage!=="window")throw new O("DEFINITION_UNSUPPORTED","UI definition usage is invalid");if(e.detailPanel!==void 0&&typeof e.detailPanel!="boolean")throw new O("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 O("DEFINITION_UNSUPPORTED","UI definition displayModes are invalid");if(e.usage==="card"&&e.displayModes!==void 0)throw new O("DEFINITION_UNSUPPORTED","Card definitions cannot declare displayModes");if(e.usage==="window"&&e.detailPanel!==void 0)throw new O("DEFINITION_UNSUPPORTED","Window definitions cannot declare detailPanel");if(e.stateProjection&&ct(e.stateProjection),e.summaryProjection){ct(e.summaryProjection);let n=new Set(e.stateProjection?.allow??[]);if(e.summaryProjection.allow.some(t=>!n.has(t)))throw new O("DEFINITION_UNSUPPORTED","UI summary projection exceeds state projection")}if(e.legacy!==void 0){if(!e.legacy||typeof e.legacy!="object"||Array.isArray(e.legacy)||Object.keys(e.legacy).some(r=>!["readTool","actionTool","hostTools","agentAccess"].includes(r)))throw new O("DEFINITION_UNSUPPORTED","UI legacy metadata is invalid");let n=new Set;for(let[r,o]of [["readTool",e.legacy.readTool],["actionTool",e.legacy.actionTool]])if(o!==void 0){if(zr(o,r==="readTool"),n.has(o.name))throw new O("DEFINITION_UNSUPPORTED","UI legacy tool names collide");n.add(o.name);}let t=e.legacy.hostTools;if(t!==void 0){if(!t||typeof t!="object"||Array.isArray(t))throw new O("DEFINITION_UNSUPPORTED","UI legacy host tools are invalid");let r={"doc.open":"crewx_app_html_viewer_open","pty.connect":"crewx_app_terminal_connect"};for(let[o,s]of Object.entries(t)){if(!Object.hasOwn(r,o)||r[o]!==s||typeof s!="string"||!/^[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(s)||n.has(s))throw new O("DEFINITION_UNSUPPORTED","UI legacy host tools are invalid");n.add(s);}}let i=e.legacy.agentAccess;if(i!==void 0&&(!i||typeof i!="object"||Array.isArray(i)||Object.entries(i).some(([r,o])=>!r||!Object.hasOwn(e.actions,r)||o!=="allowed"&&o!=="denied")))throw new O("DEFINITION_UNSUPPORTED","UI legacy agent access is invalid");if(e.legacy.actionTool!==void 0&&(!i||Object.keys(i).length===0))throw new O("DEFINITION_UNSUPPORTED","UI legacy action tool requires its complete agent access map")}if(e.dataPaths!==void 0){let n=new Set(["__proto__","prototype","constructor"]);if(!Array.isArray(e.dataPaths)||e.dataPaths.length>16||new Set(e.dataPaths).size!==e.dataPaths.length||e.dataPaths.some(t=>typeof t!="string"||!/^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)*$/.test(t)||t.split(".").some(i=>n.has(i))||!(e.stateProjection?.allow??[]).some(i=>Be(t,i))))throw new O("DEFINITION_UNSUPPORTED","UI definition dataPaths are invalid")}}function zr(e,n){if(!e||typeof e!="object"||Array.isArray(e))throw new O("DEFINITION_UNSUPPORTED","UI legacy tool metadata is invalid");let t=e,i=["name","description","inputSchema","textFallback","visibility"],r=Object.hasOwn(t,"fixedResult");if(Object.keys(t).some(o=>!i.includes(o)&&!(n&&o==="fixedResult"))||i.some(o=>!Object.hasOwn(t,o))||typeof t.name!="string"||!/^[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(t.name)||typeof t.description!="string"||t.description.trim().length===0||t.description.length>8192||typeof t.textFallback!="string"||t.textFallback.trim().length===0||t.textFallback.length>16384||!t.inputSchema||typeof t.inputSchema!="object"||Array.isArray(t.inputSchema)||!Array.isArray(t.visibility)||t.visibility.length===0||t.visibility.some(o=>o!=="model"&&o!=="app")||new Set(t.visibility).size!==t.visibility.length)throw new O("DEFINITION_UNSUPPORTED","UI legacy tool metadata is invalid");try{let o=_e(t.inputSchema);if(o.type!==void 0&&o.type!=="object")throw new Error("schema type");if(r){if(!n)throw new Error("fixed result location");let s=t.fixedResult;if(!s||typeof s!="object"||Array.isArray(s))throw new Error("fixed result");let a=s;if(Object.keys(a).sort().join(",")!=="argsPolicy,structuredContent"||a.argsPolicy!=="empty-only"&&a.argsPolicy!=="ignore"||!a.structuredContent||typeof a.structuredContent!="object"||Array.isArray(a.structuredContent))throw new Error("fixed result");let d=_e(a.structuredContent);if(Zn(He(d))>4*1024)throw new Error("fixed result size")}}catch{throw new O("DEFINITION_UNSUPPORTED","UI legacy tool metadata is not projection-safe")}}function ct(e){if(!Array.isArray(e.allow)||e.allow.some(n=>!/^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)*$/.test(n)))throw new O("DEFINITION_UNSUPPORTED","UI projection policy is invalid")}function $r(e){return e.length>0&&e.length<=128&&e!=="*"&&e!=="all"&&!/[/*]/.test(e)}var Hr,Ce=V(()=>{g();Ee();mn();at();Hr=/^[0-9a-f]{64}$/;});function F(e){throw new dt(e)}function ts(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 is(e,n){let t=Object.getOwnPropertyDescriptor(e,n);return (!t||!("value"in t))&&F("CSP_ORIGIN_INVALID"),t.value}function En(e,n){if(!Object.prototype.hasOwnProperty.call(e,n))return [];let t=is(e,n);Array.isArray(t)||F("CSP_ORIGIN_INVALID"),Reflect.ownKeys(t).some(o=>typeof o!="string"||o!=="length"&&!/^(?:0|[1-9][0-9]*)$/.test(o))&&F("CSP_ORIGIN_INVALID");let r=[];for(let o=0;o<t.length;o+=1)(!Object.prototype.hasOwnProperty.call(t,o)||typeof t[o]!="string")&&F("CSP_ORIGIN_INVALID"),r.push(t[o]);return Object.keys(t).length!==t.length&&F("CSP_ORIGIN_INVALID"),r}function os(e){let n;try{n=JSON.stringify(e);}catch{F("CSP_ORIGIN_INVALID");}return n===void 0&&F("CSP_ORIGIN_INVALID"),new TextEncoder().encode(n).byteLength}function Ai(e,n){/\s|\\/u.test(e)&&F("CSP_ORIGIN_INVALID");let t=qr.exec(e);t||F("CSP_ORIGIN_INVALID");let i=t[1].toLowerCase(),r=t[2];(r.includes("@")||r.includes("%")||r.includes("*"))&&F("CSP_ORIGIN_INVALID"),(r.startsWith("[")?Zr:Qr).test(r)||F("CSP_ORIGIN_INVALID"),i==="wss"&&n!=="connectDomains"&&F("CSP_ORIGIN_INVALID");let s;try{s=new URL(e);}catch{F("CSP_ORIGIN_INVALID");}(s.protocol!==`${i}:`||s.username!==""||s.password!==""||s.search!==""||s.hash!=="")&&F("CSP_ORIGIN_INVALID");let a=s.hostname.toLowerCase();if((!a||a.includes("%"))&&F("CSP_ORIGIN_INVALID"),!a.startsWith("[")){let c=a.endsWith(".")?a.slice(0,-1):a;(c.length===0||c.length>253)&&F("CSP_ORIGIN_INVALID"),c.split(".").some(l=>l.length>63||!es.test(l))&&F("CSP_ORIGIN_INVALID");}let d=s.origin;return (d==="null"||!d.startsWith(`${i}://`))&&F("CSP_ORIGIN_INVALID"),{origin:d,hostname:a}}function rs(e){let n=e.split(".").map(Number);return ((n[0]*256+n[1])*256+n[2])*256+n[3]}function Ii(e,n,t){let i=4294967295<<32-t>>>0;return (e&i)===(n&i)}function hi(e){let n=rs(e);return Ii(n,3221225472,24)?n!==3221225481&&n!==3221225482:ns.some(([t,i])=>Ii(n,t,i))}function ss(e){let n=e.indexOf("::"),t=(n<0?e:e.slice(0,n)).split(":").filter(Boolean),i=n<0?[]:e.slice(n+2).split(":").filter(Boolean);return (n<0?t:[...t,...Array(8-t.length-i.length).fill("0"),...i]).reduce((o,s)=>o<<16n|BigInt(Number.parseInt(s,16)),0n)}function as(e){let n=ss(e),t=Number(n>>112n),i=Number(n>>96n&0xffffn);if(n>>32n===0xffffn){let r=Number(n&0xffffffffn);return hi([r>>>24&255,r>>>16&255,r>>>8&255,r&255].join("."))}return t<8192||t>16383||t===8193&&i<=511||t===8193&&i===3512||t===8194||t===16383&&i<=4095}function cs(e){let n=e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e,t=isIP(n);if(t===4)return hi(n);if(t===6)return as(n);let i=e.toLowerCase().replace(/\.$/,"");return !i||!i.includes(".")?true:Yr.some(r=>i===r||i.endsWith(`.${r}`))}function gi(e){return Object.freeze([...new Set(e.map(n=>n.origin))].sort())}function mi(e){return JSON.stringify({baseUriDomains:[],connectDomains:e.connectDomains,declared:e.declared,frameDomains:e.frameDomains,resourceDomains:[]})}function _i(e){if(e===void 0){let l=mi({declared:false,connectDomains:[],frameDomains:[]});return Object.freeze({declared:false,connectDomains:Object.freeze([]),frameDomains:Object.freeze([]),resourceDomains:Object.freeze([]),baseUriDomains:Object.freeze([]),cspHash:createHash("sha256").update(l,"utf8").digest("hex")})}ts(e)||F("CSP_ORIGIN_INVALID");let n=Reflect.ownKeys(e);n.some(l=>typeof l!="string")&&F("CSP_ORIGIN_INVALID"),n.some(l=>!Xr.has(l))&&F("CSP_AXIS_UNKNOWN");let t=En(e,"connectDomains"),i=En(e,"frameDomains"),r=En(e,"resourceDomains"),o=En(e,"baseUriDomains");(r.length>0||o.length>0)&&F("CSP_AXIS_UNSUPPORTED"),(os(e)>Wr||t.length>yi||i.length>yi||t.length+i.length>Jr||[...t,...i].some(l=>new TextEncoder().encode(l).byteLength>Kr))&&F("CSP_LIMIT_EXCEEDED");let a=t.map(l=>Ai(l,"connectDomains")),d=i.map(l=>Ai(l,"frameDomains"));[...a,...d].some(l=>cs(l.hostname))&&F("CSP_ORIGIN_FORBIDDEN");let c={declared:true,connectDomains:gi(a),frameDomains:gi(d)},p=mi(c);return Object.freeze({...c,resourceDomains:Object.freeze([]),baseUriDomains:Object.freeze([]),cspHash:createHash("sha256").update(p,"utf8").digest("hex")})}var Wr,yi,Jr,Kr,Xr,Yr,qr,Zr,Qr,es,ns,dt,Ei=V(()=>{g();Wr=4096,yi=16,Jr=32,Kr=512,Xr=new Set(["connectDomains","frameDomains","resourceDomains","baseUriDomains"]),Yr=["localhost","local","internal","home.arpa","test","example","invalid","onion"],qr=/^(https|wss):\/\/([^/?#]+)$/i,Zr=/^\[[^\]]+\](?::[0-9]+)?$/,Qr=/^[^:\[\]]+(?::[0-9]+)?$/,es=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/,ns=[[0,8],[1681915904,10],[167772160,8],[2130706432,8],[2851995648,16],[2886729728,12],[3221225984,24],[3227017984,24],[3232235520,16],[3323068416,15],[3325256704,24],[3405803776,24],[3758096384,4],[4026531840,4]],dt=class extends Error{constructor(t){super(t);this.code=t;}code;name="UiPluginCspNormalizationError"};});var Oe,pt=V(()=>{g();Oe="window";});function tn(e,n){return n===void 0||n===""?e:e===""?n:n.startsWith("[")?`${e}${n}`:`${e}.${n}`}function u(e,n=e,t,i){throw new Z(e,n,t,i)}function z(e,n){try{return n()}catch(t){throw t instanceof Z?t.withPathPrefix(e):t}}function $(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;try{let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}catch{return false}}function x(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function G(e,n,t=[]){let i=new Set([...n,...t]),r=Object.keys(e).find(s=>!i.has(s));r!==void 0&&u("MANIFEST_INVALID","MANIFEST_INVALID",r,"unknown-key");let o=n.find(s=>!x(e,s));o!==void 0&&u("MANIFEST_INVALID","MANIFEST_INVALID",o,"missing-key");}function bn(e,n=false,t=false,i=false){return us.test(e)||!i&&ys.test(e)||fs.test(e)||t&&Ti.test(e)||As.test(e)&&!(n&&/^\s*data:/i.test(e)&&!Ti.test(e))}function Dn(e,n=new Set,t=0,i=false,r=false,o=""){if(typeof e=="string"){bn(e,i,r)&&u("UNSAFE_VALUE","UNSAFE_VALUE",o,"unsafe-value");return}if(!(e===null||typeof e!="object")){(t>8||n.has(e))&&u("MANIFEST_INVALID","MANIFEST_INVALID",o),n.add(e);try{if(Array.isArray(e)){e.forEach((s,a)=>Dn(s,n,t+1,!1,!1,tn(o,`[${a}]`)));return}$(e)||u("MANIFEST_INVALID","MANIFEST_INVALID",o);for(let[s,a]of Object.entries(e))Dn(a,n,t+1,i&&t===0&&(s==="name"||s==="description"),r,tn(o,s));}finally{n.delete(e);}}}function fe(e,n){let t=e[n];return typeof t!="string"&&u("MANIFEST_INVALID"),t}function pe(e,n,t){let i=e[n];return (!Number.isSafeInteger(i)||i<t)&&u("MANIFEST_INVALID"),i}function lt(e){return ls.test(e)||u("MANIFEST_INVALID"),e}function $e(e){return ps.test(e)||u("TOKEN_INVALID"),e}function ks(e){return Ri.test(e)||u("MANIFEST_INVALID"),e}function xs(e){$(e)||u("MANIFEST_INVALID");let n={};for(let[t,i]of Object.entries(e)){let r=ks(t);$(i)||u("MANIFEST_INVALID");let o=i.type;if(o==="text"){G(i,["type","maxLength"]),n[r]={type:o,maxLength:pe(i,"maxLength",1)};continue}if(o==="text-list"){G(i,["type","max","itemMaxLength"]),n[r]={type:o,max:pe(i,"max",0),itemMaxLength:pe(i,"itemMaxLength",1)};continue}if(o==="step-list"){G(i,["type","min","max","labelMaxLength","detailMaxLength"]);let s=pe(i,"min",0),a=pe(i,"max",1);s>a&&u("MANIFEST_INVALID"),n[r]={type:o,min:s,max:a,labelMaxLength:pe(i,"labelMaxLength",1),detailMaxLength:pe(i,"detailMaxLength",1)};continue}typeof o=="string"&&u("SCHEMA_TYPE_UNSUPPORTED"),u("MANIFEST_INVALID");}return n}function vs(e,n,t){let i=e[n];(!i||i.type!==t)&&u("MANIFEST_INVALID");}function Tn(e,n,t){let i=fe(e,"field");return Ri.test(i)||u("MANIFEST_INVALID"),vs(n,i,t),i}function js(e,n){$(e)||u("MANIFEST_INVALID");let t=e.primitive;switch(typeof t!="string"&&u("MANIFEST_INVALID"),Cs.includes(t)||u("PRIMITIVE_UNKNOWN"),t){case "card-shell":return G(e,["primitive"]),{primitive:t};case "meta-banner":return G(e,["primitive","badgeToken","noticeToken"]),{primitive:t,badgeToken:$e(fe(e,"badgeToken")),noticeToken:$e(fe(e,"noticeToken"))};case "heading":return G(e,["primitive","field"]),{primitive:t,field:Tn(e,n,"text")};case "labeled-text":return G(e,["primitive","titleToken","field","variant"]),e.variant!=="callout"&&u("MANIFEST_INVALID"),{primitive:t,titleToken:$e(fe(e,"titleToken")),field:Tn(e,n,"text"),variant:"callout"};case "step-flow":return G(e,["primitive","titleToken","field"]),{primitive:t,titleToken:$e(fe(e,"titleToken")),field:Tn(e,n,"step-list")};case "text-list":{G(e,["primitive","titleToken","field"],["emptyToken","hideWhenEmpty"]);let i={primitive:t,titleToken:$e(fe(e,"titleToken")),field:Tn(e,n,"text-list")};return x(e,"emptyToken")&&(i.emptyToken=$e(fe(e,"emptyToken"))),x(e,"hideWhenEmpty")&&(typeof e.hideWhenEmpty!="boolean"&&u("MANIFEST_INVALID"),i.hideWhenEmpty=e.hideWhenEmpty),i}}return u("MANIFEST_INVALID")}function Vs(e,n){return Array.isArray(e)||u("MANIFEST_INVALID"),e.map(t=>js(t,n))}function W(e="v2 manifest exceeds a contract limit",n,t){return u("LIMIT_EXCEEDED",e,n,t)}function se(e="initial state is not projection-safe"){return u("INITIAL_STATE_INVALID",e)}function Pi(e,n){return (typeof e!="string"||e.length===0||e.length>4096||e.trim().length===0||Rs.test(e)||ws.test(e))&&u("MANIFEST_INVALID",`${n} is invalid`),(bn(e,true,true)||Is.test(e)||gs.test(e)||ms.test(e))&&u("UNSAFE_VALUE",`${n} contains an unsafe value`),e}function ut(e,n){return (typeof e!="string"||!ue.test(e))&&u("MANIFEST_INVALID",`${n} is invalid`),e}function Fs(e){return (typeof e!="string"||!et.test(e)||e==="*"||e==="all")&&u("MANIFEST_INVALID","action capability is invalid"),e}function wi(e){return (typeof e!="string"||!Os.test(e))&&u("MANIFEST_INVALID","resource hash is invalid"),e}function ft(e,n=new Set,t=0,i=""){if(typeof e=="string"){e.length>4096&&W("v2 manifest string is too long",i,"string-too-long");return}if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){Number.isFinite(e)||u("MANIFEST_INVALID","v2 manifest contains a non-finite number",i,"non-finite-number");return}(e===void 0||typeof e=="function"||typeof e=="bigint")&&u("MANIFEST_INVALID","v2 manifest contains a non-JSON value",i,"non-json-value"),typeof e!="object"&&u("MANIFEST_INVALID","MANIFEST_INVALID",i),t>8&&W("v2 manifest nesting is too deep",i,"too-deep"),n.has(e)&&u("MANIFEST_INVALID","v2 manifest contains a cycle",i,"cycle"),n.add(e);try{if(Array.isArray(e)){e.length>128&&W("v2 manifest array is too long",i,"array-too-long"),e.forEach((r,o)=>ft(r,n,t+1,tn(i,`[${o}]`)));return}$(e)||u("MANIFEST_INVALID","v2 manifest contains a non-plain object",i,"non-plain-object");for(let[r,o]of Object.entries(e))ft(o,n,t+1,tn(i,r));}finally{n.delete(e);}}}function Ui(e){return (typeof e!="string"||e.length>4096||!en.test(e))&&(typeof e=="string"&&e.length>4096&&W("projection path is too long"),u("MANIFEST_INVALID","projection paths must be canonical exact paths")),e.split(".").some(t=>ze(t))&&u("MANIFEST_INVALID","projection paths cannot address reserved state keys"),e}function yt(e){$(e)||u("MANIFEST_INVALID","projection policy must be an object"),G(e,["allow"]),Array.isArray(e.allow)||u("MANIFEST_INVALID","projection allow must be an array"),e.allow.length>128&&W("projection allowlist is too long");let n=[],t=new Set;for(let i of e.allow){let r=Ui(i);t.has(r)&&u("MANIFEST_INVALID","projection allowlist contains a duplicate path"),t.add(r),n.push(r);}return {allow:n}}function Bs(e,n){if(e===void 0)return;Array.isArray(e)||u("MANIFEST_INVALID","dataPaths must be an array"),e.length>Us&&W("dataPaths exceed the v2 limit");let t=[],i=new Set;for(let r of e){let o=Ui(r);i.has(o)&&u("MANIFEST_INVALID","dataPaths contain a duplicate path"),n.some(s=>Be(o,s))||u("MANIFEST_INVALID","dataPaths must be projection-allowed"),i.add(o),t.push(o);}return t}function Ge(e,n,t=Number.MAX_SAFE_INTEGER){return (!Number.isSafeInteger(e)||e<0||e>t)&&u("MANIFEST_INVALID",`${n} is invalid`),e}function Di(e,n){return (typeof e!="number"||!Number.isFinite(e))&&u("MANIFEST_INVALID",`${n} is invalid`),e}function At(e,n=0,t=new Set){if(typeof e=="string")return (e.length>4096||bn(e))&&u("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)||u("MANIFEST_INVALID","schema enum contains a non-finite number"),e;(n>8||typeof e!="object"||e===void 0)&&W("schema enum is too deep"),t.has(e)&&u("MANIFEST_INVALID","schema enum contains a cycle"),t.add(e);try{if(Array.isArray(e))return e.length>128&&W("schema enum array is too long"),e.map(r=>At(r,n+1,t));$(e)||u("MANIFEST_INVALID","schema enum contains a non-plain object");let i={};for(let[r,o]of Object.entries(e))ze(r)&&u("MANIFEST_INVALID","schema enum contains a reserved key"),i[r]=At(o,n+1,t);return i}finally{t.delete(e);}}function Hs(e,n){if(e===void 0)return;Array.isArray(e)||u("MANIFEST_INVALID","schema required must be an array"),e.length>64&&W("schema required list is too long");let t=[],i=new Set;for(let r of e)(typeof r!="string"||!en.test(r))&&u("MANIFEST_INVALID","schema required contains an invalid key"),r.length>4096&&W("schema required key is too long"),i.has(r)&&u("MANIFEST_INVALID","schema required contains a duplicate key"),n&&!Object.prototype.hasOwnProperty.call(n,r)&&u("MANIFEST_INVALID","schema required references an undeclared property"),i.add(r),t.push(r);return t}function zs(e,n){let t=n?en:hn;return e.length>4096&&W("schema property name is too long"),(!t.test(e)||e.split(".").some(i=>ze(i)))&&u("MANIFEST_INVALID","schema property name is invalid"),e}function It(e,n=0,t=false){$(e)||u("MANIFEST_INVALID","action inputSchema must be an object"),n>8&&W("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"&&u("SCHEMA_TYPE_UNSUPPORTED","action inputSchema type is unsupported"),u("MANIFEST_INVALID","action inputSchema type is required"));let r=["type","enum"];i==="string"&&r.push("minLength","maxLength"),i==="array"&&r.push("minItems","maxItems","items"),i==="object"&&r.push("minProperties","maxProperties","properties","required","additionalProperties"),(i==="number"||i==="integer")&&r.push("minimum","maximum"),G(e,["type"],r.filter(a=>a!=="type"));let o={type:i};if(x(e,"enum")&&(Array.isArray(e.enum)||u("MANIFEST_INVALID","schema enum must be an array"),e.enum.length>128&&W("schema enum is too long"),o.enum=e.enum.map(a=>At(a))),i==="string"&&(x(e,"minLength")&&(o.minLength=Ge(e.minLength,"schema minLength",4096)),x(e,"maxLength")&&(o.maxLength=Ge(e.maxLength,"schema maxLength",4096)),o.minLength!==void 0&&o.maxLength!==void 0&&o.minLength>o.maxLength&&u("MANIFEST_INVALID","schema string length bounds are inverted")),(i==="number"||i==="integer")&&(x(e,"minimum")&&(o.minimum=Di(e.minimum,"schema minimum")),x(e,"maximum")&&(o.maximum=Di(e.maximum,"schema maximum")),o.minimum!==void 0&&o.maximum!==void 0&&o.minimum>o.maximum&&u("MANIFEST_INVALID","schema numeric bounds are inverted")),i==="array"&&(x(e,"minItems")&&(o.minItems=Ge(e.minItems,"schema minItems",128)),x(e,"maxItems")&&(o.maxItems=Ge(e.maxItems,"schema maxItems",128)),o.minItems!==void 0&&o.maxItems!==void 0&&o.minItems>o.maxItems&&u("MANIFEST_INVALID","schema array length bounds are inverted"),x(e,"items")&&(o.items=It(e.items,n+1,false))),i==="object"){let a;if(x(e,"properties")){$(e.properties)||u("MANIFEST_INVALID","schema properties must be an object");let c=Object.entries(e.properties);c.length>64&&W("schema properties are too many"),a={};for(let[p,l]of c){let I=zs(p,t);a[I]=It(l,n+1,false);}o.properties=a;}x(e,"minProperties")&&(o.minProperties=Ge(e.minProperties,"schema minProperties",64)),x(e,"maxProperties")&&(o.maxProperties=Ge(e.maxProperties,"schema maxProperties",64)),o.minProperties!==void 0&&o.maxProperties!==void 0&&o.minProperties>o.maxProperties&&u("MANIFEST_INVALID","schema object property bounds are inverted");let d=Hs(e.required,a);d!==void 0&&(o.required=d),x(e,"additionalProperties")&&(e.additionalProperties!==false&&u("MANIFEST_INVALID","schema additionalProperties must be false"),o.additionalProperties=false);}let s=JSON.stringify(o);return (s===void 0||Buffer.byteLength(s,"utf8")>65536)&&W("action inputSchema subtree is too large"),o}function $s(e){let n=It(e,0,true);return (n.type!=="object"||!n.properties)&&u("MANIFEST_INVALID","action inputSchema must declare object properties"),n}function Gs(e){if($(e)||u("MANIFEST_INVALID","action backend must be an object"),e.type==="core"){G(e,bs);let n=e.handler;return (typeof n!="string"||!nt.test(n))&&u("MANIFEST_INVALID","core backend handler is invalid"),{type:"core",handler:n}}if(e.type==="skill"){G(e,Ns,Ss),(!Array.isArray(e.command)||e.command.length===0||e.command.length>16)&&u("MANIFEST_INVALID","skill backend command is invalid");let n=[];for(let i of e.command)(typeof i!="string"||i.length===0||i.length>256||!tt.test(i))&&u("MANIFEST_INVALID","skill backend command token is invalid"),n.push(i);let t=x(e,"env")?Js(e.env):void 0;return {type:"skill",command:n,...t===void 0?{}:{env:t}}}u("MANIFEST_INVALID","action backend type is unsupported");}function Ws(e){$(e)||u("MANIFEST_INVALID","action must be an object"),G(e,Ts,Ps),x(e,"_meta")&&z("_meta",()=>Ci(e._meta));let n=z("actionId",()=>ut(e.actionId,"actionId"));qn(n)&&u("MANIFEST_INVALID",`actionId "${n}" is not projection-safe`,"actionId");let t=z("capability",()=>Fs(e.capability)),i=e.mutation;typeof i!="boolean"&&u("MANIFEST_INVALID","action mutation must be boolean","mutation");let r=z("inputSchema",()=>$s(e.inputSchema)),o;if(x(e,"dataInputs")){Array.isArray(e.dataInputs)||u("MANIFEST_INVALID","action dataInputs must be an array","dataInputs");let p=r.properties,l=new Set,I=[];for(let _ of e.dataInputs)(typeof _!="string"||!x(p,_)||l.has(_))&&u("MANIFEST_INVALID","action dataInputs must be unique declared properties","dataInputs"),l.add(_),I.push(_);o=I;}let s=z("resultProjection",()=>yt(e.resultProjection)),a=z("backend",()=>Gs(e.backend)),d;x(e,"content")&&((a.type!=="skill"||!_n(e.content))&&u("MANIFEST_INVALID","action content declaration is invalid","content"),d=Ks(e.content));let c;if(x(e,"confirmation")){let p=e.confirmation;p!=="none"&&p!=="native"&&u("MANIFEST_INVALID","action confirmation is invalid","confirmation"),c=p;}return {actionId:n,capability:t,mutation:i,inputSchema:r,resultProjection:s,backend:a,...d===void 0?{}:{content:d},...o===void 0?{}:{dataInputs:o},...c===void 0?{}:{confirmation:c}}}function Js(e){(!Array.isArray(e)||e.length===0)&&u("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))&&u("MANIFEST_INVALID","skill backend env is invalid"),n.add(i),t.push(i);return Object.freeze(t)}function Ks(e){return Object.freeze({...e.in===void 0?{}:{in:Object.freeze({...e.in})},...e.out===void 0?{}:{out:Object.freeze({...e.out})}})}function Xs(e){return $(e)||u("INITIAL_STATE_INVALID","initialState must be an object"),G(e,Ms,Ls),e.path!=="ui/state.json"&&u("MANIFEST_INVALID","initialState path is not fixed"),x(e,"hash")?{path:"ui/state.json",hash:wi(e.hash)}:{path:"ui/state.json"}}function Ys(e){let n=["wasm","terminal","htmlDocuments"];return (!$(e)||Object.keys(e).length===0||Object.keys(e).some(t=>!n.includes(t)||e[t]!==true))&&u("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 qs(e,n){Dn(e,new Set,0,true,true),ft(e),$(e)||u("MANIFEST_INVALID"),G(e,_s,Es),x(e,"_meta")&&z("_meta",()=>Ci(e._meta)),e.manifestVersion!==2&&u("MANIFEST_INVALID");let t;x(e,"runtime")&&(t=z("runtime",()=>Ys(e.runtime)));let i=z("pluginId",()=>ut(e.pluginId,"pluginId")),r=z("definitionId",()=>ut(e.definitionId,"definitionId")),o=z("version",()=>pe(e,"version",1)),s=z("name",()=>Pi(e.name,"name")),a=z("description",()=>Pi(e.description,"description")),d;x(e,"icon")&&((typeof e.icon!="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(e.icon))&&u("MANIFEST_INVALID","icon is invalid","icon"),d=e.icon);let c;x(e,"tone")&&((typeof e.tone!="string"||!it.includes(e.tone))&&u("MANIFEST_INVALID","tone is invalid","tone"),c=e.tone),e.entry!=="ui/index.html"&&u("MANIFEST_INVALID","entry path is not fixed","entry","fixed-value");let p;x(e,"entryHash")&&(p=z("entryHash",()=>wi(e.entryHash)));let l;x(e,"initialState")&&(l=z("initialState",()=>Xs(e.initialState)));let I;x(e,"usage")&&(e.usage!=="card"&&e.usage!=="window"&&u("MANIFEST_INVALID","usage is invalid","usage"),I=e.usage);let _;x(e,"detailPanel")&&(typeof e.detailPanel!="boolean"&&u("MANIFEST_INVALID","detailPanel is invalid","detailPanel"),_=e.detailPanel);let E;if(x(e,"displayModes")){((I??Oe)!==Oe||!Array.isArray(e.displayModes)||e.displayModes.length===0)&&u("MANIFEST_INVALID","displayModes are only valid for window Apps","displayModes");let M=new Set(["inline","floating","focused"]);(new Set(e.displayModes).size!==e.displayModes.length||e.displayModes.some(y=>typeof y!="string"||!M.has(y)))&&u("MANIFEST_INVALID","displayModes are invalid","displayModes"),E=e.displayModes;}(I??Oe)===Oe&&_!==void 0&&u("MANIFEST_INVALID","detailPanel is card-only","detailPanel");let L=n.mode??"local";L!=="local"&&L!=="installed"&&L!=="published"&&u("MANIFEST_INVALID","manifest mode is invalid"),L!=="local"&&p===void 0&&u("MANIFEST_INVALID","installed manifests require entryHash","entryHash","required-when-installed"),L!=="local"&&l!==void 0&&l.hash===void 0&&u("MANIFEST_INVALID","installed manifests require initialState.hash","initialState.hash","required-when-installed"),(!Array.isArray(e.surfaces)||e.surfaces.length===0)&&u("MANIFEST_INVALID","surfaces are invalid","surfaces"),e.surfaces.length>2&&W("surfaces exceed the v2 limit","surfaces","too-many-items");let b=[],j=new Set;for(let M of e.surfaces)(typeof M!="string"||!ot.includes(M))&&u("MANIFEST_INVALID","surface is unsupported","surfaces"),j.has(M)&&u("MANIFEST_INVALID","surfaces contain a duplicate","surfaces","duplicate-item"),j.add(M),b.push(M);$(e.size)||u("MANIFEST_INVALID","size must be an object","size"),z("size",()=>G(e.size,["height"]));let C=z("size",()=>pe(e.size,"height",1));C>720&&W("size.height exceeds the v2 limit","size.height","too-large");let k=z("stateProjection",()=>yt(e.stateProjection)),B=e.summaryProjection===void 0?void 0:z("summaryProjection",()=>yt(e.summaryProjection));B!==void 0&&B.allow.some(M=>!k.allow.includes(M))&&u("MANIFEST_INVALID","summaryProjection must be a subset of stateProjection.allow","summaryProjection");let h=z("dataPaths",()=>Bs(e.dataPaths,k.allow));Array.isArray(e.actions)||u("MANIFEST_INVALID","actions must be an array","actions"),e.actions.length>32&&W("actions exceed the v2 limit","actions","too-many-items");let m=[],N=new Set;for(let[M,y]of e.actions.entries()){let f=`actions[${M}]`,A=z(f,()=>Ws(y));if(N.has(A.actionId)&&u("MANIFEST_INVALID","actions contain a duplicate actionId",`${f}.actionId`,"duplicate-item"),A.backend.type==="core"&&A.backend.handler==="state.set"){A.mutation||u("MANIFEST_INVALID","state.set actions must be mutations",`${f}.mutation`);for(let D of Object.keys(A.inputSchema.properties))k.allow.includes(D)||u("MANIFEST_INVALID","state.set input paths must be projection-allowed",`${f}.inputSchema.properties`);}N.add(A.actionId),m.push(A);}return {manifestVersion:2,pluginId:i,definitionId:r,version:o,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},...l===void 0?{}:{initialState:l},...I===void 0?{}:{usage:I},..._===void 0?{}:{detailPanel:_},...E===void 0?{}:{displayModes:E},surfaces:b,size:{height:C},stateProjection:k,...B===void 0?{}:{summaryProjection:B},...h===void 0?{}:{dataPaths:h},actions:m}}function Ci(e){$(e)||u("MANIFEST_INVALID","_meta must be an object");let n=JSON.stringify(e);(n===void 0||Buffer.byteLength(n,"utf8")>Ds)&&W("_meta exceeds the 4 KiB limit",void 0,"meta-too-large");}function Zs(e){let n={},t={};for(let o of e.actions){n[o.actionId]={capabilities:[o.capability],inputKeys:Object.keys(o.inputSchema.properties??{}),...o.dataInputs===void 0?{}:{dataInputs:o.dataInputs},resultProjection:o.resultProjection,...o.confirmation===void 0?{}:{confirmation:o.confirmation},...o.content===void 0?{}:{content:o.content},...o.backend.type!=="skill"||o.backend.env===void 0?{}:{env:o.backend.env}};let s=o.backend.type==="skill"||o.backend.type==="core"&&o.backend.handler==="state.set";t[o.actionId]={actionId:o.actionId,mutation:o.mutation,backend:o.backend,launchPolicy:s?"allowed":"denied",...s?{}:{denialCode:"EXEC_DENIED"}};}let i={id:e.definitionId,version:e.version,renderer:"sandbox-html",...e.usage===void 0?{}:{usage:e.usage},...e.detailPanel===void 0?{}:{detailPanel:e.detailPanel},...e.displayModes===void 0?{}:{displayModes:e.displayModes},surfaces:e.surfaces,stateProjection:e.stateProjection,...e.summaryProjection===void 0?{}:{summaryProjection:e.summaryProjection},...e.dataPaths===void 0?{}:{dataPaths:e.dataPaths},actions:n},r={entry:{path:"ui/index.html",...e.entryHash===void 0?{}:{hash:e.entryHash}},...e.initialState===void 0?{}:{initialState:e.initialState}};return {manifest:e,definition:i,handlers:t,resources:r}}function gt(e,n,t,i,r,o){if(typeof e=="string"){let s=r.length>0&&o.some(a=>Be(r.join("."),a));return (e.length>4096||bn(e,false,false,s))&&se("state contains an unsafe string"),e}if(e===null||typeof e=="boolean")return e;if(typeof e=="number")return Number.isFinite(e)||se("state contains a non-finite number"),e;(e===void 0||typeof e!="object"||typeof e=="function"||typeof e=="bigint")&&se("state contains a non-JSON value"),t>8&&se("state is too deep"),n.has(e)&&se("state contains a cycle"),n.add(e);try{let s;if(Array.isArray(e))e.length>128&&se("state array is too long"),s=e.map(d=>gt(d,n,t+1,65536,r,o));else {$(e)||se("state contains a non-plain object");let d={};for(let[c,p]of Object.entries(e))(c.length>4096||!hn.test(c)||ze(c))&&(c.length>4096&&se("state key is too long"),se("state contains a reserved or invalid key")),d[c]=gt(p,n,t+1,65536,[...r,c],o);s=d;}let a=JSON.stringify(s);return (a===void 0||Buffer.byteLength(a,"utf8")>i)&&se("state subtree is too large"),s}finally{n.delete(e);}}function ht(e,n=[]){$(e)||se("initial state must be a JSON object");let t=gt(e,new Set,0,65536,[],n);return (t===null||Array.isArray(t)||typeof t!="object")&&se(),t}function Qs(e,n={}){Dn(e),$(e)||u("MANIFEST_INVALID"),G(e,hs),e.manifestVersion!==1&&u("MANIFEST_INVALID");let t=lt(fe(e,"pluginId")),i=lt(fe(e,"definitionId")),r=pe(e,"version",1),o=pe(e,"primitiveSet",1),s=n.supportedPrimitiveSet??ds;(!Number.isSafeInteger(s)||s<1)&&u("MANIFEST_INVALID"),o>s&&u("PRIMITIVE_SET_UNSUPPORTED"),$(e.activation)||u("MANIFEST_INVALID"),G(e.activation,["kind","language"]),e.activation.kind!=="fenced-code"&&u("MANIFEST_INVALID");let a=lt(fe(e.activation,"language")),d=xs(e.schema),c=Vs(e.layout,d);return {manifestVersion:1,pluginId:t,definitionId:i,version:r,primitiveSet:o,activation:{kind:"fenced-code",language:a},schema:d,layout:c}}function ea(e,n={}){return $(e)||u("MANIFEST_INVALID"),Object.hasOwn(e,"lineage")&&u("MANIFEST_INVALID","lineage is only allowed in product bundle indexes"),e.manifestVersion===2?qs(e,n):Qs(e,n)}function xe(e,n={}){try{return ea(e,n)}catch(t){if(t instanceof Z)throw t;return u("MANIFEST_INVALID")}}function on(e,n={}){let t=xe(e,n);return t.manifestVersion===2?Zs(t):t}var ds,ps,ls,Ri,us,fs,ys,As,Ti,Is,gs,ms,hs,_s,Es,Ts,Ps,Ds,bs,Ns,Ss,Ms,Ls,Os,Rs,ws,Us,Cs,Z,_t=V(()=>{g();pt();Ee();at();Ue();ds=1,ps=/^[a-z][a-zA-Z0-9]*(\.[a-zA-Z0-9]+)+$/,ls=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,Ri=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,us=/<\/?[A-Za-z][^>]*>/,fs=/^(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)/,ys=/^(?:https?|file|ftp|ws|wss):\/\//i,As=/^\s*(?:javascript|data):/i,Ti=/data:[^,\s]*,/i,Is=/(?:https?|file|ftp|ws|wss):\/\//i,gs=/javascript:/i,ms=/(?:^[\s]*|[\s"'(=])(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)(?=[^\s"'<>])[^\s"'<>]*/,hs=["manifestVersion","pluginId","definitionId","version","primitiveSet","activation","schema","layout"],_s=["manifestVersion","pluginId","definitionId","version","name","description","entry","surfaces","size","stateProjection","actions"],Es=["_meta","icon","tone","entryHash","runtime","initialState","usage","detailPanel","displayModes","summaryProjection","dataPaths","focusedAiDataPaths"],Ts=["actionId","capability","mutation","inputSchema","resultProjection","backend"],Ps=["confirmation","dataInputs","content","_meta"],Ds=4*1024,bs=["type","handler"],Ns=["type","command"],Ss=["env"],Ms=["path"],Ls=["hash"],Os=/^[0-9a-f]{64}$/,Rs=/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/,ws=/[\r\n]/,Us=16,Cs=["card-shell","meta-banner","heading","labeled-text","step-flow","text-list"],Z=class e extends Error{constructor(t,i=t,r,o){super(i);this.code=t;this.path=r;this.rule=o;}code;path;rule;name="UiPluginValidationError";withPathPrefix(t){return new e(this.code,this.message,tn(t,this.path),this.rule)}};});function ji(e){return typeof e=="string"&&e.length<=ta&&na.test(e)}function U(e,n,t,i,r){throw new Ae(e,{path:n,rule:t,...i===void 0?{}:{message:i},...r===void 0?{}:{file:r}})}function ae(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;try{let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}catch{return false}}function Q(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function ye(e){let n=`_meta["${Re}"]`;return e===void 0||e===""?n:e.startsWith("[")?`${n}${e}`:`${n}.${e}`}function sa(e){return e.toLowerCase().replace(/_/g,"-")}function aa(e){if(e===void 0||e==="")return "";let n=/^([^.[]+)(.*)$/.exec(e);if(!n)return ye(e);let[,t,i]=n;switch(t){case "pluginId":return `name${i}`;case "name":return `display_name${i}`;case "description":return `description${i}`;case "_meta":return `_meta${i}`;case "version":return ye("definitionVersion");case "definitionId":return ye("definitionId");default:return ye(`${t}${i}`)}}function Vi(e,n,t){return {path:t(e.path),rule:e.rule??sa(e.code),...e.message!==e.code?{message:e.message}:{},file:n}}function Fi(e){return JSON.parse(JSON.stringify(e))}function Pt(e,n,t=0,i=new Set){if(typeof e=="string"){e.length>4096&&U("LIMIT_EXCEEDED",n,"string-too-long"),(ia.test(e)||oa.test(e)||ra.test(e))&&U("UNSAFE_VALUE",n,"unsafe-value");return}if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){Number.isFinite(e)||U("MANIFEST_INVALID",n,"non-finite-number");return}typeof e!="object"&&U("MANIFEST_INVALID",n,"non-json-value"),t>8&&U("LIMIT_EXCEEDED",n,"too-deep"),i.has(e)&&U("MANIFEST_INVALID",n,"cycle"),i.add(e);try{if(Array.isArray(e)){e.length>128&&U("LIMIT_EXCEEDED",n,"array-too-long"),e.forEach((r,o)=>Pt(r,`${n}[${o}]`,t+1,i));return}ae(e)||U("MANIFEST_INVALID",n,"non-plain-object");for(let[r,o]of Object.entries(e))Pt(o,n===""?r:`${n}.${r}`,t+1,i);}finally{i.delete(e);}}}function le(e,n){return (typeof e!="string"||e.length===0)&&U("MANIFEST_INVALID",n,"string"),e}function Je(e,n){return ae(e)||U("MANIFEST_INVALID",n,"object"),e}function ca(e,n){Array.isArray(e)||U("MANIFEST_INVALID",n,"array"),e.forEach((t,i)=>le(t,`${n}[${i}]`));}function da(e,n){typeof e!="boolean"&&U("MANIFEST_INVALID",n,"boolean");}function rn(e,n,t,i){for(let r of Object.keys(e))!t.includes(r)&&!i.includes(r)&&U("MANIFEST_INVALID",`${n}.${r}`,"unknown-key");for(let r of t)Q(e,r)||U("MANIFEST_INVALID",`${n}.${r}`,"missing-key");}function pa(e,n){switch(Pt(n,e),e){case "long_description":case "homepage":case "documentation":case "support":case "icon":case "license":le(n,e);return;case "author":{let t=Je(n,e);rn(t,e,["name"],["email","url"]);for(let i of Object.keys(t))le(t[i],`${e}.${i}`);return}case "repository":{let t=Je(n,e);rn(t,e,[],["type","url"]);for(let i of Object.keys(t))le(t[i],`${e}.${i}`);return}case "icons":{Array.isArray(n)||U("MANIFEST_INVALID",e,"array"),n.forEach((t,i)=>{let r=`${e}[${i}]`,o=Je(t,r);rn(o,r,["src","size"],["theme"]),le(o.src,`${r}.src`),le(o.size,`${r}.size`),Q(o,"theme")&&le(o.theme,`${r}.theme`);});return}case "screenshots":case "keywords":case "privacy_policies":ca(n,e);return;case "tools":{Array.isArray(n)||U("MANIFEST_INVALID",e,"array"),n.forEach((t,i)=>{let r=`${e}[${i}]`,o=Je(t,r);rn(o,r,["name"],["description"]),le(o.name,`${r}.name`),Q(o,"description")&&le(o.description,`${r}.description`);});return}case "prompts":{Array.isArray(n)||U("MANIFEST_INVALID",e,"array"),n.forEach((t,i)=>{let r=`${e}[${i}]`,o=Je(t,r);rn(o,r,["name","text"],["description","arguments"]),le(o.name,`${r}.name`),le(o.text,`${r}.text`);});return}case "tools_generated":case "prompts_generated":da(n,e);return;case "localization":case "compatibility":case "user_config":Je(n,e);return;default:U("MANIFEST_INVALID",e,"unknown-key");}}function la(e){let n=ye("csp"),t;try{t=_i(e);}catch(i){let r=i!==null&&typeof i=="object"&&"code"in i&&typeof i.code=="string"?i.code:"CSP_ORIGIN_INVALID";U("MANIFEST_INVALID",n,r.toLowerCase().replace(/_/g,"-"),r);}(t.connectDomains.length>0||t.frameDomains.length>0)&&U("MANIFEST_INVALID",n,"csp-not-enabled","external origins in csp are not enabled in this rollout");}function Nn(e){return typeof e=="string"&&ue.test(e)?e:void 0}function Bi(e){return Number.isSafeInteger(e)&&e>=1?e:void 0}function ua(e){let n=Nn(e.name);if(n===void 0)return;let t=e._meta,i=ae(t)?t[Re]:void 0,r=ae(i)?i:{},o=Q(r,"definitionId")?Nn(r.definitionId):n,s=Q(r,"definitionVersion")?Bi(r.definitionVersion):1;return {pluginId:n,...o===void 0?{}:{definitionId:o},...s===void 0?{}:{definitionVersion:s}}}function fa(e){let n=Nn(e.pluginId);if(n===void 0)return;let t=Nn(e.definitionId),i=Bi(e.version);return {pluginId:n,...t===void 0?{}:{definitionId:t},...i===void 0?{}:{definitionVersion:i}}}function St(e){try{let n=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e));if(!ae(n))return !1;let t=n._meta;return ae(t)&&Q(t,Re)}catch{return false}}function ya(e,n){if(e===Ie)return n.builtinOnly===true;let t=n._meta,i=ae(t)?t[Re]:void 0;return ae(i)&&i.builtinOnly===true}function Aa(e){Q(e,"server")&&U("MANIFEST_INVALID","server","server-unsupported","phase 1 runs CrewX-owned Apps only");for(let s of Object.keys(e))bt.includes(s)||U("MANIFEST_INVALID",s,"unknown-key");for(let s of Nt)Q(e,s)||U("MANIFEST_INVALID",s,"missing-key");e.manifest_version!==Et&&U("MANIFEST_INVALID","manifest_version","unsupported-version",`manifest_version must be "${Et}"`),ji(e.version)||U("MANIFEST_INVALID","version","semver","version must be a semver.org version such as 0.1.0");let n=e._meta;ae(n)||U("MANIFEST_INVALID","_meta","object"),Q(n,Re)||U("MANIFEST_INVALID",ye(),"missing-key");let t=n[Re];ae(t)||U("MANIFEST_INVALID",ye(),"object");for(let s of Object.keys(t))Tt.includes(s)||vi.includes(s)||U("MANIFEST_INVALID",ye(s),"unknown-key");for(let s of Tt)Q(t,s)||U("MANIFEST_INVALID",ye(s),"missing-key");if(Q(t,"definitionVersion")){let s=t.definitionVersion;(!Number.isSafeInteger(s)||s<1)&&U("MANIFEST_INVALID",ye("definitionVersion"),"positive-integer");}Q(t,"csp")&&la(t.csp);let i={};for(let s of xi)Q(e,s)&&(pa(s,e[s]),i[s]=Fi(e[s]));let r={};for(let[s,a]of Object.entries(n))s!==Re&&(r[s]=a);let o={manifestVersion:2,pluginId:e.name,definitionId:Q(t,"definitionId")?t.definitionId:e.name,version:Q(t,"definitionVersion")?t.definitionVersion:1,name:e.display_name,description:e.description};for(let[s,a]of Object.entries(t))s==="definitionId"||s==="definitionVersion"||s==="csp"||(o[s]=a);return Object.keys(r).length>0&&(o._meta=r),{v2Input:o,...Object.keys(r).length>0?{vendorMeta:r}:{},passthrough:i}}function Ia(e,n){ae(e)||U("MANIFEST_INVALID","","not-object","manifest.json must be a JSON object",ie);let t;try{t=Aa(e);}catch(o){throw o instanceof Ae?new Ae(o.code,{...o.reason,file:ie}):o}let i;try{let o=xe(t.v2Input,{mode:n.mode??"local"});o.manifestVersion!==2&&U("MANIFEST_INVALID","","v2-required"),i=o;}catch(o){throw o instanceof Z?new Ae(o.code,Vi(o,ie,aa)):o}let r=e.tools;if(Array.isArray(r)){let o=new Set(i.actions.map(s=>s.actionId));r.forEach((s,a)=>{let d=s.name;if(!o.has(d))throw new Ae("MANIFEST_INVALID",{path:`tools[${a}].name`,rule:"tool-not-action",message:"every tools[].name must be an action id",file:ie})});}return {file:ie,manifest:i,v2Input:t.v2Input,releaseVersion:e.version,...Object.keys(t.passthrough).length>0?{mcpb:t.passthrough}:{}}}function ga(e,n){try{let t=xe(e,{mode:n.mode??"local"});if(t.manifestVersion!==2)throw new Ae("MANIFEST_INVALID",{path:"manifestVersion",rule:"v2-required",message:"a workspace App requires manifestVersion 2",file:Ie});return {file:Ie,manifest:t,v2Input:e}}catch(t){throw t instanceof Z?new Ae(t.code,Vi(t,Ie,i=>i??"")):t}}function Dt(e){return de(on(e).definition)}function ki(e){let{entryHash:n,initialState:t,...i}=e,r={...i};return t!==void 0&&(r.initialState={path:t.path}),Fi(r)}function ma(e,n){let t=ki(e),i=ki(n);return [...new Set([...Object.keys(t),...Object.keys(i)])].sort().filter(o=>Y(t[o]??null)!==Y(i[o]??null))}function ha(e,n){return e.entryHash!==void 0&&n.entryHash!==void 0&&e.entryHash!==n.entryHash||e.initialState?.hash!==void 0&&n.initialState?.hash!==void 0&&e.initialState.hash!==n.initialState.hash}function _a(e,n){let t=ma(e,n),i=ha(e,n),r="";try{let o=Dt(e),s=Dt(n);i=i||o!==s,r=` (definition hash ${o.slice(0,12)} vs ${s.slice(0,12)})`;}catch{i=true;}t.length===0&&!i||U("MANIFEST_DUAL_MISMATCH","","dual-manifest-mismatch",`${ie} and ${Ie} normalize to different definitions${r}`+(t.length>0?`; differing fields: ${t.join(", ")}`:""));}function Ea(e,n){let t=n.maxBytes??262144,i=[],r=new TextDecoder("utf-8",{fatal:true});for(let o of ee){let s=e[o];if(s===void 0)continue;if(s.byteLength>t)return {parsed:i,failure:{code:"LIMIT_EXCEEDED",reason:{path:"",rule:"file-too-large",file:o},files:[o]}};let a;try{a=JSON.parse(r.decode(s));}catch{return {parsed:i,failure:{code:"MANIFEST_INVALID",reason:{path:"",rule:"invalid-json",file:o},files:[o]}}}if(!ae(a))return {parsed:i,failure:{code:"MANIFEST_INVALID",reason:{path:"",rule:"not-object",message:`${o} must be a JSON object`,file:o},files:[o]}};i.push({file:o,raw:a});}return {parsed:i}}function sn(e,n={}){let{parsed:t,failure:i}=Ea(e,n),r=ee.filter(p=>e[p]!==void 0);if(i!==void 0)return {ok:false,rejection:i,parseFailure:true,builtinOnly:false};if(t.length===0)return {ok:false,rejection:{code:"MANIFEST_INVALID",reason:{path:"",rule:"no-manifest-file",message:"neither manifest.json nor ui-plugin.json is present"},files:[]},parseFailure:true,builtinOnly:false};let o=t[0],s=o.file===ie?ua(o.raw):fa(o.raw),a=t.some(p=>ya(p.file,p.raw)),d=[];try{for(let p of t)d.push(p.file===ie?Ia(p.raw,n):ga(p.raw,n));d.length===2&&_a(d[0].manifest,d[1].manifest);}catch(p){if(p instanceof Ae)return {ok:false,rejection:{code:p.code,reason:p.reason,files:p.code==="MANIFEST_DUAL_MISMATCH"?[...ee]:p.reason.file===void 0?r:[p.reason.file]},parseFailure:false,...s===void 0?{}:{identity:s},builtinOnly:a};throw p}let c=d[0];return {ok:true,...c,identity:s??{pluginId:c.manifest.pluginId},files:r}}var ie,Ie,ee,Et,Re,bt,Nt,xi,Tt,vi,na,ta,ia,oa,ra,Ae,Mt=V(()=>{g();Ce();Ee();Ei();Ue();_t();ie="manifest.json",Ie="ui-plugin.json",ee=[ie,Ie],Et="0.3",Re="dev.crewx",bt=Object.freeze(["manifest_version","name","display_name","version","description","long_description","author","repository","homepage","documentation","support","icon","icons","screenshots","localization","server","tools","tools_generated","prompts","prompts_generated","keywords","license","privacy_policies","compatibility","user_config","_meta"]),Nt=Object.freeze(["manifest_version","name","display_name","version","description","_meta"]),xi=Object.freeze(bt.filter(e=>e!=="server"&&!Nt.includes(e))),Tt=Object.freeze(["entry","surfaces","size","stateProjection","actions"]),vi=Object.freeze(["definitionId","definitionVersion","icon","tone","entryHash","runtime","initialState","usage","detailPanel","displayModes","summaryProjection","dataPaths","focusedAiDataPaths","csp"]),na=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/,ta=256,ia=/<\/?[A-Za-z][^>]*>/,oa=/^\s*javascript:/i,ra=/data:[^,\s]*,/i;Ae=class extends Error{constructor(t,i){super(`${t}: ${i.path||"<file>"} (${i.rule})`);this.code=t;this.reason=i;}code;reason};});var Lt=V(()=>{g();di();Mt();_t();Ue();});function Mn(e,n=e){throw new we(e,n)}var we,Ln=V(()=>{g();we=class extends Error{constructor(t,i=t){super(i);this.code=t;}code;name="McpAppContractError"};});var Yi=V(()=>{g();});var qi=V(()=>{g();Ce();Ee();Ln();Yi();});function Zi(e,n){return La.add(e),n!==void 0&&Oa.set(e,n),e}var La,Oa,On=V(()=>{g();La=new WeakSet,Oa=new WeakMap;});function pn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Rt(e,n,t=[]){let i=new Set([...n,...t]),r=Object.keys(e);return n.every(o=>Object.hasOwn(e,o))&&r.every(o=>i.has(o))}function no(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let n of Object.values(e))no(n);return Object.freeze(e)}function X(e){throw new ge("LINEAGE_INVALID",e)}function va(e){throw new ge("LINEAGE_STALE",e)}function to(e){if(!pn(e)||!Rt(e,Ua,Ca)||!pn(e.actions))return X("Lineage definition shape is invalid");for(let n of Object.values(e.actions))if(!pn(n)||!Rt(n,ka,xa))return X("Lineage action definition shape is invalid");return e}function ja(e){if(!pn(e)||!Rt(e,Ra,wa))return X("Lineage entry shape is invalid");if(!Number.isSafeInteger(e.version)||e.version<1||typeof e.hash!="string"||!Qi.test(e.hash))return X("Lineage entry identity is invalid");if(e.sourceHash!==void 0&&(typeof e.sourceHash!="string"||!Qi.test(e.sourceHash)))return X("Lineage source hash is invalid");if(e.compat!==void 0&&e.compat!=="break")return X("Lineage compatibility marker is invalid");let n=to(e.definition);if(n.version!==e.version)return X("Lineage version does not match its definition");if(e.sourceHash!==void 0&&n.sourceHash!==e.sourceHash)return X("Lineage source hash does not match its definition");let t;try{t=de(n),Te({...n,hash:e.hash});}catch{return X("Lineage definition is invalid")}return t!==e.hash?X("Lineage definition hash does not match"):no({version:e.version,hash:e.hash,definition:n,...e.sourceHash===void 0?{}:{sourceHash:e.sourceHash},...e.compat===void 0?{}:{compat:e.compat}})}function eo(e){return e.stateProjection?.allow??[]}function Va(e,n){let t=[],i=new Set(eo(n));eo(e).some(a=>!i.has(a))&&t.push("S1_STATE_PROJECTION");let r=new Set(n.dataPaths??[]);(e.dataPaths??[]).some(a=>!r.has(a))&&t.push("S2_DATA_PATHS");for(let[a,d]of Object.entries(e.actions)){let c=n.actions[a];if(c&&(d.confirmation??"native")==="native"&&(c.confirmation??"native")!=="native"){t.push("S3_ACTION_CONFIRMATION");break}}Object.keys(e.legacy?.agentAccess??{}).some(a=>!Object.hasOwn(n.actions,a))&&t.push("S4_LEGACY_AGENT_ACTIONS");let s=e.summaryProjection?.allow;if(s!==void 0){let a=new Set(n.summaryProjection?.allow??[]);s.some(d=>!a.has(d))&&t.push("S5_SUMMARY_PROJECTION");}return t}function Fa(e,n){return Y(e)===Y(n)}function wt(e,n){if(!Array.isArray(e)||e.length===0)return X("Definition lineage is missing");if(!pn(n)||typeof n.hash!="string")return X("Current definition is invalid");let t,i;try{let{hash:a,...d}=n;i=to(d),t={...i,hash:a},Te(t);}catch{return X("Current definition is invalid")}let r=e.map(ja),o=r[0].definition.id;if(r.some(a=>a.definition.id!==o))return X("Lineage definition ids do not match");if(r.some((a,d)=>d>0&&a.version<=r[d-1].version))return X("Lineage generations are not in increasing version order");if(r.some((a,d)=>r.findIndex(c=>c.hash===a.hash)!==d))return X("Lineage contains a duplicate hash");let s=r[r.length-1];if(s.version!==t.version||s.hash!==t.hash||s.definition.id!==t.id||!Fa(s.definition,i))return va("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 r)if(p.sourceHash===void 0)for(let l of Object.keys(p.definition.actions))a.has(l)&&d.add(l);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 ge("LINEAGE_INVALID",`Lineage compatibility failed: ${p}`,[p])}}for(let a=0;a<r.length-1;a+=1){if(r.slice(a,-1).some(p=>p.compat==="break"))continue;let c=Va(r[a].definition,t);if(c.length>0)throw new ge("LINEAGE_INVALID",`Lineage compatibility failed: ${c.join(", ")}`,c)}return Object.freeze({entries:Object.freeze(r),current:t})}var ge,Qi,Ra,wa,Ua,Ca,ka,xa,Ut=V(()=>{g();Ce();Ee();ge=class extends Error{constructor(t,i=t,r=[]){super(i);this.code=t;this.violations=r;}code;violations;name="UiDefinitionLineageError"},Qi=/^[0-9a-f]{64}$/,Ra=["version","hash","definition"],wa=["sourceHash","compat"],Ua=["id","version","actions"],Ca=["sourceHash","usage","detailPanel","displayModes","renderer","surfaces","stateProjection","dataPaths","summaryProjection","legacy"],ka=["capabilities"],xa=["inputKeys","dataInputs","confirmation","resultProjection","content","env"];});var io,oo,ro=V(()=>{g();io=["crewx_app_terminal_connect","crewx_app_html_viewer_open"],oo=["crewx_listWorkspaces","crewx_queryAgent","crewx_executeAgent","crewx_getTaskResult","crewx_listTasks","crewx_listAgents","callBrowser","openTab","listTabs","closeTab"];});var so=V(()=>{g();Ce();On();});function Ct(e,n=0){try{let t=_e(e,n);return t.type!==void 0&&t.type!=="object"&&Mn("TOOL_INVALID","MCP App inputSchema must describe an object"),t}catch(t){if(t instanceof we)throw t;Mn("TOOL_INVALID","MCP App inputSchema must be projection-safe JSON");}}function ao(e){if(e.length===0)return Ct({type:"object",properties:{},additionalProperties:false});let n=e.map(i=>i.actionId),t=new Map;for(let i of e)t.set(i.actionId,Ct(i.inputSchema));return Ct(za(n,t),Ha)}function za(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 ln,Ha,kt=V(()=>{g();qi();Ce();Ee();On();Ln();Ut();ro();so();ln=8*1024*1024,new Set(io),new Set(oo),Ha=4;});function $a(e){if(e===null||typeof e!="object"||!(co in e))throw new TypeError("scanCache must be created by createWorkspaceAppScanCache");return e[co]}function po(e,n){let t=$a(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 co,lo=V(()=>{g();co=Symbol("crewx.workspace-app-scan-cache.state");});function oe(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 Ka(e){if(typeof e!="string"||e.length===0||!isAbsolute(e))throw new P("READ_DENIED")}function xt(e){if(typeof e!="string"||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 Cn(e,n){let t=relative(e,n);return t===""||t!==".."&&!t.startsWith(`..${sep}`)&&!isAbsolute(t)}function Ye(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 Bt(e,n){return Ft(e,n)&&e.size===n.size&&e.mtimeNs===n.mtimeNs&&e.ctimeNs===n.ctimeNs}async function Rn(e){Ka(e);let n,t;try{n=await realpath(e),t=await stat(n,{bigint:!0});}catch(i){throw oe(i)}if(!t.isDirectory())throw new P("READ_DENIED");return {realRoot:n,identity:Ye(t)}}async function yo(e,n,t){if(t.length<2||t[0]!=="apps"&&t[0]!=="skills")return;let i,r;try{if(i=resolve(e,t[0],t[1]),r=await realpath(i),!(await stat(r,{bigint:!0})).isDirectory())throw new P("READ_DENIED")}catch(o){throw o instanceof P?o:oe(o)}if(!Cn(n,r))throw new P("PATH_ESCAPED");return r}async function wn(e,n,t,i){let r,o,s;try{r=await lstat(e,{bigint:!0}),o=await realpath(e),s=await stat(o,{bigint:!0});}catch(a){throw oe(a)}if(!Cn(n,o)||t!==void 0&&!Cn(t,o))throw new P("PATH_ESCAPED");if(!r.isFile()||!s.isFile())throw new P("READ_DENIED");if(!Ft(i,r)||!Ft(i,s)||i.dev!==s.dev)throw new P("PATH_ESCAPED")}async function Xe(e,n){let t,i;try{t=await realpath(e),i=await stat(t,{bigint:!0});}catch{throw new P("PATH_ESCAPED")}if(t!==n.realRoot||!Bt(n.identity,Ye(i)))throw new P("PATH_ESCAPED")}function Xa(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,Vt,Ja,fo,kn,Ao,zt=V(()=>{g();P=class extends Error{constructor(t){super(t);this.code=t;}code;name="AppDiscoveryFsError"},Vt=constants.O_NOFOLLOW,Ja=constants.O_NONBLOCK,fo=constants.O_RDONLY|(Vt??0)|(Ja??0);kn=class{async getRootIdentity(n){let t=await Rn(n);return await Xe(n,t),{dev:t.identity.dev,ino:t.identity.ino,realPath:t.realRoot}}async listDirectory(n,t){let i=xt(t),r=await Rn(n),o=resolve(n,...i),s,a;try{s=await realpath(o),a=await stat(s,{bigint:!0});}catch(d){let c=oe(d);if(c.code==="NOT_FOUND")return [];throw c}if(!Cn(r.realRoot,s)||!a.isDirectory())throw new P("PATH_ESCAPED");try{let d=await readdir(s,{withFileTypes:!0,encoding:"utf8"});return await Xe(n,r),d.map(Xa)}catch(d){let c=oe(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(Vt===void 0)throw new P("UNSUPPORTED");let r=xt(t),o=await Rn(n),s=resolve(n,...r),a=relative(n,s);if(a===".."||a.startsWith(`..${sep}`)||isAbsolute(a))throw new P("PATH_ESCAPED");let d;try{d=await open(s,fo);}catch(c){throw oe(c)}try{let c;try{let E=await d.stat({bigint:!0});c=Ye(E);}catch(E){throw oe(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 Xe(n,o);let p=await yo(n,o.realRoot,r);await wn(s,o.realRoot,p,c);let l=new Uint8Array(new ArrayBuffer(Number(c.size))),I=0;for(;I<l.byteLength;){let E;try{E=(await d.read(l,I,l.byteLength-I,I)).bytesRead;}catch(L){throw oe(L)}if(E<=0)throw new P("IDENTITY_CHANGED");I+=E;}let _;try{let E=await d.stat({bigint:!0});_=Ye(E);}catch(E){throw oe(E)}if(!Bt(c,_))throw new P("IDENTITY_CHANGED");return await wn(s,o.realRoot,p,_),await Xe(n,o),new Uint8Array(l)}finally{await d.close().catch(()=>{});}}async fingerprintVerifiedFile(n,t,i){if(!Number.isSafeInteger(i)||i<0)throw new P("READ_DENIED");if(Vt===void 0)throw new P("UNSUPPORTED");let r=xt(t),o=await Rn(n),s=resolve(n,...r),a=relative(n,s);if(a===".."||a.startsWith(`..${sep}`)||isAbsolute(a))throw new P("PATH_ESCAPED");let d;try{d=await open(s,fo);}catch(c){throw oe(c)}try{let c;try{let I=await d.stat({bigint:!0});c=Ye(I);}catch(I){throw oe(I)}if(c.size>BigInt(i)||c.size>BigInt(Number.MAX_SAFE_INTEGER))throw new P("LIMIT_EXCEEDED");await Xe(n,o);let p=await yo(n,o.realRoot,r);await wn(s,o.realRoot,p,c);let l;try{let I=await d.stat({bigint:!0});l=Ye(I);}catch(I){throw oe(I)}if(!Bt(c,l))throw new P("IDENTITY_CHANGED");return await wn(s,o.realRoot,p,l),await Xe(n,o),{...l,candidateRealPath:p??o.realRoot}}catch(c){throw c instanceof P?c:oe(c)}finally{await d.close().catch(()=>{});}}async readFileVerified(n,t,i){return this.readVerifiedFile(n,t,i)}},Ao=new kn;});function An(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 go(e){return typeof e=="string"&&ue.test(e)?e:void 0}function tc(e){return e.length>0&&e!=="."&&e!==".."&&!/[\\/\u0000]/.test(e)}function je(e,n){let t=new TextEncoder().encode(e),i=new TextEncoder().encode(n),r=Math.min(t.byteLength,i.byteLength);for(let o=0;o<r;o+=1){let s=t[o]-i[o];if(s!==0)return s}return t.byteLength-i.byteLength}function ic(e){if(typeof e=="string")return {name:e,kind:"directory"};if(e===null||typeof e!="object")return null;let n=e;if(typeof n.name!="string")return null;if(n.kind==="file"||n.kind==="directory"||n.kind==="symlink"||n.kind==="other")return {name:n.name,kind:n.kind};if(n.type==="file"||n.type==="directory"||n.type==="symlink"||n.type==="other")return {name:n.name,kind:n.type};let t=n.isDirectory;if(typeof t=="function"&&t.call(e))return {name:n.name,kind:"directory"};let i=n.isSymbolicLink;if(typeof i=="function"&&i.call(e))return {name:n.name,kind:"symlink"};let r=n.isFile;return typeof r=="function"&&r.call(e)?{name:n.name,kind:"file"}:{name:n.name,kind:"other"}}function oc(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 rc(e){return ec.decode(e)}function sc(e){return JSON.parse(rc(e))}function mo(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 ac(e){if(e instanceof P)return mo(e.code);if(e!==null&&typeof e=="object"&&"code"in e){let n=e.code;if(typeof n=="string")return mo(n)}}function De(e,n){let t=n();return Number.isFinite(t)&&Number.isFinite(e)&&t-e<=5e3}function cc(e){if(typeof e.readVerifiedFile=="function")return e.readVerifiedFile;if(typeof e.readFileVerified=="function")return e.readFileVerified}function dc(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 ho(e,n,t,i){let r=cc(e);if(!r)throw new P("READ_DENIED");return oc(await r.call(e,n,t,i))}async function Wt(e,n,t){let i=dc(e);if(!i)throw new P("READ_DENIED");let r=await i.call(e,n,t);if(!Array.isArray(r))throw new P("READ_DENIED");return r.map(ic).filter(o=>o!==null)}function pc(e,n,t,i){return Object.freeze({code:e,...{},source:n,relativePath:t})}function lc(e){if(!An(e))throw new TypeError("productBundle.reservedIds must be an object with appIds and definitionIds arrays");try{let n=Reflect.ownKeys(e);if(n.length!==2||!n.includes("appIds")||!n.includes("definitionIds"))throw new TypeError("productBundle.reservedIds must contain exactly appIds and definitionIds");let t=(i,r)=>{if(!Array.isArray(i))throw new TypeError("productBundle.reservedIds."+r+" must be an array");let o=[];for(let s=0;s<i.length;s+=1){let a=i[s];if(typeof a!="string"||a.length===0)throw new TypeError("productBundle.reservedIds."+r+" must contain non-empty strings");o.push(a);}return Object.freeze([...new Set(o)].sort(je))};return Object.freeze({appIds:t(e.appIds,"appIds"),definitionIds:t(e.definitionIds,"definitionIds")})}catch(n){throw n instanceof TypeError?n:new TypeError("productBundle.reservedIds must be a valid reservation object")}}function uc(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 vn(e){return Object.freeze({appIds:Object.freeze([...new Set(e.map(n=>n.appId))].sort(je)),definitionIds:Object.freeze([...new Set(e.map(n=>n.definition.id))].sort(je))})}function xn(e,n){let t=Object.keys(e).sort(je),i=[...n].sort(je);return t.length===i.length&&t.every((r,o)=>r===i[o])}function _o(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 fc(e){let n;try{n=sc(e);}catch{return}if(!An(n)||!xn(n,["version","packages"])||n.version!==1||!Array.isArray(n.packages)||n.packages.length>Jt)return;let t=new Set,i=new Set,r=0,o=[];for(let s of n.packages){if(!An(s))return;let a=["packageDir","appId","definition","files"],d=Object.hasOwn(s,"lineage"),c=Object.hasOwn(s,"launcher"),p=[...d?["lineage"]:[],...c?["launcher"]:[]];if(!xn(s,[...a,...p])||c&&s.launcher!==false)return;let l=_o(s.packageDir),I=go(s.appId);if(!l||l.length!==2||l[0]!=="apps"||!tc(l[1])||!I||t.has(s.packageDir)||!An(s.definition)||!xn(s.definition,["id","version","hash"]))return;let _=go(s.definition.id),E=s.definition.version,L=s.definition.hash;if(!_||!Number.isSafeInteger(E)||E<1||typeof L!="string"||!Gt.test(L)||!Array.isArray(s.files)||s.files.length<2||s.files.length>Kt)return;let b=new Set,j=[];for(let C of s.files){if(!An(C)||!xn(C,["path","sha256"]))return;let k=_o(C.path);if(!k||typeof C.sha256!="string"||!Gt.test(C.sha256))return;let B=k.join("/"),h=`${s.packageDir}/${B}`;if(b.has(B)||i.has(h))return;b.add(B),i.add(h),j.push(Object.freeze({path:B,sha256:C.sha256}));}if(!ee.some(C=>b.has(C))||!b.has("ui/index.html")||(r+=j.length,r>qa))return;t.add(s.packageDir),o.push(Object.freeze({packageDir:s.packageDir,...c?{launcher:false}:{},appId:I,definition:Object.freeze({id:_,version:E,hash:L}),lineage:Array.isArray(s.lineage)?s.lineage:[],files:Object.freeze(j.sort((C,k)=>je(C.path,k.path)))}));}return Object.freeze({version:1,packages:Object.freeze(o)})}function ve(e){let n=ac(e);return n==="PATH_ESCAPED"||n==="IDENTITY_CHANGED"||n==="TOCTOU"?"PATH_ESCAPED":n==="LIMIT_EXCEEDED"?"LIMIT_EXCEEDED":"BUNDLE_INTEGRITY"}async function yc(e,n,t,i,r){let o=[],s=async(a,d)=>{if(!De(i,r))throw new P("LIMIT_EXCEEDED");if(d>2)throw new P("LIMIT_EXCEEDED");let c=await Wt(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 l=`${a}/${p.name}`;if(p.kind==="file"){if(o.push(l.slice(t.length+1)),o.length>Kt)throw new P("LIMIT_EXCEEDED")}else if(p.kind==="directory")await s(l,d+1);else throw p.kind==="symlink"?new P("PATH_ESCAPED"):new P("READ_DENIED")}};return await s(t,0),o.sort(je)}function Ac(e){return ee.includes(e)?262144:e==="ui/index.html"?ln:e==="ui/state.json"?65536:e.startsWith("ui/assets/")?Qa:Za}async function Eo(e,n,t,i){if(e===void 0)return {packages:[],diagnostics:[],incomplete:false,reservedIds:nc};let r=lc(e.reservedIds),o=[],s=(y,f,A)=>pc(y,"bundled",f),a=(y=[],f=false,A)=>({...A===void 0?{}:{indexHash:A},packages:y,diagnostics:o,incomplete:f,reservedIds:r});if(typeof e.root!="string"||e.root.length===0||typeof e.expectedIndexHash!="string"||!Gt.test(e.expectedIndexHash))return o.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a();let d;try{d=await ho(n,e.root,"bundle-index.json",Ya);}catch(y){return o.push(s(ve(y),"bundle-index.json")),a()}let c=createHash("sha256").update(d).digest("hex");if(c!==e.expectedIndexHash)return o.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a();let p=fc(d);if(p===void 0)return o.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a();if(!uc(vn(p.packages),r))return o.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a([],false,c);if(!De(t,i))return o.push(s("LIMIT_EXCEEDED","bundle-index.json")),a(p.packages.map(y=>({indexEntry:y,failureCode:"LIMIT_EXCEEDED"})),true,c);let l;try{l=await Wt(n,e.root,"");}catch(y){return o.push(s(ve(y),"bundle-index.json")),a(p.packages.map(f=>({indexEntry:f,failureCode:ve(y)})),false,c)}if(!De(t,i))return o.push(s("LIMIT_EXCEEDED","bundle-index.json")),a(p.packages.map(y=>({indexEntry:y,failureCode:"LIMIT_EXCEEDED"})),true,c);let I=l.find(y=>y.name==="bundle-index.json"&&y.kind==="file"),_=l.find(y=>y.name==="apps"&&y.kind==="directory"),E=y=>p.packages.map(f=>({indexEntry:f,failureCode:y}));if(!I)return o.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a(E("BUNDLE_INTEGRITY"),false,c);let L=l.filter(y=>y.name!=="bundle-index.json"&&y.name!=="apps");if(L.length>0){let y=L.some(f=>f.kind==="symlink")?"PATH_ESCAPED":"BUNDLE_INTEGRITY";return o.push(s(y,"bundle-index.json")),a(E("BUNDLE_INTEGRITY"),false,c)}if(l.some(y=>y.name==="apps"&&y.kind!=="directory"))return o.push(s("PATH_ESCAPED","apps")),a(E("PATH_ESCAPED"),false,c);let b=[];if(_)try{b=await Wt(n,e.root,"apps");}catch(y){return o.push(s(ve(y),"apps")),a(E(ve(y)),false,c)}if(!De(t,i)||b.length>Jt)return o.push(s("LIMIT_EXCEEDED","apps")),a(E("LIMIT_EXCEEDED"),true,c);let j=new Map(p.packages.map(y=>[y.packageDir.slice(5),y])),C=b.filter(y=>!j.has(y.name));for(let y of C)o.push(s(y.kind==="symlink"?"PATH_ESCAPED":"BUNDLE_INTEGRITY",`apps/${y.name}`));if(C.length>0){let y=C.some(f=>f.kind==="symlink")?"PATH_ESCAPED":"BUNDLE_INTEGRITY";return a(E(y),false,c)}let k=new Set,B=new Map,h=new Map;for(let y of p.packages){let f=B.get(y.appId)??[];f.push(y),B.set(y.appId,f);let A=`${y.definition.id}\0${String(y.definition.version)}`,D=h.get(A)??[];D.push(y),h.set(A,D);}for(let y of [...B.values(),...h.values()])if(y.length>1)for(let f of y)k.add(f);let m=[],N=d.byteLength,M=false;for(let y of p.packages){if(!De(t,i)){M=true,m.push({indexEntry:y,failureCode:"LIMIT_EXCEEDED"});continue}let f;try{let S=y.lineage[y.lineage.length-1];if(!S)throw new ge("LINEAGE_INVALID","Definition lineage is missing");if(S.definition.id!==y.definition.id||S.version!==y.definition.version||S.hash!==y.definition.hash)throw new ge("LINEAGE_STALE","Last lineage generation does not match bundle identity");f=wt(y.lineage,{...S.definition,hash:S.hash}).entries;}catch(S){let te=S instanceof ge?S.code:"LINEAGE_INVALID";o.push(s(te,y.packageDir)),m.push({indexEntry:y,failureCode:te});continue}let A=b.find(S=>S.name===y.packageDir.slice(5));if(!_||!A){m.push({indexEntry:y,failureCode:"BUNDLE_INTEGRITY"});continue}if(A.kind!=="directory"){m.push({indexEntry:y,failureCode:A.kind==="symlink"?"PATH_ESCAPED":"BUNDLE_INTEGRITY"});continue}let D;try{let S=await yc(n,e.root,y.packageDir,t,i);if(!De(t,i)){M=!0,m.push({indexEntry:y,failureCode:"LIMIT_EXCEEDED"});continue}let te=y.files.map(me=>me.path);if(S.length!==te.length||S.some((me,he)=>me!==te[he])){m.push({indexEntry:y,failureCode:"BUNDLE_INTEGRITY"});continue}D=new Map;let H;for(let me of y.files){if(!De(t,i)){H="LIMIT_EXCEEDED",M=!0;break}if(N>=$t){H="LIMIT_EXCEEDED";break}let he;try{he=await ho(n,e.root,`${y.packageDir}/${me.path}`,Ac(me.path));}catch(Nr){H=ve(Nr);break}if(!De(t,i)){H="LIMIT_EXCEEDED",M=!0;break}if(N+he.byteLength>$t){N=$t,H="LIMIT_EXCEEDED";break}if(N+=he.byteLength,createHash("sha256").update(he).digest("hex")!==me.sha256){H="BUNDLE_INTEGRITY";break}D.set(me.path,he);}if(H!==void 0){m.push({indexEntry:y,failureCode:H});continue}}catch(S){De(t,i)||(M=true),m.push({indexEntry:y,failureCode:ve(S)});continue}m.push({indexEntry:y,lineage:f,files:D,...k.has(y)?{failureCode:"DUPLICATE_ID"}:{}});}return a(m,M,c)}var Ya,Jt,Kt,qa,Za,Qa,$t,Gt,ec,nc,Xt=V(()=>{g();Ut();Ue();Mt();kt();zt();Ya=256*1024,Jt=64,Kt=128,qa=Jt*Kt,Za=2*1024*1024,Qa=8*1024*1024,$t=32*1024*1024,Gt=/^[0-9a-f]{64}$/,ec=new TextDecoder("utf-8",{fatal:true}),nc=Object.freeze({appIds:Object.freeze([]),definitionIds:Object.freeze([])});});function gc(e){if(typeof e!="string"||!ue.test(e))throw new TypeError("pluginId must be a safe UI plugin identifier");let n=`${Yt}${e}`.length+7<=128?e:`hash_${createHash("sha256").update(e,"utf8").digest("hex")}`;return {read:`${Yt}${n}_read`,action:`${Yt}${n}_action`}}function Po(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 hc(e,n){return n.length===0||n==="."||n===".."||/[\\/\u0000]/.test(n)?e==="skills"?"skills":"apps":`${e==="skills"?"skills":"apps"}/${n}`}function _c(e){return e.length>0&&e!=="."&&e!==".."&&!/[\\/\u0000]/.test(e)}function In(e,n){let t=new TextEncoder().encode(e),i=new TextEncoder().encode(n),r=Math.min(t.byteLength,i.byteLength);for(let o=0;o<r;o+=1){let s=t[o]-i[o];if(s!==0)return s}return t.byteLength-i.byteLength}function Co(e){if(typeof e=="string")return {name:e,kind:"directory"};if(e===null||typeof e!="object")return null;let n=e;if(typeof n.name!="string")return null;if(n.kind==="file"||n.kind==="directory"||n.kind==="symlink"||n.kind==="other")return {name:n.name,kind:n.kind};if(n.type==="file"||n.type==="directory"||n.type==="symlink"||n.type==="other")return {name:n.name,kind:n.type};let t=n.isDirectory;if(typeof t=="function"&&t.call(e))return {name:n.name,kind:"directory"};let i=n.isSymbolicLink;if(typeof i=="function"&&i.call(e))return {name:n.name,kind:"symlink"};let r=n.isFile;return typeof r=="function"&&r.call(e)?{name:n.name,kind:"file"}:{name:n.name,kind:"other"}}function Ec(e){if(e instanceof Uint8Array)return new Uint8Array(e);if(e instanceof ArrayBuffer)return new Uint8Array(e.slice(0));if(Array.isArray(e)&&e.every(n=>Number.isInteger(n)&&n>=0&&n<=255))return Uint8Array.from(e);throw new TypeError("filesystem port returned an invalid byte array")}function ko(e){return mc.decode(e)}function Tc(e){return JSON.parse(ko(e))}function Pc(e){if(e===void 0)return;let n=e.definitionId!==void 0&&e.definitionVersion!==void 0?`${e.definitionId}\0${String(e.definitionVersion)}`:void 0;return {pluginId:e.pluginId,...n===void 0?{}:{definitionKey:n}}}function Vn(e,n,t,i,r){let o={code:e,...i===void 0?{}:{pluginId:i},source:n,relativePath:t,...r?.reason===void 0?{}:{reason:Object.freeze({...r.reason})},...r?.files===void 0?{}:{files:Object.freeze([...r.files])}};return Object.freeze(o)}function Do(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 ce(e){if(e instanceof P)return Do(e.code);if(e!==null&&typeof e=="object"&&"code"in e){let n=e.code;if(typeof n=="string")return Do(n)}}function qe(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 bo(e){return {reason:e.reason,...e.code==="MANIFEST_DUAL_MISMATCH"?{files:e.files}:{}}}function No(e){return e==="MANIFEST_DUAL_MISMATCH"?e:xo(e)}function Dc(e){return xo(e.code)}function xo(e){switch(e){case "MANIFEST_INVALID":case "PRIMITIVE_UNKNOWN":case "PRIMITIVE_SET_UNSUPPORTED":case "SCHEMA_TYPE_UNSUPPORTED":case "TOKEN_INVALID":case "UNSAFE_VALUE":return "MANIFEST_INVALID";case "LIMIT_EXCEEDED":return "LIMIT_EXCEEDED";case "INITIAL_STATE_INVALID":return "INITIAL_STATE_INVALID";default:return vo("UiPluginValidationError",e)}}function vo(e,n){throw new Error(`Unmapped ${e} code: ${String(n)}`)}function bc(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 vo("McpAppContractError",e)}}function be(e,n){let t=n();return Number.isFinite(t)&&Number.isFinite(e)&&t-e<=5e3}function Nc(e){return {pluginId:e.appId,definitionKey:`${e.definition.id}\0${String(e.definition.version)}`}}function Sc(e,n){let t=n.get("package.json");if(t!==void 0)try{let r=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(t));if(Po(r)){let o=r.bin,s=typeof o=="string"?o:Po(o)?Object.values(o).find(a=>typeof a=="string"):void 0;for(let a of [s,r.main]){if(typeof a!="string")continue;let d=Mc(a);if(d&&n.has(d))return d}}}catch{}return [`${e.slice(e.lastIndexOf("/")+1)}.js`,"index.js","main.js"].find(r=>n.has(r))}function Mc(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 Lc(){return globalThis.performance?.now()??Date.now()}function Ve(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let n of Object.values(e))Ve(n);return Object.freeze(e)}function So(e){return Object.freeze(Array.from(e))}async function Zt(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 r=`${n.relativePath}/${t}`,o=n.scanContext,s=e.fingerprintVerifiedFile;if(o===void 0||!o.cacheable||typeof s!="function")return Ro(e,n.root,r,i);try{let a=o.priorFingerprints.get(r)??await s.call(e,o.workspaceRoot,r,i);o.candidateRealPath=a.candidateRealPath;let d=await Ro(e,n.root,r,i),c=await s.call(e,o.workspaceRoot,r,i);return o.candidateRealPath=c.candidateRealPath,Fo(a,c)&&c.size===BigInt(d.byteLength)&&!Bo(c,o.scanStartedAtNs)?o.files.set(r,{relativePath:r,byteLimit:i,fingerprint:c}):o.cacheable=!1,d}catch(a){throw ee.includes(t)&&ce(a)==="NOT_FOUND"&&o.directoryListings.some(c=>c.relativePath===n.relativePath&&!Vo(c.key,t))||(o.cacheable=false),a}}function jo(e,n){return JSON.stringify([e.realPath,n.source,n.relativePath])}async function Oc(e,n,t,i,r,o,s,a){let d=e.fingerprintVerifiedFile,c=jo(t,i),p=r.candidates.get(c),l=i.relativePath,I;try{I=await Oo(e,n,l);}catch(h){if(ce(h)!=="NOT_FOUND")throw h}let _=I===void 0?void 0:{relativePath:l,key:I};if(_!==void 0&&(i.source==="apps"||i.source==="skills")&&!ee.some(h=>Vo(_.key,h)))return be(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:r,cacheKey:c,workspaceRoot:n,scanStartedAtNs:o,directoryListings:Object.freeze([_]),priorFingerprints:new Map,files:new Map,cacheable:true}}:{timeLimitReached:true};let E=await Promise.all(Mo.map(async h=>{if(h==="")return _;let m=`${i.relativePath}${h}`;try{let N=await Oo(e,n,m);return N===void 0?void 0:{relativePath:m,key:N}}catch(N){if(ce(N)==="NOT_FOUND")return;throw N}}));if(!be(s,a))return {timeLimitReached:true};let L=typeof d=="function"&&E.every(h=>h!==void 0),b=E.filter(h=>h!==void 0),j=new Map,C=p!==void 0&&L,k;if(p!==void 0&&typeof d=="function"){let h=await Promise.all(p.files.map(async m=>{if(!be(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 ce(N)==="NOT_FOUND"?{kind:"missing",file:m}:{kind:"error",file:m,error:N}}}));if(h.some(m=>m.kind==="time"))return {timeLimitReached:true};for(let m of h){if(m.kind==="error")throw m.error;if(m.kind==="missing"){C=false;continue}if(m.kind!=="fingerprint")continue;let{file:N,current:M}=m;j.set(N.relativePath,M),k??=M.candidateRealPath,(M.candidateRealPath!==p.candidateRealPath||!Fo(M,N.fingerprint)||Bo(M,o))&&(C=false);}}let B=p!==void 0&&p.directoryListings.length===b.length&&p.directoryListings.every((h,m)=>h.relativePath===b[m]?.relativePath&&h.key===b[m]?.key);return p!==void 0&&L&&B&&C&&k===p.candidateRealPath?{memo:p}:!L||b.length!==Mo.length?{}:{context:{state:r,cacheKey:c,workspaceRoot:n,scanStartedAtNs:o,directoryListings:Object.freeze(b),priorFingerprints:j,files:new Map,...k===void 0?{}:{candidateRealPath:k},cacheable:true}}}function Vo(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 Oo(e,n,t){let i=Ho(e);if(typeof i!="function")return;let r=await i.call(e,n,t);if(!Array.isArray(r)||r.some(s=>typeof s=="string"))return;let o=r.map(Co);if(!o.some(s=>s===null))return JSON.stringify(o.slice().sort((s,a)=>In(s.name,a.name)||In(s.kind,a.kind)).map(s=>[s.name,s.kind]))}function Fo(e,n){return e.dev===n.dev&&e.ino===n.ino&&e.size===n.size&&e.mtimeNs===n.mtimeNs&&e.ctimeNs===n.ctimeNs}function Bo(e,n){let t=e.mtimeNs-n;return t>=-Lo&&t<=Lo}function qt(e){let n=e.scanContext,t=e.source==="skills"&&e.candidate===void 0&&e.diagnostic===void 0&&n?.files.size===0,i=e.source==="apps"&&e.candidate===void 0&&e.diagnostic?.code==="MANIFEST_MISSING"&&n?.files.size===0,r=t||i;if(n===void 0||!n.cacheable||n.candidateRealPath===void 0&&!r||n.files.size===0&&!r)return;let o=Object.freeze({...!r&&n.candidateRealPath!==void 0?{candidateRealPath:n.candidateRealPath}:{},directoryListings:n.directoryListings,files:Object.freeze([...n.files.values()]),...e.candidate===void 0?{}:{candidate:e.candidate},...e.diagnostic===void 0?{}:{diagnostic:e.diagnostic},...e.identity===void 0?{}:{identity:e.identity},...e.provenance===void 0?{}:{provenance:e.provenance}});n.state.candidates.set(n.cacheKey,o);}function Rc(e,n,t){let i=createHash("sha256"),r=new TextEncoder().encode(Y(e)),o=s=>{let a=new Uint8Array(8);new DataView(a.buffer).setBigUint64(0,BigInt(s)),i.update(a);};return o(r.byteLength),i.update(r),o(n.byteLength),i.update(n),o(t.byteLength),i.update(t),i.digest("hex")}function wc(e,n){let t={...e.definition,sourceHash:n},i;try{i=de(t);}catch(o){throw o instanceof O&&o.code==="INPUT_INVALID"?new Z("MANIFEST_INVALID","normalized definition is invalid"):o}let r={...t,hash:i};try{Te(r);}catch{throw new Z("MANIFEST_INVALID","normalized definition is invalid")}return r}function Uc(e){return e.actions.some(n=>n.backend.type==="core"&&n.backend.handler!=="state.set")}function Cc(e){if(typeof e.readVerifiedFile=="function")return e.readVerifiedFile;if(typeof e.readFileVerified=="function")return e.readFileVerified}function Ho(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 Ro(e,n,t,i){let r=Cc(e);if(!r)throw new P("READ_DENIED");return Ec(await r.call(e,n,t,i))}async function kc(e,n,t){let i=Ho(e);if(!i)throw new P("READ_DENIED");let r=await i.call(e,n,t);if(!Array.isArray(r))throw new P("READ_DENIED");return r.map(Co).filter(o=>o!==null)}function xc(e){let n=[];for(let t of [e.reserved,e.builtin])t&&n.push(t);return e.builtins&&"listMcpApps"in e.builtins?n.push(wo(e.builtins)):e.builtins&&n.push(e.builtins),e.builtinCatalog&&n.push(wo(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 wo(e){let n=[],t=[],i=[];for(let r of e.listMcpApps())typeof r.appId=="string"&&n.push(r.appId),r.definition&&typeof r.definition.id=="string"&&t.push(r.definition.id);for(let r of e.listMcpAppTools())typeof r.name=="string"&&i.push(r.name);return {appIds:n,definitionIds:t,toolNames:i}}function Ne(e,n){e.diagnostic||(e.diagnostic=Vn(n,e.source,e.relativePath,e.identity?.pluginId));}function vc(e){let n=new Map;for(let i of e){let r=i.identity?.pluginId;if(r===void 0)continue;let o=n.get(r)??[];o.push(i),n.set(r,o);}for(let i of n.values()){if(i.length<2)continue;let r=i.filter(s=>s.provenance!==void 0);if(r.length>0){for(let s of i)s.provenance===void 0&&Ne(s,"RESERVED_ID");if(r.length>1)for(let s of r)Ne(s,"DUPLICATE_ID");continue}let o=i.filter(s=>s.source==="apps");if(o.length>1){for(let s of o)Ne(s,"DUPLICATE_ID");for(let s of i.filter(a=>a.source==="skills"))Ne(s,"DUPLICATE_ID");}else for(let s of i.filter(a=>a.source==="skills"))Ne(s,"DUPLICATE_ID");}let t=new Map;for(let i of e){if(i.diagnostic?.code==="RESERVED_ID")continue;let r=i.identity?.definitionKey;if(r===void 0)continue;let o=t.get(r)??[];o.push(i),t.set(r,o);}for(let i of t.values())if(i.length>1)for(let r of i)Ne(r,"DUPLICATE_ID");}function jc(e,n,t){let i=new Set,r=new Set,o=new Set,s=new Set(t.appIds),a=new Set(t.definitionIds);for(let d of xc(n)){for(let c of d.appIds??[])typeof c=="string"&&i.add(c);for(let c of d.definitionIds??[])typeof c=="string"&&r.add(c);for(let c of d.toolNames??[])typeof c=="string"&&o.add(c);}for(let d of e){let c=d.candidate;if(!c)continue;if(i.has(c.pluginId)||r.has(c.definitionId)){Ne(d,"RESERVED_ID");continue}if(d.provenance===void 0&&(s.has(c.pluginId)||a.has(c.definitionId))){Ne(d,"RESERVED_ID");continue}[c.toolNames.read,c.toolNames.action].filter(l=>l!==void 0).some(l=>o.has(l))&&Ne(d,"DUPLICATE_ID");}}function Vc(e){return [...e].sort((n,t)=>{let i=To.indexOf(n.source)-To.indexOf(t.source);return i!==0?i:In(n.relativePath,t.relativePath)})}function v(e,n,t){e.diagnostic=Vn(n,e.source,e.relativePath,e.identity?.pluginId,t);}async function Uo(e,n,t){let i=sn(t,{mode:"local"});if(!i.ok&&i.parseFailure){v(n,No(i.rejection.code),bo(i.rejection));return}let r=Pc(i.identity);if(n.bundleIdentity===void 0)n.identity=r;else if(r?.pluginId!==n.bundleIdentity.appId||r.definitionKey!==`${n.bundleIdentity.definitionId}\0${String(n.bundleIdentity.version)}`){v(n,"BUNDLE_INTEGRITY");return}if(!i.ok&&i.builtinOnly){v(n,"RESERVED_ID");return}if(!i.ok){v(n,No(i.rejection.code),bo(i.rejection));return}let o=i.manifest,s={pluginId:o.pluginId,definitionKey:`${o.definitionId}\0${String(o.version)}`};if(n.bundleIdentity===void 0&&(n.identity=s),o.actions.length>0)try{ao(o.actions.map(S=>({actionId:S.actionId,inputSchema:S.inputSchema})));}catch(S){if(S instanceof we){v(n,bc(S.code));return}throw S}let a;try{a=await Zt(e,n,"ui/index.html",ln);}catch(S){v(n,qe(ce(S),"entry"));return}if(a.byteLength>ln){v(n,"LIMIT_EXCEEDED");return}let d;try{d=ko(a);}catch{v(n,"ENTRY_INVALID");return}if(a.byteLength===0||d.length===0){v(n,"ENTRY_INVALID");return}let c=createHash("sha256").update(a).digest("hex");if(o.entryHash!==void 0&&o.entryHash!==c){v(n,"ENTRY_INVALID");return}let p={},l,I;if(o.initialState!==void 0){try{l=await Zt(e,n,"ui/state.json",65536);}catch(S){v(n,qe(ce(S),"initial"));return}if(l.byteLength>65536){v(n,"LIMIT_EXCEEDED");return}try{let S=Tc(l),te=o.dataPaths??[],H=ht(S,te);p=_e(H,0,te),He(p);}catch{v(n,"INITIAL_STATE_INVALID");return}if(I=createHash("sha256").update(l).digest("hex"),o.initialState.hash!==void 0&&o.initialState.hash!==I){v(n,"INITIAL_STATE_INVALID");return}}let _={...o,entryHash:c,...o.initialState===void 0?{}:{initialState:{path:"ui/state.json",hash:I}}},E=on(_),L=Rc(_,a,l??new Uint8Array),b;try{b=wc(E,L);}catch(S){if(S instanceof Z){v(n,Dc(S));return}throw S}let j;if(n.bundleLineage!==void 0){let S=n.bundleLineage[n.bundleLineage.length-1];if(!S){v(n,"LINEAGE_INVALID");return}let{legacy:te,...H}=S.definition,{hash:me,...he}=b;if(Y(H)!==Y(he)){v(n,"LINEAGE_STALE");return}if(te!==void 0&&(b={...b,legacy:te}),te!==void 0)try{b={...b,hash:de(b)},Te(b);}catch{v(n,"LINEAGE_INVALID");return}j=n.bundleLineage;}if(n.bundleIdentity!==void 0&&n.bundleIdentity.appId!==o.pluginId){v(n,"BUNDLE_INTEGRITY");return}if(n.bundleIdentity!==void 0&&(n.bundleIdentity.definitionId!==b.id||n.bundleIdentity.version!==b.version||n.bundleIdentity.definitionHash!==b.hash)){v(n,"LINEAGE_STALE");return}let C=gc(o.pluginId),k=o.actions.length===0?{read:C.read}:C,B=Ve(E),h=Ve(_),m=Ve(b),N=Ve({...E.handlers}),M=So(a),y=l===void 0?void 0:So(l),f=Object.freeze({...n.provenance===void 0?{}:{provenance:n.provenance},entry:Object.freeze({path:"ui/index.html",hash:c,bytes:M}),...y===void 0?{}:{initialState:Object.freeze({path:"ui/state.json",hash:I,bytes:y})}}),A={appId:o.pluginId,pluginId:o.pluginId,definitionId:o.definitionId,version:o.version,...i.releaseVersion===void 0?{}:{releaseVersion:i.releaseVersion},manifestFile:i.file,...i.mcpb===void 0?{}:{mcpb:Ve(i.mcpb)},relativePath:n.relativePath,manifest:h,normalized:B,name:o.name,description:o.description,...o.icon===void 0?{}:{icon:o.icon},...o.tone===void 0?{}:{tone:o.tone},definition:m,handlers:N,resources:f,html:d,entryBytes:M,entryHash:c,initialState:Ve(p),...y===void 0?{}:{initialStateBytes:y},...I===void 0?{}:{initialStateHash:I},sourceHash:L,toolNames:Object.freeze(k)},D=n.provenance===void 0?{...A,source:n.source}:{...A,provenance:n.provenance,lineage:j??[]};n.candidate=Object.freeze(D),Uc(o)&&v(n,"EXEC_DENIED");}async function zo(e,n){let t={};for(let i of ee)try{t[i]=await Zt(e,n,i,262144);}catch(r){if(ce(r)==="NOT_FOUND")continue;return {files:t,failure:qe(ce(r),"manifest")}}return {files:t}}function Qt(e){return ee.some(n=>e[n]!==void 0)}async function Fc(e,n){let{files:t,failure:i}=await zo(e,n);if(i!==void 0){v(n,i);return}let r=t[ie];return r!==void 0&&!St(r)&&delete t[ie],Qt(t)?t:void 0}function Bc(e,n,t,i=Ic,r=false){let o=Vc(e);vc(o);let s=Object.freeze(o.filter(p=>p.candidate!==void 0&&p.diagnostic===void 0).map(p=>p.candidate)),a=Object.freeze(o.filter(p=>p.diagnostic!==void 0).map(p=>p.diagnostic)),d=r?Object.freeze({...t===void 0?{}:{indexHash:t},candidates:Object.freeze(o.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 Hc(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 zc(e,n){if(Hc(e))return {fs:e,options:{}};let t=e??n??{};return {fs:t.filesystem??t.fileSystem??t.fs??Ao,options:t}}async function $o(e,n,t){if(typeof e!="string"||e.length===0)throw new TypeError("workspaceRoot must be explicit");let{fs:i,options:r}=zc(n,t),o=r.clock??Lc,s=o(),a=await Eo(r.productBundle,i,s,o),d=o(),c=BigInt(Date.now())*1000000n,p=[],l=0,I,_=false,E,L;if(r.scanCache!==void 0&&typeof i.getRootIdentity=="function"&&typeof i.fingerprintVerifiedFile=="function")try{L=await i.getRootIdentity(e),E=po(r.scanCache,L),E.scanStartedAtNs=c;}catch(h){if(ce(h)!=="NOT_FOUND")throw h}let b=E!==void 0&&r.productBundle===void 0&&a.packages.length===0&&a.diagnostics.length===0,j=new Set,C=true;p.push(...a.diagnostics.map(h=>({source:h.source,root:r.productBundle?.root??e,name:"",relativePath:h.relativePath,diagnostic:h})));let k=a.reservedIds;a.incomplete&&(I="time_limit");for(let h of a.packages){if(!be(d,o)){_=true,I="time_limit";break}let m=h.indexEntry,N=m.packageDir,M=h.files===void 0?void 0:Sc(N,h.files),y=a.indexHash===void 0?void 0:Zi(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}),M),f={source:"bundled",root:r.productBundle?.root??e,name:N.slice(5),relativePath:N,...y===void 0?{}:{provenance:y},...h.files===void 0?{}:{pinnedFiles:h.files},...h.lineage===void 0?{}:{bundleLineage:h.lineage},bundleIdentity:{appId:m.appId,definitionId:m.definition.id,version:m.definition.version,definitionHash:m.definition.hash},identity:Nc(m)};if(p.push(f),l+=1,h.failureCode!==void 0){v(f,h.failureCode);continue}let A={};for(let D of ee){let S=h.files?.get(D);S!==void 0&&(A[D]=S);}if(!Qt(A)){v(f,"BUNDLE_INTEGRITY");continue}if(await Uo(i,f,A),!be(d,o)){_=true,I="time_limit";break}}let B=[{source:"apps",directory:"apps"},{source:"skills",directory:"skills"}];e:for(let h of B){let{source:m,directory:N}=h,M;try{M=await kc(i,e,N);}catch(f){if(ce(f)==="NOT_FOUND")continue;b=false,C=false,p.push({source:m,root:e,name:"",relativePath:m,diagnostic:Vn(qe(ce(f),"manifest"),m,m)});continue}let y=M.filter(f=>f.kind==="directory"||f.kind==="symlink").filter(f=>_c(f.name)).map(f=>({source:m,root:e,name:f.name,relativePath:hc(m,f.name)})).sort((f,A)=>In(f.relativePath,A.relativePath));for(let f of y){let A={...f};if(p.push(A),L!==void 0?j.add(jo(L,A)):b=false,!be(d,o)){_=true,I="time_limit";break e}let D;if(E!==void 0&&L!==void 0){try{let H=await Oc(i,e,L,A,E,c,d,o);if(H.timeLimitReached){_=!0,I="time_limit";break e}A.scanContext=H.context,D=H.memo;}catch(H){b=false,v(A,qe(ce(H),"manifest"));continue}D===void 0&&(b=false);}if(D!==void 0){if(A.candidate=D.candidate,A.diagnostic=D.diagnostic,A.identity=D.identity,m==="skills"&&D.candidate===void 0&&D.diagnostic===void 0)continue;if(l>=64){v(A,"LIMIT_EXCEEDED");continue}if(f.relativePath.split("/").length-1>2){v(A,"LIMIT_EXCEEDED");continue}if(l+=1,!be(d,o)){_=true,I="time_limit";break e}continue}let S;if(m==="skills"&&(S=await Fc(i,A),S===void 0)){A.diagnostic===void 0&&qt(A);continue}if(l>=64){v(A,"LIMIT_EXCEEDED");continue}if(f.relativePath.split("/").length-1>2){v(A,"LIMIT_EXCEEDED");continue}if(!be(d,o)){_=true,I="time_limit";break e}if(l+=1,S===void 0){let H=await zo(i,A);if(H.failure!==void 0||!Qt(H.files)){v(A,H.failure??qe("NOT_FOUND","manifest")),qt(A);continue}S=H.files;}if(await Uo(i,A,S),qt(A),!be(d,o)){_=true,I="time_limit";break e}}}if(E!==void 0&&L!==void 0){let h=[...j].sort(In),m=E.lastCandidateKeys,N=m!==void 0&&m.length===h.length&&m.every((y,f)=>y===h[f]);if(b=b&&N,C&&!_&&I===void 0)for(let y of E.candidates.keys())try{JSON.parse(y)[0]===L.realPath&&!j.has(y)&&E.candidates.delete(y);}catch{E.candidates.delete(y);}let M=[...E.candidates.keys()].filter(y=>{try{return JSON.parse(y)[0]===L.realPath}catch{return false}});b=b&&M.length===j.size&&M.every(y=>j.has(y))&&!_&&I===void 0,E.lastCandidateScanUnchanged=b,C&&!_&&I===void 0&&(E.lastCandidateKeys=Object.freeze(h));}return _&&p.push({source:"apps",root:e,name:"",relativePath:"apps",diagnostic:Vn("DISCOVERY_TIME_LIMIT","apps","apps")}),jc(p,r,k),Bc(p,I,a.indexHash,k,r.productBundle!==void 0)}var Ic,Yt,To,mc,Mo,Lo,Go=V(()=>{g();Ce();mn();Ee();Lt();Ue();kt();Ln();lo();zt();On();Xt();Xt();Ic=vn([]),Yt="crewx_local_app_";To=["bundled","apps","skills"],mc=new TextDecoder("utf-8",{fatal:true});Mo=["","/ui"],Lo=2000000000n;});g();Lt();g();pt();g();var Hi="SKILL.md",Na=/^---\s*\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;function zi(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function Sa(e){return e.isDirectory()||e.isSymbolicLink()}function Ki(e){try{return existsSync(e)&&statSync(e).isDirectory()}catch{return false}}function Ot(e){let n;try{n=readFileSync(e,"utf8");}catch{return {frontmatter:{},readable:false,valid:false,hasFrontmatter:false}}let t=n.match(Na);if(!t)return {frontmatter:{},readable:true,valid:true,hasFrontmatter:false};try{let i=load(t[1]??"");if(!zi(i))return {frontmatter:{},readable:!0,valid:!1,hasFrontmatter:!0};let r=zi(i.metadata)?i.metadata:void 0;return {frontmatter:{...typeof i.name=="string"?{name:i.name}:{},...typeof(r?.version??i.version)=="string"?{version:r?.version??i.version}:{},...typeof i.description=="string"?{description:i.description}:{}},readable:!0,valid:!0,hasFrontmatter:!0}}catch{return {frontmatter:{},readable:true,valid:false,hasFrontmatter:true}}}function Ma(e){return [join(e,Hi),join(e,"skill",Hi)]}function $i(e,n){if(!Ki(e))return null;for(let t of Ma(e)){if(!existsSync(t))continue;let r=Ot(t).frontmatter;return {name:r.name??n,...r.version===void 0?{}:{version:r.version},...r.description===void 0?{}:{description:r.description},skillMdPath:t,dir:e}}return null}function Gi(e){try{return readdirSync(e,{withFileTypes:!0}).filter(Sa)}catch{return []}}function Wi(e,n,t){!e||n.has(e.name)||(n.add(e.name),t.push(e));}function Xi(e){let n=[],t=new Set;for(let i of e)if(Ki(i))for(let r of Gi(i)){if(r.name.startsWith("@")){let o=join(i,r.name);for(let s of Gi(o))Wi($i(join(o,s.name),s.name),t,n);continue}Wi($i(join(i,r.name),r.name),t,n);}return n.sort((i,r)=>i.name.localeCompare(r.name))}Go();var Gc=/^[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?Wc(e.relativePath,e.fileBytes):void 0);if(n!==void 0&&i!==void 0){let r=JSON.stringify({screenHash:n,skillHash:i});return createHash("sha256").update(r,"utf8").digest("hex")}if(n!==void 0)return n;if(i!==void 0)return i;throw new TypeError("App definition hash input must contain a screenHash or skill bytes")}function Wc(e,n){let t=new TextEncoder().encode(Hn(e)),i=Jc(n),r=new Uint8Array(t.byteLength+1+i.byteLength);return r.set(t,0),r[t.byteLength]=0,r.set(i,t.byteLength+1),createHash("sha256").update(r).digest("hex")}function Jc(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 Hn(e){if(typeof e!="string"||e.length===0||isAbsolute(e)||/[\\\u0000]/.test(e))throw new TypeError("relative path must be package-relative");let n=e.split("/").filter(t=>t.length>0&&t!==".").join("/");if(!n||n.split("/").some(t=>t===".."))throw new TypeError("relative path must stay inside the package");return n}function Fn(e,n){let t=new TextEncoder().encode(e),i=new TextEncoder().encode(n),r=Math.min(t.byteLength,i.byteLength);for(let o=0;o<r;o+=1){let s=t[o]-i[o];if(s!==0)return s}return t.byteLength-i.byteLength}function Ko(e,n){let t=relative(e,n).split(sep).join("/");return !t||t===".."||t.startsWith("../")||isAbsolute(t)?null:Hn(t)}function Kc(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 Xo(e){return Object.freeze({packageRoot:e})}function Xc(e){return Object.freeze({id:e.definition.id,version:e.definition.version,hash:e.definition.hash,usage:e.definition.usage??Oe,...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 Yo(e){return {capabilities:Object.freeze([...e]),origin:"local",ownership:"unknown",shareability:"unknown",sharingAvailability:"unavailable"}}function Yc(e,n){let t=e.candidate,i=t.provenance!==void 0,r=n&&!i?["screen","skill"]:["screen"],o=Xc(t),s=Bn(n?{screenHash:o.hash,skillHash:n.skillHash}:{screenHash:o.hash}),a=t.description||n?.skill.description||"",d=String(t.version),c={appId:t.pluginId,name:t.name,description:a,version:d,...Yo(r),definition:o,...n===void 0||i?{}:{skillName:n.skill.name},...i?{provenance:t.provenance}:{localDefinitionRef:Xo(e.packageRoot)},definitionHash:s};return {...i?{}:{packageRoot:e.packageRoot},source:i?"bundled":t.source,appId:c.appId,capabilities:r,summary:Object.freeze(c)}}function qc(e){let n=Zc(e.skill.name),t={appId:n,name:e.skill.name,description:e.skill.description??"",...e.skill.version===void 0?{}:{version:e.skill.version},...Yo(["skill"]),skillName:e.skill.name,localDefinitionRef:Xo(e.packageRoot),definitionHash:Bn({skillHash:e.skillHash})};return {packageRoot:e.packageRoot,source:e.source,appId:n,capabilities:["skill"],summary:Object.freeze(t)}}function Zc(e){return `skill.${e.replace(/^@/,"").replace(/\//g,".").replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,122)||"unnamed"}`}function J(e,n,t,i,r){return Object.freeze({code:e,source:n,relativePath:Qc(t),...i===void 0?{}:{appId:i},...r?.reason===void 0?{}:{reason:r.reason},...r?.files===void 0?{}:{files:r.files}})}function Qc(e){if(typeof e!="string"||e.length===0||isAbsolute(e)||/[\\\u0000]/.test(e))return "<unknown>";let n=e.split("/").filter(t=>t.length>0&&t!==".").join("/");return n.split("/").some(t=>t==="..")?"<unknown>":n}function qo(e){return J(e.code,e.source,e.relativePath,e.pluginId,e)}function ed(e,n){let t=Ko(e,n.dir);if(!t)return {diagnostic:J("PATH_ESCAPED","node_modules","node_modules")};let i=Kc(t);if(!i)return {diagnostic:J("PATH_ESCAPED","node_modules",t)};let r=Ot(n.skillMdPath);if(!r.readable)return {diagnostic:J("SKILL_READ_FAILED",i,t)};if(!r.valid)return {diagnostic:J("SKILL_INVALID",i,t)};let o=nd(n.dir,n.skillMdPath);if(!o)return {diagnostic:J("PATH_ESCAPED",i,t)};try{let s=new Uint8Array(readFileSync(n.skillMdPath));return {skill:n,packageRoot:t,relativeSkillPath:o,skillHash:Bn({relativePath:o,fileBytes:s}),source:i}}catch{return {diagnostic:J("SKILL_READ_FAILED",i,t)}}}function nd(e,n){let t=relative(e,n).split(sep).join("/");try{return Hn(t)}catch{return null}}function td(e){if(!Gc.test(e.appId))return {diagnostic:J("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??Oe,...e.definition.detailPanel===void 0?{}:{detailPanel:e.definition.detailPanel},...e.definition.displayModes===void 0?{}:{displayModes:e.definition.displayModes},...e.definition.summaryProjection===void 0?{}:{summaryProjection:e.definition.summaryProjection}},t=n?.hash??createHash("sha256").update(JSON.stringify({appId:e.appId,name:e.name,description:e.description}),"utf8").digest("hex"),i={appId:e.appId,name:e.name,description:e.description,...n===void 0?{}:{version:String(n.version),definition:n},capabilities:["screen"],origin:"builtin",ownership:"unknown",shareability:"forbidden",sharingAvailability:"unavailable",definitionHash:t};return {source:"builtin",appId:e.appId,summary:Object.freeze(i)}}function id(e){return e.builtinCatalog}function od(e){let n=e.packageRoot??e.relativePath??e.packageRootPath;if(n===void 0)return null;try{return Hn(n)}catch{return null}}function rd(e){let n=e.marketplaceContentId;return typeof n=="string"&&n.length>0?n:void 0}function sd(e,n,t){let i=n.installed??[],r=new Map;for(let s of i){let a=od(s);if(!a){t.push(J("INSTALLED_IDENTITY_MISMATCH","installed","installed"));continue}let d=r.get(a);if(d&&JSON.stringify(d)!==JSON.stringify(s)){t.push(J("INSTALLED_IDENTITY_MISMATCH","installed",a));continue}r.set(a,s);}let o=new Map;for(let s of e)s.packageRoot!==void 0&&o.set(s.packageRoot,s);for(let[s,a]of r){let d=o.get(s);if(!d){t.push(J("INSTALLED_MISSING","installed",s,a.appId));continue}let c=rd(a);if(!c){t.push(J("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(J("INSTALLED_IDENTITY_MISMATCH","installed",s,a.appId));continue}let p={...d.summary,origin:"installed",...a.slug===void 0?{}:{slug:a.slug},marketplaceContentId:c},l=e.indexOf(d);l>=0&&(e[l]={...d,summary:Object.freeze(p)});}}function ad(e,n){let t=new Map;for(let r of e){let o=t.get(r.appId)??[];o.push(r),t.set(r.appId,o);}let i=new Set;for(let r of t.values()){if(r.length<2)continue;let o=r.some(s=>s.source==="builtin")?"builtin":r.some(s=>s.source==="bundled")?"bundled":void 0;if(o!==void 0){let s=r.filter(a=>a.source===o);for(let a of r.filter(d=>d.source!==o))i.add(a),n.push(J("RESERVED_ID",a.source,ni(a),a.appId));if(s.length>1)for(let a of s)i.add(a),n.push(J("DUPLICATE_ID",a.source,ni(a),a.appId));continue}for(let s of r)i.add(s),n.push(J("DUPLICATE_ID",s.source,ni(s),s.appId));}return e.filter(r=>!i.has(r))}function ni(e){return e.packageRoot??e.summary.provenance?.packageDir??`builtin/${e.appId}`}function cd(e,n){return e.filter(t=>!(t.code==="MANIFEST_MISSING"&&n.has(t.relativePath))).map(qo)}function dd(e){return e.filesystem}function pd(e,n){let t=dd(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 Zo(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=id(n),i=await $o(e,pd(n,t)),r=n.registeredProductBundle??i.productBundleSnapshotMetadata,o=[join(e,"skills"),join(e,"node_modules"),join(e,"apps")],s=[],a=[],d=[],c=new Set;for(let f of o)for(let A of Xi([f])){let D=Ko(e,A.dir);(D===null||!c.has(D))&&(d.push(A),D!==null&&c.add(D));}for(let f of d){let A=ed(e,f);"diagnostic"in A?s.push(A.diagnostic):a.push(A);}let p=new Map,l=n.registeredProductBundle?.indexHash,I=(n.registeredProductBundle?.candidates??[]).filter(f=>l!==void 0&&f.provenance?.indexHash===l),_=[...i.apps??i.candidates??[],...I],E=new Set(I),L=new Set(l===void 0?[]:(t?.listMcpApps()??[]).filter(f=>f.provenance?.indexHash===l).map(f=>f.appId));for(let f of _){if(E.has(f)&&f.provenance?.indexHash===l&&L.has(f.appId))continue;let A=f.provenance===void 0?`workspace\0${f.relativePath}`:`bundled\0${f.provenance.indexHash}\0${f.provenance.packageDir}`;p.set(A,{candidate:f,packageRoot:f.relativePath});}let b=new Map(a.map(f=>[f.packageRoot,f])),j=[];for(let f of p.values()){let A=f.candidate.provenance===void 0?b.get(f.packageRoot):void 0,D=Yc(f,A);j.push({...D.packageRoot===void 0?{}:{packageRoot:D.packageRoot},source:D.source,appId:D.appId,summary:D.summary});}let C=new Set([...p.values()].filter(f=>f.candidate.provenance===void 0).map(f=>f.packageRoot)),k=r===void 0?new Set:new Set(i.diagnostics.filter(f=>f.code==="RESERVED_ID"&&f.source!=="bundled").map(f=>f.relativePath)),B=new Set(r?.reservedAppIds??[]);for(let f of a){let A=qc(f);if(!(C.has(f.packageRoot)||k.has(f.packageRoot))){if(B.has(A.appId)){s.push(J("RESERVED_ID",f.source,f.packageRoot,A.appId));continue}j.push({packageRoot:A.packageRoot,source:A.source,appId:A.appId,summary:A.summary});}}let h=[...cd(i.diagnostics,new Set(a.map(f=>f.packageRoot))),...s,...n.registeredProductBundle?.diagnostics.filter(f=>f.source==="bundled").map(qo)??[]],m=[];if(t)for(let f of t.listMcpApps()){let A=td(f);"diagnostic"in A?h.push(A.diagnostic):m.push(A);}let N=ad([...j,...m],h);sd(N,n,h);let M=N.map(f=>f.summary).sort((f,A)=>Fn(f.appId,A.appId)),y=[...h].sort((f,A)=>Fn(f.relativePath,A.relativePath)||Fn(f.code,A.code)||Fn(f.appId??"",A.appId??""));return Object.freeze({items:Object.freeze(M),diagnostics:Object.freeze(y)})}g();g();g();function ld(e){let n=r=>r.replace(/[.+^${}()|[\]\\]/g,"\\$&"),i=e.split("/").map(r=>r==="**"?".*":r.split("*").map(n).join("[^/]*"));return new RegExp(`^${i.join("\\/")}$`)}function Ze(e,n){try{return ld(n).test(e)}catch{return false}}function zn(e,...n){let t=e.split("/");if(t.length<n.length)return false;let i=t.length-n.length;return n.every((r,o)=>Ze(t[i+o],r))}function ud(e,n){return e.split("/").some(t=>Ze(t,n))}var Qo=[{label:".env*",test:e=>Ze(e,".env*")},{label:".git/",test:(e,n,t)=>t&&e===".git"},{label:"memory/",test:(e,n,t)=>t&&e==="memory"},{label:"*.key",test:e=>Ze(e,"*.key")},{label:"*.pem",test:e=>Ze(e,"*.pem")},{label:"auth.json",test:e=>e==="auth.json"},{label:"node_modules/",test:(e,n,t)=>t&&e==="node_modules"},{label:"conversations/",test:(e,n,t)=>t&&e==="conversations"},{label:".crewx/threads/",test:(e,n,t)=>t&&zn(n,".crewx","threads")},{label:".crewx/crewx.db",test:(e,n,t)=>!t&&zn(n,".crewx","crewx.db")},{label:".crewx/*.log",test:(e,n,t)=>!t&&zn(n,".crewx","*.log")},{label:".crewx/publish/",test:(e,n,t)=>t&&zn(n,".crewx","publish")},{label:".crewx/",test:(e,n)=>ud(n,".crewx")}];function $n(e,n,t){for(let i of Qo)if(i.test(e,n,t))return i.label;return null}function oi(e){let n=[],t=[];function i(r,o,s){let a;try{a=K.readdirSync(r,{withFileTypes:!0});}catch{return}a.sort((d,c)=>d.name.localeCompare(c.name));for(let d of a){let c=o?`${o}/${d.name}`:d.name,p=ne.join(r,d.name);if(d.isSymbolicLink()){let l;try{l=K.statSync(p);}catch{t.push({path:c,rule:"symlink"});continue}if(l.isDirectory()){t.push({path:c,rule:s??"symlink-dir"});continue}let I=s??$n(d.name,c,false);I?t.push({path:c,rule:I}):t.push({path:c,rule:"symlink"});continue}if(d.isDirectory()){let l=s??$n(d.name,c,true);i(p,c,l);continue}if(d.isFile()){let l=s??$n(d.name,c,false);l?t.push({path:c,rule:l}):n.push(c);}}}return i(e,"",null),n.sort(),t.sort((r,o)=>r.path<o.path?-1:r.path>o.path?1:0),{included:n,excluded:t}}g();var fd=[{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 yd(e){return e.includes(0)}function ri(e,n,t){let i=[];for(let r of n){let o=ne.join(e,r),s;try{let d=t?.get(r);s=d===void 0?K.readFileSync(o):Buffer.from(d);}catch{continue}if(yd(s))continue;s.toString("utf8").split(/\r\n|\r|\n/).forEach((d,c)=>{for(let{rule:p,regex:l}of fd)l.test(d)&&i.push({path:r,line:c+1,rule:p});});}return i}g();g();var Se=class extends Error{constructor(t,i){super(`publish: [${t}]${i?` ${i}`:""}`);this.code=t;}code;name="PublishError"};function T(e,n){return new Se(e,n)}var ir=/^[a-z0-9-]+$/,Ad=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/,Id=/^[A-Za-z_][A-Za-z0-9_]*$/;function gd(e){let n=ne.join(e,"crewx.yaml");if(!K.existsSync(n))return {};let t;try{t=or.load(K.readFileSync(n,"utf8"));}catch{return {}}if(!t||typeof t!="object")return {};let i=t.metadata;if(!i||typeof i!="object")return {};let r=i;return {name:typeof r.name=="string"?r.name:void 0,version:typeof r.version=="string"?r.version:void 0,description:typeof r.description=="string"?r.description:void 0,requiredEnv:r.requiredEnv,crewxMinVersion:typeof r.crewxMinVersion=="string"?r.crewxMinVersion:void 0}}function md(e){return si.createHash("sha256").update(e).digest("hex")}function rr(e){let n;try{n=K.lstatSync(e);}catch{throw T("PACKAGE_FILE_INVALID",`file is not readable: ${ne.basename(e)}`)}if(n.isSymbolicLink())throw T("PACKAGE_SYMLINK","symlink content is not publishable");if(!n.isFile())throw T("PACKAGE_FILE_INVALID","only regular files are publishable");return si.createHash("sha256").update(new Uint8Array(K.readFileSync(e))).digest("hex")}function hd(e,n){let t=new TextEncoder().encode(e),i=new TextEncoder().encode(n),r=Math.min(t.byteLength,i.byteLength);for(let o=0;o<r;o+=1){let s=t[o]-i[o];if(s!==0)return s}return t.byteLength-i.byteLength}function sr(e){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||ne.posix.isAbsolute(e)||e.split("/").some(n=>n===".."||n.length===0))throw T("PACKAGE_PATH_TRAVERSAL","manifest file path must be a non-empty POSIX relative path")}function _d(e){if(!/^(?:apps|skills)\/[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(e))throw T("APP_PACKAGE_ROOT_INVALID","packageRoot must be apps/<safe-id> or skills/<safe-id>")}function ar(e){if(!Ad.test(e))throw new Error(`publish: invalid version "${e}" \u2014 must be semver (e.g. 1.0.0)`)}function cr(e,n,t={}){let i=gd(e),r=i.name??ne.basename(e);if(!ir.test(r))throw new Error(`publish: invalid name "${r}" \u2014 must match ${ir} (lowercase letters, numbers, hyphen only)`);let o=t.version??i.version;if(!o)throw new Error("publish: version is required \u2014 set crewx.yaml metadata.version or pass opts.version");ar(o);let s=Array.isArray(i.requiredEnv)?i.requiredEnv:[],a=[];for(let p of s){if(typeof p!="string"||!Id.test(p))throw new Error(`publish: requiredEnv must contain names only (no values), got "${String(p)}"`);a.push(p);}let d=n.map(p=>(sr(p),{path:p,sha256:rr(ne.join(e,p))})).sort((p,l)=>p.path<l.path?-1:p.path>l.path?1:0),c={name:r,version:o,type:"template",description:i.description??"",files:d,requiredEnv:a};return i.crewxMinVersion&&(c.crewxMinVersion=i.crewxMinVersion),c}function Ed(e){let n=e.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"");if(!n)throw T("APP_PACKAGE_ROOT_INVALID","appId cannot produce a marketplace name");return n}function dr(e,n){if(_d(n.packageRoot),!n.version)throw new Error("publish: version is required for App publishing \u2014 pass opts.version");if(ar(n.version),typeof n.description!="string")throw new Error("publish: App description must be a string");let t=[...new Set(n.capabilities)].sort();if(t.length===0||t.some(s=>s!=="screen"&&s!=="skill"))throw new Error("publish: App capabilities must contain screen or skill");let i=`${n.packageRoot}/`;if(t.includes("screen")){if(typeof n.definitionId!="string"||n.definitionId.length===0)throw T("APP_UI_MANIFEST_INVALID","screen App manifests require definitionId");let s=n.includedFiles.includes(`${i}manifest.json`),a=n.includedFiles.includes(`${i}ui-plugin.json`);if(!s&&!a)throw T("APP_UI_MANIFEST_INVALID","screen App is missing manifest.json or ui-plugin.json");if(s&&!a)throw T("APP_UI_MANIFEST_INVALID","a manifest.json App must also ship a generated ui-plugin.json");if(!n.includedFiles.includes(`${i}ui/index.html`))throw T("APP_UI_MANIFEST_INVALID","screen App is missing ui/index.html")}if(t.includes("skill")&&!n.includedFiles.includes(`${i}SKILL.md`))throw T("APP_SKILL_MISSING","skill capability requires package-root SKILL.md");let r=new Set,o=n.includedFiles.map(s=>{if(sr(s),!s.startsWith(i))throw T("PACKAGE_PATH_TRAVERSAL","App manifest file is outside packageRoot");let a=n.generatedFiles?.get(s);return a!==void 0&&r.add(s),{path:s,sha256:a===void 0?rr(ne.join(e,s)):md(a),...a===void 0?{}:{generated:true}}}).sort((s,a)=>hd(s.path,a.path));if(r.size>0&&(r.size!==1||!r.has(`${i}ui-plugin.json`)))throw new Error("publish: only the generated ui-plugin.json may be present in an App package");return {manifestVersion:1,name:Ed(n.appId),version:n.version,type:"app",description:n.description,appId:n.appId,...n.definitionId===void 0?{}:{definitionId:n.definitionId},...n.definitionHash===void 0?{}:{definitionHash:n.definitionHash},capabilities:t,packageRoot:n.packageRoot,files:o,requiredEnv:[]}}g();function pr(e){return si.createHash("sha256").update(e).digest("hex")}function Ar(e,n){if(typeof n!="string"||n.length===0||n.includes("\\")||n.includes("\0")||ne.posix.isAbsolute(n)||n.split("/").some(r=>r===".."||r.length===0))throw T("PACKAGE_PATH_TRAVERSAL","archive paths must be non-empty POSIX relative paths");let t=ne.resolve(e),i=ne.resolve(t,...n.split("/"));if(i!==t&&!i.startsWith(`${t}${ne.sep}`))throw T("PACKAGE_PATH_TRAVERSAL","archive path escaped its root");return i}function lr(e,n){let t=Ar(e,n),i;try{i=K.lstatSync(t);}catch{throw T("PACKAGE_FILE_INVALID","manifest file is missing")}if(i.isSymbolicLink())throw T("PACKAGE_SYMLINK","symlink content is not publishable");if(!i.isFile())throw T("PACKAGE_FILE_INVALID","only regular files are publishable");return new Uint8Array(K.readFileSync(t))}async function Ir(e,n,t={}){let i=ne.join(e,".crewx","publish");K.mkdirSync(i,{recursive:true});let r=ne.join(i,`${n.name}-${n.version}.tgz`),o=ne.join(i,`.${n.name}-${n.version}.${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}.tmp.tgz`),s=K.mkdtempSync(ne.join(ur.tmpdir(),"crewx-publish-"));try{let a=new Set,d=[];for(let c of n.files){if(a.has(c.path))throw T("PACKAGE_PATH_TRAVERSAL","manifest contains duplicate file paths");a.add(c.path);let p=t.generatedFiles?.get(c.path);if(c.generated===!0&&p===void 0)throw T("PACKAGE_GENERATED_FILE_MISSING","generated manifest file bytes are missing");if(t.sourceFileHashes?.has(c.path)){let _=lr(e,c.path);if(t.sourceFileHashes.get(c.path)!==pr(_))throw T("PACKAGE_STAGED_BYTES_MISMATCH","workspace source changed before staging")}let l=p??lr(e,c.path);if(pr(l)!==c.sha256)throw T("PACKAGE_STAGED_BYTES_MISMATCH",`staged bytes differ for ${c.path}`);let I=Ar(s,c.path);K.mkdirSync(ne.dirname(I),{recursive:!0}),K.writeFileSync(I,new Uint8Array(l)),d.push(c.path);}K.writeFileSync(ne.join(s,"manifest.json"),JSON.stringify(n,null,2)),await yr.create({gzip:!0,file:o,cwd:s,portable:!0,noMtime:!0},["manifest.json",...d]),K.renameSync(o,r);}finally{try{K.rmSync(o,{force:!0});}catch{}K.rmSync(s,{recursive:true,force:true});}return r}g();g();var Qe="/api/v1";var Dd=201,bd=200,Nd=409,ai=401,gr={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 Sd(){return process.env.WI013_FAKE_UPLOAD==="1"}function Md(e){let n=gunzipSync(new Uint8Array(e)),t=gzipSync(new Uint8Array(n),{level:1});if(Buffer.compare(new Uint8Array(t),new Uint8Array(e))===0)throw new Error("publish: [E_MALFORMED] Re-gzipped upload bytes are identical to the original \u2014 tamper is a no-op");return t}function Ld(e){return e.replace(/\/+$/,"")}async function gn(e){try{return await e.json()}catch{return null}}function mr(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 Od(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 Rd(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 hr(e,n){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e,i=t.data&&typeof t.data=="object"&&!Array.isArray(t.data)?t.data:void 0,r=[t.code,t.message,i?.code,i?.message];for(let o of r){if(typeof o!="string"||!Object.prototype.hasOwnProperty.call(gr,o))continue;let s=o,a=s==="APP_NAME_CONFLICT"?`marketplace name is already in use: ${n}`:void 0;return T(gr[s],a)}}async function wd(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=Ld(e.baseUrl),t=e.accessPolicy??"private",i=e.manifest.name,r=e.manifest.type==="app"?e.manifest:void 0,o=r!==void 0,s=r?.appId,a;try{a=await fetch(`${n}${Qe}/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 gn(a),c=Od(d),p=Rd(d),l=o&&p!==void 0?p:i,I;if(a.status===Dd)I="created";else if(o&&a.status===bd){if(c===void 0)throw T("PUBLISH_CONTENT_ID_MISSING","App republish did not return an opaque contentId");I="existing";}else if(a.status===Nd){if(o)throw hr(d,i)??T("APP_NAME_CONFLICT",`marketplace name is already in use: ${i}`);I="existing";}else throw a.status===ai?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",E=null;if(I==="existing"&&!o){let N;try{N=await fetch(`${n}${Qe}/publisher/items`,{method:"GET",headers:{Authorization:`Bearer ${e.accessToken}`}});}catch{throw new Error("publish: [E_NETWORK] Publisher items request failed (network)")}let M=await gn(N);if(N.status!==200)throw new Error(`publish: [E_HTTP] Publisher items request failed \u2014 HTTP ${N.status}`);let f=mr(M,"publisher items",N.status)?.items;if(!Array.isArray(f))throw new Error(`publish: [E_MALFORMED] Publisher items response is malformed (expected data.items[]) \u2014 HTTP ${N.status}`);let A=f.find(D=>!D||typeof D!="object"?false:D.slug===i);if(!A||typeof A.version!="string")throw new Error(`publish: [E_MALFORMED] Publisher items response does not contain slug "${i}" \u2014 HTTP ${N.status}`);if(E=A.version,E!==e.manifest.version){let D;try{D=await fetch(`${n}${Qe}/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(!D.ok)throw await gn(D),D.status===ai?new Error(`publish: [E_AUTH_EXPIRED] Authentication is expired or missing \u2014 please log in again (HTTP ${D.status})`):D.status===403?new Error(`publish: [E_FORBIDDEN] Version update is forbidden; only the item owner can update an existing item (HTTP ${D.status})`):new Error(`publish: [E_HTTP] Version update failed \u2014 HTTP ${D.status}`);_="applied";}}let L=K.readFileSync(e.tgzPath),b=Sd()?Md(L):L,j=new FormData;j.set("archive",new Blob([new Uint8Array(b)],{type:"application/gzip"}),`${l}-${e.manifest.version}.tgz`);let C=o&&c!==void 0?c:i,k;try{k=await fetch(`${n}${Qe}/publisher/items/${encodeURIComponent(C)}/upload`,{method:"POST",headers:{Authorization:`Bearer ${e.accessToken}`},body:j});}catch{throw new Error("publish: [E_NETWORK] Upload request failed (network)")}if(k.status===ai)throw new Error("publish: [E_AUTH_EXPIRED] Authentication is expired or missing \u2014 please log in again (HTTP 401)");if(!k.ok){let N=await gn(k);if(o){let M=hr(N,l);if(M)throw M}throw new Error(`publish: [E_HTTP] Upload request failed \u2014 HTTP ${k.status}`)}let B=await gn(k),h=mr(B,"upload",k.status),m=typeof h.contentId=="string"&&h.contentId.length>0?h.contentId:c;if(o&&m===void 0)throw T("PUBLISH_CONTENT_ID_MISSING","App upload did not return an opaque contentId");return {slug:l,version:e.manifest.version,...m===void 0?{}:{contentId:m},artifactChecksum:h.artifactChecksum,artifactSizeBytes:h.artifactSizeBytes,submitOutcome:I,versionUpdate:_,serverVersionBefore:E}}var Ud=1e4,Cd=100*1024*1024;function ci(e){return si.createHash("sha256").update(e).digest("hex")}function kd(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function Wn(e,n){if(!n||n.includes("\\")||n.includes("\0")||ne.posix.isAbsolute(n)||n.split("/").some(o=>o===".."||o.length===0))throw T("PACKAGE_PATH_TRAVERSAL","workspace file path is not a safe relative path");let t=ne.resolve(e,...n.split("/")),i=ne.resolve(e);if(t!==i&&!t.startsWith(`${i}${ne.sep}`))throw T("PACKAGE_PATH_TRAVERSAL","workspace file path escaped the workspace root");let r;try{r=K.lstatSync(t);}catch{throw T("PACKAGE_FILE_INVALID",`workspace file is missing: ${n}`)}if(r.isSymbolicLink())throw T("PACKAGE_SYMLINK",`symlink is not publishable: ${n}`);if(!r.isFile())throw T("PACKAGE_FILE_INVALID",`not a regular file: ${n}`);return new Uint8Array(K.readFileSync(t))}function Jn(e,n){return e===n||e.startsWith(`${n}/`)}function xd(e,n){return e.path<n.path?-1:e.path>n.path?1:e.rule.localeCompare(n.rule)}function Er(e,n,t){let i=e??n;if(!Number.isSafeInteger(i)||i<=0)throw new Se("PACKAGE_SIZE_LIMIT",`${t} must be a positive integer`);return i}function Pr(e,n,t,i){let r=Er(t.maxFileCount??t.maxFiles,Ud,"max file count"),o=Er(t.maxTotalBytes??t.maxBytes,Cd,"max total bytes");if(n.length>r)throw new Se("PACKAGE_SIZE_LIMIT",`package exceeds file count limit (${r})`);let s=0;for(let a of n){let d=i?.get(a);if(d!==void 0?s+=d.byteLength:s+=Wn(e,a).byteLength,s>o)throw new Se("PACKAGE_SIZE_LIMIT",`package exceeds byte limit (${o})`)}}function vd(e){return e.appId!==void 0||e.expectedDefinitionHash!==void 0}function jd(e){let n=e.appId!==void 0,t=e.expectedDefinitionHash!==void 0;if(!n&&t)throw T("APP_ID_REQUIRED","appId is required with expectedDefinitionHash");if(n&&!t)throw T("APP_DEFINITION_HASH_REQUIRED","expectedDefinitionHash is required with appId");if(!n||!t)throw T("APP_ID_REQUIRED")}function Vd(e,n){let t=e.filter(i=>i.appId===n);if(t.length===0)throw T("APP_NOT_FOUND",`no publishable App matches ${n}`);if(t.length!==1)throw T("APP_AMBIGUOUS",`more than one App matches ${n}`);return t[0]}function Fd(e){let n=e.localDefinitionRef?.packageRoot;if(!n||!/^(?:apps|skills)\/[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(n))throw T("APP_PACKAGE_ROOT_INVALID","selected App is not rooted in apps/<safe-id> or skills/<safe-id>");return n}function Bd(e,n){let t=[];for(let i of e.excluded)t.push(Jn(i.path,n)?i:{path:i.path,rule:"out-of-app-scope"});for(let i of e.included)Jn(i,n)||t.push({path:i,rule:"out-of-app-scope"});return t.sort(xd)}function Hd(e){let{path:n,rule:t}=e.reason;return `${e.code} at ${n===""?"<file>":n} (${t})`+(e.files.length>0?` [${e.files.join(", ")}]`:"")}function zd(e,n,t,i){let r={};for(let l of ee){let I=`${t}/${l}`;i.includes(I)&&(r[l]=Wn(e,I));}if(Object.keys(r).length===0)throw T("APP_UI_MANIFEST_INVALID","selected screen App has no package manifest.json or ui-plugin.json");let o=sn(r,{mode:"local"});if(!o.ok)throw T("APP_UI_MANIFEST_INVALID",Hd(o.rejection));if(o.manifest.pluginId!==n.appId)throw T("APP_DEFINITION_CONFLICT",`${o.file} identity no longer matches the selected App`);let s=r[Ie],a=s===void 0?void 0:ci(s),d=`${t}/ui/index.html`;if(!i.includes(d))throw T("APP_UI_MANIFEST_INVALID","screen entry is outside package scope");let c=ci(Wn(e,d)),p=JSON.parse(JSON.stringify(o.v2Input));if(p.entryHash=c,Object.prototype.hasOwnProperty.call(p,"initialState")){let l=p.initialState;if(!kd(l)||l.path!=="ui/state.json")throw T("APP_INITIAL_STATE_OUT_OF_SCOPE","initialState must reference ui/state.json inside the package");let I=`${t}/ui/state.json`;if(!i.includes(I))throw T("APP_INITIAL_STATE_OUT_OF_SCOPE","initialState reference is outside the selected package");let _=Wn(e,I);p.initialState={...l,hash:ci(_)};}try{let l=xe(p,{mode:"published"});return {bytes:new Uint8Array(Buffer.from(Qn(l),"utf8")),...a===void 0?{}:{legacySourceHash:a}}}catch(l){throw l instanceof Z?T("APP_UI_MANIFEST_INVALID",l.code):T("APP_UI_MANIFEST_INVALID")}}async function $d(e,n){let{included:t,excluded:i}=oi(e);Pr(e,t,n);let r=cr(e,t,{version:n.version}),o=ri(e,t);return {plan:{manifest:r,included:t,excluded:i,secretFindings:o},archiveOptions:{}}}async function Gd(e,n){jd(n);let t=await Zo(e),i=Vd(t.items,n.appId);if(i.definitionHash!==n.expectedDefinitionHash)throw T("APP_DEFINITION_CONFLICT",`definitionHash changed for ${n.appId}`);let r=Fd(i),o=oi(e);if(o.excluded.some(_=>Jn(_.path,r)&&(_.rule==="symlink"||_.rule==="symlink-dir")))throw T("PACKAGE_SYMLINK","selected App package contains a symlink");let s=o.included.filter(_=>Jn(_,r)),a=Bd(o,r),d=new Map,c=new Map;if(i.capabilities.includes("screen")){let _=zd(e,i,r,s),E=`${r}/${Ie}`;d.set(E,_.bytes),_.legacySourceHash!==void 0?c.set(E,_.legacySourceHash):(s.push(E),s.sort());}if(i.capabilities.includes("skill")&&!s.includes(`${r}/SKILL.md`))throw T("APP_SKILL_MISSING","skill capability requires package-root SKILL.md");Pr(e,s,n,d);let p={appId:i.appId,version:n.version??"",description:i.description,capabilities:i.capabilities,packageRoot:r,...i.definition?.id===void 0?{}:{definitionId:i.definition.id},definitionHash:i.definitionHash,includedFiles:s,generatedFiles:d},l=dr(e,p),I=ri(e,s,d);return {plan:{manifest:l,included:s,excluded:a,secretFindings:I},archiveOptions:{generatedFiles:d,sourceFileHashes:c}}}async function Dr(e,n){let t=ne.resolve(e);if(vd(n))return Gd(t,n);if(n.expectedDefinitionHash!==void 0)throw T("APP_ID_REQUIRED");return $d(t,n)}async function Sf(e,n={}){return (await Dr(e,n)).plan}function Wd(e){let n=e.map(t=>`${t.path}:${t.line} (${t.rule})`).join(", ");throw new Se("PUBLISH_SECRET_FINDINGS",`aborted \u2014 secret findings must be resolved before packing: ${n}`)}async function br(e,n={}){let t=ne.resolve(e),i=await Dr(t,n);i.plan.secretFindings.length>0&&Wd(i.plan.secretFindings);let r=await Ir(t,i.plan.manifest,i.archiveOptions);return {manifest:i.plan.manifest,tgzPath:r}}async function Mf(e,n={}){return br(e,n)}async function Lf(e,n){let t=await br(e,n);if(t.manifest.type!=="app")throw new Error("publish: App pack unexpectedly produced a template manifest");return t}
|
|
2
|
+
export{Cd as DEFAULT_PUBLISH_MAX_BYTES,Ud as DEFAULT_PUBLISH_MAX_FILES,Qo as EXCLUDE_RULES,Qe as MARKETPLACE_API_PREFIX,Se as PublishError,Lf as packApp,br as packPublish,Mf as packTemplate,Sf as planPublish,wd as uploadToMarketplace};
|