@crewx/sdk 0.9.0-rc.115 → 0.9.0-rc.116
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/config/models.generated.d.ts +2 -2
- package/dist/config/pricing.generated.d.ts +2 -2
- package/dist/esm/index.js +241 -241
- package/dist/esm/plugins/index.js +36 -36
- package/dist/esm/publish/index.js +2 -2
- package/dist/esm/repository/index.js +3 -3
- package/dist/esm/testing/index.js +1 -1
- package/dist/index.browser.d.ts +2 -1
- package/dist/index.browser.js +4 -4
- package/dist/index.d.ts +2 -2
- package/dist/index.js +240 -240
- package/dist/lifecycle/update-admission.d.ts +1 -0
- package/dist/mcp-app/discovery.d.ts +3 -0
- package/dist/mcp-app/index.d.ts +1 -1
- package/dist/mcp-app/types.d.ts +1 -1
- package/dist/mcp-app/workspace-snapshot.d.ts +6 -1
- package/dist/plugins/index.js +35 -35
- package/dist/publish/index.js +2 -2
- package/dist/repository/index.js +3 -3
- package/dist/testing/index.js +1 -1
- package/package.json +1 -1
package/dist/publish/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var Mt=require('crypto'),L=require('fs'),w=require('path'),Cn=require('js-yaml'),promises=require('fs/promises'),zn=require('os'),$n=require('tar'),zlib=require('zlib');function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var Mt__namespace=/*#__PURE__*/_interopNamespace(Mt);var L__namespace=/*#__PURE__*/_interopNamespace(L);var w__namespace=/*#__PURE__*/_interopNamespace(w);var Cn__namespace=/*#__PURE__*/_interopNamespace(Cn);var zn__namespace=/*#__PURE__*/_interopNamespace(zn);var $n__namespace=/*#__PURE__*/_interopNamespace($n);var D=class extends Error{constructor(n,i=n,o){super(i);this.code=n;this.currentRevision=o;}code;currentRevision;name="UiRuntimeError"};var ri=/(?:proof|token|secret|password|cookie|authorization|private[_-]?key|stack|exception|plugin[_-]?text)/i,oi=/(?:url|uri|endpoint|path|file(?:name|path)?|cwd|shell|directory|dir|folder)$/i,si=/<\/?[A-Za-z][^>]*>/,ai=/^(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)/,ci=/^(?:https?|file|ftp|ws|wss):\/\//i;function H(){throw new D("INPUT_INVALID","JSON value is not projection-safe")}function pi(e){let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}var li=8,di=4;function Ge(e,t,n,i,o){if(t>i&&H(),e===null||typeof e=="string"||typeof e=="boolean")return typeof e=="string"&&(si.test(e)||ci.test(e)||ai.test(e))&&H(),e;if(typeof e=="number")return Number.isFinite(e)||H(),e;(typeof e!="object"||e===void 0||typeof e=="function"||typeof e=="bigint")&&H();let r=e;n.has(r)&&H(),n.add(r);try{if(Array.isArray(e))return e.map(a=>Ge(a,t+1,n,i));pi(r)||H();let s={};for(let[a,p]of Object.entries(e))(ri.test(a)||oi.test(a))&&H(),s[a]=Ge(p,t+1,n,i,a);return s}finally{n.delete(r);}}function ie(e,t=0){(!Number.isInteger(t)||t<0||t>di)&&H();let n=Ge(e,0,new Set,li+t);return (n===null||Array.isArray(n)||typeof n!="object")&&H(),n}function We(e){try{let t=JSON.stringify(e);return t===void 0&&H(),t}catch{H();}}function $e(e){return Array.isArray(e)?e.map($e):e!==null&&typeof e=="object"?Object.fromEntries(Object.keys(e).sort().map(t=>[t,$e(e[t])])):e}function Z(e){return We($e(e))}function Ke(e){return Z(e)}var Y="window";var Rt=["__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"],ui=new Set(Rt),fi=/(?: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 re(e){return ui.has(e)||fi.test(e)||yi.test(e)}var Ee=/^[A-Za-z0-9_]+$/,de=/^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)*$/,oe=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,Je=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/,Xe=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,Ye=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/,qe=["blue","violet","emerald","amber","rose","sky","slate","indigo"],Ze=["inline","panel"];var Ai=1,Ii=/^[a-z][a-zA-Z0-9]*(\.[a-zA-Z0-9]+)+$/,gi=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,Ht=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,mi=/<\/?[A-Za-z][^>]*>/,hi=/^(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)/,_i=/^(?:https?|file|ftp|ws|wss):\/\//i,Ei=/^\s*(?:javascript|data):/i,Ot=/data:[^,\s]*,/i,Ti=/(?:https?|file|ftp|ws|wss):\/\//i,Pi=/javascript:/i,Di=/(?:^[\s]*|[\s"'(=])(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)(?=[^\s"'<>])[^\s"'<>]*/,Ni=["manifestVersion","pluginId","definitionId","version","primitiveSet","activation","schema","layout"],bi=["manifestVersion","pluginId","definitionId","version","name","description","entry","surfaces","size","stateProjection","actions"],Mi=["icon","tone","entryHash","initialState","usage","detailPanel","displayModes"],Si=["actionId","capability","mutation","inputSchema","resultProjection","backend"],Li=["confirmation"],Ui=["type","handler"],Ri=["type","command"],Oi=["path"],wi=["hash"],xi=/^[0-9a-f]{64}$/,Ci=/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/,ki=/[\r\n]/,Vi=["card-shell","meta-banner","heading","labeled-text","step-flow","text-list"],V=class extends Error{constructor(n,i=n){super(i);this.code=n;}code;name="UiPluginValidationError"};function c(e,t=e){throw new V(e,t)}function b(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;try{let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}catch{return false}}function T(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function N(e,t,n=[]){let i=new Set([...t,...n]);Object.keys(e).some(o=>!i.has(o))&&c("MANIFEST_INVALID"),t.some(o=>!T(e,o))&&c("MANIFEST_INVALID");}function be(e,t=false,n=false){return mi.test(e)||_i.test(e)||hi.test(e)||n&&Ot.test(e)||Ei.test(e)&&!(t&&/^\s*data:/i.test(e)&&!Ot.test(e))}function De(e,t=new Set,n=0,i=false,o=false){if(typeof e=="string"){be(e,i,o)&&c("UNSAFE_VALUE");return}if(!(e===null||typeof e!="object")){(n>8||t.has(e))&&c("MANIFEST_INVALID"),t.add(e);try{if(Array.isArray(e)){for(let r of e)De(r,t,n+1);return}b(e)||c("MANIFEST_INVALID");for(let[r,s]of Object.entries(e))De(s,t,n+1,i&&n===0&&(r==="name"||r==="description"),o);}finally{t.delete(e);}}}function G(e,t){let n=e[t];return typeof n!="string"&&c("MANIFEST_INVALID"),n}function B(e,t,n){let i=e[t];return (!Number.isSafeInteger(i)||i<n)&&c("MANIFEST_INVALID"),i}function Qe(e){return gi.test(e)||c("MANIFEST_INVALID"),e}function se(e){return Ii.test(e)||c("TOKEN_INVALID"),e}function Fi(e){return Ht.test(e)||c("MANIFEST_INVALID"),e}function vi(e){b(e)||c("MANIFEST_INVALID");let t={};for(let[n,i]of Object.entries(e)){let o=Fi(n);b(i)||c("MANIFEST_INVALID");let r=i.type;if(r==="text"){N(i,["type","maxLength"]),t[o]={type:r,maxLength:B(i,"maxLength",1)};continue}if(r==="text-list"){N(i,["type","max","itemMaxLength"]),t[o]={type:r,max:B(i,"max",0),itemMaxLength:B(i,"itemMaxLength",1)};continue}if(r==="step-list"){N(i,["type","min","max","labelMaxLength","detailMaxLength"]);let s=B(i,"min",0),a=B(i,"max",1);s>a&&c("MANIFEST_INVALID"),t[o]={type:r,min:s,max:a,labelMaxLength:B(i,"labelMaxLength",1),detailMaxLength:B(i,"detailMaxLength",1)};continue}typeof r=="string"&&c("SCHEMA_TYPE_UNSUPPORTED"),c("MANIFEST_INVALID");}return t}function ji(e,t,n){let i=e[t];(!i||i.type!==n)&&c("MANIFEST_INVALID");}function Te(e,t,n){let i=G(e,"field");return Ht.test(i)||c("MANIFEST_INVALID"),ji(t,i,n),i}function Hi(e,t){b(e)||c("MANIFEST_INVALID");let n=e.primitive;switch(typeof n!="string"&&c("MANIFEST_INVALID"),Vi.includes(n)||c("PRIMITIVE_UNKNOWN"),n){case "card-shell":return N(e,["primitive"]),{primitive:n};case "meta-banner":return N(e,["primitive","badgeToken","noticeToken"]),{primitive:n,badgeToken:se(G(e,"badgeToken")),noticeToken:se(G(e,"noticeToken"))};case "heading":return N(e,["primitive","field"]),{primitive:n,field:Te(e,t,"text")};case "labeled-text":return N(e,["primitive","titleToken","field","variant"]),e.variant!=="callout"&&c("MANIFEST_INVALID"),{primitive:n,titleToken:se(G(e,"titleToken")),field:Te(e,t,"text"),variant:"callout"};case "step-flow":return N(e,["primitive","titleToken","field"]),{primitive:n,titleToken:se(G(e,"titleToken")),field:Te(e,t,"step-list")};case "text-list":{N(e,["primitive","titleToken","field"],["emptyToken","hideWhenEmpty"]);let i={primitive:n,titleToken:se(G(e,"titleToken")),field:Te(e,t,"text-list")};return T(e,"emptyToken")&&(i.emptyToken=se(G(e,"emptyToken"))),T(e,"hideWhenEmpty")&&(typeof e.hideWhenEmpty!="boolean"&&c("MANIFEST_INVALID"),i.hideWhenEmpty=e.hideWhenEmpty),i}}return c("MANIFEST_INVALID")}function Bi(e,t){return Array.isArray(e)||c("MANIFEST_INVALID"),e.map(n=>Hi(n,t))}function S(e="v2 manifest exceeds a contract limit"){return c("LIMIT_EXCEEDED",e)}function F(e="initial state is not projection-safe"){return c("INITIAL_STATE_INVALID",e)}function wt(e,t){return (typeof e!="string"||e.length===0||e.length>4096||e.trim().length===0||Ci.test(e)||ki.test(e))&&c("MANIFEST_INVALID",`${t} is invalid`),(be(e,true,true)||Ti.test(e)||Pi.test(e)||Di.test(e))&&c("UNSAFE_VALUE",`${t} contains an unsafe value`),e}function et(e,t){return (typeof e!="string"||!oe.test(e))&&c("MANIFEST_INVALID",`${t} is invalid`),e}function zi(e){return (typeof e!="string"||!Je.test(e)||e==="*"||e==="all")&&c("MANIFEST_INVALID","action capability is invalid"),e}function Bt(e){return (typeof e!="string"||!xi.test(e))&&c("MANIFEST_INVALID","resource hash is invalid"),e}function tt(e,t=new Set,n=0){if(typeof e=="string"){e.length>4096&&S("v2 manifest string is too long");return}if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){Number.isFinite(e)||c("MANIFEST_INVALID","v2 manifest contains a non-finite number");return}(e===void 0||typeof e=="function"||typeof e=="bigint")&&c("MANIFEST_INVALID","v2 manifest contains a non-JSON value"),typeof e!="object"&&c("MANIFEST_INVALID"),n>8&&S("v2 manifest nesting is too deep"),t.has(e)&&c("MANIFEST_INVALID","v2 manifest contains a cycle"),t.add(e);try{if(Array.isArray(e)){e.length>128&&S("v2 manifest array is too long");for(let i of e)tt(i,t,n+1);return}b(e)||c("MANIFEST_INVALID","v2 manifest contains a non-plain object");for(let i of Object.values(e))tt(i,t,n+1);}finally{t.delete(e);}}}function Gi(e){return (typeof e!="string"||e.length>4096||!de.test(e))&&(typeof e=="string"&&e.length>4096&&S("projection path is too long"),c("MANIFEST_INVALID","projection paths must be canonical exact paths")),e.split(".").some(n=>re(n))&&c("MANIFEST_INVALID","projection paths cannot address reserved state keys"),e}function zt(e){b(e)||c("MANIFEST_INVALID","projection policy must be an object"),N(e,["allow"]),Array.isArray(e.allow)||c("MANIFEST_INVALID","projection allow must be an array"),e.allow.length>128&&S("projection allowlist is too long");let t=[],n=new Set;for(let i of e.allow){let o=Gi(i);n.has(o)&&c("MANIFEST_INVALID","projection allowlist contains a duplicate path"),n.add(o),t.push(o);}return {allow:t}}function ae(e,t,n=Number.MAX_SAFE_INTEGER){return (!Number.isSafeInteger(e)||e<0||e>n)&&c("MANIFEST_INVALID",`${t} is invalid`),e}function xt(e,t){return (typeof e!="number"||!Number.isFinite(e))&&c("MANIFEST_INVALID",`${t} is invalid`),e}function nt(e,t=0,n=new Set){if(typeof e=="string")return (e.length>4096||be(e))&&c("UNSAFE_VALUE","schema enum contains an unsafe string"),e;if(e===null||typeof e=="boolean")return e;if(typeof e=="number")return Number.isFinite(e)||c("MANIFEST_INVALID","schema enum contains a non-finite number"),e;(t>8||typeof e!="object"||e===void 0)&&S("schema enum is too deep"),n.has(e)&&c("MANIFEST_INVALID","schema enum contains a cycle"),n.add(e);try{if(Array.isArray(e))return e.length>128&&S("schema enum array is too long"),e.map(o=>nt(o,t+1,n));b(e)||c("MANIFEST_INVALID","schema enum contains a non-plain object");let i={};for(let[o,r]of Object.entries(e))re(o)&&c("MANIFEST_INVALID","schema enum contains a reserved key"),i[o]=nt(r,t+1,n);return i}finally{n.delete(e);}}function $i(e,t){if(e===void 0)return;Array.isArray(e)||c("MANIFEST_INVALID","schema required must be an array"),e.length>64&&S("schema required list is too long");let n=[],i=new Set;for(let o of e)(typeof o!="string"||!de.test(o))&&c("MANIFEST_INVALID","schema required contains an invalid key"),o.length>4096&&S("schema required key is too long"),i.has(o)&&c("MANIFEST_INVALID","schema required contains a duplicate key"),t&&!Object.prototype.hasOwnProperty.call(t,o)&&c("MANIFEST_INVALID","schema required references an undeclared property"),i.add(o),n.push(o);return n}function Wi(e,t){let n=t?de:Ee;return e.length>4096&&S("schema property name is too long"),(!n.test(e)||e.split(".").some(i=>re(i)))&&c("MANIFEST_INVALID","schema property name is invalid"),e}function it(e,t=0,n=false){b(e)||c("MANIFEST_INVALID","action inputSchema must be an object"),t>8&&S("action inputSchema is too deep");let i=e.type;i!=="object"&&i!=="string"&&i!=="number"&&i!=="integer"&&i!=="boolean"&&i!=="array"&&i!=="null"&&(typeof i=="string"&&c("SCHEMA_TYPE_UNSUPPORTED","action inputSchema type is unsupported"),c("MANIFEST_INVALID","action inputSchema type is required"));let o=["type","enum"];i==="string"&&o.push("minLength","maxLength"),i==="array"&&o.push("minItems","maxItems","items"),i==="object"&&o.push("minProperties","maxProperties","properties","required","additionalProperties"),(i==="number"||i==="integer")&&o.push("minimum","maximum"),N(e,["type"],o.filter(a=>a!=="type"));let r={type:i};if(T(e,"enum")&&(Array.isArray(e.enum)||c("MANIFEST_INVALID","schema enum must be an array"),e.enum.length>128&&S("schema enum is too long"),r.enum=e.enum.map(a=>nt(a))),i==="string"&&(T(e,"minLength")&&(r.minLength=ae(e.minLength,"schema minLength",4096)),T(e,"maxLength")&&(r.maxLength=ae(e.maxLength,"schema maxLength",4096)),r.minLength!==void 0&&r.maxLength!==void 0&&r.minLength>r.maxLength&&c("MANIFEST_INVALID","schema string length bounds are inverted")),(i==="number"||i==="integer")&&(T(e,"minimum")&&(r.minimum=xt(e.minimum,"schema minimum")),T(e,"maximum")&&(r.maximum=xt(e.maximum,"schema maximum")),r.minimum!==void 0&&r.maximum!==void 0&&r.minimum>r.maximum&&c("MANIFEST_INVALID","schema numeric bounds are inverted")),i==="array"&&(T(e,"minItems")&&(r.minItems=ae(e.minItems,"schema minItems",128)),T(e,"maxItems")&&(r.maxItems=ae(e.maxItems,"schema maxItems",128)),r.minItems!==void 0&&r.maxItems!==void 0&&r.minItems>r.maxItems&&c("MANIFEST_INVALID","schema array length bounds are inverted"),T(e,"items")&&(r.items=it(e.items,t+1,false))),i==="object"){let a;if(T(e,"properties")){b(e.properties)||c("MANIFEST_INVALID","schema properties must be an object");let l=Object.entries(e.properties);l.length>64&&S("schema properties are too many"),a={};for(let[y,u]of l){let d=Wi(y,n);a[d]=it(u,t+1,false);}r.properties=a;}T(e,"minProperties")&&(r.minProperties=ae(e.minProperties,"schema minProperties",64)),T(e,"maxProperties")&&(r.maxProperties=ae(e.maxProperties,"schema maxProperties",64)),r.minProperties!==void 0&&r.maxProperties!==void 0&&r.minProperties>r.maxProperties&&c("MANIFEST_INVALID","schema object property bounds are inverted");let p=$i(e.required,a);p!==void 0&&(r.required=p),T(e,"additionalProperties")&&(e.additionalProperties!==false&&c("MANIFEST_INVALID","schema additionalProperties must be false"),r.additionalProperties=false);}let s=JSON.stringify(r);return (s===void 0||Buffer.byteLength(s,"utf8")>65536)&&S("action inputSchema subtree is too large"),r}function Ki(e){let t=it(e,0,true);return (t.type!=="object"||!t.properties)&&c("MANIFEST_INVALID","action inputSchema must declare object properties"),t}function Ji(e){if(b(e)||c("MANIFEST_INVALID","action backend must be an object"),e.type==="core"){N(e,Ui);let t=e.handler;return (typeof t!="string"||!Xe.test(t))&&c("MANIFEST_INVALID","core backend handler is invalid"),{type:"core",handler:t}}if(e.type==="skill"){N(e,Ri),(!Array.isArray(e.command)||e.command.length===0||e.command.length>16)&&c("MANIFEST_INVALID","skill backend command is invalid");let t=[];for(let n of e.command)(typeof n!="string"||n.length===0||n.length>256||!Ye.test(n))&&c("MANIFEST_INVALID","skill backend command token is invalid"),t.push(n);return {type:"skill",command:t}}c("MANIFEST_INVALID","action backend type is unsupported");}function Xi(e){b(e)||c("MANIFEST_INVALID","action must be an object"),N(e,Si,Li);let t=et(e.actionId,"actionId"),n=zi(e.capability),i=e.mutation;typeof i!="boolean"&&c("MANIFEST_INVALID","action mutation must be boolean");let o=Ki(e.inputSchema),r=zt(e.resultProjection),s=Ji(e.backend),a;if(T(e,"confirmation")){let p=e.confirmation;p!=="none"&&p!=="native"&&c("MANIFEST_INVALID","action confirmation is invalid"),a=p;}return a==="none"&&(s.type!=="core"||s.handler!=="sqlite.browse"||n!=="sqlite.read"||i!==true)&&c("MANIFEST_INVALID","none confirmation is only allowed for sqlite.browse read mutations"),{actionId:t,capability:n,mutation:i,inputSchema:o,resultProjection:r,backend:s,...a===void 0?{}:{confirmation:a}}}function Yi(e){return b(e)||c("INITIAL_STATE_INVALID","initialState must be an object"),N(e,Oi,wi),e.path!=="ui/state.json"&&c("MANIFEST_INVALID","initialState path is not fixed"),T(e,"hash")?{path:"ui/state.json",hash:Bt(e.hash)}:{path:"ui/state.json"}}function qi(e,t){De(e,new Set,0,true,true),tt(e),b(e)||c("MANIFEST_INVALID"),N(e,bi,Mi),e.manifestVersion!==2&&c("MANIFEST_INVALID");let n=et(e.pluginId,"pluginId"),i=et(e.definitionId,"definitionId"),o=B(e,"version",1),r=wt(e.name,"name"),s=wt(e.description,"description"),a;T(e,"icon")&&((typeof e.icon!="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(e.icon))&&c("MANIFEST_INVALID","icon is invalid"),a=e.icon);let p;T(e,"tone")&&((typeof e.tone!="string"||!qe.includes(e.tone))&&c("MANIFEST_INVALID","tone is invalid"),p=e.tone),e.entry!=="ui/index.html"&&c("MANIFEST_INVALID","entry path is not fixed");let l;T(e,"entryHash")&&(l=Bt(e.entryHash));let y;T(e,"initialState")&&(y=Yi(e.initialState));let u;T(e,"usage")&&(e.usage!=="card"&&e.usage!=="window"&&c("MANIFEST_INVALID","usage is invalid"),u=e.usage);let d;T(e,"detailPanel")&&(typeof e.detailPanel!="boolean"&&c("MANIFEST_INVALID","detailPanel is invalid"),d=e.detailPanel);let A;if(T(e,"displayModes")){((u??Y)!==Y||!Array.isArray(e.displayModes)||e.displayModes.length===0)&&c("MANIFEST_INVALID","displayModes are only valid for window Apps");let M=new Set(["inline","floating","focused"]);(new Set(e.displayModes).size!==e.displayModes.length||e.displayModes.some(U=>typeof U!="string"||!M.has(U)))&&c("MANIFEST_INVALID","displayModes are invalid"),A=e.displayModes;}(u??Y)===Y&&d!==void 0&&c("MANIFEST_INVALID","detailPanel is card-only");let g=t.mode??"local";g!=="local"&&g!=="installed"&&g!=="published"&&c("MANIFEST_INVALID","manifest mode is invalid"),g!=="local"&&l===void 0&&c("MANIFEST_INVALID","installed manifests require entryHash"),g!=="local"&&y!==void 0&&y.hash===void 0&&c("MANIFEST_INVALID","installed manifests require initialState.hash"),(!Array.isArray(e.surfaces)||e.surfaces.length===0)&&c("MANIFEST_INVALID","surfaces are invalid"),e.surfaces.length>2&&S("surfaces exceed the v2 limit");let O=[],v=new Set;for(let M of e.surfaces)(typeof M!="string"||!Ze.includes(M))&&c("MANIFEST_INVALID","surface is unsupported"),v.has(M)&&c("MANIFEST_INVALID","surfaces contain a duplicate"),v.add(M),O.push(M);b(e.size)||c("MANIFEST_INVALID","size must be an object"),N(e.size,["height"]);let z=B(e.size,"height",1);z>720&&S("size.height exceeds the v2 limit");let m=zt(e.stateProjection);Array.isArray(e.actions)||c("MANIFEST_INVALID","actions must be an array"),e.actions.length>32&&S("actions exceed the v2 limit");let I=[],j=new Set;for(let M of e.actions){let U=Xi(M);if(j.has(U.actionId)&&c("MANIFEST_INVALID","actions contain a duplicate actionId"),U.backend.type==="core"&&U.backend.handler==="state.set"){U.mutation||c("MANIFEST_INVALID","state.set actions must be mutations");for(let x of Object.keys(U.inputSchema.properties))m.allow.includes(x)||c("MANIFEST_INVALID","state.set input paths must be projection-allowed");}j.add(U.actionId),I.push(U);}return {manifestVersion:2,pluginId:n,definitionId:i,version:o,name:r,description:s,...a===void 0?{}:{icon:a},...p===void 0?{}:{tone:p},entry:"ui/index.html",...l===void 0?{}:{entryHash:l},...y===void 0?{}:{initialState:y},...u===void 0?{}:{usage:u},...d===void 0?{}:{detailPanel:d},...A===void 0?{}:{displayModes:A},surfaces:O,size:{height:z},stateProjection:m,actions:I}}function Zi(e){let t={},n={};for(let r of e.actions){t[r.actionId]={capabilities:[r.capability],inputKeys:Object.keys(r.inputSchema.properties??{}),resultProjection:r.resultProjection,...r.confirmation===void 0?{}:{confirmation:r.confirmation}};let s=r.backend.type==="core"&&(r.backend.handler==="state.set"||r.backend.handler==="sqlite.browse");n[r.actionId]={actionId:r.actionId,mutation:r.mutation,backend:r.backend,launchPolicy:s?"allowed":"denied",...s?{}:{denialCode:"EXEC_DENIED"}};}let i={id:e.definitionId,version:e.version,renderer:"sandbox-html",...e.usage===void 0?{}:{usage:e.usage},...e.detailPanel===void 0?{}:{detailPanel:e.detailPanel},...e.displayModes===void 0?{}:{displayModes:e.displayModes},surfaces:e.surfaces,stateProjection:e.stateProjection,actions:t},o={entry:{path:"ui/index.html",...e.entryHash===void 0?{}:{hash:e.entryHash}},...e.initialState===void 0?{}:{initialState:e.initialState}};return {manifest:e,definition:i,handlers:n,resources:o}}function rt(e,t,n,i){if(typeof e=="string")return (e.length>4096||be(e))&&F("state contains an unsafe string"),e;if(e===null||typeof e=="boolean")return e;if(typeof e=="number")return Number.isFinite(e)||F("state contains a non-finite number"),e;(e===void 0||typeof e!="object"||typeof e=="function"||typeof e=="bigint")&&F("state contains a non-JSON value"),n>8&&F("state is too deep"),t.has(e)&&F("state contains a cycle"),t.add(e);try{let o;if(Array.isArray(e))e.length>128&&F("state array is too long"),o=e.map(s=>rt(s,t,n+1,65536));else {b(e)||F("state contains a non-plain object");let s={};for(let[a,p]of Object.entries(e))(a.length>4096||!Ee.test(a)||re(a))&&(a.length>4096&&F("state key is too long"),F("state contains a reserved or invalid key")),s[a]=rt(p,t,n+1,65536);o=s;}let r=JSON.stringify(o);return (r===void 0||Buffer.byteLength(r,"utf8")>i)&&F("state subtree is too large"),o}finally{t.delete(e);}}function st(e){b(e)||F("initial state must be a JSON object");let t=rt(e,new Set,0,65536);return (t===null||Array.isArray(t)||typeof t!="object")&&F(),t}function Qi(e,t={}){De(e),b(e)||c("MANIFEST_INVALID"),N(e,Ni),e.manifestVersion!==1&&c("MANIFEST_INVALID");let n=Qe(G(e,"pluginId")),i=Qe(G(e,"definitionId")),o=B(e,"version",1),r=B(e,"primitiveSet",1),s=t.supportedPrimitiveSet??Ai;(!Number.isSafeInteger(s)||s<1)&&c("MANIFEST_INVALID"),r>s&&c("PRIMITIVE_SET_UNSUPPORTED"),b(e.activation)||c("MANIFEST_INVALID"),N(e.activation,["kind","language"]),e.activation.kind!=="fenced-code"&&c("MANIFEST_INVALID");let a=Qe(G(e.activation,"language")),p=vi(e.schema),l=Bi(e.layout,p);return {manifestVersion:1,pluginId:n,definitionId:i,version:o,primitiveSet:r,activation:{kind:"fenced-code",language:a},schema:p,layout:l}}function er(e,t={}){return b(e)||c("MANIFEST_INVALID"),e.manifestVersion===2?qi(e,t):Qi(e,t)}function ee(e,t={}){try{return er(e,t)}catch(n){if(n instanceof V)throw n;return c("MANIFEST_INVALID")}}function at(e,t={}){let n=ee(e,t);return n.manifestVersion===2?Zi(n):n}var Kt="SKILL.md",or=/^---\s*\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;function Jt(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function sr(e){return e.isDirectory()||e.isSymbolicLink()}function Qt(e){try{return L.existsSync(e)&&L.statSync(e).isDirectory()}catch{return false}}function ct(e){let t;try{t=L.readFileSync(e,"utf8");}catch{return {frontmatter:{},readable:false,valid:false,hasFrontmatter:false}}let n=t.match(or);if(!n)return {frontmatter:{},readable:true,valid:true,hasFrontmatter:false};try{let i=Cn.load(n[1]??"");if(!Jt(i))return {frontmatter:{},readable:!0,valid:!1,hasFrontmatter:!0};let o=Jt(i.metadata)?i.metadata:void 0;return {frontmatter:{...typeof i.name=="string"?{name:i.name}:{},...typeof(o?.version??i.version)=="string"?{version:o?.version??i.version}:{},...typeof i.description=="string"?{description:i.description}:{}},readable:!0,valid:!0,hasFrontmatter:!0}}catch{return {frontmatter:{},readable:true,valid:false,hasFrontmatter:true}}}function ar(e){return [w.join(e,Kt),w.join(e,"skill",Kt)]}function Xt(e,t){if(!Qt(e))return null;for(let n of ar(e)){if(!L.existsSync(n))continue;let o=ct(n).frontmatter;return {name:o.name??t,...o.version===void 0?{}:{version:o.version},...o.description===void 0?{}:{description:o.description},skillMdPath:n,dir:e}}return null}function Yt(e){try{return L.readdirSync(e,{withFileTypes:!0}).filter(sr)}catch{return []}}function qt(e,t,n){!e||t.has(e.name)||(t.add(e.name),n.push(e));}function en(e){let t=[],n=new Set;for(let i of e)if(Qt(i))for(let o of Yt(i)){if(o.name.startsWith("@")){let r=w.join(i,o.name);for(let s of Yt(r))qt(Xt(w.join(r,s.name),s.name),n,t);continue}qt(Xt(w.join(i,o.name),o.name),n,t);}return t.sort((i,o)=>i.name.localeCompare(o.name))}var pr=/^[0-9a-f]{64}$/;function Se(e){let n=e.renderer!==void 0||e.surfaces!==void 0||e.stateProjection!==void 0||e.usage!==void 0||e.detailPanel!==void 0||e.displayModes!==void 0||Object.values(e.actions).some(o=>o.resultProjection!==void 0)?{id:e.id,version:e.version,renderer:e.renderer,surfaces:e.surfaces,stateProjection:e.stateProjection,...e.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=ie(n);return Mt.createHash("sha256").update(Z(i)).digest("hex")}function pt(e){if(!/^\d+$/.test(String(e.version))||e.version<1||e.id.length<1||e.id.length>128)throw new D("DEFINITION_UNSUPPORTED","UI definition is invalid");if(e.sourceHash!==void 0&&(typeof e.sourceHash!="string"||!pr.test(e.sourceHash)))throw new D("DEFINITION_UNSUPPORTED","UI definition source hash is invalid");if(!/^[0-9a-f]{64}$/.test(e.hash)||Se(e)!==e.hash)throw new D("DEFINITION_UNSUPPORTED","UI definition hash is invalid");for(let[t,n]of Object.entries(e.actions)){if(!t||!Array.isArray(n.capabilities)||n.capabilities.some(i=>!lr(i)))throw new D("DEFINITION_UNSUPPORTED","UI action declaration is invalid");if(n.confirmation!==void 0&&n.confirmation!=="none"&&n.confirmation!=="native")throw new D("DEFINITION_UNSUPPORTED","UI action confirmation is invalid");if(n.inputKeys&&(!Array.isArray(n.inputKeys)||n.inputKeys.some(i=>typeof i!="string"||!i)))throw new D("DEFINITION_UNSUPPORTED","UI action input declaration is invalid");n.resultProjection&&tn(n.resultProjection);}if(e.renderer!==void 0&&(!e.renderer||e.renderer.length>128))throw new D("DEFINITION_UNSUPPORTED","UI definition renderer is invalid");if(e.surfaces&&(!Array.isArray(e.surfaces)||e.surfaces.some(t=>!t||t.length>64)))throw new D("DEFINITION_UNSUPPORTED","UI definition surfaces are invalid");if(e.usage!==void 0&&e.usage!=="card"&&e.usage!=="window")throw new D("DEFINITION_UNSUPPORTED","UI definition usage is invalid");if(e.detailPanel!==void 0&&typeof e.detailPanel!="boolean")throw new D("DEFINITION_UNSUPPORTED","UI definition detailPanel is invalid");if(e.displayModes&&(!Array.isArray(e.displayModes)||e.displayModes.length===0||new Set(e.displayModes).size!==e.displayModes.length||e.displayModes.some(t=>t!=="inline"&&t!=="floating"&&t!=="focused")))throw new D("DEFINITION_UNSUPPORTED","UI definition displayModes are invalid");if(e.usage==="card"&&e.displayModes!==void 0)throw new D("DEFINITION_UNSUPPORTED","Card definitions cannot declare displayModes");if(e.usage==="window"&&e.detailPanel!==void 0)throw new D("DEFINITION_UNSUPPORTED","Window definitions cannot declare detailPanel");e.stateProjection&&tn(e.stateProjection);}function tn(e){if(!Array.isArray(e.allow)||e.allow.some(t=>!/^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)*$/.test(t)))throw new D("DEFINITION_UNSUPPORTED","UI projection policy is invalid")}function lr(e){return e.length>0&&e.length<=128&&e!=="*"&&e!=="all"&&!/[/*]/.test(e)}var q=class extends Error{constructor(n,i=n){super(i);this.code=n;}code;name="McpAppContractError"};function lt(e,t=e){throw new q(e,t)}var nn=["crewx_app_terminal_connect"];var ut=8*1024*1024;new Set(nn);var dr=4;function dt(e,t=0){try{let n=ie(e,t);return n.type!==void 0&&n.type!=="object"&<("TOOL_INVALID","MCP App inputSchema must describe an object"),n}catch(n){if(n instanceof q)throw n;lt("TOOL_INVALID","MCP App inputSchema must be projection-safe JSON");}}function rn(e){if(e.length===0)return dt({type:"object",properties:{},additionalProperties:false});let t=e.map(i=>i.actionId),n=new Map;for(let i of e)n.set(i.actionId,dt(i.inputSchema));return dt(ur(t,n),dr)}function ur(e,t){let n=e.map(i=>({type:"object",properties:{actionId:{type:"string",const:i},input:t.get(i)??{type:"object"}},required:["actionId","input"],additionalProperties:false}));return Object.freeze({type:"object",oneOf:Object.freeze(n),properties:Object.freeze({actionId:Object.freeze({type:"string",enum:Object.freeze([...e])}),input:Object.freeze({type:"object"})}),required:Object.freeze(["actionId","input"]),additionalProperties:false})}var h=class extends Error{constructor(n){super(n);this.code=n;}code;name="AppDiscoveryFsError"},ln=L.constants.O_NOFOLLOW,Ir=L.constants.O_NONBLOCK,gr=L.constants.O_RDONLY|(ln??0)|(Ir??0);function W(e){let t=typeof e=="object"&&e!==null&&"code"in e?String(e.code):"";return t==="ENOENT"?new h("NOT_FOUND"):t==="ELOOP"?new h("PATH_ESCAPED"):t==="EFBIG"||t==="EOVERFLOW"?new h("LIMIT_EXCEEDED"):t==="EACCES"||t==="EPERM"||t==="ENOTDIR"?new h("READ_DENIED"):new h("READ_DENIED")}function mr(e){if(typeof e!="string"||e.length===0||!w.isAbsolute(e))throw new h("READ_DENIED")}function on(e){if(typeof e!="string"||w.isAbsolute(e)||/[\\\u0000]/.test(e))throw new h("PATH_ESCAPED");if(e==="")return [];let t=e.split("/");if(t.some(n=>n.length===0||n==="."||n===".."))throw new h("PATH_ESCAPED");return t}function Le(e,t){let n=w.relative(e,t);return n===""||n!==".."&&!n.startsWith(`..${w.sep}`)&&!w.isAbsolute(n)}function Ue(e){return {dev:e.dev,ino:e.ino,size:e.size,mtimeNs:e.mtimeNs,ctimeNs:e.ctimeNs}}function At(e,t){return e.dev===t.dev&&e.ino===t.ino}function dn(e,t){return At(e,t)&&e.size===t.size&&e.mtimeNs===t.mtimeNs&&e.ctimeNs===t.ctimeNs}async function sn(e){mr(e);let t,n;try{t=await promises.realpath(e),n=await promises.stat(t,{bigint:!0});}catch(i){throw W(i)}if(!n.isDirectory())throw new h("READ_DENIED");return {realRoot:t,identity:Ue(n)}}async function hr(e,t,n){if(n.length<2||n[0]!=="apps"&&n[0]!=="skills")return;let i,o;try{if(i=w.resolve(e,n[0],n[1]),o=await promises.realpath(i),!(await promises.stat(o,{bigint:!0})).isDirectory())throw new h("READ_DENIED")}catch(r){throw r instanceof h?r:W(r)}if(!Le(t,o))throw new h("PATH_ESCAPED");return o}async function an(e,t,n,i){let o,r,s;try{o=await promises.lstat(e,{bigint:!0}),r=await promises.realpath(e),s=await promises.stat(r,{bigint:!0});}catch(a){throw W(a)}if(!Le(t,r)||n!==void 0&&!Le(n,r))throw new h("PATH_ESCAPED");if(!o.isFile()||!s.isFile())throw new h("READ_DENIED");if(!At(i,o)||!At(i,s)||i.dev!==s.dev)throw new h("PATH_ESCAPED")}async function ft(e,t){let n,i;try{n=await promises.realpath(e),i=await promises.stat(n,{bigint:!0});}catch{throw new h("PATH_ESCAPED")}if(n!==t.realRoot||!dn(t.identity,Ue(i)))throw new h("PATH_ESCAPED")}function _r(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 Re=class{async listDirectory(t,n){let i=on(n),o=await sn(t),r=w.resolve(t,...i),s,a;try{s=await promises.realpath(r),a=await promises.stat(s,{bigint:!0});}catch(p){let l=W(p);if(l.code==="NOT_FOUND")return [];throw l}if(!Le(o.realRoot,s)||!a.isDirectory())throw new h("PATH_ESCAPED");try{let p=await promises.readdir(s,{withFileTypes:!0,encoding:"utf8"});return await ft(t,o),p.map(_r)}catch(p){let l=W(p);if(l.code==="NOT_FOUND")return [];throw l}}async readdir(t,n){return this.listDirectory(t,n)}async readDirectory(t,n){return this.listDirectory(t,n)}async readVerifiedFile(t,n,i){if(!Number.isSafeInteger(i)||i<0)throw new h("READ_DENIED");if(ln===void 0)throw new h("UNSUPPORTED");let o=on(n),r=await sn(t),s=w.resolve(t,...o),a=w.relative(t,s);if(a===".."||a.startsWith(`..${w.sep}`)||w.isAbsolute(a))throw new h("PATH_ESCAPED");let p;try{p=await promises.open(s,gr);}catch(l){throw W(l)}try{let l;try{let g=await p.stat({bigint:!0});l=Ue(g);}catch(g){throw W(g)}if(l.size>BigInt(i))throw new h("LIMIT_EXCEEDED");if(l.size>BigInt(Number.MAX_SAFE_INTEGER))throw new h("LIMIT_EXCEEDED");await ft(t,r);let y=await hr(t,r.realRoot,o);await an(s,r.realRoot,y,l);let u=new Uint8Array(new ArrayBuffer(Number(l.size))),d=0;for(;d<u.byteLength;){let g;try{g=(await p.read(u,d,u.byteLength-d,d)).bytesRead;}catch(O){throw W(O)}if(g<=0)throw new h("IDENTITY_CHANGED");d+=g;}let A;try{let g=await p.stat({bigint:!0});A=Ue(g);}catch(g){throw W(g)}if(!dn(l,A))throw new h("IDENTITY_CHANGED");return await an(s,r.realRoot,y,A),await ft(t,r),new Uint8Array(u)}finally{await p.close().catch(()=>{});}}async readFileVerified(t,n,i){return this.readVerifiedFile(t,n,i)}},un=new Re;var gt="crewx_local_app_";function Er(e){if(typeof e!="string"||!oe.test(e))throw new TypeError("pluginId must be a safe UI plugin identifier");let t=`${gt}${e}`.length+7<=128?e:`hash_${Mt.createHash("sha256").update(e,"utf8").digest("hex")}`;return {read:`${gt}${t}_read`,action:`${gt}${t}_action`}}var ht=["apps","skills"],Tr=new TextDecoder("utf-8",{fatal:true});function _t(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;try{let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}catch{return false}}function fn(e){return typeof e=="string"&&oe.test(e)?e:void 0}function Pr(e,t){return t.length===0||t==="."||t===".."||/[\\/\u0000]/.test(t)?e:`${e}/${t}`}function Dr(e){return e.length>0&&e!=="."&&e!==".."&&!/[\\/\u0000]/.test(e)}function hn(e,t){let n=new TextEncoder().encode(e),i=new TextEncoder().encode(t),o=Math.min(n.byteLength,i.byteLength);for(let r=0;r<o;r+=1){let s=n[r]-i[r];if(s!==0)return s}return n.byteLength-i.byteLength}function Nr(e){if(typeof e=="string")return {name:e,kind:"directory"};if(e===null||typeof e!="object")return null;let t=e;if(typeof t.name!="string")return null;if(t.kind==="file"||t.kind==="directory"||t.kind==="symlink"||t.kind==="other")return {name:t.name,kind:t.kind};if(t.type==="file"||t.type==="directory"||t.type==="symlink"||t.type==="other")return {name:t.name,kind:t.type};let n=t.isDirectory;if(typeof n=="function"&&n.call(e))return {name:t.name,kind:"directory"};let i=t.isSymbolicLink;if(typeof i=="function"&&i.call(e))return {name:t.name,kind:"symlink"};let o=t.isFile;return typeof o=="function"&&o.call(e)?{name:t.name,kind:"file"}:{name:t.name,kind:"other"}}function br(e){if(e instanceof Uint8Array)return new Uint8Array(e);if(e instanceof ArrayBuffer)return new Uint8Array(e.slice(0));if(Array.isArray(e)&&e.every(t=>Number.isInteger(t)&&t>=0&&t<=255))return Uint8Array.from(e);throw new TypeError("filesystem port returned an invalid byte array")}function _n(e){return Tr.decode(e)}function En(e){return JSON.parse(_n(e))}function Mr(e){if(!_t(e))return;let t=fn(e.pluginId);if(!t)return;let n=fn(e.definitionId),i=e.version,o=n&&Number.isSafeInteger(i)&&i>=1?`${n}\0${String(i)}`:void 0;return {pluginId:t,...o===void 0?{}:{definitionKey:o}}}function Sr(e){let t=En(e);return {value:t,identity:Mr(t)}}function Et(e,t,n,i){let o={code:e,...i===void 0?{}:{pluginId:i},source:t,relativePath:n};return Object.freeze(o)}function yn(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 te(e){if(e instanceof h)return yn(e.code);if(e!==null&&typeof e=="object"&&"code"in e){let t=e.code;if(typeof t=="string")return yn(t)}}function me(e,t){return e==="PATH_ESCAPED"||e==="IDENTITY_CHANGED"||e==="TOCTOU"?"PATH_ESCAPED":e==="LIMIT_EXCEEDED"?"LIMIT_EXCEEDED":t==="manifest"&&e==="NOT_FOUND"?"MANIFEST_MISSING":t==="entry"?"ENTRY_INVALID":t==="initial"?"INITIAL_STATE_INVALID":"MANIFEST_INVALID"}function An(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 Tn("UiPluginValidationError",e.code)}}function Tn(e,t){throw new Error(`Unmapped ${e} code: ${String(t)}`)}function mt(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 Tn("McpAppContractError",e)}}function In(e,t){let n=t();return Number.isFinite(n)&&Number.isFinite(e)&&n-e<=5e3}function ce(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let t of Object.values(e))ce(t);return Object.freeze(e)}function gn(e){return Object.freeze(Array.from(e))}function Lr(e,t,n){let i=Mt.createHash("sha256"),o=new TextEncoder().encode(Z(e)),r=s=>{let a=new Uint8Array(8);new DataView(a.buffer).setBigUint64(0,BigInt(s)),i.update(a);};return r(o.byteLength),i.update(o),r(t.byteLength),i.update(t),r(n.byteLength),i.update(n),i.digest("hex")}function Ur(e,t){let n={...e.definition,sourceHash:t},i={...n,hash:Se(n)};try{pt(i);}catch{throw new V("MANIFEST_INVALID","normalized definition is invalid")}return i}function Rr(e){return e.actions.some(t=>t.backend.type!=="core"||t.backend.handler!=="state.set"&&t.backend.handler!=="sqlite.browse")}function Or(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 xe(e,t,n,i){let o=Or(e);if(!o)throw new h("READ_DENIED");return br(await o.call(e,t,n,i))}async function xr(e,t,n){let i=wr(e);if(!i)throw new h("READ_DENIED");let o=await i.call(e,t,n);if(!Array.isArray(o))throw new h("READ_DENIED");return o.map(Nr).filter(r=>r!==null)}function Cr(e){let t=[];for(let n of [e.reserved,e.builtin])n&&t.push(n);return e.builtins&&"listMcpApps"in e.builtins?t.push(mn(e.builtins)):e.builtins&&t.push(e.builtins),e.builtinCatalog&&t.push(mn(e.builtinCatalog)),t.push({...e.reservedAppIds===void 0?{}:{appIds:e.reservedAppIds},...e.reservedDefinitionIds===void 0?{}:{definitionIds:e.reservedDefinitionIds},...e.reservedToolNames===void 0?{}:{toolNames:e.reservedToolNames}}),t}function mn(e){let t=[],n=[],i=[];for(let o of e.listMcpApps())typeof o.appId=="string"&&t.push(o.appId),o.definition&&typeof o.definition.id=="string"&&n.push(o.definition.id);for(let o of e.listMcpAppTools())typeof o.name=="string"&&i.push(o.name);return {appIds:t,definitionIds:n,toolNames:i}}function ge(e,t){e.diagnostic||(e.diagnostic=Et(t,e.source,e.relativePath,e.identity?.pluginId));}function kr(e){let t=new Map,n=new Map;for(let i of e){if(i.identity?.pluginId){let o=t.get(i.identity.pluginId)??[];o.push(i),t.set(i.identity.pluginId,o);}if(i.identity?.definitionKey){let o=n.get(i.identity.definitionKey)??[];o.push(i),n.set(i.identity.definitionKey,o);}}for(let i of [...t.values(),...n.values()]){let o=i.filter(r=>r.source==="apps");if(o.length>0){if(o.length>1)for(let r of o)ge(r,"DUPLICATE_ID");for(let r of i.filter(s=>s.source==="skills"))ge(r,"DUPLICATE_ID");continue}if(i.length>1)for(let r of i)ge(r,"DUPLICATE_ID");}}function Vr(e,t){let n=new Set,i=new Set,o=new Set;for(let r of Cr(t)){for(let s of r.appIds??[])typeof s=="string"&&n.add(s);for(let s of r.definitionIds??[])typeof s=="string"&&i.add(s);for(let s of r.toolNames??[])typeof s=="string"&&o.add(s);}for(let r of e){let s=r.candidate;if(!s)continue;if(n.has(s.pluginId)||i.has(s.definitionId)){ge(r,"RESERVED_ID");continue}[s.toolNames.read,s.toolNames.action].filter(p=>p!==void 0).some(p=>o.has(p))&&ge(r,"DUPLICATE_ID");}}function Fr(e){return [...e].sort((t,n)=>{let i=ht.indexOf(t.source)-ht.indexOf(n.source);return i!==0?i:hn(t.relativePath,n.relativePath)})}function P(e,t){e.diagnostic=Et(t,e.source,e.relativePath,e.identity?.pluginId);}async function vr(e,t,n,i){if(i.byteLength>262144){P(n,"LIMIT_EXCEEDED");return}let o;try{o=Sr(i);}catch{P(n,"MANIFEST_INVALID");return}if(n.identity=o.identity,_t(o.value)&&o.value.builtinOnly===true){P(n,"RESERVED_ID");return}let r;try{let _=ee(o.value,{mode:"local"});if(_.manifestVersion!==2)throw new V("MANIFEST_INVALID","workspace App requires v2");r=_;}catch(_){if(_ instanceof V){P(n,An(_));return}if(_ instanceof q){P(n,mt(_.code));return}if(_t(_)&&typeof _.code=="string"){P(n,mt(_.code));return}throw _}if(n.identity={pluginId:r.pluginId,definitionKey:`${r.definitionId}\0${String(r.version)}`},r.actions.length>0)try{rn(r.actions.map(_=>({actionId:_.actionId,inputSchema:_.inputSchema})));}catch(_){if(_ instanceof q){P(n,mt(_.code));return}throw _}let s=`${n.relativePath}/ui/index.html`,a;try{a=await xe(t,e,s,ut);}catch(_){P(n,me(te(_),"entry"));return}if(a.byteLength>ut){P(n,"LIMIT_EXCEEDED");return}let p;try{p=_n(a);}catch{P(n,"ENTRY_INVALID");return}if(a.byteLength===0||p.length===0){P(n,"ENTRY_INVALID");return}let l=Mt.createHash("sha256").update(a).digest("hex");if(r.entryHash!==void 0&&r.entryHash!==l){P(n,"ENTRY_INVALID");return}let y={},u,d;if(r.initialState!==void 0){let _=`${n.relativePath}/ui/state.json`;try{u=await xe(t,e,_,65536);}catch(R){P(n,me(te(R),"initial"));return}if(u.byteLength>65536){P(n,"LIMIT_EXCEEDED");return}try{let R=En(u),ii=st(R);y=ie(ii),We(y);}catch{P(n,"INITIAL_STATE_INVALID");return}if(d=Mt.createHash("sha256").update(u).digest("hex"),r.initialState.hash!==void 0&&r.initialState.hash!==d){P(n,"INITIAL_STATE_INVALID");return}}let A={...r,entryHash:l,...r.initialState===void 0?{}:{initialState:{path:"ui/state.json",hash:d}}},g=at(A),O=Lr(A,a,u??new Uint8Array),v;try{v=Ur(g,O);}catch(_){if(_ instanceof V){P(n,An(_));return}throw _}let z=Er(r.pluginId),m=r.actions.length===0?{read:z.read}:z,I=ce(g),j=ce(A),M=ce(v),U=ce({...g.handlers}),x=gn(a),$=u===void 0?void 0:gn(u),Ut=Object.freeze({entry:Object.freeze({path:"ui/index.html",hash:l,bytes:x}),...$===void 0?{}:{initialState:Object.freeze({path:"ui/state.json",hash:d,bytes:$})}}),_e={appId:r.pluginId,pluginId:r.pluginId,definitionId:r.definitionId,version:r.version,source:n.source,relativePath:n.relativePath,manifest:j,normalized:I,name:r.name,description:r.description,...r.icon===void 0?{}:{icon:r.icon},...r.tone===void 0?{}:{tone:r.tone},definition:M,handlers:U,resources:Ut,html:p,entryBytes:x,entryHash:l,initialState:ce(y),...$===void 0?{}:{initialStateBytes:$},...d===void 0?{}:{initialStateHash:d},sourceHash:O,toolNames:Object.freeze(m)};n.candidate=Object.freeze(_e),Rr(r)&&P(n,"EXEC_DENIED");}async function jr(e,t,n){try{return await xe(t,e,`${n.relativePath}/ui-plugin.json`,262144)}catch(i){if(te(i)==="NOT_FOUND")return;P(n,me(te(i),"manifest"));return}}function Hr(e){let t=Fr(e);kr(t);let n=Object.freeze(t.filter(r=>r.candidate!==void 0&&r.diagnostic===void 0).map(r=>r.candidate)),i=Object.freeze(t.filter(r=>r.diagnostic!==void 0).map(r=>r.diagnostic)),o={apps:n,diagnostics:i};return Object.defineProperty(o,"candidates",{configurable:false,enumerable:false,get:()=>n}),Object.freeze(o)}function Br(e){if(e===null||typeof e!="object"&&typeof e!="function")return false;let t=e;return typeof t.readVerifiedFile=="function"||typeof t.readFileVerified=="function"||typeof t.listDirectory=="function"||typeof t.readDirectory=="function"||typeof t.readdir=="function"}function zr(e,t){if(Br(e))return {fs:e,options:{}};let n=e??t??{};return {fs:n.filesystem??n.fileSystem??n.fs??un,options:n}}async function Pn(e,t,n){if(typeof e!="string"||e.length===0)throw new TypeError("workspaceRoot must be explicit");let{fs:i,options:o}=zr(t,n),r=o.clock??(()=>Date.now()),s=r(),a=[],p=0;for(let l of ht){let y;try{y=await xr(i,e,l);}catch(d){if(te(d)==="NOT_FOUND")continue;a.push({source:l,name:"",relativePath:l,diagnostic:Et(me(te(d),"manifest"),l,l)});continue}let u=y.filter(d=>d.kind==="directory"||d.kind==="symlink").filter(d=>Dr(d.name)).map(d=>({source:l,name:d.name,relativePath:Pr(l,d.name)})).sort((d,A)=>hn(d.relativePath,A.relativePath));for(let d of u){let A={...d};a.push(A);let g;if(l==="skills"&&(g=await jr(e,i,A),g===void 0))continue;if(!In(s,r)){P(A,"LIMIT_EXCEEDED");continue}if(p>=64){P(A,"LIMIT_EXCEEDED");continue}if(d.relativePath.split("/").length-1>2){P(A,"LIMIT_EXCEEDED");continue}if(p+=1,g===void 0)try{g=await xe(i,e,`${A.relativePath}/ui-plugin.json`,262144);}catch(v){P(A,me(te(v),"manifest"));continue}await vr(e,i,A,g),A.diagnostic===void 0&&!In(s,r)&&P(A,"LIMIT_EXCEEDED");}}return Vr(a,o),Hr(a)}var $r=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/;function ke(e){let t="screenHash"in e?e.screenHash:void 0,i=("skillHash"in e?e.skillHash:void 0)??(e.relativePath!==void 0&&e.fileBytes!==void 0?Wr(e.relativePath,e.fileBytes):void 0);if(t!==void 0&&i!==void 0){let o=JSON.stringify({screenHash:t,skillHash:i});return Mt.createHash("sha256").update(o,"utf8").digest("hex")}if(t!==void 0)return t;if(i!==void 0)return i;throw new TypeError("App definition hash input must contain a screenHash or skill bytes")}function Wr(e,t){let n=new TextEncoder().encode(Ve(e)),i=Kr(t),o=new Uint8Array(n.byteLength+1+i.byteLength);return o.set(n,0),o[n.byteLength]=0,o.set(i,n.byteLength+1),Mt.createHash("sha256").update(o).digest("hex")}function Kr(e){if(typeof e=="string")return new TextEncoder().encode(e);if(e instanceof Uint8Array)return new Uint8Array(e);if(e instanceof ArrayBuffer)return new Uint8Array(e.slice(0));if(Array.isArray(e)&&e.every(t=>Number.isInteger(t)&&t>=0&&t<=255))return Uint8Array.from(e);throw new TypeError("fileBytes must be UTF-8 text or bytes")}function Ve(e){if(typeof e!="string"||e.length===0||w.isAbsolute(e)||/[\\\u0000]/.test(e))throw new TypeError("relative path must be package-relative");let t=e.split("/").filter(n=>n.length>0&&n!==".").join("/");if(!t||t.split("/").some(n=>n===".."))throw new TypeError("relative path must stay inside the package");return t}function Ce(e,t){let n=new TextEncoder().encode(e),i=new TextEncoder().encode(t),o=Math.min(n.byteLength,i.byteLength);for(let r=0;r<o;r+=1){let s=n[r]-i[r];if(s!==0)return s}return n.byteLength-i.byteLength}function bn(e,t){let n=w.relative(e,t).split(w.sep).join("/");return !n||n===".."||n.startsWith("../")||w.isAbsolute(n)?null:Ve(n)}function Jr(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 Mn(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??Y,...e.definition.detailPanel===void 0?{}:{detailPanel:e.definition.detailPanel},...e.definition.displayModes===void 0?{}:{displayModes:e.definition.displayModes}})}function Sn(e){return {capabilities:Object.freeze([...e]),origin:"local",ownership:"unknown",shareability:"unknown",sharingAvailability:"unavailable"}}function Yr(e,t){let n=e.candidate,i=t?["screen","skill"]:["screen"],o=Xr(n),r=ke(t?{screenHash:o.hash,skillHash:t.skillHash}:{screenHash:o.hash}),s=n.description||t?.skill.description||"",a=String(n.version),p={appId:n.pluginId,name:n.name,description:s,version:a,...Sn(i),definition:o,...t===void 0?{}:{skillName:t.skill.name},localDefinitionRef:Mn(e.packageRoot),definitionHash:r};return {packageRoot:e.packageRoot,source:n.source,appId:p.appId,capabilities:i,summary:Object.freeze(p)}}function qr(e){let t=Zr(e.skill.name),n={appId:t,name:e.skill.name,description:e.skill.description??"",...e.skill.version===void 0?{}:{version:e.skill.version},...Sn(["skill"]),skillName:e.skill.name,localDefinitionRef:Mn(e.packageRoot),definitionHash:ke({skillHash:e.skillHash})};return {packageRoot:e.packageRoot,source:e.source,appId:t,capabilities:["skill"],summary:Object.freeze(n)}}function Zr(e){return `skill.${e.replace(/^@/,"").replace(/\//g,".").replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,122)||"unnamed"}`}function C(e,t,n,i){return Object.freeze({code:e,source:t,relativePath:Qr(n),...i===void 0?{}:{appId:i}})}function Qr(e){if(typeof e!="string"||e.length===0||w.isAbsolute(e)||/[\\\u0000]/.test(e))return "<unknown>";let t=e.split("/").filter(n=>n.length>0&&n!==".").join("/");return t.split("/").some(n=>n==="..")?"<unknown>":t}function eo(e){return C(e.code,e.source,e.relativePath,e.pluginId)}function to(e,t){let n=bn(e,t.dir);if(!n)return {diagnostic:C("PATH_ESCAPED","node_modules","node_modules")};let i=Jr(n);if(!i)return {diagnostic:C("PATH_ESCAPED","node_modules",n)};let o=ct(t.skillMdPath);if(!o.readable)return {diagnostic:C("SKILL_READ_FAILED",i,n)};if(!o.valid)return {diagnostic:C("SKILL_INVALID",i,n)};let r=no(t.dir,t.skillMdPath);if(!r)return {diagnostic:C("PATH_ESCAPED",i,n)};try{let s=new Uint8Array(L.readFileSync(t.skillMdPath));return {skill:t,packageRoot:n,relativeSkillPath:r,skillHash:ke({relativePath:r,fileBytes:s}),source:i}}catch{return {diagnostic:C("SKILL_READ_FAILED",i,n)}}}function no(e,t){let n=w.relative(e,t).split(w.sep).join("/");try{return Ve(n)}catch{return null}}function io(e){if(!$r.test(e.appId))return {diagnostic:C("BUILTIN_INVALID","builtin",`builtin/${e.appId||"unknown"}`)};let t=e.definition===void 0?void 0:{id:e.definition.id,version:e.definition.version,hash:e.definition.hash,usage:e.definition.usage??Y,...e.definition.detailPanel===void 0?{}:{detailPanel:e.definition.detailPanel},...e.definition.displayModes===void 0?{}:{displayModes:e.definition.displayModes}},n=t?.hash??Mt.createHash("sha256").update(JSON.stringify({appId:e.appId,name:e.name,description:e.description}),"utf8").digest("hex"),i={appId:e.appId,name:e.name,description:e.description,...t===void 0?{}:{version:String(t.version),definition:t},capabilities:["screen"],origin:"builtin",ownership:"unknown",shareability:"forbidden",sharingAvailability:"unavailable",definitionHash:n};return {source:"builtin",appId:e.appId,summary:Object.freeze(i)}}function ro(e){return e.builtinCatalog}function oo(e){let t=e.packageRoot??e.relativePath??e.packageRootPath;if(t===void 0)return null;try{return Ve(t)}catch{return null}}function so(e){let t=e.marketplaceContentId;return typeof t=="string"&&t.length>0?t:void 0}function ao(e,t,n){let i=t.installed??[],o=new Map;for(let s of i){let a=oo(s);if(!a){n.push(C("INSTALLED_IDENTITY_MISMATCH","installed","installed"));continue}let p=o.get(a);if(p&&JSON.stringify(p)!==JSON.stringify(s)){n.push(C("INSTALLED_IDENTITY_MISMATCH","installed",a));continue}o.set(a,s);}let r=new Map;for(let s of e)s.packageRoot!==void 0&&r.set(s.packageRoot,s);for(let[s,a]of o){let p=r.get(s);if(!p){n.push(C("INSTALLED_MISSING","installed",s,a.appId));continue}let l=so(a);if(!l){n.push(C("INSTALLED_CONTENT_ID_MISSING","installed",s,a.appId));continue}if(a.appId!==void 0&&a.appId!==p.appId||a.definitionHash!==void 0&&a.definitionHash!==p.summary.definitionHash){n.push(C("INSTALLED_IDENTITY_MISMATCH","installed",s,a.appId));continue}let y={...p.summary,origin:"installed",...a.slug===void 0?{}:{slug:a.slug},marketplaceContentId:l},u=e.indexOf(p);u>=0&&(e[u]={...p,summary:Object.freeze(y)});}}function co(e,t){let n=new Map;for(let o of e){let r=n.get(o.appId)??[];r.push(o),n.set(o.appId,r);}let i=new Set;for(let o of n.values())if(!(o.length<2))for(let r of o)i.add(r),t.push(C("DUPLICATE_ID",r.source,r.packageRoot??`builtin/${r.appId}`,r.appId));return e.filter(o=>!i.has(o))}function po(e,t){return e.filter(n=>!(n.code==="MANIFEST_MISSING"&&t.has(n.relativePath))).map(eo)}function lo(e){return e.filesystem}function uo(e,t){let n=lo(e);return {...n===void 0?{}:{filesystem:n},...t===void 0?{}:{builtinCatalog:t}}}async function Ln(e,t={}){if(typeof e!="string"||e.length===0)throw new TypeError("workspaceRoot must be explicit");let n=ro(t),i=await Pn(e,uo(t,n)),o=[w.join(e,"skills"),w.join(e,"node_modules"),w.join(e,"apps")],r=[],s=[],a=[],p=new Set;for(let m of o)for(let I of en([m])){let j=bn(e,I.dir);(j===null||!p.has(j))&&(a.push(I),j!==null&&p.add(j));}for(let m of a){let I=to(e,m);"diagnostic"in I?r.push(I.diagnostic):s.push(I);}let l=new Map;for(let m of i.apps??i.candidates??[])l.set(m.relativePath,{candidate:m,packageRoot:m.relativePath});let y=new Map(s.map(m=>[m.packageRoot,m])),u=[];for(let m of l.values()){let I=Yr(m,y.get(m.packageRoot));u.push({packageRoot:I.packageRoot,source:I.source,appId:I.appId,summary:I.summary});}let d=new Set(l.keys());for(let m of s){if(d.has(m.packageRoot))continue;let I=qr(m);u.push({packageRoot:I.packageRoot,source:I.source,appId:I.appId,summary:I.summary});}let A=[...po(i.diagnostics,new Set(s.map(m=>m.packageRoot))),...r],g=[];if(n)for(let m of n.listMcpApps()){let I=io(m);"diagnostic"in I?A.push(I.diagnostic):g.push(I);}let O=co([...u,...g],A);ao(O,t,A);let v=O.map(m=>m.summary).sort((m,I)=>Ce(m.appId,I.appId)),z=[...A].sort((m,I)=>Ce(m.relativePath,I.relativePath)||Ce(m.code,I.code)||Ce(m.appId??"",I.appId??""));return Object.freeze({items:Object.freeze(v),diagnostics:Object.freeze(z)})}function fo(e){let t=o=>o.replace(/[.+^${}()|[\]\\]/g,"\\$&"),i=e.split("/").map(o=>o==="**"?".*":o.split("*").map(t).join("[^/]*"));return new RegExp(`^${i.join("\\/")}$`)}function pe(e,t){try{return fo(t).test(e)}catch{return false}}function Fe(e,...t){let n=e.split("/");if(n.length<t.length)return false;let i=n.length-t.length;return t.every((o,r)=>pe(n[i+r],o))}function yo(e,t){return e.split("/").some(n=>pe(n,t))}var Un=[{label:".env*",test:e=>pe(e,".env*")},{label:".git/",test:(e,t,n)=>n&&e===".git"},{label:"memory/",test:(e,t,n)=>n&&e==="memory"},{label:"*.key",test:e=>pe(e,"*.key")},{label:"*.pem",test:e=>pe(e,"*.pem")},{label:"auth.json",test:e=>e==="auth.json"},{label:"node_modules/",test:(e,t,n)=>n&&e==="node_modules"},{label:"conversations/",test:(e,t,n)=>n&&e==="conversations"},{label:".crewx/threads/",test:(e,t,n)=>n&&Fe(t,".crewx","threads")},{label:".crewx/crewx.db",test:(e,t,n)=>!n&&Fe(t,".crewx","crewx.db")},{label:".crewx/*.log",test:(e,t,n)=>!n&&Fe(t,".crewx","*.log")},{label:".crewx/publish/",test:(e,t,n)=>n&&Fe(t,".crewx","publish")},{label:".crewx/",test:(e,t)=>yo(t,".crewx")}];function ve(e,t,n){for(let i of Un)if(i.test(e,t,n))return i.label;return null}function Nt(e){let t=[],n=[];function i(o,r,s){let a;try{a=L__namespace.readdirSync(o,{withFileTypes:!0});}catch{return}a.sort((p,l)=>p.name.localeCompare(l.name));for(let p of a){let l=r?`${r}/${p.name}`:p.name,y=w__namespace.join(o,p.name);if(p.isSymbolicLink()){let u;try{u=L__namespace.statSync(y);}catch{n.push({path:l,rule:"symlink"});continue}if(u.isDirectory()){n.push({path:l,rule:s??"symlink-dir"});continue}let d=s??ve(p.name,l,false);d?n.push({path:l,rule:d}):n.push({path:l,rule:"symlink"});continue}if(p.isDirectory()){let u=s??ve(p.name,l,true);i(y,l,u);continue}if(p.isFile()){let u=s??ve(p.name,l,false);u?n.push({path:l,rule:u}):t.push(l);}}}return i(e,"",null),t.sort(),n.sort((o,r)=>o.path<r.path?-1:o.path>r.path?1:0),{included:t,excluded:n}}var Ao=[{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 Io(e){return e.includes(0)}function bt(e,t,n){let i=[];for(let o of t){let r=w__namespace.join(e,o),s;try{let p=n?.get(o);s=p===void 0?L__namespace.readFileSync(r):Buffer.from(p);}catch{continue}if(Io(s))continue;s.toString("utf8").split(/\r\n|\r|\n/).forEach((p,l)=>{for(let{rule:y,regex:u}of Ao)u.test(p)&&i.push({path:o,line:l+1,rule:y});});}return i}var K=class extends Error{constructor(n,i){super(`publish: [${n}]${i?` ${i}`:""}`);this.code=n;}code;name="PublishError"};function f(e,t){return new K(e,t)}var xn=/^[a-z0-9-]+$/,go=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/,mo=/^[A-Za-z_][A-Za-z0-9_]*$/;function ho(e){let t=w__namespace.join(e,"crewx.yaml");if(!L__namespace.existsSync(t))return {};let n;try{n=Cn__namespace.load(L__namespace.readFileSync(t,"utf8"));}catch{return {}}if(!n||typeof n!="object")return {};let i=n.metadata;if(!i||typeof i!="object")return {};let o=i;return {name:typeof o.name=="string"?o.name:void 0,version:typeof o.version=="string"?o.version:void 0,description:typeof o.description=="string"?o.description:void 0,requiredEnv:o.requiredEnv,crewxMinVersion:typeof o.crewxMinVersion=="string"?o.crewxMinVersion:void 0}}function _o(e){return Mt__namespace.createHash("sha256").update(e).digest("hex")}function kn(e){let t;try{t=L__namespace.lstatSync(e);}catch{throw f("PACKAGE_FILE_INVALID",`file is not readable: ${w__namespace.basename(e)}`)}if(t.isSymbolicLink())throw f("PACKAGE_SYMLINK","symlink content is not publishable");if(!t.isFile())throw f("PACKAGE_FILE_INVALID","only regular files are publishable");return Mt__namespace.createHash("sha256").update(new Uint8Array(L__namespace.readFileSync(e))).digest("hex")}function Eo(e,t){let n=new TextEncoder().encode(e),i=new TextEncoder().encode(t),o=Math.min(n.byteLength,i.byteLength);for(let r=0;r<o;r+=1){let s=n[r]-i[r];if(s!==0)return s}return n.byteLength-i.byteLength}function Vn(e){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||w__namespace.posix.isAbsolute(e)||e.split("/").some(t=>t===".."||t.length===0))throw f("PACKAGE_PATH_TRAVERSAL","manifest file path must be a non-empty POSIX relative path")}function To(e){if(!/^(?:apps|skills)\/[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(e))throw f("APP_PACKAGE_ROOT_INVALID","packageRoot must be apps/<safe-id> or skills/<safe-id>")}function Fn(e){if(!go.test(e))throw new Error(`publish: invalid version "${e}" \u2014 must be semver (e.g. 1.0.0)`)}function vn(e,t,n={}){let i=ho(e),o=i.name??w__namespace.basename(e);if(!xn.test(o))throw new Error(`publish: invalid name "${o}" \u2014 must match ${xn} (lowercase letters, numbers, hyphen only)`);let r=n.version??i.version;if(!r)throw new Error("publish: version is required \u2014 set crewx.yaml metadata.version or pass opts.version");Fn(r);let s=Array.isArray(i.requiredEnv)?i.requiredEnv:[],a=[];for(let y of s){if(typeof y!="string"||!mo.test(y))throw new Error(`publish: requiredEnv must contain names only (no values), got "${String(y)}"`);a.push(y);}let p=t.map(y=>(Vn(y),{path:y,sha256:kn(w__namespace.join(e,y))})).sort((y,u)=>y.path<u.path?-1:y.path>u.path?1:0),l={name:o,version:r,type:"template",description:i.description??"",files:p,requiredEnv:a};return i.crewxMinVersion&&(l.crewxMinVersion=i.crewxMinVersion),l}function Po(e){let t=e.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"");if(!t)throw f("APP_PACKAGE_ROOT_INVALID","appId cannot produce a marketplace name");return t}function jn(e,t){if(To(t.packageRoot),!t.version)throw new Error("publish: version is required for App publishing \u2014 pass opts.version");if(Fn(t.version),typeof t.description!="string")throw new Error("publish: App description must be a string");let n=[...new Set(t.capabilities)].sort();if(n.length===0||n.some(s=>s!=="screen"&&s!=="skill"))throw new Error("publish: App capabilities must contain screen or skill");let i=`${t.packageRoot}/`;if(n.includes("screen")){if(typeof t.definitionId!="string"||t.definitionId.length===0)throw f("APP_UI_MANIFEST_INVALID","screen App manifests require definitionId");for(let s of ["ui-plugin.json","ui/index.html"])if(!t.includedFiles.includes(`${i}${s}`))throw f("APP_UI_MANIFEST_INVALID",`screen App is missing ${s}`)}if(n.includes("skill")&&!t.includedFiles.includes(`${i}SKILL.md`))throw f("APP_SKILL_MISSING","skill capability requires package-root SKILL.md");let o=new Set,r=t.includedFiles.map(s=>{if(Vn(s),!s.startsWith(i))throw f("PACKAGE_PATH_TRAVERSAL","App manifest file is outside packageRoot");let a=t.generatedFiles?.get(s);return a!==void 0&&o.add(s),{path:s,sha256:a===void 0?kn(w__namespace.join(e,s)):_o(a),...a===void 0?{}:{generated:true}}}).sort((s,a)=>Eo(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:Po(t.appId),version:t.version,type:"app",description:t.description,appId:t.appId,...t.definitionId===void 0?{}:{definitionId:t.definitionId},...t.definitionHash===void 0?{}:{definitionHash:t.definitionHash},capabilities:n,packageRoot:t.packageRoot,files:r,requiredEnv:[]}}function Hn(e){return Mt__namespace.createHash("sha256").update(e).digest("hex")}function Wn(e,t){if(typeof t!="string"||t.length===0||t.includes("\\")||t.includes("\0")||w__namespace.posix.isAbsolute(t)||t.split("/").some(o=>o===".."||o.length===0))throw f("PACKAGE_PATH_TRAVERSAL","archive paths must be non-empty POSIX relative paths");let n=w__namespace.resolve(e),i=w__namespace.resolve(n,...t.split("/"));if(i!==n&&!i.startsWith(`${n}${w__namespace.sep}`))throw f("PACKAGE_PATH_TRAVERSAL","archive path escaped its root");return i}function Bn(e,t){let n=Wn(e,t),i;try{i=L__namespace.lstatSync(n);}catch{throw f("PACKAGE_FILE_INVALID","manifest file is missing")}if(i.isSymbolicLink())throw f("PACKAGE_SYMLINK","symlink content is not publishable");if(!i.isFile())throw f("PACKAGE_FILE_INVALID","only regular files are publishable");return new Uint8Array(L__namespace.readFileSync(n))}async function Kn(e,t,n={}){let i=w__namespace.join(e,".crewx","publish");L__namespace.mkdirSync(i,{recursive:true});let o=w__namespace.join(i,`${t.name}-${t.version}.tgz`),r=w__namespace.join(i,`.${t.name}-${t.version}.${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}.tmp.tgz`),s=L__namespace.mkdtempSync(w__namespace.join(zn__namespace.tmpdir(),"crewx-publish-"));try{let a=new Set,p=[];for(let l of t.files){if(a.has(l.path))throw f("PACKAGE_PATH_TRAVERSAL","manifest contains duplicate file paths");a.add(l.path);let y=n.generatedFiles?.get(l.path);if(l.generated===!0&&y===void 0)throw f("PACKAGE_GENERATED_FILE_MISSING","generated manifest file bytes are missing");if(n.sourceFileHashes?.has(l.path)){let A=Bn(e,l.path);if(n.sourceFileHashes.get(l.path)!==Hn(A))throw f("PACKAGE_STAGED_BYTES_MISMATCH","workspace source changed before staging")}let u=y??Bn(e,l.path);if(Hn(u)!==l.sha256)throw f("PACKAGE_STAGED_BYTES_MISMATCH",`staged bytes differ for ${l.path}`);let d=Wn(s,l.path);L__namespace.mkdirSync(w__namespace.dirname(d),{recursive:!0}),L__namespace.writeFileSync(d,new Uint8Array(u)),p.push(l.path);}L__namespace.writeFileSync(w__namespace.join(s,"manifest.json"),JSON.stringify(t,null,2)),await $n__namespace.create({gzip:!0,file:r,cwd:s,portable:!0,noMtime:!0},["manifest.json",...p]),L__namespace.renameSync(r,o);}finally{try{L__namespace.rmSync(r,{force:!0});}catch{}L__namespace.rmSync(s,{recursive:true,force:true});}return o}var le="/api/v1";var bo=201,Mo=200,So=409,St=401,Jn={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 Lo(){return process.env.WI013_FAKE_UPLOAD==="1"}function Uo(e){let t=zlib.gunzipSync(new Uint8Array(e)),n=zlib.gzipSync(new Uint8Array(t),{level:1});if(Buffer.compare(new Uint8Array(n),new Uint8Array(e))===0)throw new Error("publish: [E_MALFORMED] Re-gzipped upload bytes are identical to the original \u2014 tamper is a no-op");return n}function Ro(e){return e.replace(/\/+$/,"")}async function he(e){try{return await e.json()}catch{return null}}function Xn(e,t,n){let i=e;if(!i||i.success!==true||i.data===void 0)throw new Error(`publish: [E_MALFORMED] ${t} response envelope is malformed (expected { success: true, data }) \u2014 HTTP ${n}`);return i.data}function Oo(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(typeof t.contentId=="string"&&t.contentId.length>0)return t.contentId;if(!t.data||typeof t.data!="object"||Array.isArray(t.data))return;let n=t.data;return typeof n.contentId=="string"&&n.contentId.length>0?n.contentId:void 0}function wo(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(typeof t.slug=="string"&&t.slug.length>0)return t.slug;if(!t.data||typeof t.data!="object"||Array.isArray(t.data))return;let n=t.data;return typeof n.slug=="string"&&n.slug.length>0?n.slug:void 0}function Yn(e,t){if(!e||typeof e!="object"||Array.isArray(e))return;let n=e,i=n.data&&typeof n.data=="object"&&!Array.isArray(n.data)?n.data:void 0,o=[n.code,n.message,i?.code,i?.message];for(let r of o){if(typeof r!="string"||!Object.prototype.hasOwnProperty.call(Jn,r))continue;let s=r,a=s==="APP_NAME_CONFLICT"?`marketplace name is already in use: ${t}`:void 0;return f(Jn[s],a)}}async function xo(e){if(!e.baseUrl.trim())throw new Error("publish: [E_ENV_MISSING] Marketplace base URL is required");if(!e.accessToken.trim())throw new Error("publish: [E_AUTH_EXPIRED] A valid bearer token is required");let t=Ro(e.baseUrl),n=e.accessPolicy??"private",i=e.manifest.name,o=e.manifest.type==="app"?e.manifest:void 0,r=o!==void 0,s=o?.appId,a;try{a=await fetch(`${t}${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:n,...s===void 0?{}:{appId:s}})});}catch{throw new Error("publish: [E_NETWORK] Submit request failed (network)")}let p=await he(a),l=Oo(p),y=wo(p),u=r&&y!==void 0?y:i,d;if(a.status===bo)d="created";else if(r&&a.status===Mo){if(l===void 0)throw f("PUBLISH_CONTENT_ID_MISSING","App republish did not return an opaque contentId");d="existing";}else if(a.status===So){if(r)throw Yn(p,i)??f("APP_NAME_CONFLICT",`marketplace name is already in use: ${i}`);d="existing";}else throw a.status===St?new Error("publish: [E_AUTH_EXPIRED] Authentication is expired or missing \u2014 please log in again (HTTP 401)"):new Error(`publish: [E_HTTP] Submit request failed \u2014 HTTP ${a.status}`);let A="not-needed",g=null;if(d==="existing"&&!r){let x;try{x=await fetch(`${t}${le}/publisher/items`,{method:"GET",headers:{Authorization:`Bearer ${e.accessToken}`}});}catch{throw new Error("publish: [E_NETWORK] Publisher items request failed (network)")}let $=await he(x);if(x.status!==200)throw new Error(`publish: [E_HTTP] Publisher items request failed \u2014 HTTP ${x.status}`);let _e=Xn($,"publisher items",x.status)?.items;if(!Array.isArray(_e))throw new Error(`publish: [E_MALFORMED] Publisher items response is malformed (expected data.items[]) \u2014 HTTP ${x.status}`);let _=_e.find(R=>!R||typeof R!="object"?false:R.slug===i);if(!_||typeof _.version!="string")throw new Error(`publish: [E_MALFORMED] Publisher items response does not contain slug "${i}" \u2014 HTTP ${x.status}`);if(g=_.version,g!==e.manifest.version){let R;try{R=await fetch(`${t}${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(!R.ok)throw await he(R),R.status===St?new Error(`publish: [E_AUTH_EXPIRED] Authentication is expired or missing \u2014 please log in again (HTTP ${R.status})`):R.status===403?new Error(`publish: [E_FORBIDDEN] Version update is forbidden; only the item owner can update an existing item (HTTP ${R.status})`):new Error(`publish: [E_HTTP] Version update failed \u2014 HTTP ${R.status}`);A="applied";}}let O=L__namespace.readFileSync(e.tgzPath),v=Lo()?Uo(O):O,z=new FormData;z.set("archive",new Blob([new Uint8Array(v)],{type:"application/gzip"}),`${u}-${e.manifest.version}.tgz`);let m=r&&l!==void 0?l:i,I;try{I=await fetch(`${t}${le}/publisher/items/${encodeURIComponent(m)}/upload`,{method:"POST",headers:{Authorization:`Bearer ${e.accessToken}`},body:z});}catch{throw new Error("publish: [E_NETWORK] Upload request failed (network)")}if(I.status===St)throw new Error("publish: [E_AUTH_EXPIRED] Authentication is expired or missing \u2014 please log in again (HTTP 401)");if(!I.ok){let x=await he(I);if(r){let $=Yn(x,u);if($)throw $}throw new Error(`publish: [E_HTTP] Upload request failed \u2014 HTTP ${I.status}`)}let j=await he(I),M=Xn(j,"upload",I.status),U=typeof M.contentId=="string"&&M.contentId.length>0?M.contentId:l;if(r&&U===void 0)throw f("PUBLISH_CONTENT_ID_MISSING","App upload did not return an opaque contentId");return {slug:u,version:e.manifest.version,...U===void 0?{}:{contentId:U},artifactChecksum:M.artifactChecksum,artifactSizeBytes:M.artifactSizeBytes,submitOutcome:d,versionUpdate:A,serverVersionBefore:g}}var Co=1e4,ko=100*1024*1024;function Lt(e){return Mt__namespace.createHash("sha256").update(e).digest("hex")}function Vo(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function He(e,t){if(!t||t.includes("\\")||t.includes("\0")||w__namespace.posix.isAbsolute(t)||t.split("/").some(r=>r===".."||r.length===0))throw f("PACKAGE_PATH_TRAVERSAL","workspace file path is not a safe relative path");let n=w__namespace.resolve(e,...t.split("/")),i=w__namespace.resolve(e);if(n!==i&&!n.startsWith(`${i}${w__namespace.sep}`))throw f("PACKAGE_PATH_TRAVERSAL","workspace file path escaped the workspace root");let o;try{o=L__namespace.lstatSync(n);}catch{throw f("PACKAGE_FILE_INVALID",`workspace file is missing: ${t}`)}if(o.isSymbolicLink())throw f("PACKAGE_SYMLINK",`symlink is not publishable: ${t}`);if(!o.isFile())throw f("PACKAGE_FILE_INVALID",`not a regular file: ${t}`);return new Uint8Array(L__namespace.readFileSync(n))}function Be(e,t){return e===t||e.startsWith(`${t}/`)}function Fo(e,t){return e.path<t.path?-1:e.path>t.path?1:e.rule.localeCompare(t.rule)}function Zn(e,t,n){let i=e??t;if(!Number.isSafeInteger(i)||i<=0)throw new K("PACKAGE_SIZE_LIMIT",`${n} must be a positive integer`);return i}function ei(e,t,n,i){let o=Zn(n.maxFileCount??n.maxFiles,Co,"max file count"),r=Zn(n.maxTotalBytes??n.maxBytes,ko,"max total bytes");if(t.length>o)throw new K("PACKAGE_SIZE_LIMIT",`package exceeds file count limit (${o})`);let s=0;for(let a of t){let p=i?.get(a);if(p!==void 0?s+=p.byteLength:s+=He(e,a).byteLength,s>r)throw new K("PACKAGE_SIZE_LIMIT",`package exceeds byte limit (${r})`)}}function vo(e){return e.appId!==void 0||e.expectedDefinitionHash!==void 0}function jo(e){let t=e.appId!==void 0,n=e.expectedDefinitionHash!==void 0;if(!t&&n)throw f("APP_ID_REQUIRED","appId is required with expectedDefinitionHash");if(t&&!n)throw f("APP_DEFINITION_HASH_REQUIRED","expectedDefinitionHash is required with appId");if(!t||!n)throw f("APP_ID_REQUIRED")}function Ho(e,t){let n=e.filter(i=>i.appId===t);if(n.length===0)throw f("APP_NOT_FOUND",`no publishable App matches ${t}`);if(n.length!==1)throw f("APP_AMBIGUOUS",`more than one App matches ${t}`);return n[0]}function Bo(e){let t=e.localDefinitionRef?.packageRoot;if(!t||!/^(?:apps|skills)\/[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(t))throw f("APP_PACKAGE_ROOT_INVALID","selected App is not rooted in apps/<safe-id> or skills/<safe-id>");return t}function zo(e,t){let n=[];for(let i of e.excluded)n.push(Be(i.path,t)?i:{path:i.path,rule:"out-of-app-scope"});for(let i of e.included)Be(i,t)||n.push({path:i,rule:"out-of-app-scope"});return n.sort(Fo)}function Go(e,t,n,i){let o=`${n}/ui-plugin.json`;if(!i.includes(o))throw f("APP_UI_MANIFEST_INVALID","selected screen App has no package ui-plugin.json");let r=He(e,o),s=Lt(r),a;try{a=JSON.parse(Buffer.from(r).toString("utf8"));}catch{throw f("APP_UI_MANIFEST_INVALID","ui-plugin.json is not valid JSON")}let p;try{let d=ee(a,{mode:"local"});if(d.manifestVersion!==2)throw new Error("screen App requires manifestVersion 2");p=d;}catch(d){throw d instanceof V?f("APP_UI_MANIFEST_INVALID",d.code):f("APP_UI_MANIFEST_INVALID")}if(p.pluginId!==t.appId)throw f("APP_DEFINITION_CONFLICT","ui-plugin.json pluginId no longer matches the selected App");let l=`${n}/ui/index.html`;if(!i.includes(l))throw f("APP_UI_MANIFEST_INVALID","screen entry is outside package scope");let y=Lt(He(e,l)),u=JSON.parse(JSON.stringify(a));if(u.entryHash=y,Object.prototype.hasOwnProperty.call(u,"initialState")){let d=u.initialState;if(!Vo(d)||d.path!=="ui/state.json")throw f("APP_INITIAL_STATE_OUT_OF_SCOPE","initialState must reference ui/state.json inside the package");let A=`${n}/ui/state.json`;if(!i.includes(A))throw f("APP_INITIAL_STATE_OUT_OF_SCOPE","initialState reference is outside the selected package");let g=He(e,A);u.initialState={...d,hash:Lt(g)};}try{let d=ee(u,{mode:"published"});return {bytes:new Uint8Array(Buffer.from(Ke(d),"utf8")),sourceHash:s}}catch(d){throw d instanceof V?f("APP_UI_MANIFEST_INVALID",d.code):f("APP_UI_MANIFEST_INVALID")}}async function $o(e,t){let{included:n,excluded:i}=Nt(e);ei(e,n,t);let o=vn(e,n,{version:t.version}),r=bt(e,n);return {plan:{manifest:o,included:n,excluded:i,secretFindings:r},archiveOptions:{}}}async function Wo(e,t){jo(t);let n=await Ln(e),i=Ho(n.items,t.appId);if(i.definitionHash!==t.expectedDefinitionHash)throw f("APP_DEFINITION_CONFLICT",`definitionHash changed for ${t.appId}`);let o=Bo(i),r=Nt(e);if(r.excluded.some(A=>Be(A.path,o)&&(A.rule==="symlink"||A.rule==="symlink-dir")))throw f("PACKAGE_SYMLINK","selected App package contains a symlink");let s=r.included.filter(A=>Be(A,o)),a=zo(r,o),p=new Map,l=new Map;if(i.capabilities.includes("screen")){let A=Go(e,i,o,s);p.set(`${o}/ui-plugin.json`,A.bytes),l.set(`${o}/ui-plugin.json`,A.sourceHash);}if(i.capabilities.includes("skill")&&!s.includes(`${o}/SKILL.md`))throw f("APP_SKILL_MISSING","skill capability requires package-root SKILL.md");ei(e,s,t,p);let y={appId:i.appId,version:t.version??"",description:i.description,capabilities:i.capabilities,packageRoot:o,...i.definition?.id===void 0?{}:{definitionId:i.definition.id},definitionHash:i.definitionHash,includedFiles:s,generatedFiles:p},u=jn(e,y),d=bt(e,s,p);return {plan:{manifest:u,included:s,excluded:a,secretFindings:d},archiveOptions:{generatedFiles:p,sourceFileHashes:l}}}async function ti(e,t){let n=w__namespace.resolve(e);if(vo(t))return Wo(n,t);if(t.expectedDefinitionHash!==void 0)throw f("APP_ID_REQUIRED");return $o(n,t)}async function tc(e,t={}){return (await ti(e,t)).plan}function Ko(e){let t=e.map(n=>`${n.path}:${n.line} (${n.rule})`).join(", ");throw new K("PUBLISH_SECRET_FINDINGS",`aborted \u2014 secret findings must be resolved before packing: ${t}`)}async function ni(e,t={}){let n=w__namespace.resolve(e),i=await ti(n,t);i.plan.secretFindings.length>0&&Ko(i.plan.secretFindings);let o=await Kn(n,i.plan.manifest,i.archiveOptions);return {manifest:i.plan.manifest,tgzPath:o}}async function nc(e,t={}){return ni(e,t)}async function ic(e,t){let n=await ni(e,t);if(n.manifest.type!=="app")throw new Error("publish: App pack unexpectedly produced a template manifest");return n}
|
|
2
|
-
exports.DEFAULT_PUBLISH_MAX_BYTES=
|
|
1
|
+
'use strict';var St=require('crypto'),U=require('fs'),w=require('path'),Cn=require('js-yaml'),promises=require('fs/promises'),zn=require('os'),$n=require('tar'),zlib=require('zlib');function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var St__namespace=/*#__PURE__*/_interopNamespace(St);var U__namespace=/*#__PURE__*/_interopNamespace(U);var w__namespace=/*#__PURE__*/_interopNamespace(w);var Cn__namespace=/*#__PURE__*/_interopNamespace(Cn);var zn__namespace=/*#__PURE__*/_interopNamespace(zn);var $n__namespace=/*#__PURE__*/_interopNamespace($n);var b=class extends Error{constructor(n,i=n,r){super(i);this.code=n;this.currentRevision=r;}code;currentRevision;name="UiRuntimeError"};var ri=/(?:proof|token|secret|password|cookie|authorization|private[_-]?key|stack|exception|plugin[_-]?text)/i,oi=/(?:url|uri|endpoint|path|file(?:name|path)?|cwd|shell|directory|dir|folder)$/i,si=/<\/?[A-Za-z][^>]*>/,ai=/^(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)/,ci=/^(?:https?|file|ftp|ws|wss):\/\//i;function H(){throw new b("INPUT_INVALID","JSON value is not projection-safe")}function pi(e){let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}var li=8,di=4;function Ge(e,t,n,i,r){if(t>i&&H(),e===null||typeof e=="string"||typeof e=="boolean")return typeof e=="string"&&(si.test(e)||ci.test(e)||ai.test(e))&&H(),e;if(typeof e=="number")return Number.isFinite(e)||H(),e;(typeof e!="object"||e===void 0||typeof e=="function"||typeof e=="bigint")&&H();let o=e;n.has(o)&&H(),n.add(o);try{if(Array.isArray(e))return e.map(a=>Ge(a,t+1,n,i));pi(o)||H();let s={};for(let[a,p]of Object.entries(e))(ri.test(a)||oi.test(a))&&H(),s[a]=Ge(p,t+1,n,i,a);return s}finally{n.delete(o);}}function ie(e,t=0){(!Number.isInteger(t)||t<0||t>di)&&H();let n=Ge(e,0,new Set,li+t);return (n===null||Array.isArray(n)||typeof n!="object")&&H(),n}function We(e){try{let t=JSON.stringify(e);return t===void 0&&H(),t}catch{H();}}function $e(e){return Array.isArray(e)?e.map($e):e!==null&&typeof e=="object"?Object.fromEntries(Object.keys(e).sort().map(t=>[t,$e(e[t])])):e}function Z(e){return We($e(e))}function Ke(e){return Z(e)}var Y="window";var Ot=["__proto__","prototype","constructor","proof","token","secret","password","cookie","authorization","private_key","private-key","stack","exception","plugin_text","url","uri","endpoint","path","filename","filepath","cwd","shell","directory","dir","folder"],ui=new Set(Ot),fi=/(?: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 re(e){return ui.has(e)||fi.test(e)||yi.test(e)}var Ee=/^[A-Za-z0-9_]+$/,de=/^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)*$/,oe=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,Je=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/,Xe=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,Ye=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/,qe=["blue","violet","emerald","amber","rose","sky","slate","indigo"],Ze=["inline","panel"];var Ai=1,Ii=/^[a-z][a-zA-Z0-9]*(\.[a-zA-Z0-9]+)+$/,gi=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,Bt=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,mi=/<\/?[A-Za-z][^>]*>/,hi=/^(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)/,_i=/^(?:https?|file|ftp|ws|wss):\/\//i,Ei=/^\s*(?:javascript|data):/i,wt=/data:[^,\s]*,/i,Ti=/(?:https?|file|ftp|ws|wss):\/\//i,Pi=/javascript:/i,Di=/(?:^[\s]*|[\s"'(=])(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)(?=[^\s"'<>])[^\s"'<>]*/,bi=["manifestVersion","pluginId","definitionId","version","primitiveSet","activation","schema","layout"],Ni=["manifestVersion","pluginId","definitionId","version","name","description","entry","surfaces","size","stateProjection","actions"],Mi=["icon","tone","entryHash","initialState","usage","detailPanel","displayModes"],Si=["actionId","capability","mutation","inputSchema","resultProjection","backend"],Li=["confirmation"],Ui=["type","handler"],Ri=["type","command"],Oi=["path"],wi=["hash"],xi=/^[0-9a-f]{64}$/,Ci=/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/,ki=/[\r\n]/,Vi=["card-shell","meta-banner","heading","labeled-text","step-flow","text-list"],V=class extends Error{constructor(n,i=n){super(i);this.code=n;}code;name="UiPluginValidationError"};function c(e,t=e){throw new V(e,t)}function M(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;try{let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}catch{return false}}function T(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function N(e,t,n=[]){let i=new Set([...t,...n]);Object.keys(e).some(r=>!i.has(r))&&c("MANIFEST_INVALID"),t.some(r=>!T(e,r))&&c("MANIFEST_INVALID");}function Ne(e,t=false,n=false){return mi.test(e)||_i.test(e)||hi.test(e)||n&&wt.test(e)||Ei.test(e)&&!(t&&/^\s*data:/i.test(e)&&!wt.test(e))}function De(e,t=new Set,n=0,i=false,r=false){if(typeof e=="string"){Ne(e,i,r)&&c("UNSAFE_VALUE");return}if(!(e===null||typeof e!="object")){(n>8||t.has(e))&&c("MANIFEST_INVALID"),t.add(e);try{if(Array.isArray(e)){for(let o of e)De(o,t,n+1);return}M(e)||c("MANIFEST_INVALID");for(let[o,s]of Object.entries(e))De(s,t,n+1,i&&n===0&&(o==="name"||o==="description"),r);}finally{t.delete(e);}}}function G(e,t){let n=e[t];return typeof n!="string"&&c("MANIFEST_INVALID"),n}function B(e,t,n){let i=e[t];return (!Number.isSafeInteger(i)||i<n)&&c("MANIFEST_INVALID"),i}function Qe(e){return gi.test(e)||c("MANIFEST_INVALID"),e}function se(e){return Ii.test(e)||c("TOKEN_INVALID"),e}function Fi(e){return Bt.test(e)||c("MANIFEST_INVALID"),e}function vi(e){M(e)||c("MANIFEST_INVALID");let t={};for(let[n,i]of Object.entries(e)){let r=Fi(n);M(i)||c("MANIFEST_INVALID");let o=i.type;if(o==="text"){N(i,["type","maxLength"]),t[r]={type:o,maxLength:B(i,"maxLength",1)};continue}if(o==="text-list"){N(i,["type","max","itemMaxLength"]),t[r]={type:o,max:B(i,"max",0),itemMaxLength:B(i,"itemMaxLength",1)};continue}if(o==="step-list"){N(i,["type","min","max","labelMaxLength","detailMaxLength"]);let s=B(i,"min",0),a=B(i,"max",1);s>a&&c("MANIFEST_INVALID"),t[r]={type:o,min:s,max:a,labelMaxLength:B(i,"labelMaxLength",1),detailMaxLength:B(i,"detailMaxLength",1)};continue}typeof o=="string"&&c("SCHEMA_TYPE_UNSUPPORTED"),c("MANIFEST_INVALID");}return t}function ji(e,t,n){let i=e[t];(!i||i.type!==n)&&c("MANIFEST_INVALID");}function Te(e,t,n){let i=G(e,"field");return Bt.test(i)||c("MANIFEST_INVALID"),ji(t,i,n),i}function Hi(e,t){M(e)||c("MANIFEST_INVALID");let n=e.primitive;switch(typeof n!="string"&&c("MANIFEST_INVALID"),Vi.includes(n)||c("PRIMITIVE_UNKNOWN"),n){case "card-shell":return N(e,["primitive"]),{primitive:n};case "meta-banner":return N(e,["primitive","badgeToken","noticeToken"]),{primitive:n,badgeToken:se(G(e,"badgeToken")),noticeToken:se(G(e,"noticeToken"))};case "heading":return N(e,["primitive","field"]),{primitive:n,field:Te(e,t,"text")};case "labeled-text":return N(e,["primitive","titleToken","field","variant"]),e.variant!=="callout"&&c("MANIFEST_INVALID"),{primitive:n,titleToken:se(G(e,"titleToken")),field:Te(e,t,"text"),variant:"callout"};case "step-flow":return N(e,["primitive","titleToken","field"]),{primitive:n,titleToken:se(G(e,"titleToken")),field:Te(e,t,"step-list")};case "text-list":{N(e,["primitive","titleToken","field"],["emptyToken","hideWhenEmpty"]);let i={primitive:n,titleToken:se(G(e,"titleToken")),field:Te(e,t,"text-list")};return T(e,"emptyToken")&&(i.emptyToken=se(G(e,"emptyToken"))),T(e,"hideWhenEmpty")&&(typeof e.hideWhenEmpty!="boolean"&&c("MANIFEST_INVALID"),i.hideWhenEmpty=e.hideWhenEmpty),i}}return c("MANIFEST_INVALID")}function Bi(e,t){return Array.isArray(e)||c("MANIFEST_INVALID"),e.map(n=>Hi(n,t))}function L(e="v2 manifest exceeds a contract limit"){return c("LIMIT_EXCEEDED",e)}function v(e="initial state is not projection-safe"){return c("INITIAL_STATE_INVALID",e)}function xt(e,t){return (typeof e!="string"||e.length===0||e.length>4096||e.trim().length===0||Ci.test(e)||ki.test(e))&&c("MANIFEST_INVALID",`${t} is invalid`),(Ne(e,true,true)||Ti.test(e)||Pi.test(e)||Di.test(e))&&c("UNSAFE_VALUE",`${t} contains an unsafe value`),e}function et(e,t){return (typeof e!="string"||!oe.test(e))&&c("MANIFEST_INVALID",`${t} is invalid`),e}function zi(e){return (typeof e!="string"||!Je.test(e)||e==="*"||e==="all")&&c("MANIFEST_INVALID","action capability is invalid"),e}function zt(e){return (typeof e!="string"||!xi.test(e))&&c("MANIFEST_INVALID","resource hash is invalid"),e}function tt(e,t=new Set,n=0){if(typeof e=="string"){e.length>4096&&L("v2 manifest string is too long");return}if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){Number.isFinite(e)||c("MANIFEST_INVALID","v2 manifest contains a non-finite number");return}(e===void 0||typeof e=="function"||typeof e=="bigint")&&c("MANIFEST_INVALID","v2 manifest contains a non-JSON value"),typeof e!="object"&&c("MANIFEST_INVALID"),n>8&&L("v2 manifest nesting is too deep"),t.has(e)&&c("MANIFEST_INVALID","v2 manifest contains a cycle"),t.add(e);try{if(Array.isArray(e)){e.length>128&&L("v2 manifest array is too long");for(let i of e)tt(i,t,n+1);return}M(e)||c("MANIFEST_INVALID","v2 manifest contains a non-plain object");for(let i of Object.values(e))tt(i,t,n+1);}finally{t.delete(e);}}}function Gi(e){return (typeof e!="string"||e.length>4096||!de.test(e))&&(typeof e=="string"&&e.length>4096&&L("projection path is too long"),c("MANIFEST_INVALID","projection paths must be canonical exact paths")),e.split(".").some(n=>re(n))&&c("MANIFEST_INVALID","projection paths cannot address reserved state keys"),e}function Gt(e){M(e)||c("MANIFEST_INVALID","projection policy must be an object"),N(e,["allow"]),Array.isArray(e.allow)||c("MANIFEST_INVALID","projection allow must be an array"),e.allow.length>128&&L("projection allowlist is too long");let t=[],n=new Set;for(let i of e.allow){let r=Gi(i);n.has(r)&&c("MANIFEST_INVALID","projection allowlist contains a duplicate path"),n.add(r),t.push(r);}return {allow:t}}function ae(e,t,n=Number.MAX_SAFE_INTEGER){return (!Number.isSafeInteger(e)||e<0||e>n)&&c("MANIFEST_INVALID",`${t} is invalid`),e}function Ct(e,t){return (typeof e!="number"||!Number.isFinite(e))&&c("MANIFEST_INVALID",`${t} is invalid`),e}function nt(e,t=0,n=new Set){if(typeof e=="string")return (e.length>4096||Ne(e))&&c("UNSAFE_VALUE","schema enum contains an unsafe string"),e;if(e===null||typeof e=="boolean")return e;if(typeof e=="number")return Number.isFinite(e)||c("MANIFEST_INVALID","schema enum contains a non-finite number"),e;(t>8||typeof e!="object"||e===void 0)&&L("schema enum is too deep"),n.has(e)&&c("MANIFEST_INVALID","schema enum contains a cycle"),n.add(e);try{if(Array.isArray(e))return e.length>128&&L("schema enum array is too long"),e.map(r=>nt(r,t+1,n));M(e)||c("MANIFEST_INVALID","schema enum contains a non-plain object");let i={};for(let[r,o]of Object.entries(e))re(r)&&c("MANIFEST_INVALID","schema enum contains a reserved key"),i[r]=nt(o,t+1,n);return i}finally{n.delete(e);}}function $i(e,t){if(e===void 0)return;Array.isArray(e)||c("MANIFEST_INVALID","schema required must be an array"),e.length>64&&L("schema required list is too long");let n=[],i=new Set;for(let r of e)(typeof r!="string"||!de.test(r))&&c("MANIFEST_INVALID","schema required contains an invalid key"),r.length>4096&&L("schema required key is too long"),i.has(r)&&c("MANIFEST_INVALID","schema required contains a duplicate key"),t&&!Object.prototype.hasOwnProperty.call(t,r)&&c("MANIFEST_INVALID","schema required references an undeclared property"),i.add(r),n.push(r);return n}function Wi(e,t){let n=t?de:Ee;return e.length>4096&&L("schema property name is too long"),(!n.test(e)||e.split(".").some(i=>re(i)))&&c("MANIFEST_INVALID","schema property name is invalid"),e}function it(e,t=0,n=false){M(e)||c("MANIFEST_INVALID","action inputSchema must be an object"),t>8&&L("action inputSchema is too deep");let i=e.type;i!=="object"&&i!=="string"&&i!=="number"&&i!=="integer"&&i!=="boolean"&&i!=="array"&&i!=="null"&&(typeof i=="string"&&c("SCHEMA_TYPE_UNSUPPORTED","action inputSchema type is unsupported"),c("MANIFEST_INVALID","action inputSchema type is required"));let r=["type","enum"];i==="string"&&r.push("minLength","maxLength"),i==="array"&&r.push("minItems","maxItems","items"),i==="object"&&r.push("minProperties","maxProperties","properties","required","additionalProperties"),(i==="number"||i==="integer")&&r.push("minimum","maximum"),N(e,["type"],r.filter(a=>a!=="type"));let o={type:i};if(T(e,"enum")&&(Array.isArray(e.enum)||c("MANIFEST_INVALID","schema enum must be an array"),e.enum.length>128&&L("schema enum is too long"),o.enum=e.enum.map(a=>nt(a))),i==="string"&&(T(e,"minLength")&&(o.minLength=ae(e.minLength,"schema minLength",4096)),T(e,"maxLength")&&(o.maxLength=ae(e.maxLength,"schema maxLength",4096)),o.minLength!==void 0&&o.maxLength!==void 0&&o.minLength>o.maxLength&&c("MANIFEST_INVALID","schema string length bounds are inverted")),(i==="number"||i==="integer")&&(T(e,"minimum")&&(o.minimum=Ct(e.minimum,"schema minimum")),T(e,"maximum")&&(o.maximum=Ct(e.maximum,"schema maximum")),o.minimum!==void 0&&o.maximum!==void 0&&o.minimum>o.maximum&&c("MANIFEST_INVALID","schema numeric bounds are inverted")),i==="array"&&(T(e,"minItems")&&(o.minItems=ae(e.minItems,"schema minItems",128)),T(e,"maxItems")&&(o.maxItems=ae(e.maxItems,"schema maxItems",128)),o.minItems!==void 0&&o.maxItems!==void 0&&o.minItems>o.maxItems&&c("MANIFEST_INVALID","schema array length bounds are inverted"),T(e,"items")&&(o.items=it(e.items,t+1,false))),i==="object"){let a;if(T(e,"properties")){M(e.properties)||c("MANIFEST_INVALID","schema properties must be an object");let l=Object.entries(e.properties);l.length>64&&L("schema properties are too many"),a={};for(let[u,d]of l){let f=Wi(u,n);a[f]=it(d,t+1,false);}o.properties=a;}T(e,"minProperties")&&(o.minProperties=ae(e.minProperties,"schema minProperties",64)),T(e,"maxProperties")&&(o.maxProperties=ae(e.maxProperties,"schema maxProperties",64)),o.minProperties!==void 0&&o.maxProperties!==void 0&&o.minProperties>o.maxProperties&&c("MANIFEST_INVALID","schema object property bounds are inverted");let p=$i(e.required,a);p!==void 0&&(o.required=p),T(e,"additionalProperties")&&(e.additionalProperties!==false&&c("MANIFEST_INVALID","schema additionalProperties must be false"),o.additionalProperties=false);}let s=JSON.stringify(o);return (s===void 0||Buffer.byteLength(s,"utf8")>65536)&&L("action inputSchema subtree is too large"),o}function Ki(e){let t=it(e,0,true);return (t.type!=="object"||!t.properties)&&c("MANIFEST_INVALID","action inputSchema must declare object properties"),t}function Ji(e){if(M(e)||c("MANIFEST_INVALID","action backend must be an object"),e.type==="core"){N(e,Ui);let t=e.handler;return (typeof t!="string"||!Xe.test(t))&&c("MANIFEST_INVALID","core backend handler is invalid"),{type:"core",handler:t}}if(e.type==="skill"){N(e,Ri),(!Array.isArray(e.command)||e.command.length===0||e.command.length>16)&&c("MANIFEST_INVALID","skill backend command is invalid");let t=[];for(let n of e.command)(typeof n!="string"||n.length===0||n.length>256||!Ye.test(n))&&c("MANIFEST_INVALID","skill backend command token is invalid"),t.push(n);return {type:"skill",command:t}}c("MANIFEST_INVALID","action backend type is unsupported");}function Xi(e){M(e)||c("MANIFEST_INVALID","action must be an object"),N(e,Si,Li);let t=et(e.actionId,"actionId"),n=zi(e.capability),i=e.mutation;typeof i!="boolean"&&c("MANIFEST_INVALID","action mutation must be boolean");let r=Ki(e.inputSchema),o=Gt(e.resultProjection),s=Ji(e.backend),a;if(T(e,"confirmation")){let p=e.confirmation;p!=="none"&&p!=="native"&&c("MANIFEST_INVALID","action confirmation is invalid"),a=p;}return a==="none"&&(s.type!=="core"||s.handler!=="sqlite.browse"||n!=="sqlite.read"||i!==true)&&c("MANIFEST_INVALID","none confirmation is only allowed for sqlite.browse read mutations"),{actionId:t,capability:n,mutation:i,inputSchema:r,resultProjection:o,backend:s,...a===void 0?{}:{confirmation:a}}}function Yi(e){return M(e)||c("INITIAL_STATE_INVALID","initialState must be an object"),N(e,Oi,wi),e.path!=="ui/state.json"&&c("MANIFEST_INVALID","initialState path is not fixed"),T(e,"hash")?{path:"ui/state.json",hash:zt(e.hash)}:{path:"ui/state.json"}}function qi(e,t){De(e,new Set,0,true,true),tt(e),M(e)||c("MANIFEST_INVALID"),N(e,Ni,Mi),e.manifestVersion!==2&&c("MANIFEST_INVALID");let n=et(e.pluginId,"pluginId"),i=et(e.definitionId,"definitionId"),r=B(e,"version",1),o=xt(e.name,"name"),s=xt(e.description,"description"),a;T(e,"icon")&&((typeof e.icon!="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(e.icon))&&c("MANIFEST_INVALID","icon is invalid"),a=e.icon);let p;T(e,"tone")&&((typeof e.tone!="string"||!qe.includes(e.tone))&&c("MANIFEST_INVALID","tone is invalid"),p=e.tone),e.entry!=="ui/index.html"&&c("MANIFEST_INVALID","entry path is not fixed");let l;T(e,"entryHash")&&(l=zt(e.entryHash));let u;T(e,"initialState")&&(u=Yi(e.initialState));let d;T(e,"usage")&&(e.usage!=="card"&&e.usage!=="window"&&c("MANIFEST_INVALID","usage is invalid"),d=e.usage);let f;T(e,"detailPanel")&&(typeof e.detailPanel!="boolean"&&c("MANIFEST_INVALID","detailPanel is invalid"),f=e.detailPanel);let A;if(T(e,"displayModes")){((d??Y)!==Y||!Array.isArray(e.displayModes)||e.displayModes.length===0)&&c("MANIFEST_INVALID","displayModes are only valid for window Apps");let S=new Set(["inline","floating","focused"]);(new Set(e.displayModes).size!==e.displayModes.length||e.displayModes.some(R=>typeof R!="string"||!S.has(R)))&&c("MANIFEST_INVALID","displayModes are invalid"),A=e.displayModes;}(d??Y)===Y&&f!==void 0&&c("MANIFEST_INVALID","detailPanel is card-only");let I=t.mode??"local";I!=="local"&&I!=="installed"&&I!=="published"&&c("MANIFEST_INVALID","manifest mode is invalid"),I!=="local"&&l===void 0&&c("MANIFEST_INVALID","installed manifests require entryHash"),I!=="local"&&u!==void 0&&u.hash===void 0&&c("MANIFEST_INVALID","installed manifests require initialState.hash"),(!Array.isArray(e.surfaces)||e.surfaces.length===0)&&c("MANIFEST_INVALID","surfaces are invalid"),e.surfaces.length>2&&L("surfaces exceed the v2 limit");let D=[],z=new Set;for(let S of e.surfaces)(typeof S!="string"||!Ze.includes(S))&&c("MANIFEST_INVALID","surface is unsupported"),z.has(S)&&c("MANIFEST_INVALID","surfaces contain a duplicate"),z.add(S),D.push(S);M(e.size)||c("MANIFEST_INVALID","size must be an object"),N(e.size,["height"]);let F=B(e.size,"height",1);F>720&&L("size.height exceeds the v2 limit");let m=Gt(e.stateProjection);Array.isArray(e.actions)||c("MANIFEST_INVALID","actions must be an array"),e.actions.length>32&&L("actions exceed the v2 limit");let g=[],j=new Set;for(let S of e.actions){let R=Xi(S);if(j.has(R.actionId)&&c("MANIFEST_INVALID","actions contain a duplicate actionId"),R.backend.type==="core"&&R.backend.handler==="state.set"){R.mutation||c("MANIFEST_INVALID","state.set actions must be mutations");for(let x of Object.keys(R.inputSchema.properties))m.allow.includes(x)||c("MANIFEST_INVALID","state.set input paths must be projection-allowed");}j.add(R.actionId),g.push(R);}return {manifestVersion:2,pluginId:n,definitionId:i,version:r,name:o,description:s,...a===void 0?{}:{icon:a},...p===void 0?{}:{tone:p},entry:"ui/index.html",...l===void 0?{}:{entryHash:l},...u===void 0?{}:{initialState:u},...d===void 0?{}:{usage:d},...f===void 0?{}:{detailPanel:f},...A===void 0?{}:{displayModes:A},surfaces:D,size:{height:F},stateProjection:m,actions:g}}function Zi(e){let t={},n={};for(let o of e.actions){t[o.actionId]={capabilities:[o.capability],inputKeys:Object.keys(o.inputSchema.properties??{}),resultProjection:o.resultProjection,...o.confirmation===void 0?{}:{confirmation:o.confirmation}};let s=o.backend.type==="core"&&(o.backend.handler==="state.set"||o.backend.handler==="sqlite.browse");n[o.actionId]={actionId:o.actionId,mutation:o.mutation,backend:o.backend,launchPolicy:s?"allowed":"denied",...s?{}:{denialCode:"EXEC_DENIED"}};}let i={id:e.definitionId,version:e.version,renderer:"sandbox-html",...e.usage===void 0?{}:{usage:e.usage},...e.detailPanel===void 0?{}:{detailPanel:e.detailPanel},...e.displayModes===void 0?{}:{displayModes:e.displayModes},surfaces:e.surfaces,stateProjection:e.stateProjection,actions:t},r={entry:{path:"ui/index.html",...e.entryHash===void 0?{}:{hash:e.entryHash}},...e.initialState===void 0?{}:{initialState:e.initialState}};return {manifest:e,definition:i,handlers:n,resources:r}}function rt(e,t,n,i){if(typeof e=="string")return (e.length>4096||Ne(e))&&v("state contains an unsafe string"),e;if(e===null||typeof e=="boolean")return e;if(typeof e=="number")return Number.isFinite(e)||v("state contains a non-finite number"),e;(e===void 0||typeof e!="object"||typeof e=="function"||typeof e=="bigint")&&v("state contains a non-JSON value"),n>8&&v("state is too deep"),t.has(e)&&v("state contains a cycle"),t.add(e);try{let r;if(Array.isArray(e))e.length>128&&v("state array is too long"),r=e.map(s=>rt(s,t,n+1,65536));else {M(e)||v("state contains a non-plain object");let s={};for(let[a,p]of Object.entries(e))(a.length>4096||!Ee.test(a)||re(a))&&(a.length>4096&&v("state key is too long"),v("state contains a reserved or invalid key")),s[a]=rt(p,t,n+1,65536);r=s;}let o=JSON.stringify(r);return (o===void 0||Buffer.byteLength(o,"utf8")>i)&&v("state subtree is too large"),r}finally{t.delete(e);}}function st(e){M(e)||v("initial state must be a JSON object");let t=rt(e,new Set,0,65536);return (t===null||Array.isArray(t)||typeof t!="object")&&v(),t}function Qi(e,t={}){De(e),M(e)||c("MANIFEST_INVALID"),N(e,bi),e.manifestVersion!==1&&c("MANIFEST_INVALID");let n=Qe(G(e,"pluginId")),i=Qe(G(e,"definitionId")),r=B(e,"version",1),o=B(e,"primitiveSet",1),s=t.supportedPrimitiveSet??Ai;(!Number.isSafeInteger(s)||s<1)&&c("MANIFEST_INVALID"),o>s&&c("PRIMITIVE_SET_UNSUPPORTED"),M(e.activation)||c("MANIFEST_INVALID"),N(e.activation,["kind","language"]),e.activation.kind!=="fenced-code"&&c("MANIFEST_INVALID");let a=Qe(G(e.activation,"language")),p=vi(e.schema),l=Bi(e.layout,p);return {manifestVersion:1,pluginId:n,definitionId:i,version:r,primitiveSet:o,activation:{kind:"fenced-code",language:a},schema:p,layout:l}}function er(e,t={}){return M(e)||c("MANIFEST_INVALID"),e.manifestVersion===2?qi(e,t):Qi(e,t)}function ee(e,t={}){try{return er(e,t)}catch(n){if(n instanceof V)throw n;return c("MANIFEST_INVALID")}}function at(e,t={}){let n=ee(e,t);return n.manifestVersion===2?Zi(n):n}var Kt="SKILL.md",or=/^---\s*\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;function Jt(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function sr(e){return e.isDirectory()||e.isSymbolicLink()}function Qt(e){try{return U.existsSync(e)&&U.statSync(e).isDirectory()}catch{return false}}function pt(e){let t;try{t=U.readFileSync(e,"utf8");}catch{return {frontmatter:{},readable:false,valid:false,hasFrontmatter:false}}let n=t.match(or);if(!n)return {frontmatter:{},readable:true,valid:true,hasFrontmatter:false};try{let i=Cn.load(n[1]??"");if(!Jt(i))return {frontmatter:{},readable:!0,valid:!1,hasFrontmatter:!0};let r=Jt(i.metadata)?i.metadata:void 0;return {frontmatter:{...typeof i.name=="string"?{name:i.name}:{},...typeof(r?.version??i.version)=="string"?{version:r?.version??i.version}:{},...typeof i.description=="string"?{description:i.description}:{}},readable:!0,valid:!0,hasFrontmatter:!0}}catch{return {frontmatter:{},readable:true,valid:false,hasFrontmatter:true}}}function ar(e){return [w.join(e,Kt),w.join(e,"skill",Kt)]}function Xt(e,t){if(!Qt(e))return null;for(let n of ar(e)){if(!U.existsSync(n))continue;let r=pt(n).frontmatter;return {name:r.name??t,...r.version===void 0?{}:{version:r.version},...r.description===void 0?{}:{description:r.description},skillMdPath:n,dir:e}}return null}function Yt(e){try{return U.readdirSync(e,{withFileTypes:!0}).filter(sr)}catch{return []}}function qt(e,t,n){!e||t.has(e.name)||(t.add(e.name),n.push(e));}function en(e){let t=[],n=new Set;for(let i of e)if(Qt(i))for(let r of Yt(i)){if(r.name.startsWith("@")){let o=w.join(i,r.name);for(let s of Yt(o))qt(Xt(w.join(o,s.name),s.name),n,t);continue}qt(Xt(w.join(i,r.name),r.name),n,t);}return t.sort((i,r)=>i.name.localeCompare(r.name))}var pr=/^[0-9a-f]{64}$/;function Se(e){let n=e.renderer!==void 0||e.surfaces!==void 0||e.stateProjection!==void 0||e.usage!==void 0||e.detailPanel!==void 0||e.displayModes!==void 0||Object.values(e.actions).some(r=>r.resultProjection!==void 0)?{id:e.id,version:e.version,renderer:e.renderer,surfaces:e.surfaces,stateProjection:e.stateProjection,...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=ie(n);return St.createHash("sha256").update(Z(i)).digest("hex")}function lt(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"||!pr.test(e.sourceHash)))throw new b("DEFINITION_UNSUPPORTED","UI definition source hash is invalid");if(!/^[0-9a-f]{64}$/.test(e.hash)||Se(e)!==e.hash)throw new b("DEFINITION_UNSUPPORTED","UI definition hash is invalid");for(let[t,n]of Object.entries(e.actions)){if(!t||!Array.isArray(n.capabilities)||n.capabilities.some(i=>!lr(i)))throw new b("DEFINITION_UNSUPPORTED","UI action declaration is invalid");if(n.confirmation!==void 0&&n.confirmation!=="none"&&n.confirmation!=="native")throw new b("DEFINITION_UNSUPPORTED","UI action confirmation is invalid");if(n.inputKeys&&(!Array.isArray(n.inputKeys)||n.inputKeys.some(i=>typeof i!="string"||!i)))throw new b("DEFINITION_UNSUPPORTED","UI action input declaration is invalid");n.resultProjection&&tn(n.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(t=>!t||t.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(t=>t!=="inline"&&t!=="floating"&&t!=="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");e.stateProjection&&tn(e.stateProjection);}function tn(e){if(!Array.isArray(e.allow)||e.allow.some(t=>!/^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)*$/.test(t)))throw new b("DEFINITION_UNSUPPORTED","UI projection policy is invalid")}function lr(e){return e.length>0&&e.length<=128&&e!=="*"&&e!=="all"&&!/[/*]/.test(e)}var q=class extends Error{constructor(n,i=n){super(i);this.code=n;}code;name="McpAppContractError"};function dt(e,t=e){throw new q(e,t)}var nn=["crewx_app_terminal_connect","crewx_app_html_viewer_open"];var ft=8*1024*1024;new Set(nn);var dr=4;function ut(e,t=0){try{let n=ie(e,t);return n.type!==void 0&&n.type!=="object"&&dt("TOOL_INVALID","MCP App inputSchema must describe an object"),n}catch(n){if(n instanceof q)throw n;dt("TOOL_INVALID","MCP App inputSchema must be projection-safe JSON");}}function rn(e){if(e.length===0)return ut({type:"object",properties:{},additionalProperties:false});let t=e.map(i=>i.actionId),n=new Map;for(let i of e)n.set(i.actionId,ut(i.inputSchema));return ut(ur(t,n),dr)}function ur(e,t){let n=e.map(i=>({type:"object",properties:{actionId:{type:"string",const:i},input:t.get(i)??{type:"object"}},required:["actionId","input"],additionalProperties:false}));return Object.freeze({type:"object",oneOf:Object.freeze(n),properties:Object.freeze({actionId:Object.freeze({type:"string",enum:Object.freeze([...e])}),input:Object.freeze({type:"object"})}),required:Object.freeze(["actionId","input"]),additionalProperties:false})}var h=class extends Error{constructor(n){super(n);this.code=n;}code;name="AppDiscoveryFsError"},ln=U.constants.O_NOFOLLOW,Ir=U.constants.O_NONBLOCK,gr=U.constants.O_RDONLY|(ln??0)|(Ir??0);function W(e){let t=typeof e=="object"&&e!==null&&"code"in e?String(e.code):"";return t==="ENOENT"?new h("NOT_FOUND"):t==="ELOOP"?new h("PATH_ESCAPED"):t==="EFBIG"||t==="EOVERFLOW"?new h("LIMIT_EXCEEDED"):t==="EACCES"||t==="EPERM"||t==="ENOTDIR"?new h("READ_DENIED"):new h("READ_DENIED")}function mr(e){if(typeof e!="string"||e.length===0||!w.isAbsolute(e))throw new h("READ_DENIED")}function on(e){if(typeof e!="string"||w.isAbsolute(e)||/[\\\u0000]/.test(e))throw new h("PATH_ESCAPED");if(e==="")return [];let t=e.split("/");if(t.some(n=>n.length===0||n==="."||n===".."))throw new h("PATH_ESCAPED");return t}function Le(e,t){let n=w.relative(e,t);return n===""||n!==".."&&!n.startsWith(`..${w.sep}`)&&!w.isAbsolute(n)}function Ue(e){return {dev:e.dev,ino:e.ino,size:e.size,mtimeNs:e.mtimeNs,ctimeNs:e.ctimeNs}}function It(e,t){return e.dev===t.dev&&e.ino===t.ino}function dn(e,t){return It(e,t)&&e.size===t.size&&e.mtimeNs===t.mtimeNs&&e.ctimeNs===t.ctimeNs}async function sn(e){mr(e);let t,n;try{t=await promises.realpath(e),n=await promises.stat(t,{bigint:!0});}catch(i){throw W(i)}if(!n.isDirectory())throw new h("READ_DENIED");return {realRoot:t,identity:Ue(n)}}async function hr(e,t,n){if(n.length<2||n[0]!=="apps"&&n[0]!=="skills")return;let i,r;try{if(i=w.resolve(e,n[0],n[1]),r=await promises.realpath(i),!(await promises.stat(r,{bigint:!0})).isDirectory())throw new h("READ_DENIED")}catch(o){throw o instanceof h?o:W(o)}if(!Le(t,r))throw new h("PATH_ESCAPED");return r}async function an(e,t,n,i){let r,o,s;try{r=await promises.lstat(e,{bigint:!0}),o=await promises.realpath(e),s=await promises.stat(o,{bigint:!0});}catch(a){throw W(a)}if(!Le(t,o)||n!==void 0&&!Le(n,o))throw new h("PATH_ESCAPED");if(!r.isFile()||!s.isFile())throw new h("READ_DENIED");if(!It(i,r)||!It(i,s)||i.dev!==s.dev)throw new h("PATH_ESCAPED")}async function yt(e,t){let n,i;try{n=await promises.realpath(e),i=await promises.stat(n,{bigint:!0});}catch{throw new h("PATH_ESCAPED")}if(n!==t.realRoot||!dn(t.identity,Ue(i)))throw new h("PATH_ESCAPED")}function _r(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 Re=class{async listDirectory(t,n){let i=on(n),r=await sn(t),o=w.resolve(t,...i),s,a;try{s=await promises.realpath(o),a=await promises.stat(s,{bigint:!0});}catch(p){let l=W(p);if(l.code==="NOT_FOUND")return [];throw l}if(!Le(r.realRoot,s)||!a.isDirectory())throw new h("PATH_ESCAPED");try{let p=await promises.readdir(s,{withFileTypes:!0,encoding:"utf8"});return await yt(t,r),p.map(_r)}catch(p){let l=W(p);if(l.code==="NOT_FOUND")return [];throw l}}async readdir(t,n){return this.listDirectory(t,n)}async readDirectory(t,n){return this.listDirectory(t,n)}async readVerifiedFile(t,n,i){if(!Number.isSafeInteger(i)||i<0)throw new h("READ_DENIED");if(ln===void 0)throw new h("UNSUPPORTED");let r=on(n),o=await sn(t),s=w.resolve(t,...r),a=w.relative(t,s);if(a===".."||a.startsWith(`..${w.sep}`)||w.isAbsolute(a))throw new h("PATH_ESCAPED");let p;try{p=await promises.open(s,gr);}catch(l){throw W(l)}try{let l;try{let I=await p.stat({bigint:!0});l=Ue(I);}catch(I){throw W(I)}if(l.size>BigInt(i))throw new h("LIMIT_EXCEEDED");if(l.size>BigInt(Number.MAX_SAFE_INTEGER))throw new h("LIMIT_EXCEEDED");await yt(t,o);let u=await hr(t,o.realRoot,r);await an(s,o.realRoot,u,l);let d=new Uint8Array(new ArrayBuffer(Number(l.size))),f=0;for(;f<d.byteLength;){let I;try{I=(await p.read(d,f,d.byteLength-f,f)).bytesRead;}catch(D){throw W(D)}if(I<=0)throw new h("IDENTITY_CHANGED");f+=I;}let A;try{let I=await p.stat({bigint:!0});A=Ue(I);}catch(I){throw W(I)}if(!dn(l,A))throw new h("IDENTITY_CHANGED");return await an(s,o.realRoot,u,A),await yt(t,o),new Uint8Array(d)}finally{await p.close().catch(()=>{});}}async readFileVerified(t,n,i){return this.readVerifiedFile(t,n,i)}},un=new Re;var mt="crewx_local_app_";function Er(e){if(typeof e!="string"||!oe.test(e))throw new TypeError("pluginId must be a safe UI plugin identifier");let t=`${mt}${e}`.length+7<=128?e:`hash_${St.createHash("sha256").update(e,"utf8").digest("hex")}`;return {read:`${mt}${t}_read`,action:`${mt}${t}_action`}}var _t=["apps","skills"],Tr=new TextDecoder("utf-8",{fatal:true});function Et(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;try{let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}catch{return false}}function fn(e){return typeof e=="string"&&oe.test(e)?e:void 0}function Pr(e,t){return t.length===0||t==="."||t===".."||/[\\/\u0000]/.test(t)?e:`${e}/${t}`}function Dr(e){return e.length>0&&e!=="."&&e!==".."&&!/[\\/\u0000]/.test(e)}function hn(e,t){let n=new TextEncoder().encode(e),i=new TextEncoder().encode(t),r=Math.min(n.byteLength,i.byteLength);for(let o=0;o<r;o+=1){let s=n[o]-i[o];if(s!==0)return s}return n.byteLength-i.byteLength}function br(e){if(typeof e=="string")return {name:e,kind:"directory"};if(e===null||typeof e!="object")return null;let t=e;if(typeof t.name!="string")return null;if(t.kind==="file"||t.kind==="directory"||t.kind==="symlink"||t.kind==="other")return {name:t.name,kind:t.kind};if(t.type==="file"||t.type==="directory"||t.type==="symlink"||t.type==="other")return {name:t.name,kind:t.type};let n=t.isDirectory;if(typeof n=="function"&&n.call(e))return {name:t.name,kind:"directory"};let i=t.isSymbolicLink;if(typeof i=="function"&&i.call(e))return {name:t.name,kind:"symlink"};let r=t.isFile;return typeof r=="function"&&r.call(e)?{name:t.name,kind:"file"}:{name:t.name,kind:"other"}}function Nr(e){if(e instanceof Uint8Array)return new Uint8Array(e);if(e instanceof ArrayBuffer)return new Uint8Array(e.slice(0));if(Array.isArray(e)&&e.every(t=>Number.isInteger(t)&&t>=0&&t<=255))return Uint8Array.from(e);throw new TypeError("filesystem port returned an invalid byte array")}function _n(e){return Tr.decode(e)}function En(e){return JSON.parse(_n(e))}function Mr(e){if(!Et(e))return;let t=fn(e.pluginId);if(!t)return;let n=fn(e.definitionId),i=e.version,r=n&&Number.isSafeInteger(i)&&i>=1?`${n}\0${String(i)}`:void 0;return {pluginId:t,...r===void 0?{}:{definitionKey:r}}}function Sr(e){let t=En(e);return {value:t,identity:Mr(t)}}function Tt(e,t,n,i){let r={code:e,...i===void 0?{}:{pluginId:i},source:t,relativePath:n};return Object.freeze(r)}function yn(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 te(e){if(e instanceof h)return yn(e.code);if(e!==null&&typeof e=="object"&&"code"in e){let t=e.code;if(typeof t=="string")return yn(t)}}function me(e,t){return e==="PATH_ESCAPED"||e==="IDENTITY_CHANGED"||e==="TOCTOU"?"PATH_ESCAPED":e==="LIMIT_EXCEEDED"?"LIMIT_EXCEEDED":t==="manifest"&&e==="NOT_FOUND"?"MANIFEST_MISSING":t==="entry"?"ENTRY_INVALID":t==="initial"?"INITIAL_STATE_INVALID":"MANIFEST_INVALID"}function An(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 Tn("UiPluginValidationError",e.code)}}function Tn(e,t){throw new Error(`Unmapped ${e} code: ${String(t)}`)}function ht(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 Tn("McpAppContractError",e)}}function In(e,t){let n=t();return Number.isFinite(n)&&Number.isFinite(e)&&n-e<=5e3}function Lr(){return globalThis.performance?.now()??Date.now()}function ce(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let t of Object.values(e))ce(t);return Object.freeze(e)}function gn(e){return Object.freeze(Array.from(e))}function Ur(e,t,n){let i=St.createHash("sha256"),r=new TextEncoder().encode(Z(e)),o=s=>{let a=new Uint8Array(8);new DataView(a.buffer).setBigUint64(0,BigInt(s)),i.update(a);};return o(r.byteLength),i.update(r),o(t.byteLength),i.update(t),o(n.byteLength),i.update(n),i.digest("hex")}function Rr(e,t){let n={...e.definition,sourceHash:t},i={...n,hash:Se(n)};try{lt(i);}catch{throw new V("MANIFEST_INVALID","normalized definition is invalid")}return i}function Or(e){return e.actions.some(t=>t.backend.type!=="core"||t.backend.handler!=="state.set"&&t.backend.handler!=="sqlite.browse")}function wr(e){if(typeof e.readVerifiedFile=="function")return e.readVerifiedFile;if(typeof e.readFileVerified=="function")return e.readFileVerified}function xr(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 xe(e,t,n,i){let r=wr(e);if(!r)throw new h("READ_DENIED");return Nr(await r.call(e,t,n,i))}async function Cr(e,t,n){let i=xr(e);if(!i)throw new h("READ_DENIED");let r=await i.call(e,t,n);if(!Array.isArray(r))throw new h("READ_DENIED");return r.map(br).filter(o=>o!==null)}function kr(e){let t=[];for(let n of [e.reserved,e.builtin])n&&t.push(n);return e.builtins&&"listMcpApps"in e.builtins?t.push(mn(e.builtins)):e.builtins&&t.push(e.builtins),e.builtinCatalog&&t.push(mn(e.builtinCatalog)),t.push({...e.reservedAppIds===void 0?{}:{appIds:e.reservedAppIds},...e.reservedDefinitionIds===void 0?{}:{definitionIds:e.reservedDefinitionIds},...e.reservedToolNames===void 0?{}:{toolNames:e.reservedToolNames}}),t}function mn(e){let t=[],n=[],i=[];for(let r of e.listMcpApps())typeof r.appId=="string"&&t.push(r.appId),r.definition&&typeof r.definition.id=="string"&&n.push(r.definition.id);for(let r of e.listMcpAppTools())typeof r.name=="string"&&i.push(r.name);return {appIds:t,definitionIds:n,toolNames:i}}function ge(e,t){e.diagnostic||(e.diagnostic=Tt(t,e.source,e.relativePath,e.identity?.pluginId));}function Vr(e){let t=new Map,n=new Map;for(let i of e){if(i.identity?.pluginId){let r=t.get(i.identity.pluginId)??[];r.push(i),t.set(i.identity.pluginId,r);}if(i.identity?.definitionKey){let r=n.get(i.identity.definitionKey)??[];r.push(i),n.set(i.identity.definitionKey,r);}}for(let i of [...t.values(),...n.values()]){let r=i.filter(o=>o.source==="apps");if(r.length>0){if(r.length>1)for(let o of r)ge(o,"DUPLICATE_ID");for(let o of i.filter(s=>s.source==="skills"))ge(o,"DUPLICATE_ID");continue}if(i.length>1)for(let o of i)ge(o,"DUPLICATE_ID");}}function Fr(e,t){let n=new Set,i=new Set,r=new Set;for(let o of kr(t)){for(let s of o.appIds??[])typeof s=="string"&&n.add(s);for(let s of o.definitionIds??[])typeof s=="string"&&i.add(s);for(let s of o.toolNames??[])typeof s=="string"&&r.add(s);}for(let o of e){let s=o.candidate;if(!s)continue;if(n.has(s.pluginId)||i.has(s.definitionId)){ge(o,"RESERVED_ID");continue}[s.toolNames.read,s.toolNames.action].filter(p=>p!==void 0).some(p=>r.has(p))&&ge(o,"DUPLICATE_ID");}}function vr(e){return [...e].sort((t,n)=>{let i=_t.indexOf(t.source)-_t.indexOf(n.source);return i!==0?i:hn(t.relativePath,n.relativePath)})}function P(e,t){e.diagnostic=Tt(t,e.source,e.relativePath,e.identity?.pluginId);}async function jr(e,t,n,i){if(i.byteLength>262144){P(n,"LIMIT_EXCEEDED");return}let r;try{r=Sr(i);}catch{P(n,"MANIFEST_INVALID");return}if(n.identity=r.identity,Et(r.value)&&r.value.builtinOnly===true){P(n,"RESERVED_ID");return}let o;try{let _=ee(r.value,{mode:"local"});if(_.manifestVersion!==2)throw new V("MANIFEST_INVALID","workspace App requires v2");o=_;}catch(_){if(_ instanceof V){P(n,An(_));return}if(_ instanceof q){P(n,ht(_.code));return}if(Et(_)&&typeof _.code=="string"){P(n,ht(_.code));return}throw _}if(n.identity={pluginId:o.pluginId,definitionKey:`${o.definitionId}\0${String(o.version)}`},o.actions.length>0)try{rn(o.actions.map(_=>({actionId:_.actionId,inputSchema:_.inputSchema})));}catch(_){if(_ instanceof q){P(n,ht(_.code));return}throw _}let s=`${n.relativePath}/ui/index.html`,a;try{a=await xe(t,e,s,ft);}catch(_){P(n,me(te(_),"entry"));return}if(a.byteLength>ft){P(n,"LIMIT_EXCEEDED");return}let p;try{p=_n(a);}catch{P(n,"ENTRY_INVALID");return}if(a.byteLength===0||p.length===0){P(n,"ENTRY_INVALID");return}let l=St.createHash("sha256").update(a).digest("hex");if(o.entryHash!==void 0&&o.entryHash!==l){P(n,"ENTRY_INVALID");return}let u={},d,f;if(o.initialState!==void 0){let _=`${n.relativePath}/ui/state.json`;try{d=await xe(t,e,_,65536);}catch(O){P(n,me(te(O),"initial"));return}if(d.byteLength>65536){P(n,"LIMIT_EXCEEDED");return}try{let O=En(d),ii=st(O);u=ie(ii),We(u);}catch{P(n,"INITIAL_STATE_INVALID");return}if(f=St.createHash("sha256").update(d).digest("hex"),o.initialState.hash!==void 0&&o.initialState.hash!==f){P(n,"INITIAL_STATE_INVALID");return}}let A={...o,entryHash:l,...o.initialState===void 0?{}:{initialState:{path:"ui/state.json",hash:f}}},I=at(A),D=Ur(A,a,d??new Uint8Array),z;try{z=Rr(I,D);}catch(_){if(_ instanceof V){P(n,An(_));return}throw _}let F=Er(o.pluginId),m=o.actions.length===0?{read:F.read}:F,g=ce(I),j=ce(A),S=ce(z),R=ce({...I.handlers}),x=gn(a),$=d===void 0?void 0:gn(d),Rt=Object.freeze({entry:Object.freeze({path:"ui/index.html",hash:l,bytes:x}),...$===void 0?{}:{initialState:Object.freeze({path:"ui/state.json",hash:f,bytes:$})}}),_e={appId:o.pluginId,pluginId:o.pluginId,definitionId:o.definitionId,version:o.version,source:n.source,relativePath:n.relativePath,manifest:j,normalized:g,name:o.name,description:o.description,...o.icon===void 0?{}:{icon:o.icon},...o.tone===void 0?{}:{tone:o.tone},definition:S,handlers:R,resources:Rt,html:p,entryBytes:x,entryHash:l,initialState:ce(u),...$===void 0?{}:{initialStateBytes:$},...f===void 0?{}:{initialStateHash:f},sourceHash:D,toolNames:Object.freeze(m)};n.candidate=Object.freeze(_e),Or(o)&&P(n,"EXEC_DENIED");}async function Hr(e,t,n){try{return await xe(t,e,`${n.relativePath}/ui-plugin.json`,262144)}catch(i){if(te(i)==="NOT_FOUND")return;P(n,me(te(i),"manifest"));return}}function Br(e,t){let n=vr(e);Vr(n);let i=Object.freeze(n.filter(s=>s.candidate!==void 0&&s.diagnostic===void 0).map(s=>s.candidate)),r=Object.freeze(n.filter(s=>s.diagnostic!==void 0).map(s=>s.diagnostic)),o={apps:i,diagnostics:r,complete:t===void 0,...t===void 0?{}:{incompleteReason:t}};return Object.defineProperty(o,"candidates",{configurable:false,enumerable:false,get:()=>i}),Object.freeze(o)}function zr(e){if(e===null||typeof e!="object"&&typeof e!="function")return false;let t=e;return typeof t.readVerifiedFile=="function"||typeof t.readFileVerified=="function"||typeof t.listDirectory=="function"||typeof t.readDirectory=="function"||typeof t.readdir=="function"}function Gr(e,t){if(zr(e))return {fs:e,options:{}};let n=e??t??{};return {fs:n.filesystem??n.fileSystem??n.fs??un,options:n}}async function Pn(e,t,n){if(typeof e!="string"||e.length===0)throw new TypeError("workspaceRoot must be explicit");let{fs:i,options:r}=Gr(t,n),o=r.clock??Lr,s=o(),a=[],p=0,l;for(let u of _t){let d;try{d=await Cr(i,e,u);}catch(A){if(te(A)==="NOT_FOUND")continue;a.push({source:u,name:"",relativePath:u,diagnostic:Tt(me(te(A),"manifest"),u,u)});continue}let f=d.filter(A=>A.kind==="directory"||A.kind==="symlink").filter(A=>Dr(A.name)).map(A=>({source:u,name:A.name,relativePath:Pr(u,A.name)})).sort((A,I)=>hn(A.relativePath,I.relativePath));for(let A of f){let I={...A};a.push(I);let D;if(u==="skills"&&(D=await Hr(e,i,I),D===void 0))continue;if(p>=64){P(I,"LIMIT_EXCEEDED");continue}if(A.relativePath.split("/").length-1>2){P(I,"LIMIT_EXCEEDED");continue}if(l!==void 0||!In(s,o)){P(I,"LIMIT_EXCEEDED"),l="time_limit";continue}if(p+=1,D===void 0)try{D=await xe(i,e,`${I.relativePath}/ui-plugin.json`,262144);}catch(F){P(I,me(te(F),"manifest"));continue}await jr(e,i,I,D),I.diagnostic===void 0&&p<64&&!In(s,o)&&(l="time_limit");}}return Fr(a,r),Br(a,l)}var Wr=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/;function ke(e){let t="screenHash"in e?e.screenHash:void 0,i=("skillHash"in e?e.skillHash:void 0)??(e.relativePath!==void 0&&e.fileBytes!==void 0?Kr(e.relativePath,e.fileBytes):void 0);if(t!==void 0&&i!==void 0){let r=JSON.stringify({screenHash:t,skillHash:i});return St.createHash("sha256").update(r,"utf8").digest("hex")}if(t!==void 0)return t;if(i!==void 0)return i;throw new TypeError("App definition hash input must contain a screenHash or skill bytes")}function Kr(e,t){let n=new TextEncoder().encode(Ve(e)),i=Jr(t),r=new Uint8Array(n.byteLength+1+i.byteLength);return r.set(n,0),r[n.byteLength]=0,r.set(i,n.byteLength+1),St.createHash("sha256").update(r).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(t=>Number.isInteger(t)&&t>=0&&t<=255))return Uint8Array.from(e);throw new TypeError("fileBytes must be UTF-8 text or bytes")}function Ve(e){if(typeof e!="string"||e.length===0||w.isAbsolute(e)||/[\\\u0000]/.test(e))throw new TypeError("relative path must be package-relative");let t=e.split("/").filter(n=>n.length>0&&n!==".").join("/");if(!t||t.split("/").some(n=>n===".."))throw new TypeError("relative path must stay inside the package");return t}function Ce(e,t){let n=new TextEncoder().encode(e),i=new TextEncoder().encode(t),r=Math.min(n.byteLength,i.byteLength);for(let o=0;o<r;o+=1){let s=n[o]-i[o];if(s!==0)return s}return n.byteLength-i.byteLength}function Nn(e,t){let n=w.relative(e,t).split(w.sep).join("/");return !n||n===".."||n.startsWith("../")||w.isAbsolute(n)?null:Ve(n)}function Xr(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 Mn(e){return Object.freeze({packageRoot:e})}function Yr(e){return Object.freeze({id:e.definition.id,version:e.definition.version,hash:e.definition.hash,usage:e.definition.usage??Y,...e.definition.detailPanel===void 0?{}:{detailPanel:e.definition.detailPanel},...e.definition.displayModes===void 0?{}:{displayModes:e.definition.displayModes}})}function Sn(e){return {capabilities:Object.freeze([...e]),origin:"local",ownership:"unknown",shareability:"unknown",sharingAvailability:"unavailable"}}function qr(e,t){let n=e.candidate,i=t?["screen","skill"]:["screen"],r=Yr(n),o=ke(t?{screenHash:r.hash,skillHash:t.skillHash}:{screenHash:r.hash}),s=n.description||t?.skill.description||"",a=String(n.version),p={appId:n.pluginId,name:n.name,description:s,version:a,...Sn(i),definition:r,...t===void 0?{}:{skillName:t.skill.name},localDefinitionRef:Mn(e.packageRoot),definitionHash:o};return {packageRoot:e.packageRoot,source:n.source,appId:p.appId,capabilities:i,summary:Object.freeze(p)}}function Zr(e){let t=Qr(e.skill.name),n={appId:t,name:e.skill.name,description:e.skill.description??"",...e.skill.version===void 0?{}:{version:e.skill.version},...Sn(["skill"]),skillName:e.skill.name,localDefinitionRef:Mn(e.packageRoot),definitionHash:ke({skillHash:e.skillHash})};return {packageRoot:e.packageRoot,source:e.source,appId:t,capabilities:["skill"],summary:Object.freeze(n)}}function Qr(e){return `skill.${e.replace(/^@/,"").replace(/\//g,".").replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,122)||"unnamed"}`}function C(e,t,n,i){return Object.freeze({code:e,source:t,relativePath:eo(n),...i===void 0?{}:{appId:i}})}function eo(e){if(typeof e!="string"||e.length===0||w.isAbsolute(e)||/[\\\u0000]/.test(e))return "<unknown>";let t=e.split("/").filter(n=>n.length>0&&n!==".").join("/");return t.split("/").some(n=>n==="..")?"<unknown>":t}function to(e){return C(e.code,e.source,e.relativePath,e.pluginId)}function no(e,t){let n=Nn(e,t.dir);if(!n)return {diagnostic:C("PATH_ESCAPED","node_modules","node_modules")};let i=Xr(n);if(!i)return {diagnostic:C("PATH_ESCAPED","node_modules",n)};let r=pt(t.skillMdPath);if(!r.readable)return {diagnostic:C("SKILL_READ_FAILED",i,n)};if(!r.valid)return {diagnostic:C("SKILL_INVALID",i,n)};let o=io(t.dir,t.skillMdPath);if(!o)return {diagnostic:C("PATH_ESCAPED",i,n)};try{let s=new Uint8Array(U.readFileSync(t.skillMdPath));return {skill:t,packageRoot:n,relativeSkillPath:o,skillHash:ke({relativePath:o,fileBytes:s}),source:i}}catch{return {diagnostic:C("SKILL_READ_FAILED",i,n)}}}function io(e,t){let n=w.relative(e,t).split(w.sep).join("/");try{return Ve(n)}catch{return null}}function ro(e){if(!Wr.test(e.appId))return {diagnostic:C("BUILTIN_INVALID","builtin",`builtin/${e.appId||"unknown"}`)};let t=e.definition===void 0?void 0:{id:e.definition.id,version:e.definition.version,hash:e.definition.hash,usage:e.definition.usage??Y,...e.definition.detailPanel===void 0?{}:{detailPanel:e.definition.detailPanel},...e.definition.displayModes===void 0?{}:{displayModes:e.definition.displayModes}},n=t?.hash??St.createHash("sha256").update(JSON.stringify({appId:e.appId,name:e.name,description:e.description}),"utf8").digest("hex"),i={appId:e.appId,name:e.name,description:e.description,...t===void 0?{}:{version:String(t.version),definition:t},capabilities:["screen"],origin:"builtin",ownership:"unknown",shareability:"forbidden",sharingAvailability:"unavailable",definitionHash:n};return {source:"builtin",appId:e.appId,summary:Object.freeze(i)}}function oo(e){return e.builtinCatalog}function so(e){let t=e.packageRoot??e.relativePath??e.packageRootPath;if(t===void 0)return null;try{return Ve(t)}catch{return null}}function ao(e){let t=e.marketplaceContentId;return typeof t=="string"&&t.length>0?t:void 0}function co(e,t,n){let i=t.installed??[],r=new Map;for(let s of i){let a=so(s);if(!a){n.push(C("INSTALLED_IDENTITY_MISMATCH","installed","installed"));continue}let p=r.get(a);if(p&&JSON.stringify(p)!==JSON.stringify(s)){n.push(C("INSTALLED_IDENTITY_MISMATCH","installed",a));continue}r.set(a,s);}let o=new Map;for(let s of e)s.packageRoot!==void 0&&o.set(s.packageRoot,s);for(let[s,a]of r){let p=o.get(s);if(!p){n.push(C("INSTALLED_MISSING","installed",s,a.appId));continue}let l=ao(a);if(!l){n.push(C("INSTALLED_CONTENT_ID_MISSING","installed",s,a.appId));continue}if(a.appId!==void 0&&a.appId!==p.appId||a.definitionHash!==void 0&&a.definitionHash!==p.summary.definitionHash){n.push(C("INSTALLED_IDENTITY_MISMATCH","installed",s,a.appId));continue}let u={...p.summary,origin:"installed",...a.slug===void 0?{}:{slug:a.slug},marketplaceContentId:l},d=e.indexOf(p);d>=0&&(e[d]={...p,summary:Object.freeze(u)});}}function po(e,t){let n=new Map;for(let r of e){let o=n.get(r.appId)??[];o.push(r),n.set(r.appId,o);}let i=new Set;for(let r of n.values())if(!(r.length<2))for(let o of r)i.add(o),t.push(C("DUPLICATE_ID",o.source,o.packageRoot??`builtin/${o.appId}`,o.appId));return e.filter(r=>!i.has(r))}function lo(e,t){return e.filter(n=>!(n.code==="MANIFEST_MISSING"&&t.has(n.relativePath))).map(to)}function uo(e){return e.filesystem}function fo(e,t){let n=uo(e);return {...n===void 0?{}:{filesystem:n},...t===void 0?{}:{builtinCatalog:t}}}async function Ln(e,t={}){if(typeof e!="string"||e.length===0)throw new TypeError("workspaceRoot must be explicit");let n=oo(t),i=await Pn(e,fo(t,n)),r=[w.join(e,"skills"),w.join(e,"node_modules"),w.join(e,"apps")],o=[],s=[],a=[],p=new Set;for(let m of r)for(let g of en([m])){let j=Nn(e,g.dir);(j===null||!p.has(j))&&(a.push(g),j!==null&&p.add(j));}for(let m of a){let g=no(e,m);"diagnostic"in g?o.push(g.diagnostic):s.push(g);}let l=new Map;for(let m of i.apps??i.candidates??[])l.set(m.relativePath,{candidate:m,packageRoot:m.relativePath});let u=new Map(s.map(m=>[m.packageRoot,m])),d=[];for(let m of l.values()){let g=qr(m,u.get(m.packageRoot));d.push({packageRoot:g.packageRoot,source:g.source,appId:g.appId,summary:g.summary});}let f=new Set(l.keys());for(let m of s){if(f.has(m.packageRoot))continue;let g=Zr(m);d.push({packageRoot:g.packageRoot,source:g.source,appId:g.appId,summary:g.summary});}let A=[...lo(i.diagnostics,new Set(s.map(m=>m.packageRoot))),...o],I=[];if(n)for(let m of n.listMcpApps()){let g=ro(m);"diagnostic"in g?A.push(g.diagnostic):I.push(g);}let D=po([...d,...I],A);co(D,t,A);let z=D.map(m=>m.summary).sort((m,g)=>Ce(m.appId,g.appId)),F=[...A].sort((m,g)=>Ce(m.relativePath,g.relativePath)||Ce(m.code,g.code)||Ce(m.appId??"",g.appId??""));return Object.freeze({items:Object.freeze(z),diagnostics:Object.freeze(F)})}function yo(e){let t=r=>r.replace(/[.+^${}()|[\]\\]/g,"\\$&"),i=e.split("/").map(r=>r==="**"?".*":r.split("*").map(t).join("[^/]*"));return new RegExp(`^${i.join("\\/")}$`)}function pe(e,t){try{return yo(t).test(e)}catch{return false}}function Fe(e,...t){let n=e.split("/");if(n.length<t.length)return false;let i=n.length-t.length;return t.every((r,o)=>pe(n[i+o],r))}function Ao(e,t){return e.split("/").some(n=>pe(n,t))}var Un=[{label:".env*",test:e=>pe(e,".env*")},{label:".git/",test:(e,t,n)=>n&&e===".git"},{label:"memory/",test:(e,t,n)=>n&&e==="memory"},{label:"*.key",test:e=>pe(e,"*.key")},{label:"*.pem",test:e=>pe(e,"*.pem")},{label:"auth.json",test:e=>e==="auth.json"},{label:"node_modules/",test:(e,t,n)=>n&&e==="node_modules"},{label:"conversations/",test:(e,t,n)=>n&&e==="conversations"},{label:".crewx/threads/",test:(e,t,n)=>n&&Fe(t,".crewx","threads")},{label:".crewx/crewx.db",test:(e,t,n)=>!n&&Fe(t,".crewx","crewx.db")},{label:".crewx/*.log",test:(e,t,n)=>!n&&Fe(t,".crewx","*.log")},{label:".crewx/publish/",test:(e,t,n)=>n&&Fe(t,".crewx","publish")},{label:".crewx/",test:(e,t)=>Ao(t,".crewx")}];function ve(e,t,n){for(let i of Un)if(i.test(e,t,n))return i.label;return null}function Nt(e){let t=[],n=[];function i(r,o,s){let a;try{a=U__namespace.readdirSync(r,{withFileTypes:!0});}catch{return}a.sort((p,l)=>p.name.localeCompare(l.name));for(let p of a){let l=o?`${o}/${p.name}`:p.name,u=w__namespace.join(r,p.name);if(p.isSymbolicLink()){let d;try{d=U__namespace.statSync(u);}catch{n.push({path:l,rule:"symlink"});continue}if(d.isDirectory()){n.push({path:l,rule:s??"symlink-dir"});continue}let f=s??ve(p.name,l,false);f?n.push({path:l,rule:f}):n.push({path:l,rule:"symlink"});continue}if(p.isDirectory()){let d=s??ve(p.name,l,true);i(u,l,d);continue}if(p.isFile()){let d=s??ve(p.name,l,false);d?n.push({path:l,rule:d}):t.push(l);}}}return i(e,"",null),t.sort(),n.sort((r,o)=>r.path<o.path?-1:r.path>o.path?1:0),{included:t,excluded:n}}var Io=[{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 go(e){return e.includes(0)}function Mt(e,t,n){let i=[];for(let r of t){let o=w__namespace.join(e,r),s;try{let p=n?.get(r);s=p===void 0?U__namespace.readFileSync(o):Buffer.from(p);}catch{continue}if(go(s))continue;s.toString("utf8").split(/\r\n|\r|\n/).forEach((p,l)=>{for(let{rule:u,regex:d}of Io)d.test(p)&&i.push({path:r,line:l+1,rule:u});});}return i}var K=class extends Error{constructor(n,i){super(`publish: [${n}]${i?` ${i}`:""}`);this.code=n;}code;name="PublishError"};function y(e,t){return new K(e,t)}var xn=/^[a-z0-9-]+$/,mo=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/,ho=/^[A-Za-z_][A-Za-z0-9_]*$/;function _o(e){let t=w__namespace.join(e,"crewx.yaml");if(!U__namespace.existsSync(t))return {};let n;try{n=Cn__namespace.load(U__namespace.readFileSync(t,"utf8"));}catch{return {}}if(!n||typeof n!="object")return {};let i=n.metadata;if(!i||typeof i!="object")return {};let r=i;return {name:typeof r.name=="string"?r.name:void 0,version:typeof r.version=="string"?r.version:void 0,description:typeof r.description=="string"?r.description:void 0,requiredEnv:r.requiredEnv,crewxMinVersion:typeof r.crewxMinVersion=="string"?r.crewxMinVersion:void 0}}function Eo(e){return St__namespace.createHash("sha256").update(e).digest("hex")}function kn(e){let t;try{t=U__namespace.lstatSync(e);}catch{throw y("PACKAGE_FILE_INVALID",`file is not readable: ${w__namespace.basename(e)}`)}if(t.isSymbolicLink())throw y("PACKAGE_SYMLINK","symlink content is not publishable");if(!t.isFile())throw y("PACKAGE_FILE_INVALID","only regular files are publishable");return St__namespace.createHash("sha256").update(new Uint8Array(U__namespace.readFileSync(e))).digest("hex")}function To(e,t){let n=new TextEncoder().encode(e),i=new TextEncoder().encode(t),r=Math.min(n.byteLength,i.byteLength);for(let o=0;o<r;o+=1){let s=n[o]-i[o];if(s!==0)return s}return n.byteLength-i.byteLength}function Vn(e){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||w__namespace.posix.isAbsolute(e)||e.split("/").some(t=>t===".."||t.length===0))throw y("PACKAGE_PATH_TRAVERSAL","manifest file path must be a non-empty POSIX relative path")}function Po(e){if(!/^(?:apps|skills)\/[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(e))throw y("APP_PACKAGE_ROOT_INVALID","packageRoot must be apps/<safe-id> or skills/<safe-id>")}function Fn(e){if(!mo.test(e))throw new Error(`publish: invalid version "${e}" \u2014 must be semver (e.g. 1.0.0)`)}function vn(e,t,n={}){let i=_o(e),r=i.name??w__namespace.basename(e);if(!xn.test(r))throw new Error(`publish: invalid name "${r}" \u2014 must match ${xn} (lowercase letters, numbers, hyphen only)`);let o=n.version??i.version;if(!o)throw new Error("publish: version is required \u2014 set crewx.yaml metadata.version or pass opts.version");Fn(o);let s=Array.isArray(i.requiredEnv)?i.requiredEnv:[],a=[];for(let u of s){if(typeof u!="string"||!ho.test(u))throw new Error(`publish: requiredEnv must contain names only (no values), got "${String(u)}"`);a.push(u);}let p=t.map(u=>(Vn(u),{path:u,sha256:kn(w__namespace.join(e,u))})).sort((u,d)=>u.path<d.path?-1:u.path>d.path?1:0),l={name:r,version:o,type:"template",description:i.description??"",files:p,requiredEnv:a};return i.crewxMinVersion&&(l.crewxMinVersion=i.crewxMinVersion),l}function Do(e){let t=e.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"");if(!t)throw y("APP_PACKAGE_ROOT_INVALID","appId cannot produce a marketplace name");return t}function jn(e,t){if(Po(t.packageRoot),!t.version)throw new Error("publish: version is required for App publishing \u2014 pass opts.version");if(Fn(t.version),typeof t.description!="string")throw new Error("publish: App description must be a string");let n=[...new Set(t.capabilities)].sort();if(n.length===0||n.some(s=>s!=="screen"&&s!=="skill"))throw new Error("publish: App capabilities must contain screen or skill");let i=`${t.packageRoot}/`;if(n.includes("screen")){if(typeof t.definitionId!="string"||t.definitionId.length===0)throw y("APP_UI_MANIFEST_INVALID","screen App manifests require definitionId");for(let s of ["ui-plugin.json","ui/index.html"])if(!t.includedFiles.includes(`${i}${s}`))throw y("APP_UI_MANIFEST_INVALID",`screen App is missing ${s}`)}if(n.includes("skill")&&!t.includedFiles.includes(`${i}SKILL.md`))throw y("APP_SKILL_MISSING","skill capability requires package-root SKILL.md");let r=new Set,o=t.includedFiles.map(s=>{if(Vn(s),!s.startsWith(i))throw y("PACKAGE_PATH_TRAVERSAL","App manifest file is outside packageRoot");let a=t.generatedFiles?.get(s);return a!==void 0&&r.add(s),{path:s,sha256:a===void 0?kn(w__namespace.join(e,s)):Eo(a),...a===void 0?{}:{generated:true}}}).sort((s,a)=>To(s.path,a.path));if(r.size>0&&(r.size!==1||!r.has(`${i}ui-plugin.json`)))throw new Error("publish: only the generated ui-plugin.json may be present in an App package");return {manifestVersion:1,name:Do(t.appId),version:t.version,type:"app",description:t.description,appId:t.appId,...t.definitionId===void 0?{}:{definitionId:t.definitionId},...t.definitionHash===void 0?{}:{definitionHash:t.definitionHash},capabilities:n,packageRoot:t.packageRoot,files:o,requiredEnv:[]}}function Hn(e){return St__namespace.createHash("sha256").update(e).digest("hex")}function Wn(e,t){if(typeof t!="string"||t.length===0||t.includes("\\")||t.includes("\0")||w__namespace.posix.isAbsolute(t)||t.split("/").some(r=>r===".."||r.length===0))throw y("PACKAGE_PATH_TRAVERSAL","archive paths must be non-empty POSIX relative paths");let n=w__namespace.resolve(e),i=w__namespace.resolve(n,...t.split("/"));if(i!==n&&!i.startsWith(`${n}${w__namespace.sep}`))throw y("PACKAGE_PATH_TRAVERSAL","archive path escaped its root");return i}function Bn(e,t){let n=Wn(e,t),i;try{i=U__namespace.lstatSync(n);}catch{throw y("PACKAGE_FILE_INVALID","manifest file is missing")}if(i.isSymbolicLink())throw y("PACKAGE_SYMLINK","symlink content is not publishable");if(!i.isFile())throw y("PACKAGE_FILE_INVALID","only regular files are publishable");return new Uint8Array(U__namespace.readFileSync(n))}async function Kn(e,t,n={}){let i=w__namespace.join(e,".crewx","publish");U__namespace.mkdirSync(i,{recursive:true});let r=w__namespace.join(i,`${t.name}-${t.version}.tgz`),o=w__namespace.join(i,`.${t.name}-${t.version}.${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}.tmp.tgz`),s=U__namespace.mkdtempSync(w__namespace.join(zn__namespace.tmpdir(),"crewx-publish-"));try{let a=new Set,p=[];for(let l of t.files){if(a.has(l.path))throw y("PACKAGE_PATH_TRAVERSAL","manifest contains duplicate file paths");a.add(l.path);let u=n.generatedFiles?.get(l.path);if(l.generated===!0&&u===void 0)throw y("PACKAGE_GENERATED_FILE_MISSING","generated manifest file bytes are missing");if(n.sourceFileHashes?.has(l.path)){let A=Bn(e,l.path);if(n.sourceFileHashes.get(l.path)!==Hn(A))throw y("PACKAGE_STAGED_BYTES_MISMATCH","workspace source changed before staging")}let d=u??Bn(e,l.path);if(Hn(d)!==l.sha256)throw y("PACKAGE_STAGED_BYTES_MISMATCH",`staged bytes differ for ${l.path}`);let f=Wn(s,l.path);U__namespace.mkdirSync(w__namespace.dirname(f),{recursive:!0}),U__namespace.writeFileSync(f,new Uint8Array(d)),p.push(l.path);}U__namespace.writeFileSync(w__namespace.join(s,"manifest.json"),JSON.stringify(t,null,2)),await $n__namespace.create({gzip:!0,file:o,cwd:s,portable:!0,noMtime:!0},["manifest.json",...p]),U__namespace.renameSync(o,r);}finally{try{U__namespace.rmSync(o,{force:!0});}catch{}U__namespace.rmSync(s,{recursive:true,force:true});}return r}var le="/api/v1";var Mo=201,So=200,Lo=409,Lt=401,Jn={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 Uo(){return process.env.WI013_FAKE_UPLOAD==="1"}function Ro(e){let t=zlib.gunzipSync(new Uint8Array(e)),n=zlib.gzipSync(new Uint8Array(t),{level:1});if(Buffer.compare(new Uint8Array(n),new Uint8Array(e))===0)throw new Error("publish: [E_MALFORMED] Re-gzipped upload bytes are identical to the original \u2014 tamper is a no-op");return n}function Oo(e){return e.replace(/\/+$/,"")}async function he(e){try{return await e.json()}catch{return null}}function Xn(e,t,n){let i=e;if(!i||i.success!==true||i.data===void 0)throw new Error(`publish: [E_MALFORMED] ${t} response envelope is malformed (expected { success: true, data }) \u2014 HTTP ${n}`);return i.data}function wo(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(typeof t.contentId=="string"&&t.contentId.length>0)return t.contentId;if(!t.data||typeof t.data!="object"||Array.isArray(t.data))return;let n=t.data;return typeof n.contentId=="string"&&n.contentId.length>0?n.contentId:void 0}function xo(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(typeof t.slug=="string"&&t.slug.length>0)return t.slug;if(!t.data||typeof t.data!="object"||Array.isArray(t.data))return;let n=t.data;return typeof n.slug=="string"&&n.slug.length>0?n.slug:void 0}function Yn(e,t){if(!e||typeof e!="object"||Array.isArray(e))return;let n=e,i=n.data&&typeof n.data=="object"&&!Array.isArray(n.data)?n.data:void 0,r=[n.code,n.message,i?.code,i?.message];for(let o of r){if(typeof o!="string"||!Object.prototype.hasOwnProperty.call(Jn,o))continue;let s=o,a=s==="APP_NAME_CONFLICT"?`marketplace name is already in use: ${t}`:void 0;return y(Jn[s],a)}}async function Co(e){if(!e.baseUrl.trim())throw new Error("publish: [E_ENV_MISSING] Marketplace base URL is required");if(!e.accessToken.trim())throw new Error("publish: [E_AUTH_EXPIRED] A valid bearer token is required");let t=Oo(e.baseUrl),n=e.accessPolicy??"private",i=e.manifest.name,r=e.manifest.type==="app"?e.manifest:void 0,o=r!==void 0,s=r?.appId,a;try{a=await fetch(`${t}${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:n,...s===void 0?{}:{appId:s}})});}catch{throw new Error("publish: [E_NETWORK] Submit request failed (network)")}let p=await he(a),l=wo(p),u=xo(p),d=o&&u!==void 0?u:i,f;if(a.status===Mo)f="created";else if(o&&a.status===So){if(l===void 0)throw y("PUBLISH_CONTENT_ID_MISSING","App republish did not return an opaque contentId");f="existing";}else if(a.status===Lo){if(o)throw Yn(p,i)??y("APP_NAME_CONFLICT",`marketplace name is already in use: ${i}`);f="existing";}else throw a.status===Lt?new Error("publish: [E_AUTH_EXPIRED] Authentication is expired or missing \u2014 please log in again (HTTP 401)"):new Error(`publish: [E_HTTP] Submit request failed \u2014 HTTP ${a.status}`);let A="not-needed",I=null;if(f==="existing"&&!o){let x;try{x=await fetch(`${t}${le}/publisher/items`,{method:"GET",headers:{Authorization:`Bearer ${e.accessToken}`}});}catch{throw new Error("publish: [E_NETWORK] Publisher items request failed (network)")}let $=await he(x);if(x.status!==200)throw new Error(`publish: [E_HTTP] Publisher items request failed \u2014 HTTP ${x.status}`);let _e=Xn($,"publisher items",x.status)?.items;if(!Array.isArray(_e))throw new Error(`publish: [E_MALFORMED] Publisher items response is malformed (expected data.items[]) \u2014 HTTP ${x.status}`);let _=_e.find(O=>!O||typeof O!="object"?false:O.slug===i);if(!_||typeof _.version!="string")throw new Error(`publish: [E_MALFORMED] Publisher items response does not contain slug "${i}" \u2014 HTTP ${x.status}`);if(I=_.version,I!==e.manifest.version){let O;try{O=await fetch(`${t}${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(!O.ok)throw await he(O),O.status===Lt?new Error(`publish: [E_AUTH_EXPIRED] Authentication is expired or missing \u2014 please log in again (HTTP ${O.status})`):O.status===403?new Error(`publish: [E_FORBIDDEN] Version update is forbidden; only the item owner can update an existing item (HTTP ${O.status})`):new Error(`publish: [E_HTTP] Version update failed \u2014 HTTP ${O.status}`);A="applied";}}let D=U__namespace.readFileSync(e.tgzPath),z=Uo()?Ro(D):D,F=new FormData;F.set("archive",new Blob([new Uint8Array(z)],{type:"application/gzip"}),`${d}-${e.manifest.version}.tgz`);let m=o&&l!==void 0?l:i,g;try{g=await fetch(`${t}${le}/publisher/items/${encodeURIComponent(m)}/upload`,{method:"POST",headers:{Authorization:`Bearer ${e.accessToken}`},body:F});}catch{throw new Error("publish: [E_NETWORK] Upload request failed (network)")}if(g.status===Lt)throw new Error("publish: [E_AUTH_EXPIRED] Authentication is expired or missing \u2014 please log in again (HTTP 401)");if(!g.ok){let x=await he(g);if(o){let $=Yn(x,d);if($)throw $}throw new Error(`publish: [E_HTTP] Upload request failed \u2014 HTTP ${g.status}`)}let j=await he(g),S=Xn(j,"upload",g.status),R=typeof S.contentId=="string"&&S.contentId.length>0?S.contentId:l;if(o&&R===void 0)throw y("PUBLISH_CONTENT_ID_MISSING","App upload did not return an opaque contentId");return {slug:d,version:e.manifest.version,...R===void 0?{}:{contentId:R},artifactChecksum:S.artifactChecksum,artifactSizeBytes:S.artifactSizeBytes,submitOutcome:f,versionUpdate:A,serverVersionBefore:I}}var ko=1e4,Vo=100*1024*1024;function Ut(e){return St__namespace.createHash("sha256").update(e).digest("hex")}function Fo(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function He(e,t){if(!t||t.includes("\\")||t.includes("\0")||w__namespace.posix.isAbsolute(t)||t.split("/").some(o=>o===".."||o.length===0))throw y("PACKAGE_PATH_TRAVERSAL","workspace file path is not a safe relative path");let n=w__namespace.resolve(e,...t.split("/")),i=w__namespace.resolve(e);if(n!==i&&!n.startsWith(`${i}${w__namespace.sep}`))throw y("PACKAGE_PATH_TRAVERSAL","workspace file path escaped the workspace root");let r;try{r=U__namespace.lstatSync(n);}catch{throw y("PACKAGE_FILE_INVALID",`workspace file is missing: ${t}`)}if(r.isSymbolicLink())throw y("PACKAGE_SYMLINK",`symlink is not publishable: ${t}`);if(!r.isFile())throw y("PACKAGE_FILE_INVALID",`not a regular file: ${t}`);return new Uint8Array(U__namespace.readFileSync(n))}function Be(e,t){return e===t||e.startsWith(`${t}/`)}function vo(e,t){return e.path<t.path?-1:e.path>t.path?1:e.rule.localeCompare(t.rule)}function Zn(e,t,n){let i=e??t;if(!Number.isSafeInteger(i)||i<=0)throw new K("PACKAGE_SIZE_LIMIT",`${n} must be a positive integer`);return i}function ei(e,t,n,i){let r=Zn(n.maxFileCount??n.maxFiles,ko,"max file count"),o=Zn(n.maxTotalBytes??n.maxBytes,Vo,"max total bytes");if(t.length>r)throw new K("PACKAGE_SIZE_LIMIT",`package exceeds file count limit (${r})`);let s=0;for(let a of t){let p=i?.get(a);if(p!==void 0?s+=p.byteLength:s+=He(e,a).byteLength,s>o)throw new K("PACKAGE_SIZE_LIMIT",`package exceeds byte limit (${o})`)}}function jo(e){return e.appId!==void 0||e.expectedDefinitionHash!==void 0}function Ho(e){let t=e.appId!==void 0,n=e.expectedDefinitionHash!==void 0;if(!t&&n)throw y("APP_ID_REQUIRED","appId is required with expectedDefinitionHash");if(t&&!n)throw y("APP_DEFINITION_HASH_REQUIRED","expectedDefinitionHash is required with appId");if(!t||!n)throw y("APP_ID_REQUIRED")}function Bo(e,t){let n=e.filter(i=>i.appId===t);if(n.length===0)throw y("APP_NOT_FOUND",`no publishable App matches ${t}`);if(n.length!==1)throw y("APP_AMBIGUOUS",`more than one App matches ${t}`);return n[0]}function zo(e){let t=e.localDefinitionRef?.packageRoot;if(!t||!/^(?:apps|skills)\/[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(t))throw y("APP_PACKAGE_ROOT_INVALID","selected App is not rooted in apps/<safe-id> or skills/<safe-id>");return t}function Go(e,t){let n=[];for(let i of e.excluded)n.push(Be(i.path,t)?i:{path:i.path,rule:"out-of-app-scope"});for(let i of e.included)Be(i,t)||n.push({path:i,rule:"out-of-app-scope"});return n.sort(vo)}function $o(e,t,n,i){let r=`${n}/ui-plugin.json`;if(!i.includes(r))throw y("APP_UI_MANIFEST_INVALID","selected screen App has no package ui-plugin.json");let o=He(e,r),s=Ut(o),a;try{a=JSON.parse(Buffer.from(o).toString("utf8"));}catch{throw y("APP_UI_MANIFEST_INVALID","ui-plugin.json is not valid JSON")}let p;try{let f=ee(a,{mode:"local"});if(f.manifestVersion!==2)throw new Error("screen App requires manifestVersion 2");p=f;}catch(f){throw f instanceof V?y("APP_UI_MANIFEST_INVALID",f.code):y("APP_UI_MANIFEST_INVALID")}if(p.pluginId!==t.appId)throw y("APP_DEFINITION_CONFLICT","ui-plugin.json pluginId no longer matches the selected App");let l=`${n}/ui/index.html`;if(!i.includes(l))throw y("APP_UI_MANIFEST_INVALID","screen entry is outside package scope");let u=Ut(He(e,l)),d=JSON.parse(JSON.stringify(a));if(d.entryHash=u,Object.prototype.hasOwnProperty.call(d,"initialState")){let f=d.initialState;if(!Fo(f)||f.path!=="ui/state.json")throw y("APP_INITIAL_STATE_OUT_OF_SCOPE","initialState must reference ui/state.json inside the package");let A=`${n}/ui/state.json`;if(!i.includes(A))throw y("APP_INITIAL_STATE_OUT_OF_SCOPE","initialState reference is outside the selected package");let I=He(e,A);d.initialState={...f,hash:Ut(I)};}try{let f=ee(d,{mode:"published"});return {bytes:new Uint8Array(Buffer.from(Ke(f),"utf8")),sourceHash:s}}catch(f){throw f instanceof V?y("APP_UI_MANIFEST_INVALID",f.code):y("APP_UI_MANIFEST_INVALID")}}async function Wo(e,t){let{included:n,excluded:i}=Nt(e);ei(e,n,t);let r=vn(e,n,{version:t.version}),o=Mt(e,n);return {plan:{manifest:r,included:n,excluded:i,secretFindings:o},archiveOptions:{}}}async function Ko(e,t){Ho(t);let n=await Ln(e),i=Bo(n.items,t.appId);if(i.definitionHash!==t.expectedDefinitionHash)throw y("APP_DEFINITION_CONFLICT",`definitionHash changed for ${t.appId}`);let r=zo(i),o=Nt(e);if(o.excluded.some(A=>Be(A.path,r)&&(A.rule==="symlink"||A.rule==="symlink-dir")))throw y("PACKAGE_SYMLINK","selected App package contains a symlink");let s=o.included.filter(A=>Be(A,r)),a=Go(o,r),p=new Map,l=new Map;if(i.capabilities.includes("screen")){let A=$o(e,i,r,s);p.set(`${r}/ui-plugin.json`,A.bytes),l.set(`${r}/ui-plugin.json`,A.sourceHash);}if(i.capabilities.includes("skill")&&!s.includes(`${r}/SKILL.md`))throw y("APP_SKILL_MISSING","skill capability requires package-root SKILL.md");ei(e,s,t,p);let u={appId:i.appId,version:t.version??"",description:i.description,capabilities:i.capabilities,packageRoot:r,...i.definition?.id===void 0?{}:{definitionId:i.definition.id},definitionHash:i.definitionHash,includedFiles:s,generatedFiles:p},d=jn(e,u),f=Mt(e,s,p);return {plan:{manifest:d,included:s,excluded:a,secretFindings:f},archiveOptions:{generatedFiles:p,sourceFileHashes:l}}}async function ti(e,t){let n=w__namespace.resolve(e);if(jo(t))return Ko(n,t);if(t.expectedDefinitionHash!==void 0)throw y("APP_ID_REQUIRED");return Wo(n,t)}async function nc(e,t={}){return (await ti(e,t)).plan}function Jo(e){let t=e.map(n=>`${n.path}:${n.line} (${n.rule})`).join(", ");throw new K("PUBLISH_SECRET_FINDINGS",`aborted \u2014 secret findings must be resolved before packing: ${t}`)}async function ni(e,t={}){let n=w__namespace.resolve(e),i=await ti(n,t);i.plan.secretFindings.length>0&&Jo(i.plan.secretFindings);let r=await Kn(n,i.plan.manifest,i.archiveOptions);return {manifest:i.plan.manifest,tgzPath:r}}async function ic(e,t={}){return ni(e,t)}async function rc(e,t){let n=await ni(e,t);if(n.manifest.type!=="app")throw new Error("publish: App pack unexpectedly produced a template manifest");return n}
|
|
2
|
+
exports.DEFAULT_PUBLISH_MAX_BYTES=Vo;exports.DEFAULT_PUBLISH_MAX_FILES=ko;exports.EXCLUDE_RULES=Un;exports.MARKETPLACE_API_PREFIX=le;exports.PublishError=K;exports.packApp=rc;exports.packPublish=ni;exports.packTemplate=ic;exports.planPublish=nc;exports.uploadToMarketplace=Co;
|