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