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