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