@crewx/sdk 0.9.0-rc.164 → 0.9.0-rc.166
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/app/app.d.ts +10 -0
- package/dist/app/entry.d.ts +2 -0
- package/dist/app/index.d.ts +6 -0
- package/dist/app/index.js +12 -10
- package/dist/app/job-bridge.child.d.ts +1 -0
- package/dist/app/job-bridge.d.ts +67 -0
- package/dist/app/job-bridge.drain.child.d.ts +1 -0
- package/dist/app/job-bridge.example.d.ts +11 -0
- package/dist/app/job-contract.d.ts +40 -0
- package/dist/app/job-wire.d.ts +149 -0
- package/dist/app/runtime.d.ts +2 -0
- package/dist/app-artifact-policy/check.d.ts +2 -0
- package/dist/app-artifact-policy/contract.d.ts +54 -0
- package/dist/app-artifact-policy/helper.d.ts +15 -0
- package/dist/app-artifact-policy/index.d.ts +3 -0
- package/dist/app-artifact-policy/index.js +18 -0
- package/dist/app-artifact-policy/paths.d.ts +24 -0
- package/dist/app-artifact-policy/scan.d.ts +47 -0
- package/dist/desktop/index.js +3 -3
- package/dist/esm/app/index.js +12 -10
- package/dist/esm/app-artifact-policy/index.js +18 -0
- package/dist/esm/desktop/index.js +3 -3
- package/dist/esm/index.js +234 -232
- package/dist/esm/plugins/index.js +27 -27
- package/dist/esm/process/index.js +1 -1
- package/dist/esm/publish/index.js +2 -2
- package/dist/esm/repository/index.js +30 -30
- package/dist/esm/skills/index.js +2 -2
- package/dist/index.browser.d.ts +4 -0
- package/dist/index.browser.js +4 -4
- package/dist/index.d.ts +10 -2
- package/dist/index.js +240 -238
- package/dist/mcp-app/app-job-bridge.d.ts +30 -0
- package/dist/mcp-app/app-job-bridge.example.d.ts +36 -0
- package/dist/mcp-app/app-job.d.ts +168 -0
- package/dist/mcp-app/index.d.ts +4 -0
- package/dist/mcp-app/skill-backend.d.ts +7 -1
- package/dist/plugins/index.js +20 -20
- package/dist/process/index.d.ts +2 -2
- package/dist/process/index.js +1 -1
- package/dist/process/process-control.d.ts +19 -0
- package/dist/publish/index.js +2 -2
- package/dist/repository/index.js +37 -37
- package/dist/skills/index.js +2 -2
- package/dist/ui-instance/types.d.ts +6 -0
- package/dist/ui-plugin/types.d.ts +4 -1
- package/package.json +7 -1
package/dist/publish/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var xi=require('crypto'),net=require('net'),ee=require('fs'),promises=require('fs/promises'),ce=require('path'),gs=require('js-yaml'),Ds=require('os'),Ss=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 xi__namespace=/*#__PURE__*/_interopNamespace(xi);var ee__namespace=/*#__PURE__*/_interopNamespace(ee);var ce__namespace=/*#__PURE__*/_interopNamespace(ce);var gs__namespace=/*#__PURE__*/_interopNamespace(gs);var Ds__namespace=/*#__PURE__*/_interopNamespace(Ds);var Ss__namespace=/*#__PURE__*/_interopNamespace(Ss);var j=(e,n)=>()=>(e&&(n=e(e=0)),n);var m=j(()=>{});var x,Fn=j(()=>{m();x=class extends Error{constructor(t,i=t,o){super(i);this.code=t;this.currentRevision=o;}code;currentRevision;name="UiRuntimeError"};});function bt(e){return js.test(e)||Vs.test(e)}function ue(){throw new x("INPUT_INVALID","JSON value is not projection-safe")}function $s(e){let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function Nt(e,n,t,i,o,r){if(n>i&&ue(),e===null||typeof e=="string"||typeof e=="boolean")return typeof e=="string"&&(Bs.test(e)||zs.test(e)&&!Js(o,r)||Hs.test(e))&&ue(),e;if(typeof e=="number")return Number.isFinite(e)||ue(),e;(typeof e!="object"||e===void 0||typeof e=="function"||typeof e=="bigint")&&ue();let s=e;t.has(s)&&ue(),t.add(s);try{if(Array.isArray(e))return e.map(c=>Nt(c,n+1,t,i,o,r));$s(s)||ue();let a={};for(let[c,d]of Object.entries(e))bt(c)&&ue(),a[c]=Nt(d,n+1,t,i,[...o,c],r);return a}finally{t.delete(s);}}function fe(e,n=0,t=[]){(!Number.isInteger(n)||n<0||n>Ws)&&ue(),(!Array.isArray(t)||t.some(o=>typeof o!="string"))&&ue();let i=Nt(e,0,new Set,Gs+n,[],t);return (i===null||Array.isArray(i)||typeof i!="object")&&ue(),i}function Qe(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 Js(e,n){if(e.length===0)return false;let t=e.join(".");return n.some(i=>Qe(t,i))}function en(e){try{let n=JSON.stringify(e);return n===void 0&&ue(),n}catch{ue();}}function Dt(e){return Array.isArray(e)?e.map(Dt):e!==null&&typeof e=="object"?Object.fromEntries(Object.keys(e).sort().map(n=>[n,Dt(e[n])])):e}function te(e){return en(Dt(e))}function St(e){return Buffer.byteLength(e,"utf8")}var js,Vs,Bs,Hs,zs,Gs,Ws,Se=j(()=>{m();Fn();js=/(?:proof|token|secret|password|cookie|authorization|private[_-]?key|stack|exception|plugin[_-]?text)/i,Vs=/(?:url|uri|endpoint|path|file(?:name|path)?|cwd|shell|directory|dir|folder)$/i,Bs=/<\/?[A-Za-z][^>]*>/,Hs=/^(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)/,zs=/^(?:https?|file|ftp|ws|wss):\/\//i;Gs=8,Ws=4;});var Vi=j(()=>{m();Se();});var jn,Mt=j(()=>{m();jn=["text/plain","application/json"];});var Bi=j(()=>{m();Mt();});function nn(e){return Xs.has(e)||Ys.test(e)||qs.test(e)}var Hi,Xs,Ys,qs,Vn,An,Ee,Lt,Rt,Ot,wt,Ct,He=j(()=>{m();Hi=["__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"],Xs=new Set(Hi),Ys=/(?:proof|token|secret|password|cookie|authorization|private[_-]?key|stack|exception|plugin[_-]?text)/i,qs=/(?:url|uri|endpoint|path|file(?:name|path)?|cwd|shell|directory|dir|folder)$/i;Vn=/^[A-Za-z0-9_]+$/,An=/^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)*$/,Ee=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,Lt=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/,Rt=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,Ot=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/,wt=["blue","violet","emerald","amber","rose","sky","slate","indigo"],Ct=["inline","panel"];});function Ut(e){return typeof e=="string"&&jn.includes(e)}var zi=j(()=>{m();Mt();He();});function Bn(e){if(!kt(e))return false;let n=Object.keys(e);return !(n.some(t=>t!=="in"&&t!=="out")||n.length===0||Object.hasOwn(e,"in")&&!Zs(e.in)||Object.hasOwn(e,"out")&&!Qs(e.out))}function Zs(e){return kt(e)?Object.keys(e).every(t=>t==="mediaType"||t==="required")&&Object.hasOwn(e,"mediaType")&&Ut(e.mediaType)&&(!Object.hasOwn(e,"required")||typeof e.required=="boolean"):false}function Qs(e){return kt(e)?Object.keys(e).every(t=>t==="mediaType"||t==="range")&&Object.hasOwn(e,"mediaType")&&Ut(e.mediaType)&&(!Object.hasOwn(e,"range")||typeof e.range=="boolean"):false}function kt(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}var xt=j(()=>{m();Bi();zi();new TextDecoder("utf-8",{fatal:true,ignoreBOM:true});});function zn(e){return ea.includes(e)}function $n(e){return Number.isSafeInteger(e)&&e>=Hn.min&&e<=Hn.max}var ea,Hn,$i,vt=j(()=>{m();ea=[5,15,30,60],Hn=Object.freeze({min:15e3,max:6e5,default:3e5}),$i=1;});function pe(e){let t=e.renderer!==void 0||e.surfaces!==void 0||e.stateProjection!==void 0||e.dataPaths!==void 0||e.usage!==void 0||e.detailPanel!==void 0||e.displayModes!==void 0||e.summaryProjection!==void 0||e.legacy!==void 0||Object.values(e.actions).some(o=>o.resultProjection!==void 0)?{id:e.id,version:e.version,...e.renderer===void 0?{}:{renderer:e.renderer},...e.surfaces===void 0?{}:{surfaces:e.surfaces},...e.stateProjection===void 0?{}:{stateProjection:e.stateProjection},...e.dataPaths===void 0?{}:{dataPaths:e.dataPaths},...e.summaryProjection===void 0?{}:{summaryProjection:e.summaryProjection},...e.legacy===void 0?{}:{legacy:e.legacy},...e.usage===void 0?{}:{usage:e.usage},...e.detailPanel===void 0?{}:{detailPanel:e.detailPanel},...e.displayModes===void 0?{}:{displayModes:e.displayModes},...e.sourceHash===void 0?{}:{sourceHash:e.sourceHash},actions:e.actions}:e.sourceHash===void 0?{id:e.id,version:e.version,actions:e.actions}:{id:e.id,version:e.version,sourceHash:e.sourceHash,actions:e.actions},i=fe(t);return xi.createHash("sha256").update(te(i)).digest("hex")}function jt(e){return `${e.id}\0${e.version}`}function ye(e){if(!/^\d+$/.test(String(e.version))||e.version<1||e.id.length<1||e.id.length>128)throw new x("DEFINITION_UNSUPPORTED","UI definition is invalid");if(e.sourceHash!==void 0&&(typeof e.sourceHash!="string"||!ta.test(e.sourceHash)))throw new x("DEFINITION_UNSUPPORTED","UI definition source hash is invalid");if(!/^[0-9a-f]{64}$/.test(e.hash)||pe(e)!==e.hash)throw new x("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=>!oa(i)))throw new x("DEFINITION_UNSUPPORTED","UI action declaration is invalid");if(t.confirmation!==void 0&&t.confirmation!=="none"&&t.confirmation!=="native")throw new x("DEFINITION_UNSUPPORTED","UI action confirmation is invalid");if(t.inputKeys&&(!Array.isArray(t.inputKeys)||t.inputKeys.some(i=>typeof i!="string"||!i)))throw new x("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 x("DEFINITION_UNSUPPORTED","UI action data input declaration is invalid");if(t.resultProjection&&Ft(t.resultProjection),t.schedule!==void 0&&(!zn(t.schedule.everyMinutes)||!$n(t.schedule.timeoutMs)))throw new x("DEFINITION_UNSUPPORTED","UI action schedule declaration is invalid");if(t.content!==void 0&&!Bn(t.content))throw new x("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 x("DEFINITION_UNSUPPORTED","UI action environment declaration is invalid")}if(e.renderer!==void 0&&(!e.renderer||e.renderer.length>128))throw new x("DEFINITION_UNSUPPORTED","UI definition renderer is invalid");if(e.surfaces&&(!Array.isArray(e.surfaces)||e.surfaces.some(n=>!n||n.length>64)))throw new x("DEFINITION_UNSUPPORTED","UI definition surfaces are invalid");if(e.usage!==void 0&&e.usage!=="card"&&e.usage!=="window")throw new x("DEFINITION_UNSUPPORTED","UI definition usage is invalid");if(e.detailPanel!==void 0&&typeof e.detailPanel!="boolean")throw new x("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 x("DEFINITION_UNSUPPORTED","UI definition displayModes are invalid");if(e.usage==="card"&&e.displayModes!==void 0)throw new x("DEFINITION_UNSUPPORTED","Card definitions cannot declare displayModes");if(e.usage==="window"&&e.detailPanel!==void 0)throw new x("DEFINITION_UNSUPPORTED","Window definitions cannot declare detailPanel");if(e.stateProjection&&Ft(e.stateProjection),e.summaryProjection){Ft(e.summaryProjection);let n=new Set(e.stateProjection?.allow??[]);if(e.summaryProjection.allow.some(t=>!n.has(t)))throw new x("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 x("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(ia(r,o==="readTool"),n.has(r.name))throw new x("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 x("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 x("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 x("DEFINITION_UNSUPPORTED","UI legacy agent access is invalid");if(e.legacy.actionTool!==void 0&&(!i||Object.keys(i).length===0))throw new x("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=>Qe(t,i))))throw new x("DEFINITION_UNSUPPORTED","UI definition dataPaths are invalid")}}function ia(e,n){if(!e||typeof e!="object"||Array.isArray(e))throw new x("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 x("DEFINITION_UNSUPPORTED","UI legacy tool metadata is invalid");try{let r=fe(t.inputSchema);if(r.type!==void 0&&r.type!=="object")throw new Error("schema type");if(o){if(!n)throw new Error("fixed result location");let s=t.fixedResult;if(!s||typeof s!="object"||Array.isArray(s))throw new Error("fixed result");let a=s;if(Object.keys(a).sort().join(",")!=="argsPolicy,structuredContent"||a.argsPolicy!=="empty-only"&&a.argsPolicy!=="ignore"||!a.structuredContent||typeof a.structuredContent!="object"||Array.isArray(a.structuredContent))throw new Error("fixed result");let c=fe(a.structuredContent);if(St(en(c))>4*1024)throw new Error("fixed result size")}}catch{throw new x("DEFINITION_UNSUPPORTED","UI legacy tool metadata is not projection-safe")}}function Ft(e){if(!Array.isArray(e.allow)||e.allow.some(n=>!/^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)*$/.test(n)))throw new x("DEFINITION_UNSUPPORTED","UI projection policy is invalid")}function oa(e){return e.length>0&&e.length<=128&&e!=="*"&&e!=="all"&&!/[/*]/.test(e)}var ta,ze=j(()=>{m();Se();Fn();xt();vt();ta=/^[0-9a-f]{64}$/;});var H,$e,Vt=j(()=>{m();H="dist/tools.json",$e="dist/main.mjs";});var ke,Bt=j(()=>{m();ke="window";});function Gi(e){if(!Array.isArray(e)||e.length===0)return false;let n=new Set;for(let t of e){if(!ra.some(i=>i===t)||n.has(t))return false;n.add(t);}return true}var ra,Wi=j(()=>{m();ra=["CREWX_APP_INSTANCE_ID","CREWX_THREAD_ID"];});function z(e){throw new Ht(e)}function ga(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 ma(e,n){let t=Object.getOwnPropertyDescriptor(e,n);return (!t||!("value"in t))&&z("CSP_ORIGIN_INVALID"),t.value}function Gn(e,n){if(!Object.prototype.hasOwnProperty.call(e,n))return [];let t=ma(e,n);Array.isArray(t)||z("CSP_ORIGIN_INVALID"),Reflect.ownKeys(t).some(r=>typeof r!="string"||r!=="length"&&!/^(?:0|[1-9][0-9]*)$/.test(r))&&z("CSP_ORIGIN_INVALID");let o=[];for(let r=0;r<t.length;r+=1)(!Object.prototype.hasOwnProperty.call(t,r)||typeof t[r]!="string")&&z("CSP_ORIGIN_INVALID"),o.push(t[r]);return Object.keys(t).length!==t.length&&z("CSP_ORIGIN_INVALID"),o}function ha(e){let n;try{n=JSON.stringify(e);}catch{z("CSP_ORIGIN_INVALID");}return n===void 0&&z("CSP_ORIGIN_INVALID"),new TextEncoder().encode(n).byteLength}function Xi(e,n){/\s|\\/u.test(e)&&z("CSP_ORIGIN_INVALID");let t=ua.exec(e);t||z("CSP_ORIGIN_INVALID");let i=t[1].toLowerCase(),o=t[2];(o.includes("@")||o.includes("%")||o.includes("*"))&&z("CSP_ORIGIN_INVALID"),(o.startsWith("[")?fa:ya).test(o)||z("CSP_ORIGIN_INVALID"),i==="wss"&&n!=="connectDomains"&&z("CSP_ORIGIN_INVALID");let s;try{s=new URL(e);}catch{z("CSP_ORIGIN_INVALID");}(s.protocol!==`${i}:`||s.username!==""||s.password!==""||s.search!==""||s.hash!=="")&&z("CSP_ORIGIN_INVALID");let a=s.hostname.toLowerCase();if((!a||a.includes("%"))&&z("CSP_ORIGIN_INVALID"),!a.startsWith("[")){let d=a.endsWith(".")?a.slice(0,-1):a;(d.length===0||d.length>253)&&z("CSP_ORIGIN_INVALID"),d.split(".").some(p=>p.length>63||!Aa.test(p))&&z("CSP_ORIGIN_INVALID");}let c=s.origin;return (c==="null"||!c.startsWith(`${i}://`))&&z("CSP_ORIGIN_INVALID"),{origin:c,hostname:a}}function _a(e){let n=e.split(".").map(Number);return ((n[0]*256+n[1])*256+n[2])*256+n[3]}function Yi(e,n,t){let i=4294967295<<32-t>>>0;return (e&i)===(n&i)}function Qi(e){let n=_a(e);return Yi(n,3221225472,24)?n!==3221225481&&n!==3221225482:Ia.some(([t,i])=>Yi(n,t,i))}function Ea(e){let n=e.indexOf("::"),t=(n<0?e:e.slice(0,n)).split(":").filter(Boolean),i=n<0?[]:e.slice(n+2).split(":").filter(Boolean);return (n<0?t:[...t,...Array(8-t.length-i.length).fill("0"),...i]).reduce((r,s)=>r<<16n|BigInt(Number.parseInt(s,16)),0n)}function Ta(e){let n=Ea(e),t=Number(n>>112n),i=Number(n>>96n&0xffffn);if(n>>32n===0xffffn){let o=Number(n&0xffffffffn);return Qi([o>>>24&255,o>>>16&255,o>>>8&255,o&255].join("."))}return t<8192||t>16383||t===8193&&i<=511||t===8193&&i===3512||t===8194||t===16383&&i<=4095}function Pa(e,n){let t=e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e,i=net.isIP(t);if(i===4)return Qi(t);if(i===6)return Ta(t);let o=e.toLowerCase().replace(/\.$/,"");return !o||!o.includes(".")||n.has(o)?true:la.some(r=>o===r||o.endsWith(`.${r}`))}function qi(e){return Object.freeze([...new Set(e.map(n=>n.origin))].sort())}function Zi(e){return JSON.stringify({baseUriDomains:[],connectDomains:e.connectDomains,declared:e.declared,frameDomains:e.frameDomains,resourceDomains:[]})}function eo(e,n={}){if(e===void 0){let f=Zi({declared:false,connectDomains:[],frameDomains:[]});return Object.freeze({declared:false,connectDomains:Object.freeze([]),frameDomains:Object.freeze([]),resourceDomains:Object.freeze([]),baseUriDomains:Object.freeze([]),cspHash:xi.createHash("sha256").update(f,"utf8").digest("hex")})}ga(e)||z("CSP_ORIGIN_INVALID");let t=Reflect.ownKeys(e);t.some(f=>typeof f!="string")&&z("CSP_ORIGIN_INVALID"),t.some(f=>!pa.has(f))&&z("CSP_AXIS_UNKNOWN");let i=Gn(e,"connectDomains"),o=Gn(e,"frameDomains"),r=Gn(e,"resourceDomains"),s=Gn(e,"baseUriDomains");(r.length>0||s.length>0)&&z("CSP_AXIS_UNSUPPORTED"),(ha(e)>aa||i.length>Ki||o.length>Ki||i.length+o.length>ca||[...i,...o].some(f=>new TextEncoder().encode(f).byteLength>da))&&z("CSP_LIMIT_EXCEEDED");let c=i.map(f=>Xi(f,"connectDomains")),d=o.map(f=>Xi(f,"frameDomains")),l=new Set((n.runtimeHostnames??[]).map(f=>f.toLowerCase().replace(/\.$/,"")));[...c,...d].some(f=>Pa(f.hostname,l))&&z("CSP_ORIGIN_FORBIDDEN");let p={declared:true,connectDomains:qi(c),frameDomains:qi(d)},u=Zi(p);return Object.freeze({...p,resourceDomains:Object.freeze([]),baseUriDomains:Object.freeze([]),cspHash:xi.createHash("sha256").update(u,"utf8").digest("hex")})}var aa,Ki,ca,da,pa,la,ua,fa,ya,Aa,Ia,Ht,no=j(()=>{m();aa=4096,Ki=16,ca=32,da=512,pa=new Set(["connectDomains","frameDomains","resourceDomains","baseUriDomains"]),la=["localhost","local","internal","home.arpa","test","example","invalid","onion","lan","corp","home","intranet","private","localdomain"],ua=/^(https|wss):\/\/([^/?#]+)$/i,fa=/^\[[^\]]+\](?::[0-9]+)?$/,ya=/^[^:\[\]]+(?::[0-9]+)?$/,Aa=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/,Ia=[[0,8],[1681915904,10],[167772160,8],[2130706432,8],[2851995648,16],[2886729728,12],[3221225984,24],[3227017984,24],[3232235520,16],[3323068416,15],[3325256704,24],[3405803776,24],[3758096384,4],[4026531840,4]],Ht=class extends Error{constructor(t){super(t);this.code=t;}code;name="UiPluginCspNormalizationError"};});function gn(e,n){return n===void 0||n===""?e:e===""?n:n.startsWith("[")?`${e}${n}`:`${e}.${n}`}function y(e,n=e,t,i){throw new ae(e,n,t,i)}function W(e,n){try{return n()}catch(t){throw t instanceof ae?t.withPathPrefix(e):t}}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 v(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function Qa(e,n){let t={};for(let[i,o]of Object.entries(e))i!==n&&(t[i]=o);return t}function K(e,n,t=[]){let i=new Set([...n,...t]),o=Object.keys(e).find(s=>!i.has(s));o!==void 0&&y("MANIFEST_INVALID","MANIFEST_INVALID",o,"unknown-key");let r=n.find(s=>!v(e,s));r!==void 0&&y("MANIFEST_INVALID","MANIFEST_INVALID",r,"missing-key");}function Xn(e,n=false,t=false,i=false){return Sa.test(e)||!i&&La.test(e)||Ma.test(e)||t&&to.test(e)||Ra.test(e)&&!(n&&/^\s*data:/i.test(e)&&!to.test(e))}function Kn(e,n=new Set,t=0,i=false,o=false,r=""){if(typeof e=="string"){Xn(e,i,o)&&y("UNSAFE_VALUE","UNSAFE_VALUE",r,"unsafe-value");return}if(!(e===null||typeof e!="object")){(t>8||n.has(e))&&y("MANIFEST_INVALID","MANIFEST_INVALID",r),n.add(e);try{if(Array.isArray(e)){e.forEach((s,a)=>Kn(s,n,t+1,!1,!1,gn(r,`[${a}]`)));return}J(e)||y("MANIFEST_INVALID","MANIFEST_INVALID",r);for(let[s,a]of Object.entries(e))Kn(a,n,t+1,i&&t===0&&(s==="name"||s==="description"),o,gn(r,s));}finally{n.delete(e);}}}function Te(e,n){let t=e[n];return typeof t!="string"&&y("MANIFEST_INVALID"),t}function Ie(e,n,t){let i=e[n];return (!Number.isSafeInteger(i)||i<t)&&y("MANIFEST_INVALID"),i}function zt(e){return ba.test(e)||y("MANIFEST_INVALID"),e}function tn(e){return Da.test(e)||y("TOKEN_INVALID"),e}function ec(e){return uo.test(e)||y("MANIFEST_INVALID"),e}function nc(e){J(e)||y("MANIFEST_INVALID");let n={};for(let[t,i]of Object.entries(e)){let o=ec(t);J(i)||y("MANIFEST_INVALID");let r=i.type;if(r==="text"){K(i,["type","maxLength"]),n[o]={type:r,maxLength:Ie(i,"maxLength",1)};continue}if(r==="text-list"){K(i,["type","max","itemMaxLength"]),n[o]={type:r,max:Ie(i,"max",0),itemMaxLength:Ie(i,"itemMaxLength",1)};continue}if(r==="step-list"){K(i,["type","min","max","labelMaxLength","detailMaxLength"]);let s=Ie(i,"min",0),a=Ie(i,"max",1);s>a&&y("MANIFEST_INVALID"),n[o]={type:r,min:s,max:a,labelMaxLength:Ie(i,"labelMaxLength",1),detailMaxLength:Ie(i,"detailMaxLength",1)};continue}typeof r=="string"&&y("SCHEMA_TYPE_UNSUPPORTED"),y("MANIFEST_INVALID");}return n}function tc(e,n,t){let i=e[n];(!i||i.type!==t)&&y("MANIFEST_INVALID");}function Wn(e,n,t){let i=Te(e,"field");return uo.test(i)||y("MANIFEST_INVALID"),tc(n,i,t),i}function ic(e,n){J(e)||y("MANIFEST_INVALID");let t=e.primitive;switch(typeof t!="string"&&y("MANIFEST_INVALID"),Za.includes(t)||y("PRIMITIVE_UNKNOWN"),t){case "card-shell":return K(e,["primitive"]),{primitive:t};case "meta-banner":return K(e,["primitive","badgeToken","noticeToken"]),{primitive:t,badgeToken:tn(Te(e,"badgeToken")),noticeToken:tn(Te(e,"noticeToken"))};case "heading":return K(e,["primitive","field"]),{primitive:t,field:Wn(e,n,"text")};case "labeled-text":return K(e,["primitive","titleToken","field","variant"]),e.variant!=="callout"&&y("MANIFEST_INVALID"),{primitive:t,titleToken:tn(Te(e,"titleToken")),field:Wn(e,n,"text"),variant:"callout"};case "step-flow":return K(e,["primitive","titleToken","field"]),{primitive:t,titleToken:tn(Te(e,"titleToken")),field:Wn(e,n,"step-list")};case "text-list":{K(e,["primitive","titleToken","field"],["emptyToken","hideWhenEmpty"]);let i={primitive:t,titleToken:tn(Te(e,"titleToken")),field:Wn(e,n,"text-list")};return v(e,"emptyToken")&&(i.emptyToken=tn(Te(e,"emptyToken"))),v(e,"hideWhenEmpty")&&(typeof e.hideWhenEmpty!="boolean"&&y("MANIFEST_INVALID"),i.hideWhenEmpty=e.hideWhenEmpty),i}}return y("MANIFEST_INVALID")}function oc(e,n){return Array.isArray(e)||y("MANIFEST_INVALID"),e.map(t=>ic(t,n))}function X(e="v2 manifest exceeds a contract limit",n,t){return y("LIMIT_EXCEEDED",e,n,t)}function Ae(e="initial state is not projection-safe"){return y("INITIAL_STATE_INVALID",e)}function io(e,n){return (typeof e!="string"||e.length===0||e.length>4096||e.trim().length===0||Xa.test(e)||Ya.test(e))&&y("MANIFEST_INVALID",`${n} is invalid`),(Xn(e,true,true)||Oa.test(e)||wa.test(e)||Ca.test(e))&&y("UNSAFE_VALUE",`${n} contains an unsafe value`),e}function $t(e,n){return (typeof e!="string"||!Ee.test(e))&&y("MANIFEST_INVALID",`${n} is invalid`),e}function rc(e){return (typeof e!="string"||!Lt.test(e)||e==="*"||e==="all")&&y("MANIFEST_INVALID","action capability is invalid"),e}function fo(e){return (typeof e!="string"||!Ka.test(e))&&y("MANIFEST_INVALID","resource hash is invalid"),e}function Gt(e,n=new Set,t=0,i=""){if(typeof e=="string"){e.length>4096&&X("v2 manifest string is too long",i,"string-too-long");return}if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){Number.isFinite(e)||y("MANIFEST_INVALID","v2 manifest contains a non-finite number",i,"non-finite-number");return}(e===void 0||typeof e=="function"||typeof e=="bigint")&&y("MANIFEST_INVALID","v2 manifest contains a non-JSON value",i,"non-json-value"),typeof e!="object"&&y("MANIFEST_INVALID","MANIFEST_INVALID",i),t>8&&X("v2 manifest nesting is too deep",i,"too-deep"),n.has(e)&&y("MANIFEST_INVALID","v2 manifest contains a cycle",i,"cycle"),n.add(e);try{if(Array.isArray(e)){e.length>128&&X("v2 manifest array is too long",i,"array-too-long"),e.forEach((o,r)=>Gt(o,n,t+1,gn(i,`[${r}]`)));return}J(e)||y("MANIFEST_INVALID","v2 manifest contains a non-plain object",i,"non-plain-object");for(let[o,r]of Object.entries(e))Gt(r,n,t+1,gn(i,o));}finally{n.delete(e);}}}function yo(e){return (typeof e!="string"||e.length>4096||!An.test(e))&&(typeof e=="string"&&e.length>4096&&X("projection path is too long"),y("MANIFEST_INVALID","projection paths must be canonical exact paths")),e.split(".").some(t=>nn(t))&&y("MANIFEST_INVALID","projection paths cannot address reserved state keys"),e}function Wt(e){J(e)||y("MANIFEST_INVALID","projection policy must be an object"),K(e,["allow"]),Array.isArray(e.allow)||y("MANIFEST_INVALID","projection allow must be an array"),e.allow.length>128&&X("projection allowlist is too long");let n=[],t=new Set;for(let i of e.allow){let o=yo(i);t.has(o)&&y("MANIFEST_INVALID","projection allowlist contains a duplicate path"),t.add(o),n.push(o);}return {allow:n}}function sc(e,n){if(e===void 0)return;Array.isArray(e)||y("MANIFEST_INVALID","dataPaths must be an array"),e.length>qa&&X("dataPaths exceed the v2 limit");let t=[],i=new Set;for(let o of e){let r=yo(o);i.has(r)&&y("MANIFEST_INVALID","dataPaths contain a duplicate path"),n.some(s=>Qe(r,s))||y("MANIFEST_INVALID","dataPaths must be projection-allowed"),i.add(r),t.push(r);}return t}function on(e,n,t=Number.MAX_SAFE_INTEGER){return (!Number.isSafeInteger(e)||e<0||e>t)&&y("MANIFEST_INVALID",`${n} is invalid`),e}function oo(e,n){return (typeof e!="number"||!Number.isFinite(e))&&y("MANIFEST_INVALID",`${n} is invalid`),e}function Jt(e,n=0,t=new Set){if(typeof e=="string")return (e.length>4096||Xn(e))&&y("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)||y("MANIFEST_INVALID","schema enum contains a non-finite number"),e;(n>8||typeof e!="object"||e===void 0)&&X("schema enum is too deep"),t.has(e)&&y("MANIFEST_INVALID","schema enum contains a cycle"),t.add(e);try{if(Array.isArray(e))return e.length>128&&X("schema enum array is too long"),e.map(o=>Jt(o,n+1,t));J(e)||y("MANIFEST_INVALID","schema enum contains a non-plain object");let i={};for(let[o,r]of Object.entries(e))nn(o)&&y("MANIFEST_INVALID","schema enum contains a reserved key"),i[o]=Jt(r,n+1,t);return i}finally{t.delete(e);}}function ac(e,n){if(e===void 0)return;Array.isArray(e)||y("MANIFEST_INVALID","schema required must be an array"),e.length>64&&X("schema required list is too long");let t=[],i=new Set;for(let o of e)(typeof o!="string"||!An.test(o))&&y("MANIFEST_INVALID","schema required contains an invalid key"),o.length>4096&&X("schema required key is too long"),i.has(o)&&y("MANIFEST_INVALID","schema required contains a duplicate key"),n&&!Object.prototype.hasOwnProperty.call(n,o)&&y("MANIFEST_INVALID","schema required references an undeclared property"),i.add(o),t.push(o);return t}function cc(e,n){let t=n?An:Vn;return e.length>4096&&X("schema property name is too long"),(!t.test(e)||e.split(".").some(i=>nn(i)))&&y("MANIFEST_INVALID","schema property name is invalid"),e}function Kt(e,n=0,t=false){J(e)||y("MANIFEST_INVALID","action inputSchema must be an object"),n>8&&X("action inputSchema is too deep");let i=e.type;i!=="object"&&i!=="string"&&i!=="number"&&i!=="integer"&&i!=="boolean"&&i!=="array"&&i!=="null"&&(typeof i=="string"&&y("SCHEMA_TYPE_UNSUPPORTED","action inputSchema type is unsupported"),y("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"),K(e,["type"],o.filter(a=>a!=="type"));let r={type:i};if(v(e,"enum")&&(Array.isArray(e.enum)||y("MANIFEST_INVALID","schema enum must be an array"),e.enum.length>128&&X("schema enum is too long"),r.enum=e.enum.map(a=>Jt(a))),i==="string"&&(v(e,"minLength")&&(r.minLength=on(e.minLength,"schema minLength",4096)),v(e,"maxLength")&&(r.maxLength=on(e.maxLength,"schema maxLength",4096)),r.minLength!==void 0&&r.maxLength!==void 0&&r.minLength>r.maxLength&&y("MANIFEST_INVALID","schema string length bounds are inverted")),(i==="number"||i==="integer")&&(v(e,"minimum")&&(r.minimum=oo(e.minimum,"schema minimum")),v(e,"maximum")&&(r.maximum=oo(e.maximum,"schema maximum")),r.minimum!==void 0&&r.maximum!==void 0&&r.minimum>r.maximum&&y("MANIFEST_INVALID","schema numeric bounds are inverted")),i==="array"&&(v(e,"minItems")&&(r.minItems=on(e.minItems,"schema minItems",128)),v(e,"maxItems")&&(r.maxItems=on(e.maxItems,"schema maxItems",128)),r.minItems!==void 0&&r.maxItems!==void 0&&r.minItems>r.maxItems&&y("MANIFEST_INVALID","schema array length bounds are inverted"),v(e,"items")&&(r.items=Kt(e.items,n+1,false))),i==="object"){let a;if(v(e,"properties")){J(e.properties)||y("MANIFEST_INVALID","schema properties must be an object");let d=Object.entries(e.properties);d.length>64&&X("schema properties are too many"),a={};for(let[l,p]of d){let u=cc(l,t);a[u]=Kt(p,n+1,false);}r.properties=a;}v(e,"minProperties")&&(r.minProperties=on(e.minProperties,"schema minProperties",64)),v(e,"maxProperties")&&(r.maxProperties=on(e.maxProperties,"schema maxProperties",64)),r.minProperties!==void 0&&r.maxProperties!==void 0&&r.minProperties>r.maxProperties&&y("MANIFEST_INVALID","schema object property bounds are inverted");let c=ac(e.required,a);c!==void 0&&(r.required=c),v(e,"additionalProperties")&&(e.additionalProperties!==false&&y("MANIFEST_INVALID","schema additionalProperties must be false"),r.additionalProperties=false);}let s=JSON.stringify(r);return (s===void 0||Buffer.byteLength(s,"utf8")>2097152)&&X("action inputSchema subtree is too large"),r}function dc(e){let n=Kt(e,0,true);return (n.type!=="object"||!n.properties)&&y("MANIFEST_INVALID","action inputSchema must declare object properties"),n}function pc(e){if(J(e)||y("MANIFEST_INVALID","action backend must be an object"),e.type==="core"){K(e,Ha);let n=e.handler;return (typeof n!="string"||!Rt.test(n))&&y("MANIFEST_INVALID","core backend handler is invalid"),{type:"core",handler:n}}if(e.type==="skill"&&v(e,"entry"))return K(e,Ga),e.entry!==$e&&y("MANIFEST_INVALID",`skill backend entry must be ${$e}`),{type:"skill",entry:$e};if(e.type==="skill"){K(e,za,$a),(!Array.isArray(e.command)||e.command.length===0||e.command.length>16)&&y("MANIFEST_INVALID","skill backend command is invalid");let n=[];for(let i of e.command)(typeof i!="string"||i.length===0||i.length>256||!Ot.test(i))&&y("MANIFEST_INVALID","skill backend command token is invalid"),n.push(i);let t=v(e,"env")?fc(e.env):void 0;return {type:"skill",command:n,...t===void 0?{}:{env:t}}}y("MANIFEST_INVALID","action backend type is unsupported");}function lc(e){J(e)||y("MANIFEST_INVALID","action must be an object"),K(e,va,Fa),v(e,"_meta")&&W("_meta",()=>Ao(e._meta));let n=W("actionId",()=>$t(e.actionId,"actionId"));bt(n)&&y("MANIFEST_INVALID",`actionId "${n}" is not projection-safe`,"actionId");let t=W("capability",()=>rc(e.capability)),i=e.mutation;typeof i!="boolean"&&y("MANIFEST_INVALID","action mutation must be boolean","mutation");let o=W("inputSchema",()=>dc(e.inputSchema)),r;if(v(e,"dataInputs")){Array.isArray(e.dataInputs)||y("MANIFEST_INVALID","action dataInputs must be an array","dataInputs");let p=o.properties,u=new Set,f=[];for(let g of e.dataInputs)(typeof g!="string"||!v(p,g)||u.has(g))&&y("MANIFEST_INVALID","action dataInputs must be unique declared properties","dataInputs"),u.add(g),f.push(g);r=f;}let s=W("resultProjection",()=>Wt(e.resultProjection)),a=W("backend",()=>pc(e.backend)),c;v(e,"content")&&((a.type!=="skill"||!Bn(e.content))&&y("MANIFEST_INVALID","action content declaration is invalid","content"),c=yc(e.content));let d;if(v(e,"confirmation")){let p=e.confirmation;p!=="none"&&p!=="native"&&y("MANIFEST_INVALID","action confirmation is invalid","confirmation"),d=p;}let l;return v(e,"schedule")&&(l=W("schedule",()=>uc(e.schedule,{backend:a,inputSchema:o,hasContent:c!==void 0,hasDataInputs:r!==void 0,confirmation:d}))),{actionId:n,capability:t,mutation:i,inputSchema:o,resultProjection:s,backend:a,...c===void 0?{}:{content:c},...r===void 0?{}:{dataInputs:r},...d===void 0?{}:{confirmation:d},...l===void 0?{}:{schedule:l}}}function uc(e,n){(n.backend.type!=="skill"||!("entry"in n.backend)||n.backend.entry!==$e)&&y("MANIFEST_INVALID","schedule needs a tool-mode action","schedule"),(n.hasContent||n.hasDataInputs||n.confirmation!==void 0&&n.confirmation!=="none")&&y("MANIFEST_INVALID","a scheduled action takes no content, dataInputs or native confirmation","schedule"),(n.inputSchema.required??[]).length>0&&y("MANIFEST_INVALID","a scheduled action input must accept {}","inputSchema.required"),J(e)||y("MANIFEST_INVALID","schedule must be an object","schedule"),K(e,ja,Va),zn(e.everyMinutes)||y("MANIFEST_INVALID","schedule everyMinutes is invalid","schedule.everyMinutes");let t=v(e,"timeoutMs")?e.timeoutMs:Hn.default;return $n(t)||y("MANIFEST_INVALID","schedule timeoutMs is invalid","schedule.timeoutMs"),{everyMinutes:e.everyMinutes,timeoutMs:t}}function fc(e){return Gi(e)||y("MANIFEST_INVALID","skill backend env is invalid"),Object.freeze([...e])}function yc(e){return Object.freeze({...e.in===void 0?{}:{in:Object.freeze({...e.in})},...e.out===void 0?{}:{out:Object.freeze({...e.out})}})}function Ac(e){return J(e)||y("INITIAL_STATE_INVALID","initialState must be an object"),K(e,Wa,Ja),e.path!=="ui/state.json"&&y("MANIFEST_INVALID","initialState path is not fixed"),v(e,"hash")?{path:"ui/state.json",hash:fo(e.hash)}:{path:"ui/state.json"}}function Ic(e){let n=["wasm","terminal","htmlDocuments"];return (!J(e)||Object.keys(e).length===0||Object.keys(e).some(t=>!n.includes(t)||e[t]!==true))&&y("MANIFEST_INVALID","runtime must contain only known capability flags set to true"),{...e.wasm===true?{wasm:true}:{},...e.terminal===true?{terminal:true}:{},...e.htmlDocuments===true?{htmlDocuments:true}:{}}}function gc(e,n){let t;try{t=eo(e);}catch(i){let o=i!==null&&typeof i=="object"&&"code"in i&&typeof i.code=="string"?i.code:"CSP_ORIGIN_INVALID";return y("MANIFEST_INVALID",o,void 0,o.toLowerCase().replace(/_/g,"-"))}if(t.frameDomains.length>0&&y("MANIFEST_INVALID","external origins in csp are not enabled in this rollout",void 0,"csp-not-enabled"),t.connectDomains.length!==0)return n?.terminal===true&&y("MANIFEST_INVALID","runtime.terminal cannot be combined with csp.connectDomains","connectDomains","terminal-with-connect-domains"),Object.freeze({connectDomains:t.connectDomains})}function mc(e,n){Kn(J(e)&&v(e,"csp")?Qa(e,"csp"):e,new Set,0,true,true),Gt(e),J(e)||y("MANIFEST_INVALID"),K(e,ka,xa),v(e,"_meta")&&W("_meta",()=>Ao(e._meta)),e.manifestVersion!==2&&y("MANIFEST_INVALID");let t;v(e,"runtime")&&(t=W("runtime",()=>Ic(e.runtime)));let i;v(e,"csp")&&(i=W("csp",()=>gc(e.csp,t)));let o=W("pluginId",()=>$t(e.pluginId,"pluginId")),r=W("definitionId",()=>$t(e.definitionId,"definitionId")),s=W("version",()=>Ie(e,"version",1)),a=W("name",()=>io(e.name,"name")),c=W("description",()=>io(e.description,"description")),d;v(e,"icon")&&((typeof e.icon!="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(e.icon))&&y("MANIFEST_INVALID","icon is invalid","icon"),d=e.icon);let l;v(e,"tone")&&((typeof e.tone!="string"||!wt.includes(e.tone))&&y("MANIFEST_INVALID","tone is invalid","tone"),l=e.tone),e.entry!=="ui/index.html"&&y("MANIFEST_INVALID","entry path is not fixed","entry","fixed-value");let p;v(e,"entryHash")&&(p=W("entryHash",()=>fo(e.entryHash)));let u;v(e,"initialState")&&(u=W("initialState",()=>Ac(e.initialState)));let f;v(e,"usage")&&(e.usage!=="card"&&e.usage!=="window"&&y("MANIFEST_INVALID","usage is invalid","usage"),f=e.usage);let g;v(e,"detailPanel")&&(typeof e.detailPanel!="boolean"&&y("MANIFEST_INVALID","detailPanel is invalid","detailPanel"),g=e.detailPanel);let _;if(v(e,"displayModes")){((f??ke)!==ke||!Array.isArray(e.displayModes)||e.displayModes.length===0)&&y("MANIFEST_INVALID","displayModes are only valid for window Apps","displayModes");let A=new Set(["inline","floating","focused"]);(new Set(e.displayModes).size!==e.displayModes.length||e.displayModes.some(h=>typeof h!="string"||!A.has(h)))&&y("MANIFEST_INVALID","displayModes are invalid","displayModes"),_=e.displayModes;}(f??ke)===ke&&g!==void 0&&y("MANIFEST_INVALID","detailPanel is card-only","detailPanel");let P=n.mode??"local";P!=="local"&&P!=="installed"&&P!=="published"&&y("MANIFEST_INVALID","manifest mode is invalid"),P!=="local"&&p===void 0&&y("MANIFEST_INVALID","installed manifests require entryHash","entryHash","required-when-installed"),P!=="local"&&u!==void 0&&u.hash===void 0&&y("MANIFEST_INVALID","installed manifests require initialState.hash","initialState.hash","required-when-installed"),(!Array.isArray(e.surfaces)||e.surfaces.length===0)&&y("MANIFEST_INVALID","surfaces are invalid","surfaces"),e.surfaces.length>2&&X("surfaces exceed the v2 limit","surfaces","too-many-items");let C=[],U=new Set;for(let A of e.surfaces)(typeof A!="string"||!Ct.includes(A))&&y("MANIFEST_INVALID","surface is unsupported","surfaces"),U.has(A)&&y("MANIFEST_INVALID","surfaces contain a duplicate","surfaces","duplicate-item"),U.add(A),C.push(A);J(e.size)||y("MANIFEST_INVALID","size must be an object","size"),W("size",()=>K(e.size,["height"]));let N=W("size",()=>Ie(e.size,"height",1));N>720&&X("size.height exceeds the v2 limit","size.height","too-large");let O=W("stateProjection",()=>Wt(e.stateProjection)),V=e.summaryProjection===void 0?void 0:W("summaryProjection",()=>Wt(e.summaryProjection));V!==void 0&&V.allow.some(A=>!O.allow.includes(A))&&y("MANIFEST_INVALID","summaryProjection must be a subset of stateProjection.allow","summaryProjection");let D=W("dataPaths",()=>sc(e.dataPaths,O.allow));Array.isArray(e.actions)||y("MANIFEST_INVALID","actions must be an array","actions"),e.actions.length>32&&X("actions exceed the v2 limit","actions","too-many-items");let b=[],L=new Set,I=0;for(let[A,h]of e.actions.entries()){let E=`actions[${A}]`,w=W(E,()=>lc(h));if(L.has(w.actionId)&&y("MANIFEST_INVALID","actions contain a duplicate actionId",`${E}.actionId`,"duplicate-item"),w.schedule!==void 0&&(I+=1,I>$i&&y("MANIFEST_INVALID","an App declares at most one scheduled action",`${E}.schedule`,"duplicate-item")),w.backend.type==="core"&&w.backend.handler==="state.set"){w.mutation||y("MANIFEST_INVALID","state.set actions must be mutations",`${E}.mutation`);for(let k of Object.keys(w.inputSchema.properties))O.allow.includes(k)||y("MANIFEST_INVALID","state.set input paths must be projection-allowed",`${E}.inputSchema.properties`);}L.add(w.actionId),b.push(w);}return {manifestVersion:2,pluginId:o,definitionId:r,version:s,name:a,description:c,...d===void 0?{}:{icon:d},...l===void 0?{}:{tone:l},entry:"ui/index.html",...p===void 0?{}:{entryHash:p},...t===void 0?{}:{runtime:t},...i===void 0?{}:{csp:i},...u===void 0?{}:{initialState:u},...f===void 0?{}:{usage:f},...g===void 0?{}:{detailPanel:g},..._===void 0?{}:{displayModes:_},surfaces:C,size:{height:N},stateProjection:O,...V===void 0?{}:{summaryProjection:V},...D===void 0?{}:{dataPaths:D},actions:b}}function Ao(e){J(e)||y("MANIFEST_INVALID","_meta must be an object");let n=JSON.stringify(e);(n===void 0||Buffer.byteLength(n,"utf8")>Ba)&&X("_meta exceeds the 4 KiB limit",void 0,"meta-too-large");}function hc(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.schedule===void 0?{}:{schedule:r.schedule},...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 Xt(e,n,t,i,o,r){if(typeof e=="string"){let s=o.length>0&&r.some(a=>Qe(o.join("."),a));return (e.length>4096||Xn(e,false,false,s))&&Ae("state contains an unsafe string"),e}if(e===null||typeof e=="boolean")return e;if(typeof e=="number")return Number.isFinite(e)||Ae("state contains a non-finite number"),e;(e===void 0||typeof e!="object"||typeof e=="function"||typeof e=="bigint")&&Ae("state contains a non-JSON value"),t>8&&Ae("state is too deep"),n.has(e)&&Ae("state contains a cycle"),n.add(e);try{let s;if(Array.isArray(e))e.length>128&&Ae("state array is too long"),s=e.map(c=>Xt(c,n,t+1,2097152,o,r));else {J(e)||Ae("state contains a non-plain object");let c={};for(let[d,l]of Object.entries(e))(d.length>4096||!Vn.test(d)||nn(d))&&(d.length>4096&&Ae("state key is too long"),Ae("state contains a reserved or invalid key")),c[d]=Xt(l,n,t+1,2097152,[...o,d],r);s=c;}let a=JSON.stringify(s);return (a===void 0||Buffer.byteLength(a,"utf8")>i)&&Ae("state subtree is too large"),s}finally{n.delete(e);}}function qt(e,n=[]){J(e)||Ae("initial state must be a JSON object");let t=Xt(e,new Set,0,2097152,[],n);return (t===null||Array.isArray(t)||typeof t!="object")&&Ae(),t}function _c(e,n={}){Kn(e),J(e)||y("MANIFEST_INVALID"),K(e,Ua),e.manifestVersion!==1&&y("MANIFEST_INVALID");let t=zt(Te(e,"pluginId")),i=zt(Te(e,"definitionId")),o=Ie(e,"version",1),r=Ie(e,"primitiveSet",1),s=n.supportedPrimitiveSet??Na;(!Number.isSafeInteger(s)||s<1)&&y("MANIFEST_INVALID"),r>s&&y("PRIMITIVE_SET_UNSUPPORTED"),J(e.activation)||y("MANIFEST_INVALID"),K(e.activation,["kind","language"]),e.activation.kind!=="fenced-code"&&y("MANIFEST_INVALID");let a=zt(Te(e.activation,"language")),c=nc(e.schema),d=oc(e.layout,c);return {manifestVersion:1,pluginId:t,definitionId:i,version:o,primitiveSet:r,activation:{kind:"fenced-code",language:a},schema:c,layout:d}}function Ec(e,n={}){return J(e)||y("MANIFEST_INVALID"),Object.hasOwn(e,"lineage")&&y("MANIFEST_INVALID","lineage is only allowed in product bundle indexes"),e.manifestVersion===2?mc(e,n):_c(e,n)}function We(e,n={}){try{return Ec(e,n)}catch(t){if(t instanceof ae)throw t;return y("MANIFEST_INVALID")}}function mn(e,n={}){let t=We(e,n);return t.manifestVersion===2?hc(t):t}var Na,Da,ba,uo,Sa,Ma,La,Ra,to,Oa,wa,Ca,Ua,ka,xa,va,Fa,ja,Va,Ba,Ha,za,$a,Ga,Wa,Ja,Ka,Xa,Ya,qa,Za,ae,Zt=j(()=>{m();Bt();Se();xt();Wi();Vt();vt();no();He();Na=1,Da=/^[a-z][a-zA-Z0-9]*(\.[a-zA-Z0-9]+)+$/,ba=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,uo=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,Sa=/<\/?[A-Za-z][^>]*>/,Ma=/^(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)/,La=/^(?:https?|file|ftp|ws|wss):\/\//i,Ra=/^\s*(?:javascript|data):/i,to=/data:[^,\s]*,/i,Oa=/(?:https?|file|ftp|ws|wss):\/\//i,wa=/javascript:/i,Ca=/(?:^[\s]*|[\s"'(=])(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)(?=[^\s"'<>])[^\s"'<>]*/,Ua=["manifestVersion","pluginId","definitionId","version","primitiveSet","activation","schema","layout"],ka=["manifestVersion","pluginId","definitionId","version","name","description","entry","surfaces","size","stateProjection","actions"],xa=["_meta","icon","tone","entryHash","runtime","csp","initialState","usage","detailPanel","displayModes","summaryProjection","dataPaths","focusedAiDataPaths"],va=["actionId","capability","mutation","inputSchema","resultProjection","backend"],Fa=["confirmation","dataInputs","content","schedule","_meta"],ja=["everyMinutes"],Va=["timeoutMs"],Ba=4*1024,Ha=["type","handler"],za=["type","command"],$a=["env"],Ga=["type","entry"],Wa=["path"],Ja=["hash"],Ka=/^[0-9a-f]{64}$/,Xa=/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/,Ya=/[\r\n]/,qa=16,Za=["card-shell","meta-banner","heading","labeled-text","step-flow","text-list"],ae=class e extends Error{constructor(t,i=t,o,r){super(i);this.code=t;this.path=o;this.rule=r;}code;path;rule;name="UiPluginValidationError";withPathPrefix(t){return new e(this.code,this.message,gn(t,this.path),this.rule)}};});function Eo(e){return typeof e=="string"&&e.length<=Pc&&Tc.test(e)}function F(e,n,t,i,o){throw new Ne(e,{path:n,rule:t,...i===void 0?{}:{message:i},...o===void 0?{}:{file:o}})}function ie(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 Y(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function me(e){let n=`_meta["${xe}"]`;return e===void 0||e===""?n:e.startsWith("[")?`${n}${e}`:`${n}.${e}`}function Sc(e){return e.toLowerCase().replace(/_/g,"-")}function Mc(e){if(e===void 0||e==="")return "";let n=/^([^.[]+)(.*)$/.exec(e);if(!n)return me(e);let[,t,i]=n;switch(t){case "pluginId":return `name${i}`;case "name":return `display_name${i}`;case "description":return `description${i}`;case "_meta":return `_meta${i}`;case "version":return me("definitionVersion");case "definitionId":return me("definitionId");default:return me(`${t}${i}`)}}function To(e,n,t){return {path:t(e.path),rule:e.rule??Sc(e.code),...e.message!==e.code?{message:e.message}:{},file:n}}function Po(e){return JSON.parse(JSON.stringify(e))}function ni(e,n,t=0,i=new Set){if(typeof e=="string"){e.length>4096&&F("LIMIT_EXCEEDED",n,"string-too-long"),(Nc.test(e)||Dc.test(e)||bc.test(e))&&F("UNSAFE_VALUE",n,"unsafe-value");return}if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){Number.isFinite(e)||F("MANIFEST_INVALID",n,"non-finite-number");return}typeof e!="object"&&F("MANIFEST_INVALID",n,"non-json-value"),t>8&&F("LIMIT_EXCEEDED",n,"too-deep"),i.has(e)&&F("MANIFEST_INVALID",n,"cycle"),i.add(e);try{if(Array.isArray(e)){e.length>128&&F("LIMIT_EXCEEDED",n,"array-too-long"),e.forEach((o,r)=>ni(o,`${n}[${r}]`,t+1,i));return}ie(e)||F("MANIFEST_INVALID",n,"non-plain-object");for(let[o,r]of Object.entries(e))ni(r,n===""?o:`${n}.${o}`,t+1,i);}finally{i.delete(e);}}}function ge(e,n){return (typeof e!="string"||e.length===0)&&F("MANIFEST_INVALID",n,"string"),e}function sn(e,n){return ie(e)||F("MANIFEST_INVALID",n,"object"),e}function Lc(e,n){Array.isArray(e)||F("MANIFEST_INVALID",n,"array"),e.forEach((t,i)=>ge(t,`${n}[${i}]`));}function Rc(e,n){typeof e!="boolean"&&F("MANIFEST_INVALID",n,"boolean");}function hn(e,n,t,i){for(let o of Object.keys(e))!t.includes(o)&&!i.includes(o)&&F("MANIFEST_INVALID",`${n}.${o}`,"unknown-key");for(let o of t)Y(e,o)||F("MANIFEST_INVALID",`${n}.${o}`,"missing-key");}function Oc(e,n){if(e!=="icon")switch(ni(n,e),e){case "long_description":case "homepage":case "documentation":case "support":case "license":ge(n,e);return;case "author":{let t=sn(n,e);hn(t,e,["name"],["email","url"]);for(let i of Object.keys(t))ge(t[i],`${e}.${i}`);return}case "repository":{let t=sn(n,e);hn(t,e,[],["type","url"]);for(let i of Object.keys(t))ge(t[i],`${e}.${i}`);return}case "icons":{Array.isArray(n)||F("MANIFEST_INVALID",e,"array"),n.forEach((t,i)=>{let o=`${e}[${i}]`,r=sn(t,o);hn(r,o,["src","size"],["theme"]),ge(r.src,`${o}.src`),ge(r.size,`${o}.size`),Y(r,"theme")&&ge(r.theme,`${o}.theme`);});return}case "screenshots":case "keywords":case "privacy_policies":Lc(n,e);return;case "tools":{Array.isArray(n)||F("MANIFEST_INVALID",e,"array"),n.forEach((t,i)=>{let o=`${e}[${i}]`,r=sn(t,o);hn(r,o,["name"],["description"]),ge(r.name,`${o}.name`),Y(r,"description")&&ge(r.description,`${o}.description`);});return}case "prompts":{Array.isArray(n)||F("MANIFEST_INVALID",e,"array"),n.forEach((t,i)=>{let o=`${e}[${i}]`,r=sn(t,o);hn(r,o,["name","text"],["description","arguments"]),ge(r.name,`${o}.name`),ge(r.text,`${o}.text`);});return}case "tools_generated":case "prompts_generated":Rc(n,e);return;case "localization":case "compatibility":case "user_config":sn(n,e);return;default:F("MANIFEST_INVALID",e,"unknown-key");}}function Yn(e){return typeof e=="string"&&Ee.test(e)?e:void 0}function No(e){return Number.isSafeInteger(e)&&e>=1?e:void 0}function wc(e){let n=Yn(e.name);if(n===void 0)return;let t=e._meta,i=ie(t)?t[xe]:void 0,o=ie(i)?i:{},r=Y(o,"definitionId")?Yn(o.definitionId):n,s=Y(o,"definitionVersion")?No(o.definitionVersion):1;return {pluginId:n,...r===void 0?{}:{definitionId:r},...s===void 0?{}:{definitionVersion:s}}}function Cc(e){let n=Yn(e.pluginId);if(n===void 0)return;let t=Yn(e.definitionId),i=No(e.version);return {pluginId:n,...t===void 0?{}:{definitionId:t},...i===void 0?{}:{definitionVersion:i}}}function oi(e){try{let n=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e));if(!ie(n))return !1;let t=n._meta;return ie(t)&&Y(t,xe)}catch{return false}}function Uc(e,n){if(e===de)return n.builtinOnly===true;let t=n._meta,i=ie(t)?t[xe]:void 0;return ie(i)&&i.builtinOnly===true}function kc(e,n){Y(e,"server")&&F("MANIFEST_INVALID","server","server-unsupported","phase 1 runs CrewX-owned Apps only");for(let a of Object.keys(e))ti.includes(a)||F("MANIFEST_INVALID",a,"unknown-key");for(let a of ii)Y(e,a)||F("MANIFEST_INVALID",a,"missing-key");e.manifest_version!==Qt&&F("MANIFEST_INVALID","manifest_version","unsupported-version",`manifest_version must be "${Qt}"`),Eo(e.version)||F("MANIFEST_INVALID","version","semver","version must be a semver.org version such as 0.1.0");let t=e._meta;ie(t)||F("MANIFEST_INVALID","_meta","object"),Y(t,xe)||F("MANIFEST_INVALID",me(),"missing-key");let i=t[xe];ie(i)||F("MANIFEST_INVALID",me(),"object");for(let a of Object.keys(i))ei.includes(a)||_o.includes(a)||F("MANIFEST_INVALID",me(a),"unknown-key");for(let a of ei)a==="actions"&&n!==void 0||Y(i,a)||F("MANIFEST_INVALID",me(a),"missing-key");if(n!==void 0&&Y(i,"actions")&&F("MANIFEST_INVALID",me("actions"),"two-truths",`actions are declared in both ${$} and ${H}; a server.ts App keeps them in the tools file only`),xc(i.actions),Y(i,"definitionVersion")){let a=i.definitionVersion;(!Number.isSafeInteger(a)||a<1)&&F("MANIFEST_INVALID",me("definitionVersion"),"positive-integer");}let o={};for(let a of ho)Y(e,a)&&(Oc(a,e[a]),o[a]=Po(e[a]));let r={};for(let[a,c]of Object.entries(t))a!==xe&&(r[a]=c);let s={manifestVersion:2,pluginId:e.name,definitionId:Y(i,"definitionId")?i.definitionId:e.name,version:Y(i,"definitionVersion")?i.definitionVersion:1,name:e.display_name,description:e.description};for(let[a,c]of Object.entries(i))a==="definitionId"||a==="definitionVersion"||(s[a]=c);return n!==void 0&&(s.actions=n.map(a=>({...a,backend:{type:"skill",entry:$e}}))),Object.keys(r).length>0&&(s._meta=r),{v2Input:s,...Object.keys(r).length>0?{vendorMeta:r}:{},passthrough:o}}function xc(e){Array.isArray(e)&&e.forEach((n,t)=>{let i=ie(n)?n.backend:void 0;ie(i)&&Y(i,"entry")&&F("MANIFEST_INVALID",me(`actions[${t}].backend.entry`),"entry-not-authorable",`an action in ${$} cannot name an entry; a server.ts App declares its actions in ${H}`);});}function vc(e,n,t){ie(e)||F("MANIFEST_INVALID","","not-object","manifest.json must be a JSON object",$);let i;try{i=kc(e,t);}catch(s){throw s instanceof Ne?new Ne(s.code,{...s.reason,file:$}):s}let o;try{let s=We(i.v2Input,{mode:n.mode??"local"});s.manifestVersion!==2&&F("MANIFEST_INVALID","","v2-required"),o=s;}catch(s){throw s instanceof ae?new Ne(s.code,To(s,$,Mc)):s}let r=e.tools;if(Array.isArray(r)){let s=new Set(o.actions.map(a=>a.actionId));r.forEach((a,c)=>{let d=a.name;if(!s.has(d))throw new Ne("MANIFEST_INVALID",{path:`tools[${c}].name`,rule:"tool-not-action",message:"every tools[].name must be an action id",file:$})});}return {file:$,manifest:o,v2Input:i.v2Input,releaseVersion:e.version,...Object.keys(i.passthrough).length>0?{mcpb:i.passthrough}:{}}}function Fc(e,n){try{let t=We(e,{mode:n.mode??"local"});if(t.manifestVersion!==2)throw new Ne("MANIFEST_INVALID",{path:"manifestVersion",rule:"v2-required",message:"a workspace App requires manifestVersion 2",file:de});return {file:de,manifest:t,v2Input:e}}catch(t){throw t instanceof ae?new Ne(t.code,To(t,de,i=>i??"")):t}}function an(e){return pe(mn(e).definition)}function go(e){let{entryHash:n,initialState:t,...i}=e,o={...i};return t!==void 0&&(o.initialState={path:t.path}),Po(o)}function jc(e,n){let t=go(e),i=go(n);return [...new Set([...Object.keys(t),...Object.keys(i)])].sort().filter(r=>te(t[r]??null)!==te(i[r]??null))}function Vc(e,n){return e.entryHash!==void 0&&n.entryHash!==void 0&&e.entryHash!==n.entryHash||e.initialState?.hash!==void 0&&n.initialState?.hash!==void 0&&e.initialState.hash!==n.initialState.hash}function Bc(e,n){let t=jc(e,n),i=Vc(e,n),o="";try{let r=an(e),s=an(n);i=i||r!==s,o=` (definition hash ${r.slice(0,12)} vs ${s.slice(0,12)})`;}catch{i=true;}t.length===0&&!i||F("MANIFEST_DUAL_MISMATCH","","dual-manifest-mismatch",`${$} and ${de} normalize to different definitions${o}`+(t.length>0?`; differing fields: ${t.join(", ")}`:""));}function Pe(e,n,t="MANIFEST_INVALID",i){return {code:t,reason:{path:e,rule:n,...i===void 0?{}:{message:i},file:H},files:[]}}function mo(e){return {...Pe("","tools-needs-manifest-json","MANIFEST_INVALID",`${H} is read with ${$} only`),files:e}}function Hc(e,n){if(e.byteLength>n)return {failure:Pe("","file-too-large","LIMIT_EXCEEDED")};let t;try{t=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e));}catch{return {failure:Pe("","invalid-json")}}if(!ie(t))return {failure:Pe("","not-object","MANIFEST_INVALID",`${H} must be a JSON object`)};for(let o of Object.keys(t))if(o!=="schemaVersion"&&o!=="actions")return {failure:Pe(o,"unknown-key")};for(let o of ["schemaVersion","actions"])if(!Y(t,o))return {failure:Pe(o,"missing-key")};if(t.schemaVersion!==1)return {failure:Pe("schemaVersion","unsupported-version","MANIFEST_INVALID",`schemaVersion must be ${1}`)};let i=t.actions;if(!Array.isArray(i))return {failure:Pe("actions","array")};for(let[o,r]of i.entries()){if(!ie(r))return {failure:Pe(`actions[${o}]`,"object")};if(Y(r,"backend"))return {failure:Pe(`actions[${o}].backend`,"tools-backend","MANIFEST_INVALID",`an action in ${H} cannot carry a backend`)}}return {actions:i}}function zc(e,n){let t=n.maxBytes??262144,i=[],o=new TextDecoder("utf-8",{fatal:true});for(let r of Z){let s=e[r];if(s===void 0)continue;if(s.byteLength>t)return {parsed:i,failure:{code:"LIMIT_EXCEEDED",reason:{path:"",rule:"file-too-large",file:r},files:[r]}};let a;try{a=JSON.parse(o.decode(s));}catch{return {parsed:i,failure:{code:"MANIFEST_INVALID",reason:{path:"",rule:"invalid-json",file:r},files:[r]}}}if(!ie(a))return {parsed:i,failure:{code:"MANIFEST_INVALID",reason:{path:"",rule:"not-object",message:`${r} must be a JSON object`,file:r},files:[r]}};i.push({file:r,raw:a});}return {parsed:i}}function Fe(e,n={}){let{parsed:t,failure:i}=zc(e,n),o=Z.filter(f=>e[f]!==void 0);if(i!==void 0)return {ok:false,rejection:i,parseFailure:true,builtinOnly:false};let r=e[H],s=r===void 0?void 0:Hc(r,n.maxBytes??262144);if(t.length===0)return {ok:false,rejection:s===void 0?{code:"MANIFEST_INVALID",reason:{path:"",rule:"no-manifest-file",message:"neither manifest.json nor ui-plugin.json is present"},files:[]}:mo(o),parseFailure:true,builtinOnly:false};let a=t[0],c=a.file===$?wc(a.raw):Cc(a.raw),d=t.some(f=>Uc(f.file,f.raw)),l;if(s!==void 0){let f=t.some(g=>g.file===$)?s.failure:mo(o);if(f!==void 0)return {ok:false,rejection:f,parseFailure:false,...c===void 0?{}:{identity:c},builtinOnly:d};l=s.actions;}let p=[];try{for(let f of t)p.push(f.file===$?vc(f.raw,n,l):Fc(f.raw,n));p.length===2&&Bc(p[0].manifest,p[1].manifest);}catch(f){if(f instanceof Ne)return {ok:false,rejection:{code:f.code,reason:f.reason,files:f.code==="MANIFEST_DUAL_MISMATCH"?[...Z]:f.reason.file===void 0||f.reason.file===H?o:[f.reason.file]},parseFailure:false,...c===void 0?{}:{identity:c},builtinOnly:d};throw f}let u=p[0];return {ok:true,...u,identity:c??{pluginId:u.manifest.pluginId},files:o}}var $,de,Z,Qt,xe,ti,ii,ho,ei,_o,Tc,Pc,Nc,Dc,bc,Ne,qn=j(()=>{m();ze();Se();Vt();He();Zt();$="manifest.json",de="ui-plugin.json",Z=[$,de],Qt="0.3",xe="dev.crewx",ti=Object.freeze(["manifest_version","name","display_name","version","description","long_description","author","repository","homepage","documentation","support","icon","icons","screenshots","localization","server","tools","tools_generated","prompts","prompts_generated","keywords","license","privacy_policies","compatibility","user_config","_meta"]),ii=Object.freeze(["manifest_version","name","display_name","version","description","_meta"]),ho=Object.freeze(ti.filter(e=>e!=="server"&&!ii.includes(e))),ei=Object.freeze(["entry","surfaces","size","stateProjection","actions"]),_o=Object.freeze(["definitionId","definitionVersion","icon","tone","entryHash","runtime","initialState","usage","detailPanel","displayModes","summaryProjection","dataPaths","focusedAiDataPaths","csp"]),Tc=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/,Pc=256,Nc=/<\/?[A-Za-z][^>]*>/,Dc=/^\s*javascript:/i,bc=/data:[^,\s]*,/i;Ne=class extends Error{constructor(t,i){super(`${t}: ${i.path||"<file>"} (${i.rule})`);this.code=t;this.reason=i;}code;reason};});function Oo(e){if(e===void 0)return {kind:"none"};if(typeof e!="string")return {kind:"invalid",reason:"bad-path"};if(Wc.test(e))return {kind:"url",declared:e};if(!Xc(e))return {kind:"invalid",reason:"bad-path",declared:e};let n=e.lastIndexOf("."),t=n<0?void 0:$c.get(e.slice(n+1).toLowerCase());return t===void 0?{kind:"invalid",reason:"bad-type",declared:e}:{kind:"file",path:e,contentType:t}}function Xc(e){return e.length===0||e.length>512||e.startsWith("/")||e.includes("\\")||e.includes("\0")?false:e.split("/").every(n=>n!==""&&n!=="."&&n!=="..")}async function _n(e,n){let t=Oo(e);if(t.kind==="none")return {diagnostics:[]};if(t.kind==="url")return {diagnostics:[{code:"ICON_NOT_FILE",severity:"warning",declared:t.declared}]};if(t.kind==="invalid")return {diagnostics:[ri(t.reason,t.declared)]};let i=await n(t.path);if(typeof i=="string")return {diagnostics:[ri(i,t.path)]};let o=wo(t.contentType,i);if(!o.ok)return {diagnostics:[ri(o.reason,t.path)]};let r={path:t.path,contentType:t.contentType,byteLength:i.byteLength,bytes:i},s=o.square===false?[{code:"ICON_NOT_SQUARE",severity:"warning",declared:t.path}]:[];return {file:r,diagnostics:s}}function ri(e,n){return {code:"ICON_INVALID",severity:"error",reason:e,...n===void 0?{}:{declared:n}}}function wo(e,n){if(n.byteLength>262144)return {ok:false,reason:"too-large"};if(e==="image/png")return !Mo(n,Jc)||rd(n,12,16)!=="IHDR"||n.byteLength<24?{ok:false,reason:"bytes-mismatch"}:{ok:true,square:So(Lo(n,16),Lo(n,20))};if(e==="image/jpeg"){if(!Mo(n,Kc))return {ok:false,reason:"bytes-mismatch"};let t=id(n);return {ok:true,square:t===void 0?void 0:So(t.width,t.height)}}return Yc(n)}function Yc(e){let n;try{n=Gc.decode(e);}catch{return {ok:false,reason:"bytes-mismatch"}}return nd(n)?{ok:false,reason:"unsafe-svg"}:qc.test(n)?{ok:true,square:td(n)}:{ok:false,reason:"bytes-mismatch"}}function nd(e){if(Zc.some(n=>n.test(e)))return true;for(let n of e.matchAll(Qc))if(!(n[1]??n[2]??n[3]??"").startsWith("#"))return true;for(let n of e.matchAll(ed))if(Do.lastIndex=n.index??0,!Do.test(e))return true;return false}function td(e){let n=/<svg\b[^>]*>/i.exec(e)?.[0];if(n===void 0)return;let t=Co(n,"viewBox");if(t!==void 0){let r=t.trim().split(/[\s,]+/).map(Number);return r.length===4&&r.every(Number.isFinite)?r[2]===r[3]:void 0}let i=bo(n,"width"),o=bo(n,"height");return i===void 0||o===void 0?void 0:i===o}function Co(e,n){let t=new RegExp(`\\s${n}\\s*=\\s*(?:"([^"]*)"|'([^']*)')`).exec(e);return t?.[1]??t?.[2]}function bo(e,n){let t=Co(e,n),i=t===void 0?null:/^\s*(\d+(?:\.\d+)?)(?:px)?\s*$/.exec(t);return i===null?void 0:Number(i[1])}function id(e){let n=2;for(;n+4<=e.byteLength;){if(e[n]!==255)return;let t=e[n+1];if(t===255){n+=1;continue}if(t===216||t===1||t>=208&&t<=215){n+=2;continue}if(t===217)return;let i=e[n+2]<<8|e[n+3];if(i<2)return;if(od(t))return n+9>e.byteLength?void 0:{height:Ro(e,n+5),width:Ro(e,n+7)};n+=2+i;}}function od(e){return e>=192&&e<=207&&e!==196&&e!==200&&e!==204}function So(e,n){if(!(e<=0||n<=0))return e===n}function Mo(e,n){return e.byteLength>=n.length&&n.every((t,i)=>e[i]===t)}function rd(e,n,t){return String.fromCharCode(...e.subarray(n,t))}function Lo(e,n){return (e[n]<<24|e[n+1]<<16|e[n+2]<<8|e[n+3])>>>0}function Ro(e,n){return e[n]<<8|e[n+1]}var $c,Gc,Wc,Jc,Kc,qc,Zc,Qc,ed,Do,si=j(()=>{m();$c=new Map([["svg","image/svg+xml"],["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"]]),Gc=new TextDecoder("utf-8",{fatal:true}),Wc=/^[A-Za-z][A-Za-z0-9+.-]*:/,Jc=[137,80,78,71,13,10,26,10],Kc=[255,216,255];qc=/^\s*(?:<\?[\s\S]*?\?>\s*|<!--[\s\S]*?-->\s*)*<svg(?=[\s/>])/,Zc=[/<script/i,/[\s"'/]on[a-z]+\s*=/i,/<foreignobject/i,/<!doctype/i,/<!entity/i,/<(?:iframe|embed|object)\b/i,/@import/i],Qc=/(?:^|[\s"'/])(?:xlink:)?href\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+))/gi,ed=/url\(/gi,Do=/url\(\s*["']?#/iy;});var ai=j(()=>{m();Vi();qn();si();Zt();He();});function S(e,n=e){throw new De(e,n)}var De,Qn=j(()=>{m();De=class extends Error{constructor(t,i=t){super(i);this.code=t;}code;name="McpAppContractError"};});var Go=j(()=>{m();});var Wo=j(()=>{m();ze();Se();Qn();Go();});function Ko(e,n){return Jo.add(e),n!==void 0&&gd.set(e,n),e}function cn(e){return e!==null&&typeof e=="object"&&Jo.has(e)}var Jo,gd,et=j(()=>{m();Jo=new WeakSet,gd=new WeakMap;});function Nn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function di(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 qo(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let n of Object.values(e))qo(n);return Object.freeze(e)}function oe(e){throw new be("LINEAGE_INVALID",e)}function Nd(e){throw new be("LINEAGE_STALE",e)}function Zo(e){if(!Nn(e)||!di(e,_d,Ed)||!Nn(e.actions))return oe("Lineage definition shape is invalid");for(let n of Object.values(e.actions))if(!Nn(n)||!di(n,Td,Pd))return oe("Lineage action definition shape is invalid");return e}function Dd(e){if(!Nn(e)||!di(e,md,hd))return oe("Lineage entry shape is invalid");if(!Number.isSafeInteger(e.version)||e.version<1||typeof e.hash!="string"||!Xo.test(e.hash))return oe("Lineage entry identity is invalid");if(e.sourceHash!==void 0&&(typeof e.sourceHash!="string"||!Xo.test(e.sourceHash)))return oe("Lineage source hash is invalid");if(e.compat!==void 0&&e.compat!=="break")return oe("Lineage compatibility marker is invalid");let n=Zo(e.definition);if(n.version!==e.version)return oe("Lineage version does not match its definition");if(e.sourceHash!==void 0&&n.sourceHash!==e.sourceHash)return oe("Lineage source hash does not match its definition");let t;try{t=pe(n),ye({...n,hash:e.hash});}catch{return oe("Lineage definition is invalid")}return t!==e.hash?oe("Lineage definition hash does not match"):qo({version:e.version,hash:e.hash,definition:n,...e.sourceHash===void 0?{}:{sourceHash:e.sourceHash},...e.compat===void 0?{}:{compat:e.compat}})}function Yo(e){return e.stateProjection?.allow??[]}function bd(e,n){let t=[],i=new Set(Yo(n));Yo(e).some(a=>!i.has(a))&&t.push("S1_STATE_PROJECTION");let o=new Set(n.dataPaths??[]);(e.dataPaths??[]).some(a=>!o.has(a))&&t.push("S2_DATA_PATHS");for(let[a,c]of Object.entries(e.actions)){let d=n.actions[a];if(d&&(c.confirmation??"native")==="native"&&(d.confirmation??"native")!=="native"){t.push("S3_ACTION_CONFIRMATION");break}}Object.keys(e.legacy?.agentAccess??{}).some(a=>!Object.hasOwn(n.actions,a))&&t.push("S4_LEGACY_AGENT_ACTIONS");let s=e.summaryProjection?.allow;if(s!==void 0){let a=new Set(n.summaryProjection?.allow??[]);s.some(c=>!a.has(c))&&t.push("S5_SUMMARY_PROJECTION");}return t}function Sd(e,n){return te(e)===te(n)}function pi(e,n){if(!Array.isArray(e)||e.length===0)return oe("Definition lineage is missing");if(!Nn(n)||typeof n.hash!="string")return oe("Current definition is invalid");let t,i;try{let{hash:a,...c}=n;i=Zo(c),t={...i,hash:a},ye(t);}catch{return oe("Current definition is invalid")}let o=e.map(Dd),r=o[0].definition.id;if(o.some(a=>a.definition.id!==r))return oe("Lineage definition ids do not match");if(o.some((a,c)=>c>0&&a.version<=o[c-1].version))return oe("Lineage generations are not in increasing version order");if(o.some((a,c)=>o.findIndex(d=>d.hash===a.hash)!==c))return oe("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||!Sd(s.definition,i))return Nd("The last lineage generation does not match the current package");if(t.legacy!==void 0){let a=new Set(Object.keys(t.actions)),c=new Set;for(let l of o)if(l.sourceHash===void 0)for(let p of Object.keys(l.definition.actions))a.has(p)&&c.add(p);let d=Object.keys(t.legacy.agentAccess??{});if(d.length!==c.size||d.some(l=>!c.has(l))){let l="S4_LEGACY_AGENT_ACCESS_COMPLETE";throw new be("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 d=bd(o[a].definition,t);if(d.length>0)throw new be("LINEAGE_INVALID",`Lineage compatibility failed: ${d.join(", ")}`,d)}return Object.freeze({entries:Object.freeze(o),current:t})}var be,Xo,md,hd,_d,Ed,Td,Pd,li=j(()=>{m();ze();Se();be=class extends Error{constructor(t,i=t,o=[]){super(i);this.code=t;this.violations=o;}code;violations;name="UiDefinitionLineageError"},Xo=/^[0-9a-f]{64}$/,md=["version","hash","definition"],hd=["sourceHash","compat"],_d=["id","version","actions"],Ed=["sourceHash","usage","detailPanel","displayModes","renderer","surfaces","stateProjection","dataPaths","summaryProjection","legacy"],Td=["capabilities"],Pd=["inputKeys","dataInputs","confirmation","resultProjection","content","env","schedule"];});var Qo,er,nr,tr,ir=j(()=>{m();Qo="text/html;profile=mcp-app",er=["crewx_app_terminal_connect","crewx_app_html_viewer_open"],nr=["crewx_listWorkspaces","crewx_queryAgent","crewx_executeAgent","crewx_getTaskResult","crewx_listTasks","crewx_listAgents","callBrowser","openTab","listTabs","closeTab"],tr="text/html";});function Dn(e){return typeof e=="string"&&Md.includes(e)}function nt(e,n){return e==="card"&&n?.type==="core"&&Dn(n.handler)}var Md,tt=j(()=>{m();Md=Object.freeze(["card.secret-env"]);});function or(e,n=[],t){if(e.content!==void 0||e.confirmation!=="none")return "denied";let i=Ld();return i&&Object.hasOwn(i,e.actionId)?i[e.actionId]:e.backend?.type==="core"&&e.backend.handler.startsWith("host.")?"denied":e.backend?.type==="core"&&e.backend.handler==="state.set"?"allowed":e.backend?.type==="core"&&Dn(e.backend.handler)||e.backend?.type==="skill"?"approval_required":e.backend===void 0&&n.includes(e.actionId)?"allowed":"denied"}function Ld(e){return;}var rr=j(()=>{m();ze();et();tt();});function Fd(e){return Mn.has(e)&&(e.initialState===void 0||Mn.has(e.initialState))}function pr(e,n,t,i){let o=i===void 0?void 0:Object.freeze({hash:i.hash,bytes:Object.freeze(i.bytes)}),r=Object.freeze({mimeType:tr,entryHash:e,html:n,bytes:Object.freeze(t),...o===void 0?{}:{initialState:o}});return o!==void 0&&Mn.add(o),Mn.add(r),r}function jd(e){let n=[];return e?.terminal===true&&n.push({name:"crewx_app_terminal_connect",description:"Open a local-only terminal session for this App.",inputSchema:{type:"object",properties:{workspace:{type:"string"},threadId:{type:"string"},instanceId:{type:"string"}},required:["threadId","instanceId"],additionalProperties:false},textFallback:"A local terminal connection is ready for this App.",visibility:Object.freeze(["app"]),kind:"host",resourceBinding:je}),e?.htmlDocuments===true&&n.push({name:"crewx_app_html_viewer_open",description:"List workspace HTML documents or open one through a short-lived Host capability.",inputSchema:{type:"object",properties:{workspace:{type:"string"},threadId:{type:"string"},instanceId:{type:"string"},operation:{type:"string",enum:["list","open"]},documentId:{type:"string"}},required:["threadId","instanceId","operation"],additionalProperties:false},textFallback:"Workspace HTML documents are available through this App.",visibility:Object.freeze(["app"]),kind:"host",resourceBinding:je}),n}function Ve(e,n,t){return (typeof e!="string"||!cr.test(e))&&S(n,`${t} must be a safe identifier`),e}function bn(e,n,t){let i=e??t;return (typeof i!="string"||i.trim().length===0||i.length>wd)&&S("TOOL_INVALID",`${n} must be a meaningful description`),i}function fi(e){return (typeof e!="string"||e.length===0||e.length>dn||!/<html(?:\s|>)/i.test(e)||!/<\/html\s*>/i.test(e))&&S("HTML_INVALID","MCP App HTML must be a non-empty HTML document"),e}function Sn(e,n=0){try{let t=fe(e,n);return t.type!==void 0&&t.type!=="object"&&S("TOOL_INVALID","MCP App inputSchema must describe an object"),t}catch(t){if(t instanceof De)throw t;S("TOOL_INVALID","MCP App inputSchema must be projection-safe JSON");}}function Vd(e){return (typeof e!="string"||e.trim().length===0||e.length>Cd)&&S("TOOL_INVALID","MCP App tools require a meaningful text fallback"),e}function Bd(e){e===void 0&&S("TOOL_INVALID","MCP App tool visibility is required");let n=[...e];return (n.length===0||n.some(t=>t!=="model"&&t!=="app")||new Set(n).size!==n.length)&&S("TOOL_INVALID","MCP App tool visibility must contain model and/or app once"),n}function ur(e){return (typeof e!="string"||!dr.test(e))&&S("RESOURCE_URI_INVALID","MCP App resource URI is not a registered ui:// URI"),e}function fr(e){let n=Ve(e.appId,"APP_ID_INVALID","Local App id"),t=bn(e.name,"Local App name",n),i=bn(e.description,"Local App description",`${t} interactive view`),o=st(e.definition),r=fi(e.html),s=it(e.entryHash,"Local App entry hash"),a=e.entryBytes===void 0?Array.from(new TextEncoder().encode(r)):rt(e.entryBytes,"Local App entry bytes");(ot(a)!==s||Ir(a)!==r)&&S("HTML_INVALID","Local App entry bytes do not match the HTML hash");let c=Hd(e),d=[];Array.isArray(e.actions)||S("TOOL_INVALID","Local App actions must be an array");for(let N of e.actions){let O=Ve(N.actionId,"TOOL_ID_INVALID","Local App action id");(d.includes(O)||!Object.prototype.hasOwnProperty.call(o.actions,O))&&S("TOOL_INVALID",`Local App action is not declared by the UI definition: ${O}`),d.push(O);}let l=Ve(e.readToolName,"TOOL_ID_INVALID","Local App read tool name"),p=e.actionToolName===void 0?void 0:Ve(e.actionToolName,"TOOL_ID_INVALID","Local App action tool name");d.length===0&&p!==void 0&&S("TOOL_INVALID","A static local App cannot register an action tool"),d.length>0&&p===void 0&&S("TOOL_INVALID","A stateful local App requires an action tool name"),p!==void 0&&p===l&&S("TOOL_ID_CONFLICT",`Local App read and action tools share a name: ${l}`);let u=jd(e.runtime);u.some(N=>N.name===l||N.name===p)&&S("TOOL_ID_CONFLICT","Local App read or action tool conflicts with a requested Host capability");let f={name:l,description:`${t} current state`,inputSchema:vd,textFallback:`${t} current state is available through its open instance.`,visibility:Object.freeze(["model","app"]),kind:"read",resourceBinding:je},g=[Object.freeze(f)];if(g.push(...u.map(N=>Object.freeze(N))),p!==void 0){let N={name:p,description:`${t} actions`,inputSchema:yi(e.actions),textFallback:`${t} action requests are handled by the open App instance.`,visibility:Object.freeze(["app"]),kind:"action",resourceBinding:je,actionIds:Object.freeze([...d])};g.push(Object.freeze(N));}let _=[],P=new Set(g.map(N=>N.name));if(p!==void 0)for(let N of e.actions){let O=`${p}__${N.actionId}`;if(O.length>128||!cr.test(O)){_.push(Object.freeze({toolName:O,actionId:N.actionId,reason:"name_too_long"}));continue}if(P.has(O)){_.push(Object.freeze({toolName:O,actionId:N.actionId,reason:"name_collision"}));continue}let V=or({actionId:N.actionId,confirmation:o.actions[N.actionId]?.confirmation,content:o.actions[N.actionId]?.content,backend:N.backend},e.modelActions),D=Object.freeze([...Jd(V,o.usage,N.backend)]),b={name:O,description:`${O} action`,inputSchema:Sn(N.inputSchema),textFallback:`${O} action requests are handled by the open App instance.`,visibility:D,kind:"action",resourceBinding:je,actionId:N.actionId,actionIds:Object.freeze([N.actionId]),_meta:Object.freeze({ui:Object.freeze({visibility:D})})};g.push(Object.freeze(b)),P.add(O);}let C=pr(s,r,a,c===void 0?void 0:{hash:c.hash,bytes:[...c.bytes]}),U={appId:n,name:t,description:i,...e.icon===void 0?{}:{icon:gr(e.icon)},...e.tone===void 0?{}:{tone:mr(e.tone)},builtinOnly:false,definition:o,...e.runtime===void 0?{}:{runtime:Object.freeze({...e.runtime})},resourceBinding:je,resource:C,tools:Object.freeze(g),toolDiagnostics:Object.freeze(_)};return Q(U)}function yr(e={}){return new ui(e)}function yi(e){if(e.length===0)return Sn({type:"object",properties:{},additionalProperties:false});let n=e.map(i=>i.actionId),t=new Map;for(let i of e)t.set(i.actionId,Sn(i.inputSchema));return Sn(zd(n,t),lr)}function Hd(e){let n=e.definition.dataPaths??[];if(e.initialStateBytes===void 0){e.initialStateHash!==void 0&&S("STATE_INVALID","Initial state hash has no bytes"),e.initialState!==void 0&&fe(e.initialState,0,n);return}e.initialStateHash===void 0&&S("STATE_INVALID","Initial state bytes require a hash");let t=it(e.initialStateHash,"Initial state hash"),i=rt(e.initialStateBytes,"Initial state bytes");ot(i)!==t&&S("STATE_INVALID","Initial state bytes do not match the hash");let o;try{let r=new TextDecoder("utf-8",{fatal:!0}).decode(Uint8Array.from(i));o=fe(JSON.parse(r),0,n);}catch{S("STATE_INVALID","Initial state bytes are not projection-safe JSON");}return e.initialState!==void 0&&te(o)!==te(fe(e.initialState,0,n))&&S("STATE_INVALID","Initial state bytes do not match the state value"),{hash:t,bytes:Object.freeze([...i])}}function zd(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})}function $d(e){let n=Ln(e),t=Ve(n.appId,"APP_ID_INVALID","MCP App id"),i=fi(n.html);ur(n.uiUri);let o=n.definition===void 0?void 0:st(n.definition),r=e.provenance;r!==void 0&&(!cn(r)||r.appId!==t||r.definitionId!==o?.id||r.version!==o?.version||r.definitionHash!==o?.hash)&&S("TOOL_INVALID","Product App built-in registration provenance is not verified");let s=Object.freeze(n.tools.map(d=>Q(Ln(d)))),a=Q({...n,appId:t,html:i,...o===void 0?{}:{definition:o},...r===void 0?{}:{provenance:r},tools:s}),c=Q({uri:a.uiUri,mimeType:Qo,text:i,...a.csp===void 0?{}:{_meta:{ui:{csp:a.csp}}}});return Q({appId:t,name:a.name,description:a.description,...a.icon===void 0?{}:{icon:a.icon},...a.tone===void 0?{}:{tone:a.tone},builtinOnly:a.builtinOnly,uiUri:a.uiUri,...o===void 0?{}:{definition:o},resourceBinding:Object.freeze({kind:"mcp",uri:a.uiUri}),resource:c,tools:s,descriptor:a})}function Gd(e){(e.resourceBinding.kind!=="instance"||e.builtinOnly!==false)&&S("STATE_INVALID","Local App registration binding is invalid"),Object.prototype.hasOwnProperty.call(e,"uiUri")&&S("STATE_INVALID","Local App registration cannot contain uiUri");let n=Ve(e.appId,"APP_ID_INVALID","Local App id"),t=st(e.definition),i=e.provenance;i!==void 0&&(!cn(i)||i.appId!==n||i.definitionId!==t.id||i.version!==t.version||i.definitionHash!==t.hash)&&S("TOOL_INVALID","Product App local registration provenance is not verified");let o=Wd(e.resource),r=e.tools.map(a=>{Ve(a.name,"TOOL_ID_INVALID","Local App tool name"),bn(a.description,"Local App tool description","Local App tool"),Vd(a.textFallback);let c=Sn(a.inputSchema,a.kind==="action"&&!("actionId"in a)?lr:0);if((a.resourceBinding.kind!=="instance"||Object.prototype.hasOwnProperty.call(a,"resourceUri"))&&S("TOOL_INVALID","Local App tools cannot carry an MCP resource URI"),a.kind==="host")return (!xd.has(a.name)||a.visibility.length!==1||a.visibility[0]!=="app"||Object.prototype.hasOwnProperty.call(a,"actionId"))&&S("TOOL_INVALID","Local App Host tools must use an allow-listed name and app-only visibility"),Q({...a,inputSchema:c,visibility:Object.freeze(["app"])});if(a.kind==="action"){if("actionId"in a){let l=Ve(a.actionId,"TOOL_ID_INVALID","Local App action id");Object.prototype.hasOwnProperty.call(t.actions,l)||S("TOOL_INVALID","Local App action tool references an undeclared action");let p=Bd(a._meta.ui.visibility);return JSON.stringify(p)!==JSON.stringify(a.visibility)&&S("TOOL_INVALID","Local App action metadata visibility must match the tool visibility"),Q({...a,actionId:l,actionIds:Object.freeze([l]),inputSchema:c,visibility:p,_meta:{ui:{visibility:p}}})}let d=[...a.actionIds];return (d.length===0||d.some(l=>!Object.prototype.hasOwnProperty.call(t.actions,l)))&&S("TOOL_INVALID","Local App action tool references an undeclared action"),Q({...a,inputSchema:c,actionIds:Object.freeze(d)})}return Q({...a,inputSchema:c})}),s=Q({appId:n,name:bn(e.name,"Local App name",e.appId),description:bn(e.description,"Local App description",e.name),...e.icon===void 0?{}:{icon:gr(e.icon)},...e.tone===void 0?{}:{tone:mr(e.tone)},builtinOnly:false,definition:t,...e.runtime===void 0?{}:{runtime:Object.freeze({...e.runtime})},...i===void 0?{}:{provenance:i},resourceBinding:je,resource:o,tools:Object.freeze(r),toolDiagnostics:Object.freeze([...e.toolDiagnostics??[]])});return sr.has(e)?e:(sr.add(s),s)}function Wd(e){let n=fi(e.html),t=it(e.entryHash,"Local App entry hash");if(Fd(e))return e;let i=rt(e.bytes,"Local App entry bytes");(ot(i)!==t||Ir(i)!==n)&&S("HTML_INVALID","Local App entry bytes do not match the HTML hash");let o=e.initialState===void 0?void 0:{hash:it(e.initialState.hash,"Initial state hash"),bytes:rt(e.initialState.bytes,"Initial state bytes")};return o&&ot(o.bytes)!==o.hash&&S("STATE_INVALID","Initial state bytes do not match the hash"),pr(t,n,i,o)}function Jd(e,n,t){if(nt(n,t))return ["model"];let i=t?.type==="core"&&Dn(t.handler);return e==="denied"||i?["app"]:["model","app"]}function Kd(e){return Q({appId:e.appId,name:e.name,description:e.description,...e.icon===void 0?{}:{icon:e.icon},...e.tone===void 0?{}:{tone:e.tone},builtinOnly:false,definition:Ar(e.definition),...e.provenance===void 0?{}:{provenance:e.provenance},entryHash:e.resource.entryHash,resourceBinding:je,tools:e.tools})}function Xd(e){return Q({appId:e.appId,name:e.name,description:e.description,...e.icon===void 0?{}:{icon:e.icon},...e.tone===void 0?{}:{tone:e.tone},builtinOnly:e.builtinOnly,uiUri:e.uiUri,...e.definition===void 0?{}:{definition:Ar(e.definition)},resourceBinding:Object.freeze({kind:"mcp",uri:e.uiUri}),tools:e.tools})}function st(e){try{if(Object.isFrozen(e))return ye(e),Q(e);let n=Ln(e);return ye(n),Q(n)}catch(n){if(n instanceof De)throw n;S("STATE_INVALID","UI definition is not a valid immutable definition");}}function Ar(e){return Q({id:e.id,version:e.version,hash:e.hash})}function Yd(e){return e!==null&&typeof e=="object"&&typeof e.id=="string"&&Number.isSafeInteger(e.version)&&typeof e.hash=="string"}function ar(e,n,t){return `${e}\0${n}\0${t}`}function it(e,n){return (typeof e!="string"||!Od.test(e))&&S("SERIALIZATION_INVALID",`${n} is invalid`),e}function ot(e){return xi.createHash("sha256").update(Uint8Array.from(e)).digest("hex")}function rt(e,n){return (!Array.isArray(e)||e.some(t=>!Number.isInteger(t)||t<0||t>255))&&S("SERIALIZATION_INVALID",`${n} is invalid`),[...e]}function Ir(e){try{return new TextDecoder("utf-8",{fatal:!0}).decode(Uint8Array.from(e))}catch{S("SERIALIZATION_INVALID","UTF-8 bytes are invalid");}}function gr(e){return (typeof e!="string"||!Ud.test(e))&&S("TOOL_INVALID","MCP App icon is invalid"),e}function mr(e){return (typeof e!="string"||!kd.has(e))&&S("TOOL_INVALID","MCP App tone is invalid"),e}function Ln(e,n=new Map){if(e===null||typeof e!="object")return e;let t=e;if(n.has(t)&&S("SERIALIZATION_INVALID","MCP App value contains a cycle"),Array.isArray(e)){let r=[];n.set(t,r);for(let s of e)r.push(Ln(s,n));return n.delete(t),r}let i;try{i=Object.getPrototypeOf(e);}catch{S("SERIALIZATION_INVALID","MCP App value cannot be cloned");}i!==Object.prototype&&i!==null&&S("SERIALIZATION_INVALID","MCP App value must be plain JSON");let o={};n.set(t,o);for(let[r,s]of Object.entries(e))Object.defineProperty(o,r,{configurable:true,enumerable:true,value:Ln(s,n),writable:true});return n.delete(t),o}function Q(e,n=new Set){if(e===null||typeof e!="object"||n.has(e)||Mn.has(e))return e;n.add(e);for(let t of Object.values(e))Q(t,n);return Object.freeze(e),e}var cr,dr,Od,dn,wd,Cd,Ud,kd,xd,je,vd,Mn,sr,lr,ui,at=j(()=>{m();Wo();ze();Se();et();Qn();li();ir();rr();tt();cr=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,dr=/^ui:\/\/crewx\/([A-Za-z][A-Za-z0-9._-]{0,127})\/([0-9a-f]{12})$/,Od=/^[0-9a-f]{64}$/,dn=8*1024*1024,wd=8*1024,Cd=16*1024,Ud=/^[a-z][a-z0-9-]{0,63}$/,kd=new Set(["blue","violet","emerald","amber","rose","sky","slate","indigo"]),xd=new Set(er),new Set(nr),je=Object.freeze({kind:"instance"}),vd=Object.freeze({type:"object",properties:Object.freeze({}),additionalProperties:false}),Mn=new WeakSet,sr=new WeakSet;lr=4;ui=class{builtinApps;localApps;builtinDescriptors;builtinTools;mcpResources=new Map;localById=new Map;registrationById=new Map;launcherById=new Map;definitionByKey=new Map;handlerByKey=new Map;mcpToolByName=new Map;localToolByName=new Map;constructor(n){let t=n.builtins??n.builtin,i=[],o=[],r=[],s=new Set,a=new Set;for(let p of t?.listMcpApps()??[]){let u=$d(p);s.has(u.appId)&&S("APP_ID_CONFLICT",`MCP App id is already registered: ${u.appId}`),s.add(u.appId);let f=u.tools;for(let g of f)a.has(g.name)&&S("TOOL_ID_CONFLICT",`MCP App tool name is already registered: ${g.name}`),a.add(g.name),this.mcpToolByName.set(g.name,g),r.push(g);this.mcpResources.set(u.resource.uri,u.resource),i.push(u),o.push(u.descriptor);}let c=(n.localApps??n.locals??[]).map(Gd),d=new Set(c.flatMap(p=>p.tools.filter(u=>!(u.kind==="action"&&"actionId"in u)).map(u=>u.name))),l=[];for(let p of c){let u=p;s.has(u.appId)&&S("APP_ID_CONFLICT",`MCP App id is already registered: ${u.appId}`),s.add(u.appId);let f=[],g=[...u.toolDiagnostics??[]];for(let _ of u.tools){if(a.has(_.name)){if(_.kind==="host"&&this.localToolByName.get(_.name)?.kind==="host"){f.push(_);continue}if(_.kind==="action"&&"actionId"in _){g.push(Object.freeze({toolName:_.name,actionId:_.actionId,reason:"name_collision"}));continue}S("TOOL_ID_CONFLICT",`MCP App tool name is already registered: ${_.name}`);}if(_.kind==="action"&&"actionId"in _&&d.has(_.name)){g.push(Object.freeze({toolName:_.name,actionId:_.actionId,reason:"name_collision"}));continue}a.add(_.name),this.localToolByName.set(_.name,_),f.push(_);}(f.length!==u.tools.length||g.length!==(u.toolDiagnostics?.length??0))&&(u=Q({...u,tools:Object.freeze(f),toolDiagnostics:Object.freeze(g)})),l.push(u),this.localById.set(u.appId,u);}for(let p of i)this.registrationById.set(p.appId,p),this.launcherById.set(p.appId,Xd(p)),p.definition&&this.addDefinition(p.definition);for(let p of l)this.registrationById.set(p.appId,p),this.launcherById.set(p.appId,Kd(p)),this.addDefinition(p.definition);for(let p of n.definitions??[])this.addDefinition(p);for(let p of n.handlers??[])this.addHandler(p);this.builtinApps=Object.freeze(i),this.localApps=Object.freeze(l),this.builtinDescriptors=Object.freeze(o),this.builtinTools=Object.freeze(r);}getMcpApp(n){return this.builtinApps.find(t=>t.appId===n)?.descriptor??null}listMcpApps(){return this.builtinDescriptors}listMcpAppTools(){return this.builtinTools}resolveMcpAppTool(n){return this.mcpToolByName.get(n)??null}resolveMcpAppResource(n){return typeof n!="string"||!dr.test(n)?null:this.mcpResources.get(n)??null}requireMcpAppResource(n){ur(n);let t=this.mcpResources.get(n);return t||S("RESOURCE_NOT_FOUND",`MCP App resource is not registered: ${n}`),t}listLocalMcpApps(){return this.localApps}getLocalMcpApp(n){return this.localById.get(n)??null}listLocalMcpAppTools(){return Object.freeze([...this.localToolByName.values()])}resolveLocalMcpAppTool(n){return this.localToolByName.get(n)??null}resolveLocalMcpAppResource(n,t){let i=this.localById.get(n);return !i||t!==void 0&&i.definition.hash!==t?null:i.resource}listRegistrations(){return Object.freeze([...this.builtinApps,...this.localApps])}getRegistration(n){return this.registrationById.get(n)??null}listLaunchers(){return Object.freeze([...this.launcherById.values()].filter(n=>{let t=this.registrationById.get(n.appId),i=t?"descriptor"in t?t.descriptor.provenance:t.provenance:void 0,o=cn(i)&&i.launcher===false;return t?.definition?.usage!=="card"&&!o}))}listCardApps(){return Object.freeze([...this.launcherById.values()].filter(n=>this.registrationById.get(n.appId)?.definition?.usage==="card"))}getLauncher(n){return this.launcherById.get(n)??null}resolveDefinition(n){if(!Yd(n))return null;let t=this.definitionByKey.get(jt(n));if(!t||t.hash!==n.hash)return null;try{return pe(t)===t.hash?t:null}catch{return null}}resolveActionHandler(n,t,i){return typeof n!="string"||typeof i!="string"||!Number.isSafeInteger(t)?null:this.handlerByKey.get(ar(n,t,i))??null}addDefinition(n){let t=st(n),i=jt(t),o=this.definitionByKey.get(i);o&&o.hash!==t.hash&&S("STATE_INVALID",`UI definition generation conflicts: ${i}`),o||this.definitionByKey.set(i,t);}addHandler(n){(!n||typeof n.definitionId!="string"||typeof n.actionId!="string"||!Number.isSafeInteger(n.version)||n.version<1||typeof n.handle!="function")&&S("STATE_INVALID","UI action handler registration is invalid");let t=ar(n.definitionId,n.version,n.actionId);this.handlerByKey.has(t)&&S("TOOL_INVALID",`Duplicate UI action handler registration: ${t}`),this.handlerByKey.set(t,Object.freeze({...n}));}};});function qd(e){let n=fr({appId:e.appId,name:e.name,description:e.description,...e.icon===void 0?{}:{icon:e.icon},...e.tone===void 0?{}:{tone:e.tone},...e.normalized.manifest.runtime===void 0?{}:{runtime:e.normalized.manifest.runtime},definition:e.definition,html:e.html,entryHash:e.entryHash,entryBytes:e.entryBytes,initialState:e.initialState,...e.initialStateHash===void 0?{}:{initialStateHash:e.initialStateHash},...e.initialStateBytes===void 0?{}:{initialStateBytes:e.initialStateBytes},readToolName:e.toolNames.read,...e.toolNames.action===void 0?{}:{actionToolName:e.toolNames.action},actions:e.normalized.manifest.actions.map(i=>({actionId:i.actionId,inputSchema:i.inputSchema,backend:i.backend}))});return e.provenance===void 0?n:Object.freeze({...n,provenance:e.provenance})}function hr(e){let n=e.normalized.manifest.actions;if(n.some(i=>i.backend.type==="skill")&&n.some(i=>i.backend.type==="core"))throw new Error("Mixed workspace App execution models");let t=qd(e);yr({localApps:[t],definitions:[e.definition]});}var _r=j(()=>{m();at();});function Zd(e){if(e===null||typeof e!="object"||!(Er in e))throw new TypeError("scanCache must be created by createWorkspaceAppScanCache");return e[Er]}function Tr(e,n){let t=Zd(e),i=t.rootIdentity;return i!==void 0&&(i.dev!==n.dev||i.ino!==n.ino||i.realPath!==n.realPath)&&(t.candidates.clear(),t.assetCatalogs.clear(),t.preparedCandidates.clear(),t.lastCandidateScanUnchanged=void 0,t.lastCandidateKeys=void 0,t.scanStartedAtNs=void 0,t.lastAssetCatalogsUnchanged=void 0,t.lastSnapshot=void 0,t.lastSnapshotBuildInputs=void 0,t.lastSnapshotCandidates=void 0,t.lastSnapshotCatalogFingerprint=void 0),t.rootIdentity=n,t}var Er,Pr=j(()=>{m();Er=Symbol("crewx.workspace-app-scan-cache.state");});function le(e){let n=typeof e=="object"&&e!==null&&"code"in e?String(e.code):"";return n==="ENOENT"?new M("NOT_FOUND"):n==="ELOOP"?new M("PATH_ESCAPED"):n==="EFBIG"||n==="EOVERFLOW"?new M("LIMIT_EXCEEDED"):n==="EACCES"||n==="EPERM"||n==="ENOTDIR"?new M("READ_DENIED"):new M("READ_DENIED")}function tp(e){if(typeof e!="string"||e.length===0||!ce.isAbsolute(e))throw new M("READ_DENIED")}function Ai(e){if(typeof e!="string"||ce.isAbsolute(e)||/[\\\u0000]/.test(e))throw new M("PATH_ESCAPED");if(e==="")return [];let n=e.split("/");if(n.some(t=>t.length===0||t==="."||t===".."))throw new M("PATH_ESCAPED");return n}function lt(e,n){let t=ce.relative(e,n);return t===""||t!==".."&&!t.startsWith(`..${ce.sep}`)&&!ce.isAbsolute(t)}function ln(e){return {dev:e.dev,ino:e.ino,size:e.size,mtimeNs:e.mtimeNs,ctimeNs:e.ctimeNs}}function hi(e,n){return e.dev===n.dev&&e.ino===n.ino}function _i(e,n){return hi(e,n)&&e.size===n.size&&e.mtimeNs===n.mtimeNs&&e.ctimeNs===n.ctimeNs}async function ct(e){tp(e);let n,t;try{n=await promises.realpath(e),t=await promises.stat(n,{bigint:!0});}catch(i){throw le(i)}if(!t.isDirectory())throw new M("READ_DENIED");return {realRoot:n,identity:ln(t)}}async function br(e,n,t){if(t.length<2||t[0]!=="apps"&&t[0]!=="skills")return;let i,o;try{if(i=ce.resolve(e,t[0],t[1]),o=await promises.realpath(i),!(await promises.stat(o,{bigint:!0})).isDirectory())throw new M("READ_DENIED")}catch(r){throw r instanceof M?r:le(r)}if(!lt(n,o))throw new M("PATH_ESCAPED");return o}async function dt(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 le(a)}if(!lt(n,r)||t!==void 0&&!lt(t,r))throw new M("PATH_ESCAPED");if(!o.isFile()||!s.isFile())throw new M("READ_DENIED");if(!hi(i,o)||!hi(i,s)||i.dev!==s.dev)throw new M("PATH_ESCAPED")}async function pn(e,n){let t,i;try{t=await promises.realpath(e),i=await promises.stat(t,{bigint:!0});}catch{throw new M("PATH_ESCAPED")}if(t!==n.realRoot||!_i(n.identity,ln(i)))throw new M("PATH_ESCAPED")}function ip(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 M,mi,np,Dr,ut,Sr,Ti=j(()=>{m();M=class extends Error{constructor(t){super(t);this.code=t;}code;name="AppDiscoveryFsError"},mi=ee.constants.O_NOFOLLOW,np=ee.constants.O_NONBLOCK,Dr=ee.constants.O_RDONLY|(mi??0)|(np??0);ut=class{async getRootIdentity(n){let t=await ct(n);return await pn(n,t),{dev:t.identity.dev,ino:t.identity.ino,realPath:t.realRoot}}async listDirectory(n,t){let i=Ai(t),o=await ct(n),r=ce.resolve(n,...i),s,a;try{s=await promises.realpath(r),a=await promises.stat(s,{bigint:!0});}catch(c){let d=le(c);if(d.code==="NOT_FOUND")return [];throw d}if(!lt(o.realRoot,s)||!a.isDirectory())throw new M("PATH_ESCAPED");try{let c=await promises.readdir(s,{withFileTypes:!0,encoding:"utf8"});return await pn(n,o),c.map(ip)}catch(c){let d=le(c);if(d.code==="NOT_FOUND")return [];throw d}}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 M("READ_DENIED");if(mi===void 0)throw new M("UNSUPPORTED");let o=Ai(t),r=await ct(n),s=ce.resolve(n,...o),a=ce.relative(n,s);if(a===".."||a.startsWith(`..${ce.sep}`)||ce.isAbsolute(a))throw new M("PATH_ESCAPED");let c;try{c=await promises.open(s,Dr);}catch(d){throw le(d)}try{let d;try{let g=await c.stat({bigint:!0});d=ln(g);}catch(g){throw le(g)}if(d.size>BigInt(i))throw new M("LIMIT_EXCEEDED");if(d.size>BigInt(Number.MAX_SAFE_INTEGER))throw new M("LIMIT_EXCEEDED");await pn(n,r);let l=await br(n,r.realRoot,o);await dt(s,r.realRoot,l,d);let p=new Uint8Array(new ArrayBuffer(Number(d.size))),u=0;for(;u<p.byteLength;){let g;try{g=(await c.read(p,u,p.byteLength-u,u)).bytesRead;}catch(_){throw le(_)}if(g<=0)throw new M("IDENTITY_CHANGED");u+=g;}let f;try{let g=await c.stat({bigint:!0});f=ln(g);}catch(g){throw le(g)}if(!_i(d,f))throw new M("IDENTITY_CHANGED");return await dt(s,r.realRoot,l,f),await pn(n,r),new Uint8Array(p)}finally{await c.close().catch(()=>{});}}async fingerprintVerifiedFile(n,t,i){if(!Number.isSafeInteger(i)||i<0)throw new M("READ_DENIED");if(mi===void 0)throw new M("UNSUPPORTED");let o=Ai(t),r=await ct(n),s=ce.resolve(n,...o),a=ce.relative(n,s);if(a===".."||a.startsWith(`..${ce.sep}`)||ce.isAbsolute(a))throw new M("PATH_ESCAPED");let c;try{c=await promises.open(s,Dr);}catch(d){throw le(d)}try{let d;try{let u=await c.stat({bigint:!0});d=ln(u);}catch(u){throw le(u)}if(d.size>BigInt(i)||d.size>BigInt(Number.MAX_SAFE_INTEGER))throw new M("LIMIT_EXCEEDED");await pn(n,r);let l=await br(n,r.realRoot,o);await dt(s,r.realRoot,l,d);let p;try{let u=await c.stat({bigint:!0});p=ln(u);}catch(u){throw le(u)}if(!_i(d,p))throw new M("IDENTITY_CHANGED");return await dt(s,r.realRoot,l,p),await pn(n,r),{...p,candidateRealPath:l??r.realRoot}}catch(d){throw d instanceof M?d:le(d)}finally{await c.close().catch(()=>{});}}async readFileVerified(n,t,i){return this.readVerifiedFile(n,t,i)}},Sr=new ut;});function Cn(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 Lr(e){return typeof e=="string"&&Ee.test(e)?e:void 0}function pp(e){return e.length>0&&e!=="."&&e!==".."&&!/[\\/\u0000]/.test(e)}function Ke(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 lp(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 up(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 fp(e){return cp.decode(e)}function yp(e){return JSON.parse(fp(e))}function Rr(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 Ap(e){if(e instanceof M)return Rr(e.code);if(e!==null&&typeof e=="object"&&"code"in e){let n=e.code;if(typeof n=="string")return Rr(n)}}function Le(e,n){let t=n();return Number.isFinite(t)&&Number.isFinite(e)&&t-e<=5e3}function Ip(e){if(typeof e.readVerifiedFile=="function")return e.readVerifiedFile;if(typeof e.readFileVerified=="function")return e.readFileVerified}function gp(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 Or(e,n,t,i){let o=Ip(e);if(!o)throw new M("READ_DENIED");return up(await o.call(e,n,t,i))}async function Di(e,n,t){let i=gp(e);if(!i)throw new M("READ_DENIED");let o=await i.call(e,n,t);if(!Array.isArray(o))throw new M("READ_DENIED");return o.map(lp).filter(r=>r!==null)}function mp(e,n,t,i){return Object.freeze({code:e,...{},source:n,relativePath:t})}function hp(e){if(!Cn(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(Ke))};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 _p(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 yt(e){return Object.freeze({appIds:Object.freeze([...new Set(e.map(n=>n.appId))].sort(Ke)),definitionIds:Object.freeze([...new Set(e.map(n=>n.definition.id))].sort(Ke))})}function ft(e,n){let t=Object.keys(e).sort(Ke),i=[...n].sort(Ke);return t.length===i.length&&t.every((o,r)=>o===i[r])}function wr(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 Ep(e){let n;try{n=yp(e);}catch{return}if(!Cn(n)||!ft(n,["version","packages"])||n.version!==1||!Array.isArray(n.packages)||n.packages.length>bi)return;let t=new Set,i=new Set,o=0,r=[];for(let s of n.packages){if(!Cn(s))return;let a=["packageDir","appId","definition","files"],c=Object.hasOwn(s,"lineage"),d=Object.hasOwn(s,"launcher"),l=[...c?["lineage"]:[],...d?["launcher"]:[]];if(!ft(s,[...a,...l])||d&&s.launcher!==false)return;let p=wr(s.packageDir),u=Lr(s.appId);if(!p||p.length!==2||p[0]!=="apps"||!pp(p[1])||!u||t.has(s.packageDir)||!Cn(s.definition)||!ft(s.definition,["id","version","hash"]))return;let f=Lr(s.definition.id),g=s.definition.version,_=s.definition.hash;if(!f||!Number.isSafeInteger(g)||g<1||typeof _!="string"||!Ni.test(_)||!Array.isArray(s.files)||s.files.length<2||s.files.length>Si)return;let P=new Set,C=[];for(let U of s.files){if(!Cn(U)||!ft(U,["path","sha256"]))return;let N=wr(U.path);if(!N||typeof U.sha256!="string"||!Ni.test(U.sha256))return;let O=N.join("/"),V=`${s.packageDir}/${O}`;if(P.has(O)||i.has(V))return;P.add(O),i.add(V),C.push(Object.freeze({path:O,sha256:U.sha256}));}if(!Z.some(U=>P.has(U))||!P.has("ui/index.html")||(o+=C.length,o>rp))return;t.add(s.packageDir),r.push(Object.freeze({packageDir:s.packageDir,...d?{launcher:false}:{},appId:u,definition:Object.freeze({id:f,version:g,hash:_}),lineage:Array.isArray(s.lineage)?s.lineage:[],files:Object.freeze(C.sort((U,N)=>Ke(U.path,N.path)))}));}return Object.freeze({version:1,packages:Object.freeze(r)})}function Je(e){let n=Ap(e);return n==="PATH_ESCAPED"||n==="IDENTITY_CHANGED"||n==="TOCTOU"?"PATH_ESCAPED":n==="LIMIT_EXCEEDED"?"LIMIT_EXCEEDED":"BUNDLE_INTEGRITY"}async function Tp(e,n,t,i,o){let r=[],s=async(a,c)=>{if(!Le(i,o))throw new M("LIMIT_EXCEEDED");if(c>2)throw new M("LIMIT_EXCEEDED");let d=await Di(e,n,a);for(let l of d){if(typeof l.name!="string"||l.name.length===0||l.name==="."||l.name===".."||/[\\/\u0000]/.test(l.name))throw new M("PATH_ESCAPED");let p=`${a}/${l.name}`;if(l.kind==="file"){if(r.push(p.slice(t.length+1)),r.length>Si)throw new M("LIMIT_EXCEEDED")}else if(l.kind==="directory")await s(p,c+1);else throw l.kind==="symlink"?new M("PATH_ESCAPED"):new M("READ_DENIED")}};return await s(t,0),r.sort(Ke)}function Pp(e){return Z.includes(e)?262144:e==="ui/index.html"?dn:e==="ui/state.json"?2097152:e.startsWith("ui/assets/")?ap:sp}async function Cr(e,n,t,i){if(e===void 0)return {packages:[],diagnostics:[],incomplete:false,reservedIds:dp};let o=hp(e.reservedIds),r=[],s=(I,A,h)=>mp(I,"bundled",A),a=(I=[],A=false,h)=>({...h===void 0?{}:{indexHash:h},packages:I,diagnostics:r,incomplete:A,reservedIds:o});if(typeof e.root!="string"||e.root.length===0||typeof e.expectedIndexHash!="string"||!Ni.test(e.expectedIndexHash))return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a();let c;try{c=await Or(n,e.root,"bundle-index.json",op);}catch(I){return r.push(s(Je(I),"bundle-index.json")),a()}let d=xi.createHash("sha256").update(c).digest("hex");if(d!==e.expectedIndexHash)return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a();let l=Ep(c);if(l===void 0)return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a();if(!_p(yt(l.packages),o))return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a([],false,d);if(!Le(t,i))return r.push(s("LIMIT_EXCEEDED","bundle-index.json")),a(l.packages.map(I=>({indexEntry:I,failureCode:"LIMIT_EXCEEDED"})),true,d);let p;try{p=await Di(n,e.root,"");}catch(I){return r.push(s(Je(I),"bundle-index.json")),a(l.packages.map(A=>({indexEntry:A,failureCode:Je(I)})),false,d)}if(!Le(t,i))return r.push(s("LIMIT_EXCEEDED","bundle-index.json")),a(l.packages.map(I=>({indexEntry:I,failureCode:"LIMIT_EXCEEDED"})),true,d);let u=p.find(I=>I.name==="bundle-index.json"&&I.kind==="file"),f=p.find(I=>I.name==="apps"&&I.kind==="directory"),g=I=>l.packages.map(A=>({indexEntry:A,failureCode:I}));if(!u)return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a(g("BUNDLE_INTEGRITY"),false,d);let _=p.filter(I=>I.name!=="bundle-index.json"&&I.name!=="apps");if(_.length>0){let I=_.some(A=>A.kind==="symlink")?"PATH_ESCAPED":"BUNDLE_INTEGRITY";return r.push(s(I,"bundle-index.json")),a(g("BUNDLE_INTEGRITY"),false,d)}if(p.some(I=>I.name==="apps"&&I.kind!=="directory"))return r.push(s("PATH_ESCAPED","apps")),a(g("PATH_ESCAPED"),false,d);let P=[];if(f)try{P=await Di(n,e.root,"apps");}catch(I){return r.push(s(Je(I),"apps")),a(g(Je(I)),false,d)}if(!Le(t,i)||P.length>bi)return r.push(s("LIMIT_EXCEEDED","apps")),a(g("LIMIT_EXCEEDED"),true,d);let C=new Map(l.packages.map(I=>[I.packageDir.slice(5),I])),U=P.filter(I=>!C.has(I.name));for(let I of U)r.push(s(I.kind==="symlink"?"PATH_ESCAPED":"BUNDLE_INTEGRITY",`apps/${I.name}`));if(U.length>0){let I=U.some(A=>A.kind==="symlink")?"PATH_ESCAPED":"BUNDLE_INTEGRITY";return a(g(I),false,d)}let N=new Set,O=new Map,V=new Map;for(let I of l.packages){let A=O.get(I.appId)??[];A.push(I),O.set(I.appId,A);let h=`${I.definition.id}\0${String(I.definition.version)}`,E=V.get(h)??[];E.push(I),V.set(h,E);}for(let I of [...O.values(),...V.values()])if(I.length>1)for(let A of I)N.add(A);let D=[],b=c.byteLength,L=false;for(let I of l.packages){if(!Le(t,i)){L=true,D.push({indexEntry:I,failureCode:"LIMIT_EXCEEDED"});continue}let A;try{let w=I.lineage[I.lineage.length-1];if(!w)throw new be("LINEAGE_INVALID","Definition lineage is missing");if(w.definition.id!==I.definition.id||w.version!==I.definition.version||w.hash!==I.definition.hash)throw new be("LINEAGE_STALE","Last lineage generation does not match bundle identity");A=pi(I.lineage,{...w.definition,hash:w.hash}).entries;}catch(w){let k=w instanceof be?w.code:"LINEAGE_INVALID";r.push(s(k,I.packageDir)),D.push({indexEntry:I,failureCode:k});continue}let h=P.find(w=>w.name===I.packageDir.slice(5));if(!f||!h){D.push({indexEntry:I,failureCode:"BUNDLE_INTEGRITY"});continue}if(h.kind!=="directory"){D.push({indexEntry:I,failureCode:h.kind==="symlink"?"PATH_ESCAPED":"BUNDLE_INTEGRITY"});continue}let E;try{let w=await Tp(n,e.root,I.packageDir,t,i);if(!Le(t,i)){L=!0,D.push({indexEntry:I,failureCode:"LIMIT_EXCEEDED"});continue}let k=I.files.map(G=>G.path);if(w.length!==k.length||w.some((G,Ue)=>G!==k[Ue])){D.push({indexEntry:I,failureCode:"BUNDLE_INTEGRITY"});continue}E=new Map;let ne;for(let G of I.files){if(!Le(t,i)){ne="LIMIT_EXCEEDED",L=!0;break}if(b>=Pi){ne="LIMIT_EXCEEDED";break}let Ue;try{Ue=await Or(n,e.root,`${I.packageDir}/${G.path}`,Pp(G.path));}catch(Pt){ne=Je(Pt);break}if(!Le(t,i)){ne="LIMIT_EXCEEDED",L=!0;break}if(b+Ue.byteLength>Pi){b=Pi,ne="LIMIT_EXCEEDED";break}if(b+=Ue.byteLength,xi.createHash("sha256").update(Ue).digest("hex")!==G.sha256){ne="BUNDLE_INTEGRITY";break}E.set(G.path,Ue);}if(ne!==void 0){D.push({indexEntry:I,failureCode:ne});continue}}catch(w){Le(t,i)||(L=true),D.push({indexEntry:I,failureCode:Je(w)});continue}D.push({indexEntry:I,lineage:A,files:E,...N.has(I)?{failureCode:"DUPLICATE_ID"}:{}});}return a(D,L,d)}var op,bi,Si,rp,sp,ap,Pi,Ni,cp,dp,Mi=j(()=>{m();li();He();qn();at();Ti();op=256*1024,bi=64,Si=128,rp=bi*Si,sp=2*1024*1024,ap=8*1024*1024,Pi=32*1024*1024,Ni=/^[0-9a-f]{64}$/,cp=new TextDecoder("utf-8",{fatal:true}),dp=Object.freeze({appIds:Object.freeze([]),definitionIds:Object.freeze([])});});function Dp(e){if(typeof e!="string"||!Ee.test(e))throw new TypeError("pluginId must be a safe UI plugin identifier");let n=`${Li}${e}`.length+7<=128?e:`hash_${xi.createHash("sha256").update(e,"utf8").digest("hex")}`;return {read:`${Li}${n}_read`,action:`${Li}${n}_action`}}function kr(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 Sp(e,n){return n.length===0||n==="."||n===".."||/[\\/\u0000]/.test(n)?e==="skills"?"skills":"apps":`${e==="skills"?"skills":"apps"}/${n}`}function Mp(e){return e.length>0&&e!=="."&&e!==".."&&!/[\\/\u0000]/.test(e)}function kn(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 Wr(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 Lp(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 Jr(e){return bp.decode(e)}function Rp(e){return JSON.parse(Jr(e))}function Op(e){if(e===void 0)return;let n=e.definitionId!==void 0&&e.definitionVersion!==void 0?`${e.definitionId}\0${String(e.definitionVersion)}`:void 0;return {pluginId:e.pluginId,...n===void 0?{}:{definitionKey:n}}}function At(e,n,t,i,o){let r={code:e,...i===void 0?{}:{pluginId:i},source:n,relativePath:t,...o?.reason===void 0?{}:{reason:Object.freeze({...o.reason})},...o?.files===void 0?{}:{files:Object.freeze([...o.files])}};return Object.freeze(r)}function xr(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 re(e){if(e instanceof M)return xr(e.code);if(e!==null&&typeof e=="object"&&"code"in e){let n=e.code;if(typeof n=="string")return xr(n)}}function Ye(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 vr(e){return {reason:e.reason,...e.code==="MANIFEST_DUAL_MISMATCH"?{files:e.files}:{}}}function Fr(e){return e==="MANIFEST_DUAL_MISMATCH"?e:Kr(e)}function wp(e){return Kr(e.code)}function Kr(e){switch(e){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 Xr("UiPluginValidationError",e)}}function Xr(e,n){throw new Error(`Unmapped ${e} code: ${String(n)}`)}function Yr(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 Xr("McpAppContractError",e)}}function Re(e,n){let t=n();return Number.isFinite(t)&&Number.isFinite(e)&&t-e<=5e3}function Cp(e){return {pluginId:e.appId,definitionKey:`${e.definition.id}\0${String(e.definition.version)}`}}function Up(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(kr(o)){let r=o.bin,s=typeof r=="string"?r:kr(r)?Object.values(r).find(a=>typeof a=="string"):void 0;for(let a of [s,o.main]){if(typeof a!="string")continue;let c=kp(a);if(c&&n.has(c))return c}}}catch{}return [`${e.slice(e.lastIndexOf("/")+1)}.js`,"index.js","main.js"].find(o=>n.has(o))}function kp(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 xp(){return globalThis.performance?.now()??Date.now()}function Xe(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let n of Object.values(e))Xe(n);return Object.freeze(e)}function jr(e){return Object.freeze(Array.from(e))}async function xn(e,n,t,i){if(n.pinnedFiles!==void 0){let a=n.pinnedFiles.get(t);if(a===void 0)throw new M("NOT_FOUND");if(a.byteLength>i)throw new M("LIMIT_EXCEEDED");return new Uint8Array(a)}let o=`${n.relativePath}/${t}`,r=n.scanContext,s=e.fingerprintVerifiedFile;if(r===void 0||!r.cacheable||typeof s!="function")return zr(e,n.root,o,i);try{let a=r.priorFingerprints.get(o)??await s.call(e,r.workspaceRoot,o,i);r.candidateRealPath=a.candidateRealPath;let c=await zr(e,n.root,o,i),d=await s.call(e,r.workspaceRoot,o,i);return r.candidateRealPath=d.candidateRealPath,Zr(a,d)&&d.size===BigInt(c.byteLength)&&!Qr(d,r.scanStartedAtNs)?r.files.set(o,{relativePath:o,byteLimit:i,fingerprint:d}):r.cacheable=!1,c}catch(a){let c=!t.includes("/")&&re(a)==="NOT_FOUND"&&r.directoryListings.some(l=>l.relativePath===n.relativePath&&!It(l.key,t)),d=t===H&&re(a)==="NOT_FOUND"&&Fp(r.directoryListings,n.relativePath);throw !c&&!d&&(r.cacheable=false),a}}async function vp(e,n,t){if(n.pinnedFiles!==void 0)return {iconDiagnostics:[]};let i=await _n(t,async r=>{try{return await xn(e,n,r,262144)}catch(s){let a=re(s);return a==="NOT_FOUND"?"missing":a==="LIMIT_EXCEEDED"?"too-large":"bad-path"}}),o=i.file;return {...o===void 0?{}:{iconFile:{path:o.path,sha256:xi.createHash("sha256").update(o.bytes).digest("hex"),contentType:o.contentType,byteLength:o.byteLength}},iconDiagnostics:i.diagnostics}}function Fp(e,n){let t=e.find(o=>o.relativePath===n);if(t===void 0)return false;if(!It(t.key,"dist"))return true;let i=e.find(o=>o.relativePath===`${n}/dist`);return i!==void 0&&!It(i.key,"tools.json")}function qr(e,n){return JSON.stringify([e.realPath,n.source,n.relativePath])}async function Vp(e,n,t,i,o,r,s,a){let c=e.fingerprintVerifiedFile,d=qr(t,i),l=o.candidates.get(d),p=i.relativePath,u;try{u=await Hr(e,n,p);}catch(L){if(re(L)!=="NOT_FOUND")throw L}let f=u===void 0?void 0:{relativePath:p,key:u};if(f!==void 0&&(i.source==="apps"||i.source==="skills")&&!Z.some(L=>It(f.key,L)))return Re(s,a)?l!==void 0&&l.candidate===void 0&&l.candidateRealPath===void 0&&l.files.length===0&&l.directoryListings.length===1&&l.directoryListings[0]?.relativePath===f.relativePath&&l.directoryListings[0]?.key===f.key&&(i.source==="apps"?l.diagnostic?.code==="MANIFEST_MISSING":l.diagnostic===void 0)&&typeof c=="function"?{memo:l}:typeof c!="function"?{}:{context:{state:o,cacheKey:d,workspaceRoot:n,scanStartedAtNs:r,directoryListings:Object.freeze([f]),priorFingerprints:new Map,files:new Map,cacheable:true}}:{timeLimitReached:true};let g=async L=>{if(L==="")return f;let I=`${i.relativePath}${L}`;try{let A=await Hr(e,n,I);return A===void 0?void 0:{relativePath:I,key:A}}catch(A){if(re(A)==="NOT_FOUND")return;throw A}},_=await Promise.all(Vr.map(g)),P=await Promise.all(jp.map(g));if(!Re(s,a))return {timeLimitReached:true};let C=typeof c=="function"&&_.every(L=>L!==void 0),U=_.filter(L=>L!==void 0),N=[...U,...P.filter(L=>L!==void 0)],O=new Map,V=l!==void 0&&C,D;if(l!==void 0&&typeof c=="function"){let L=await Promise.all(l.files.map(async I=>{if(!Re(s,a))return {kind:"time",file:I};try{let A=await c.call(e,n,I.relativePath,I.byteLimit);return {kind:"fingerprint",file:I,current:A}}catch(A){return re(A)==="NOT_FOUND"?{kind:"missing",file:I}:{kind:"error",file:I,error:A}}}));if(L.some(I=>I.kind==="time"))return {timeLimitReached:true};for(let I of L){if(I.kind==="error")throw I.error;if(I.kind==="missing"){V=false;continue}if(I.kind!=="fingerprint")continue;let{file:A,current:h}=I;O.set(A.relativePath,h),D??=h.candidateRealPath,(h.candidateRealPath!==l.candidateRealPath||!Zr(h,A.fingerprint)||Qr(h,r))&&(V=false);}}let b=l!==void 0&&l.directoryListings.length===N.length&&l.directoryListings.every((L,I)=>L.relativePath===N[I]?.relativePath&&L.key===N[I]?.key);return l!==void 0&&C&&b&&V&&D===l.candidateRealPath?{memo:l}:!C||U.length!==Vr.length?{}:{context:{state:o,cacheKey:d,workspaceRoot:n,scanStartedAtNs:r,directoryListings:Object.freeze(N),priorFingerprints:O,files:new Map,...D===void 0?{}:{candidateRealPath:D},cacheable:true}}}function It(e,n){try{let t=JSON.parse(e);return Array.isArray(t)&&t.some(i=>Array.isArray(i)&&i[0]===n)}catch{return true}}async function Hr(e,n,t){let i=es(e);if(typeof i!="function")return;let o=await i.call(e,n,t);if(!Array.isArray(o)||o.some(s=>typeof s=="string"))return;let r=o.map(Wr);if(!r.some(s=>s===null))return JSON.stringify(r.slice().sort((s,a)=>kn(s.name,a.name)||kn(s.kind,a.kind)).map(s=>[s.name,s.kind]))}function Zr(e,n){return e.dev===n.dev&&e.ino===n.ino&&e.size===n.size&&e.mtimeNs===n.mtimeNs&&e.ctimeNs===n.ctimeNs}function Qr(e,n){let t=e.mtimeNs-n;return t>=-Br&&t<=Br}function Ri(e){let n=e.scanContext,t=e.source==="skills"&&e.candidate===void 0&&e.diagnostic===void 0&&n?.files.size===0,i=e.source==="apps"&&e.candidate===void 0&&e.diagnostic?.code==="MANIFEST_MISSING"&&n?.files.size===0,o=t||i;if(n===void 0||!n.cacheable||n.candidateRealPath===void 0&&!o||n.files.size===0&&!o)return;let r=Object.freeze({...!o&&n.candidateRealPath!==void 0?{candidateRealPath:n.candidateRealPath}:{},directoryListings:n.directoryListings,files:Object.freeze([...n.files.values()]),...e.candidate===void 0?{}:{candidate:e.candidate},...e.diagnostic===void 0?{}:{diagnostic:e.diagnostic},...e.identity===void 0?{}:{identity:e.identity},...e.provenance===void 0?{}:{provenance:e.provenance}});n.state.candidates.set(n.cacheKey,r);}function Bp(e,n,t){let i=xi.createHash("sha256"),o=new TextEncoder().encode(te(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 Hp(e,n){let t={...e.definition,sourceHash:n},i;try{i=pe(t);}catch(r){throw r instanceof x&&r.code==="INPUT_INVALID"?new ae("MANIFEST_INVALID","normalized definition is invalid"):r}let o={...t,hash:i};try{ye(o);}catch{throw new ae("MANIFEST_INVALID","normalized definition is invalid")}return o}function zp(e,n){return e.actions.some(t=>t.backend.type==="core"&&t.backend.handler!=="state.set"&&!nt(n,t.backend))}function $p(e){if(typeof e.readVerifiedFile=="function")return e.readVerifiedFile;if(typeof e.readFileVerified=="function")return e.readFileVerified}function es(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 zr(e,n,t,i){let o=$p(e);if(!o)throw new M("READ_DENIED");return Lp(await o.call(e,n,t,i))}async function Gp(e,n,t){let i=es(e);if(!i)throw new M("READ_DENIED");let o=await i.call(e,n,t);if(!Array.isArray(o))throw new M("READ_DENIED");return o.map(Wr).filter(r=>r!==null)}function Wp(e){let n=[];for(let t of [e.reserved,e.builtin])t&&n.push(t);return e.builtins&&"listMcpApps"in e.builtins?n.push($r(e.builtins)):e.builtins&&n.push(e.builtins),e.builtinCatalog&&n.push($r(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 $r(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 he(e,n){e.diagnostic||(e.diagnostic=At(n,e.source,e.relativePath,e.identity?.pluginId));}function Jp(e,n){let t=new Set,i=new Map;for(let r of e){let s=r.identity?.pluginId;if(s===void 0)continue;let a=i.get(s)??[];a.push(r),i.set(s,a);}for(let r of i.values()){if(r.length<2)continue;let s=r.filter(c=>c.provenance!==void 0);if(s.length>0){let c=r.find(d=>n.has(d));if(c){for(let d of s)t.add(d);for(let d of r)d!==c&&d.provenance===void 0&&he(d,"RESERVED_ID");continue}for(let d of r)d.provenance===void 0&&he(d,"RESERVED_ID");if(s.length>1)for(let d of s)he(d,"DUPLICATE_ID");continue}let a=r.filter(c=>c.source==="apps");if(a.length>1){for(let c of a)he(c,"DUPLICATE_ID");for(let c of r.filter(d=>d.source==="skills"))he(c,"DUPLICATE_ID");}else for(let c of r.filter(d=>d.source==="skills"))he(c,"DUPLICATE_ID");}let o=new Map;for(let r of e){if(r.diagnostic?.code==="RESERVED_ID"||t.has(r)||r.provenance===void 0&&!n.has(r)&&i.get(r.identity?.pluginId??"")?.some(c=>c.provenance!==void 0))continue;let s=r.identity?.definitionKey;if(s===void 0)continue;let a=o.get(s)??[];a.push(r),o.set(s,a);}for(let r of o.values())if(r.length>1)for(let s of r)he(s,"DUPLICATE_ID");return t}function Kp(e,n,t){let i=new Set,o=new Set,r=new Set,s=new Set([...t.appIds,...n.productBundleReservationMetadata?.reservedAppIds??[]]),a=new Set([...t.definitionIds,...n.productBundleReservationMetadata?.reservedDefinitionIds??[]]);for(let l of Wp(n)){for(let p of l.appIds??[])typeof p=="string"&&i.add(p);for(let p of l.definitionIds??[])typeof p=="string"&&o.add(p);for(let p of l.toolNames??[])typeof p=="string"&&r.add(p);}for(let l of e){let p=l.candidate;if(!p)continue;if(i.has(p.pluginId)||o.has(p.definitionId)){he(l,"RESERVED_ID");continue}[p.toolNames.read,p.toolNames.action].filter(f=>f!==void 0).some(f=>r.has(f))&&he(l,"DUPLICATE_ID");}let c=[...e.filter(l=>l.provenance!==void 0&&l.diagnostic===void 0).flatMap(l=>l.candidate?[l.candidate]:[]),...(n.productBundleReservationMetadata?.candidates??[]).filter(l=>n.productBundleReservationMetadata?.indexHash!==void 0&&l.provenance?.indexHash===n.productBundleReservationMetadata.indexHash)],d=new Set;for(let l of e){let p=l.candidate;if(!(!p||l.diagnostic||l.source!=="apps"||l.provenance!==void 0)&&e.filter(u=>u.source==="apps"&&u.identity?.pluginId===p.pluginId).length===1&&c.some(u=>u.pluginId===p.pluginId)&&!(a.has(p.definitionId)&&!c.some(u=>u.pluginId===p.pluginId&&u.definitionId===p.definitionId))&&!c.some(u=>u.pluginId!==p.pluginId&&u.definitionId===p.definitionId)&&!e.some(u=>u.identity?.pluginId!==p.pluginId&&u.identity?.definitionKey===`${p.definitionId}\0${p.version}`&&u.diagnostic?.code!=="RESERVED_ID"))try{hr(p),d.add(l);}catch(u){he(l,u instanceof De?Yr(u.code):"EXEC_DENIED");}}for(let l of e){let p=l.candidate;p&&l.provenance===void 0&&!d.has(l)&&(s.has(p.pluginId)||a.has(p.definitionId))&&he(l,"RESERVED_ID");}return d}function Xp(e){return [...e].sort((n,t)=>{let i=Ur.indexOf(n.source)-Ur.indexOf(t.source);return i!==0?i:kn(n.relativePath,t.relativePath)})}function B(e,n,t){e.diagnostic=At(n,e.source,e.relativePath,e.identity?.pluginId,t);}async function Gr(e,n,t){let i=Fe(t,{mode:"local"});if(!i.ok&&i.parseFailure){B(n,Fr(i.rejection.code),vr(i.rejection));return}let o=Op(i.identity);if(n.bundleIdentity===void 0)n.identity=o;else if(o?.pluginId!==n.bundleIdentity.appId||o.definitionKey!==`${n.bundleIdentity.definitionId}\0${String(n.bundleIdentity.version)}`){B(n,"BUNDLE_INTEGRITY");return}if(!i.ok&&i.builtinOnly){B(n,"RESERVED_ID");return}if(!i.ok){B(n,Fr(i.rejection.code),vr(i.rejection));return}let r=i.manifest,s={pluginId:r.pluginId,definitionKey:`${r.definitionId}\0${String(r.version)}`};if(n.bundleIdentity===void 0&&(n.identity=s),r.actions.length>0)try{yi(r.actions.map(k=>({actionId:k.actionId,inputSchema:k.inputSchema})));}catch(k){if(k instanceof De){B(n,Yr(k.code));return}throw k}let a;try{a=await xn(e,n,"ui/index.html",dn);}catch(k){B(n,Ye(re(k),"entry"));return}if(a.byteLength>dn){B(n,"LIMIT_EXCEEDED");return}let c;try{c=Jr(a);}catch{B(n,"ENTRY_INVALID");return}if(a.byteLength===0||c.length===0){B(n,"ENTRY_INVALID");return}let d=xi.createHash("sha256").update(a).digest("hex");if(r.entryHash!==void 0&&r.entryHash!==d){B(n,"ENTRY_INVALID");return}let l={},p,u;if(r.initialState!==void 0){try{p=await xn(e,n,"ui/state.json",2097152);}catch(k){B(n,Ye(re(k),"initial"));return}if(p.byteLength>2097152){B(n,"LIMIT_EXCEEDED");return}try{let k=Rp(p),ne=r.dataPaths??[],G=qt(k,ne);l=fe(G,0,ne),en(l);}catch{B(n,"INITIAL_STATE_INVALID");return}if(u=xi.createHash("sha256").update(p).digest("hex"),r.initialState.hash!==void 0&&r.initialState.hash!==u){B(n,"INITIAL_STATE_INVALID");return}}let f={...r,entryHash:d,...r.initialState===void 0?{}:{initialState:{path:"ui/state.json",hash:u}}},g=mn(f),_=Bp(f,a,p??new Uint8Array),P;try{P=Hp(g,_);}catch(k){if(k instanceof ae){B(n,wp(k));return}throw k}let C;if(n.bundleLineage!==void 0){let k=n.bundleLineage[n.bundleLineage.length-1];if(!k){B(n,"LINEAGE_INVALID");return}let{legacy:ne,...G}=k.definition,{hash:Ue,...Pt}=P;if(te(G)!==te(Pt)){B(n,"LINEAGE_STALE");return}if(ne!==void 0&&(P={...P,legacy:ne}),ne!==void 0)try{P={...P,hash:pe(P)},ye(P);}catch{B(n,"LINEAGE_INVALID");return}C=n.bundleLineage;}if(n.bundleIdentity!==void 0&&n.bundleIdentity.appId!==r.pluginId){B(n,"BUNDLE_INTEGRITY");return}if(n.bundleIdentity!==void 0&&(n.bundleIdentity.definitionId!==P.id||n.bundleIdentity.version!==P.version||n.bundleIdentity.definitionHash!==P.hash)){B(n,"LINEAGE_STALE");return}let U=await vp(e,n,i.mcpb?.icon),N=Dp(r.pluginId),O=r.actions.length===0?{read:N.read}:N,V=Xe(g),D=Xe(f),b=Xe(P),L=Xe({...g.handlers}),I=jr(a),A=p===void 0?void 0:jr(p),h=Object.freeze({...n.provenance===void 0?{}:{provenance:n.provenance},entry:Object.freeze({path:"ui/index.html",hash:d,bytes:I}),...A===void 0?{}:{initialState:Object.freeze({path:"ui/state.json",hash:u,bytes:A})}}),E={appId:r.pluginId,pluginId:r.pluginId,definitionId:r.definitionId,version:r.version,...i.releaseVersion===void 0?{}:{releaseVersion:i.releaseVersion},manifestFile:i.file,...i.mcpb===void 0?{}:{mcpb:Xe(i.mcpb)},relativePath:n.relativePath,manifest:D,normalized:V,name:r.name,description:r.description,...r.icon===void 0?{}:{icon:r.icon},...r.tone===void 0?{}:{tone:r.tone},...U.iconFile===void 0?{}:{iconFile:Object.freeze({...U.iconFile})},...U.iconDiagnostics.length===0?{}:{iconDiagnostics:Object.freeze([...U.iconDiagnostics])},definition:b,handlers:L,resources:h,html:c,entryBytes:I,entryHash:d,initialState:Xe(l),...A===void 0?{}:{initialStateBytes:A},...u===void 0?{}:{initialStateHash:u},sourceHash:_,toolNames:Object.freeze(O)},w=n.provenance===void 0?{...E,source:n.source}:{...E,provenance:n.provenance,lineage:C??[]};n.candidate=Object.freeze(w),zp(r,P.usage)&&B(n,"EXEC_DENIED");}async function ns(e,n){let t={};for(let i of Z)try{t[i]=await xn(e,n,i,262144);}catch(o){if(re(o)==="NOT_FOUND")continue;return {files:t,failure:Ye(re(o),"manifest")}}if(t[$]!==void 0)try{t[H]=await xn(e,n,H,262144);}catch(i){if(re(i)!=="NOT_FOUND")return {files:t,failure:Ye(re(i),"manifest")}}return {files:t}}function Oi(e){return Z.some(n=>e[n]!==void 0)}async function Yp(e,n){let{files:t,failure:i}=await ns(e,n);if(i!==void 0){B(n,i);return}let o=t[$];return o!==void 0&&!oi(o)&&(delete t[$],delete t[H]),Oi(t)?t:void 0}function qp(e,n,t,i=Np,o=false,r=new Set){let s=Xp(e),a=Jp(s,r),c=Object.freeze(s.filter(u=>u.candidate!==void 0&&u.diagnostic===void 0&&!a.has(u)).map(u=>u.candidate)),d=Object.freeze(s.filter(u=>u.diagnostic!==void 0).map(u=>u.diagnostic)),l=o?Object.freeze({...t===void 0?{}:{indexHash:t},candidates:Object.freeze(s.filter(u=>u.source==="bundled"&&u.diagnostic===void 0&&t!==void 0&&u.candidate?.provenance?.indexHash===t).map(u=>u.candidate)),diagnostics:Object.freeze(d.filter(u=>u.source==="bundled").map(u=>Object.freeze({...u}))),reservedAppIds:Object.freeze([...i.appIds]),reservedDefinitionIds:Object.freeze([...i.definitionIds])}):void 0,p={apps:c,diagnostics:d,complete:n===void 0,...n===void 0?{}:{incompleteReason:n},...t===void 0?{}:{productBundleIndexHash:t},...l===void 0?{}:{productBundleSnapshotMetadata:l}};return Object.defineProperty(p,"candidates",{configurable:false,enumerable:false,get:()=>c}),Object.freeze(p)}function Zp(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 Qp(e,n){if(Zp(e))return {fs:e,options:{}};let t=e??n??{};return {fs:t.filesystem??t.fileSystem??t.fs??Sr,options:t}}async function ts(e,n,t){if(typeof e!="string"||e.length===0)throw new TypeError("workspaceRoot must be explicit");let{fs:i,options:o}=Qp(n,t),r=o.clock??xp,s=r(),a=await Cr(o.productBundle,i,s,r),c=r(),d=BigInt(Date.now())*1000000n,l=[],p=0,u,f=false,g,_;if(o.scanCache!==void 0&&typeof i.getRootIdentity=="function"&&typeof i.fingerprintVerifiedFile=="function")try{_=await i.getRootIdentity(e),g=Tr(o.scanCache,_),g.scanStartedAtNs=d;}catch(D){if(re(D)!=="NOT_FOUND")throw D}let P=g!==void 0&&o.productBundle===void 0&&a.packages.length===0&&a.diagnostics.length===0,C=new Set,U=true;l.push(...a.diagnostics.map(D=>({source:D.source,root:o.productBundle?.root??e,name:"",relativePath:D.relativePath,diagnostic:D})));let N=a.reservedIds;a.incomplete&&(u="time_limit");for(let D of a.packages){if(!Re(c,r)){f=true,u="time_limit";break}let b=D.indexEntry,L=b.packageDir,I=D.files===void 0?void 0:Up(L,D.files),A=a.indexHash===void 0?void 0:Ko(Object.freeze({kind:"bundled",launcher:b.launcher!==false,indexHash:a.indexHash,packageDir:L,appId:b.appId,definitionId:b.definition.id,version:b.definition.version,definitionHash:b.definition.hash,files:b.files}),I),h={source:"bundled",root:o.productBundle?.root??e,name:L.slice(5),relativePath:L,...A===void 0?{}:{provenance:A},...D.files===void 0?{}:{pinnedFiles:D.files},...D.lineage===void 0?{}:{bundleLineage:D.lineage},bundleIdentity:{appId:b.appId,definitionId:b.definition.id,version:b.definition.version,definitionHash:b.definition.hash},identity:Cp(b)};if(l.push(h),p+=1,D.failureCode!==void 0){B(h,D.failureCode);continue}if(D.files?.has(H)===true){B(h,"EXEC_DENIED",{reason:{path:"",rule:"bundled-tool-mode-unsupported",file:H}});continue}let E={};for(let w of Z){let k=D.files?.get(w);k!==void 0&&(E[w]=k);}if(!Oi(E)){B(h,"BUNDLE_INTEGRITY");continue}if(await Gr(i,h,E),!Re(c,r)){f=true,u="time_limit";break}}let O=[{source:"apps",directory:"apps"},{source:"skills",directory:"skills"}];e:for(let D of O){let{source:b,directory:L}=D,I;try{I=await Gp(i,e,L);}catch(h){if(re(h)==="NOT_FOUND")continue;P=false,U=false,l.push({source:b,root:e,name:"",relativePath:b,diagnostic:At(Ye(re(h),"manifest"),b,b)});continue}let A=I.filter(h=>h.kind==="directory"||h.kind==="symlink").filter(h=>Mp(h.name)).map(h=>({source:b,root:e,name:h.name,relativePath:Sp(b,h.name)})).sort((h,E)=>kn(h.relativePath,E.relativePath));for(let h of A){let E={...h};if(l.push(E),_!==void 0?C.add(qr(_,E)):P=false,!Re(c,r)){f=true,u="time_limit";break e}let w;if(g!==void 0&&_!==void 0){try{let G=await Vp(i,e,_,E,g,d,c,r);if(G.timeLimitReached){f=!0,u="time_limit";break e}E.scanContext=G.context,w=G.memo;}catch(G){P=false,B(E,Ye(re(G),"manifest"));continue}w===void 0&&(P=false);}if(w!==void 0){if(E.candidate=w.candidate,E.diagnostic=w.diagnostic,E.identity=w.identity,b==="skills"&&w.candidate===void 0&&w.diagnostic===void 0)continue;if(p>=64){B(E,"LIMIT_EXCEEDED");continue}if(h.relativePath.split("/").length-1>2){B(E,"LIMIT_EXCEEDED");continue}if(p+=1,!Re(c,r)){f=true,u="time_limit";break e}continue}let k;if(b==="skills"&&(k=await Yp(i,E),k===void 0)){E.diagnostic===void 0&&Ri(E);continue}if(p>=64){B(E,"LIMIT_EXCEEDED");continue}if(h.relativePath.split("/").length-1>2){B(E,"LIMIT_EXCEEDED");continue}if(!Re(c,r)){f=true,u="time_limit";break e}if(p+=1,k===void 0){let G=await ns(i,E);if(G.failure!==void 0||!Oi(G.files)){B(E,G.failure??Ye("NOT_FOUND","manifest")),Ri(E);continue}k=G.files;}if(await Gr(i,E,k),Ri(E),!Re(c,r)){f=true,u="time_limit";break e}}}if(g!==void 0&&_!==void 0){let D=[...C].sort(kn),b=g.lastCandidateKeys,L=b!==void 0&&b.length===D.length&&b.every((A,h)=>A===D[h]);if(P=P&&L,U&&!f&&u===void 0)for(let A of g.candidates.keys())try{JSON.parse(A)[0]===_.realPath&&!C.has(A)&&g.candidates.delete(A);}catch{g.candidates.delete(A);}let I=[...g.candidates.keys()].filter(A=>{try{return JSON.parse(A)[0]===_.realPath}catch{return false}});P=P&&I.length===C.size&&I.every(A=>C.has(A))&&!f&&u===void 0,g.lastCandidateScanUnchanged=P,U&&!f&&u===void 0&&(g.lastCandidateKeys=Object.freeze(D));}f&&l.push({source:"apps",root:e,name:"",relativePath:"apps",diagnostic:At("DISCOVERY_TIME_LIMIT","apps","apps")});let V=Kp(l,o,N);return qp(l,u,a.indexHash,N,o.productBundle!==void 0,V)}var Np,Li,Ur,bp,Vr,jp,Br,is=j(()=>{m();ze();Fn();Se();ai();si();He();at();_r();tt();Qn();Pr();Ti();et();Mi();Mi();Np=yt([]),Li="crewx_local_app_";Ur=["bundled","apps","skills"],bp=new TextDecoder("utf-8",{fatal:true});Vr=["","/ui"],jp=["/dist"],Br=2000000000n;});m();ai();m();Bt();m();var ko="SKILL.md",pd=/^---\s*\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;function xo(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function ld(e){return e.isDirectory()||e.isSymbolicLink()}function Bo(e){try{return ee.existsSync(e)&&ee.statSync(e).isDirectory()}catch{return false}}function ci(e){let n;try{n=ee.readFileSync(e,"utf8");}catch{return {frontmatter:{},readable:false,valid:false,hasFrontmatter:false}}let t=n.match(pd);if(!t)return {frontmatter:{},readable:true,valid:true,hasFrontmatter:false};try{let i=gs.load(t[1]??"");if(!xo(i))return {frontmatter:{},readable:!0,valid:!1,hasFrontmatter:!0};let o=xo(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 ud(e){return [ce.join(e,ko),ce.join(e,"skill",ko)]}function vo(e,n){if(!Bo(e))return null;for(let t of ud(e)){if(!ee.existsSync(t))continue;let o=ci(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 Fo(e){try{return ee.readdirSync(e,{withFileTypes:!0}).filter(ld)}catch{return []}}function jo(e,n,t){!e||n.has(e.name)||(n.add(e.name),t.push(e));}function Ho(e){let n=[],t=new Set;for(let i of e)if(Bo(i))for(let o of Fo(i)){if(o.name.startsWith("@")){let r=ce.join(i,o.name);for(let s of Fo(r))jo(vo(ce.join(r,s.name),s.name),t,n);continue}jo(vo(ce.join(i,o.name),o.name),t,n);}return n.sort((i,o)=>i.name.localeCompare(o.name))}m();qn();var fd=/^[A-Za-z0-9_$.[\]"-]{0,200}$/,yd=/^[a-z][a-z0-9-]{0,63}$/,Ad="<unknown>";function Id(e){return typeof e=="string"&&(Z.includes(e)||e===H)}function zo(e){if(typeof e!="object"||e===null)return;let{file:n,path:t,rule:i}=e;if(!(typeof i!="string"||!yd.test(i)))return {...Id(n)?{file:n}:{},path:typeof t=="string"&&fd.test(t)?t:Ad,rule:i}}function $o(e){if(!Array.isArray(e))return;let n=Z.filter(t=>e.includes(t));return n.length>0?n:void 0}is();var nl=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/;function ht(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?tl(e.relativePath,e.fileBytes):void 0);if(n!==void 0&&i!==void 0){let o=JSON.stringify({screenHash:n,skillHash:i});return xi.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 tl(e,n){let t=new TextEncoder().encode(_t(e)),i=il(n),o=new Uint8Array(t.byteLength+1+i.byteLength);return o.set(t,0),o[t.byteLength]=0,o.set(i,t.byteLength+1),xi.createHash("sha256").update(o).digest("hex")}function il(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 _t(e){if(typeof e!="string"||e.length===0||ce.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 gt(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 ss(e,n){let t=ce.relative(e,n).split(ce.sep).join("/");return !t||t===".."||t.startsWith("../")||ce.isAbsolute(t)?null:_t(t)}function ol(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 as(e){return Object.freeze({packageRoot:e})}function rl(e){return Object.freeze({id:e.definition.id,version:e.definition.version,hash:e.definition.hash,usage:e.definition.usage??ke,...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 cs(e){return {capabilities:Object.freeze([...e]),origin:"local",ownership:"unknown",shareability:"unknown",sharingAvailability:"unavailable"}}function sl(e,n){let t=e.candidate,i=t.provenance!==void 0,o=n&&!i?["screen","skill"]:["screen"],r=rl(t),s=ht(n?{screenHash:r.hash,skillHash:n.skillHash}:{screenHash:r.hash}),a=t.description||n?.skill.description||"",c=t.releaseVersion??String(t.version),d={appId:t.pluginId,name:t.name,description:a,version:c,...cs(o),definition:r,...n===void 0||i?{}:{skillName:n.skill.name},...i?{provenance:t.provenance}:{localDefinitionRef:as(e.packageRoot)},definitionHash:s,...t.manifest.csp===void 0?{}:{connectDomains:Object.freeze([...t.manifest.csp.connectDomains])}};return {...i?{}:{packageRoot:e.packageRoot},source:i?"bundled":t.source,appId:d.appId,capabilities:o,summary:Object.freeze(d)}}function al(e){let n=cl(e.skill.name),t={appId:n,name:e.skill.name,description:e.skill.description??"",...e.skill.version===void 0?{}:{version:e.skill.version},...cs(["skill"]),skillName:e.skill.name,localDefinitionRef:as(e.packageRoot),definitionHash:ht({skillHash:e.skillHash})};return {packageRoot:e.packageRoot,source:e.source,appId:n,capabilities:["skill"],summary:Object.freeze(t)}}function cl(e){return `skill.${e.replace(/^@/,"").replace(/\//g,".").replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,122)||"unnamed"}`}function q(e,n,t,i,o){let r=zo(o?.reason),s=$o(o?.files);return Object.freeze({code:e,source:n,relativePath:dl(t),...i===void 0?{}:{appId:i},...r===void 0?{}:{reason:r},...s===void 0?{}:{files:s}})}function dl(e){if(typeof e!="string"||e.length===0||ce.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 ds(e){return q(e.code,e.source,e.relativePath,e.pluginId,e)}function pl(e,n){let t=ss(e,n.dir);if(!t)return {diagnostic:q("PATH_ESCAPED","node_modules","node_modules")};let i=ol(t);if(!i)return {diagnostic:q("PATH_ESCAPED","node_modules",t)};let o=ci(n.skillMdPath);if(!o.readable)return {diagnostic:q("SKILL_READ_FAILED",i,t)};if(!o.valid)return {diagnostic:q("SKILL_INVALID",i,t)};let r=ll(n.dir,n.skillMdPath);if(!r)return {diagnostic:q("PATH_ESCAPED",i,t)};try{let s=new Uint8Array(ee.readFileSync(n.skillMdPath));return {skill:n,packageRoot:t,relativeSkillPath:r,skillHash:ht({relativePath:r,fileBytes:s}),source:i}}catch{return {diagnostic:q("SKILL_READ_FAILED",i,t)}}}function ll(e,n){let t=ce.relative(e,n).split(ce.sep).join("/");try{return _t(t)}catch{return null}}function ul(e){if(!nl.test(e.appId))return {diagnostic:q("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??ke,...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??xi.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 fl(e){return e.builtinCatalog}function yl(e){let n=e.packageRoot??e.relativePath??e.packageRootPath;if(n===void 0)return null;try{return _t(n)}catch{return null}}function Al(e){let n=e.marketplaceContentId;return typeof n=="string"&&n.length>0?n:void 0}function Il(e,n,t){let i=n.installed??[],o=new Map;for(let s of i){let a=yl(s);if(!a){t.push(q("INSTALLED_IDENTITY_MISMATCH","installed","installed"));continue}let c=o.get(a);if(c&&JSON.stringify(c)!==JSON.stringify(s)){t.push(q("INSTALLED_IDENTITY_MISMATCH","installed",a));continue}o.set(a,s);}let r=new Map;for(let s of e)s.packageRoot!==void 0&&r.set(s.packageRoot,s);for(let[s,a]of o){let c=r.get(s);if(!c){t.push(q("INSTALLED_MISSING","installed",s,a.appId));continue}let d=Al(a);if(!d){t.push(q("INSTALLED_CONTENT_ID_MISSING","installed",s,a.appId));continue}if(a.appId!==void 0&&a.appId!==c.appId||a.definitionHash!==void 0&&a.definitionHash!==c.summary.definitionHash){t.push(q("INSTALLED_IDENTITY_MISMATCH","installed",s,a.appId));continue}let l={...c.summary,origin:"installed",...a.slug===void 0?{}:{slug:a.slug},marketplaceContentId:d},p=e.indexOf(c);p>=0&&(e[p]={...c,summary:Object.freeze(l)});}}function gl(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==="bundled"){let s=o.filter(a=>a.source==="apps"&&a.summary.definition!==void 0);if(s.length===1){for(let a of o)a.source==="bundled"?i.add(a):a!==s[0]&&(i.add(a),n.push(q("RESERVED_ID",a.source,mt(a),a.appId)));continue}}if(r!==void 0){let s=o.filter(a=>a.source===r);for(let a of o.filter(c=>c.source!==r))i.add(a),n.push(q("RESERVED_ID",a.source,mt(a),a.appId));if(s.length>1)for(let a of s)i.add(a),n.push(q("DUPLICATE_ID",a.source,mt(a),a.appId));continue}for(let s of o)i.add(s),n.push(q("DUPLICATE_ID",s.source,mt(s),s.appId));}return e.filter(o=>!i.has(o))}function mt(e){return e.packageRoot??e.summary.provenance?.packageDir??`builtin/${e.appId}`}function ml(e,n){return e.filter(t=>!(t.code==="MANIFEST_MISSING"&&n.has(t.relativePath))).map(ds)}function hl(e){return e.filesystem}function _l(e,n){let t=hl(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?{}:{productBundleReservationMetadata:i}}}async function ps(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=fl(n),i=await ts(e,_l(n,t)),o=n.registeredProductBundle??i.productBundleSnapshotMetadata,r=[ce.join(e,"skills"),ce.join(e,"node_modules"),ce.join(e,"apps")],s=[],a=[],c=[],d=new Set;for(let A of r)for(let h of Ho([A])){let E=ss(e,h.dir);(E===null||!d.has(E))&&(c.push(h),E!==null&&d.add(E));}for(let A of c){let h=pl(e,A);"diagnostic"in h?s.push(h.diagnostic):a.push(h);}let l=new Map,p=n.registeredProductBundle?.indexHash,u=(n.registeredProductBundle?.candidates??[]).filter(A=>p!==void 0&&A.provenance?.indexHash===p),f=[...new Set([...i.apps??i.candidates??[],...i.productBundleSnapshotMetadata?.candidates??[]]),...u],g=new Set(u),_=new Set(p===void 0?[]:(t?.listMcpApps()??[]).filter(A=>A.provenance?.indexHash===p).map(A=>A.appId));for(let A of f){if(g.has(A)&&A.provenance?.indexHash===p&&_.has(A.appId))continue;let h=A.provenance===void 0?`workspace\0${A.relativePath}`:`bundled\0${A.provenance.indexHash}\0${A.provenance.packageDir}`;l.set(h,{candidate:A,packageRoot:A.relativePath});}let P=new Map(a.map(A=>[A.packageRoot,A])),C=[];for(let A of l.values()){let h=A.candidate.provenance===void 0?P.get(A.packageRoot):void 0,E=sl(A,h);C.push({...E.packageRoot===void 0?{}:{packageRoot:E.packageRoot},source:E.source,appId:E.appId,summary:E.summary});}let U=new Set([...l.values()].filter(A=>A.candidate.provenance===void 0).map(A=>A.packageRoot)),N=o===void 0?new Set:new Set(i.diagnostics.filter(A=>A.code==="RESERVED_ID"&&A.source!=="bundled").map(A=>A.relativePath)),O=new Set(o?.reservedAppIds??[]);for(let A of a){let h=al(A);if(!(U.has(A.packageRoot)||N.has(A.packageRoot))){if(O.has(h.appId)){s.push(q("RESERVED_ID",A.source,A.packageRoot,h.appId));continue}C.push({packageRoot:h.packageRoot,source:h.source,appId:h.appId,summary:h.summary});}}let V=[...ml(i.diagnostics,new Set(a.map(A=>A.packageRoot))),...s,...n.registeredProductBundle?.diagnostics.filter(A=>A.source==="bundled").map(ds)??[]],D=[];if(t)for(let A of t.listMcpApps()){let h=ul(A);"diagnostic"in h?V.push(h.diagnostic):D.push(h);}let b=gl([...C,...D],V);Il(b,n,V);let L=b.map(A=>A.summary).sort((A,h)=>gt(A.appId,h.appId)),I=[...V].sort((A,h)=>gt(A.relativePath,h.relativePath)||gt(A.code,h.code)||gt(A.appId??"",h.appId??""));return Object.freeze({items:Object.freeze(L),diagnostics:Object.freeze(I)})}m();m();m();function El(e){let n=o=>o.replace(/[.+^${}()|[\]\\]/g,"\\$&"),i=e.split("/").map(o=>o==="**"?".*":o.split("*").map(n).join("[^/]*"));return new RegExp(`^${i.join("\\/")}$`)}function un(e,n){try{return El(n).test(e)}catch{return false}}function Et(e,...n){let t=e.split("/");if(t.length<n.length)return false;let i=t.length-n.length;return n.every((o,r)=>un(t[i+r],o))}function Tl(e,n){return e.split("/").some(t=>un(t,n))}var ls=[{label:".env*",test:e=>un(e,".env*")},{label:".git/",test:(e,n,t)=>t&&e===".git"},{label:"memory/",test:(e,n,t)=>t&&e==="memory"},{label:"*.key",test:e=>un(e,"*.key")},{label:"*.pem",test:e=>un(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&&Et(n,".crewx","threads")},{label:".crewx/crewx.db",test:(e,n,t)=>!t&&Et(n,".crewx","crewx.db")},{label:".crewx/*.log",test:(e,n,t)=>!t&&Et(n,".crewx","*.log")},{label:".crewx/publish/",test:(e,n,t)=>t&&Et(n,".crewx","publish")},{label:".crewx/",test:(e,n)=>Tl(n,".crewx")}];function fn(e,n,t){for(let i of ls)if(i.test(e,n,t))return i.label;return null}m();var Oe=class extends Error{constructor(t,i){super(`publish: [${t}]${i?` ${i}`:""}`);this.code=t;}code;name="PublishError"};function T(e,n){return new Oe(e,n)}function us(e,n){if(!n||/[\\\u0000]/.test(n)||ce__namespace.posix.isAbsolute(n)||n.split("/").some(f=>!f||f==="."||f===".."))throw T("PACKAGE_PATH_TRAVERSAL","package root must be a safe workspace-relative path");let t=ce__namespace.resolve(e),i=ce__namespace.resolve(t,...n.split("/"));if(!i.startsWith(`${t}${ce__namespace.sep}`))throw T("PACKAGE_PATH_TRAVERSAL","package root escaped the workspace");function o(f,g){let _;try{_=ee__namespace.lstatSync(f);}catch{throw T("PACKAGE_FILE_INVALID",`package directory is missing: ${g}`)}if(_.isSymbolicLink())throw T("PACKAGE_SYMLINK",`symlink is not publishable: ${g}`);if(!_.isDirectory())throw T("PACKAGE_FILE_INVALID",`not a package directory: ${g}`)}o(t,".");let r=t,s="",a=null;for(let f of n.split("/"))r=ce__namespace.join(r,f),s=s?`${s}/${f}`:f,o(r,s),a??=fn(f,s,true);let c=[],d=[];function l(f,g){o(f,g);let _=ee__namespace.readdirSync(f,{withFileTypes:true});for(let P of _){let C=`${g}/${P.name}`,U=ce__namespace.join(f,P.name);if(P.isSymbolicLink())throw T("PACKAGE_SYMLINK",`symlink is not publishable: ${C}`);let N=fn(P.name,C,P.isDirectory());N?d.push({path:C,rule:N}):P.isDirectory()?l(U,C):P.isFile()&&c.push(C);}}a?d.push({path:n,rule:a}):l(i,n);let p=new TextEncoder,u=(f,g)=>Buffer.compare(p.encode(f),p.encode(g));return c.sort(u),d.sort((f,g)=>u(f.path,g.path)),{included:c,excluded:d}}function fs(e){let n=[],t=[];function i(o,r,s){let a;try{a=ee__namespace.readdirSync(o,{withFileTypes:!0});}catch{return}a.sort((c,d)=>c.name.localeCompare(d.name));for(let c of a){let d=r?`${r}/${c.name}`:c.name,l=ce__namespace.join(o,c.name);if(c.isSymbolicLink()){let p;try{p=ee__namespace.statSync(l);}catch{t.push({path:d,rule:"symlink"});continue}if(p.isDirectory()){t.push({path:d,rule:s??"symlink-dir"});continue}let u=s??fn(c.name,d,false);u?t.push({path:d,rule:u}):t.push({path:d,rule:"symlink"});continue}if(c.isDirectory()){let p=s??fn(c.name,d,true);i(l,d,p);continue}if(c.isFile()){let p=s??fn(c.name,d,false);p?t.push({path:d,rule:p}):n.push(d);}}}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}}m();var Pl=[{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 Nl(e){return e.includes(0)}function ki(e,n,t){let i=[];for(let o of n){let r=ce__namespace.join(e,o),s;try{let c=t?.get(o);s=c===void 0?ee__namespace.readFileSync(r):Buffer.from(c);}catch{continue}if(Nl(s))continue;s.toString("utf8").split(/\r\n|\r|\n/).forEach((c,d)=>{for(let{rule:l,regex:p}of Pl)p.test(c)&&i.push({path:o,line:d+1,rule:l});});}return i}m();var Is=/^[a-z0-9-]+$/,Dl=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/,bl=/^[A-Za-z_][A-Za-z0-9_]*$/;function Sl(e){let n=ce__namespace.join(e,"crewx.yaml");if(!ee__namespace.existsSync(n))return {};let t;try{t=gs__namespace.load(ee__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 Ml(e){return xi__namespace.createHash("sha256").update(e).digest("hex")}function ms(e){let n;try{n=ee__namespace.lstatSync(e);}catch{throw T("PACKAGE_FILE_INVALID",`file is not readable: ${ce__namespace.basename(e)}`)}if(n.isSymbolicLink())throw T("PACKAGE_SYMLINK","symlink content is not publishable");if(!n.isFile())throw T("PACKAGE_FILE_INVALID","only regular files are publishable");return xi__namespace.createHash("sha256").update(new Uint8Array(ee__namespace.readFileSync(e))).digest("hex")}function Ll(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 hs(e){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||ce__namespace.posix.isAbsolute(e)||e.split("/").some(n=>n===".."||n.length===0))throw T("PACKAGE_PATH_TRAVERSAL","manifest file path must be a non-empty POSIX relative path")}function Rl(e){if(!/^(?:apps|skills)\/[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(e))throw T("APP_PACKAGE_ROOT_INVALID","packageRoot must be apps/<safe-id> or skills/<safe-id>")}function _s(e){if(!Dl.test(e))throw new Error(`publish: invalid version "${e}" \u2014 must be semver (e.g. 1.0.0)`)}function Es(e,n,t={}){let i=Sl(e),o=i.name??ce__namespace.basename(e);if(!Is.test(o))throw new Error(`publish: invalid name "${o}" \u2014 must match ${Is} (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");_s(r);let s=Array.isArray(i.requiredEnv)?i.requiredEnv:[],a=[];for(let l of s){if(typeof l!="string"||!bl.test(l))throw new Error(`publish: requiredEnv must contain names only (no values), got "${String(l)}"`);a.push(l);}let c=n.map(l=>(hs(l),{path:l,sha256:ms(ce__namespace.join(e,l))})).sort((l,p)=>l.path<p.path?-1:l.path>p.path?1:0),d={name:o,version:r,type:"template",description:i.description??"",files:c,requiredEnv:a};return i.crewxMinVersion&&(d.crewxMinVersion=i.crewxMinVersion),d}function Ol(e){let n=e.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"");if(!n)throw T("APP_PACKAGE_ROOT_INVALID","appId cannot produce a marketplace name");return n}function Ts(e,n){if(Rl(n.packageRoot),!n.version)throw new Error("publish: version is required for App publishing \u2014 pass opts.version");if(_s(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 T("APP_UI_MANIFEST_INVALID","screen App manifests require definitionId");let s=n.includedFiles.includes(`${i}manifest.json`),a=n.includedFiles.includes(`${i}ui-plugin.json`);if(!s&&!a)throw T("APP_UI_MANIFEST_INVALID","screen App is missing manifest.json or ui-plugin.json");if(s&&!a)throw T("APP_UI_MANIFEST_INVALID","a manifest.json App must also ship a generated ui-plugin.json");if(!n.includedFiles.includes(`${i}ui/index.html`))throw T("APP_UI_MANIFEST_INVALID","screen App is missing ui/index.html")}if(t.includes("skill")&&!n.includedFiles.includes(`${i}SKILL.md`))throw T("APP_SKILL_MISSING","skill capability requires package-root SKILL.md");let o=new Set,r=n.includedFiles.map(s=>{if(hs(s),!s.startsWith(i))throw T("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?ms(ce__namespace.join(e,s)):Ml(a),...a===void 0?{}:{generated:true}}}).sort((s,a)=>Ll(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:Ol(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:[]}}m();function Ps(e){return xi__namespace.createHash("sha256").update(e).digest("hex")}function Ms(e,n){if(typeof n!="string"||n.length===0||n.includes("\\")||n.includes("\0")||ce__namespace.posix.isAbsolute(n)||n.split("/").some(o=>o===".."||o.length===0))throw T("PACKAGE_PATH_TRAVERSAL","archive paths must be non-empty POSIX relative paths");let t=ce__namespace.resolve(e),i=ce__namespace.resolve(t,...n.split("/"));if(i!==t&&!i.startsWith(`${t}${ce__namespace.sep}`))throw T("PACKAGE_PATH_TRAVERSAL","archive path escaped its root");return i}function Ns(e,n){let t=Ms(e,n),i;try{i=ee__namespace.lstatSync(t);}catch{throw T("PACKAGE_FILE_INVALID","manifest file is missing")}if(i.isSymbolicLink())throw T("PACKAGE_SYMLINK","symlink content is not publishable");if(!i.isFile())throw T("PACKAGE_FILE_INVALID","only regular files are publishable");return new Uint8Array(ee__namespace.readFileSync(t))}async function Ls(e,n,t={}){let i=ce__namespace.join(e,".crewx","publish");ee__namespace.mkdirSync(i,{recursive:true});let o=ce__namespace.join(i,`${n.name}-${n.version}.tgz`),r=ce__namespace.join(i,`.${n.name}-${n.version}.${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}.tmp.tgz`),s=ee__namespace.mkdtempSync(ce__namespace.join(Ds__namespace.tmpdir(),"crewx-publish-"));try{let a=new Set,c=[];for(let d of n.files){if(a.has(d.path))throw T("PACKAGE_PATH_TRAVERSAL","manifest contains duplicate file paths");a.add(d.path);let l=t.generatedFiles?.get(d.path);if(d.generated===!0&&l===void 0)throw T("PACKAGE_GENERATED_FILE_MISSING","generated manifest file bytes are missing");if(t.sourceFileHashes?.has(d.path)){let f=Ns(e,d.path);if(t.sourceFileHashes.get(d.path)!==Ps(f))throw T("PACKAGE_STAGED_BYTES_MISMATCH","workspace source changed before staging")}let p=l??Ns(e,d.path);if(Ps(p)!==d.sha256)throw T("PACKAGE_STAGED_BYTES_MISMATCH",`staged bytes differ for ${d.path}`);let u=Ms(s,d.path);ee__namespace.mkdirSync(ce__namespace.dirname(u),{recursive:!0}),ee__namespace.writeFileSync(u,new Uint8Array(p)),c.push(d.path);}ee__namespace.writeFileSync(ce__namespace.join(s,"manifest.json"),JSON.stringify(n,null,2)),await Ss__namespace.create({gzip:!0,file:r,cwd:s,portable:!0,noMtime:!0},["manifest.json",...c]),ee__namespace.renameSync(r,o);}finally{try{ee__namespace.rmSync(r,{force:!0});}catch{}ee__namespace.rmSync(s,{recursive:true,force:true});}return o}m();m();var yn="/api/v1";var Ul=201,kl=200,xl=409,vi=401,Rs={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 vl(){return process.env.WI013_FAKE_UPLOAD==="1"}function Fl(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 jl(e){return e.replace(/\/+$/,"")}async function vn(e){try{return await e.json()}catch{return null}}function Os(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 Vl(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 Bl(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 ws(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(Rs,r))continue;let s=r,a=s==="APP_NAME_CONFLICT"?`marketplace name is already in use: ${n}`:void 0;return T(Rs[s],a)}}async function Hl(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=jl(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}${yn}/publisher/items`,{method:"POST",headers:{Authorization:`Bearer ${e.accessToken}`,"Content-Type":"application/json"},body:JSON.stringify({slug:i,displayName:i,description:e.manifest.description,type:e.manifest.type,version:e.manifest.version,accessPolicy:t,...s===void 0?{}:{appId:s}})});}catch{throw new Error("publish: [E_NETWORK] Submit request failed (network)")}let c=await vn(a),d=Vl(c),l=Bl(c),p=r&&l!==void 0?l:i,u;if(a.status===Ul)u="created";else if(r&&a.status===kl){if(d===void 0)throw T("PUBLISH_CONTENT_ID_MISSING","App republish did not return an opaque contentId");u="existing";}else if(a.status===xl){if(r)throw ws(c,i)??T("APP_NAME_CONFLICT",`marketplace name is already in use: ${i}`);u="existing";}else throw a.status===vi?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 f="not-needed",g=null;if(u==="existing"&&!r){let b;try{b=await fetch(`${n}${yn}/publisher/items`,{method:"GET",headers:{Authorization:`Bearer ${e.accessToken}`}});}catch{throw new Error("publish: [E_NETWORK] Publisher items request failed (network)")}let L=await vn(b);if(b.status!==200)throw new Error(`publish: [E_HTTP] Publisher items request failed \u2014 HTTP ${b.status}`);let A=Os(L,"publisher items",b.status)?.items;if(!Array.isArray(A))throw new Error(`publish: [E_MALFORMED] Publisher items response is malformed (expected data.items[]) \u2014 HTTP ${b.status}`);let h=A.find(E=>!E||typeof E!="object"?false:E.slug===i);if(!h||typeof h.version!="string")throw new Error(`publish: [E_MALFORMED] Publisher items response does not contain slug "${i}" \u2014 HTTP ${b.status}`);if(g=h.version,g!==e.manifest.version){let E;try{E=await fetch(`${n}${yn}/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 vn(E),E.status===vi?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}`);f="applied";}}let _=ee__namespace.readFileSync(e.tgzPath),P=vl()?Fl(_):_,C=new FormData;C.set("archive",new Blob([new Uint8Array(P)],{type:"application/gzip"}),`${p}-${e.manifest.version}.tgz`);let U=r&&d!==void 0?d:i,N;try{N=await fetch(`${n}${yn}/publisher/items/${encodeURIComponent(U)}/upload`,{method:"POST",headers:{Authorization:`Bearer ${e.accessToken}`},body:C});}catch{throw new Error("publish: [E_NETWORK] Upload request failed (network)")}if(N.status===vi)throw new Error("publish: [E_AUTH_EXPIRED] Authentication is expired or missing \u2014 please log in again (HTTP 401)");if(!N.ok){let b=await vn(N);if(r){let L=ws(b,p);if(L)throw L}throw new Error(`publish: [E_HTTP] Upload request failed \u2014 HTTP ${N.status}`)}let O=await vn(N),V=Os(O,"upload",N.status),D=typeof V.contentId=="string"&&V.contentId.length>0?V.contentId:d;if(r&&D===void 0)throw T("PUBLISH_CONTENT_ID_MISSING","App upload did not return an opaque contentId");return {slug:p,version:e.manifest.version,...D===void 0?{}:{contentId:D},artifactChecksum:V.artifactChecksum,artifactSizeBytes:V.artifactSizeBytes,submitOutcome:u,versionUpdate:f,serverVersionBefore:g}}var zl=1e4,$l=100*1024*1024;function Fi(e){return xi__namespace.createHash("sha256").update(e).digest("hex")}function Gl(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function Be(e,n){if(!n||n.includes("\\")||n.includes("\0")||ce__namespace.posix.isAbsolute(n)||n.split("/").some(r=>r===".."||r.length===0))throw T("PACKAGE_PATH_TRAVERSAL","workspace file path is not a safe relative path");let t=ce__namespace.resolve(e,...n.split("/")),i=ce__namespace.resolve(e);if(t!==i&&!t.startsWith(`${i}${ce__namespace.sep}`))throw T("PACKAGE_PATH_TRAVERSAL","workspace file path escaped the workspace root");let o;try{o=ee__namespace.lstatSync(t);}catch{throw T("PACKAGE_FILE_INVALID",`workspace file is missing: ${n}`)}if(o.isSymbolicLink())throw T("PACKAGE_SYMLINK",`symlink is not publishable: ${n}`);if(!o.isFile())throw T("PACKAGE_FILE_INVALID",`not a regular file: ${n}`);return new Uint8Array(ee__namespace.readFileSync(t))}async function Wl(e,n,t){let i=`${n}/${$}`;if(!t.includes(i))return [];let o={[$]:Be(e,i)},r=`${n}/${H}`;t.includes(r)&&(o[H]=Be(e,r));let s=Fe(o,{mode:"local"});if(!s.ok)return [];let{diagnostics:a}=await _n(s.mcpb?.icon,async d=>{let l=`${n}/${d}`;return t.includes(l)?Be(e,l):"missing"}),c=a.find(d=>d.code==="ICON_INVALID");if(c!==void 0)throw T("ICON_INVALID",`${c.reason??"invalid"} at ${c.declared??"icon"}`);return a.flatMap(d=>d.code==="ICON_INVALID"?[]:[{code:d.code,path:d.declared??"icon"}])}function Us(e,n,t){let i=e??n;if(!Number.isSafeInteger(i)||i<=0)throw new Oe("PACKAGE_SIZE_LIMIT",`${t} must be a positive integer`);return i}function xs(e,n,t,i){let o=Us(t.maxFileCount??t.maxFiles,zl,"max file count"),r=Us(t.maxTotalBytes??t.maxBytes,$l,"max total bytes");if(n.length>o)throw new Oe("PACKAGE_SIZE_LIMIT",`package exceeds file count limit (${o})`);let s=0;for(let a of n){let c=i?.get(a);if(c!==void 0?s+=c.byteLength:s+=Be(e,a).byteLength,s>r)throw new Oe("PACKAGE_SIZE_LIMIT",`package exceeds byte limit (${r})`)}}function Jl(e){return e.appId!==void 0||e.expectedDefinitionHash!==void 0}function Kl(e){let n=e.appId!==void 0,t=e.expectedDefinitionHash!==void 0;if(!n&&t)throw T("APP_ID_REQUIRED","appId is required with expectedDefinitionHash");if(n&&!t)throw T("APP_DEFINITION_HASH_REQUIRED","expectedDefinitionHash is required with appId");if(!n||!t)throw T("APP_ID_REQUIRED")}function Xl(e,n){let t=e.filter(i=>i.appId===n);if(t.length===0)throw T("APP_NOT_FOUND",`no publishable App matches ${n}`);if(t.length!==1)throw T("APP_AMBIGUOUS",`more than one App matches ${n}`);return t[0]}function Yl(e){let n=e.localDefinitionRef?.packageRoot;if(!n||!/^(?:apps|skills)\/[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(n))throw T("APP_PACKAGE_ROOT_INVALID","selected App is not rooted in apps/<safe-id> or skills/<safe-id>");return n}function ji(e){let{path:n,rule:t}=e.reason;return `${e.code} at ${n===""?"<file>":n} (${t})`+(e.files.length>0?` [${e.files.join(", ")}]`:"")}function ql(e,n,t){let i=Fe({[de]:t},{mode:"published"});if(!i.ok)throw T("APP_UI_MANIFEST_INVALID",`generated ${de} does not read: ${ji(i.rejection)}`);if(an(i.manifest)!==an(n))throw T("APP_UI_MANIFEST_INVALID",`generated ${de} normalizes to a different definition hash than the source`);let o=e[$];if(o===void 0)return;let r=e[H],s=Fe({[$]:o,[de]:t,...r===void 0?{}:{[H]:r}},{mode:"local"});if(!s.ok)throw T("APP_UI_MANIFEST_INVALID",ji(s.rejection))}function Zl(e,n,t,i){let o={};for(let f of Z){let g=`${t}/${f}`;i.includes(g)&&(o[f]=Be(e,g));}let r=`${t}/${H}`;if(o[$]!==void 0&&i.includes(r)&&(o[H]=Be(e,r)),Object.keys(o).length===0)throw T("APP_UI_MANIFEST_INVALID","selected screen App has no package manifest.json or ui-plugin.json");let s=Fe(o,{mode:"local"});if(!s.ok)throw T("APP_UI_MANIFEST_INVALID",ji(s.rejection));if(s.manifest.pluginId!==n.appId)throw T("APP_DEFINITION_CONFLICT",`${s.file} identity no longer matches the selected App`);let a=o[de],c=a===void 0?void 0:Fi(a),d=`${t}/ui/index.html`;if(!i.includes(d))throw T("APP_UI_MANIFEST_INVALID","screen entry is outside package scope");let l=Fi(Be(e,d)),p=JSON.parse(JSON.stringify(s.v2Input));if(p.entryHash=l,Object.prototype.hasOwnProperty.call(p,"initialState")){let f=p.initialState;if(!Gl(f)||f.path!=="ui/state.json")throw T("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 T("APP_INITIAL_STATE_OUT_OF_SCOPE","initialState reference is outside the selected package");let _=Be(e,g);p.initialState={...f,hash:Fi(_)};}let u;try{let f=We(p,{mode:"published"});u=new Uint8Array(Buffer.from(JSON.stringify(f),"utf8"));}catch(f){throw f instanceof ae?T("APP_UI_MANIFEST_INVALID",f.code):T("APP_UI_MANIFEST_INVALID")}return ql(o,s.manifest,u),{bytes:u,...c===void 0?{}:{legacySourceHash:c}}}async function Ql(e,n){let{included:t,excluded:i}=fs(e);xs(e,t,n);let o=Es(e,t,{version:n.version}),r=ki(e,t);return {plan:{manifest:o,included:t,excluded:i,secretFindings:r},archiveOptions:{}}}async function eu(e,n){Kl(n);let t=await ps(e),i=Xl(t.items,n.appId);if(i.definitionHash!==n.expectedDefinitionHash)throw T("APP_DEFINITION_CONFLICT",`definitionHash changed for ${n.appId}`);let o=Yl(i),{included:r,excluded:s}=us(e,o),a=await Wl(e,o,r),c=new Map,d=new Map;if(i.capabilities.includes("screen")){let f=Zl(e,i,o,r),g=`${o}/${de}`;if(c.set(g,f.bytes),f.legacySourceHash!==void 0)d.set(g,f.legacySourceHash);else {r.push(g);let _=new TextEncoder;r.sort((P,C)=>Buffer.compare(_.encode(P),_.encode(C)));}}if(i.capabilities.includes("skill")&&!r.includes(`${o}/SKILL.md`))throw T("APP_SKILL_MISSING","skill capability requires package-root SKILL.md");xs(e,r,n,c);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:r,generatedFiles:c},p=Ts(e,l),u=ki(e,r,c);return {plan:{manifest:p,included:r,excluded:s,secretFindings:u,warnings:a},archiveOptions:{generatedFiles:c,sourceFileHashes:d}}}async function vs(e,n){let t=ce__namespace.resolve(e);if(Jl(n))return eu(t,n);if(n.expectedDefinitionHash!==void 0)throw T("APP_ID_REQUIRED");return Ql(t,n)}async function aI(e,n={}){return (await vs(e,n)).plan}function nu(e){let n=e.map(t=>`${t.path}:${t.line} (${t.rule})`).join(", ");throw new Oe("PUBLISH_SECRET_FINDINGS",`aborted \u2014 secret findings must be resolved before packing: ${n}`)}async function Fs(e,n={}){let t=ce__namespace.resolve(e),i=await vs(t,n);i.plan.secretFindings.length>0&&nu(i.plan.secretFindings);let o=await Ls(t,i.plan.manifest,i.archiveOptions);return {manifest:i.plan.manifest,tgzPath:o}}async function cI(e,n={}){return Fs(e,n)}async function dI(e,n){let t=await Fs(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 Vi=require('crypto'),net=require('net'),ne=require('fs'),promises=require('fs/promises'),ce=require('path'),Ts=require('js-yaml'),Os=require('os'),ws=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 Vi__namespace=/*#__PURE__*/_interopNamespace(Vi);var ne__namespace=/*#__PURE__*/_interopNamespace(ne);var ce__namespace=/*#__PURE__*/_interopNamespace(ce);var Ts__namespace=/*#__PURE__*/_interopNamespace(Ts);var Os__namespace=/*#__PURE__*/_interopNamespace(Os);var ws__namespace=/*#__PURE__*/_interopNamespace(ws);var j=(e,n)=>()=>(e&&(n=e(e=0)),n);var m=j(()=>{});var k,jn=j(()=>{m();k=class extends Error{constructor(t,i=t,o){super(i);this.code=t;this.currentRevision=o;}code;currentRevision;name="UiRuntimeError"};});function Lt(e){return $s.test(e)||Gs.test(e)}function ue(){throw new k("INPUT_INVALID","JSON value is not projection-safe")}function Xs(e){let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function St(e,n,t,i,o,r){if(n>i&&ue(),e===null||typeof e=="string"||typeof e=="boolean")return typeof e=="string"&&(Js.test(e)||Ks.test(e)&&!Zs(o,r)||Ws.test(e))&&ue(),e;if(typeof e=="number")return Number.isFinite(e)||ue(),e;(typeof e!="object"||e===void 0||typeof e=="function"||typeof e=="bigint")&&ue();let s=e;t.has(s)&&ue(),t.add(s);try{if(Array.isArray(e))return e.map(c=>St(c,n+1,t,i,o,r));Xs(s)||ue();let a={};for(let[c,d]of Object.entries(e))Lt(c)&&ue(),a[c]=St(d,n+1,t,i,[...o,c],r);return a}finally{t.delete(s);}}function fe(e,n=0,t=[]){(!Number.isInteger(n)||n<0||n>qs)&&ue(),(!Array.isArray(t)||t.some(o=>typeof o!="string"))&&ue();let i=St(e,0,new Set,Ys+n,[],t);return (i===null||Array.isArray(i)||typeof i!="object")&&ue(),i}function Qe(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 Zs(e,n){if(e.length===0)return false;let t=e.join(".");return n.some(i=>Qe(t,i))}function en(e){try{let n=JSON.stringify(e);return n===void 0&&ue(),n}catch{ue();}}function Mt(e){return Array.isArray(e)?e.map(Mt):e!==null&&typeof e=="object"?Object.fromEntries(Object.keys(e).sort().map(n=>[n,Mt(e[n])])):e}function te(e){return en(Mt(e))}function Ot(e){return Buffer.byteLength(e,"utf8")}var $s,Gs,Js,Ws,Ks,Ys,qs,Se=j(()=>{m();jn();$s=/(?:proof|token|secret|password|cookie|authorization|private[_-]?key|stack|exception|plugin[_-]?text)/i,Gs=/(?:url|uri|endpoint|path|file(?:name|path)?|cwd|shell|directory|dir|folder)$/i,Js=/<\/?[A-Za-z][^>]*>/,Ws=/^(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)/,Ks=/^(?:https?|file|ftp|ws|wss):\/\//i;Ys=8,qs=4;});var $i=j(()=>{m();Se();});var Fn,Rt=j(()=>{m();Fn=["text/plain","application/json"];});var Gi=j(()=>{m();Rt();});function nn(e){return ea.has(e)||na.test(e)||ta.test(e)}var Ji,ea,na,ta,Vn,An,Ee,wt,Ct,Ut,kt,xt,ze=j(()=>{m();Ji=["__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"],ea=new Set(Ji),na=/(?:proof|token|secret|password|cookie|authorization|private[_-]?key|stack|exception|plugin[_-]?text)/i,ta=/(?:url|uri|endpoint|path|file(?:name|path)?|cwd|shell|directory|dir|folder)$/i;Vn=/^[A-Za-z0-9_]+$/,An=/^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)*$/,Ee=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,wt=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/,Ct=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,Ut=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/,kt=["blue","violet","emerald","amber","rose","sky","slate","indigo"],xt=["inline","panel"];});function vt(e){return typeof e=="string"&&Fn.includes(e)}var Wi=j(()=>{m();Rt();ze();});function Bn(e){if(!jt(e))return false;let n=Object.keys(e);return !(n.some(t=>t!=="in"&&t!=="out")||n.length===0||Object.hasOwn(e,"in")&&!ia(e.in)||Object.hasOwn(e,"out")&&!oa(e.out))}function ia(e){return jt(e)?Object.keys(e).every(t=>t==="mediaType"||t==="required")&&Object.hasOwn(e,"mediaType")&&vt(e.mediaType)&&(!Object.hasOwn(e,"required")||typeof e.required=="boolean"):false}function oa(e){return jt(e)?Object.keys(e).every(t=>t==="mediaType"||t==="range")&&Object.hasOwn(e,"mediaType")&&vt(e.mediaType)&&(!Object.hasOwn(e,"range")||typeof e.range=="boolean"):false}function jt(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}var Ft=j(()=>{m();Gi();Wi();new TextDecoder("utf-8",{fatal:true,ignoreBOM:true});});function zn(e){return ra.includes(e)}function $n(e){return Number.isSafeInteger(e)&&e>=Hn.min&&e<=Hn.max}var ra,Hn,Ki,Vt=j(()=>{m();ra=[5,15,30,60],Hn=Object.freeze({min:15e3,max:6e5,default:3e5}),Ki=1;});function Jn(e){return Number.isSafeInteger(e)&&e>=Gn.min&&e<=Gn.max}function Wn(e){return sa.includes(e)}var Gn,Xi,sa,Bt=j(()=>{m();Gn=Object.freeze({min:6e4,max:18e5,default:6e5}),Xi=1,sa=["start","status","cancel"];});function pe(e){let t=e.renderer!==void 0||e.surfaces!==void 0||e.stateProjection!==void 0||e.dataPaths!==void 0||e.usage!==void 0||e.detailPanel!==void 0||e.displayModes!==void 0||e.summaryProjection!==void 0||e.legacy!==void 0||Object.values(e.actions).some(o=>o.resultProjection!==void 0)?{id:e.id,version:e.version,...e.renderer===void 0?{}:{renderer:e.renderer},...e.surfaces===void 0?{}:{surfaces:e.surfaces},...e.stateProjection===void 0?{}:{stateProjection:e.stateProjection},...e.dataPaths===void 0?{}:{dataPaths:e.dataPaths},...e.summaryProjection===void 0?{}:{summaryProjection:e.summaryProjection},...e.legacy===void 0?{}:{legacy:e.legacy},...e.usage===void 0?{}:{usage:e.usage},...e.detailPanel===void 0?{}:{detailPanel:e.detailPanel},...e.displayModes===void 0?{}:{displayModes:e.displayModes},...e.sourceHash===void 0?{}:{sourceHash:e.sourceHash},actions:e.actions}:e.sourceHash===void 0?{id:e.id,version:e.version,actions:e.actions}:{id:e.id,version:e.version,sourceHash:e.sourceHash,actions:e.actions},i=fe(t);return Vi.createHash("sha256").update(te(i)).digest("hex")}function zt(e){return `${e.id}\0${e.version}`}function ye(e){if(!/^\d+$/.test(String(e.version))||e.version<1||e.id.length<1||e.id.length>128)throw new k("DEFINITION_UNSUPPORTED","UI definition is invalid");if(e.sourceHash!==void 0&&(typeof e.sourceHash!="string"||!ca.test(e.sourceHash)))throw new k("DEFINITION_UNSUPPORTED","UI definition source hash is invalid");if(!/^[0-9a-f]{64}$/.test(e.hash)||pe(e)!==e.hash)throw new k("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=>!pa(i)))throw new k("DEFINITION_UNSUPPORTED","UI action declaration is invalid");if(t.confirmation!==void 0&&t.confirmation!=="none"&&t.confirmation!=="native")throw new k("DEFINITION_UNSUPPORTED","UI action confirmation is invalid");if(t.inputKeys&&(!Array.isArray(t.inputKeys)||t.inputKeys.some(i=>typeof i!="string"||!i)))throw new k("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 k("DEFINITION_UNSUPPORTED","UI action data input declaration is invalid");if(t.resultProjection&&Ht(t.resultProjection),t.schedule!==void 0&&(!zn(t.schedule.everyMinutes)||!$n(t.schedule.timeoutMs)))throw new k("DEFINITION_UNSUPPORTED","UI action schedule declaration is invalid");if(t.job!==void 0&&(typeof t.job!="object"||Object.keys(t.job).some(i=>i!=="deadlineMs")||!Jn(t.job.deadlineMs)))throw new k("DEFINITION_UNSUPPORTED","UI action job declaration is invalid");if(t.jobAccess!==void 0&&(!Array.isArray(t.jobAccess)||t.jobAccess.length===0||new Set(t.jobAccess).size!==t.jobAccess.length||!t.jobAccess.every(Wn)||t.job!==void 0))throw new k("DEFINITION_UNSUPPORTED","UI action job control declaration is invalid");if(t.content!==void 0&&!Bn(t.content))throw new k("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 k("DEFINITION_UNSUPPORTED","UI action environment declaration is invalid")}if(e.renderer!==void 0&&(!e.renderer||e.renderer.length>128))throw new k("DEFINITION_UNSUPPORTED","UI definition renderer is invalid");if(e.surfaces&&(!Array.isArray(e.surfaces)||e.surfaces.some(n=>!n||n.length>64)))throw new k("DEFINITION_UNSUPPORTED","UI definition surfaces are invalid");if(e.usage!==void 0&&e.usage!=="card"&&e.usage!=="window")throw new k("DEFINITION_UNSUPPORTED","UI definition usage is invalid");if(e.detailPanel!==void 0&&typeof e.detailPanel!="boolean")throw new k("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 k("DEFINITION_UNSUPPORTED","UI definition displayModes are invalid");if(e.usage==="card"&&e.displayModes!==void 0)throw new k("DEFINITION_UNSUPPORTED","Card definitions cannot declare displayModes");if(e.usage==="window"&&e.detailPanel!==void 0)throw new k("DEFINITION_UNSUPPORTED","Window definitions cannot declare detailPanel");if(e.stateProjection&&Ht(e.stateProjection),e.summaryProjection){Ht(e.summaryProjection);let n=new Set(e.stateProjection?.allow??[]);if(e.summaryProjection.allow.some(t=>!n.has(t)))throw new k("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 k("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(da(r,o==="readTool"),n.has(r.name))throw new k("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 k("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 k("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 k("DEFINITION_UNSUPPORTED","UI legacy agent access is invalid");if(e.legacy.actionTool!==void 0&&(!i||Object.keys(i).length===0))throw new k("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=>Qe(t,i))))throw new k("DEFINITION_UNSUPPORTED","UI definition dataPaths are invalid")}}function da(e,n){if(!e||typeof e!="object"||Array.isArray(e))throw new k("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 k("DEFINITION_UNSUPPORTED","UI legacy tool metadata is invalid");try{let r=fe(t.inputSchema);if(r.type!==void 0&&r.type!=="object")throw new Error("schema type");if(o){if(!n)throw new Error("fixed result location");let s=t.fixedResult;if(!s||typeof s!="object"||Array.isArray(s))throw new Error("fixed result");let a=s;if(Object.keys(a).sort().join(",")!=="argsPolicy,structuredContent"||a.argsPolicy!=="empty-only"&&a.argsPolicy!=="ignore"||!a.structuredContent||typeof a.structuredContent!="object"||Array.isArray(a.structuredContent))throw new Error("fixed result");let c=fe(a.structuredContent);if(Ot(en(c))>4*1024)throw new Error("fixed result size")}}catch{throw new k("DEFINITION_UNSUPPORTED","UI legacy tool metadata is not projection-safe")}}function Ht(e){if(!Array.isArray(e.allow)||e.allow.some(n=>!/^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)*$/.test(n)))throw new k("DEFINITION_UNSUPPORTED","UI projection policy is invalid")}function pa(e){return e.length>0&&e.length<=128&&e!=="*"&&e!=="all"&&!/[/*]/.test(e)}var ca,$e=j(()=>{m();Se();jn();Ft();Vt();Bt();ca=/^[0-9a-f]{64}$/;});var H,Me,$t=j(()=>{m();H="dist/tools.json",Me="dist/main.mjs";});var xe,Gt=j(()=>{m();xe="window";});function Yi(e){if(!Array.isArray(e)||e.length===0)return false;let n=new Set;for(let t of e){if(!la.some(i=>i===t)||n.has(t))return false;n.add(t);}return true}var la,qi=j(()=>{m();la=["CREWX_APP_INSTANCE_ID","CREWX_THREAD_ID"];});function $(e){throw new Jt(e)}function Pa(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 ba(e,n){let t=Object.getOwnPropertyDescriptor(e,n);return (!t||!("value"in t))&&$("CSP_ORIGIN_INVALID"),t.value}function Kn(e,n){if(!Object.prototype.hasOwnProperty.call(e,n))return [];let t=ba(e,n);Array.isArray(t)||$("CSP_ORIGIN_INVALID"),Reflect.ownKeys(t).some(r=>typeof r!="string"||r!=="length"&&!/^(?:0|[1-9][0-9]*)$/.test(r))&&$("CSP_ORIGIN_INVALID");let o=[];for(let r=0;r<t.length;r+=1)(!Object.prototype.hasOwnProperty.call(t,r)||typeof t[r]!="string")&&$("CSP_ORIGIN_INVALID"),o.push(t[r]);return Object.keys(t).length!==t.length&&$("CSP_ORIGIN_INVALID"),o}function Na(e){let n;try{n=JSON.stringify(e);}catch{$("CSP_ORIGIN_INVALID");}return n===void 0&&$("CSP_ORIGIN_INVALID"),new TextEncoder().encode(n).byteLength}function eo(e,n){/\s|\\/u.test(e)&&$("CSP_ORIGIN_INVALID");let t=ma.exec(e);t||$("CSP_ORIGIN_INVALID");let i=t[1].toLowerCase(),o=t[2];(o.includes("@")||o.includes("%")||o.includes("*"))&&$("CSP_ORIGIN_INVALID"),(o.startsWith("[")?ha:_a).test(o)||$("CSP_ORIGIN_INVALID"),i==="wss"&&n!=="connectDomains"&&$("CSP_ORIGIN_INVALID");let s;try{s=new URL(e);}catch{$("CSP_ORIGIN_INVALID");}(s.protocol!==`${i}:`||s.username!==""||s.password!==""||s.search!==""||s.hash!=="")&&$("CSP_ORIGIN_INVALID");let a=s.hostname.toLowerCase();if((!a||a.includes("%"))&&$("CSP_ORIGIN_INVALID"),!a.startsWith("[")){let d=a.endsWith(".")?a.slice(0,-1):a;(d.length===0||d.length>253)&&$("CSP_ORIGIN_INVALID"),d.split(".").some(p=>p.length>63||!Ea.test(p))&&$("CSP_ORIGIN_INVALID");}let c=s.origin;return (c==="null"||!c.startsWith(`${i}://`))&&$("CSP_ORIGIN_INVALID"),{origin:c,hostname:a}}function Da(e){let n=e.split(".").map(Number);return ((n[0]*256+n[1])*256+n[2])*256+n[3]}function no(e,n,t){let i=4294967295<<32-t>>>0;return (e&i)===(n&i)}function oo(e){let n=Da(e);return no(n,3221225472,24)?n!==3221225481&&n!==3221225482:Ta.some(([t,i])=>no(n,t,i))}function Sa(e){let n=e.indexOf("::"),t=(n<0?e:e.slice(0,n)).split(":").filter(Boolean),i=n<0?[]:e.slice(n+2).split(":").filter(Boolean);return (n<0?t:[...t,...Array(8-t.length-i.length).fill("0"),...i]).reduce((r,s)=>r<<16n|BigInt(Number.parseInt(s,16)),0n)}function Ma(e){let n=Sa(e),t=Number(n>>112n),i=Number(n>>96n&0xffffn);if(n>>32n===0xffffn){let o=Number(n&0xffffffffn);return oo([o>>>24&255,o>>>16&255,o>>>8&255,o&255].join("."))}return t<8192||t>16383||t===8193&&i<=511||t===8193&&i===3512||t===8194||t===16383&&i<=4095}function La(e,n){let t=e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e,i=net.isIP(t);if(i===4)return oo(t);if(i===6)return Ma(t);let o=e.toLowerCase().replace(/\.$/,"");return !o||!o.includes(".")||n.has(o)?true:ga.some(r=>o===r||o.endsWith(`.${r}`))}function to(e){return Object.freeze([...new Set(e.map(n=>n.origin))].sort())}function io(e){return JSON.stringify({baseUriDomains:[],connectDomains:e.connectDomains,declared:e.declared,frameDomains:e.frameDomains,resourceDomains:[]})}function ro(e,n={}){if(e===void 0){let y=io({declared:false,connectDomains:[],frameDomains:[]});return Object.freeze({declared:false,connectDomains:Object.freeze([]),frameDomains:Object.freeze([]),resourceDomains:Object.freeze([]),baseUriDomains:Object.freeze([]),cspHash:Vi.createHash("sha256").update(y,"utf8").digest("hex")})}Pa(e)||$("CSP_ORIGIN_INVALID");let t=Reflect.ownKeys(e);t.some(y=>typeof y!="string")&&$("CSP_ORIGIN_INVALID"),t.some(y=>!Ia.has(y))&&$("CSP_AXIS_UNKNOWN");let i=Kn(e,"connectDomains"),o=Kn(e,"frameDomains"),r=Kn(e,"resourceDomains"),s=Kn(e,"baseUriDomains");(r.length>0||s.length>0)&&$("CSP_AXIS_UNSUPPORTED"),(Na(e)>fa||i.length>Qi||o.length>Qi||i.length+o.length>ya||[...i,...o].some(y=>new TextEncoder().encode(y).byteLength>Aa))&&$("CSP_LIMIT_EXCEEDED");let c=i.map(y=>eo(y,"connectDomains")),d=o.map(y=>eo(y,"frameDomains")),l=new Set((n.runtimeHostnames??[]).map(y=>y.toLowerCase().replace(/\.$/,"")));[...c,...d].some(y=>La(y.hostname,l))&&$("CSP_ORIGIN_FORBIDDEN");let p={declared:true,connectDomains:to(c),frameDomains:to(d)},u=io(p);return Object.freeze({...p,resourceDomains:Object.freeze([]),baseUriDomains:Object.freeze([]),cspHash:Vi.createHash("sha256").update(u,"utf8").digest("hex")})}var fa,Qi,ya,Aa,Ia,ga,ma,ha,_a,Ea,Ta,Jt,so=j(()=>{m();fa=4096,Qi=16,ya=32,Aa=512,Ia=new Set(["connectDomains","frameDomains","resourceDomains","baseUriDomains"]),ga=["localhost","local","internal","home.arpa","test","example","invalid","onion","lan","corp","home","intranet","private","localdomain"],ma=/^(https|wss):\/\/([^/?#]+)$/i,ha=/^\[[^\]]+\](?::[0-9]+)?$/,_a=/^[^:\[\]]+(?::[0-9]+)?$/,Ea=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/,Ta=[[0,8],[1681915904,10],[167772160,8],[2130706432,8],[2851995648,16],[2886729728,12],[3221225984,24],[3227017984,24],[3232235520,16],[3323068416,15],[3325256704,24],[3405803776,24],[3758096384,4],[4026531840,4]],Jt=class extends Error{constructor(t){super(t);this.code=t;}code;name="UiPluginCspNormalizationError"};});function gn(e,n){return n===void 0||n===""?e:e===""?n:n.startsWith("[")?`${e}${n}`:`${e}.${n}`}function f(e,n=e,t,i){throw new ae(e,n,t,i)}function z(e,n){try{return n()}catch(t){throw t instanceof ae?t.withPathPrefix(e):t}}function G(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 C(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function sc(e,n){let t={};for(let[i,o]of Object.entries(e))i!==n&&(t[i]=o);return t}function K(e,n,t=[]){let i=new Set([...n,...t]),o=Object.keys(e).find(s=>!i.has(s));o!==void 0&&f("MANIFEST_INVALID","MANIFEST_INVALID",o,"unknown-key");let r=n.find(s=>!C(e,s));r!==void 0&&f("MANIFEST_INVALID","MANIFEST_INVALID",r,"missing-key");}function Zn(e,n=false,t=false,i=false){return Ca.test(e)||!i&&ka.test(e)||Ua.test(e)||t&&ao.test(e)||xa.test(e)&&!(n&&/^\s*data:/i.test(e)&&!ao.test(e))}function qn(e,n=new Set,t=0,i=false,o=false,r=""){if(typeof e=="string"){Zn(e,i,o)&&f("UNSAFE_VALUE","UNSAFE_VALUE",r,"unsafe-value");return}if(!(e===null||typeof e!="object")){(t>8||n.has(e))&&f("MANIFEST_INVALID","MANIFEST_INVALID",r),n.add(e);try{if(Array.isArray(e)){e.forEach((s,a)=>qn(s,n,t+1,!1,!1,gn(r,`[${a}]`)));return}G(e)||f("MANIFEST_INVALID","MANIFEST_INVALID",r);for(let[s,a]of Object.entries(e))qn(a,n,t+1,i&&t===0&&(s==="name"||s==="description"),o,gn(r,s));}finally{n.delete(e);}}}function Te(e,n){let t=e[n];return typeof t!="string"&&f("MANIFEST_INVALID"),t}function Ie(e,n,t){let i=e[n];return (!Number.isSafeInteger(i)||i<t)&&f("MANIFEST_INVALID"),i}function Wt(e){return wa.test(e)||f("MANIFEST_INVALID"),e}function tn(e){return Ra.test(e)||f("TOKEN_INVALID"),e}function ac(e){return go.test(e)||f("MANIFEST_INVALID"),e}function cc(e){G(e)||f("MANIFEST_INVALID");let n={};for(let[t,i]of Object.entries(e)){let o=ac(t);G(i)||f("MANIFEST_INVALID");let r=i.type;if(r==="text"){K(i,["type","maxLength"]),n[o]={type:r,maxLength:Ie(i,"maxLength",1)};continue}if(r==="text-list"){K(i,["type","max","itemMaxLength"]),n[o]={type:r,max:Ie(i,"max",0),itemMaxLength:Ie(i,"itemMaxLength",1)};continue}if(r==="step-list"){K(i,["type","min","max","labelMaxLength","detailMaxLength"]);let s=Ie(i,"min",0),a=Ie(i,"max",1);s>a&&f("MANIFEST_INVALID"),n[o]={type:r,min:s,max:a,labelMaxLength:Ie(i,"labelMaxLength",1),detailMaxLength:Ie(i,"detailMaxLength",1)};continue}typeof r=="string"&&f("SCHEMA_TYPE_UNSUPPORTED"),f("MANIFEST_INVALID");}return n}function dc(e,n,t){let i=e[n];(!i||i.type!==t)&&f("MANIFEST_INVALID");}function Xn(e,n,t){let i=Te(e,"field");return go.test(i)||f("MANIFEST_INVALID"),dc(n,i,t),i}function pc(e,n){G(e)||f("MANIFEST_INVALID");let t=e.primitive;switch(typeof t!="string"&&f("MANIFEST_INVALID"),rc.includes(t)||f("PRIMITIVE_UNKNOWN"),t){case "card-shell":return K(e,["primitive"]),{primitive:t};case "meta-banner":return K(e,["primitive","badgeToken","noticeToken"]),{primitive:t,badgeToken:tn(Te(e,"badgeToken")),noticeToken:tn(Te(e,"noticeToken"))};case "heading":return K(e,["primitive","field"]),{primitive:t,field:Xn(e,n,"text")};case "labeled-text":return K(e,["primitive","titleToken","field","variant"]),e.variant!=="callout"&&f("MANIFEST_INVALID"),{primitive:t,titleToken:tn(Te(e,"titleToken")),field:Xn(e,n,"text"),variant:"callout"};case "step-flow":return K(e,["primitive","titleToken","field"]),{primitive:t,titleToken:tn(Te(e,"titleToken")),field:Xn(e,n,"step-list")};case "text-list":{K(e,["primitive","titleToken","field"],["emptyToken","hideWhenEmpty"]);let i={primitive:t,titleToken:tn(Te(e,"titleToken")),field:Xn(e,n,"text-list")};return C(e,"emptyToken")&&(i.emptyToken=tn(Te(e,"emptyToken"))),C(e,"hideWhenEmpty")&&(typeof e.hideWhenEmpty!="boolean"&&f("MANIFEST_INVALID"),i.hideWhenEmpty=e.hideWhenEmpty),i}}return f("MANIFEST_INVALID")}function lc(e,n){return Array.isArray(e)||f("MANIFEST_INVALID"),e.map(t=>pc(t,n))}function X(e="v2 manifest exceeds a contract limit",n,t){return f("LIMIT_EXCEEDED",e,n,t)}function Ae(e="initial state is not projection-safe"){return f("INITIAL_STATE_INVALID",e)}function co(e,n){return (typeof e!="string"||e.length===0||e.length>4096||e.trim().length===0||tc.test(e)||ic.test(e))&&f("MANIFEST_INVALID",`${n} is invalid`),(Zn(e,true,true)||va.test(e)||ja.test(e)||Fa.test(e))&&f("UNSAFE_VALUE",`${n} contains an unsafe value`),e}function Kt(e,n){return (typeof e!="string"||!Ee.test(e))&&f("MANIFEST_INVALID",`${n} is invalid`),e}function uc(e){return (typeof e!="string"||!wt.test(e)||e==="*"||e==="all")&&f("MANIFEST_INVALID","action capability is invalid"),e}function mo(e){return (typeof e!="string"||!nc.test(e))&&f("MANIFEST_INVALID","resource hash is invalid"),e}function Xt(e,n=new Set,t=0,i=""){if(typeof e=="string"){e.length>4096&&X("v2 manifest string is too long",i,"string-too-long");return}if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){Number.isFinite(e)||f("MANIFEST_INVALID","v2 manifest contains a non-finite number",i,"non-finite-number");return}(e===void 0||typeof e=="function"||typeof e=="bigint")&&f("MANIFEST_INVALID","v2 manifest contains a non-JSON value",i,"non-json-value"),typeof e!="object"&&f("MANIFEST_INVALID","MANIFEST_INVALID",i),t>8&&X("v2 manifest nesting is too deep",i,"too-deep"),n.has(e)&&f("MANIFEST_INVALID","v2 manifest contains a cycle",i,"cycle"),n.add(e);try{if(Array.isArray(e)){e.length>128&&X("v2 manifest array is too long",i,"array-too-long"),e.forEach((o,r)=>Xt(o,n,t+1,gn(i,`[${r}]`)));return}G(e)||f("MANIFEST_INVALID","v2 manifest contains a non-plain object",i,"non-plain-object");for(let[o,r]of Object.entries(e))Xt(r,n,t+1,gn(i,o));}finally{n.delete(e);}}}function ho(e){return (typeof e!="string"||e.length>4096||!An.test(e))&&(typeof e=="string"&&e.length>4096&&X("projection path is too long"),f("MANIFEST_INVALID","projection paths must be canonical exact paths")),e.split(".").some(t=>nn(t))&&f("MANIFEST_INVALID","projection paths cannot address reserved state keys"),e}function Yt(e){G(e)||f("MANIFEST_INVALID","projection policy must be an object"),K(e,["allow"]),Array.isArray(e.allow)||f("MANIFEST_INVALID","projection allow must be an array"),e.allow.length>128&&X("projection allowlist is too long");let n=[],t=new Set;for(let i of e.allow){let o=ho(i);t.has(o)&&f("MANIFEST_INVALID","projection allowlist contains a duplicate path"),t.add(o),n.push(o);}return {allow:n}}function fc(e,n){if(e===void 0)return;Array.isArray(e)||f("MANIFEST_INVALID","dataPaths must be an array"),e.length>oc&&X("dataPaths exceed the v2 limit");let t=[],i=new Set;for(let o of e){let r=ho(o);i.has(r)&&f("MANIFEST_INVALID","dataPaths contain a duplicate path"),n.some(s=>Qe(r,s))||f("MANIFEST_INVALID","dataPaths must be projection-allowed"),i.add(r),t.push(r);}return t}function on(e,n,t=Number.MAX_SAFE_INTEGER){return (!Number.isSafeInteger(e)||e<0||e>t)&&f("MANIFEST_INVALID",`${n} is invalid`),e}function po(e,n){return (typeof e!="number"||!Number.isFinite(e))&&f("MANIFEST_INVALID",`${n} is invalid`),e}function qt(e,n=0,t=new Set){if(typeof e=="string")return (e.length>4096||Zn(e))&&f("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)||f("MANIFEST_INVALID","schema enum contains a non-finite number"),e;(n>8||typeof e!="object"||e===void 0)&&X("schema enum is too deep"),t.has(e)&&f("MANIFEST_INVALID","schema enum contains a cycle"),t.add(e);try{if(Array.isArray(e))return e.length>128&&X("schema enum array is too long"),e.map(o=>qt(o,n+1,t));G(e)||f("MANIFEST_INVALID","schema enum contains a non-plain object");let i={};for(let[o,r]of Object.entries(e))nn(o)&&f("MANIFEST_INVALID","schema enum contains a reserved key"),i[o]=qt(r,n+1,t);return i}finally{t.delete(e);}}function yc(e,n){if(e===void 0)return;Array.isArray(e)||f("MANIFEST_INVALID","schema required must be an array"),e.length>64&&X("schema required list is too long");let t=[],i=new Set;for(let o of e)(typeof o!="string"||!An.test(o))&&f("MANIFEST_INVALID","schema required contains an invalid key"),o.length>4096&&X("schema required key is too long"),i.has(o)&&f("MANIFEST_INVALID","schema required contains a duplicate key"),n&&!Object.prototype.hasOwnProperty.call(n,o)&&f("MANIFEST_INVALID","schema required references an undeclared property"),i.add(o),t.push(o);return t}function Ac(e,n){let t=n?An:Vn;return e.length>4096&&X("schema property name is too long"),(!t.test(e)||e.split(".").some(i=>nn(i)))&&f("MANIFEST_INVALID","schema property name is invalid"),e}function Zt(e,n=0,t=false){G(e)||f("MANIFEST_INVALID","action inputSchema must be an object"),n>8&&X("action inputSchema is too deep");let i=e.type;i!=="object"&&i!=="string"&&i!=="number"&&i!=="integer"&&i!=="boolean"&&i!=="array"&&i!=="null"&&(typeof i=="string"&&f("SCHEMA_TYPE_UNSUPPORTED","action inputSchema type is unsupported"),f("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"),K(e,["type"],o.filter(a=>a!=="type"));let r={type:i};if(C(e,"enum")&&(Array.isArray(e.enum)||f("MANIFEST_INVALID","schema enum must be an array"),e.enum.length>128&&X("schema enum is too long"),r.enum=e.enum.map(a=>qt(a))),i==="string"&&(C(e,"minLength")&&(r.minLength=on(e.minLength,"schema minLength",4096)),C(e,"maxLength")&&(r.maxLength=on(e.maxLength,"schema maxLength",4096)),r.minLength!==void 0&&r.maxLength!==void 0&&r.minLength>r.maxLength&&f("MANIFEST_INVALID","schema string length bounds are inverted")),(i==="number"||i==="integer")&&(C(e,"minimum")&&(r.minimum=po(e.minimum,"schema minimum")),C(e,"maximum")&&(r.maximum=po(e.maximum,"schema maximum")),r.minimum!==void 0&&r.maximum!==void 0&&r.minimum>r.maximum&&f("MANIFEST_INVALID","schema numeric bounds are inverted")),i==="array"&&(C(e,"minItems")&&(r.minItems=on(e.minItems,"schema minItems",128)),C(e,"maxItems")&&(r.maxItems=on(e.maxItems,"schema maxItems",128)),r.minItems!==void 0&&r.maxItems!==void 0&&r.minItems>r.maxItems&&f("MANIFEST_INVALID","schema array length bounds are inverted"),C(e,"items")&&(r.items=Zt(e.items,n+1,false))),i==="object"){let a;if(C(e,"properties")){G(e.properties)||f("MANIFEST_INVALID","schema properties must be an object");let d=Object.entries(e.properties);d.length>64&&X("schema properties are too many"),a={};for(let[l,p]of d){let u=Ac(l,t);a[u]=Zt(p,n+1,false);}r.properties=a;}C(e,"minProperties")&&(r.minProperties=on(e.minProperties,"schema minProperties",64)),C(e,"maxProperties")&&(r.maxProperties=on(e.maxProperties,"schema maxProperties",64)),r.minProperties!==void 0&&r.maxProperties!==void 0&&r.minProperties>r.maxProperties&&f("MANIFEST_INVALID","schema object property bounds are inverted");let c=yc(e.required,a);c!==void 0&&(r.required=c),C(e,"additionalProperties")&&(e.additionalProperties!==false&&f("MANIFEST_INVALID","schema additionalProperties must be false"),r.additionalProperties=false);}let s=JSON.stringify(r);return (s===void 0||Buffer.byteLength(s,"utf8")>2097152)&&X("action inputSchema subtree is too large"),r}function Ic(e){let n=Zt(e,0,true);return (n.type!=="object"||!n.properties)&&f("MANIFEST_INVALID","action inputSchema must declare object properties"),n}function gc(e){if(G(e)||f("MANIFEST_INVALID","action backend must be an object"),e.type==="core"){K(e,Xa);let n=e.handler;return (typeof n!="string"||!Ct.test(n))&&f("MANIFEST_INVALID","core backend handler is invalid"),{type:"core",handler:n}}if(e.type==="skill"&&C(e,"entry"))return K(e,Za),e.entry!==Me&&f("MANIFEST_INVALID",`skill backend entry must be ${Me}`),{type:"skill",entry:Me};if(e.type==="skill"){K(e,Ya,qa),(!Array.isArray(e.command)||e.command.length===0||e.command.length>16)&&f("MANIFEST_INVALID","skill backend command is invalid");let n=[];for(let i of e.command)(typeof i!="string"||i.length===0||i.length>256||!Ut.test(i))&&f("MANIFEST_INVALID","skill backend command token is invalid"),n.push(i);let t=C(e,"env")?Tc(e.env):void 0;return {type:"skill",command:n,...t===void 0?{}:{env:t}}}f("MANIFEST_INVALID","action backend type is unsupported");}function mc(e){G(e)||f("MANIFEST_INVALID","action must be an object"),K(e,za,$a),C(e,"_meta")&&z("_meta",()=>_o(e._meta));let n=z("actionId",()=>Kt(e.actionId,"actionId"));Lt(n)&&f("MANIFEST_INVALID",`actionId "${n}" is not projection-safe`,"actionId");let t=z("capability",()=>uc(e.capability)),i=e.mutation;typeof i!="boolean"&&f("MANIFEST_INVALID","action mutation must be boolean","mutation");let o=z("inputSchema",()=>Ic(e.inputSchema)),r;if(C(e,"dataInputs")){Array.isArray(e.dataInputs)||f("MANIFEST_INVALID","action dataInputs must be an array","dataInputs");let y=o.properties,g=new Set,_=[];for(let T of e.dataInputs)(typeof T!="string"||!C(y,T)||g.has(T))&&f("MANIFEST_INVALID","action dataInputs must be unique declared properties","dataInputs"),g.add(T),_.push(T);r=_;}let s=z("resultProjection",()=>Yt(e.resultProjection)),a=z("backend",()=>gc(e.backend)),c;C(e,"content")&&((a.type!=="skill"||!Bn(e.content))&&f("MANIFEST_INVALID","action content declaration is invalid","content"),c=Pc(e.content));let d;if(C(e,"confirmation")){let y=e.confirmation;y!=="none"&&y!=="native"&&f("MANIFEST_INVALID","action confirmation is invalid","confirmation"),d=y;}let l;C(e,"schedule")&&(l=z("schedule",()=>Ec(e.schedule,{backend:a,inputSchema:o,hasContent:c!==void 0,hasDataInputs:r!==void 0,confirmation:d})));let p;C(e,"job")&&(l!==void 0&&f("MANIFEST_INVALID","an action is either the scheduled run or a job, not both","job"),p=z("job",()=>_c(e.job,{backend:a,inputSchema:o,hasContent:c!==void 0,hasDataInputs:r!==void 0,confirmation:d})));let u;return C(e,"jobAccess")&&(p!==void 0&&f("MANIFEST_INVALID","an action is either the job or a job control, not both","jobAccess"),u=z("jobAccess",()=>hc(e.jobAccess,{backend:a,hasContent:c!==void 0}))),{actionId:n,capability:t,mutation:i,inputSchema:o,resultProjection:s,backend:a,...c===void 0?{}:{content:c},...r===void 0?{}:{dataInputs:r},...d===void 0?{}:{confirmation:d},...l===void 0?{}:{schedule:l},...p===void 0?{}:{job:p},...u===void 0?{}:{jobAccess:u}}}function hc(e,n){return (n.backend.type!=="skill"||!("entry"in n.backend)||n.backend.entry!==Me)&&f("MANIFEST_INVALID","jobAccess needs a tool-mode action","jobAccess"),n.hasContent&&f("MANIFEST_INVALID","a job control action takes no content","jobAccess"),(!Array.isArray(e)||e.length===0)&&f("MANIFEST_INVALID","jobAccess must list at least one operation","jobAccess"),(new Set(e).size!==e.length||!e.every(Wn))&&f("MANIFEST_INVALID","jobAccess must name each operation once: start, status or cancel","jobAccess"),Object.freeze([...e])}function _c(e,n){(n.backend.type!=="skill"||!("entry"in n.backend)||n.backend.entry!==Me)&&f("MANIFEST_INVALID","job needs a tool-mode action","job"),(n.hasContent||n.hasDataInputs||n.confirmation!==void 0&&n.confirmation!=="none")&&f("MANIFEST_INVALID","a job action takes no content, dataInputs or native confirmation","job"),(n.inputSchema.required??[]).length>0&&f("MANIFEST_INVALID","a job action input must accept {}","inputSchema.required"),G(e)||f("MANIFEST_INVALID","job must be an object","job"),K(e,[],Wa);let t=C(e,"deadlineMs")?e.deadlineMs:Gn.default;return Jn(t)||f("MANIFEST_INVALID","job deadlineMs is invalid","job.deadlineMs"),{deadlineMs:t}}function Ec(e,n){(n.backend.type!=="skill"||!("entry"in n.backend)||n.backend.entry!==Me)&&f("MANIFEST_INVALID","schedule needs a tool-mode action","schedule"),(n.hasContent||n.hasDataInputs||n.confirmation!==void 0&&n.confirmation!=="none")&&f("MANIFEST_INVALID","a scheduled action takes no content, dataInputs or native confirmation","schedule"),(n.inputSchema.required??[]).length>0&&f("MANIFEST_INVALID","a scheduled action input must accept {}","inputSchema.required"),G(e)||f("MANIFEST_INVALID","schedule must be an object","schedule"),K(e,Ga,Ja),zn(e.everyMinutes)||f("MANIFEST_INVALID","schedule everyMinutes is invalid","schedule.everyMinutes");let t=C(e,"timeoutMs")?e.timeoutMs:Hn.default;return $n(t)||f("MANIFEST_INVALID","schedule timeoutMs is invalid","schedule.timeoutMs"),{everyMinutes:e.everyMinutes,timeoutMs:t}}function Tc(e){return Yi(e)||f("MANIFEST_INVALID","skill backend env is invalid"),Object.freeze([...e])}function Pc(e){return Object.freeze({...e.in===void 0?{}:{in:Object.freeze({...e.in})},...e.out===void 0?{}:{out:Object.freeze({...e.out})}})}function bc(e){return G(e)||f("INITIAL_STATE_INVALID","initialState must be an object"),K(e,Qa,ec),e.path!=="ui/state.json"&&f("MANIFEST_INVALID","initialState path is not fixed"),C(e,"hash")?{path:"ui/state.json",hash:mo(e.hash)}:{path:"ui/state.json"}}function Nc(e){let n=["wasm","terminal","htmlDocuments"];return (!G(e)||Object.keys(e).length===0||Object.keys(e).some(t=>!n.includes(t)||e[t]!==true))&&f("MANIFEST_INVALID","runtime must contain only known capability flags set to true"),{...e.wasm===true?{wasm:true}:{},...e.terminal===true?{terminal:true}:{},...e.htmlDocuments===true?{htmlDocuments:true}:{}}}function Dc(e,n){let t;try{t=ro(e);}catch(i){let o=i!==null&&typeof i=="object"&&"code"in i&&typeof i.code=="string"?i.code:"CSP_ORIGIN_INVALID";return f("MANIFEST_INVALID",o,void 0,o.toLowerCase().replace(/_/g,"-"))}if(t.frameDomains.length>0&&f("MANIFEST_INVALID","external origins in csp are not enabled in this rollout",void 0,"csp-not-enabled"),t.connectDomains.length!==0)return n?.terminal===true&&f("MANIFEST_INVALID","runtime.terminal cannot be combined with csp.connectDomains","connectDomains","terminal-with-connect-domains"),Object.freeze({connectDomains:t.connectDomains})}function Sc(e,n){qn(G(e)&&C(e,"csp")?sc(e,"csp"):e,new Set,0,true,true),Xt(e),G(e)||f("MANIFEST_INVALID"),K(e,Ba,Ha),C(e,"_meta")&&z("_meta",()=>_o(e._meta)),e.manifestVersion!==2&&f("MANIFEST_INVALID");let t;C(e,"runtime")&&(t=z("runtime",()=>Nc(e.runtime)));let i;C(e,"csp")&&(i=z("csp",()=>Dc(e.csp,t)));let o=z("pluginId",()=>Kt(e.pluginId,"pluginId")),r=z("definitionId",()=>Kt(e.definitionId,"definitionId")),s=z("version",()=>Ie(e,"version",1)),a=z("name",()=>co(e.name,"name")),c=z("description",()=>co(e.description,"description")),d;C(e,"icon")&&((typeof e.icon!="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(e.icon))&&f("MANIFEST_INVALID","icon is invalid","icon"),d=e.icon);let l;C(e,"tone")&&((typeof e.tone!="string"||!kt.includes(e.tone))&&f("MANIFEST_INVALID","tone is invalid","tone"),l=e.tone),e.entry!=="ui/index.html"&&f("MANIFEST_INVALID","entry path is not fixed","entry","fixed-value");let p;C(e,"entryHash")&&(p=z("entryHash",()=>mo(e.entryHash)));let u;C(e,"initialState")&&(u=z("initialState",()=>bc(e.initialState)));let y;C(e,"usage")&&(e.usage!=="card"&&e.usage!=="window"&&f("MANIFEST_INVALID","usage is invalid","usage"),y=e.usage);let g;C(e,"detailPanel")&&(typeof e.detailPanel!="boolean"&&f("MANIFEST_INVALID","detailPanel is invalid","detailPanel"),g=e.detailPanel);let _;if(C(e,"displayModes")){((y??xe)!==xe||!Array.isArray(e.displayModes)||e.displayModes.length===0)&&f("MANIFEST_INVALID","displayModes are only valid for window Apps","displayModes");let h=new Set(["inline","floating","focused"]);(new Set(e.displayModes).size!==e.displayModes.length||e.displayModes.some(E=>typeof E!="string"||!h.has(E)))&&f("MANIFEST_INVALID","displayModes are invalid","displayModes"),_=e.displayModes;}(y??xe)===xe&&g!==void 0&&f("MANIFEST_INVALID","detailPanel is card-only","detailPanel");let T=n.mode??"local";T!=="local"&&T!=="installed"&&T!=="published"&&f("MANIFEST_INVALID","manifest mode is invalid"),T!=="local"&&p===void 0&&f("MANIFEST_INVALID","installed manifests require entryHash","entryHash","required-when-installed"),T!=="local"&&u!==void 0&&u.hash===void 0&&f("MANIFEST_INVALID","installed manifests require initialState.hash","initialState.hash","required-when-installed"),(!Array.isArray(e.surfaces)||e.surfaces.length===0)&&f("MANIFEST_INVALID","surfaces are invalid","surfaces"),e.surfaces.length>2&&X("surfaces exceed the v2 limit","surfaces","too-many-items");let U=[],x=new Set;for(let h of e.surfaces)(typeof h!="string"||!xt.includes(h))&&f("MANIFEST_INVALID","surface is unsupported","surfaces"),x.has(h)&&f("MANIFEST_INVALID","surfaces contain a duplicate","surfaces","duplicate-item"),x.add(h),U.push(h);G(e.size)||f("MANIFEST_INVALID","size must be an object","size"),z("size",()=>K(e.size,["height"]));let b=z("size",()=>Ie(e.size,"height",1));b>720&&X("size.height exceeds the v2 limit","size.height","too-large");let w=z("stateProjection",()=>Yt(e.stateProjection)),V=e.summaryProjection===void 0?void 0:z("summaryProjection",()=>Yt(e.summaryProjection));V!==void 0&&V.allow.some(h=>!w.allow.includes(h))&&f("MANIFEST_INVALID","summaryProjection must be a subset of stateProjection.allow","summaryProjection");let N=z("dataPaths",()=>fc(e.dataPaths,w.allow));Array.isArray(e.actions)||f("MANIFEST_INVALID","actions must be an array","actions"),e.actions.length>32&&X("actions exceed the v2 limit","actions","too-many-items");let D=[],L=new Set,I=0,A=0;for(let[h,E]of e.actions.entries()){let v=`actions[${h}]`,R=z(v,()=>mc(E));if(L.has(R.actionId)&&f("MANIFEST_INVALID","actions contain a duplicate actionId",`${v}.actionId`,"duplicate-item"),R.schedule!==void 0&&(I+=1,I>Ki&&f("MANIFEST_INVALID","an App declares at most one scheduled action",`${v}.schedule`,"duplicate-item")),R.job!==void 0&&(A+=1,A>Xi&&f("MANIFEST_INVALID","an App declares at most one job action",`${v}.job`,"duplicate-item")),R.backend.type==="core"&&R.backend.handler==="state.set"){R.mutation||f("MANIFEST_INVALID","state.set actions must be mutations",`${v}.mutation`);for(let Y of Object.keys(R.inputSchema.properties))w.allow.includes(Y)||f("MANIFEST_INVALID","state.set input paths must be projection-allowed",`${v}.inputSchema.properties`);}L.add(R.actionId),D.push(R);}return {manifestVersion:2,pluginId:o,definitionId:r,version:s,name:a,description:c,...d===void 0?{}:{icon:d},...l===void 0?{}:{tone:l},entry:"ui/index.html",...p===void 0?{}:{entryHash:p},...t===void 0?{}:{runtime:t},...i===void 0?{}:{csp:i},...u===void 0?{}:{initialState:u},...y===void 0?{}:{usage:y},...g===void 0?{}:{detailPanel:g},..._===void 0?{}:{displayModes:_},surfaces:U,size:{height:b},stateProjection:w,...V===void 0?{}:{summaryProjection:V},...N===void 0?{}:{dataPaths:N},actions:D}}function _o(e){G(e)||f("MANIFEST_INVALID","_meta must be an object");let n=JSON.stringify(e);(n===void 0||Buffer.byteLength(n,"utf8")>Ka)&&X("_meta exceeds the 4 KiB limit",void 0,"meta-too-large");}function Mc(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.schedule===void 0?{}:{schedule:r.schedule},...r.job===void 0?{}:{job:r.job},...r.jobAccess===void 0?{}:{jobAccess:r.jobAccess},...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 Qt(e,n,t,i,o,r){if(typeof e=="string"){let s=o.length>0&&r.some(a=>Qe(o.join("."),a));return (e.length>4096||Zn(e,false,false,s))&&Ae("state contains an unsafe string"),e}if(e===null||typeof e=="boolean")return e;if(typeof e=="number")return Number.isFinite(e)||Ae("state contains a non-finite number"),e;(e===void 0||typeof e!="object"||typeof e=="function"||typeof e=="bigint")&&Ae("state contains a non-JSON value"),t>8&&Ae("state is too deep"),n.has(e)&&Ae("state contains a cycle"),n.add(e);try{let s;if(Array.isArray(e))e.length>128&&Ae("state array is too long"),s=e.map(c=>Qt(c,n,t+1,2097152,o,r));else {G(e)||Ae("state contains a non-plain object");let c={};for(let[d,l]of Object.entries(e))(d.length>4096||!Vn.test(d)||nn(d))&&(d.length>4096&&Ae("state key is too long"),Ae("state contains a reserved or invalid key")),c[d]=Qt(l,n,t+1,2097152,[...o,d],r);s=c;}let a=JSON.stringify(s);return (a===void 0||Buffer.byteLength(a,"utf8")>i)&&Ae("state subtree is too large"),s}finally{n.delete(e);}}function ni(e,n=[]){G(e)||Ae("initial state must be a JSON object");let t=Qt(e,new Set,0,2097152,[],n);return (t===null||Array.isArray(t)||typeof t!="object")&&Ae(),t}function Lc(e,n={}){qn(e),G(e)||f("MANIFEST_INVALID"),K(e,Va),e.manifestVersion!==1&&f("MANIFEST_INVALID");let t=Wt(Te(e,"pluginId")),i=Wt(Te(e,"definitionId")),o=Ie(e,"version",1),r=Ie(e,"primitiveSet",1),s=n.supportedPrimitiveSet??Oa;(!Number.isSafeInteger(s)||s<1)&&f("MANIFEST_INVALID"),r>s&&f("PRIMITIVE_SET_UNSUPPORTED"),G(e.activation)||f("MANIFEST_INVALID"),K(e.activation,["kind","language"]),e.activation.kind!=="fenced-code"&&f("MANIFEST_INVALID");let a=Wt(Te(e.activation,"language")),c=cc(e.schema),d=lc(e.layout,c);return {manifestVersion:1,pluginId:t,definitionId:i,version:o,primitiveSet:r,activation:{kind:"fenced-code",language:a},schema:c,layout:d}}function Oc(e,n={}){return G(e)||f("MANIFEST_INVALID"),Object.hasOwn(e,"lineage")&&f("MANIFEST_INVALID","lineage is only allowed in product bundle indexes"),e.manifestVersion===2?Sc(e,n):Lc(e,n)}function Je(e,n={}){try{return Oc(e,n)}catch(t){if(t instanceof ae)throw t;return f("MANIFEST_INVALID")}}function mn(e,n={}){let t=Je(e,n);return t.manifestVersion===2?Mc(t):t}var Oa,Ra,wa,go,Ca,Ua,ka,xa,ao,va,ja,Fa,Va,Ba,Ha,za,$a,Ga,Ja,Wa,Ka,Xa,Ya,qa,Za,Qa,ec,nc,tc,ic,oc,rc,ae,ti=j(()=>{m();Gt();Se();Ft();qi();$t();Vt();Bt();so();ze();Oa=1,Ra=/^[a-z][a-zA-Z0-9]*(\.[a-zA-Z0-9]+)+$/,wa=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,go=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,Ca=/<\/?[A-Za-z][^>]*>/,Ua=/^(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)/,ka=/^(?:https?|file|ftp|ws|wss):\/\//i,xa=/^\s*(?:javascript|data):/i,ao=/data:[^,\s]*,/i,va=/(?:https?|file|ftp|ws|wss):\/\//i,ja=/javascript:/i,Fa=/(?:^[\s]*|[\s"'(=])(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)(?=[^\s"'<>])[^\s"'<>]*/,Va=["manifestVersion","pluginId","definitionId","version","primitiveSet","activation","schema","layout"],Ba=["manifestVersion","pluginId","definitionId","version","name","description","entry","surfaces","size","stateProjection","actions"],Ha=["_meta","icon","tone","entryHash","runtime","csp","initialState","usage","detailPanel","displayModes","summaryProjection","dataPaths","focusedAiDataPaths"],za=["actionId","capability","mutation","inputSchema","resultProjection","backend"],$a=["confirmation","dataInputs","content","schedule","job","jobAccess","_meta"],Ga=["everyMinutes"],Ja=["timeoutMs"],Wa=["deadlineMs"],Ka=4*1024,Xa=["type","handler"],Ya=["type","command"],qa=["env"],Za=["type","entry"],Qa=["path"],ec=["hash"],nc=/^[0-9a-f]{64}$/,tc=/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/,ic=/[\r\n]/,oc=16,rc=["card-shell","meta-banner","heading","labeled-text","step-flow","text-list"],ae=class e extends Error{constructor(t,i=t,o,r){super(i);this.code=t;this.path=o;this.rule=r;}code;path;rule;name="UiPluginValidationError";withPathPrefix(t){return new e(this.code,this.message,gn(t,this.path),this.rule)}};});function Do(e){return typeof e=="string"&&e.length<=wc&&Rc.test(e)}function F(e,n,t,i,o){throw new be(e,{path:n,rule:t,...i===void 0?{}:{message:i},...o===void 0?{}:{file:o}})}function ie(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 q(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function me(e){let n=`_meta["${ve}"]`;return e===void 0||e===""?n:e.startsWith("[")?`${n}${e}`:`${n}.${e}`}function xc(e){return e.toLowerCase().replace(/_/g,"-")}function vc(e){if(e===void 0||e==="")return "";let n=/^([^.[]+)(.*)$/.exec(e);if(!n)return me(e);let[,t,i]=n;switch(t){case "pluginId":return `name${i}`;case "name":return `display_name${i}`;case "description":return `description${i}`;case "_meta":return `_meta${i}`;case "version":return me("definitionVersion");case "definitionId":return me("definitionId");default:return me(`${t}${i}`)}}function So(e,n,t){return {path:t(e.path),rule:e.rule??xc(e.code),...e.message!==e.code?{message:e.message}:{},file:n}}function Mo(e){return JSON.parse(JSON.stringify(e))}function ri(e,n,t=0,i=new Set){if(typeof e=="string"){e.length>4096&&F("LIMIT_EXCEEDED",n,"string-too-long"),(Cc.test(e)||Uc.test(e)||kc.test(e))&&F("UNSAFE_VALUE",n,"unsafe-value");return}if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){Number.isFinite(e)||F("MANIFEST_INVALID",n,"non-finite-number");return}typeof e!="object"&&F("MANIFEST_INVALID",n,"non-json-value"),t>8&&F("LIMIT_EXCEEDED",n,"too-deep"),i.has(e)&&F("MANIFEST_INVALID",n,"cycle"),i.add(e);try{if(Array.isArray(e)){e.length>128&&F("LIMIT_EXCEEDED",n,"array-too-long"),e.forEach((o,r)=>ri(o,`${n}[${r}]`,t+1,i));return}ie(e)||F("MANIFEST_INVALID",n,"non-plain-object");for(let[o,r]of Object.entries(e))ri(r,n===""?o:`${n}.${o}`,t+1,i);}finally{i.delete(e);}}}function ge(e,n){return (typeof e!="string"||e.length===0)&&F("MANIFEST_INVALID",n,"string"),e}function sn(e,n){return ie(e)||F("MANIFEST_INVALID",n,"object"),e}function jc(e,n){Array.isArray(e)||F("MANIFEST_INVALID",n,"array"),e.forEach((t,i)=>ge(t,`${n}[${i}]`));}function Fc(e,n){typeof e!="boolean"&&F("MANIFEST_INVALID",n,"boolean");}function hn(e,n,t,i){for(let o of Object.keys(e))!t.includes(o)&&!i.includes(o)&&F("MANIFEST_INVALID",`${n}.${o}`,"unknown-key");for(let o of t)q(e,o)||F("MANIFEST_INVALID",`${n}.${o}`,"missing-key");}function Vc(e,n){if(e!=="icon")switch(ri(n,e),e){case "long_description":case "homepage":case "documentation":case "support":case "license":ge(n,e);return;case "author":{let t=sn(n,e);hn(t,e,["name"],["email","url"]);for(let i of Object.keys(t))ge(t[i],`${e}.${i}`);return}case "repository":{let t=sn(n,e);hn(t,e,[],["type","url"]);for(let i of Object.keys(t))ge(t[i],`${e}.${i}`);return}case "icons":{Array.isArray(n)||F("MANIFEST_INVALID",e,"array"),n.forEach((t,i)=>{let o=`${e}[${i}]`,r=sn(t,o);hn(r,o,["src","size"],["theme"]),ge(r.src,`${o}.src`),ge(r.size,`${o}.size`),q(r,"theme")&&ge(r.theme,`${o}.theme`);});return}case "screenshots":case "keywords":case "privacy_policies":jc(n,e);return;case "tools":{Array.isArray(n)||F("MANIFEST_INVALID",e,"array"),n.forEach((t,i)=>{let o=`${e}[${i}]`,r=sn(t,o);hn(r,o,["name"],["description"]),ge(r.name,`${o}.name`),q(r,"description")&&ge(r.description,`${o}.description`);});return}case "prompts":{Array.isArray(n)||F("MANIFEST_INVALID",e,"array"),n.forEach((t,i)=>{let o=`${e}[${i}]`,r=sn(t,o);hn(r,o,["name","text"],["description","arguments"]),ge(r.name,`${o}.name`),ge(r.text,`${o}.text`);});return}case "tools_generated":case "prompts_generated":Fc(n,e);return;case "localization":case "compatibility":case "user_config":sn(n,e);return;default:F("MANIFEST_INVALID",e,"unknown-key");}}function Qn(e){return typeof e=="string"&&Ee.test(e)?e:void 0}function Lo(e){return Number.isSafeInteger(e)&&e>=1?e:void 0}function Bc(e){let n=Qn(e.name);if(n===void 0)return;let t=e._meta,i=ie(t)?t[ve]:void 0,o=ie(i)?i:{},r=q(o,"definitionId")?Qn(o.definitionId):n,s=q(o,"definitionVersion")?Lo(o.definitionVersion):1;return {pluginId:n,...r===void 0?{}:{definitionId:r},...s===void 0?{}:{definitionVersion:s}}}function Hc(e){let n=Qn(e.pluginId);if(n===void 0)return;let t=Qn(e.definitionId),i=Lo(e.version);return {pluginId:n,...t===void 0?{}:{definitionId:t},...i===void 0?{}:{definitionVersion:i}}}function ci(e){try{let n=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e));if(!ie(n))return !1;let t=n._meta;return ie(t)&&q(t,ve)}catch{return false}}function zc(e,n){if(e===de)return n.builtinOnly===true;let t=n._meta,i=ie(t)?t[ve]:void 0;return ie(i)&&i.builtinOnly===true}function $c(e,n){q(e,"server")&&F("MANIFEST_INVALID","server","server-unsupported","phase 1 runs CrewX-owned Apps only");for(let a of Object.keys(e))si.includes(a)||F("MANIFEST_INVALID",a,"unknown-key");for(let a of ai)q(e,a)||F("MANIFEST_INVALID",a,"missing-key");e.manifest_version!==ii&&F("MANIFEST_INVALID","manifest_version","unsupported-version",`manifest_version must be "${ii}"`),Do(e.version)||F("MANIFEST_INVALID","version","semver","version must be a semver.org version such as 0.1.0");let t=e._meta;ie(t)||F("MANIFEST_INVALID","_meta","object"),q(t,ve)||F("MANIFEST_INVALID",me(),"missing-key");let i=t[ve];ie(i)||F("MANIFEST_INVALID",me(),"object");for(let a of Object.keys(i))oi.includes(a)||No.includes(a)||F("MANIFEST_INVALID",me(a),"unknown-key");for(let a of oi)a==="actions"&&n!==void 0||q(i,a)||F("MANIFEST_INVALID",me(a),"missing-key");if(n!==void 0&&q(i,"actions")&&F("MANIFEST_INVALID",me("actions"),"two-truths",`actions are declared in both ${J} and ${H}; a server.ts App keeps them in the tools file only`),Gc(i.actions),q(i,"definitionVersion")){let a=i.definitionVersion;(!Number.isSafeInteger(a)||a<1)&&F("MANIFEST_INVALID",me("definitionVersion"),"positive-integer");}let o={};for(let a of bo)q(e,a)&&(Vc(a,e[a]),o[a]=Mo(e[a]));let r={};for(let[a,c]of Object.entries(t))a!==ve&&(r[a]=c);let s={manifestVersion:2,pluginId:e.name,definitionId:q(i,"definitionId")?i.definitionId:e.name,version:q(i,"definitionVersion")?i.definitionVersion:1,name:e.display_name,description:e.description};for(let[a,c]of Object.entries(i))a==="definitionId"||a==="definitionVersion"||(s[a]=c);return n!==void 0&&(s.actions=n.map(a=>({...a,backend:{type:"skill",entry:Me}}))),Object.keys(r).length>0&&(s._meta=r),{v2Input:s,...Object.keys(r).length>0?{vendorMeta:r}:{},passthrough:o}}function Gc(e){Array.isArray(e)&&e.forEach((n,t)=>{let i=ie(n)?n.backend:void 0;ie(i)&&q(i,"entry")&&F("MANIFEST_INVALID",me(`actions[${t}].backend.entry`),"entry-not-authorable",`an action in ${J} cannot name an entry; a server.ts App declares its actions in ${H}`);});}function Jc(e,n,t){ie(e)||F("MANIFEST_INVALID","","not-object","manifest.json must be a JSON object",J);let i;try{i=$c(e,t);}catch(s){throw s instanceof be?new be(s.code,{...s.reason,file:J}):s}let o;try{let s=Je(i.v2Input,{mode:n.mode??"local"});s.manifestVersion!==2&&F("MANIFEST_INVALID","","v2-required"),o=s;}catch(s){throw s instanceof ae?new be(s.code,So(s,J,vc)):s}let r=e.tools;if(Array.isArray(r)){let s=new Set(o.actions.map(a=>a.actionId));r.forEach((a,c)=>{let d=a.name;if(!s.has(d))throw new be("MANIFEST_INVALID",{path:`tools[${c}].name`,rule:"tool-not-action",message:"every tools[].name must be an action id",file:J})});}return {file:J,manifest:o,v2Input:i.v2Input,releaseVersion:e.version,...Object.keys(i.passthrough).length>0?{mcpb:i.passthrough}:{}}}function Wc(e,n){try{let t=Je(e,{mode:n.mode??"local"});if(t.manifestVersion!==2)throw new be("MANIFEST_INVALID",{path:"manifestVersion",rule:"v2-required",message:"a workspace App requires manifestVersion 2",file:de});return {file:de,manifest:t,v2Input:e}}catch(t){throw t instanceof ae?new be(t.code,So(t,de,i=>i??"")):t}}function an(e){return pe(mn(e).definition)}function To(e){let{entryHash:n,initialState:t,...i}=e,o={...i};return t!==void 0&&(o.initialState={path:t.path}),Mo(o)}function Kc(e,n){let t=To(e),i=To(n);return [...new Set([...Object.keys(t),...Object.keys(i)])].sort().filter(r=>te(t[r]??null)!==te(i[r]??null))}function Xc(e,n){return e.entryHash!==void 0&&n.entryHash!==void 0&&e.entryHash!==n.entryHash||e.initialState?.hash!==void 0&&n.initialState?.hash!==void 0&&e.initialState.hash!==n.initialState.hash}function Yc(e,n){let t=Kc(e,n),i=Xc(e,n),o="";try{let r=an(e),s=an(n);i=i||r!==s,o=` (definition hash ${r.slice(0,12)} vs ${s.slice(0,12)})`;}catch{i=true;}t.length===0&&!i||F("MANIFEST_DUAL_MISMATCH","","dual-manifest-mismatch",`${J} and ${de} normalize to different definitions${o}`+(t.length>0?`; differing fields: ${t.join(", ")}`:""));}function Pe(e,n,t="MANIFEST_INVALID",i){return {code:t,reason:{path:e,rule:n,...i===void 0?{}:{message:i},file:H},files:[]}}function Po(e){return {...Pe("","tools-needs-manifest-json","MANIFEST_INVALID",`${H} is read with ${J} only`),files:e}}function qc(e,n){if(e.byteLength>n)return {failure:Pe("","file-too-large","LIMIT_EXCEEDED")};let t;try{t=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e));}catch{return {failure:Pe("","invalid-json")}}if(!ie(t))return {failure:Pe("","not-object","MANIFEST_INVALID",`${H} must be a JSON object`)};for(let o of Object.keys(t))if(o!=="schemaVersion"&&o!=="actions")return {failure:Pe(o,"unknown-key")};for(let o of ["schemaVersion","actions"])if(!q(t,o))return {failure:Pe(o,"missing-key")};if(t.schemaVersion!==1)return {failure:Pe("schemaVersion","unsupported-version","MANIFEST_INVALID",`schemaVersion must be ${1}`)};let i=t.actions;if(!Array.isArray(i))return {failure:Pe("actions","array")};for(let[o,r]of i.entries()){if(!ie(r))return {failure:Pe(`actions[${o}]`,"object")};if(q(r,"backend"))return {failure:Pe(`actions[${o}].backend`,"tools-backend","MANIFEST_INVALID",`an action in ${H} cannot carry a backend`)}}return {actions:i}}function Zc(e,n){let t=n.maxBytes??262144,i=[],o=new TextDecoder("utf-8",{fatal:true});for(let r of Q){let s=e[r];if(s===void 0)continue;if(s.byteLength>t)return {parsed:i,failure:{code:"LIMIT_EXCEEDED",reason:{path:"",rule:"file-too-large",file:r},files:[r]}};let a;try{a=JSON.parse(o.decode(s));}catch{return {parsed:i,failure:{code:"MANIFEST_INVALID",reason:{path:"",rule:"invalid-json",file:r},files:[r]}}}if(!ie(a))return {parsed:i,failure:{code:"MANIFEST_INVALID",reason:{path:"",rule:"not-object",message:`${r} must be a JSON object`,file:r},files:[r]}};i.push({file:r,raw:a});}return {parsed:i}}function Fe(e,n={}){let{parsed:t,failure:i}=Zc(e,n),o=Q.filter(y=>e[y]!==void 0);if(i!==void 0)return {ok:false,rejection:i,parseFailure:true,builtinOnly:false};let r=e[H],s=r===void 0?void 0:qc(r,n.maxBytes??262144);if(t.length===0)return {ok:false,rejection:s===void 0?{code:"MANIFEST_INVALID",reason:{path:"",rule:"no-manifest-file",message:"neither manifest.json nor ui-plugin.json is present"},files:[]}:Po(o),parseFailure:true,builtinOnly:false};let a=t[0],c=a.file===J?Bc(a.raw):Hc(a.raw),d=t.some(y=>zc(y.file,y.raw)),l;if(s!==void 0){let y=t.some(g=>g.file===J)?s.failure:Po(o);if(y!==void 0)return {ok:false,rejection:y,parseFailure:false,...c===void 0?{}:{identity:c},builtinOnly:d};l=s.actions;}let p=[];try{for(let y of t)p.push(y.file===J?Jc(y.raw,n,l):Wc(y.raw,n));p.length===2&&Yc(p[0].manifest,p[1].manifest);}catch(y){if(y instanceof be)return {ok:false,rejection:{code:y.code,reason:y.reason,files:y.code==="MANIFEST_DUAL_MISMATCH"?[...Q]:y.reason.file===void 0||y.reason.file===H?o:[y.reason.file]},parseFailure:false,...c===void 0?{}:{identity:c},builtinOnly:d};throw y}let u=p[0];return {ok:true,...u,identity:c??{pluginId:u.manifest.pluginId},files:o}}var J,de,Q,ii,ve,si,ai,bo,oi,No,Rc,wc,Cc,Uc,kc,be,et=j(()=>{m();$e();Se();$t();ze();ti();J="manifest.json",de="ui-plugin.json",Q=[J,de],ii="0.3",ve="dev.crewx",si=Object.freeze(["manifest_version","name","display_name","version","description","long_description","author","repository","homepage","documentation","support","icon","icons","screenshots","localization","server","tools","tools_generated","prompts","prompts_generated","keywords","license","privacy_policies","compatibility","user_config","_meta"]),ai=Object.freeze(["manifest_version","name","display_name","version","description","_meta"]),bo=Object.freeze(si.filter(e=>e!=="server"&&!ai.includes(e))),oi=Object.freeze(["entry","surfaces","size","stateProjection","actions"]),No=Object.freeze(["definitionId","definitionVersion","icon","tone","entryHash","runtime","initialState","usage","detailPanel","displayModes","summaryProjection","dataPaths","focusedAiDataPaths","csp"]),Rc=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/,wc=256,Cc=/<\/?[A-Za-z][^>]*>/,Uc=/^\s*javascript:/i,kc=/data:[^,\s]*,/i;be=class extends Error{constructor(t,i){super(`${t}: ${i.path||"<file>"} (${i.rule})`);this.code=t;this.reason=i;}code;reason};});function xo(e){if(e===void 0)return {kind:"none"};if(typeof e!="string")return {kind:"invalid",reason:"bad-path"};if(nd.test(e))return {kind:"url",declared:e};if(!od(e))return {kind:"invalid",reason:"bad-path",declared:e};let n=e.lastIndexOf("."),t=n<0?void 0:Qc.get(e.slice(n+1).toLowerCase());return t===void 0?{kind:"invalid",reason:"bad-type",declared:e}:{kind:"file",path:e,contentType:t}}function od(e){return e.length===0||e.length>512||e.startsWith("/")||e.includes("\\")||e.includes("\0")?false:e.split("/").every(n=>n!==""&&n!=="."&&n!=="..")}async function _n(e,n){let t=xo(e);if(t.kind==="none")return {diagnostics:[]};if(t.kind==="url")return {diagnostics:[{code:"ICON_NOT_FILE",severity:"warning",declared:t.declared}]};if(t.kind==="invalid")return {diagnostics:[di(t.reason,t.declared)]};let i=await n(t.path);if(typeof i=="string")return {diagnostics:[di(i,t.path)]};let o=vo(t.contentType,i);if(!o.ok)return {diagnostics:[di(o.reason,t.path)]};let r={path:t.path,contentType:t.contentType,byteLength:i.byteLength,bytes:i},s=o.square===false?[{code:"ICON_NOT_SQUARE",severity:"warning",declared:t.path}]:[];return {file:r,diagnostics:s}}function di(e,n){return {code:"ICON_INVALID",severity:"error",reason:e,...n===void 0?{}:{declared:n}}}function vo(e,n){if(n.byteLength>262144)return {ok:false,reason:"too-large"};if(e==="image/png")return !Co(n,td)||yd(n,12,16)!=="IHDR"||n.byteLength<24?{ok:false,reason:"bytes-mismatch"}:{ok:true,square:wo(Uo(n,16),Uo(n,20))};if(e==="image/jpeg"){if(!Co(n,id))return {ok:false,reason:"bytes-mismatch"};let t=ud(n);return {ok:true,square:t===void 0?void 0:wo(t.width,t.height)}}return rd(n)}function rd(e){let n;try{n=ed.decode(e);}catch{return {ok:false,reason:"bytes-mismatch"}}return pd(n)?{ok:false,reason:"unsafe-svg"}:sd.test(n)?{ok:true,square:ld(n)}:{ok:false,reason:"bytes-mismatch"}}function pd(e){if(ad.some(n=>n.test(e)))return true;for(let n of e.matchAll(cd))if(!(n[1]??n[2]??n[3]??"").startsWith("#"))return true;for(let n of e.matchAll(dd))if(Oo.lastIndex=n.index??0,!Oo.test(e))return true;return false}function ld(e){let n=/<svg\b[^>]*>/i.exec(e)?.[0];if(n===void 0)return;let t=jo(n,"viewBox");if(t!==void 0){let r=t.trim().split(/[\s,]+/).map(Number);return r.length===4&&r.every(Number.isFinite)?r[2]===r[3]:void 0}let i=Ro(n,"width"),o=Ro(n,"height");return i===void 0||o===void 0?void 0:i===o}function jo(e,n){let t=new RegExp(`\\s${n}\\s*=\\s*(?:"([^"]*)"|'([^']*)')`).exec(e);return t?.[1]??t?.[2]}function Ro(e,n){let t=jo(e,n),i=t===void 0?null:/^\s*(\d+(?:\.\d+)?)(?:px)?\s*$/.exec(t);return i===null?void 0:Number(i[1])}function ud(e){let n=2;for(;n+4<=e.byteLength;){if(e[n]!==255)return;let t=e[n+1];if(t===255){n+=1;continue}if(t===216||t===1||t>=208&&t<=215){n+=2;continue}if(t===217)return;let i=e[n+2]<<8|e[n+3];if(i<2)return;if(fd(t))return n+9>e.byteLength?void 0:{height:ko(e,n+5),width:ko(e,n+7)};n+=2+i;}}function fd(e){return e>=192&&e<=207&&e!==196&&e!==200&&e!==204}function wo(e,n){if(!(e<=0||n<=0))return e===n}function Co(e,n){return e.byteLength>=n.length&&n.every((t,i)=>e[i]===t)}function yd(e,n,t){return String.fromCharCode(...e.subarray(n,t))}function Uo(e,n){return (e[n]<<24|e[n+1]<<16|e[n+2]<<8|e[n+3])>>>0}function ko(e,n){return e[n]<<8|e[n+1]}var Qc,ed,nd,td,id,sd,ad,cd,dd,Oo,pi=j(()=>{m();Qc=new Map([["svg","image/svg+xml"],["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"]]),ed=new TextDecoder("utf-8",{fatal:true}),nd=/^[A-Za-z][A-Za-z0-9+.-]*:/,td=[137,80,78,71,13,10,26,10],id=[255,216,255];sd=/^\s*(?:<\?[\s\S]*?\?>\s*|<!--[\s\S]*?-->\s*)*<svg(?=[\s/>])/,ad=[/<script/i,/[\s"'/]on[a-z]+\s*=/i,/<foreignobject/i,/<!doctype/i,/<!entity/i,/<(?:iframe|embed|object)\b/i,/@import/i],cd=/(?:^|[\s"'/])(?:xlink:)?href\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+))/gi,dd=/url\(/gi,Oo=/url\(\s*["']?#/iy;});var li=j(()=>{m();$i();et();pi();ti();ze();});function S(e,n=e){throw new Ne(e,n)}var Ne,tt=j(()=>{m();Ne=class extends Error{constructor(t,i=t){super(i);this.code=t;}code;name="McpAppContractError"};});var Yo=j(()=>{m();});var qo=j(()=>{m();$e();Se();tt();Yo();});function Qo(e,n){return Zo.add(e),n!==void 0&&Dd.set(e,n),e}function cn(e){return e!==null&&typeof e=="object"&&Zo.has(e)}var Zo,Dd,it=j(()=>{m();Zo=new WeakSet,Dd=new WeakMap;});function bn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function fi(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 tr(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let n of Object.values(e))tr(n);return Object.freeze(e)}function oe(e){throw new De("LINEAGE_INVALID",e)}function Cd(e){throw new De("LINEAGE_STALE",e)}function ir(e){if(!bn(e)||!fi(e,Ld,Od)||!bn(e.actions))return oe("Lineage definition shape is invalid");for(let n of Object.values(e.actions))if(!bn(n)||!fi(n,Rd,wd))return oe("Lineage action definition shape is invalid");return e}function Ud(e){if(!bn(e)||!fi(e,Sd,Md))return oe("Lineage entry shape is invalid");if(!Number.isSafeInteger(e.version)||e.version<1||typeof e.hash!="string"||!er.test(e.hash))return oe("Lineage entry identity is invalid");if(e.sourceHash!==void 0&&(typeof e.sourceHash!="string"||!er.test(e.sourceHash)))return oe("Lineage source hash is invalid");if(e.compat!==void 0&&e.compat!=="break")return oe("Lineage compatibility marker is invalid");let n=ir(e.definition);if(n.version!==e.version)return oe("Lineage version does not match its definition");if(e.sourceHash!==void 0&&n.sourceHash!==e.sourceHash)return oe("Lineage source hash does not match its definition");let t;try{t=pe(n),ye({...n,hash:e.hash});}catch{return oe("Lineage definition is invalid")}return t!==e.hash?oe("Lineage definition hash does not match"):tr({version:e.version,hash:e.hash,definition:n,...e.sourceHash===void 0?{}:{sourceHash:e.sourceHash},...e.compat===void 0?{}:{compat:e.compat}})}function nr(e){return e.stateProjection?.allow??[]}function kd(e,n){let t=[],i=new Set(nr(n));nr(e).some(a=>!i.has(a))&&t.push("S1_STATE_PROJECTION");let o=new Set(n.dataPaths??[]);(e.dataPaths??[]).some(a=>!o.has(a))&&t.push("S2_DATA_PATHS");for(let[a,c]of Object.entries(e.actions)){let d=n.actions[a];if(d&&(c.confirmation??"native")==="native"&&(d.confirmation??"native")!=="native"){t.push("S3_ACTION_CONFIRMATION");break}}Object.keys(e.legacy?.agentAccess??{}).some(a=>!Object.hasOwn(n.actions,a))&&t.push("S4_LEGACY_AGENT_ACTIONS");let s=e.summaryProjection?.allow;if(s!==void 0){let a=new Set(n.summaryProjection?.allow??[]);s.some(c=>!a.has(c))&&t.push("S5_SUMMARY_PROJECTION");}return t}function xd(e,n){return te(e)===te(n)}function yi(e,n){if(!Array.isArray(e)||e.length===0)return oe("Definition lineage is missing");if(!bn(n)||typeof n.hash!="string")return oe("Current definition is invalid");let t,i;try{let{hash:a,...c}=n;i=ir(c),t={...i,hash:a},ye(t);}catch{return oe("Current definition is invalid")}let o=e.map(Ud),r=o[0].definition.id;if(o.some(a=>a.definition.id!==r))return oe("Lineage definition ids do not match");if(o.some((a,c)=>c>0&&a.version<=o[c-1].version))return oe("Lineage generations are not in increasing version order");if(o.some((a,c)=>o.findIndex(d=>d.hash===a.hash)!==c))return oe("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||!xd(s.definition,i))return Cd("The last lineage generation does not match the current package");if(t.legacy!==void 0){let a=new Set(Object.keys(t.actions)),c=new Set;for(let l of o)if(l.sourceHash===void 0)for(let p of Object.keys(l.definition.actions))a.has(p)&&c.add(p);let d=Object.keys(t.legacy.agentAccess??{});if(d.length!==c.size||d.some(l=>!c.has(l))){let l="S4_LEGACY_AGENT_ACCESS_COMPLETE";throw new De("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 d=kd(o[a].definition,t);if(d.length>0)throw new De("LINEAGE_INVALID",`Lineage compatibility failed: ${d.join(", ")}`,d)}return Object.freeze({entries:Object.freeze(o),current:t})}var De,er,Sd,Md,Ld,Od,Rd,wd,Ai=j(()=>{m();$e();Se();De=class extends Error{constructor(t,i=t,o=[]){super(i);this.code=t;this.violations=o;}code;violations;name="UiDefinitionLineageError"},er=/^[0-9a-f]{64}$/,Sd=["version","hash","definition"],Md=["sourceHash","compat"],Ld=["id","version","actions"],Od=["sourceHash","usage","detailPanel","displayModes","renderer","surfaces","stateProjection","dataPaths","summaryProjection","legacy"],Rd=["capabilities"],wd=["inputKeys","dataInputs","confirmation","resultProjection","content","env","schedule","job","jobAccess"];});var or,rr,sr,ar,cr=j(()=>{m();or="text/html;profile=mcp-app",rr=["crewx_app_terminal_connect","crewx_app_html_viewer_open"],sr=["crewx_listWorkspaces","crewx_queryAgent","crewx_executeAgent","crewx_getTaskResult","crewx_listTasks","crewx_listAgents","callBrowser","openTab","listTabs","closeTab"],ar="text/html";});function Nn(e){return typeof e=="string"&&vd.includes(e)}function ot(e,n){return e==="card"&&n?.type==="core"&&Nn(n.handler)}var vd,rt=j(()=>{m();vd=Object.freeze(["card.secret-env"]);});function dr(e,n=[],t){if(e.content!==void 0||e.confirmation!=="none")return "denied";let i=jd();return i&&Object.hasOwn(i,e.actionId)?i[e.actionId]:e.backend?.type==="core"&&e.backend.handler.startsWith("host.")?"denied":e.backend?.type==="core"&&e.backend.handler==="state.set"?"allowed":e.backend?.type==="core"&&Nn(e.backend.handler)||e.backend?.type==="skill"?"approval_required":e.backend===void 0&&n.includes(e.actionId)?"allowed":"denied"}function jd(e){return;}var pr=j(()=>{m();$e();it();rt();});function Wd(e){return Mn.has(e)&&(e.initialState===void 0||Mn.has(e.initialState))}function Ar(e,n,t,i){let o=i===void 0?void 0:Object.freeze({hash:i.hash,bytes:Object.freeze(i.bytes)}),r=Object.freeze({mimeType:ar,entryHash:e,html:n,bytes:Object.freeze(t),...o===void 0?{}:{initialState:o}});return o!==void 0&&Mn.add(o),Mn.add(r),r}function Kd(e){let n=[];return e?.terminal===true&&n.push({name:"crewx_app_terminal_connect",description:"Open a local-only terminal session for this App.",inputSchema:{type:"object",properties:{workspace:{type:"string"},threadId:{type:"string"},instanceId:{type:"string"}},required:["threadId","instanceId"],additionalProperties:false},textFallback:"A local terminal connection is ready for this App.",visibility:Object.freeze(["app"]),kind:"host",resourceBinding:Ve}),e?.htmlDocuments===true&&n.push({name:"crewx_app_html_viewer_open",description:"List workspace HTML documents or open one through a short-lived Host capability.",inputSchema:{type:"object",properties:{workspace:{type:"string"},threadId:{type:"string"},instanceId:{type:"string"},operation:{type:"string",enum:["list","open"]},documentId:{type:"string"}},required:["threadId","instanceId","operation"],additionalProperties:false},textFallback:"Workspace HTML documents are available through this App.",visibility:Object.freeze(["app"]),kind:"host",resourceBinding:Ve}),n}function Be(e,n,t){return (typeof e!="string"||!fr.test(e))&&S(n,`${t} must be a safe identifier`),e}function Dn(e,n,t){let i=e??t;return (typeof i!="string"||i.trim().length===0||i.length>Bd)&&S("TOOL_INVALID",`${n} must be a meaningful description`),i}function gi(e){return (typeof e!="string"||e.length===0||e.length>dn||!/<html(?:\s|>)/i.test(e)||!/<\/html\s*>/i.test(e))&&S("HTML_INVALID","MCP App HTML must be a non-empty HTML document"),e}function Sn(e,n=0){try{let t=fe(e,n);return t.type!==void 0&&t.type!=="object"&&S("TOOL_INVALID","MCP App inputSchema must describe an object"),t}catch(t){if(t instanceof Ne)throw t;S("TOOL_INVALID","MCP App inputSchema must be projection-safe JSON");}}function Xd(e){return (typeof e!="string"||e.trim().length===0||e.length>Hd)&&S("TOOL_INVALID","MCP App tools require a meaningful text fallback"),e}function Yd(e){e===void 0&&S("TOOL_INVALID","MCP App tool visibility is required");let n=[...e];return (n.length===0||n.some(t=>t!=="model"&&t!=="app")||new Set(n).size!==n.length)&&S("TOOL_INVALID","MCP App tool visibility must contain model and/or app once"),n}function gr(e){return (typeof e!="string"||!yr.test(e))&&S("RESOURCE_URI_INVALID","MCP App resource URI is not a registered ui:// URI"),e}function mr(e){let n=Be(e.appId,"APP_ID_INVALID","Local App id"),t=Dn(e.name,"Local App name",n),i=Dn(e.description,"Local App description",`${t} interactive view`),o=dt(e.definition),r=gi(e.html),s=st(e.entryHash,"Local App entry hash"),a=e.entryBytes===void 0?Array.from(new TextEncoder().encode(r)):ct(e.entryBytes,"Local App entry bytes");(at(a)!==s||Er(a)!==r)&&S("HTML_INVALID","Local App entry bytes do not match the HTML hash");let c=qd(e),d=[];Array.isArray(e.actions)||S("TOOL_INVALID","Local App actions must be an array");for(let b of e.actions){let w=Be(b.actionId,"TOOL_ID_INVALID","Local App action id");(d.includes(w)||!Object.prototype.hasOwnProperty.call(o.actions,w))&&S("TOOL_INVALID",`Local App action is not declared by the UI definition: ${w}`),d.push(w);}let l=Be(e.readToolName,"TOOL_ID_INVALID","Local App read tool name"),p=e.actionToolName===void 0?void 0:Be(e.actionToolName,"TOOL_ID_INVALID","Local App action tool name");d.length===0&&p!==void 0&&S("TOOL_INVALID","A static local App cannot register an action tool"),d.length>0&&p===void 0&&S("TOOL_INVALID","A stateful local App requires an action tool name"),p!==void 0&&p===l&&S("TOOL_ID_CONFLICT",`Local App read and action tools share a name: ${l}`);let u=Kd(e.runtime);u.some(b=>b.name===l||b.name===p)&&S("TOOL_ID_CONFLICT","Local App read or action tool conflicts with a requested Host capability");let y={name:l,description:`${t} current state`,inputSchema:Jd,textFallback:`${t} current state is available through its open instance.`,visibility:Object.freeze(["model","app"]),kind:"read",resourceBinding:Ve},g=[Object.freeze(y)];if(g.push(...u.map(b=>Object.freeze(b))),p!==void 0){let b={name:p,description:`${t} actions`,inputSchema:mi(e.actions),textFallback:`${t} action requests are handled by the open App instance.`,visibility:Object.freeze(["app"]),kind:"action",resourceBinding:Ve,actionIds:Object.freeze([...d])};g.push(Object.freeze(b));}let _=[],T=new Set(g.map(b=>b.name));if(p!==void 0)for(let b of e.actions){let w=`${p}__${b.actionId}`;if(w.length>128||!fr.test(w)){_.push(Object.freeze({toolName:w,actionId:b.actionId,reason:"name_too_long"}));continue}if(T.has(w)){_.push(Object.freeze({toolName:w,actionId:b.actionId,reason:"name_collision"}));continue}let V=dr({actionId:b.actionId,confirmation:o.actions[b.actionId]?.confirmation,content:o.actions[b.actionId]?.content,backend:b.backend},e.modelActions),N=Object.freeze([...tp(V,o.usage,b.backend)]),D={name:w,description:`${w} action`,inputSchema:Sn(b.inputSchema),textFallback:`${w} action requests are handled by the open App instance.`,visibility:N,kind:"action",resourceBinding:Ve,actionId:b.actionId,actionIds:Object.freeze([b.actionId]),_meta:Object.freeze({ui:Object.freeze({visibility:N})})};g.push(Object.freeze(D)),T.add(w);}let U=Ar(s,r,a,c===void 0?void 0:{hash:c.hash,bytes:[...c.bytes]}),x={appId:n,name:t,description:i,...e.icon===void 0?{}:{icon:Tr(e.icon)},...e.tone===void 0?{}:{tone:Pr(e.tone)},builtinOnly:false,definition:o,...e.runtime===void 0?{}:{runtime:Object.freeze({...e.runtime})},resourceBinding:Ve,resource:U,tools:Object.freeze(g),toolDiagnostics:Object.freeze(_)};return ee(x)}function hr(e={}){return new Ii(e)}function mi(e){if(e.length===0)return Sn({type:"object",properties:{},additionalProperties:false});let n=e.map(i=>i.actionId),t=new Map;for(let i of e)t.set(i.actionId,Sn(i.inputSchema));return Sn(Zd(n,t),Ir)}function qd(e){let n=e.definition.dataPaths??[];if(e.initialStateBytes===void 0){e.initialStateHash!==void 0&&S("STATE_INVALID","Initial state hash has no bytes"),e.initialState!==void 0&&fe(e.initialState,0,n);return}e.initialStateHash===void 0&&S("STATE_INVALID","Initial state bytes require a hash");let t=st(e.initialStateHash,"Initial state hash"),i=ct(e.initialStateBytes,"Initial state bytes");at(i)!==t&&S("STATE_INVALID","Initial state bytes do not match the hash");let o;try{let r=new TextDecoder("utf-8",{fatal:!0}).decode(Uint8Array.from(i));o=fe(JSON.parse(r),0,n);}catch{S("STATE_INVALID","Initial state bytes are not projection-safe JSON");}return e.initialState!==void 0&&te(o)!==te(fe(e.initialState,0,n))&&S("STATE_INVALID","Initial state bytes do not match the state value"),{hash:t,bytes:Object.freeze([...i])}}function Zd(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})}function Qd(e){let n=Ln(e),t=Be(n.appId,"APP_ID_INVALID","MCP App id"),i=gi(n.html);gr(n.uiUri);let o=n.definition===void 0?void 0:dt(n.definition),r=e.provenance;r!==void 0&&(!cn(r)||r.appId!==t||r.definitionId!==o?.id||r.version!==o?.version||r.definitionHash!==o?.hash)&&S("TOOL_INVALID","Product App built-in registration provenance is not verified");let s=Object.freeze(n.tools.map(d=>ee(Ln(d)))),a=ee({...n,appId:t,html:i,...o===void 0?{}:{definition:o},...r===void 0?{}:{provenance:r},tools:s}),c=ee({uri:a.uiUri,mimeType:or,text:i,...a.csp===void 0?{}:{_meta:{ui:{csp:a.csp}}}});return ee({appId:t,name:a.name,description:a.description,...a.icon===void 0?{}:{icon:a.icon},...a.tone===void 0?{}:{tone:a.tone},builtinOnly:a.builtinOnly,uiUri:a.uiUri,...o===void 0?{}:{definition:o},resourceBinding:Object.freeze({kind:"mcp",uri:a.uiUri}),resource:c,tools:s,descriptor:a})}function ep(e){(e.resourceBinding.kind!=="instance"||e.builtinOnly!==false)&&S("STATE_INVALID","Local App registration binding is invalid"),Object.prototype.hasOwnProperty.call(e,"uiUri")&&S("STATE_INVALID","Local App registration cannot contain uiUri");let n=Be(e.appId,"APP_ID_INVALID","Local App id"),t=dt(e.definition),i=e.provenance;i!==void 0&&(!cn(i)||i.appId!==n||i.definitionId!==t.id||i.version!==t.version||i.definitionHash!==t.hash)&&S("TOOL_INVALID","Product App local registration provenance is not verified");let o=np(e.resource),r=e.tools.map(a=>{Be(a.name,"TOOL_ID_INVALID","Local App tool name"),Dn(a.description,"Local App tool description","Local App tool"),Xd(a.textFallback);let c=Sn(a.inputSchema,a.kind==="action"&&!("actionId"in a)?Ir:0);if((a.resourceBinding.kind!=="instance"||Object.prototype.hasOwnProperty.call(a,"resourceUri"))&&S("TOOL_INVALID","Local App tools cannot carry an MCP resource URI"),a.kind==="host")return (!Gd.has(a.name)||a.visibility.length!==1||a.visibility[0]!=="app"||Object.prototype.hasOwnProperty.call(a,"actionId"))&&S("TOOL_INVALID","Local App Host tools must use an allow-listed name and app-only visibility"),ee({...a,inputSchema:c,visibility:Object.freeze(["app"])});if(a.kind==="action"){if("actionId"in a){let l=Be(a.actionId,"TOOL_ID_INVALID","Local App action id");Object.prototype.hasOwnProperty.call(t.actions,l)||S("TOOL_INVALID","Local App action tool references an undeclared action");let p=Yd(a._meta.ui.visibility);return JSON.stringify(p)!==JSON.stringify(a.visibility)&&S("TOOL_INVALID","Local App action metadata visibility must match the tool visibility"),ee({...a,actionId:l,actionIds:Object.freeze([l]),inputSchema:c,visibility:p,_meta:{ui:{visibility:p}}})}let d=[...a.actionIds];return (d.length===0||d.some(l=>!Object.prototype.hasOwnProperty.call(t.actions,l)))&&S("TOOL_INVALID","Local App action tool references an undeclared action"),ee({...a,inputSchema:c,actionIds:Object.freeze(d)})}return ee({...a,inputSchema:c})}),s=ee({appId:n,name:Dn(e.name,"Local App name",e.appId),description:Dn(e.description,"Local App description",e.name),...e.icon===void 0?{}:{icon:Tr(e.icon)},...e.tone===void 0?{}:{tone:Pr(e.tone)},builtinOnly:false,definition:t,...e.runtime===void 0?{}:{runtime:Object.freeze({...e.runtime})},...i===void 0?{}:{provenance:i},resourceBinding:Ve,resource:o,tools:Object.freeze(r),toolDiagnostics:Object.freeze([...e.toolDiagnostics??[]])});return lr.has(e)?e:(lr.add(s),s)}function np(e){let n=gi(e.html),t=st(e.entryHash,"Local App entry hash");if(Wd(e))return e;let i=ct(e.bytes,"Local App entry bytes");(at(i)!==t||Er(i)!==n)&&S("HTML_INVALID","Local App entry bytes do not match the HTML hash");let o=e.initialState===void 0?void 0:{hash:st(e.initialState.hash,"Initial state hash"),bytes:ct(e.initialState.bytes,"Initial state bytes")};return o&&at(o.bytes)!==o.hash&&S("STATE_INVALID","Initial state bytes do not match the hash"),Ar(t,n,i,o)}function tp(e,n,t){if(ot(n,t))return ["model"];let i=t?.type==="core"&&Nn(t.handler);return e==="denied"||i?["app"]:["model","app"]}function ip(e){return ee({appId:e.appId,name:e.name,description:e.description,...e.icon===void 0?{}:{icon:e.icon},...e.tone===void 0?{}:{tone:e.tone},builtinOnly:false,definition:_r(e.definition),...e.provenance===void 0?{}:{provenance:e.provenance},entryHash:e.resource.entryHash,resourceBinding:Ve,tools:e.tools})}function op(e){return ee({appId:e.appId,name:e.name,description:e.description,...e.icon===void 0?{}:{icon:e.icon},...e.tone===void 0?{}:{tone:e.tone},builtinOnly:e.builtinOnly,uiUri:e.uiUri,...e.definition===void 0?{}:{definition:_r(e.definition)},resourceBinding:Object.freeze({kind:"mcp",uri:e.uiUri}),tools:e.tools})}function dt(e){try{if(Object.isFrozen(e))return ye(e),ee(e);let n=Ln(e);return ye(n),ee(n)}catch(n){if(n instanceof Ne)throw n;S("STATE_INVALID","UI definition is not a valid immutable definition");}}function _r(e){return ee({id:e.id,version:e.version,hash:e.hash})}function rp(e){return e!==null&&typeof e=="object"&&typeof e.id=="string"&&Number.isSafeInteger(e.version)&&typeof e.hash=="string"}function ur(e,n,t){return `${e}\0${n}\0${t}`}function st(e,n){return (typeof e!="string"||!Vd.test(e))&&S("SERIALIZATION_INVALID",`${n} is invalid`),e}function at(e){return Vi.createHash("sha256").update(Uint8Array.from(e)).digest("hex")}function ct(e,n){return (!Array.isArray(e)||e.some(t=>!Number.isInteger(t)||t<0||t>255))&&S("SERIALIZATION_INVALID",`${n} is invalid`),[...e]}function Er(e){try{return new TextDecoder("utf-8",{fatal:!0}).decode(Uint8Array.from(e))}catch{S("SERIALIZATION_INVALID","UTF-8 bytes are invalid");}}function Tr(e){return (typeof e!="string"||!zd.test(e))&&S("TOOL_INVALID","MCP App icon is invalid"),e}function Pr(e){return (typeof e!="string"||!$d.has(e))&&S("TOOL_INVALID","MCP App tone is invalid"),e}function Ln(e,n=new Map){if(e===null||typeof e!="object")return e;let t=e;if(n.has(t)&&S("SERIALIZATION_INVALID","MCP App value contains a cycle"),Array.isArray(e)){let r=[];n.set(t,r);for(let s of e)r.push(Ln(s,n));return n.delete(t),r}let i;try{i=Object.getPrototypeOf(e);}catch{S("SERIALIZATION_INVALID","MCP App value cannot be cloned");}i!==Object.prototype&&i!==null&&S("SERIALIZATION_INVALID","MCP App value must be plain JSON");let o={};n.set(t,o);for(let[r,s]of Object.entries(e))Object.defineProperty(o,r,{configurable:true,enumerable:true,value:Ln(s,n),writable:true});return n.delete(t),o}function ee(e,n=new Set){if(e===null||typeof e!="object"||n.has(e)||Mn.has(e))return e;n.add(e);for(let t of Object.values(e))ee(t,n);return Object.freeze(e),e}var fr,yr,Vd,dn,Bd,Hd,zd,$d,Gd,Ve,Jd,Mn,lr,Ir,Ii,pt=j(()=>{m();qo();$e();Se();it();tt();Ai();cr();pr();rt();fr=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,yr=/^ui:\/\/crewx\/([A-Za-z][A-Za-z0-9._-]{0,127})\/([0-9a-f]{12})$/,Vd=/^[0-9a-f]{64}$/,dn=8*1024*1024,Bd=8*1024,Hd=16*1024,zd=/^[a-z][a-z0-9-]{0,63}$/,$d=new Set(["blue","violet","emerald","amber","rose","sky","slate","indigo"]),Gd=new Set(rr),new Set(sr),Ve=Object.freeze({kind:"instance"}),Jd=Object.freeze({type:"object",properties:Object.freeze({}),additionalProperties:false}),Mn=new WeakSet,lr=new WeakSet;Ir=4;Ii=class{builtinApps;localApps;builtinDescriptors;builtinTools;mcpResources=new Map;localById=new Map;registrationById=new Map;launcherById=new Map;definitionByKey=new Map;handlerByKey=new Map;mcpToolByName=new Map;localToolByName=new Map;constructor(n){let t=n.builtins??n.builtin,i=[],o=[],r=[],s=new Set,a=new Set;for(let p of t?.listMcpApps()??[]){let u=Qd(p);s.has(u.appId)&&S("APP_ID_CONFLICT",`MCP App id is already registered: ${u.appId}`),s.add(u.appId);let y=u.tools;for(let g of y)a.has(g.name)&&S("TOOL_ID_CONFLICT",`MCP App tool name is already registered: ${g.name}`),a.add(g.name),this.mcpToolByName.set(g.name,g),r.push(g);this.mcpResources.set(u.resource.uri,u.resource),i.push(u),o.push(u.descriptor);}let c=(n.localApps??n.locals??[]).map(ep),d=new Set(c.flatMap(p=>p.tools.filter(u=>!(u.kind==="action"&&"actionId"in u)).map(u=>u.name))),l=[];for(let p of c){let u=p;s.has(u.appId)&&S("APP_ID_CONFLICT",`MCP App id is already registered: ${u.appId}`),s.add(u.appId);let y=[],g=[...u.toolDiagnostics??[]];for(let _ of u.tools){if(a.has(_.name)){if(_.kind==="host"&&this.localToolByName.get(_.name)?.kind==="host"){y.push(_);continue}if(_.kind==="action"&&"actionId"in _){g.push(Object.freeze({toolName:_.name,actionId:_.actionId,reason:"name_collision"}));continue}S("TOOL_ID_CONFLICT",`MCP App tool name is already registered: ${_.name}`);}if(_.kind==="action"&&"actionId"in _&&d.has(_.name)){g.push(Object.freeze({toolName:_.name,actionId:_.actionId,reason:"name_collision"}));continue}a.add(_.name),this.localToolByName.set(_.name,_),y.push(_);}(y.length!==u.tools.length||g.length!==(u.toolDiagnostics?.length??0))&&(u=ee({...u,tools:Object.freeze(y),toolDiagnostics:Object.freeze(g)})),l.push(u),this.localById.set(u.appId,u);}for(let p of i)this.registrationById.set(p.appId,p),this.launcherById.set(p.appId,op(p)),p.definition&&this.addDefinition(p.definition);for(let p of l)this.registrationById.set(p.appId,p),this.launcherById.set(p.appId,ip(p)),this.addDefinition(p.definition);for(let p of n.definitions??[])this.addDefinition(p);for(let p of n.handlers??[])this.addHandler(p);this.builtinApps=Object.freeze(i),this.localApps=Object.freeze(l),this.builtinDescriptors=Object.freeze(o),this.builtinTools=Object.freeze(r);}getMcpApp(n){return this.builtinApps.find(t=>t.appId===n)?.descriptor??null}listMcpApps(){return this.builtinDescriptors}listMcpAppTools(){return this.builtinTools}resolveMcpAppTool(n){return this.mcpToolByName.get(n)??null}resolveMcpAppResource(n){return typeof n!="string"||!yr.test(n)?null:this.mcpResources.get(n)??null}requireMcpAppResource(n){gr(n);let t=this.mcpResources.get(n);return t||S("RESOURCE_NOT_FOUND",`MCP App resource is not registered: ${n}`),t}listLocalMcpApps(){return this.localApps}getLocalMcpApp(n){return this.localById.get(n)??null}listLocalMcpAppTools(){return Object.freeze([...this.localToolByName.values()])}resolveLocalMcpAppTool(n){return this.localToolByName.get(n)??null}resolveLocalMcpAppResource(n,t){let i=this.localById.get(n);return !i||t!==void 0&&i.definition.hash!==t?null:i.resource}listRegistrations(){return Object.freeze([...this.builtinApps,...this.localApps])}getRegistration(n){return this.registrationById.get(n)??null}listLaunchers(){return Object.freeze([...this.launcherById.values()].filter(n=>{let t=this.registrationById.get(n.appId),i=t?"descriptor"in t?t.descriptor.provenance:t.provenance:void 0,o=cn(i)&&i.launcher===false;return t?.definition?.usage!=="card"&&!o}))}listCardApps(){return Object.freeze([...this.launcherById.values()].filter(n=>this.registrationById.get(n.appId)?.definition?.usage==="card"))}getLauncher(n){return this.launcherById.get(n)??null}resolveDefinition(n){if(!rp(n))return null;let t=this.definitionByKey.get(zt(n));if(!t||t.hash!==n.hash)return null;try{return pe(t)===t.hash?t:null}catch{return null}}resolveActionHandler(n,t,i){return typeof n!="string"||typeof i!="string"||!Number.isSafeInteger(t)?null:this.handlerByKey.get(ur(n,t,i))??null}addDefinition(n){let t=dt(n),i=zt(t),o=this.definitionByKey.get(i);o&&o.hash!==t.hash&&S("STATE_INVALID",`UI definition generation conflicts: ${i}`),o||this.definitionByKey.set(i,t);}addHandler(n){(!n||typeof n.definitionId!="string"||typeof n.actionId!="string"||!Number.isSafeInteger(n.version)||n.version<1||typeof n.handle!="function")&&S("STATE_INVALID","UI action handler registration is invalid");let t=ur(n.definitionId,n.version,n.actionId);this.handlerByKey.has(t)&&S("TOOL_INVALID",`Duplicate UI action handler registration: ${t}`),this.handlerByKey.set(t,Object.freeze({...n}));}};});function sp(e){let n=mr({appId:e.appId,name:e.name,description:e.description,...e.icon===void 0?{}:{icon:e.icon},...e.tone===void 0?{}:{tone:e.tone},...e.normalized.manifest.runtime===void 0?{}:{runtime:e.normalized.manifest.runtime},definition:e.definition,html:e.html,entryHash:e.entryHash,entryBytes:e.entryBytes,initialState:e.initialState,...e.initialStateHash===void 0?{}:{initialStateHash:e.initialStateHash},...e.initialStateBytes===void 0?{}:{initialStateBytes:e.initialStateBytes},readToolName:e.toolNames.read,...e.toolNames.action===void 0?{}:{actionToolName:e.toolNames.action},actions:e.normalized.manifest.actions.map(i=>({actionId:i.actionId,inputSchema:i.inputSchema,backend:i.backend}))});return e.provenance===void 0?n:Object.freeze({...n,provenance:e.provenance})}function br(e){let n=e.normalized.manifest.actions;if(n.some(i=>i.backend.type==="skill")&&n.some(i=>i.backend.type==="core"))throw new Error("Mixed workspace App execution models");let t=sp(e);hr({localApps:[t],definitions:[e.definition]});}var Nr=j(()=>{m();pt();});function ap(e){if(e===null||typeof e!="object"||!(Dr in e))throw new TypeError("scanCache must be created by createWorkspaceAppScanCache");return e[Dr]}function Sr(e,n){let t=ap(e),i=t.rootIdentity;return i!==void 0&&(i.dev!==n.dev||i.ino!==n.ino||i.realPath!==n.realPath)&&(t.candidates.clear(),t.assetCatalogs.clear(),t.preparedCandidates.clear(),t.lastCandidateScanUnchanged=void 0,t.lastCandidateKeys=void 0,t.scanStartedAtNs=void 0,t.lastAssetCatalogsUnchanged=void 0,t.lastSnapshot=void 0,t.lastSnapshotBuildInputs=void 0,t.lastSnapshotCandidates=void 0,t.lastSnapshotCatalogFingerprint=void 0),t.rootIdentity=n,t}var Dr,Mr=j(()=>{m();Dr=Symbol("crewx.workspace-app-scan-cache.state");});function le(e){let n=typeof e=="object"&&e!==null&&"code"in e?String(e.code):"";return n==="ENOENT"?new M("NOT_FOUND"):n==="ELOOP"?new M("PATH_ESCAPED"):n==="EFBIG"||n==="EOVERFLOW"?new M("LIMIT_EXCEEDED"):n==="EACCES"||n==="EPERM"||n==="ENOTDIR"?new M("READ_DENIED"):new M("READ_DENIED")}function lp(e){if(typeof e!="string"||e.length===0||!ce.isAbsolute(e))throw new M("READ_DENIED")}function hi(e){if(typeof e!="string"||ce.isAbsolute(e)||/[\\\u0000]/.test(e))throw new M("PATH_ESCAPED");if(e==="")return [];let n=e.split("/");if(n.some(t=>t.length===0||t==="."||t===".."))throw new M("PATH_ESCAPED");return n}function yt(e,n){let t=ce.relative(e,n);return t===""||t!==".."&&!t.startsWith(`..${ce.sep}`)&&!ce.isAbsolute(t)}function ln(e){return {dev:e.dev,ino:e.ino,size:e.size,mtimeNs:e.mtimeNs,ctimeNs:e.ctimeNs}}function Pi(e,n){return e.dev===n.dev&&e.ino===n.ino}function bi(e,n){return Pi(e,n)&&e.size===n.size&&e.mtimeNs===n.mtimeNs&&e.ctimeNs===n.ctimeNs}async function lt(e){lp(e);let n,t;try{n=await promises.realpath(e),t=await promises.stat(n,{bigint:!0});}catch(i){throw le(i)}if(!t.isDirectory())throw new M("READ_DENIED");return {realRoot:n,identity:ln(t)}}async function Rr(e,n,t){if(t.length<2||t[0]!=="apps"&&t[0]!=="skills")return;let i,o;try{if(i=ce.resolve(e,t[0],t[1]),o=await promises.realpath(i),!(await promises.stat(o,{bigint:!0})).isDirectory())throw new M("READ_DENIED")}catch(r){throw r instanceof M?r:le(r)}if(!yt(n,o))throw new M("PATH_ESCAPED");return o}async function ut(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 le(a)}if(!yt(n,r)||t!==void 0&&!yt(t,r))throw new M("PATH_ESCAPED");if(!o.isFile()||!s.isFile())throw new M("READ_DENIED");if(!Pi(i,o)||!Pi(i,s)||i.dev!==s.dev)throw new M("PATH_ESCAPED")}async function pn(e,n){let t,i;try{t=await promises.realpath(e),i=await promises.stat(t,{bigint:!0});}catch{throw new M("PATH_ESCAPED")}if(t!==n.realRoot||!bi(n.identity,ln(i)))throw new M("PATH_ESCAPED")}function up(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 M,Ti,pp,Or,At,wr,Di=j(()=>{m();M=class extends Error{constructor(t){super(t);this.code=t;}code;name="AppDiscoveryFsError"},Ti=ne.constants.O_NOFOLLOW,pp=ne.constants.O_NONBLOCK,Or=ne.constants.O_RDONLY|(Ti??0)|(pp??0);At=class{async getRootIdentity(n){let t=await lt(n);return await pn(n,t),{dev:t.identity.dev,ino:t.identity.ino,realPath:t.realRoot}}async listDirectory(n,t){let i=hi(t),o=await lt(n),r=ce.resolve(n,...i),s,a;try{s=await promises.realpath(r),a=await promises.stat(s,{bigint:!0});}catch(c){let d=le(c);if(d.code==="NOT_FOUND")return [];throw d}if(!yt(o.realRoot,s)||!a.isDirectory())throw new M("PATH_ESCAPED");try{let c=await promises.readdir(s,{withFileTypes:!0,encoding:"utf8"});return await pn(n,o),c.map(up)}catch(c){let d=le(c);if(d.code==="NOT_FOUND")return [];throw d}}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 M("READ_DENIED");if(Ti===void 0)throw new M("UNSUPPORTED");let o=hi(t),r=await lt(n),s=ce.resolve(n,...o),a=ce.relative(n,s);if(a===".."||a.startsWith(`..${ce.sep}`)||ce.isAbsolute(a))throw new M("PATH_ESCAPED");let c;try{c=await promises.open(s,Or);}catch(d){throw le(d)}try{let d;try{let g=await c.stat({bigint:!0});d=ln(g);}catch(g){throw le(g)}if(d.size>BigInt(i))throw new M("LIMIT_EXCEEDED");if(d.size>BigInt(Number.MAX_SAFE_INTEGER))throw new M("LIMIT_EXCEEDED");await pn(n,r);let l=await Rr(n,r.realRoot,o);await ut(s,r.realRoot,l,d);let p=new Uint8Array(new ArrayBuffer(Number(d.size))),u=0;for(;u<p.byteLength;){let g;try{g=(await c.read(p,u,p.byteLength-u,u)).bytesRead;}catch(_){throw le(_)}if(g<=0)throw new M("IDENTITY_CHANGED");u+=g;}let y;try{let g=await c.stat({bigint:!0});y=ln(g);}catch(g){throw le(g)}if(!bi(d,y))throw new M("IDENTITY_CHANGED");return await ut(s,r.realRoot,l,y),await pn(n,r),new Uint8Array(p)}finally{await c.close().catch(()=>{});}}async fingerprintVerifiedFile(n,t,i){if(!Number.isSafeInteger(i)||i<0)throw new M("READ_DENIED");if(Ti===void 0)throw new M("UNSUPPORTED");let o=hi(t),r=await lt(n),s=ce.resolve(n,...o),a=ce.relative(n,s);if(a===".."||a.startsWith(`..${ce.sep}`)||ce.isAbsolute(a))throw new M("PATH_ESCAPED");let c;try{c=await promises.open(s,Or);}catch(d){throw le(d)}try{let d;try{let u=await c.stat({bigint:!0});d=ln(u);}catch(u){throw le(u)}if(d.size>BigInt(i)||d.size>BigInt(Number.MAX_SAFE_INTEGER))throw new M("LIMIT_EXCEEDED");await pn(n,r);let l=await Rr(n,r.realRoot,o);await ut(s,r.realRoot,l,d);let p;try{let u=await c.stat({bigint:!0});p=ln(u);}catch(u){throw le(u)}if(!bi(d,p))throw new M("IDENTITY_CHANGED");return await ut(s,r.realRoot,l,p),await pn(n,r),{...p,candidateRealPath:l??r.realRoot}}catch(d){throw d instanceof M?d:le(d)}finally{await c.close().catch(()=>{});}}async readFileVerified(n,t,i){return this.readVerifiedFile(n,t,i)}},wr=new At;});function Cn(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 Ur(e){return typeof e=="string"&&Ee.test(e)?e:void 0}function hp(e){return e.length>0&&e!=="."&&e!==".."&&!/[\\/\u0000]/.test(e)}function Ke(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 _p(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 Ep(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 Tp(e){return gp.decode(e)}function Pp(e){return JSON.parse(Tp(e))}function kr(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 bp(e){if(e instanceof M)return kr(e.code);if(e!==null&&typeof e=="object"&&"code"in e){let n=e.code;if(typeof n=="string")return kr(n)}}function Oe(e,n){let t=n();return Number.isFinite(t)&&Number.isFinite(e)&&t-e<=5e3}function Np(e){if(typeof e.readVerifiedFile=="function")return e.readVerifiedFile;if(typeof e.readFileVerified=="function")return e.readFileVerified}function Dp(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 xr(e,n,t,i){let o=Np(e);if(!o)throw new M("READ_DENIED");return Ep(await o.call(e,n,t,i))}async function Li(e,n,t){let i=Dp(e);if(!i)throw new M("READ_DENIED");let o=await i.call(e,n,t);if(!Array.isArray(o))throw new M("READ_DENIED");return o.map(_p).filter(r=>r!==null)}function Sp(e,n,t,i){return Object.freeze({code:e,...{},source:n,relativePath:t})}function Mp(e){if(!Cn(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(Ke))};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 Lp(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 gt(e){return Object.freeze({appIds:Object.freeze([...new Set(e.map(n=>n.appId))].sort(Ke)),definitionIds:Object.freeze([...new Set(e.map(n=>n.definition.id))].sort(Ke))})}function It(e,n){let t=Object.keys(e).sort(Ke),i=[...n].sort(Ke);return t.length===i.length&&t.every((o,r)=>o===i[r])}function vr(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 Op(e){let n;try{n=Pp(e);}catch{return}if(!Cn(n)||!It(n,["version","packages"])||n.version!==1||!Array.isArray(n.packages)||n.packages.length>Oi)return;let t=new Set,i=new Set,o=0,r=[];for(let s of n.packages){if(!Cn(s))return;let a=["packageDir","appId","definition","files"],c=Object.hasOwn(s,"lineage"),d=Object.hasOwn(s,"launcher"),l=[...c?["lineage"]:[],...d?["launcher"]:[]];if(!It(s,[...a,...l])||d&&s.launcher!==false)return;let p=vr(s.packageDir),u=Ur(s.appId);if(!p||p.length!==2||p[0]!=="apps"||!hp(p[1])||!u||t.has(s.packageDir)||!Cn(s.definition)||!It(s.definition,["id","version","hash"]))return;let y=Ur(s.definition.id),g=s.definition.version,_=s.definition.hash;if(!y||!Number.isSafeInteger(g)||g<1||typeof _!="string"||!Mi.test(_)||!Array.isArray(s.files)||s.files.length<2||s.files.length>Ri)return;let T=new Set,U=[];for(let x of s.files){if(!Cn(x)||!It(x,["path","sha256"]))return;let b=vr(x.path);if(!b||typeof x.sha256!="string"||!Mi.test(x.sha256))return;let w=b.join("/"),V=`${s.packageDir}/${w}`;if(T.has(w)||i.has(V))return;T.add(w),i.add(V),U.push(Object.freeze({path:w,sha256:x.sha256}));}if(!Q.some(x=>T.has(x))||!T.has("ui/index.html")||(o+=U.length,o>yp))return;t.add(s.packageDir),r.push(Object.freeze({packageDir:s.packageDir,...d?{launcher:false}:{},appId:u,definition:Object.freeze({id:y,version:g,hash:_}),lineage:Array.isArray(s.lineage)?s.lineage:[],files:Object.freeze(U.sort((x,b)=>Ke(x.path,b.path)))}));}return Object.freeze({version:1,packages:Object.freeze(r)})}function We(e){let n=bp(e);return n==="PATH_ESCAPED"||n==="IDENTITY_CHANGED"||n==="TOCTOU"?"PATH_ESCAPED":n==="LIMIT_EXCEEDED"?"LIMIT_EXCEEDED":"BUNDLE_INTEGRITY"}async function Rp(e,n,t,i,o){let r=[],s=async(a,c)=>{if(!Oe(i,o))throw new M("LIMIT_EXCEEDED");if(c>2)throw new M("LIMIT_EXCEEDED");let d=await Li(e,n,a);for(let l of d){if(typeof l.name!="string"||l.name.length===0||l.name==="."||l.name===".."||/[\\/\u0000]/.test(l.name))throw new M("PATH_ESCAPED");let p=`${a}/${l.name}`;if(l.kind==="file"){if(r.push(p.slice(t.length+1)),r.length>Ri)throw new M("LIMIT_EXCEEDED")}else if(l.kind==="directory")await s(p,c+1);else throw l.kind==="symlink"?new M("PATH_ESCAPED"):new M("READ_DENIED")}};return await s(t,0),r.sort(Ke)}function wp(e){return Q.includes(e)?262144:e==="ui/index.html"?dn:e==="ui/state.json"?2097152:e.startsWith("ui/assets/")?Ip:Ap}async function jr(e,n,t,i){if(e===void 0)return {packages:[],diagnostics:[],incomplete:false,reservedIds:mp};let o=Mp(e.reservedIds),r=[],s=(I,A,h)=>Sp(I,"bundled",A),a=(I=[],A=false,h)=>({...h===void 0?{}:{indexHash:h},packages:I,diagnostics:r,incomplete:A,reservedIds:o});if(typeof e.root!="string"||e.root.length===0||typeof e.expectedIndexHash!="string"||!Mi.test(e.expectedIndexHash))return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a();let c;try{c=await xr(n,e.root,"bundle-index.json",fp);}catch(I){return r.push(s(We(I),"bundle-index.json")),a()}let d=Vi.createHash("sha256").update(c).digest("hex");if(d!==e.expectedIndexHash)return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a();let l=Op(c);if(l===void 0)return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a();if(!Lp(gt(l.packages),o))return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a([],false,d);if(!Oe(t,i))return r.push(s("LIMIT_EXCEEDED","bundle-index.json")),a(l.packages.map(I=>({indexEntry:I,failureCode:"LIMIT_EXCEEDED"})),true,d);let p;try{p=await Li(n,e.root,"");}catch(I){return r.push(s(We(I),"bundle-index.json")),a(l.packages.map(A=>({indexEntry:A,failureCode:We(I)})),false,d)}if(!Oe(t,i))return r.push(s("LIMIT_EXCEEDED","bundle-index.json")),a(l.packages.map(I=>({indexEntry:I,failureCode:"LIMIT_EXCEEDED"})),true,d);let u=p.find(I=>I.name==="bundle-index.json"&&I.kind==="file"),y=p.find(I=>I.name==="apps"&&I.kind==="directory"),g=I=>l.packages.map(A=>({indexEntry:A,failureCode:I}));if(!u)return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a(g("BUNDLE_INTEGRITY"),false,d);let _=p.filter(I=>I.name!=="bundle-index.json"&&I.name!=="apps");if(_.length>0){let I=_.some(A=>A.kind==="symlink")?"PATH_ESCAPED":"BUNDLE_INTEGRITY";return r.push(s(I,"bundle-index.json")),a(g("BUNDLE_INTEGRITY"),false,d)}if(p.some(I=>I.name==="apps"&&I.kind!=="directory"))return r.push(s("PATH_ESCAPED","apps")),a(g("PATH_ESCAPED"),false,d);let T=[];if(y)try{T=await Li(n,e.root,"apps");}catch(I){return r.push(s(We(I),"apps")),a(g(We(I)),false,d)}if(!Oe(t,i)||T.length>Oi)return r.push(s("LIMIT_EXCEEDED","apps")),a(g("LIMIT_EXCEEDED"),true,d);let U=new Map(l.packages.map(I=>[I.packageDir.slice(5),I])),x=T.filter(I=>!U.has(I.name));for(let I of x)r.push(s(I.kind==="symlink"?"PATH_ESCAPED":"BUNDLE_INTEGRITY",`apps/${I.name}`));if(x.length>0){let I=x.some(A=>A.kind==="symlink")?"PATH_ESCAPED":"BUNDLE_INTEGRITY";return a(g(I),false,d)}let b=new Set,w=new Map,V=new Map;for(let I of l.packages){let A=w.get(I.appId)??[];A.push(I),w.set(I.appId,A);let h=`${I.definition.id}\0${String(I.definition.version)}`,E=V.get(h)??[];E.push(I),V.set(h,E);}for(let I of [...w.values(),...V.values()])if(I.length>1)for(let A of I)b.add(A);let N=[],D=c.byteLength,L=false;for(let I of l.packages){if(!Oe(t,i)){L=true,N.push({indexEntry:I,failureCode:"LIMIT_EXCEEDED"});continue}let A;try{let v=I.lineage[I.lineage.length-1];if(!v)throw new De("LINEAGE_INVALID","Definition lineage is missing");if(v.definition.id!==I.definition.id||v.version!==I.definition.version||v.hash!==I.definition.hash)throw new De("LINEAGE_STALE","Last lineage generation does not match bundle identity");A=yi(I.lineage,{...v.definition,hash:v.hash}).entries;}catch(v){let R=v instanceof De?v.code:"LINEAGE_INVALID";r.push(s(R,I.packageDir)),N.push({indexEntry:I,failureCode:R});continue}let h=T.find(v=>v.name===I.packageDir.slice(5));if(!y||!h){N.push({indexEntry:I,failureCode:"BUNDLE_INTEGRITY"});continue}if(h.kind!=="directory"){N.push({indexEntry:I,failureCode:h.kind==="symlink"?"PATH_ESCAPED":"BUNDLE_INTEGRITY"});continue}let E;try{let v=await Rp(n,e.root,I.packageDir,t,i);if(!Oe(t,i)){L=!0,N.push({indexEntry:I,failureCode:"LIMIT_EXCEEDED"});continue}let R=I.files.map(W=>W.path);if(v.length!==R.length||v.some((W,ke)=>W!==R[ke])){N.push({indexEntry:I,failureCode:"BUNDLE_INTEGRITY"});continue}E=new Map;let Y;for(let W of I.files){if(!Oe(t,i)){Y="LIMIT_EXCEEDED",L=!0;break}if(D>=Si){Y="LIMIT_EXCEEDED";break}let ke;try{ke=await xr(n,e.root,`${I.packageDir}/${W.path}`,wp(W.path));}catch(Dt){Y=We(Dt);break}if(!Oe(t,i)){Y="LIMIT_EXCEEDED",L=!0;break}if(D+ke.byteLength>Si){D=Si,Y="LIMIT_EXCEEDED";break}if(D+=ke.byteLength,Vi.createHash("sha256").update(ke).digest("hex")!==W.sha256){Y="BUNDLE_INTEGRITY";break}E.set(W.path,ke);}if(Y!==void 0){N.push({indexEntry:I,failureCode:Y});continue}}catch(v){Oe(t,i)||(L=true),N.push({indexEntry:I,failureCode:We(v)});continue}N.push({indexEntry:I,lineage:A,files:E,...b.has(I)?{failureCode:"DUPLICATE_ID"}:{}});}return a(N,L,d)}var fp,Oi,Ri,yp,Ap,Ip,Si,Mi,gp,mp,wi=j(()=>{m();Ai();ze();et();pt();Di();fp=256*1024,Oi=64,Ri=128,yp=Oi*Ri,Ap=2*1024*1024,Ip=8*1024*1024,Si=32*1024*1024,Mi=/^[0-9a-f]{64}$/,gp=new TextDecoder("utf-8",{fatal:true}),mp=Object.freeze({appIds:Object.freeze([]),definitionIds:Object.freeze([])});});function Up(e){if(typeof e!="string"||!Ee.test(e))throw new TypeError("pluginId must be a safe UI plugin identifier");let n=`${Ci}${e}`.length+7<=128?e:`hash_${Vi.createHash("sha256").update(e,"utf8").digest("hex")}`;return {read:`${Ci}${n}_read`,action:`${Ci}${n}_action`}}function Vr(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 xp(e,n){return n.length===0||n==="."||n===".."||/[\\/\u0000]/.test(n)?e==="skills"?"skills":"apps":`${e==="skills"?"skills":"apps"}/${n}`}function vp(e){return e.length>0&&e!=="."&&e!==".."&&!/[\\/\u0000]/.test(e)}function kn(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 qr(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 jp(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 Zr(e){return kp.decode(e)}function Fp(e){return JSON.parse(Zr(e))}function Vp(e){if(e===void 0)return;let n=e.definitionId!==void 0&&e.definitionVersion!==void 0?`${e.definitionId}\0${String(e.definitionVersion)}`:void 0;return {pluginId:e.pluginId,...n===void 0?{}:{definitionKey:n}}}function mt(e,n,t,i,o){let r={code:e,...i===void 0?{}:{pluginId:i},source:n,relativePath:t,...o?.reason===void 0?{}:{reason:Object.freeze({...o.reason})},...o?.files===void 0?{}:{files:Object.freeze([...o.files])}};return Object.freeze(r)}function Br(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 re(e){if(e instanceof M)return Br(e.code);if(e!==null&&typeof e=="object"&&"code"in e){let n=e.code;if(typeof n=="string")return Br(n)}}function Ye(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 Hr(e){return {reason:e.reason,...e.code==="MANIFEST_DUAL_MISMATCH"?{files:e.files}:{}}}function zr(e){return e==="MANIFEST_DUAL_MISMATCH"?e:Qr(e)}function Bp(e){return Qr(e.code)}function Qr(e){switch(e){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 es("UiPluginValidationError",e)}}function es(e,n){throw new Error(`Unmapped ${e} code: ${String(n)}`)}function ns(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 es("McpAppContractError",e)}}function Re(e,n){let t=n();return Number.isFinite(t)&&Number.isFinite(e)&&t-e<=5e3}function Hp(e){return {pluginId:e.appId,definitionKey:`${e.definition.id}\0${String(e.definition.version)}`}}function zp(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(Vr(o)){let r=o.bin,s=typeof r=="string"?r:Vr(r)?Object.values(r).find(a=>typeof a=="string"):void 0;for(let a of [s,o.main]){if(typeof a!="string")continue;let c=$p(a);if(c&&n.has(c))return c}}}catch{}return [`${e.slice(e.lastIndexOf("/")+1)}.js`,"index.js","main.js"].find(o=>n.has(o))}function $p(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 Gp(){return globalThis.performance?.now()??Date.now()}function Xe(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let n of Object.values(e))Xe(n);return Object.freeze(e)}function $r(e){return Object.freeze(Array.from(e))}async function xn(e,n,t,i){if(n.pinnedFiles!==void 0){let a=n.pinnedFiles.get(t);if(a===void 0)throw new M("NOT_FOUND");if(a.byteLength>i)throw new M("LIMIT_EXCEEDED");return new Uint8Array(a)}let o=`${n.relativePath}/${t}`,r=n.scanContext,s=e.fingerprintVerifiedFile;if(r===void 0||!r.cacheable||typeof s!="function")return Kr(e,n.root,o,i);try{let a=r.priorFingerprints.get(o)??await s.call(e,r.workspaceRoot,o,i);r.candidateRealPath=a.candidateRealPath;let c=await Kr(e,n.root,o,i),d=await s.call(e,r.workspaceRoot,o,i);return r.candidateRealPath=d.candidateRealPath,is(a,d)&&d.size===BigInt(c.byteLength)&&!os(d,r.scanStartedAtNs)?r.files.set(o,{relativePath:o,byteLimit:i,fingerprint:d}):r.cacheable=!1,c}catch(a){let c=!t.includes("/")&&re(a)==="NOT_FOUND"&&r.directoryListings.some(l=>l.relativePath===n.relativePath&&!ht(l.key,t)),d=t===H&&re(a)==="NOT_FOUND"&&Wp(r.directoryListings,n.relativePath);throw !c&&!d&&(r.cacheable=false),a}}async function Jp(e,n,t){if(n.pinnedFiles!==void 0)return {iconDiagnostics:[]};let i=await _n(t,async r=>{try{return await xn(e,n,r,262144)}catch(s){let a=re(s);return a==="NOT_FOUND"?"missing":a==="LIMIT_EXCEEDED"?"too-large":"bad-path"}}),o=i.file;return {...o===void 0?{}:{iconFile:{path:o.path,sha256:Vi.createHash("sha256").update(o.bytes).digest("hex"),contentType:o.contentType,byteLength:o.byteLength}},iconDiagnostics:i.diagnostics}}function Wp(e,n){let t=e.find(o=>o.relativePath===n);if(t===void 0)return false;if(!ht(t.key,"dist"))return true;let i=e.find(o=>o.relativePath===`${n}/dist`);return i!==void 0&&!ht(i.key,"tools.json")}function ts(e,n){return JSON.stringify([e.realPath,n.source,n.relativePath])}async function Xp(e,n,t,i,o,r,s,a){let c=e.fingerprintVerifiedFile,d=ts(t,i),l=o.candidates.get(d),p=i.relativePath,u;try{u=await Wr(e,n,p);}catch(L){if(re(L)!=="NOT_FOUND")throw L}let y=u===void 0?void 0:{relativePath:p,key:u};if(y!==void 0&&(i.source==="apps"||i.source==="skills")&&!Q.some(L=>ht(y.key,L)))return Re(s,a)?l!==void 0&&l.candidate===void 0&&l.candidateRealPath===void 0&&l.files.length===0&&l.directoryListings.length===1&&l.directoryListings[0]?.relativePath===y.relativePath&&l.directoryListings[0]?.key===y.key&&(i.source==="apps"?l.diagnostic?.code==="MANIFEST_MISSING":l.diagnostic===void 0)&&typeof c=="function"?{memo:l}:typeof c!="function"?{}:{context:{state:o,cacheKey:d,workspaceRoot:n,scanStartedAtNs:r,directoryListings:Object.freeze([y]),priorFingerprints:new Map,files:new Map,cacheable:true}}:{timeLimitReached:true};let g=async L=>{if(L==="")return y;let I=`${i.relativePath}${L}`;try{let A=await Wr(e,n,I);return A===void 0?void 0:{relativePath:I,key:A}}catch(A){if(re(A)==="NOT_FOUND")return;throw A}},_=await Promise.all(Gr.map(g)),T=await Promise.all(Kp.map(g));if(!Re(s,a))return {timeLimitReached:true};let U=typeof c=="function"&&_.every(L=>L!==void 0),x=_.filter(L=>L!==void 0),b=[...x,...T.filter(L=>L!==void 0)],w=new Map,V=l!==void 0&&U,N;if(l!==void 0&&typeof c=="function"){let L=await Promise.all(l.files.map(async I=>{if(!Re(s,a))return {kind:"time",file:I};try{let A=await c.call(e,n,I.relativePath,I.byteLimit);return {kind:"fingerprint",file:I,current:A}}catch(A){return re(A)==="NOT_FOUND"?{kind:"missing",file:I}:{kind:"error",file:I,error:A}}}));if(L.some(I=>I.kind==="time"))return {timeLimitReached:true};for(let I of L){if(I.kind==="error")throw I.error;if(I.kind==="missing"){V=false;continue}if(I.kind!=="fingerprint")continue;let{file:A,current:h}=I;w.set(A.relativePath,h),N??=h.candidateRealPath,(h.candidateRealPath!==l.candidateRealPath||!is(h,A.fingerprint)||os(h,r))&&(V=false);}}let D=l!==void 0&&l.directoryListings.length===b.length&&l.directoryListings.every((L,I)=>L.relativePath===b[I]?.relativePath&&L.key===b[I]?.key);return l!==void 0&&U&&D&&V&&N===l.candidateRealPath?{memo:l}:!U||x.length!==Gr.length?{}:{context:{state:o,cacheKey:d,workspaceRoot:n,scanStartedAtNs:r,directoryListings:Object.freeze(b),priorFingerprints:w,files:new Map,...N===void 0?{}:{candidateRealPath:N},cacheable:true}}}function ht(e,n){try{let t=JSON.parse(e);return Array.isArray(t)&&t.some(i=>Array.isArray(i)&&i[0]===n)}catch{return true}}async function Wr(e,n,t){let i=rs(e);if(typeof i!="function")return;let o=await i.call(e,n,t);if(!Array.isArray(o)||o.some(s=>typeof s=="string"))return;let r=o.map(qr);if(!r.some(s=>s===null))return JSON.stringify(r.slice().sort((s,a)=>kn(s.name,a.name)||kn(s.kind,a.kind)).map(s=>[s.name,s.kind]))}function is(e,n){return e.dev===n.dev&&e.ino===n.ino&&e.size===n.size&&e.mtimeNs===n.mtimeNs&&e.ctimeNs===n.ctimeNs}function os(e,n){let t=e.mtimeNs-n;return t>=-Jr&&t<=Jr}function Ui(e){let n=e.scanContext,t=e.source==="skills"&&e.candidate===void 0&&e.diagnostic===void 0&&n?.files.size===0,i=e.source==="apps"&&e.candidate===void 0&&e.diagnostic?.code==="MANIFEST_MISSING"&&n?.files.size===0,o=t||i;if(n===void 0||!n.cacheable||n.candidateRealPath===void 0&&!o||n.files.size===0&&!o)return;let r=Object.freeze({...!o&&n.candidateRealPath!==void 0?{candidateRealPath:n.candidateRealPath}:{},directoryListings:n.directoryListings,files:Object.freeze([...n.files.values()]),...e.candidate===void 0?{}:{candidate:e.candidate},...e.diagnostic===void 0?{}:{diagnostic:e.diagnostic},...e.identity===void 0?{}:{identity:e.identity},...e.provenance===void 0?{}:{provenance:e.provenance}});n.state.candidates.set(n.cacheKey,r);}function Yp(e,n,t){let i=Vi.createHash("sha256"),o=new TextEncoder().encode(te(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 qp(e,n){let t={...e.definition,sourceHash:n},i;try{i=pe(t);}catch(r){throw r instanceof k&&r.code==="INPUT_INVALID"?new ae("MANIFEST_INVALID","normalized definition is invalid"):r}let o={...t,hash:i};try{ye(o);}catch{throw new ae("MANIFEST_INVALID","normalized definition is invalid")}return o}function Zp(e,n){return e.actions.some(t=>t.backend.type==="core"&&t.backend.handler!=="state.set"&&!ot(n,t.backend))}function Qp(e){if(typeof e.readVerifiedFile=="function")return e.readVerifiedFile;if(typeof e.readFileVerified=="function")return e.readFileVerified}function rs(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 Kr(e,n,t,i){let o=Qp(e);if(!o)throw new M("READ_DENIED");return jp(await o.call(e,n,t,i))}async function el(e,n,t){let i=rs(e);if(!i)throw new M("READ_DENIED");let o=await i.call(e,n,t);if(!Array.isArray(o))throw new M("READ_DENIED");return o.map(qr).filter(r=>r!==null)}function nl(e){let n=[];for(let t of [e.reserved,e.builtin])t&&n.push(t);return e.builtins&&"listMcpApps"in e.builtins?n.push(Xr(e.builtins)):e.builtins&&n.push(e.builtins),e.builtinCatalog&&n.push(Xr(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 Xr(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 he(e,n){e.diagnostic||(e.diagnostic=mt(n,e.source,e.relativePath,e.identity?.pluginId));}function tl(e,n){let t=new Set,i=new Map;for(let r of e){let s=r.identity?.pluginId;if(s===void 0)continue;let a=i.get(s)??[];a.push(r),i.set(s,a);}for(let r of i.values()){if(r.length<2)continue;let s=r.filter(c=>c.provenance!==void 0);if(s.length>0){let c=r.find(d=>n.has(d));if(c){for(let d of s)t.add(d);for(let d of r)d!==c&&d.provenance===void 0&&he(d,"RESERVED_ID");continue}for(let d of r)d.provenance===void 0&&he(d,"RESERVED_ID");if(s.length>1)for(let d of s)he(d,"DUPLICATE_ID");continue}let a=r.filter(c=>c.source==="apps");if(a.length>1){for(let c of a)he(c,"DUPLICATE_ID");for(let c of r.filter(d=>d.source==="skills"))he(c,"DUPLICATE_ID");}else for(let c of r.filter(d=>d.source==="skills"))he(c,"DUPLICATE_ID");}let o=new Map;for(let r of e){if(r.diagnostic?.code==="RESERVED_ID"||t.has(r)||r.provenance===void 0&&!n.has(r)&&i.get(r.identity?.pluginId??"")?.some(c=>c.provenance!==void 0))continue;let s=r.identity?.definitionKey;if(s===void 0)continue;let a=o.get(s)??[];a.push(r),o.set(s,a);}for(let r of o.values())if(r.length>1)for(let s of r)he(s,"DUPLICATE_ID");return t}function il(e,n,t){let i=new Set,o=new Set,r=new Set,s=new Set([...t.appIds,...n.productBundleReservationMetadata?.reservedAppIds??[]]),a=new Set([...t.definitionIds,...n.productBundleReservationMetadata?.reservedDefinitionIds??[]]);for(let l of nl(n)){for(let p of l.appIds??[])typeof p=="string"&&i.add(p);for(let p of l.definitionIds??[])typeof p=="string"&&o.add(p);for(let p of l.toolNames??[])typeof p=="string"&&r.add(p);}for(let l of e){let p=l.candidate;if(!p)continue;if(i.has(p.pluginId)||o.has(p.definitionId)){he(l,"RESERVED_ID");continue}[p.toolNames.read,p.toolNames.action].filter(y=>y!==void 0).some(y=>r.has(y))&&he(l,"DUPLICATE_ID");}let c=[...e.filter(l=>l.provenance!==void 0&&l.diagnostic===void 0).flatMap(l=>l.candidate?[l.candidate]:[]),...(n.productBundleReservationMetadata?.candidates??[]).filter(l=>n.productBundleReservationMetadata?.indexHash!==void 0&&l.provenance?.indexHash===n.productBundleReservationMetadata.indexHash)],d=new Set;for(let l of e){let p=l.candidate;if(!(!p||l.diagnostic||l.source!=="apps"||l.provenance!==void 0)&&e.filter(u=>u.source==="apps"&&u.identity?.pluginId===p.pluginId).length===1&&c.some(u=>u.pluginId===p.pluginId)&&!(a.has(p.definitionId)&&!c.some(u=>u.pluginId===p.pluginId&&u.definitionId===p.definitionId))&&!c.some(u=>u.pluginId!==p.pluginId&&u.definitionId===p.definitionId)&&!e.some(u=>u.identity?.pluginId!==p.pluginId&&u.identity?.definitionKey===`${p.definitionId}\0${p.version}`&&u.diagnostic?.code!=="RESERVED_ID"))try{br(p),d.add(l);}catch(u){he(l,u instanceof Ne?ns(u.code):"EXEC_DENIED");}}for(let l of e){let p=l.candidate;p&&l.provenance===void 0&&!d.has(l)&&(s.has(p.pluginId)||a.has(p.definitionId))&&he(l,"RESERVED_ID");}return d}function ol(e){return [...e].sort((n,t)=>{let i=Fr.indexOf(n.source)-Fr.indexOf(t.source);return i!==0?i:kn(n.relativePath,t.relativePath)})}function B(e,n,t){e.diagnostic=mt(n,e.source,e.relativePath,e.identity?.pluginId,t);}async function Yr(e,n,t){let i=Fe(t,{mode:"local"});if(!i.ok&&i.parseFailure){B(n,zr(i.rejection.code),Hr(i.rejection));return}let o=Vp(i.identity);if(n.bundleIdentity===void 0)n.identity=o;else if(o?.pluginId!==n.bundleIdentity.appId||o.definitionKey!==`${n.bundleIdentity.definitionId}\0${String(n.bundleIdentity.version)}`){B(n,"BUNDLE_INTEGRITY");return}if(!i.ok&&i.builtinOnly){B(n,"RESERVED_ID");return}if(!i.ok){B(n,zr(i.rejection.code),Hr(i.rejection));return}let r=i.manifest,s={pluginId:r.pluginId,definitionKey:`${r.definitionId}\0${String(r.version)}`};if(n.bundleIdentity===void 0&&(n.identity=s),r.actions.length>0)try{mi(r.actions.map(R=>({actionId:R.actionId,inputSchema:R.inputSchema})));}catch(R){if(R instanceof Ne){B(n,ns(R.code));return}throw R}let a;try{a=await xn(e,n,"ui/index.html",dn);}catch(R){B(n,Ye(re(R),"entry"));return}if(a.byteLength>dn){B(n,"LIMIT_EXCEEDED");return}let c;try{c=Zr(a);}catch{B(n,"ENTRY_INVALID");return}if(a.byteLength===0||c.length===0){B(n,"ENTRY_INVALID");return}let d=Vi.createHash("sha256").update(a).digest("hex");if(r.entryHash!==void 0&&r.entryHash!==d){B(n,"ENTRY_INVALID");return}let l={},p,u;if(r.initialState!==void 0){try{p=await xn(e,n,"ui/state.json",2097152);}catch(R){B(n,Ye(re(R),"initial"));return}if(p.byteLength>2097152){B(n,"LIMIT_EXCEEDED");return}try{let R=Fp(p),Y=r.dataPaths??[],W=ni(R,Y);l=fe(W,0,Y),en(l);}catch{B(n,"INITIAL_STATE_INVALID");return}if(u=Vi.createHash("sha256").update(p).digest("hex"),r.initialState.hash!==void 0&&r.initialState.hash!==u){B(n,"INITIAL_STATE_INVALID");return}}let y={...r,entryHash:d,...r.initialState===void 0?{}:{initialState:{path:"ui/state.json",hash:u}}},g=mn(y),_=Yp(y,a,p??new Uint8Array),T;try{T=qp(g,_);}catch(R){if(R instanceof ae){B(n,Bp(R));return}throw R}let U;if(n.bundleLineage!==void 0){let R=n.bundleLineage[n.bundleLineage.length-1];if(!R){B(n,"LINEAGE_INVALID");return}let{legacy:Y,...W}=R.definition,{hash:ke,...Dt}=T;if(te(W)!==te(Dt)){B(n,"LINEAGE_STALE");return}if(Y!==void 0&&(T={...T,legacy:Y}),Y!==void 0)try{T={...T,hash:pe(T)},ye(T);}catch{B(n,"LINEAGE_INVALID");return}U=n.bundleLineage;}if(n.bundleIdentity!==void 0&&n.bundleIdentity.appId!==r.pluginId){B(n,"BUNDLE_INTEGRITY");return}if(n.bundleIdentity!==void 0&&(n.bundleIdentity.definitionId!==T.id||n.bundleIdentity.version!==T.version||n.bundleIdentity.definitionHash!==T.hash)){B(n,"LINEAGE_STALE");return}let x=await Jp(e,n,i.mcpb?.icon),b=Up(r.pluginId),w=r.actions.length===0?{read:b.read}:b,V=Xe(g),N=Xe(y),D=Xe(T),L=Xe({...g.handlers}),I=$r(a),A=p===void 0?void 0:$r(p),h=Object.freeze({...n.provenance===void 0?{}:{provenance:n.provenance},entry:Object.freeze({path:"ui/index.html",hash:d,bytes:I}),...A===void 0?{}:{initialState:Object.freeze({path:"ui/state.json",hash:u,bytes:A})}}),E={appId:r.pluginId,pluginId:r.pluginId,definitionId:r.definitionId,version:r.version,...i.releaseVersion===void 0?{}:{releaseVersion:i.releaseVersion},manifestFile:i.file,...i.mcpb===void 0?{}:{mcpb:Xe(i.mcpb)},relativePath:n.relativePath,manifest:N,normalized:V,name:r.name,description:r.description,...r.icon===void 0?{}:{icon:r.icon},...r.tone===void 0?{}:{tone:r.tone},...x.iconFile===void 0?{}:{iconFile:Object.freeze({...x.iconFile})},...x.iconDiagnostics.length===0?{}:{iconDiagnostics:Object.freeze([...x.iconDiagnostics])},definition:D,handlers:L,resources:h,html:c,entryBytes:I,entryHash:d,initialState:Xe(l),...A===void 0?{}:{initialStateBytes:A},...u===void 0?{}:{initialStateHash:u},sourceHash:_,toolNames:Object.freeze(w)},v=n.provenance===void 0?{...E,source:n.source}:{...E,provenance:n.provenance,lineage:U??[]};n.candidate=Object.freeze(v),Zp(r,T.usage)&&B(n,"EXEC_DENIED");}async function ss(e,n){let t={};for(let i of Q)try{t[i]=await xn(e,n,i,262144);}catch(o){if(re(o)==="NOT_FOUND")continue;return {files:t,failure:Ye(re(o),"manifest")}}if(t[J]!==void 0)try{t[H]=await xn(e,n,H,262144);}catch(i){if(re(i)!=="NOT_FOUND")return {files:t,failure:Ye(re(i),"manifest")}}return {files:t}}function ki(e){return Q.some(n=>e[n]!==void 0)}async function rl(e,n){let{files:t,failure:i}=await ss(e,n);if(i!==void 0){B(n,i);return}let o=t[J];return o!==void 0&&!ci(o)&&(delete t[J],delete t[H]),ki(t)?t:void 0}function sl(e,n,t,i=Cp,o=false,r=new Set){let s=ol(e),a=tl(s,r),c=Object.freeze(s.filter(u=>u.candidate!==void 0&&u.diagnostic===void 0&&!a.has(u)).map(u=>u.candidate)),d=Object.freeze(s.filter(u=>u.diagnostic!==void 0).map(u=>u.diagnostic)),l=o?Object.freeze({...t===void 0?{}:{indexHash:t},candidates:Object.freeze(s.filter(u=>u.source==="bundled"&&u.diagnostic===void 0&&t!==void 0&&u.candidate?.provenance?.indexHash===t).map(u=>u.candidate)),diagnostics:Object.freeze(d.filter(u=>u.source==="bundled").map(u=>Object.freeze({...u}))),reservedAppIds:Object.freeze([...i.appIds]),reservedDefinitionIds:Object.freeze([...i.definitionIds])}):void 0,p={apps:c,diagnostics:d,complete:n===void 0,...n===void 0?{}:{incompleteReason:n},...t===void 0?{}:{productBundleIndexHash:t},...l===void 0?{}:{productBundleSnapshotMetadata:l}};return Object.defineProperty(p,"candidates",{configurable:false,enumerable:false,get:()=>c}),Object.freeze(p)}function al(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 cl(e,n){if(al(e))return {fs:e,options:{}};let t=e??n??{};return {fs:t.filesystem??t.fileSystem??t.fs??wr,options:t}}async function as(e,n,t){if(typeof e!="string"||e.length===0)throw new TypeError("workspaceRoot must be explicit");let{fs:i,options:o}=cl(n,t),r=o.clock??Gp,s=r(),a=await jr(o.productBundle,i,s,r),c=r(),d=BigInt(Date.now())*1000000n,l=[],p=0,u,y=false,g,_;if(o.scanCache!==void 0&&typeof i.getRootIdentity=="function"&&typeof i.fingerprintVerifiedFile=="function")try{_=await i.getRootIdentity(e),g=Sr(o.scanCache,_),g.scanStartedAtNs=d;}catch(N){if(re(N)!=="NOT_FOUND")throw N}let T=g!==void 0&&o.productBundle===void 0&&a.packages.length===0&&a.diagnostics.length===0,U=new Set,x=true;l.push(...a.diagnostics.map(N=>({source:N.source,root:o.productBundle?.root??e,name:"",relativePath:N.relativePath,diagnostic:N})));let b=a.reservedIds;a.incomplete&&(u="time_limit");for(let N of a.packages){if(!Re(c,r)){y=true,u="time_limit";break}let D=N.indexEntry,L=D.packageDir,I=N.files===void 0?void 0:zp(L,N.files),A=a.indexHash===void 0?void 0:Qo(Object.freeze({kind:"bundled",launcher:D.launcher!==false,indexHash:a.indexHash,packageDir:L,appId:D.appId,definitionId:D.definition.id,version:D.definition.version,definitionHash:D.definition.hash,files:D.files}),I),h={source:"bundled",root:o.productBundle?.root??e,name:L.slice(5),relativePath:L,...A===void 0?{}:{provenance:A},...N.files===void 0?{}:{pinnedFiles:N.files},...N.lineage===void 0?{}:{bundleLineage:N.lineage},bundleIdentity:{appId:D.appId,definitionId:D.definition.id,version:D.definition.version,definitionHash:D.definition.hash},identity:Hp(D)};if(l.push(h),p+=1,N.failureCode!==void 0){B(h,N.failureCode);continue}if(N.files?.has(H)===true){B(h,"EXEC_DENIED",{reason:{path:"",rule:"bundled-tool-mode-unsupported",file:H}});continue}let E={};for(let v of Q){let R=N.files?.get(v);R!==void 0&&(E[v]=R);}if(!ki(E)){B(h,"BUNDLE_INTEGRITY");continue}if(await Yr(i,h,E),!Re(c,r)){y=true,u="time_limit";break}}let w=[{source:"apps",directory:"apps"},{source:"skills",directory:"skills"}];e:for(let N of w){let{source:D,directory:L}=N,I;try{I=await el(i,e,L);}catch(h){if(re(h)==="NOT_FOUND")continue;T=false,x=false,l.push({source:D,root:e,name:"",relativePath:D,diagnostic:mt(Ye(re(h),"manifest"),D,D)});continue}let A=I.filter(h=>h.kind==="directory"||h.kind==="symlink").filter(h=>vp(h.name)).map(h=>({source:D,root:e,name:h.name,relativePath:xp(D,h.name)})).sort((h,E)=>kn(h.relativePath,E.relativePath));for(let h of A){let E={...h};if(l.push(E),_!==void 0?U.add(ts(_,E)):T=false,!Re(c,r)){y=true,u="time_limit";break e}let v;if(g!==void 0&&_!==void 0){try{let W=await Xp(i,e,_,E,g,d,c,r);if(W.timeLimitReached){y=!0,u="time_limit";break e}E.scanContext=W.context,v=W.memo;}catch(W){T=false,B(E,Ye(re(W),"manifest"));continue}v===void 0&&(T=false);}if(v!==void 0){if(E.candidate=v.candidate,E.diagnostic=v.diagnostic,E.identity=v.identity,D==="skills"&&v.candidate===void 0&&v.diagnostic===void 0)continue;if(p>=64){B(E,"LIMIT_EXCEEDED");continue}if(h.relativePath.split("/").length-1>2){B(E,"LIMIT_EXCEEDED");continue}if(p+=1,!Re(c,r)){y=true,u="time_limit";break e}continue}let R;if(D==="skills"&&(R=await rl(i,E),R===void 0)){E.diagnostic===void 0&&Ui(E);continue}if(p>=64){B(E,"LIMIT_EXCEEDED");continue}if(h.relativePath.split("/").length-1>2){B(E,"LIMIT_EXCEEDED");continue}if(!Re(c,r)){y=true,u="time_limit";break e}if(p+=1,R===void 0){let W=await ss(i,E);if(W.failure!==void 0||!ki(W.files)){B(E,W.failure??Ye("NOT_FOUND","manifest")),Ui(E);continue}R=W.files;}if(await Yr(i,E,R),Ui(E),!Re(c,r)){y=true,u="time_limit";break e}}}if(g!==void 0&&_!==void 0){let N=[...U].sort(kn),D=g.lastCandidateKeys,L=D!==void 0&&D.length===N.length&&D.every((A,h)=>A===N[h]);if(T=T&&L,x&&!y&&u===void 0)for(let A of g.candidates.keys())try{JSON.parse(A)[0]===_.realPath&&!U.has(A)&&g.candidates.delete(A);}catch{g.candidates.delete(A);}let I=[...g.candidates.keys()].filter(A=>{try{return JSON.parse(A)[0]===_.realPath}catch{return false}});T=T&&I.length===U.size&&I.every(A=>U.has(A))&&!y&&u===void 0,g.lastCandidateScanUnchanged=T,x&&!y&&u===void 0&&(g.lastCandidateKeys=Object.freeze(N));}y&&l.push({source:"apps",root:e,name:"",relativePath:"apps",diagnostic:mt("DISCOVERY_TIME_LIMIT","apps","apps")});let V=il(l,o,b);return sl(l,u,a.indexHash,b,o.productBundle!==void 0,V)}var Cp,Ci,Fr,kp,Gr,Kp,Jr,cs=j(()=>{m();$e();jn();Se();li();pi();ze();pt();Nr();rt();tt();Mr();Di();it();wi();wi();Cp=gt([]),Ci="crewx_local_app_";Fr=["bundled","apps","skills"],kp=new TextDecoder("utf-8",{fatal:true});Gr=["","/ui"],Kp=["/dist"],Jr=2000000000n;});m();li();m();Gt();m();var Vo="SKILL.md",hd=/^---\s*\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;function Bo(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function _d(e){return e.isDirectory()||e.isSymbolicLink()}function Jo(e){try{return ne.existsSync(e)&&ne.statSync(e).isDirectory()}catch{return false}}function ui(e){let n;try{n=ne.readFileSync(e,"utf8");}catch{return {frontmatter:{},readable:false,valid:false,hasFrontmatter:false}}let t=n.match(hd);if(!t)return {frontmatter:{},readable:true,valid:true,hasFrontmatter:false};try{let i=Ts.load(t[1]??"");if(!Bo(i))return {frontmatter:{},readable:!0,valid:!1,hasFrontmatter:!0};let o=Bo(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 Ed(e){return [ce.join(e,Vo),ce.join(e,"skill",Vo)]}function Ho(e,n){if(!Jo(e))return null;for(let t of Ed(e)){if(!ne.existsSync(t))continue;let o=ui(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 zo(e){try{return ne.readdirSync(e,{withFileTypes:!0}).filter(_d)}catch{return []}}function $o(e,n,t){!e||n.has(e.name)||(n.add(e.name),t.push(e));}function Wo(e){let n=[],t=new Set;for(let i of e)if(Jo(i))for(let o of zo(i)){if(o.name.startsWith("@")){let r=ce.join(i,o.name);for(let s of zo(r))$o(Ho(ce.join(r,s.name),s.name),t,n);continue}$o(Ho(ce.join(i,o.name),o.name),t,n);}return n.sort((i,o)=>i.name.localeCompare(o.name))}m();et();var Td=/^[A-Za-z0-9_$.[\]"-]{0,200}$/,Pd=/^[a-z][a-z0-9-]{0,63}$/,bd="<unknown>";function Nd(e){return typeof e=="string"&&(Q.includes(e)||e===H)}function Ko(e){if(typeof e!="object"||e===null)return;let{file:n,path:t,rule:i}=e;if(!(typeof i!="string"||!Pd.test(i)))return {...Nd(n)?{file:n}:{},path:typeof t=="string"&&Td.test(t)?t:bd,rule:i}}function Xo(e){if(!Array.isArray(e))return;let n=Q.filter(t=>e.includes(t));return n.length>0?n:void 0}cs();var pl=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/;function Tt(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?ll(e.relativePath,e.fileBytes):void 0);if(n!==void 0&&i!==void 0){let o=JSON.stringify({screenHash:n,skillHash:i});return Vi.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 ll(e,n){let t=new TextEncoder().encode(Pt(e)),i=ul(n),o=new Uint8Array(t.byteLength+1+i.byteLength);return o.set(t,0),o[t.byteLength]=0,o.set(i,t.byteLength+1),Vi.createHash("sha256").update(o).digest("hex")}function ul(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 Pt(e){if(typeof e!="string"||e.length===0||ce.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 _t(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 ls(e,n){let t=ce.relative(e,n).split(ce.sep).join("/");return !t||t===".."||t.startsWith("../")||ce.isAbsolute(t)?null:Pt(t)}function fl(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 us(e){return Object.freeze({packageRoot:e})}function yl(e){return Object.freeze({id:e.definition.id,version:e.definition.version,hash:e.definition.hash,usage:e.definition.usage??xe,...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 fs(e){return {capabilities:Object.freeze([...e]),origin:"local",ownership:"unknown",shareability:"unknown",sharingAvailability:"unavailable"}}function Al(e,n){let t=e.candidate,i=t.provenance!==void 0,o=n&&!i?["screen","skill"]:["screen"],r=yl(t),s=Tt(n?{screenHash:r.hash,skillHash:n.skillHash}:{screenHash:r.hash}),a=t.description||n?.skill.description||"",c=t.releaseVersion??String(t.version),d={appId:t.pluginId,name:t.name,description:a,version:c,...fs(o),definition:r,...n===void 0||i?{}:{skillName:n.skill.name},...i?{provenance:t.provenance}:{localDefinitionRef:us(e.packageRoot)},definitionHash:s,...t.manifest.csp===void 0?{}:{connectDomains:Object.freeze([...t.manifest.csp.connectDomains])}};return {...i?{}:{packageRoot:e.packageRoot},source:i?"bundled":t.source,appId:d.appId,capabilities:o,summary:Object.freeze(d)}}function Il(e){let n=gl(e.skill.name),t={appId:n,name:e.skill.name,description:e.skill.description??"",...e.skill.version===void 0?{}:{version:e.skill.version},...fs(["skill"]),skillName:e.skill.name,localDefinitionRef:us(e.packageRoot),definitionHash:Tt({skillHash:e.skillHash})};return {packageRoot:e.packageRoot,source:e.source,appId:n,capabilities:["skill"],summary:Object.freeze(t)}}function gl(e){return `skill.${e.replace(/^@/,"").replace(/\//g,".").replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,122)||"unnamed"}`}function Z(e,n,t,i,o){let r=Ko(o?.reason),s=Xo(o?.files);return Object.freeze({code:e,source:n,relativePath:ml(t),...i===void 0?{}:{appId:i},...r===void 0?{}:{reason:r},...s===void 0?{}:{files:s}})}function ml(e){if(typeof e!="string"||e.length===0||ce.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 ys(e){return Z(e.code,e.source,e.relativePath,e.pluginId,e)}function hl(e,n){let t=ls(e,n.dir);if(!t)return {diagnostic:Z("PATH_ESCAPED","node_modules","node_modules")};let i=fl(t);if(!i)return {diagnostic:Z("PATH_ESCAPED","node_modules",t)};let o=ui(n.skillMdPath);if(!o.readable)return {diagnostic:Z("SKILL_READ_FAILED",i,t)};if(!o.valid)return {diagnostic:Z("SKILL_INVALID",i,t)};let r=_l(n.dir,n.skillMdPath);if(!r)return {diagnostic:Z("PATH_ESCAPED",i,t)};try{let s=new Uint8Array(ne.readFileSync(n.skillMdPath));return {skill:n,packageRoot:t,relativeSkillPath:r,skillHash:Tt({relativePath:r,fileBytes:s}),source:i}}catch{return {diagnostic:Z("SKILL_READ_FAILED",i,t)}}}function _l(e,n){let t=ce.relative(e,n).split(ce.sep).join("/");try{return Pt(t)}catch{return null}}function El(e){if(!pl.test(e.appId))return {diagnostic:Z("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??xe,...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??Vi.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 Tl(e){return e.builtinCatalog}function Pl(e){let n=e.packageRoot??e.relativePath??e.packageRootPath;if(n===void 0)return null;try{return Pt(n)}catch{return null}}function bl(e){let n=e.marketplaceContentId;return typeof n=="string"&&n.length>0?n:void 0}function Nl(e,n,t){let i=n.installed??[],o=new Map;for(let s of i){let a=Pl(s);if(!a){t.push(Z("INSTALLED_IDENTITY_MISMATCH","installed","installed"));continue}let c=o.get(a);if(c&&JSON.stringify(c)!==JSON.stringify(s)){t.push(Z("INSTALLED_IDENTITY_MISMATCH","installed",a));continue}o.set(a,s);}let r=new Map;for(let s of e)s.packageRoot!==void 0&&r.set(s.packageRoot,s);for(let[s,a]of o){let c=r.get(s);if(!c){t.push(Z("INSTALLED_MISSING","installed",s,a.appId));continue}let d=bl(a);if(!d){t.push(Z("INSTALLED_CONTENT_ID_MISSING","installed",s,a.appId));continue}if(a.appId!==void 0&&a.appId!==c.appId||a.definitionHash!==void 0&&a.definitionHash!==c.summary.definitionHash){t.push(Z("INSTALLED_IDENTITY_MISMATCH","installed",s,a.appId));continue}let l={...c.summary,origin:"installed",...a.slug===void 0?{}:{slug:a.slug},marketplaceContentId:d},p=e.indexOf(c);p>=0&&(e[p]={...c,summary:Object.freeze(l)});}}function Dl(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==="bundled"){let s=o.filter(a=>a.source==="apps"&&a.summary.definition!==void 0);if(s.length===1){for(let a of o)a.source==="bundled"?i.add(a):a!==s[0]&&(i.add(a),n.push(Z("RESERVED_ID",a.source,Et(a),a.appId)));continue}}if(r!==void 0){let s=o.filter(a=>a.source===r);for(let a of o.filter(c=>c.source!==r))i.add(a),n.push(Z("RESERVED_ID",a.source,Et(a),a.appId));if(s.length>1)for(let a of s)i.add(a),n.push(Z("DUPLICATE_ID",a.source,Et(a),a.appId));continue}for(let s of o)i.add(s),n.push(Z("DUPLICATE_ID",s.source,Et(s),s.appId));}return e.filter(o=>!i.has(o))}function Et(e){return e.packageRoot??e.summary.provenance?.packageDir??`builtin/${e.appId}`}function Sl(e,n){return e.filter(t=>!(t.code==="MANIFEST_MISSING"&&n.has(t.relativePath))).map(ys)}function Ml(e){return e.filesystem}function Ll(e,n){let t=Ml(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?{}:{productBundleReservationMetadata:i}}}async function As(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=Tl(n),i=await as(e,Ll(n,t)),o=n.registeredProductBundle??i.productBundleSnapshotMetadata,r=[ce.join(e,"skills"),ce.join(e,"node_modules"),ce.join(e,"apps")],s=[],a=[],c=[],d=new Set;for(let A of r)for(let h of Wo([A])){let E=ls(e,h.dir);(E===null||!d.has(E))&&(c.push(h),E!==null&&d.add(E));}for(let A of c){let h=hl(e,A);"diagnostic"in h?s.push(h.diagnostic):a.push(h);}let l=new Map,p=n.registeredProductBundle?.indexHash,u=(n.registeredProductBundle?.candidates??[]).filter(A=>p!==void 0&&A.provenance?.indexHash===p),y=[...new Set([...i.apps??i.candidates??[],...i.productBundleSnapshotMetadata?.candidates??[]]),...u],g=new Set(u),_=new Set(p===void 0?[]:(t?.listMcpApps()??[]).filter(A=>A.provenance?.indexHash===p).map(A=>A.appId));for(let A of y){if(g.has(A)&&A.provenance?.indexHash===p&&_.has(A.appId))continue;let h=A.provenance===void 0?`workspace\0${A.relativePath}`:`bundled\0${A.provenance.indexHash}\0${A.provenance.packageDir}`;l.set(h,{candidate:A,packageRoot:A.relativePath});}let T=new Map(a.map(A=>[A.packageRoot,A])),U=[];for(let A of l.values()){let h=A.candidate.provenance===void 0?T.get(A.packageRoot):void 0,E=Al(A,h);U.push({...E.packageRoot===void 0?{}:{packageRoot:E.packageRoot},source:E.source,appId:E.appId,summary:E.summary});}let x=new Set([...l.values()].filter(A=>A.candidate.provenance===void 0).map(A=>A.packageRoot)),b=o===void 0?new Set:new Set(i.diagnostics.filter(A=>A.code==="RESERVED_ID"&&A.source!=="bundled").map(A=>A.relativePath)),w=new Set(o?.reservedAppIds??[]);for(let A of a){let h=Il(A);if(!(x.has(A.packageRoot)||b.has(A.packageRoot))){if(w.has(h.appId)){s.push(Z("RESERVED_ID",A.source,A.packageRoot,h.appId));continue}U.push({packageRoot:h.packageRoot,source:h.source,appId:h.appId,summary:h.summary});}}let V=[...Sl(i.diagnostics,new Set(a.map(A=>A.packageRoot))),...s,...n.registeredProductBundle?.diagnostics.filter(A=>A.source==="bundled").map(ys)??[]],N=[];if(t)for(let A of t.listMcpApps()){let h=El(A);"diagnostic"in h?V.push(h.diagnostic):N.push(h);}let D=Dl([...U,...N],V);Nl(D,n,V);let L=D.map(A=>A.summary).sort((A,h)=>_t(A.appId,h.appId)),I=[...V].sort((A,h)=>_t(A.relativePath,h.relativePath)||_t(A.code,h.code)||_t(A.appId??"",h.appId??""));return Object.freeze({items:Object.freeze(L),diagnostics:Object.freeze(I)})}m();m();m();function Ol(e){let n=o=>o.replace(/[.+^${}()|[\]\\]/g,"\\$&"),i=e.split("/").map(o=>o==="**"?".*":o.split("*").map(n).join("[^/]*"));return new RegExp(`^${i.join("\\/")}$`)}function un(e,n){try{return Ol(n).test(e)}catch{return false}}function bt(e,...n){let t=e.split("/");if(t.length<n.length)return false;let i=t.length-n.length;return n.every((o,r)=>un(t[i+r],o))}function Rl(e,n){return e.split("/").some(t=>un(t,n))}var Is=[{label:".env*",test:e=>un(e,".env*")},{label:".git/",test:(e,n,t)=>t&&e===".git"},{label:"memory/",test:(e,n,t)=>t&&e==="memory"},{label:"*.key",test:e=>un(e,"*.key")},{label:"*.pem",test:e=>un(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&&bt(n,".crewx","threads")},{label:".crewx/crewx.db",test:(e,n,t)=>!t&&bt(n,".crewx","crewx.db")},{label:".crewx/*.log",test:(e,n,t)=>!t&&bt(n,".crewx","*.log")},{label:".crewx/publish/",test:(e,n,t)=>t&&bt(n,".crewx","publish")},{label:".crewx/",test:(e,n)=>Rl(n,".crewx")}];function fn(e,n,t){for(let i of Is)if(i.test(e,n,t))return i.label;return null}m();var we=class extends Error{constructor(t,i){super(`publish: [${t}]${i?` ${i}`:""}`);this.code=t;}code;name="PublishError"};function P(e,n){return new we(e,n)}function gs(e,n){if(!n||/[\\\u0000]/.test(n)||ce__namespace.posix.isAbsolute(n)||n.split("/").some(y=>!y||y==="."||y===".."))throw P("PACKAGE_PATH_TRAVERSAL","package root must be a safe workspace-relative path");let t=ce__namespace.resolve(e),i=ce__namespace.resolve(t,...n.split("/"));if(!i.startsWith(`${t}${ce__namespace.sep}`))throw P("PACKAGE_PATH_TRAVERSAL","package root escaped the workspace");function o(y,g){let _;try{_=ne__namespace.lstatSync(y);}catch{throw P("PACKAGE_FILE_INVALID",`package directory is missing: ${g}`)}if(_.isSymbolicLink())throw P("PACKAGE_SYMLINK",`symlink is not publishable: ${g}`);if(!_.isDirectory())throw P("PACKAGE_FILE_INVALID",`not a package directory: ${g}`)}o(t,".");let r=t,s="",a=null;for(let y of n.split("/"))r=ce__namespace.join(r,y),s=s?`${s}/${y}`:y,o(r,s),a??=fn(y,s,true);let c=[],d=[];function l(y,g){o(y,g);let _=ne__namespace.readdirSync(y,{withFileTypes:true});for(let T of _){let U=`${g}/${T.name}`,x=ce__namespace.join(y,T.name);if(T.isSymbolicLink())throw P("PACKAGE_SYMLINK",`symlink is not publishable: ${U}`);let b=fn(T.name,U,T.isDirectory());b?d.push({path:U,rule:b}):T.isDirectory()?l(x,U):T.isFile()&&c.push(U);}}a?d.push({path:n,rule:a}):l(i,n);let p=new TextEncoder,u=(y,g)=>Buffer.compare(p.encode(y),p.encode(g));return c.sort(u),d.sort((y,g)=>u(y.path,g.path)),{included:c,excluded:d}}function ms(e){let n=[],t=[];function i(o,r,s){let a;try{a=ne__namespace.readdirSync(o,{withFileTypes:!0});}catch{return}a.sort((c,d)=>c.name.localeCompare(d.name));for(let c of a){let d=r?`${r}/${c.name}`:c.name,l=ce__namespace.join(o,c.name);if(c.isSymbolicLink()){let p;try{p=ne__namespace.statSync(l);}catch{t.push({path:d,rule:"symlink"});continue}if(p.isDirectory()){t.push({path:d,rule:s??"symlink-dir"});continue}let u=s??fn(c.name,d,false);u?t.push({path:d,rule:u}):t.push({path:d,rule:"symlink"});continue}if(c.isDirectory()){let p=s??fn(c.name,d,true);i(l,d,p);continue}if(c.isFile()){let p=s??fn(c.name,d,false);p?t.push({path:d,rule:p}):n.push(d);}}}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}}m();var wl=[{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 Cl(e){return e.includes(0)}function Fi(e,n,t){let i=[];for(let o of n){let r=ce__namespace.join(e,o),s;try{let c=t?.get(o);s=c===void 0?ne__namespace.readFileSync(r):Buffer.from(c);}catch{continue}if(Cl(s))continue;s.toString("utf8").split(/\r\n|\r|\n/).forEach((c,d)=>{for(let{rule:l,regex:p}of wl)p.test(c)&&i.push({path:o,line:d+1,rule:l});});}return i}m();var Es=/^[a-z0-9-]+$/,Ul=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/,kl=/^[A-Za-z_][A-Za-z0-9_]*$/;function xl(e){let n=ce__namespace.join(e,"crewx.yaml");if(!ne__namespace.existsSync(n))return {};let t;try{t=Ts__namespace.load(ne__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 vl(e){return Vi__namespace.createHash("sha256").update(e).digest("hex")}function Ps(e){let n;try{n=ne__namespace.lstatSync(e);}catch{throw P("PACKAGE_FILE_INVALID",`file is not readable: ${ce__namespace.basename(e)}`)}if(n.isSymbolicLink())throw P("PACKAGE_SYMLINK","symlink content is not publishable");if(!n.isFile())throw P("PACKAGE_FILE_INVALID","only regular files are publishable");return Vi__namespace.createHash("sha256").update(new Uint8Array(ne__namespace.readFileSync(e))).digest("hex")}function jl(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 bs(e){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||ce__namespace.posix.isAbsolute(e)||e.split("/").some(n=>n===".."||n.length===0))throw P("PACKAGE_PATH_TRAVERSAL","manifest file path must be a non-empty POSIX relative path")}function Fl(e){if(!/^(?:apps|skills)\/[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(e))throw P("APP_PACKAGE_ROOT_INVALID","packageRoot must be apps/<safe-id> or skills/<safe-id>")}function Ns(e){if(!Ul.test(e))throw new Error(`publish: invalid version "${e}" \u2014 must be semver (e.g. 1.0.0)`)}function Ds(e,n,t={}){let i=xl(e),o=i.name??ce__namespace.basename(e);if(!Es.test(o))throw new Error(`publish: invalid name "${o}" \u2014 must match ${Es} (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");Ns(r);let s=Array.isArray(i.requiredEnv)?i.requiredEnv:[],a=[];for(let l of s){if(typeof l!="string"||!kl.test(l))throw new Error(`publish: requiredEnv must contain names only (no values), got "${String(l)}"`);a.push(l);}let c=n.map(l=>(bs(l),{path:l,sha256:Ps(ce__namespace.join(e,l))})).sort((l,p)=>l.path<p.path?-1:l.path>p.path?1:0),d={name:o,version:r,type:"template",description:i.description??"",files:c,requiredEnv:a};return i.crewxMinVersion&&(d.crewxMinVersion=i.crewxMinVersion),d}function Vl(e){let n=e.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"");if(!n)throw P("APP_PACKAGE_ROOT_INVALID","appId cannot produce a marketplace name");return n}function Ss(e,n){if(Fl(n.packageRoot),!n.version)throw new Error("publish: version is required for App publishing \u2014 pass opts.version");if(Ns(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 P("APP_UI_MANIFEST_INVALID","screen App manifests require definitionId");let s=n.includedFiles.includes(`${i}manifest.json`),a=n.includedFiles.includes(`${i}ui-plugin.json`);if(!s&&!a)throw P("APP_UI_MANIFEST_INVALID","screen App is missing manifest.json or ui-plugin.json");if(s&&!a)throw P("APP_UI_MANIFEST_INVALID","a manifest.json App must also ship a generated ui-plugin.json");if(!n.includedFiles.includes(`${i}ui/index.html`))throw P("APP_UI_MANIFEST_INVALID","screen App is missing ui/index.html")}if(t.includes("skill")&&!n.includedFiles.includes(`${i}SKILL.md`))throw P("APP_SKILL_MISSING","skill capability requires package-root SKILL.md");let o=new Set,r=n.includedFiles.map(s=>{if(bs(s),!s.startsWith(i))throw P("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?Ps(ce__namespace.join(e,s)):vl(a),...a===void 0?{}:{generated:true}}}).sort((s,a)=>jl(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:Vl(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:[]}}m();function Ms(e){return Vi__namespace.createHash("sha256").update(e).digest("hex")}function Cs(e,n){if(typeof n!="string"||n.length===0||n.includes("\\")||n.includes("\0")||ce__namespace.posix.isAbsolute(n)||n.split("/").some(o=>o===".."||o.length===0))throw P("PACKAGE_PATH_TRAVERSAL","archive paths must be non-empty POSIX relative paths");let t=ce__namespace.resolve(e),i=ce__namespace.resolve(t,...n.split("/"));if(i!==t&&!i.startsWith(`${t}${ce__namespace.sep}`))throw P("PACKAGE_PATH_TRAVERSAL","archive path escaped its root");return i}function Ls(e,n){let t=Cs(e,n),i;try{i=ne__namespace.lstatSync(t);}catch{throw P("PACKAGE_FILE_INVALID","manifest file is missing")}if(i.isSymbolicLink())throw P("PACKAGE_SYMLINK","symlink content is not publishable");if(!i.isFile())throw P("PACKAGE_FILE_INVALID","only regular files are publishable");return new Uint8Array(ne__namespace.readFileSync(t))}async function Us(e,n,t={}){let i=ce__namespace.join(e,".crewx","publish");ne__namespace.mkdirSync(i,{recursive:true});let o=ce__namespace.join(i,`${n.name}-${n.version}.tgz`),r=ce__namespace.join(i,`.${n.name}-${n.version}.${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}.tmp.tgz`),s=ne__namespace.mkdtempSync(ce__namespace.join(Os__namespace.tmpdir(),"crewx-publish-"));try{let a=new Set,c=[];for(let d of n.files){if(a.has(d.path))throw P("PACKAGE_PATH_TRAVERSAL","manifest contains duplicate file paths");a.add(d.path);let l=t.generatedFiles?.get(d.path);if(d.generated===!0&&l===void 0)throw P("PACKAGE_GENERATED_FILE_MISSING","generated manifest file bytes are missing");if(t.sourceFileHashes?.has(d.path)){let y=Ls(e,d.path);if(t.sourceFileHashes.get(d.path)!==Ms(y))throw P("PACKAGE_STAGED_BYTES_MISMATCH","workspace source changed before staging")}let p=l??Ls(e,d.path);if(Ms(p)!==d.sha256)throw P("PACKAGE_STAGED_BYTES_MISMATCH",`staged bytes differ for ${d.path}`);let u=Cs(s,d.path);ne__namespace.mkdirSync(ce__namespace.dirname(u),{recursive:!0}),ne__namespace.writeFileSync(u,new Uint8Array(p)),c.push(d.path);}ne__namespace.writeFileSync(ce__namespace.join(s,"manifest.json"),JSON.stringify(n,null,2)),await ws__namespace.create({gzip:!0,file:r,cwd:s,portable:!0,noMtime:!0},["manifest.json",...c]),ne__namespace.renameSync(r,o);}finally{try{ne__namespace.rmSync(r,{force:!0});}catch{}ne__namespace.rmSync(s,{recursive:true,force:true});}return o}m();m();var yn="/api/v1";var zl=201,$l=200,Gl=409,Bi=401,ks={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 Jl(){return process.env.WI013_FAKE_UPLOAD==="1"}function Wl(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 Kl(e){return e.replace(/\/+$/,"")}async function vn(e){try{return await e.json()}catch{return null}}function xs(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 Xl(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 Yl(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 vs(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(ks,r))continue;let s=r,a=s==="APP_NAME_CONFLICT"?`marketplace name is already in use: ${n}`:void 0;return P(ks[s],a)}}async function ql(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=Kl(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}${yn}/publisher/items`,{method:"POST",headers:{Authorization:`Bearer ${e.accessToken}`,"Content-Type":"application/json"},body:JSON.stringify({slug:i,displayName:i,description:e.manifest.description,type:e.manifest.type,version:e.manifest.version,accessPolicy:t,...s===void 0?{}:{appId:s}})});}catch{throw new Error("publish: [E_NETWORK] Submit request failed (network)")}let c=await vn(a),d=Xl(c),l=Yl(c),p=r&&l!==void 0?l:i,u;if(a.status===zl)u="created";else if(r&&a.status===$l){if(d===void 0)throw P("PUBLISH_CONTENT_ID_MISSING","App republish did not return an opaque contentId");u="existing";}else if(a.status===Gl){if(r)throw vs(c,i)??P("APP_NAME_CONFLICT",`marketplace name is already in use: ${i}`);u="existing";}else throw a.status===Bi?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 y="not-needed",g=null;if(u==="existing"&&!r){let D;try{D=await fetch(`${n}${yn}/publisher/items`,{method:"GET",headers:{Authorization:`Bearer ${e.accessToken}`}});}catch{throw new Error("publish: [E_NETWORK] Publisher items request failed (network)")}let L=await vn(D);if(D.status!==200)throw new Error(`publish: [E_HTTP] Publisher items request failed \u2014 HTTP ${D.status}`);let A=xs(L,"publisher items",D.status)?.items;if(!Array.isArray(A))throw new Error(`publish: [E_MALFORMED] Publisher items response is malformed (expected data.items[]) \u2014 HTTP ${D.status}`);let h=A.find(E=>!E||typeof E!="object"?false:E.slug===i);if(!h||typeof h.version!="string")throw new Error(`publish: [E_MALFORMED] Publisher items response does not contain slug "${i}" \u2014 HTTP ${D.status}`);if(g=h.version,g!==e.manifest.version){let E;try{E=await fetch(`${n}${yn}/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 vn(E),E.status===Bi?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}`);y="applied";}}let _=ne__namespace.readFileSync(e.tgzPath),T=Jl()?Wl(_):_,U=new FormData;U.set("archive",new Blob([new Uint8Array(T)],{type:"application/gzip"}),`${p}-${e.manifest.version}.tgz`);let x=r&&d!==void 0?d:i,b;try{b=await fetch(`${n}${yn}/publisher/items/${encodeURIComponent(x)}/upload`,{method:"POST",headers:{Authorization:`Bearer ${e.accessToken}`},body:U});}catch{throw new Error("publish: [E_NETWORK] Upload request failed (network)")}if(b.status===Bi)throw new Error("publish: [E_AUTH_EXPIRED] Authentication is expired or missing \u2014 please log in again (HTTP 401)");if(!b.ok){let D=await vn(b);if(r){let L=vs(D,p);if(L)throw L}throw new Error(`publish: [E_HTTP] Upload request failed \u2014 HTTP ${b.status}`)}let w=await vn(b),V=xs(w,"upload",b.status),N=typeof V.contentId=="string"&&V.contentId.length>0?V.contentId:d;if(r&&N===void 0)throw P("PUBLISH_CONTENT_ID_MISSING","App upload did not return an opaque contentId");return {slug:p,version:e.manifest.version,...N===void 0?{}:{contentId:N},artifactChecksum:V.artifactChecksum,artifactSizeBytes:V.artifactSizeBytes,submitOutcome:u,versionUpdate:y,serverVersionBefore:g}}var Zl=1e4,Ql=100*1024*1024;function Hi(e){return Vi__namespace.createHash("sha256").update(e).digest("hex")}function eu(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function He(e,n){if(!n||n.includes("\\")||n.includes("\0")||ce__namespace.posix.isAbsolute(n)||n.split("/").some(r=>r===".."||r.length===0))throw P("PACKAGE_PATH_TRAVERSAL","workspace file path is not a safe relative path");let t=ce__namespace.resolve(e,...n.split("/")),i=ce__namespace.resolve(e);if(t!==i&&!t.startsWith(`${i}${ce__namespace.sep}`))throw P("PACKAGE_PATH_TRAVERSAL","workspace file path escaped the workspace root");let o;try{o=ne__namespace.lstatSync(t);}catch{throw P("PACKAGE_FILE_INVALID",`workspace file is missing: ${n}`)}if(o.isSymbolicLink())throw P("PACKAGE_SYMLINK",`symlink is not publishable: ${n}`);if(!o.isFile())throw P("PACKAGE_FILE_INVALID",`not a regular file: ${n}`);return new Uint8Array(ne__namespace.readFileSync(t))}async function nu(e,n,t){let i=`${n}/${J}`;if(!t.includes(i))return [];let o={[J]:He(e,i)},r=`${n}/${H}`;t.includes(r)&&(o[H]=He(e,r));let s=Fe(o,{mode:"local"});if(!s.ok)return [];let{diagnostics:a}=await _n(s.mcpb?.icon,async d=>{let l=`${n}/${d}`;return t.includes(l)?He(e,l):"missing"}),c=a.find(d=>d.code==="ICON_INVALID");if(c!==void 0)throw P("ICON_INVALID",`${c.reason??"invalid"} at ${c.declared??"icon"}`);return a.flatMap(d=>d.code==="ICON_INVALID"?[]:[{code:d.code,path:d.declared??"icon"}])}function Fs(e,n,t){let i=e??n;if(!Number.isSafeInteger(i)||i<=0)throw new we("PACKAGE_SIZE_LIMIT",`${t} must be a positive integer`);return i}function Bs(e,n,t,i){let o=Fs(t.maxFileCount??t.maxFiles,Zl,"max file count"),r=Fs(t.maxTotalBytes??t.maxBytes,Ql,"max total bytes");if(n.length>o)throw new we("PACKAGE_SIZE_LIMIT",`package exceeds file count limit (${o})`);let s=0;for(let a of n){let c=i?.get(a);if(c!==void 0?s+=c.byteLength:s+=He(e,a).byteLength,s>r)throw new we("PACKAGE_SIZE_LIMIT",`package exceeds byte limit (${r})`)}}function tu(e){return e.appId!==void 0||e.expectedDefinitionHash!==void 0}function iu(e){let n=e.appId!==void 0,t=e.expectedDefinitionHash!==void 0;if(!n&&t)throw P("APP_ID_REQUIRED","appId is required with expectedDefinitionHash");if(n&&!t)throw P("APP_DEFINITION_HASH_REQUIRED","expectedDefinitionHash is required with appId");if(!n||!t)throw P("APP_ID_REQUIRED")}function ou(e,n){let t=e.filter(i=>i.appId===n);if(t.length===0)throw P("APP_NOT_FOUND",`no publishable App matches ${n}`);if(t.length!==1)throw P("APP_AMBIGUOUS",`more than one App matches ${n}`);return t[0]}function ru(e){let n=e.localDefinitionRef?.packageRoot;if(!n||!/^(?:apps|skills)\/[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(n))throw P("APP_PACKAGE_ROOT_INVALID","selected App is not rooted in apps/<safe-id> or skills/<safe-id>");return n}function zi(e){let{path:n,rule:t}=e.reason;return `${e.code} at ${n===""?"<file>":n} (${t})`+(e.files.length>0?` [${e.files.join(", ")}]`:"")}function su(e,n,t){let i=Fe({[de]:t},{mode:"published"});if(!i.ok)throw P("APP_UI_MANIFEST_INVALID",`generated ${de} does not read: ${zi(i.rejection)}`);if(an(i.manifest)!==an(n))throw P("APP_UI_MANIFEST_INVALID",`generated ${de} normalizes to a different definition hash than the source`);let o=e[J];if(o===void 0)return;let r=e[H],s=Fe({[J]:o,[de]:t,...r===void 0?{}:{[H]:r}},{mode:"local"});if(!s.ok)throw P("APP_UI_MANIFEST_INVALID",zi(s.rejection))}function au(e,n,t,i){let o={};for(let y of Q){let g=`${t}/${y}`;i.includes(g)&&(o[y]=He(e,g));}let r=`${t}/${H}`;if(o[J]!==void 0&&i.includes(r)&&(o[H]=He(e,r)),Object.keys(o).length===0)throw P("APP_UI_MANIFEST_INVALID","selected screen App has no package manifest.json or ui-plugin.json");let s=Fe(o,{mode:"local"});if(!s.ok)throw P("APP_UI_MANIFEST_INVALID",zi(s.rejection));if(s.manifest.pluginId!==n.appId)throw P("APP_DEFINITION_CONFLICT",`${s.file} identity no longer matches the selected App`);let a=o[de],c=a===void 0?void 0:Hi(a),d=`${t}/ui/index.html`;if(!i.includes(d))throw P("APP_UI_MANIFEST_INVALID","screen entry is outside package scope");let l=Hi(He(e,d)),p=JSON.parse(JSON.stringify(s.v2Input));if(p.entryHash=l,Object.prototype.hasOwnProperty.call(p,"initialState")){let y=p.initialState;if(!eu(y)||y.path!=="ui/state.json")throw P("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 P("APP_INITIAL_STATE_OUT_OF_SCOPE","initialState reference is outside the selected package");let _=He(e,g);p.initialState={...y,hash:Hi(_)};}let u;try{let y=Je(p,{mode:"published"});u=new Uint8Array(Buffer.from(JSON.stringify(y),"utf8"));}catch(y){throw y instanceof ae?P("APP_UI_MANIFEST_INVALID",y.code):P("APP_UI_MANIFEST_INVALID")}return su(o,s.manifest,u),{bytes:u,...c===void 0?{}:{legacySourceHash:c}}}async function cu(e,n){let{included:t,excluded:i}=ms(e);Bs(e,t,n);let o=Ds(e,t,{version:n.version}),r=Fi(e,t);return {plan:{manifest:o,included:t,excluded:i,secretFindings:r},archiveOptions:{}}}async function du(e,n){iu(n);let t=await As(e),i=ou(t.items,n.appId);if(i.definitionHash!==n.expectedDefinitionHash)throw P("APP_DEFINITION_CONFLICT",`definitionHash changed for ${n.appId}`);let o=ru(i),{included:r,excluded:s}=gs(e,o),a=await nu(e,o,r),c=new Map,d=new Map;if(i.capabilities.includes("screen")){let y=au(e,i,o,r),g=`${o}/${de}`;if(c.set(g,y.bytes),y.legacySourceHash!==void 0)d.set(g,y.legacySourceHash);else {r.push(g);let _=new TextEncoder;r.sort((T,U)=>Buffer.compare(_.encode(T),_.encode(U)));}}if(i.capabilities.includes("skill")&&!r.includes(`${o}/SKILL.md`))throw P("APP_SKILL_MISSING","skill capability requires package-root SKILL.md");Bs(e,r,n,c);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:r,generatedFiles:c},p=Ss(e,l),u=Fi(e,r,c);return {plan:{manifest:p,included:r,excluded:s,secretFindings:u,warnings:a},archiveOptions:{generatedFiles:c,sourceFileHashes:d}}}async function Hs(e,n){let t=ce__namespace.resolve(e);if(tu(n))return du(t,n);if(n.expectedDefinitionHash!==void 0)throw P("APP_ID_REQUIRED");return cu(t,n)}async function EI(e,n={}){return (await Hs(e,n)).plan}function pu(e){let n=e.map(t=>`${t.path}:${t.line} (${t.rule})`).join(", ");throw new we("PUBLISH_SECRET_FINDINGS",`aborted \u2014 secret findings must be resolved before packing: ${n}`)}async function zs(e,n={}){let t=ce__namespace.resolve(e),i=await Hs(t,n);i.plan.secretFindings.length>0&&pu(i.plan.secretFindings);let o=await Us(t,i.plan.manifest,i.archiveOptions);return {manifest:i.plan.manifest,tgzPath:o}}async function TI(e,n={}){return zs(e,n)}async function PI(e,n){let t=await zs(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=Ql;exports.DEFAULT_PUBLISH_MAX_FILES=Zl;exports.EXCLUDE_RULES=Is;exports.MARKETPLACE_API_PREFIX=yn;exports.PublishError=we;exports.packApp=PI;exports.packPublish=zs;exports.packTemplate=TI;exports.planPublish=EI;exports.uploadToMarketplace=ql;
|