@crewx/sdk 0.9.0-rc.124 → 0.9.0-rc.126

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