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