@crewx/sdk 0.9.0-rc.159 → 0.9.0-rc.160
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/context-budget/continuity.d.ts +2 -0
- package/dist/context-budget/index.d.ts +2 -1
- package/dist/conversation/types.d.ts +10 -0
- package/dist/esm/index.js +310 -326
- package/dist/esm/plugins/index.js +84 -84
- package/dist/esm/publish/index.js +2 -2
- package/dist/esm/repository/index.js +173 -173
- package/dist/esm/skills/index.js +2 -2
- package/dist/events/types.d.ts +7 -0
- package/dist/facade/Crewx.d.ts +2 -1
- package/dist/index.browser.d.ts +2 -0
- package/dist/index.browser.js +4 -4
- package/dist/index.d.ts +5 -4
- package/dist/index.js +237 -253
- package/dist/mcp-app/app-handoff.d.ts +109 -0
- package/dist/mcp-app/apps-context.d.ts +13 -1
- package/dist/mcp-app/card-handler.d.ts +7 -0
- package/dist/mcp-app/index.d.ts +5 -1
- package/dist/mcp-app/prompt-cards.d.ts +28 -0
- package/dist/mcp-app/types.d.ts +16 -0
- package/dist/mcp-app/workspace-snapshot.d.ts +1 -0
- package/dist/migrations/0040_task_provider_inputs.sql +53 -0
- package/dist/migrations/meta/0040_snapshot.json +3759 -0
- package/dist/migrations/meta/_journal.json +7 -0
- package/dist/plugins/index.js +84 -84
- package/dist/publish/index.js +2 -2
- package/dist/repository/index.d.ts +2 -1
- package/dist/repository/index.js +130 -130
- package/dist/repository/task.repository.d.ts +26 -1
- package/dist/schema/index.d.ts +1 -0
- package/dist/schema/task-provider-inputs.d.ts +100 -0
- package/dist/schema/tasks.d.ts +855 -1
- package/dist/skills/index.js +2 -2
- package/dist/template/helpers/format-conversation.d.ts +1 -0
- package/dist/types/index.d.ts +4 -0
- package/package.json +1 -1
- package/templates/agents/default.yaml +8 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import*as ce from'path';import {resolve,relative,sep,isAbsolute,join}from'path';import'url';import*as bi from'crypto';import {createHash}from'crypto';import {isIP}from'net';import*as ne from'fs';import {constants,readFileSync,existsSync,statSync,readdirSync}from'fs';import {realpath,stat,readdir,open,lstat}from'fs/promises';import*as Yr from'js-yaml';import {load}from'js-yaml';import*as os from'os';import*as ss from'tar';import {gunzipSync,gzipSync}from'zlib';var B=(e,n)=>()=>(e&&(n=e(e=0)),n);var m=B(()=>{});var x,kn=B(()=>{m();x=class extends Error{constructor(t,i=t,o){super(i);this.code=t;this.currentRevision=o;}code;currentRevision;name="UiRuntimeError"};});function ht(e){return hs.test(e)||_s.test(e)}function fe(){throw new x("INPUT_INVALID","JSON value is not projection-safe")}function Ns(e){let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function gt(e,n,t,i,o,r){if(n>i&&fe(),e===null||typeof e=="string"||typeof e=="boolean")return typeof e=="string"&&(Es.test(e)||Ps.test(e)&&!Ss(o,r)||Ts.test(e))&&fe(),e;if(typeof e=="number")return Number.isFinite(e)||fe(),e;(typeof e!="object"||e===void 0||typeof e=="function"||typeof e=="bigint")&&fe();let s=e;t.has(s)&&fe(),t.add(s);try{if(Array.isArray(e))return e.map(c=>gt(c,n+1,t,i,o,r));Ns(s)||fe();let a={};for(let[c,d]of Object.entries(e))ht(c)&&fe(),a[c]=gt(d,n+1,t,i,[...o,c],r);return a}finally{t.delete(s);}}function ye(e,n=0,t=[]){(!Number.isInteger(n)||n<0||n>bs)&&fe(),(!Array.isArray(t)||t.some(o=>typeof o!="string"))&&fe();let i=gt(e,0,new Set,Ds+n,[],t);return (i===null||Array.isArray(i)||typeof i!="object")&&fe(),i}function Ze(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 Ss(e,n){if(e.length===0)return false;let t=e.join(".");return n.some(i=>Ze(t,i))}function Qe(e){try{let n=JSON.stringify(e);return n===void 0&&fe(),n}catch{fe();}}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 Qe(mt(e))}function _t(e){return Buffer.byteLength(e,"utf8")}var hs,_s,Es,Ts,Ps,Ds,bs,Le=B(()=>{m();kn();hs=/(?:proof|token|secret|password|cookie|authorization|private[_-]?key|stack|exception|plugin[_-]?text)/i,_s=/(?:url|uri|endpoint|path|file(?:name|path)?|cwd|shell|directory|dir|folder)$/i,Es=/<\/?[A-Za-z][^>]*>/,Ts=/^(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)/,Ps=/^(?:https?|file|ftp|ws|wss):\/\//i;Ds=8,bs=4;});var Ri=B(()=>{m();Le();});var xn,Et=B(()=>{m();xn=["text/plain","application/json"];});var Oi=B(()=>{m();Et();});function en(e){return Ls.has(e)||Rs.test(e)||Os.test(e)}var wi,Ls,Rs,Os,vn,An,Te,Tt,Pt,Nt,Dt,bt,Be=B(()=>{m();wi=["__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"],Ls=new Set(wi),Rs=/(?:proof|token|secret|password|cookie|authorization|private[_-]?key|stack|exception|plugin[_-]?text)/i,Os=/(?: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_]+)*$/,Te=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,Tt=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/,Pt=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,Nt=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/,Dt=["blue","violet","emerald","amber","rose","sky","slate","indigo"],bt=["inline","panel"];});function St(e){return typeof e=="string"&&xn.includes(e)}var Ci=B(()=>{m();Et();Be();});function jn(e){if(!Mt(e))return false;let n=Object.keys(e);return !(n.some(t=>t!=="in"&&t!=="out")||n.length===0||Object.hasOwn(e,"in")&&!ws(e.in)||Object.hasOwn(e,"out")&&!Cs(e.out))}function ws(e){return Mt(e)?Object.keys(e).every(t=>t==="mediaType"||t==="required")&&Object.hasOwn(e,"mediaType")&&St(e.mediaType)&&(!Object.hasOwn(e,"required")||typeof e.required=="boolean"):false}function Cs(e){return Mt(e)?Object.keys(e).every(t=>t==="mediaType"||t==="range")&&Object.hasOwn(e,"mediaType")&&St(e.mediaType)&&(!Object.hasOwn(e,"range")||typeof e.range=="boolean"):false}function Mt(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}var Lt=B(()=>{m();Oi();Ci();new TextDecoder("utf-8",{fatal:true,ignoreBOM:true});});function le(e){let t=e.renderer!==void 0||e.surfaces!==void 0||e.stateProjection!==void 0||e.dataPaths!==void 0||e.usage!==void 0||e.detailPanel!==void 0||e.displayModes!==void 0||e.summaryProjection!==void 0||e.legacy!==void 0||Object.values(e.actions).some(o=>o.resultProjection!==void 0)?{id:e.id,version:e.version,...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=ye(t);return createHash("sha256").update(te(i)).digest("hex")}function Ot(e){return `${e.id}\0${e.version}`}function Ae(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"||!ks.test(e.sourceHash)))throw new x("DEFINITION_UNSUPPORTED","UI definition source hash is invalid");if(!/^[0-9a-f]{64}$/.test(e.hash)||le(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=>!vs(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&&Rt(t.resultProjection),t.content!==void 0&&!jn(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&&Rt(e.stateProjection),e.summaryProjection){Rt(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(xs(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=>Ze(t,i))))throw new x("DEFINITION_UNSUPPORTED","UI definition dataPaths are invalid")}}function xs(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=ye(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=ye(a.structuredContent);if(_t(Qe(c))>4*1024)throw new Error("fixed result size")}}catch{throw new x("DEFINITION_UNSUPPORTED","UI legacy tool metadata is not projection-safe")}}function Rt(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 vs(e){return e.length>0&&e.length<=128&&e!=="*"&&e!=="all"&&!/[/*]/.test(e)}var ks,He=B(()=>{m();Le();kn();Lt();ks=/^[0-9a-f]{64}$/;});var H,nn,wt=B(()=>{m();H="dist/tools.json",nn="dist/main.mjs";});var xe,Ct=B(()=>{m();xe="window";});function Ui(e){if(!Array.isArray(e)||e.length===0)return false;let n=new Set;for(let t of e){if(!js.some(i=>i===t)||n.has(t))return false;n.add(t);}return true}var js,ki=B(()=>{m();js=["CREWX_APP_INSTANCE_ID","CREWX_THREAD_ID"];});function z(e){throw new Ut(e)}function Ys(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 qs(e,n){let t=Object.getOwnPropertyDescriptor(e,n);return (!t||!("value"in t))&&z("CSP_ORIGIN_INVALID"),t.value}function Fn(e,n){if(!Object.prototype.hasOwnProperty.call(e,n))return [];let t=qs(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 Zs(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 ji(e,n){/\s|\\/u.test(e)&&z("CSP_ORIGIN_INVALID");let t=Gs.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("[")?Ws:Js).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||!Ks.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 Qs(e){let n=e.split(".").map(Number);return ((n[0]*256+n[1])*256+n[2])*256+n[3]}function Fi(e,n,t){let i=4294967295<<32-t>>>0;return (e&i)===(n&i)}function Hi(e){let n=Qs(e);return Fi(n,3221225472,24)?n!==3221225481&&n!==3221225482:Xs.some(([t,i])=>Fi(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 na(e){let n=ea(e),t=Number(n>>112n),i=Number(n>>96n&0xffffn);if(n>>32n===0xffffn){let o=Number(n&0xffffffffn);return Hi([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 ta(e,n){let t=e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e,i=isIP(t);if(i===4)return Hi(t);if(i===6)return na(t);let o=e.toLowerCase().replace(/\.$/,"");return !o||!o.includes(".")||n.has(o)?true:$s.some(r=>o===r||o.endsWith(`.${r}`))}function Vi(e){return Object.freeze([...new Set(e.map(n=>n.origin))].sort())}function Bi(e){return JSON.stringify({baseUriDomains:[],connectDomains:e.connectDomains,declared:e.declared,frameDomains:e.frameDomains,resourceDomains:[]})}function zi(e,n={}){if(e===void 0){let f=Bi({declared:false,connectDomains:[],frameDomains:[]});return Object.freeze({declared:false,connectDomains:Object.freeze([]),frameDomains:Object.freeze([]),resourceDomains:Object.freeze([]),baseUriDomains:Object.freeze([]),cspHash:createHash("sha256").update(f,"utf8").digest("hex")})}Ys(e)||z("CSP_ORIGIN_INVALID");let t=Reflect.ownKeys(e);t.some(f=>typeof f!="string")&&z("CSP_ORIGIN_INVALID"),t.some(f=>!zs.has(f))&&z("CSP_AXIS_UNKNOWN");let i=Fn(e,"connectDomains"),o=Fn(e,"frameDomains"),r=Fn(e,"resourceDomains"),s=Fn(e,"baseUriDomains");(r.length>0||s.length>0)&&z("CSP_AXIS_UNSUPPORTED"),(Zs(e)>Vs||i.length>vi||o.length>vi||i.length+o.length>Bs||[...i,...o].some(f=>new TextEncoder().encode(f).byteLength>Hs))&&z("CSP_LIMIT_EXCEEDED");let c=i.map(f=>ji(f,"connectDomains")),d=o.map(f=>ji(f,"frameDomains")),l=new Set((n.runtimeHostnames??[]).map(f=>f.toLowerCase().replace(/\.$/,"")));[...c,...d].some(f=>ta(f.hostname,l))&&z("CSP_ORIGIN_FORBIDDEN");let p={declared:true,connectDomains:Vi(c),frameDomains:Vi(d)},u=Bi(p);return Object.freeze({...p,resourceDomains:Object.freeze([]),baseUriDomains:Object.freeze([]),cspHash:createHash("sha256").update(u,"utf8").digest("hex")})}var Vs,vi,Bs,Hs,zs,$s,Gs,Ws,Js,Ks,Xs,Ut,$i=B(()=>{m();Vs=4096,vi=16,Bs=32,Hs=512,zs=new Set(["connectDomains","frameDomains","resourceDomains","baseUriDomains"]),$s=["localhost","local","internal","home.arpa","test","example","invalid","onion","lan","corp","home","intranet","private","localdomain"],Gs=/^(https|wss):\/\/([^/?#]+)$/i,Ws=/^\[[^\]]+\](?::[0-9]+)?$/,Js=/^[^:\[\]]+(?::[0-9]+)?$/,Ks=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/,Xs=[[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]],Ut=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 A(e,n=e,t,i){throw new se(e,n,t,i)}function $(e,n){try{return n()}catch(t){throw t instanceof se?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 v(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function Ra(e,n){let t={};for(let[i,o]of Object.entries(e))i!==n&&(t[i]=o);return t}function X(e,n,t=[]){let i=new Set([...n,...t]),o=Object.keys(e).find(s=>!i.has(s));o!==void 0&&A("MANIFEST_INVALID","MANIFEST_INVALID",o,"unknown-key");let r=n.find(s=>!v(e,s));r!==void 0&&A("MANIFEST_INVALID","MANIFEST_INVALID",r,"missing-key");}function zn(e,n=false,t=false,i=false){return sa.test(e)||!i&&ca.test(e)||aa.test(e)||t&&Gi.test(e)||da.test(e)&&!(n&&/^\s*data:/i.test(e)&&!Gi.test(e))}function Hn(e,n=new Set,t=0,i=false,o=false,r=""){if(typeof e=="string"){zn(e,i,o)&&A("UNSAFE_VALUE","UNSAFE_VALUE",r,"unsafe-value");return}if(!(e===null||typeof e!="object")){(t>8||n.has(e))&&A("MANIFEST_INVALID","MANIFEST_INVALID",r),n.add(e);try{if(Array.isArray(e)){e.forEach((s,a)=>Hn(s,n,t+1,!1,!1,gn(r,`[${a}]`)));return}G(e)||A("MANIFEST_INVALID","MANIFEST_INVALID",r);for(let[s,a]of Object.entries(e))Hn(a,n,t+1,i&&t===0&&(s==="name"||s==="description"),o,gn(r,s));}finally{n.delete(e);}}}function Pe(e,n){let t=e[n];return typeof t!="string"&&A("MANIFEST_INVALID"),t}function ge(e,n,t){let i=e[n];return (!Number.isSafeInteger(i)||i<t)&&A("MANIFEST_INVALID"),i}function kt(e){return ra.test(e)||A("MANIFEST_INVALID"),e}function tn(e){return oa.test(e)||A("TOKEN_INVALID"),e}function Oa(e){return eo.test(e)||A("MANIFEST_INVALID"),e}function wa(e){G(e)||A("MANIFEST_INVALID");let n={};for(let[t,i]of Object.entries(e)){let o=Oa(t);G(i)||A("MANIFEST_INVALID");let r=i.type;if(r==="text"){X(i,["type","maxLength"]),n[o]={type:r,maxLength:ge(i,"maxLength",1)};continue}if(r==="text-list"){X(i,["type","max","itemMaxLength"]),n[o]={type:r,max:ge(i,"max",0),itemMaxLength:ge(i,"itemMaxLength",1)};continue}if(r==="step-list"){X(i,["type","min","max","labelMaxLength","detailMaxLength"]);let s=ge(i,"min",0),a=ge(i,"max",1);s>a&&A("MANIFEST_INVALID"),n[o]={type:r,min:s,max:a,labelMaxLength:ge(i,"labelMaxLength",1),detailMaxLength:ge(i,"detailMaxLength",1)};continue}typeof r=="string"&&A("SCHEMA_TYPE_UNSUPPORTED"),A("MANIFEST_INVALID");}return n}function Ca(e,n,t){let i=e[n];(!i||i.type!==t)&&A("MANIFEST_INVALID");}function Vn(e,n,t){let i=Pe(e,"field");return eo.test(i)||A("MANIFEST_INVALID"),Ca(n,i,t),i}function Ua(e,n){G(e)||A("MANIFEST_INVALID");let t=e.primitive;switch(typeof t!="string"&&A("MANIFEST_INVALID"),La.includes(t)||A("PRIMITIVE_UNKNOWN"),t){case "card-shell":return X(e,["primitive"]),{primitive:t};case "meta-banner":return X(e,["primitive","badgeToken","noticeToken"]),{primitive:t,badgeToken:tn(Pe(e,"badgeToken")),noticeToken:tn(Pe(e,"noticeToken"))};case "heading":return X(e,["primitive","field"]),{primitive:t,field:Vn(e,n,"text")};case "labeled-text":return X(e,["primitive","titleToken","field","variant"]),e.variant!=="callout"&&A("MANIFEST_INVALID"),{primitive:t,titleToken:tn(Pe(e,"titleToken")),field:Vn(e,n,"text"),variant:"callout"};case "step-flow":return X(e,["primitive","titleToken","field"]),{primitive:t,titleToken:tn(Pe(e,"titleToken")),field:Vn(e,n,"step-list")};case "text-list":{X(e,["primitive","titleToken","field"],["emptyToken","hideWhenEmpty"]);let i={primitive:t,titleToken:tn(Pe(e,"titleToken")),field:Vn(e,n,"text-list")};return v(e,"emptyToken")&&(i.emptyToken=tn(Pe(e,"emptyToken"))),v(e,"hideWhenEmpty")&&(typeof e.hideWhenEmpty!="boolean"&&A("MANIFEST_INVALID"),i.hideWhenEmpty=e.hideWhenEmpty),i}}return A("MANIFEST_INVALID")}function ka(e,n){return Array.isArray(e)||A("MANIFEST_INVALID"),e.map(t=>Ua(t,n))}function Y(e="v2 manifest exceeds a contract limit",n,t){return A("LIMIT_EXCEEDED",e,n,t)}function Ie(e="initial state is not projection-safe"){return A("INITIAL_STATE_INVALID",e)}function Wi(e,n){return (typeof e!="string"||e.length===0||e.length>4096||e.trim().length===0||ba.test(e)||Sa.test(e))&&A("MANIFEST_INVALID",`${n} is invalid`),(zn(e,true,true)||pa.test(e)||la.test(e)||ua.test(e))&&A("UNSAFE_VALUE",`${n} contains an unsafe value`),e}function xt(e,n){return (typeof e!="string"||!Te.test(e))&&A("MANIFEST_INVALID",`${n} is invalid`),e}function xa(e){return (typeof e!="string"||!Tt.test(e)||e==="*"||e==="all")&&A("MANIFEST_INVALID","action capability is invalid"),e}function no(e){return (typeof e!="string"||!Da.test(e))&&A("MANIFEST_INVALID","resource hash is invalid"),e}function vt(e,n=new Set,t=0,i=""){if(typeof e=="string"){e.length>4096&&Y("v2 manifest string is too long",i,"string-too-long");return}if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){Number.isFinite(e)||A("MANIFEST_INVALID","v2 manifest contains a non-finite number",i,"non-finite-number");return}(e===void 0||typeof e=="function"||typeof e=="bigint")&&A("MANIFEST_INVALID","v2 manifest contains a non-JSON value",i,"non-json-value"),typeof e!="object"&&A("MANIFEST_INVALID","MANIFEST_INVALID",i),t>8&&Y("v2 manifest nesting is too deep",i,"too-deep"),n.has(e)&&A("MANIFEST_INVALID","v2 manifest contains a cycle",i,"cycle"),n.add(e);try{if(Array.isArray(e)){e.length>128&&Y("v2 manifest array is too long",i,"array-too-long"),e.forEach((o,r)=>vt(o,n,t+1,gn(i,`[${r}]`)));return}G(e)||A("MANIFEST_INVALID","v2 manifest contains a non-plain object",i,"non-plain-object");for(let[o,r]of Object.entries(e))vt(r,n,t+1,gn(i,o));}finally{n.delete(e);}}}function to(e){return (typeof e!="string"||e.length>4096||!An.test(e))&&(typeof e=="string"&&e.length>4096&&Y("projection path is too long"),A("MANIFEST_INVALID","projection paths must be canonical exact paths")),e.split(".").some(t=>en(t))&&A("MANIFEST_INVALID","projection paths cannot address reserved state keys"),e}function jt(e){G(e)||A("MANIFEST_INVALID","projection policy must be an object"),X(e,["allow"]),Array.isArray(e.allow)||A("MANIFEST_INVALID","projection allow must be an array"),e.allow.length>128&&Y("projection allowlist is too long");let n=[],t=new Set;for(let i of e.allow){let o=to(i);t.has(o)&&A("MANIFEST_INVALID","projection allowlist contains a duplicate path"),t.add(o),n.push(o);}return {allow:n}}function va(e,n){if(e===void 0)return;Array.isArray(e)||A("MANIFEST_INVALID","dataPaths must be an array"),e.length>Ma&&Y("dataPaths exceed the v2 limit");let t=[],i=new Set;for(let o of e){let r=to(o);i.has(r)&&A("MANIFEST_INVALID","dataPaths contain a duplicate path"),n.some(s=>Ze(r,s))||A("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)&&A("MANIFEST_INVALID",`${n} is invalid`),e}function Ji(e,n){return (typeof e!="number"||!Number.isFinite(e))&&A("MANIFEST_INVALID",`${n} is invalid`),e}function Ft(e,n=0,t=new Set){if(typeof e=="string")return (e.length>4096||zn(e))&&A("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)||A("MANIFEST_INVALID","schema enum contains a non-finite number"),e;(n>8||typeof e!="object"||e===void 0)&&Y("schema enum is too deep"),t.has(e)&&A("MANIFEST_INVALID","schema enum contains a cycle"),t.add(e);try{if(Array.isArray(e))return e.length>128&&Y("schema enum array is too long"),e.map(o=>Ft(o,n+1,t));G(e)||A("MANIFEST_INVALID","schema enum contains a non-plain object");let i={};for(let[o,r]of Object.entries(e))en(o)&&A("MANIFEST_INVALID","schema enum contains a reserved key"),i[o]=Ft(r,n+1,t);return i}finally{t.delete(e);}}function ja(e,n){if(e===void 0)return;Array.isArray(e)||A("MANIFEST_INVALID","schema required must be an array"),e.length>64&&Y("schema required list is too long");let t=[],i=new Set;for(let o of e)(typeof o!="string"||!An.test(o))&&A("MANIFEST_INVALID","schema required contains an invalid key"),o.length>4096&&Y("schema required key is too long"),i.has(o)&&A("MANIFEST_INVALID","schema required contains a duplicate key"),n&&!Object.prototype.hasOwnProperty.call(n,o)&&A("MANIFEST_INVALID","schema required references an undeclared property"),i.add(o),t.push(o);return t}function Fa(e,n){let t=n?An:vn;return e.length>4096&&Y("schema property name is too long"),(!t.test(e)||e.split(".").some(i=>en(i)))&&A("MANIFEST_INVALID","schema property name is invalid"),e}function Vt(e,n=0,t=false){G(e)||A("MANIFEST_INVALID","action inputSchema must be an object"),n>8&&Y("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"&&A("SCHEMA_TYPE_UNSUPPORTED","action inputSchema type is unsupported"),A("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"),X(e,["type"],o.filter(a=>a!=="type"));let r={type:i};if(v(e,"enum")&&(Array.isArray(e.enum)||A("MANIFEST_INVALID","schema enum must be an array"),e.enum.length>128&&Y("schema enum is too long"),r.enum=e.enum.map(a=>Ft(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&&A("MANIFEST_INVALID","schema string length bounds are inverted")),(i==="number"||i==="integer")&&(v(e,"minimum")&&(r.minimum=Ji(e.minimum,"schema minimum")),v(e,"maximum")&&(r.maximum=Ji(e.maximum,"schema maximum")),r.minimum!==void 0&&r.maximum!==void 0&&r.minimum>r.maximum&&A("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&&A("MANIFEST_INVALID","schema array length bounds are inverted"),v(e,"items")&&(r.items=Vt(e.items,n+1,false))),i==="object"){let a;if(v(e,"properties")){G(e.properties)||A("MANIFEST_INVALID","schema properties must be an object");let d=Object.entries(e.properties);d.length>64&&Y("schema properties are too many"),a={};for(let[l,p]of d){let u=Fa(l,t);a[u]=Vt(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&&A("MANIFEST_INVALID","schema object property bounds are inverted");let c=ja(e.required,a);c!==void 0&&(r.required=c),v(e,"additionalProperties")&&(e.additionalProperties!==false&&A("MANIFEST_INVALID","schema additionalProperties must be false"),r.additionalProperties=false);}let s=JSON.stringify(r);return (s===void 0||Buffer.byteLength(s,"utf8")>2097152)&&Y("action inputSchema subtree is too large"),r}function Va(e){let n=Vt(e,0,true);return (n.type!=="object"||!n.properties)&&A("MANIFEST_INVALID","action inputSchema must declare object properties"),n}function Ba(e){if(G(e)||A("MANIFEST_INVALID","action backend must be an object"),e.type==="core"){X(e,ha);let n=e.handler;return (typeof n!="string"||!Pt.test(n))&&A("MANIFEST_INVALID","core backend handler is invalid"),{type:"core",handler:n}}if(e.type==="skill"&&v(e,"entry"))return X(e,Ta),e.entry!==nn&&A("MANIFEST_INVALID",`skill backend entry must be ${nn}`),{type:"skill",entry:nn};if(e.type==="skill"){X(e,_a,Ea),(!Array.isArray(e.command)||e.command.length===0||e.command.length>16)&&A("MANIFEST_INVALID","skill backend command is invalid");let n=[];for(let i of e.command)(typeof i!="string"||i.length===0||i.length>256||!Nt.test(i))&&A("MANIFEST_INVALID","skill backend command token is invalid"),n.push(i);let t=v(e,"env")?za(e.env):void 0;return {type:"skill",command:n,...t===void 0?{}:{env:t}}}A("MANIFEST_INVALID","action backend type is unsupported");}function Ha(e){G(e)||A("MANIFEST_INVALID","action must be an object"),X(e,Ia,ga),v(e,"_meta")&&$("_meta",()=>io(e._meta));let n=$("actionId",()=>xt(e.actionId,"actionId"));ht(n)&&A("MANIFEST_INVALID",`actionId "${n}" is not projection-safe`,"actionId");let t=$("capability",()=>xa(e.capability)),i=e.mutation;typeof i!="boolean"&&A("MANIFEST_INVALID","action mutation must be boolean","mutation");let o=$("inputSchema",()=>Va(e.inputSchema)),r;if(v(e,"dataInputs")){Array.isArray(e.dataInputs)||A("MANIFEST_INVALID","action dataInputs must be an array","dataInputs");let l=o.properties,p=new Set,u=[];for(let f of e.dataInputs)(typeof f!="string"||!v(l,f)||p.has(f))&&A("MANIFEST_INVALID","action dataInputs must be unique declared properties","dataInputs"),p.add(f),u.push(f);r=u;}let s=$("resultProjection",()=>jt(e.resultProjection)),a=$("backend",()=>Ba(e.backend)),c;v(e,"content")&&((a.type!=="skill"||!jn(e.content))&&A("MANIFEST_INVALID","action content declaration is invalid","content"),c=$a(e.content));let d;if(v(e,"confirmation")){let l=e.confirmation;l!=="none"&&l!=="native"&&A("MANIFEST_INVALID","action confirmation is invalid","confirmation"),d=l;}return {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}}}function za(e){return Ui(e)||A("MANIFEST_INVALID","skill backend env is invalid"),Object.freeze([...e])}function $a(e){return Object.freeze({...e.in===void 0?{}:{in:Object.freeze({...e.in})},...e.out===void 0?{}:{out:Object.freeze({...e.out})}})}function Ga(e){return G(e)||A("INITIAL_STATE_INVALID","initialState must be an object"),X(e,Pa,Na),e.path!=="ui/state.json"&&A("MANIFEST_INVALID","initialState path is not fixed"),v(e,"hash")?{path:"ui/state.json",hash:no(e.hash)}:{path:"ui/state.json"}}function Wa(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))&&A("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 Ja(e,n){let t;try{t=zi(e);}catch(i){let o=i!==null&&typeof i=="object"&&"code"in i&&typeof i.code=="string"?i.code:"CSP_ORIGIN_INVALID";return A("MANIFEST_INVALID",o,void 0,o.toLowerCase().replace(/_/g,"-"))}if(t.frameDomains.length>0&&A("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&&A("MANIFEST_INVALID","runtime.terminal cannot be combined with csp.connectDomains","connectDomains","terminal-with-connect-domains"),Object.freeze({connectDomains:t.connectDomains})}function Ka(e,n){Hn(G(e)&&v(e,"csp")?Ra(e,"csp"):e,new Set,0,true,true),vt(e),G(e)||A("MANIFEST_INVALID"),X(e,ya,Aa),v(e,"_meta")&&$("_meta",()=>io(e._meta)),e.manifestVersion!==2&&A("MANIFEST_INVALID");let t;v(e,"runtime")&&(t=$("runtime",()=>Wa(e.runtime)));let i;v(e,"csp")&&(i=$("csp",()=>Ja(e.csp,t)));let o=$("pluginId",()=>xt(e.pluginId,"pluginId")),r=$("definitionId",()=>xt(e.definitionId,"definitionId")),s=$("version",()=>ge(e,"version",1)),a=$("name",()=>Wi(e.name,"name")),c=$("description",()=>Wi(e.description,"description")),d;v(e,"icon")&&((typeof e.icon!="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(e.icon))&&A("MANIFEST_INVALID","icon is invalid","icon"),d=e.icon);let l;v(e,"tone")&&((typeof e.tone!="string"||!Dt.includes(e.tone))&&A("MANIFEST_INVALID","tone is invalid","tone"),l=e.tone),e.entry!=="ui/index.html"&&A("MANIFEST_INVALID","entry path is not fixed","entry","fixed-value");let p;v(e,"entryHash")&&(p=$("entryHash",()=>no(e.entryHash)));let u;v(e,"initialState")&&(u=$("initialState",()=>Ga(e.initialState)));let f;v(e,"usage")&&(e.usage!=="card"&&e.usage!=="window"&&A("MANIFEST_INVALID","usage is invalid","usage"),f=e.usage);let g;v(e,"detailPanel")&&(typeof e.detailPanel!="boolean"&&A("MANIFEST_INVALID","detailPanel is invalid","detailPanel"),g=e.detailPanel);let _;if(v(e,"displayModes")){((f??xe)!==xe||!Array.isArray(e.displayModes)||e.displayModes.length===0)&&A("MANIFEST_INVALID","displayModes are only valid for window Apps","displayModes");let y=new Set(["inline","floating","focused"]);(new Set(e.displayModes).size!==e.displayModes.length||e.displayModes.some(I=>typeof I!="string"||!y.has(I)))&&A("MANIFEST_INVALID","displayModes are invalid","displayModes"),_=e.displayModes;}(f??xe)===xe&&g!==void 0&&A("MANIFEST_INVALID","detailPanel is card-only","detailPanel");let P=n.mode??"local";P!=="local"&&P!=="installed"&&P!=="published"&&A("MANIFEST_INVALID","manifest mode is invalid"),P!=="local"&&p===void 0&&A("MANIFEST_INVALID","installed manifests require entryHash","entryHash","required-when-installed"),P!=="local"&&u!==void 0&&u.hash===void 0&&A("MANIFEST_INVALID","installed manifests require initialState.hash","initialState.hash","required-when-installed"),(!Array.isArray(e.surfaces)||e.surfaces.length===0)&&A("MANIFEST_INVALID","surfaces are invalid","surfaces"),e.surfaces.length>2&&Y("surfaces exceed the v2 limit","surfaces","too-many-items");let U=[],k=new Set;for(let y of e.surfaces)(typeof y!="string"||!bt.includes(y))&&A("MANIFEST_INVALID","surface is unsupported","surfaces"),k.has(y)&&A("MANIFEST_INVALID","surfaces contain a duplicate","surfaces","duplicate-item"),k.add(y),U.push(y);G(e.size)||A("MANIFEST_INVALID","size must be an object","size"),$("size",()=>X(e.size,["height"]));let N=$("size",()=>ge(e.size,"height",1));N>720&&Y("size.height exceeds the v2 limit","size.height","too-large");let C=$("stateProjection",()=>jt(e.stateProjection)),F=e.summaryProjection===void 0?void 0:$("summaryProjection",()=>jt(e.summaryProjection));F!==void 0&&F.allow.some(y=>!C.allow.includes(y))&&A("MANIFEST_INVALID","summaryProjection must be a subset of stateProjection.allow","summaryProjection");let D=$("dataPaths",()=>va(e.dataPaths,C.allow));Array.isArray(e.actions)||A("MANIFEST_INVALID","actions must be an array","actions"),e.actions.length>32&&Y("actions exceed the v2 limit","actions","too-many-items");let b=[],R=new Set;for(let[y,I]of e.actions.entries()){let h=`actions[${y}]`,E=$(h,()=>Ha(I));if(R.has(E.actionId)&&A("MANIFEST_INVALID","actions contain a duplicate actionId",`${h}.actionId`,"duplicate-item"),E.backend.type==="core"&&E.backend.handler==="state.set"){E.mutation||A("MANIFEST_INVALID","state.set actions must be mutations",`${h}.mutation`);for(let L of Object.keys(E.inputSchema.properties))C.allow.includes(L)||A("MANIFEST_INVALID","state.set input paths must be projection-allowed",`${h}.inputSchema.properties`);}R.add(E.actionId),b.push(E);}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:U,size:{height:N},stateProjection:C,...F===void 0?{}:{summaryProjection:F},...D===void 0?{}:{dataPaths:D},actions:b}}function io(e){G(e)||A("MANIFEST_INVALID","_meta must be an object");let n=JSON.stringify(e);(n===void 0||Buffer.byteLength(n,"utf8")>ma)&&Y("_meta exceeds the 4 KiB limit",void 0,"meta-too-large");}function Xa(e){let n={},t={};for(let r of e.actions){n[r.actionId]={capabilities:[r.capability],inputKeys:Object.keys(r.inputSchema.properties??{}),...r.dataInputs===void 0?{}:{dataInputs:r.dataInputs},resultProjection:r.resultProjection,...r.confirmation===void 0?{}:{confirmation:r.confirmation},...r.content===void 0?{}:{content:r.content},...r.backend.type!=="skill"||r.backend.env===void 0?{}:{env:r.backend.env}};let s=r.backend.type==="skill"||r.backend.type==="core"&&r.backend.handler==="state.set";t[r.actionId]={actionId:r.actionId,mutation:r.mutation,backend:r.backend,launchPolicy:s?"allowed":"denied",...s?{}:{denialCode:"EXEC_DENIED"}};}let i={id:e.definitionId,version:e.version,renderer:"sandbox-html",...e.usage===void 0?{}:{usage:e.usage},...e.detailPanel===void 0?{}:{detailPanel:e.detailPanel},...e.displayModes===void 0?{}:{displayModes:e.displayModes},surfaces:e.surfaces,stateProjection:e.stateProjection,...e.summaryProjection===void 0?{}:{summaryProjection:e.summaryProjection},...e.dataPaths===void 0?{}:{dataPaths:e.dataPaths},actions:n},o={entry:{path:"ui/index.html",...e.entryHash===void 0?{}:{hash:e.entryHash}},...e.initialState===void 0?{}:{initialState:e.initialState}};return {manifest:e,definition:i,handlers:t,resources:o}}function Bt(e,n,t,i,o,r){if(typeof e=="string"){let s=o.length>0&&r.some(a=>Ze(o.join("."),a));return (e.length>4096||zn(e,false,false,s))&&Ie("state contains an unsafe string"),e}if(e===null||typeof e=="boolean")return e;if(typeof e=="number")return Number.isFinite(e)||Ie("state contains a non-finite number"),e;(e===void 0||typeof e!="object"||typeof e=="function"||typeof e=="bigint")&&Ie("state contains a non-JSON value"),t>8&&Ie("state is too deep"),n.has(e)&&Ie("state contains a cycle"),n.add(e);try{let s;if(Array.isArray(e))e.length>128&&Ie("state array is too long"),s=e.map(c=>Bt(c,n,t+1,2097152,o,r));else {G(e)||Ie("state contains a non-plain object");let c={};for(let[d,l]of Object.entries(e))(d.length>4096||!vn.test(d)||en(d))&&(d.length>4096&&Ie("state key is too long"),Ie("state contains a reserved or invalid key")),c[d]=Bt(l,n,t+1,2097152,[...o,d],r);s=c;}let a=JSON.stringify(s);return (a===void 0||Buffer.byteLength(a,"utf8")>i)&&Ie("state subtree is too large"),s}finally{n.delete(e);}}function zt(e,n=[]){G(e)||Ie("initial state must be a JSON object");let t=Bt(e,new Set,0,2097152,[],n);return (t===null||Array.isArray(t)||typeof t!="object")&&Ie(),t}function Ya(e,n={}){Hn(e),G(e)||A("MANIFEST_INVALID"),X(e,fa),e.manifestVersion!==1&&A("MANIFEST_INVALID");let t=kt(Pe(e,"pluginId")),i=kt(Pe(e,"definitionId")),o=ge(e,"version",1),r=ge(e,"primitiveSet",1),s=n.supportedPrimitiveSet??ia;(!Number.isSafeInteger(s)||s<1)&&A("MANIFEST_INVALID"),r>s&&A("PRIMITIVE_SET_UNSUPPORTED"),G(e.activation)||A("MANIFEST_INVALID"),X(e.activation,["kind","language"]),e.activation.kind!=="fenced-code"&&A("MANIFEST_INVALID");let a=kt(Pe(e.activation,"language")),c=wa(e.schema),d=ka(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 qa(e,n={}){return G(e)||A("MANIFEST_INVALID"),Object.hasOwn(e,"lineage")&&A("MANIFEST_INVALID","lineage is only allowed in product bundle indexes"),e.manifestVersion===2?Ka(e,n):Ya(e,n)}function $e(e,n={}){try{return qa(e,n)}catch(t){if(t instanceof se)throw t;return A("MANIFEST_INVALID")}}function mn(e,n={}){let t=$e(e,n);return t.manifestVersion===2?Xa(t):t}var ia,oa,ra,eo,sa,aa,ca,da,Gi,pa,la,ua,fa,ya,Aa,Ia,ga,ma,ha,_a,Ea,Ta,Pa,Na,Da,ba,Sa,Ma,La,se,$t=B(()=>{m();Ct();Le();Lt();ki();wt();$i();Be();ia=1,oa=/^[a-z][a-zA-Z0-9]*(\.[a-zA-Z0-9]+)+$/,ra=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,eo=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,sa=/<\/?[A-Za-z][^>]*>/,aa=/^(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)/,ca=/^(?:https?|file|ftp|ws|wss):\/\//i,da=/^\s*(?:javascript|data):/i,Gi=/data:[^,\s]*,/i,pa=/(?:https?|file|ftp|ws|wss):\/\//i,la=/javascript:/i,ua=/(?:^[\s]*|[\s"'(=])(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)(?=[^\s"'<>])[^\s"'<>]*/,fa=["manifestVersion","pluginId","definitionId","version","primitiveSet","activation","schema","layout"],ya=["manifestVersion","pluginId","definitionId","version","name","description","entry","surfaces","size","stateProjection","actions"],Aa=["_meta","icon","tone","entryHash","runtime","csp","initialState","usage","detailPanel","displayModes","summaryProjection","dataPaths","focusedAiDataPaths"],Ia=["actionId","capability","mutation","inputSchema","resultProjection","backend"],ga=["confirmation","dataInputs","content","_meta"],ma=4*1024,ha=["type","handler"],_a=["type","command"],Ea=["env"],Ta=["type","entry"],Pa=["path"],Na=["hash"],Da=/^[0-9a-f]{64}$/,ba=/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/,Sa=/[\r\n]/,Ma=16,La=["card-shell","meta-banner","heading","labeled-text","step-flow","text-list"],se=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 po(e){return typeof e=="string"&&e.length<=Qa&&Za.test(e)}function j(e,n,t,i,o){throw new De(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 he(e){let n=`_meta["${ve}"]`;return e===void 0||e===""?n:e.startsWith("[")?`${n}${e}`:`${n}.${e}`}function ic(e){return e.toLowerCase().replace(/_/g,"-")}function oc(e){if(e===void 0||e==="")return "";let n=/^([^.[]+)(.*)$/.exec(e);if(!n)return he(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 he("definitionVersion");case "definitionId":return he("definitionId");default:return he(`${t}${i}`)}}function lo(e,n,t){return {path:t(e.path),rule:e.rule??ic(e.code),...e.message!==e.code?{message:e.message}:{},file:n}}function uo(e){return JSON.parse(JSON.stringify(e))}function Jt(e,n,t=0,i=new Set){if(typeof e=="string"){e.length>4096&&j("LIMIT_EXCEEDED",n,"string-too-long"),(ec.test(e)||nc.test(e)||tc.test(e))&&j("UNSAFE_VALUE",n,"unsafe-value");return}if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){Number.isFinite(e)||j("MANIFEST_INVALID",n,"non-finite-number");return}typeof e!="object"&&j("MANIFEST_INVALID",n,"non-json-value"),t>8&&j("LIMIT_EXCEEDED",n,"too-deep"),i.has(e)&&j("MANIFEST_INVALID",n,"cycle"),i.add(e);try{if(Array.isArray(e)){e.length>128&&j("LIMIT_EXCEEDED",n,"array-too-long"),e.forEach((o,r)=>Jt(o,`${n}[${r}]`,t+1,i));return}ie(e)||j("MANIFEST_INVALID",n,"non-plain-object");for(let[o,r]of Object.entries(e))Jt(r,n===""?o:`${n}.${o}`,t+1,i);}finally{i.delete(e);}}}function me(e,n){return (typeof e!="string"||e.length===0)&&j("MANIFEST_INVALID",n,"string"),e}function sn(e,n){return ie(e)||j("MANIFEST_INVALID",n,"object"),e}function rc(e,n){Array.isArray(e)||j("MANIFEST_INVALID",n,"array"),e.forEach((t,i)=>me(t,`${n}[${i}]`));}function sc(e,n){typeof e!="boolean"&&j("MANIFEST_INVALID",n,"boolean");}function hn(e,n,t,i){for(let o of Object.keys(e))!t.includes(o)&&!i.includes(o)&&j("MANIFEST_INVALID",`${n}.${o}`,"unknown-key");for(let o of t)q(e,o)||j("MANIFEST_INVALID",`${n}.${o}`,"missing-key");}function ac(e,n){switch(Jt(n,e),e){case "long_description":case "homepage":case "documentation":case "support":case "icon":case "license":me(n,e);return;case "author":{let t=sn(n,e);hn(t,e,["name"],["email","url"]);for(let i of Object.keys(t))me(t[i],`${e}.${i}`);return}case "repository":{let t=sn(n,e);hn(t,e,[],["type","url"]);for(let i of Object.keys(t))me(t[i],`${e}.${i}`);return}case "icons":{Array.isArray(n)||j("MANIFEST_INVALID",e,"array"),n.forEach((t,i)=>{let o=`${e}[${i}]`,r=sn(t,o);hn(r,o,["src","size"],["theme"]),me(r.src,`${o}.src`),me(r.size,`${o}.size`),q(r,"theme")&&me(r.theme,`${o}.theme`);});return}case "screenshots":case "keywords":case "privacy_policies":rc(n,e);return;case "tools":{Array.isArray(n)||j("MANIFEST_INVALID",e,"array"),n.forEach((t,i)=>{let o=`${e}[${i}]`,r=sn(t,o);hn(r,o,["name"],["description"]),me(r.name,`${o}.name`),q(r,"description")&&me(r.description,`${o}.description`);});return}case "prompts":{Array.isArray(n)||j("MANIFEST_INVALID",e,"array"),n.forEach((t,i)=>{let o=`${e}[${i}]`,r=sn(t,o);hn(r,o,["name","text"],["description","arguments"]),me(r.name,`${o}.name`),me(r.text,`${o}.text`);});return}case "tools_generated":case "prompts_generated":sc(n,e);return;case "localization":case "compatibility":case "user_config":sn(n,e);return;default:j("MANIFEST_INVALID",e,"unknown-key");}}function $n(e){return typeof e=="string"&&Te.test(e)?e:void 0}function fo(e){return Number.isSafeInteger(e)&&e>=1?e:void 0}function cc(e){let n=$n(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")?$n(o.definitionId):n,s=q(o,"definitionVersion")?fo(o.definitionVersion):1;return {pluginId:n,...r===void 0?{}:{definitionId:r},...s===void 0?{}:{definitionVersion:s}}}function dc(e){let n=$n(e.pluginId);if(n===void 0)return;let t=$n(e.definitionId),i=fo(e.version);return {pluginId:n,...t===void 0?{}:{definitionId:t},...i===void 0?{}:{definitionVersion:i}}}function Yt(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 pc(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 lc(e,n){q(e,"server")&&j("MANIFEST_INVALID","server","server-unsupported","phase 1 runs CrewX-owned Apps only");for(let a of Object.keys(e))Kt.includes(a)||j("MANIFEST_INVALID",a,"unknown-key");for(let a of Xt)q(e,a)||j("MANIFEST_INVALID",a,"missing-key");e.manifest_version!==Gt&&j("MANIFEST_INVALID","manifest_version","unsupported-version",`manifest_version must be "${Gt}"`),po(e.version)||j("MANIFEST_INVALID","version","semver","version must be a semver.org version such as 0.1.0");let t=e._meta;ie(t)||j("MANIFEST_INVALID","_meta","object"),q(t,ve)||j("MANIFEST_INVALID",he(),"missing-key");let i=t[ve];ie(i)||j("MANIFEST_INVALID",he(),"object");for(let a of Object.keys(i))Wt.includes(a)||co.includes(a)||j("MANIFEST_INVALID",he(a),"unknown-key");for(let a of Wt)a==="actions"&&n!==void 0||q(i,a)||j("MANIFEST_INVALID",he(a),"missing-key");if(n!==void 0&&q(i,"actions")&&j("MANIFEST_INVALID",he("actions"),"two-truths",`actions are declared in both ${W} and ${H}; a server.ts App keeps them in the tools file only`),uc(i.actions),q(i,"definitionVersion")){let a=i.definitionVersion;(!Number.isSafeInteger(a)||a<1)&&j("MANIFEST_INVALID",he("definitionVersion"),"positive-integer");}let o={};for(let a of ao)q(e,a)&&(ac(a,e[a]),o[a]=uo(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:nn}}))),Object.keys(r).length>0&&(s._meta=r),{v2Input:s,...Object.keys(r).length>0?{vendorMeta:r}:{},passthrough:o}}function uc(e){Array.isArray(e)&&e.forEach((n,t)=>{let i=ie(n)?n.backend:void 0;ie(i)&&q(i,"entry")&&j("MANIFEST_INVALID",he(`actions[${t}].backend.entry`),"entry-not-authorable",`an action in ${W} cannot name an entry; a server.ts App declares its actions in ${H}`);});}function fc(e,n,t){ie(e)||j("MANIFEST_INVALID","","not-object","manifest.json must be a JSON object",W);let i;try{i=lc(e,t);}catch(s){throw s instanceof De?new De(s.code,{...s.reason,file:W}):s}let o;try{let s=$e(i.v2Input,{mode:n.mode??"local"});s.manifestVersion!==2&&j("MANIFEST_INVALID","","v2-required"),o=s;}catch(s){throw s instanceof se?new De(s.code,lo(s,W,oc)):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 De("MANIFEST_INVALID",{path:`tools[${c}].name`,rule:"tool-not-action",message:"every tools[].name must be an action id",file:W})});}return {file:W,manifest:o,v2Input:i.v2Input,releaseVersion:e.version,...Object.keys(i.passthrough).length>0?{mcpb:i.passthrough}:{}}}function yc(e,n){try{let t=$e(e,{mode:n.mode??"local"});if(t.manifestVersion!==2)throw new De("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 se?new De(t.code,lo(t,de,i=>i??"")):t}}function an(e){return le(mn(e).definition)}function ro(e){let{entryHash:n,initialState:t,...i}=e,o={...i};return t!==void 0&&(o.initialState={path:t.path}),uo(o)}function Ac(e,n){let t=ro(e),i=ro(n);return [...new Set([...Object.keys(t),...Object.keys(i)])].sort().filter(r=>te(t[r]??null)!==te(i[r]??null))}function Ic(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 gc(e,n){let t=Ac(e,n),i=Ic(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||j("MANIFEST_DUAL_MISMATCH","","dual-manifest-mismatch",`${W} and ${de} normalize to different definitions${o}`+(t.length>0?`; differing fields: ${t.join(", ")}`:""));}function Ne(e,n,t="MANIFEST_INVALID",i){return {code:t,reason:{path:e,rule:n,...i===void 0?{}:{message:i},file:H},files:[]}}function so(e){return {...Ne("","tools-needs-manifest-json","MANIFEST_INVALID",`${H} is read with ${W} only`),files:e}}function mc(e,n){if(e.byteLength>n)return {failure:Ne("","file-too-large","LIMIT_EXCEEDED")};let t;try{t=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e));}catch{return {failure:Ne("","invalid-json")}}if(!ie(t))return {failure:Ne("","not-object","MANIFEST_INVALID",`${H} must be a JSON object`)};for(let o of Object.keys(t))if(o!=="schemaVersion"&&o!=="actions")return {failure:Ne(o,"unknown-key")};for(let o of ["schemaVersion","actions"])if(!q(t,o))return {failure:Ne(o,"missing-key")};if(t.schemaVersion!==1)return {failure:Ne("schemaVersion","unsupported-version","MANIFEST_INVALID",`schemaVersion must be ${1}`)};let i=t.actions;if(!Array.isArray(i))return {failure:Ne("actions","array")};for(let[o,r]of i.entries()){if(!ie(r))return {failure:Ne(`actions[${o}]`,"object")};if(q(r,"backend"))return {failure:Ne(`actions[${o}].backend`,"tools-backend","MANIFEST_INVALID",`an action in ${H} cannot carry a backend`)}}return {actions:i}}function hc(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 Ge(e,n={}){let{parsed:t,failure:i}=hc(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:mc(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:[]}:so(o),parseFailure:true,builtinOnly:false};let a=t[0],c=a.file===W?cc(a.raw):dc(a.raw),d=t.some(f=>pc(f.file,f.raw)),l;if(s!==void 0){let f=t.some(g=>g.file===W)?s.failure:so(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===W?fc(f.raw,n,l):yc(f.raw,n));p.length===2&&gc(p[0].manifest,p[1].manifest);}catch(f){if(f instanceof De)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 W,de,Z,Gt,ve,Kt,Xt,ao,Wt,co,Za,Qa,ec,nc,tc,De,Gn=B(()=>{m();He();Le();wt();Be();$t();W="manifest.json",de="ui-plugin.json",Z=[W,de],Gt="0.3",ve="dev.crewx",Kt=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"]),Xt=Object.freeze(["manifest_version","name","display_name","version","description","_meta"]),ao=Object.freeze(Kt.filter(e=>e!=="server"&&!Xt.includes(e))),Wt=Object.freeze(["entry","surfaces","size","stateProjection","actions"]),co=Object.freeze(["definitionId","definitionVersion","icon","tone","entryHash","runtime","initialState","usage","detailPanel","displayModes","summaryProjection","dataPaths","focusedAiDataPaths","csp"]),Za=/^(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-]+)*))?$/,Qa=256,ec=/<\/?[A-Za-z][^>]*>/,nc=/^\s*javascript:/i,tc=/data:[^,\s]*,/i;De=class extends Error{constructor(t,i){super(`${t}: ${i.path||"<file>"} (${i.rule})`);this.code=t;this.reason=i;}code;reason};});var qt=B(()=>{m();Ri();Gn();$t();Be();});function S(e,n=e){throw new be(e,n)}var be,Jn=B(()=>{m();be=class extends Error{constructor(t,i=t){super(i);this.code=t;}code;name="McpAppContractError"};});var No=B(()=>{m();});var Do=B(()=>{m();He();Le();Jn();No();});function So(e,n){return bo.add(e),n!==void 0&&Oc.set(e,n),e}function cn(e){return e!==null&&typeof e=="object"&&bo.has(e)}var bo,Oc,Kn=B(()=>{m();bo=new WeakSet,Oc=new WeakMap;});function Pn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Qt(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 Ro(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let n of Object.values(e))Ro(n);return Object.freeze(e)}function oe(e){throw new Se("LINEAGE_INVALID",e)}function jc(e){throw new Se("LINEAGE_STALE",e)}function Oo(e){if(!Pn(e)||!Qt(e,Uc,kc)||!Pn(e.actions))return oe("Lineage definition shape is invalid");for(let n of Object.values(e.actions))if(!Pn(n)||!Qt(n,xc,vc))return oe("Lineage action definition shape is invalid");return e}function Fc(e){if(!Pn(e)||!Qt(e,wc,Cc))return oe("Lineage entry shape is invalid");if(!Number.isSafeInteger(e.version)||e.version<1||typeof e.hash!="string"||!Mo.test(e.hash))return oe("Lineage entry identity is invalid");if(e.sourceHash!==void 0&&(typeof e.sourceHash!="string"||!Mo.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=Oo(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=le(n),Ae({...n,hash:e.hash});}catch{return oe("Lineage definition is invalid")}return t!==e.hash?oe("Lineage definition hash does not match"):Ro({version:e.version,hash:e.hash,definition:n,...e.sourceHash===void 0?{}:{sourceHash:e.sourceHash},...e.compat===void 0?{}:{compat:e.compat}})}function Lo(e){return e.stateProjection?.allow??[]}function Vc(e,n){let t=[],i=new Set(Lo(n));Lo(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 Bc(e,n){return te(e)===te(n)}function ei(e,n){if(!Array.isArray(e)||e.length===0)return oe("Definition lineage is missing");if(!Pn(n)||typeof n.hash!="string")return oe("Current definition is invalid");let t,i;try{let{hash:a,...c}=n;i=Oo(c),t={...i,hash:a},Ae(t);}catch{return oe("Current definition is invalid")}let o=e.map(Fc),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||!Bc(s.definition,i))return jc("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 Se("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=Vc(o[a].definition,t);if(d.length>0)throw new Se("LINEAGE_INVALID",`Lineage compatibility failed: ${d.join(", ")}`,d)}return Object.freeze({entries:Object.freeze(o),current:t})}var Se,Mo,wc,Cc,Uc,kc,xc,vc,ni=B(()=>{m();He();Le();Se=class extends Error{constructor(t,i=t,o=[]){super(i);this.code=t;this.violations=o;}code;violations;name="UiDefinitionLineageError"},Mo=/^[0-9a-f]{64}$/,wc=["version","hash","definition"],Cc=["sourceHash","compat"],Uc=["id","version","actions"],kc=["sourceHash","usage","detailPanel","displayModes","renderer","surfaces","stateProjection","dataPaths","summaryProjection","legacy"],xc=["capabilities"],vc=["inputKeys","dataInputs","confirmation","resultProjection","content","env"];});var wo,Co,Uo,ko,xo=B(()=>{m();wo="text/html;profile=mcp-app",Co=["crewx_app_terminal_connect","crewx_app_html_viewer_open"],Uo=["crewx_listWorkspaces","crewx_queryAgent","crewx_executeAgent","crewx_getTaskResult","crewx_listTasks","crewx_listAgents","callBrowser","openTab","listTabs","closeTab"],ko="text/html";});function vo(e,n=[],t){if(e.content!==void 0||e.confirmation!=="none")return "denied";let i=Hc();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==="skill"?"approval_required":e.backend===void 0&&n.includes(e.actionId)?"allowed":"denied"}function Hc(e){return;}var jo=B(()=>{m();He();Kn();});function qc(e){return bn.has(e)&&(e.initialState===void 0||bn.has(e.initialState))}function zo(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:ko,entryHash:e,html:n,bytes:Object.freeze(t),...o===void 0?{}:{initialState:o}});return o!==void 0&&bn.add(o),bn.add(r),r}function Zc(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:Fe}),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:Fe}),n}function Ve(e,n,t){return (typeof e!="string"||!Bo.test(e))&&S(n,`${t} must be a safe identifier`),e}function Nn(e,n,t){let i=e??t;return (typeof i!="string"||i.trim().length===0||i.length>Gc)&&S("TOOL_INVALID",`${n} must be a meaningful description`),i}function ii(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 Dn(e,n=0){try{let t=ye(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 be)throw t;S("TOOL_INVALID","MCP App inputSchema must be projection-safe JSON");}}function Qc(e){return (typeof e!="string"||e.trim().length===0||e.length>Wc)&&S("TOOL_INVALID","MCP App tools require a meaningful text fallback"),e}function ed(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 Go(e){return (typeof e!="string"||!Ho.test(e))&&S("RESOURCE_URI_INVALID","MCP App resource URI is not a registered ui:// URI"),e}function Wo(e){let n=Ve(e.appId,"APP_ID_INVALID","Local App id"),t=Nn(e.name,"Local App name",n),i=Nn(e.description,"Local App description",`${t} interactive view`),o=Zn(e.definition),r=ii(e.html),s=Xn(e.entryHash,"Local App entry hash"),a=e.entryBytes===void 0?Array.from(new TextEncoder().encode(r)):qn(e.entryBytes,"Local App entry bytes");(Yn(a)!==s||Xo(a)!==r)&&S("HTML_INVALID","Local App entry bytes do not match the HTML hash");let c=nd(e),d=[];Array.isArray(e.actions)||S("TOOL_INVALID","Local App actions must be an array");for(let N of e.actions){let C=Ve(N.actionId,"TOOL_ID_INVALID","Local App action id");(d.includes(C)||!Object.prototype.hasOwnProperty.call(o.actions,C))&&S("TOOL_INVALID",`Local App action is not declared by the UI definition: ${C}`),d.push(C);}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=Zc(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:Yc,textFallback:`${t} current state is available through its open instance.`,visibility:Object.freeze(["model","app"]),kind:"read",resourceBinding:Fe},g=[Object.freeze(f)];if(g.push(...u.map(N=>Object.freeze(N))),p!==void 0){let N={name:p,description:`${t} actions`,inputSchema:oi(e.actions),textFallback:`${t} action requests are handled by the open App instance.`,visibility:Object.freeze(["app"]),kind:"action",resourceBinding:Fe,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 C=`${p}__${N.actionId}`;if(C.length>128||!Bo.test(C)){_.push(Object.freeze({toolName:C,actionId:N.actionId,reason:"name_too_long"}));continue}if(P.has(C)){_.push(Object.freeze({toolName:C,actionId:N.actionId,reason:"name_collision"}));continue}let F=vo({actionId:N.actionId,confirmation:o.actions[N.actionId]?.confirmation,content:o.actions[N.actionId]?.content,backend:N.backend},e.modelActions),D=Object.freeze(F==="denied"?["app"]:["model","app"]),b={name:C,description:`${C} action`,inputSchema:Dn(N.inputSchema),textFallback:`${C} action requests are handled by the open App instance.`,visibility:D,kind:"action",resourceBinding:Fe,actionId:N.actionId,actionIds:Object.freeze([N.actionId]),_meta:Object.freeze({ui:Object.freeze({visibility:D})})};g.push(Object.freeze(b)),P.add(C);}let U=zo(s,r,a,c===void 0?void 0:{hash:c.hash,bytes:[...c.bytes]}),k={appId:n,name:t,description:i,...e.icon===void 0?{}:{icon:Yo(e.icon)},...e.tone===void 0?{}:{tone:qo(e.tone)},builtinOnly:false,definition:o,...e.runtime===void 0?{}:{runtime:Object.freeze({...e.runtime})},resourceBinding:Fe,resource:U,tools:Object.freeze(g),toolDiagnostics:Object.freeze(_)};return ee(k)}function Jo(e={}){return new ti(e)}function oi(e){if(e.length===0)return Dn({type:"object",properties:{},additionalProperties:false});let n=e.map(i=>i.actionId),t=new Map;for(let i of e)t.set(i.actionId,Dn(i.inputSchema));return Dn(td(n,t),$o)}function nd(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&&ye(e.initialState,0,n);return}e.initialStateHash===void 0&&S("STATE_INVALID","Initial state bytes require a hash");let t=Xn(e.initialStateHash,"Initial state hash"),i=qn(e.initialStateBytes,"Initial state bytes");Yn(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=ye(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(ye(e.initialState,0,n))&&S("STATE_INVALID","Initial state bytes do not match the state value"),{hash:t,bytes:Object.freeze([...i])}}function td(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 id(e){let n=Sn(e),t=Ve(n.appId,"APP_ID_INVALID","MCP App id"),i=ii(n.html);Go(n.uiUri);let o=n.definition===void 0?void 0:Zn(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(Sn(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:wo,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 od(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=Zn(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=rd(e.resource),r=e.tools.map(a=>{Ve(a.name,"TOOL_ID_INVALID","Local App tool name"),Nn(a.description,"Local App tool description","Local App tool"),Qc(a.textFallback);let c=Dn(a.inputSchema,a.kind==="action"&&!("actionId"in a)?$o: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 (!Xc.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=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=ed(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:Nn(e.name,"Local App name",e.appId),description:Nn(e.description,"Local App description",e.name),...e.icon===void 0?{}:{icon:Yo(e.icon)},...e.tone===void 0?{}:{tone:qo(e.tone)},builtinOnly:false,definition:t,...e.runtime===void 0?{}:{runtime:Object.freeze({...e.runtime})},...i===void 0?{}:{provenance:i},resourceBinding:Fe,resource:o,tools:Object.freeze(r),toolDiagnostics:Object.freeze([...e.toolDiagnostics??[]])});return Fo.has(e)?e:(Fo.add(s),s)}function rd(e){let n=ii(e.html),t=Xn(e.entryHash,"Local App entry hash");if(qc(e))return e;let i=qn(e.bytes,"Local App entry bytes");(Yn(i)!==t||Xo(i)!==n)&&S("HTML_INVALID","Local App entry bytes do not match the HTML hash");let o=e.initialState===void 0?void 0:{hash:Xn(e.initialState.hash,"Initial state hash"),bytes:qn(e.initialState.bytes,"Initial state bytes")};return o&&Yn(o.bytes)!==o.hash&&S("STATE_INVALID","Initial state bytes do not match the hash"),zo(t,n,i,o)}function sd(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:Ko(e.definition),...e.provenance===void 0?{}:{provenance:e.provenance},entryHash:e.resource.entryHash,resourceBinding:Fe,tools:e.tools})}function ad(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:Ko(e.definition)},resourceBinding:Object.freeze({kind:"mcp",uri:e.uiUri}),tools:e.tools})}function Zn(e){try{if(Object.isFrozen(e))return Ae(e),ee(e);let n=Sn(e);return Ae(n),ee(n)}catch(n){if(n instanceof be)throw n;S("STATE_INVALID","UI definition is not a valid immutable definition");}}function Ko(e){return ee({id:e.id,version:e.version,hash:e.hash})}function cd(e){return e!==null&&typeof e=="object"&&typeof e.id=="string"&&Number.isSafeInteger(e.version)&&typeof e.hash=="string"}function Vo(e,n,t){return `${e}\0${n}\0${t}`}function Xn(e,n){return (typeof e!="string"||!$c.test(e))&&S("SERIALIZATION_INVALID",`${n} is invalid`),e}function Yn(e){return createHash("sha256").update(Uint8Array.from(e)).digest("hex")}function qn(e,n){return (!Array.isArray(e)||e.some(t=>!Number.isInteger(t)||t<0||t>255))&&S("SERIALIZATION_INVALID",`${n} is invalid`),[...e]}function Xo(e){try{return new TextDecoder("utf-8",{fatal:!0}).decode(Uint8Array.from(e))}catch{S("SERIALIZATION_INVALID","UTF-8 bytes are invalid");}}function Yo(e){return (typeof e!="string"||!Jc.test(e))&&S("TOOL_INVALID","MCP App icon is invalid"),e}function qo(e){return (typeof e!="string"||!Kc.has(e))&&S("TOOL_INVALID","MCP App tone is invalid"),e}function Sn(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(Sn(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:Sn(s,n),writable:true});return n.delete(t),o}function ee(e,n=new Set){if(e===null||typeof e!="object"||n.has(e)||bn.has(e))return e;n.add(e);for(let t of Object.values(e))ee(t,n);return Object.freeze(e),e}var Bo,Ho,$c,dn,Gc,Wc,Jc,Kc,Xc,Fe,Yc,bn,Fo,$o,ti,Qn=B(()=>{m();Do();He();Le();Kn();Jn();ni();xo();jo();Bo=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,Ho=/^ui:\/\/crewx\/([A-Za-z][A-Za-z0-9._-]{0,127})\/([0-9a-f]{12})$/,$c=/^[0-9a-f]{64}$/,dn=8*1024*1024,Gc=8*1024,Wc=16*1024,Jc=/^[a-z][a-z0-9-]{0,63}$/,Kc=new Set(["blue","violet","emerald","amber","rose","sky","slate","indigo"]),Xc=new Set(Co),new Set(Uo),Fe=Object.freeze({kind:"instance"}),Yc=Object.freeze({type:"object",properties:Object.freeze({}),additionalProperties:false}),bn=new WeakSet,Fo=new WeakSet;$o=4;ti=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=id(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(od),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=ee({...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,ad(p)),p.definition&&this.addDefinition(p.definition);for(let p of l)this.registrationById.set(p.appId,p),this.launcherById.set(p.appId,sd(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"||!Ho.test(n)?null:this.mcpResources.get(n)??null}requireMcpAppResource(n){Go(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}))}getLauncher(n){return this.launcherById.get(n)??null}resolveDefinition(n){if(!cd(n))return null;let t=this.definitionByKey.get(Ot(n));if(!t||t.hash!==n.hash)return null;try{return le(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(Vo(n,t,i))??null}addDefinition(n){let t=Zn(n),i=Ot(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=Vo(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 dd(e){let n=Wo({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 Zo(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=dd(e);Jo({localApps:[t],definitions:[e.definition]});}var Qo=B(()=>{m();Qn();});function pd(e){if(e===null||typeof e!="object"||!(er in e))throw new TypeError("scanCache must be created by createWorkspaceAppScanCache");return e[er]}function nr(e,n){let t=pd(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,tr=B(()=>{m();er=Symbol("crewx.workspace-app-scan-cache.state");});function ue(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 yd(e){if(typeof e!="string"||e.length===0||!isAbsolute(e))throw new M("READ_DENIED")}function ri(e){if(typeof e!="string"||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 it(e,n){let t=relative(e,n);return t===""||t!==".."&&!t.startsWith(`..${sep}`)&&!isAbsolute(t)}function ln(e){return {dev:e.dev,ino:e.ino,size:e.size,mtimeNs:e.mtimeNs,ctimeNs:e.ctimeNs}}function di(e,n){return e.dev===n.dev&&e.ino===n.ino}function pi(e,n){return di(e,n)&&e.size===n.size&&e.mtimeNs===n.mtimeNs&&e.ctimeNs===n.ctimeNs}async function et(e){yd(e);let n,t;try{n=await realpath(e),t=await stat(n,{bigint:!0});}catch(i){throw ue(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=resolve(e,t[0],t[1]),o=await realpath(i),!(await stat(o,{bigint:!0})).isDirectory())throw new M("READ_DENIED")}catch(r){throw r instanceof M?r:ue(r)}if(!it(n,o))throw new M("PATH_ESCAPED");return o}async function nt(e,n,t,i){let o,r,s;try{o=await lstat(e,{bigint:!0}),r=await realpath(e),s=await stat(r,{bigint:!0});}catch(a){throw ue(a)}if(!it(n,r)||t!==void 0&&!it(t,r))throw new M("PATH_ESCAPED");if(!o.isFile()||!s.isFile())throw new M("READ_DENIED");if(!di(i,o)||!di(i,s)||i.dev!==s.dev)throw new M("PATH_ESCAPED")}async function pn(e,n){let t,i;try{t=await realpath(e),i=await stat(t,{bigint:!0});}catch{throw new M("PATH_ESCAPED")}if(t!==n.realRoot||!pi(n.identity,ln(i)))throw new M("PATH_ESCAPED")}function Ad(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,ci,fd,or,ot,sr,ui=B(()=>{m();M=class extends Error{constructor(t){super(t);this.code=t;}code;name="AppDiscoveryFsError"},ci=constants.O_NOFOLLOW,fd=constants.O_NONBLOCK,or=constants.O_RDONLY|(ci??0)|(fd??0);ot=class{async getRootIdentity(n){let t=await et(n);return await pn(n,t),{dev:t.identity.dev,ino:t.identity.ino,realPath:t.realRoot}}async listDirectory(n,t){let i=ri(t),o=await et(n),r=resolve(n,...i),s,a;try{s=await realpath(r),a=await stat(s,{bigint:!0});}catch(c){let d=ue(c);if(d.code==="NOT_FOUND")return [];throw d}if(!it(o.realRoot,s)||!a.isDirectory())throw new M("PATH_ESCAPED");try{let c=await readdir(s,{withFileTypes:!0,encoding:"utf8"});return await pn(n,o),c.map(Ad)}catch(c){let d=ue(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(ci===void 0)throw new M("UNSUPPORTED");let o=ri(t),r=await et(n),s=resolve(n,...o),a=relative(n,s);if(a===".."||a.startsWith(`..${sep}`)||isAbsolute(a))throw new M("PATH_ESCAPED");let c;try{c=await open(s,or);}catch(d){throw ue(d)}try{let d;try{let g=await c.stat({bigint:!0});d=ln(g);}catch(g){throw ue(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 nt(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 ue(_)}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 ue(g)}if(!pi(d,f))throw new M("IDENTITY_CHANGED");return await nt(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(ci===void 0)throw new M("UNSUPPORTED");let o=ri(t),r=await et(n),s=resolve(n,...o),a=relative(n,s);if(a===".."||a.startsWith(`..${sep}`)||isAbsolute(a))throw new M("PATH_ESCAPED");let c;try{c=await open(s,or);}catch(d){throw ue(d)}try{let d;try{let u=await c.stat({bigint:!0});d=ln(u);}catch(u){throw ue(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 nt(s,r.realRoot,l,d);let p;try{let u=await c.stat({bigint:!0});p=ln(u);}catch(u){throw ue(u)}if(!pi(d,p))throw new M("IDENTITY_CHANGED");return await nt(s,r.realRoot,l,p),await pn(n,r),{...p,candidateRealPath:l??r.realRoot}}catch(d){throw d instanceof M?d:ue(d)}finally{await c.close().catch(()=>{});}}async readFileVerified(n,t,i){return this.readVerifiedFile(n,t,i)}},sr=new ot;});function On(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 cr(e){return typeof e=="string"&&Te.test(e)?e:void 0}function Td(e){return e.length>0&&e!=="."&&e!==".."&&!/[\\/\u0000]/.test(e)}function Je(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 Pd(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 Nd(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 Dd(e){return _d.decode(e)}function bd(e){return JSON.parse(Dd(e))}function dr(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 Sd(e){if(e instanceof M)return dr(e.code);if(e!==null&&typeof e=="object"&&"code"in e){let n=e.code;if(typeof n=="string")return dr(n)}}function Oe(e,n){let t=n();return Number.isFinite(t)&&Number.isFinite(e)&&t-e<=5e3}function Md(e){if(typeof e.readVerifiedFile=="function")return e.readVerifiedFile;if(typeof e.readFileVerified=="function")return e.readFileVerified}function Ld(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 pr(e,n,t,i){let o=Md(e);if(!o)throw new M("READ_DENIED");return Nd(await o.call(e,n,t,i))}async function Ai(e,n,t){let i=Ld(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(Pd).filter(r=>r!==null)}function Rd(e,n,t,i){return Object.freeze({code:e,...{},source:n,relativePath:t})}function Od(e){if(!On(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(Je))};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 wd(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 st(e){return Object.freeze({appIds:Object.freeze([...new Set(e.map(n=>n.appId))].sort(Je)),definitionIds:Object.freeze([...new Set(e.map(n=>n.definition.id))].sort(Je))})}function rt(e,n){let t=Object.keys(e).sort(Je),i=[...n].sort(Je);return t.length===i.length&&t.every((o,r)=>o===i[r])}function lr(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 Cd(e){let n;try{n=bd(e);}catch{return}if(!On(n)||!rt(n,["version","packages"])||n.version!==1||!Array.isArray(n.packages)||n.packages.length>Ii)return;let t=new Set,i=new Set,o=0,r=[];for(let s of n.packages){if(!On(s))return;let a=["packageDir","appId","definition","files"],c=Object.hasOwn(s,"lineage"),d=Object.hasOwn(s,"launcher"),l=[...c?["lineage"]:[],...d?["launcher"]:[]];if(!rt(s,[...a,...l])||d&&s.launcher!==false)return;let p=lr(s.packageDir),u=cr(s.appId);if(!p||p.length!==2||p[0]!=="apps"||!Td(p[1])||!u||t.has(s.packageDir)||!On(s.definition)||!rt(s.definition,["id","version","hash"]))return;let f=cr(s.definition.id),g=s.definition.version,_=s.definition.hash;if(!f||!Number.isSafeInteger(g)||g<1||typeof _!="string"||!yi.test(_)||!Array.isArray(s.files)||s.files.length<2||s.files.length>gi)return;let P=new Set,U=[];for(let k of s.files){if(!On(k)||!rt(k,["path","sha256"]))return;let N=lr(k.path);if(!N||typeof k.sha256!="string"||!yi.test(k.sha256))return;let C=N.join("/"),F=`${s.packageDir}/${C}`;if(P.has(C)||i.has(F))return;P.add(C),i.add(F),U.push(Object.freeze({path:C,sha256:k.sha256}));}if(!Z.some(k=>P.has(k))||!P.has("ui/index.html")||(o+=U.length,o>gd))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(U.sort((k,N)=>Je(k.path,N.path)))}));}return Object.freeze({version:1,packages:Object.freeze(r)})}function We(e){let n=Sd(e);return n==="PATH_ESCAPED"||n==="IDENTITY_CHANGED"||n==="TOCTOU"?"PATH_ESCAPED":n==="LIMIT_EXCEEDED"?"LIMIT_EXCEEDED":"BUNDLE_INTEGRITY"}async function Ud(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 Ai(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>gi)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(Je)}function kd(e){return Z.includes(e)?262144:e==="ui/index.html"?dn:e==="ui/state.json"?2097152:e.startsWith("ui/assets/")?hd:md}async function ur(e,n,t,i){if(e===void 0)return {packages:[],diagnostics:[],incomplete:false,reservedIds:Ed};let o=Od(e.reservedIds),r=[],s=(y,I,h)=>Rd(y,"bundled",I),a=(y=[],I=false,h)=>({...h===void 0?{}:{indexHash:h},packages:y,diagnostics:r,incomplete:I,reservedIds:o});if(typeof e.root!="string"||e.root.length===0||typeof e.expectedIndexHash!="string"||!yi.test(e.expectedIndexHash))return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a();let c;try{c=await pr(n,e.root,"bundle-index.json",Id);}catch(y){return r.push(s(We(y),"bundle-index.json")),a()}let d=createHash("sha256").update(c).digest("hex");if(d!==e.expectedIndexHash)return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a();let l=Cd(c);if(l===void 0)return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a();if(!wd(st(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(y=>({indexEntry:y,failureCode:"LIMIT_EXCEEDED"})),true,d);let p;try{p=await Ai(n,e.root,"");}catch(y){return r.push(s(We(y),"bundle-index.json")),a(l.packages.map(I=>({indexEntry:I,failureCode:We(y)})),false,d)}if(!Oe(t,i))return r.push(s("LIMIT_EXCEEDED","bundle-index.json")),a(l.packages.map(y=>({indexEntry:y,failureCode:"LIMIT_EXCEEDED"})),true,d);let u=p.find(y=>y.name==="bundle-index.json"&&y.kind==="file"),f=p.find(y=>y.name==="apps"&&y.kind==="directory"),g=y=>l.packages.map(I=>({indexEntry:I,failureCode:y}));if(!u)return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a(g("BUNDLE_INTEGRITY"),false,d);let _=p.filter(y=>y.name!=="bundle-index.json"&&y.name!=="apps");if(_.length>0){let y=_.some(I=>I.kind==="symlink")?"PATH_ESCAPED":"BUNDLE_INTEGRITY";return r.push(s(y,"bundle-index.json")),a(g("BUNDLE_INTEGRITY"),false,d)}if(p.some(y=>y.name==="apps"&&y.kind!=="directory"))return r.push(s("PATH_ESCAPED","apps")),a(g("PATH_ESCAPED"),false,d);let P=[];if(f)try{P=await Ai(n,e.root,"apps");}catch(y){return r.push(s(We(y),"apps")),a(g(We(y)),false,d)}if(!Oe(t,i)||P.length>Ii)return r.push(s("LIMIT_EXCEEDED","apps")),a(g("LIMIT_EXCEEDED"),true,d);let U=new Map(l.packages.map(y=>[y.packageDir.slice(5),y])),k=P.filter(y=>!U.has(y.name));for(let y of k)r.push(s(y.kind==="symlink"?"PATH_ESCAPED":"BUNDLE_INTEGRITY",`apps/${y.name}`));if(k.length>0){let y=k.some(I=>I.kind==="symlink")?"PATH_ESCAPED":"BUNDLE_INTEGRITY";return a(g(y),false,d)}let N=new Set,C=new Map,F=new Map;for(let y of l.packages){let I=C.get(y.appId)??[];I.push(y),C.set(y.appId,I);let h=`${y.definition.id}\0${String(y.definition.version)}`,E=F.get(h)??[];E.push(y),F.set(h,E);}for(let y of [...C.values(),...F.values()])if(y.length>1)for(let I of y)N.add(I);let D=[],b=c.byteLength,R=false;for(let y of l.packages){if(!Oe(t,i)){R=true,D.push({indexEntry:y,failureCode:"LIMIT_EXCEEDED"});continue}let I;try{let L=y.lineage[y.lineage.length-1];if(!L)throw new Se("LINEAGE_INVALID","Definition lineage is missing");if(L.definition.id!==y.definition.id||L.version!==y.definition.version||L.hash!==y.definition.hash)throw new Se("LINEAGE_STALE","Last lineage generation does not match bundle identity");I=ei(y.lineage,{...L.definition,hash:L.hash}).entries;}catch(L){let J=L instanceof Se?L.code:"LINEAGE_INVALID";r.push(s(J,y.packageDir)),D.push({indexEntry:y,failureCode:J});continue}let h=P.find(L=>L.name===y.packageDir.slice(5));if(!f||!h){D.push({indexEntry:y,failureCode:"BUNDLE_INTEGRITY"});continue}if(h.kind!=="directory"){D.push({indexEntry:y,failureCode:h.kind==="symlink"?"PATH_ESCAPED":"BUNDLE_INTEGRITY"});continue}let E;try{let L=await Ud(n,e.root,y.packageDir,t,i);if(!Oe(t,i)){R=!0,D.push({indexEntry:y,failureCode:"LIMIT_EXCEEDED"});continue}let J=y.files.map(K=>K.path);if(L.length!==J.length||L.some((K,Me)=>K!==J[Me])){D.push({indexEntry:y,failureCode:"BUNDLE_INTEGRITY"});continue}E=new Map;let pe;for(let K of y.files){if(!Oe(t,i)){pe="LIMIT_EXCEEDED",R=!0;break}if(b>=fi){pe="LIMIT_EXCEEDED";break}let Me;try{Me=await pr(n,e.root,`${y.packageDir}/${K.path}`,kd(K.path));}catch(ms){pe=We(ms);break}if(!Oe(t,i)){pe="LIMIT_EXCEEDED",R=!0;break}if(b+Me.byteLength>fi){b=fi,pe="LIMIT_EXCEEDED";break}if(b+=Me.byteLength,createHash("sha256").update(Me).digest("hex")!==K.sha256){pe="BUNDLE_INTEGRITY";break}E.set(K.path,Me);}if(pe!==void 0){D.push({indexEntry:y,failureCode:pe});continue}}catch(L){Oe(t,i)||(R=true),D.push({indexEntry:y,failureCode:We(L)});continue}D.push({indexEntry:y,lineage:I,files:E,...N.has(y)?{failureCode:"DUPLICATE_ID"}:{}});}return a(D,R,d)}var Id,Ii,gi,gd,md,hd,fi,yi,_d,Ed,mi=B(()=>{m();ni();Be();Gn();Qn();ui();Id=256*1024,Ii=64,gi=128,gd=Ii*gi,md=2*1024*1024,hd=8*1024*1024,fi=32*1024*1024,yi=/^[0-9a-f]{64}$/,_d=new TextDecoder("utf-8",{fatal:true}),Ed=Object.freeze({appIds:Object.freeze([]),definitionIds:Object.freeze([])});});function vd(e){if(typeof e!="string"||!Te.test(e))throw new TypeError("pluginId must be a safe UI plugin identifier");let n=`${hi}${e}`.length+7<=128?e:`hash_${createHash("sha256").update(e,"utf8").digest("hex")}`;return {read:`${hi}${n}_read`,action:`${hi}${n}_action`}}function yr(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 Fd(e,n){return n.length===0||n==="."||n===".."||/[\\/\u0000]/.test(n)?e==="skills"?"skills":"apps":`${e==="skills"?"skills":"apps"}/${n}`}function Vd(e){return e.length>0&&e!=="."&&e!==".."&&!/[\\/\u0000]/.test(e)}function wn(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 Dr(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 Bd(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 br(e){return jd.decode(e)}function Hd(e){return JSON.parse(br(e))}function zd(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 ct(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 Ar(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 ae(e){if(e instanceof M)return Ar(e.code);if(e!==null&&typeof e=="object"&&"code"in e){let n=e.code;if(typeof n=="string")return Ar(n)}}function Xe(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 Ir(e){return {reason:e.reason,...e.code==="MANIFEST_DUAL_MISMATCH"?{files:e.files}:{}}}function gr(e){return e==="MANIFEST_DUAL_MISMATCH"?e:Sr(e)}function $d(e){return Sr(e.code)}function Sr(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 Mr("UiPluginValidationError",e)}}function Mr(e,n){throw new Error(`Unmapped ${e} code: ${String(n)}`)}function Lr(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 Mr("McpAppContractError",e)}}function we(e,n){let t=n();return Number.isFinite(t)&&Number.isFinite(e)&&t-e<=5e3}function Gd(e){return {pluginId:e.appId,definitionKey:`${e.definition.id}\0${String(e.definition.version)}`}}function Wd(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(yr(o)){let r=o.bin,s=typeof r=="string"?r:yr(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=Jd(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 Jd(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 Kd(){return globalThis.performance?.now()??Date.now()}function Ke(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let n of Object.values(e))Ke(n);return Object.freeze(e)}function mr(e){return Object.freeze(Array.from(e))}async function dt(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 Tr(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 Tr(e,n.root,o,i),d=await s.call(e,r.workspaceRoot,o,i);return r.candidateRealPath=d.candidateRealPath,Or(a,d)&&d.size===BigInt(c.byteLength)&&!wr(d,r.scanStartedAtNs)?r.files.set(o,{relativePath:o,byteLimit:i,fingerprint:d}):r.cacheable=!1,c}catch(a){let c=Z.includes(t)&&ae(a)==="NOT_FOUND"&&r.directoryListings.some(l=>l.relativePath===n.relativePath&&!pt(l.key,t)),d=t===H&&ae(a)==="NOT_FOUND"&&Xd(r.directoryListings,n.relativePath);throw !c&&!d&&(r.cacheable=false),a}}function Xd(e,n){let t=e.find(o=>o.relativePath===n);if(t===void 0)return false;if(!pt(t.key,"dist"))return true;let i=e.find(o=>o.relativePath===`${n}/dist`);return i!==void 0&&!pt(i.key,"tools.json")}function Rr(e,n){return JSON.stringify([e.realPath,n.source,n.relativePath])}async function qd(e,n,t,i,o,r,s,a){let c=e.fingerprintVerifiedFile,d=Rr(t,i),l=o.candidates.get(d),p=i.relativePath,u;try{u=await Er(e,n,p);}catch(R){if(ae(R)!=="NOT_FOUND")throw R}let f=u===void 0?void 0:{relativePath:p,key:u};if(f!==void 0&&(i.source==="apps"||i.source==="skills")&&!Z.some(R=>pt(f.key,R)))return we(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 R=>{if(R==="")return f;let y=`${i.relativePath}${R}`;try{let I=await Er(e,n,y);return I===void 0?void 0:{relativePath:y,key:I}}catch(I){if(ae(I)==="NOT_FOUND")return;throw I}},_=await Promise.all(hr.map(g)),P=await Promise.all(Yd.map(g));if(!we(s,a))return {timeLimitReached:true};let U=typeof c=="function"&&_.every(R=>R!==void 0),k=_.filter(R=>R!==void 0),N=[...k,...P.filter(R=>R!==void 0)],C=new Map,F=l!==void 0&&U,D;if(l!==void 0&&typeof c=="function"){let R=await Promise.all(l.files.map(async y=>{if(!we(s,a))return {kind:"time",file:y};try{let I=await c.call(e,n,y.relativePath,y.byteLimit);return {kind:"fingerprint",file:y,current:I}}catch(I){return ae(I)==="NOT_FOUND"?{kind:"missing",file:y}:{kind:"error",file:y,error:I}}}));if(R.some(y=>y.kind==="time"))return {timeLimitReached:true};for(let y of R){if(y.kind==="error")throw y.error;if(y.kind==="missing"){F=false;continue}if(y.kind!=="fingerprint")continue;let{file:I,current:h}=y;C.set(I.relativePath,h),D??=h.candidateRealPath,(h.candidateRealPath!==l.candidateRealPath||!Or(h,I.fingerprint)||wr(h,r))&&(F=false);}}let b=l!==void 0&&l.directoryListings.length===N.length&&l.directoryListings.every((R,y)=>R.relativePath===N[y]?.relativePath&&R.key===N[y]?.key);return l!==void 0&&U&&b&&F&&D===l.candidateRealPath?{memo:l}:!U||k.length!==hr.length?{}:{context:{state:o,cacheKey:d,workspaceRoot:n,scanStartedAtNs:r,directoryListings:Object.freeze(N),priorFingerprints:C,files:new Map,...D===void 0?{}:{candidateRealPath:D},cacheable:true}}}function pt(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 Er(e,n,t){let i=Cr(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(Dr);if(!r.some(s=>s===null))return JSON.stringify(r.slice().sort((s,a)=>wn(s.name,a.name)||wn(s.kind,a.kind)).map(s=>[s.name,s.kind]))}function Or(e,n){return e.dev===n.dev&&e.ino===n.ino&&e.size===n.size&&e.mtimeNs===n.mtimeNs&&e.ctimeNs===n.ctimeNs}function wr(e,n){let t=e.mtimeNs-n;return t>=-_r&&t<=_r}function _i(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 Zd(e,n,t){let i=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 Qd(e,n){let t={...e.definition,sourceHash:n},i;try{i=le(t);}catch(r){throw r instanceof x&&r.code==="INPUT_INVALID"?new se("MANIFEST_INVALID","normalized definition is invalid"):r}let o={...t,hash:i};try{Ae(o);}catch{throw new se("MANIFEST_INVALID","normalized definition is invalid")}return o}function ep(e){return e.actions.some(n=>n.backend.type==="core"&&n.backend.handler!=="state.set")}function np(e){if(typeof e.readVerifiedFile=="function")return e.readVerifiedFile;if(typeof e.readFileVerified=="function")return e.readFileVerified}function Cr(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 Tr(e,n,t,i){let o=np(e);if(!o)throw new M("READ_DENIED");return Bd(await o.call(e,n,t,i))}async function tp(e,n,t){let i=Cr(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(Dr).filter(r=>r!==null)}function ip(e){let n=[];for(let t of [e.reserved,e.builtin])t&&n.push(t);return e.builtins&&"listMcpApps"in e.builtins?n.push(Pr(e.builtins)):e.builtins&&n.push(e.builtins),e.builtinCatalog&&n.push(Pr(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 Pr(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 _e(e,n){e.diagnostic||(e.diagnostic=ct(n,e.source,e.relativePath,e.identity?.pluginId));}function op(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&&_e(d,"RESERVED_ID");continue}for(let d of r)d.provenance===void 0&&_e(d,"RESERVED_ID");if(s.length>1)for(let d of s)_e(d,"DUPLICATE_ID");continue}let a=r.filter(c=>c.source==="apps");if(a.length>1){for(let c of a)_e(c,"DUPLICATE_ID");for(let c of r.filter(d=>d.source==="skills"))_e(c,"DUPLICATE_ID");}else for(let c of r.filter(d=>d.source==="skills"))_e(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)_e(s,"DUPLICATE_ID");return t}function rp(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 ip(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)){_e(l,"RESERVED_ID");continue}[p.toolNames.read,p.toolNames.action].filter(f=>f!==void 0).some(f=>r.has(f))&&_e(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{Zo(p),d.add(l);}catch(u){_e(l,u instanceof be?Lr(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))&&_e(l,"RESERVED_ID");}return d}function sp(e){return [...e].sort((n,t)=>{let i=fr.indexOf(n.source)-fr.indexOf(t.source);return i!==0?i:wn(n.relativePath,t.relativePath)})}function V(e,n,t){e.diagnostic=ct(n,e.source,e.relativePath,e.identity?.pluginId,t);}async function Nr(e,n,t){let i=Ge(t,{mode:"local"});if(!i.ok&&i.parseFailure){V(n,gr(i.rejection.code),Ir(i.rejection));return}let o=zd(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)}`){V(n,"BUNDLE_INTEGRITY");return}if(!i.ok&&i.builtinOnly){V(n,"RESERVED_ID");return}if(!i.ok){V(n,gr(i.rejection.code),Ir(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{oi(r.actions.map(L=>({actionId:L.actionId,inputSchema:L.inputSchema})));}catch(L){if(L instanceof be){V(n,Lr(L.code));return}throw L}let a;try{a=await dt(e,n,"ui/index.html",dn);}catch(L){V(n,Xe(ae(L),"entry"));return}if(a.byteLength>dn){V(n,"LIMIT_EXCEEDED");return}let c;try{c=br(a);}catch{V(n,"ENTRY_INVALID");return}if(a.byteLength===0||c.length===0){V(n,"ENTRY_INVALID");return}let d=createHash("sha256").update(a).digest("hex");if(r.entryHash!==void 0&&r.entryHash!==d){V(n,"ENTRY_INVALID");return}let l={},p,u;if(r.initialState!==void 0){try{p=await dt(e,n,"ui/state.json",2097152);}catch(L){V(n,Xe(ae(L),"initial"));return}if(p.byteLength>2097152){V(n,"LIMIT_EXCEEDED");return}try{let L=Hd(p),J=r.dataPaths??[],pe=zt(L,J);l=ye(pe,0,J),Qe(l);}catch{V(n,"INITIAL_STATE_INVALID");return}if(u=createHash("sha256").update(p).digest("hex"),r.initialState.hash!==void 0&&r.initialState.hash!==u){V(n,"INITIAL_STATE_INVALID");return}}let f={...r,entryHash:d,...r.initialState===void 0?{}:{initialState:{path:"ui/state.json",hash:u}}},g=mn(f),_=Zd(f,a,p??new Uint8Array),P;try{P=Qd(g,_);}catch(L){if(L instanceof se){V(n,$d(L));return}throw L}let U;if(n.bundleLineage!==void 0){let L=n.bundleLineage[n.bundleLineage.length-1];if(!L){V(n,"LINEAGE_INVALID");return}let{legacy:J,...pe}=L.definition,{hash:K,...Me}=P;if(te(pe)!==te(Me)){V(n,"LINEAGE_STALE");return}if(J!==void 0&&(P={...P,legacy:J}),J!==void 0)try{P={...P,hash:le(P)},Ae(P);}catch{V(n,"LINEAGE_INVALID");return}U=n.bundleLineage;}if(n.bundleIdentity!==void 0&&n.bundleIdentity.appId!==r.pluginId){V(n,"BUNDLE_INTEGRITY");return}if(n.bundleIdentity!==void 0&&(n.bundleIdentity.definitionId!==P.id||n.bundleIdentity.version!==P.version||n.bundleIdentity.definitionHash!==P.hash)){V(n,"LINEAGE_STALE");return}let k=vd(r.pluginId),N=r.actions.length===0?{read:k.read}:k,C=Ke(g),F=Ke(f),D=Ke(P),b=Ke({...g.handlers}),R=mr(a),y=p===void 0?void 0:mr(p),I=Object.freeze({...n.provenance===void 0?{}:{provenance:n.provenance},entry:Object.freeze({path:"ui/index.html",hash:d,bytes:R}),...y===void 0?{}:{initialState:Object.freeze({path:"ui/state.json",hash:u,bytes:y})}}),h={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:Ke(i.mcpb)},relativePath:n.relativePath,manifest:F,normalized:C,name:r.name,description:r.description,...r.icon===void 0?{}:{icon:r.icon},...r.tone===void 0?{}:{tone:r.tone},definition:D,handlers:b,resources:I,html:c,entryBytes:R,entryHash:d,initialState:Ke(l),...y===void 0?{}:{initialStateBytes:y},...u===void 0?{}:{initialStateHash:u},sourceHash:_,toolNames:Object.freeze(N)},E=n.provenance===void 0?{...h,source:n.source}:{...h,provenance:n.provenance,lineage:U??[]};n.candidate=Object.freeze(E),ep(r)&&V(n,"EXEC_DENIED");}async function Ur(e,n){let t={};for(let i of Z)try{t[i]=await dt(e,n,i,262144);}catch(o){if(ae(o)==="NOT_FOUND")continue;return {files:t,failure:Xe(ae(o),"manifest")}}if(t[W]!==void 0)try{t[H]=await dt(e,n,H,262144);}catch(i){if(ae(i)!=="NOT_FOUND")return {files:t,failure:Xe(ae(i),"manifest")}}return {files:t}}function Ei(e){return Z.some(n=>e[n]!==void 0)}async function ap(e,n){let{files:t,failure:i}=await Ur(e,n);if(i!==void 0){V(n,i);return}let o=t[W];return o!==void 0&&!Yt(o)&&(delete t[W],delete t[H]),Ei(t)?t:void 0}function cp(e,n,t,i=xd,o=false,r=new Set){let s=sp(e),a=op(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 dp(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 pp(e,n){if(dp(e))return {fs:e,options:{}};let t=e??n??{};return {fs:t.filesystem??t.fileSystem??t.fs??sr,options:t}}async function kr(e,n,t){if(typeof e!="string"||e.length===0)throw new TypeError("workspaceRoot must be explicit");let{fs:i,options:o}=pp(n,t),r=o.clock??Kd,s=r(),a=await ur(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=nr(o.scanCache,_),g.scanStartedAtNs=d;}catch(D){if(ae(D)!=="NOT_FOUND")throw D}let P=g!==void 0&&o.productBundle===void 0&&a.packages.length===0&&a.diagnostics.length===0,U=new Set,k=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(!we(c,r)){f=true,u="time_limit";break}let b=D.indexEntry,R=b.packageDir,y=D.files===void 0?void 0:Wd(R,D.files),I=a.indexHash===void 0?void 0:So(Object.freeze({kind:"bundled",launcher:b.launcher!==false,indexHash:a.indexHash,packageDir:R,appId:b.appId,definitionId:b.definition.id,version:b.definition.version,definitionHash:b.definition.hash,files:b.files}),y),h={source:"bundled",root:o.productBundle?.root??e,name:R.slice(5),relativePath:R,...I===void 0?{}:{provenance:I},...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:Gd(b)};if(l.push(h),p+=1,D.failureCode!==void 0){V(h,D.failureCode);continue}if(D.files?.has(H)===true){V(h,"EXEC_DENIED",{reason:{path:"",rule:"bundled-tool-mode-unsupported",file:H}});continue}let E={};for(let L of Z){let J=D.files?.get(L);J!==void 0&&(E[L]=J);}if(!Ei(E)){V(h,"BUNDLE_INTEGRITY");continue}if(await Nr(i,h,E),!we(c,r)){f=true,u="time_limit";break}}let C=[{source:"apps",directory:"apps"},{source:"skills",directory:"skills"}];e:for(let D of C){let{source:b,directory:R}=D,y;try{y=await tp(i,e,R);}catch(h){if(ae(h)==="NOT_FOUND")continue;P=false,k=false,l.push({source:b,root:e,name:"",relativePath:b,diagnostic:ct(Xe(ae(h),"manifest"),b,b)});continue}let I=y.filter(h=>h.kind==="directory"||h.kind==="symlink").filter(h=>Vd(h.name)).map(h=>({source:b,root:e,name:h.name,relativePath:Fd(b,h.name)})).sort((h,E)=>wn(h.relativePath,E.relativePath));for(let h of I){let E={...h};if(l.push(E),_!==void 0?U.add(Rr(_,E)):P=false,!we(c,r)){f=true,u="time_limit";break e}let L;if(g!==void 0&&_!==void 0){try{let K=await qd(i,e,_,E,g,d,c,r);if(K.timeLimitReached){f=!0,u="time_limit";break e}E.scanContext=K.context,L=K.memo;}catch(K){P=false,V(E,Xe(ae(K),"manifest"));continue}L===void 0&&(P=false);}if(L!==void 0){if(E.candidate=L.candidate,E.diagnostic=L.diagnostic,E.identity=L.identity,b==="skills"&&L.candidate===void 0&&L.diagnostic===void 0)continue;if(p>=64){V(E,"LIMIT_EXCEEDED");continue}if(h.relativePath.split("/").length-1>2){V(E,"LIMIT_EXCEEDED");continue}if(p+=1,!we(c,r)){f=true,u="time_limit";break e}continue}let J;if(b==="skills"&&(J=await ap(i,E),J===void 0)){E.diagnostic===void 0&&_i(E);continue}if(p>=64){V(E,"LIMIT_EXCEEDED");continue}if(h.relativePath.split("/").length-1>2){V(E,"LIMIT_EXCEEDED");continue}if(!we(c,r)){f=true,u="time_limit";break e}if(p+=1,J===void 0){let K=await Ur(i,E);if(K.failure!==void 0||!Ei(K.files)){V(E,K.failure??Xe("NOT_FOUND","manifest")),_i(E);continue}J=K.files;}if(await Nr(i,E,J),_i(E),!we(c,r)){f=true,u="time_limit";break e}}}if(g!==void 0&&_!==void 0){let D=[...U].sort(wn),b=g.lastCandidateKeys,R=b!==void 0&&b.length===D.length&&b.every((I,h)=>I===D[h]);if(P=P&&R,k&&!f&&u===void 0)for(let I of g.candidates.keys())try{JSON.parse(I)[0]===_.realPath&&!U.has(I)&&g.candidates.delete(I);}catch{g.candidates.delete(I);}let y=[...g.candidates.keys()].filter(I=>{try{return JSON.parse(I)[0]===_.realPath}catch{return false}});P=P&&y.length===U.size&&y.every(I=>U.has(I))&&!f&&u===void 0,g.lastCandidateScanUnchanged=P,k&&!f&&u===void 0&&(g.lastCandidateKeys=Object.freeze(D));}f&&l.push({source:"apps",root:e,name:"",relativePath:"apps",diagnostic:ct("DISCOVERY_TIME_LIMIT","apps","apps")});let F=rp(l,o,N);return cp(l,u,a.indexHash,N,o.productBundle!==void 0,F)}var xd,hi,fr,jd,hr,Yd,_r,xr=B(()=>{m();He();kn();Le();qt();Be();Qn();Qo();Jn();tr();ui();Kn();mi();mi();xd=st([]),hi="crewx_local_app_";fr=["bundled","apps","skills"],jd=new TextDecoder("utf-8",{fatal:true});hr=["","/ui"],Yd=["/dist"],_r=2000000000n;});m();qt();m();Ct();m();var yo="SKILL.md",Nc=/^---\s*\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;function Ao(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function Dc(e){return e.isDirectory()||e.isSymbolicLink()}function _o(e){try{return existsSync(e)&&statSync(e).isDirectory()}catch{return false}}function Zt(e){let n;try{n=readFileSync(e,"utf8");}catch{return {frontmatter:{},readable:false,valid:false,hasFrontmatter:false}}let t=n.match(Nc);if(!t)return {frontmatter:{},readable:true,valid:true,hasFrontmatter:false};try{let i=load(t[1]??"");if(!Ao(i))return {frontmatter:{},readable:!0,valid:!1,hasFrontmatter:!0};let o=Ao(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 bc(e){return [join(e,yo),join(e,"skill",yo)]}function Io(e,n){if(!_o(e))return null;for(let t of bc(e)){if(!existsSync(t))continue;let o=Zt(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 go(e){try{return readdirSync(e,{withFileTypes:!0}).filter(Dc)}catch{return []}}function mo(e,n,t){!e||n.has(e.name)||(n.add(e.name),t.push(e));}function Eo(e){let n=[],t=new Set;for(let i of e)if(_o(i))for(let o of go(i)){if(o.name.startsWith("@")){let r=join(i,o.name);for(let s of go(r))mo(Io(join(r,s.name),s.name),t,n);continue}mo(Io(join(i,o.name),o.name),t,n);}return n.sort((i,o)=>i.name.localeCompare(o.name))}m();Gn();var Sc=/^[A-Za-z0-9_$.[\]"-]{0,200}$/,Mc=/^[a-z][a-z0-9-]{0,63}$/,Lc="<unknown>";function Rc(e){return typeof e=="string"&&(Z.includes(e)||e===H)}function To(e){if(typeof e!="object"||e===null)return;let{file:n,path:t,rule:i}=e;if(!(typeof i!="string"||!Mc.test(i)))return {...Rc(n)?{file:n}:{},path:typeof t=="string"&&Sc.test(t)?t:Lc,rule:i}}function Po(e){if(!Array.isArray(e))return;let n=Z.filter(t=>e.includes(t));return n.length>0?n:void 0}xr();var up=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/;function ft(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?fp(e.relativePath,e.fileBytes):void 0);if(n!==void 0&&i!==void 0){let o=JSON.stringify({screenHash:n,skillHash:i});return 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 fp(e,n){let t=new TextEncoder().encode(yt(e)),i=yp(n),o=new Uint8Array(t.byteLength+1+i.byteLength);return o.set(t,0),o[t.byteLength]=0,o.set(i,t.byteLength+1),createHash("sha256").update(o).digest("hex")}function yp(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 yt(e){if(typeof e!="string"||e.length===0||isAbsolute(e)||/[\\\u0000]/.test(e))throw new TypeError("relative path must be package-relative");let n=e.split("/").filter(t=>t.length>0&&t!==".").join("/");if(!n||n.split("/").some(t=>t===".."))throw new TypeError("relative path must stay inside the package");return n}function lt(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 Fr(e,n){let t=relative(e,n).split(sep).join("/");return !t||t===".."||t.startsWith("../")||isAbsolute(t)?null:yt(t)}function Ap(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 Vr(e){return Object.freeze({packageRoot:e})}function Ip(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 Br(e){return {capabilities:Object.freeze([...e]),origin:"local",ownership:"unknown",shareability:"unknown",sharingAvailability:"unavailable"}}function gp(e,n){let t=e.candidate,i=t.provenance!==void 0,o=n&&!i?["screen","skill"]:["screen"],r=Ip(t),s=ft(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,...Br(o),definition:r,...n===void 0||i?{}:{skillName:n.skill.name},...i?{provenance:t.provenance}:{localDefinitionRef:Vr(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 mp(e){let n=hp(e.skill.name),t={appId:n,name:e.skill.name,description:e.skill.description??"",...e.skill.version===void 0?{}:{version:e.skill.version},...Br(["skill"]),skillName:e.skill.name,localDefinitionRef:Vr(e.packageRoot),definitionHash:ft({skillHash:e.skillHash})};return {packageRoot:e.packageRoot,source:e.source,appId:n,capabilities:["skill"],summary:Object.freeze(t)}}function hp(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=To(o?.reason),s=Po(o?.files);return Object.freeze({code:e,source:n,relativePath:_p(t),...i===void 0?{}:{appId:i},...r===void 0?{}:{reason:r},...s===void 0?{}:{files:s}})}function _p(e){if(typeof e!="string"||e.length===0||isAbsolute(e)||/[\\\u0000]/.test(e))return "<unknown>";let n=e.split("/").filter(t=>t.length>0&&t!==".").join("/");return n.split("/").some(t=>t==="..")?"<unknown>":n}function Hr(e){return Q(e.code,e.source,e.relativePath,e.pluginId,e)}function Ep(e,n){let t=Fr(e,n.dir);if(!t)return {diagnostic:Q("PATH_ESCAPED","node_modules","node_modules")};let i=Ap(t);if(!i)return {diagnostic:Q("PATH_ESCAPED","node_modules",t)};let o=Zt(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=Tp(n.dir,n.skillMdPath);if(!r)return {diagnostic:Q("PATH_ESCAPED",i,t)};try{let s=new Uint8Array(readFileSync(n.skillMdPath));return {skill:n,packageRoot:t,relativeSkillPath:r,skillHash:ft({relativePath:r,fileBytes:s}),source:i}}catch{return {diagnostic:Q("SKILL_READ_FAILED",i,t)}}}function Tp(e,n){let t=relative(e,n).split(sep).join("/");try{return yt(t)}catch{return null}}function Pp(e){if(!up.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??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??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 Np(e){return e.builtinCatalog}function Dp(e){let n=e.packageRoot??e.relativePath??e.packageRootPath;if(n===void 0)return null;try{return yt(n)}catch{return null}}function bp(e){let n=e.marketplaceContentId;return typeof n=="string"&&n.length>0?n:void 0}function Sp(e,n,t){let i=n.installed??[],o=new Map;for(let s of i){let a=Dp(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=bp(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 Mp(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,ut(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,ut(a),a.appId));if(s.length>1)for(let a of s)i.add(a),n.push(Q("DUPLICATE_ID",a.source,ut(a),a.appId));continue}for(let s of o)i.add(s),n.push(Q("DUPLICATE_ID",s.source,ut(s),s.appId));}return e.filter(o=>!i.has(o))}function ut(e){return e.packageRoot??e.summary.provenance?.packageDir??`builtin/${e.appId}`}function Lp(e,n){return e.filter(t=>!(t.code==="MANIFEST_MISSING"&&n.has(t.relativePath))).map(Hr)}function Rp(e){return e.filesystem}function Op(e,n){let t=Rp(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 zr(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=Np(n),i=await kr(e,Op(n,t)),o=n.registeredProductBundle??i.productBundleSnapshotMetadata,r=[join(e,"skills"),join(e,"node_modules"),join(e,"apps")],s=[],a=[],c=[],d=new Set;for(let I of r)for(let h of Eo([I])){let E=Fr(e,h.dir);(E===null||!d.has(E))&&(c.push(h),E!==null&&d.add(E));}for(let I of c){let h=Ep(e,I);"diagnostic"in h?s.push(h.diagnostic):a.push(h);}let l=new Map,p=n.registeredProductBundle?.indexHash,u=(n.registeredProductBundle?.candidates??[]).filter(I=>p!==void 0&&I.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(I=>I.provenance?.indexHash===p).map(I=>I.appId));for(let I of f){if(g.has(I)&&I.provenance?.indexHash===p&&_.has(I.appId))continue;let h=I.provenance===void 0?`workspace\0${I.relativePath}`:`bundled\0${I.provenance.indexHash}\0${I.provenance.packageDir}`;l.set(h,{candidate:I,packageRoot:I.relativePath});}let P=new Map(a.map(I=>[I.packageRoot,I])),U=[];for(let I of l.values()){let h=I.candidate.provenance===void 0?P.get(I.packageRoot):void 0,E=gp(I,h);U.push({...E.packageRoot===void 0?{}:{packageRoot:E.packageRoot},source:E.source,appId:E.appId,summary:E.summary});}let k=new Set([...l.values()].filter(I=>I.candidate.provenance===void 0).map(I=>I.packageRoot)),N=o===void 0?new Set:new Set(i.diagnostics.filter(I=>I.code==="RESERVED_ID"&&I.source!=="bundled").map(I=>I.relativePath)),C=new Set(o?.reservedAppIds??[]);for(let I of a){let h=mp(I);if(!(k.has(I.packageRoot)||N.has(I.packageRoot))){if(C.has(h.appId)){s.push(Q("RESERVED_ID",I.source,I.packageRoot,h.appId));continue}U.push({packageRoot:h.packageRoot,source:h.source,appId:h.appId,summary:h.summary});}}let F=[...Lp(i.diagnostics,new Set(a.map(I=>I.packageRoot))),...s,...n.registeredProductBundle?.diagnostics.filter(I=>I.source==="bundled").map(Hr)??[]],D=[];if(t)for(let I of t.listMcpApps()){let h=Pp(I);"diagnostic"in h?F.push(h.diagnostic):D.push(h);}let b=Mp([...U,...D],F);Sp(b,n,F);let R=b.map(I=>I.summary).sort((I,h)=>lt(I.appId,h.appId)),y=[...F].sort((I,h)=>lt(I.relativePath,h.relativePath)||lt(I.code,h.code)||lt(I.appId??"",h.appId??""));return Object.freeze({items:Object.freeze(R),diagnostics:Object.freeze(y)})}m();m();m();function wp(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 wp(n).test(e)}catch{return false}}function At(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 Cp(e,n){return e.split("/").some(t=>un(t,n))}var $r=[{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&&At(n,".crewx","threads")},{label:".crewx/crewx.db",test:(e,n,t)=>!t&&At(n,".crewx","crewx.db")},{label:".crewx/*.log",test:(e,n,t)=>!t&&At(n,".crewx","*.log")},{label:".crewx/publish/",test:(e,n,t)=>t&&At(n,".crewx","publish")},{label:".crewx/",test:(e,n)=>Cp(n,".crewx")}];function fn(e,n,t){for(let i of $r)if(i.test(e,n,t))return i.label;return null}m();var Ce=class extends Error{constructor(t,i){super(`publish: [${t}]${i?` ${i}`:""}`);this.code=t;}code;name="PublishError"};function T(e,n){return new Ce(e,n)}function Gr(e,n){if(!n||/[\\\u0000]/.test(n)||ce.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.resolve(e),i=ce.resolve(t,...n.split("/"));if(!i.startsWith(`${t}${ce.sep}`))throw T("PACKAGE_PATH_TRAVERSAL","package root escaped the workspace");function o(f,g){let _;try{_=ne.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.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 _=ne.readdirSync(f,{withFileTypes:true});for(let P of _){let U=`${g}/${P.name}`,k=ce.join(f,P.name);if(P.isSymbolicLink())throw T("PACKAGE_SYMLINK",`symlink is not publishable: ${U}`);let N=fn(P.name,U,P.isDirectory());N?d.push({path:U,rule:N}):P.isDirectory()?l(k,U):P.isFile()&&c.push(U);}}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 Wr(e){let n=[],t=[];function i(o,r,s){let a;try{a=ne.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.join(o,c.name);if(c.isSymbolicLink()){let p;try{p=ne.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 Up=[{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 kp(e){return e.includes(0)}function Di(e,n,t){let i=[];for(let o of n){let r=ce.join(e,o),s;try{let c=t?.get(o);s=c===void 0?ne.readFileSync(r):Buffer.from(c);}catch{continue}if(kp(s))continue;s.toString("utf8").split(/\r\n|\r|\n/).forEach((c,d)=>{for(let{rule:l,regex:p}of Up)p.test(c)&&i.push({path:o,line:d+1,rule:l});});}return i}m();var Xr=/^[a-z0-9-]+$/,xp=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/,vp=/^[A-Za-z_][A-Za-z0-9_]*$/;function jp(e){let n=ce.join(e,"crewx.yaml");if(!ne.existsSync(n))return {};let t;try{t=Yr.load(ne.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 Fp(e){return bi.createHash("sha256").update(e).digest("hex")}function qr(e){let n;try{n=ne.lstatSync(e);}catch{throw T("PACKAGE_FILE_INVALID",`file is not readable: ${ce.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 bi.createHash("sha256").update(new Uint8Array(ne.readFileSync(e))).digest("hex")}function Vp(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 Zr(e){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||ce.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 Bp(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 Qr(e){if(!xp.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=jp(e),o=i.name??ce.basename(e);if(!Xr.test(o))throw new Error(`publish: invalid name "${o}" \u2014 must match ${Xr} (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");Qr(r);let s=Array.isArray(i.requiredEnv)?i.requiredEnv:[],a=[];for(let l of s){if(typeof l!="string"||!vp.test(l))throw new Error(`publish: requiredEnv must contain names only (no values), got "${String(l)}"`);a.push(l);}let c=n.map(l=>(Zr(l),{path:l,sha256:qr(ce.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 Hp(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 ns(e,n){if(Bp(n.packageRoot),!n.version)throw new Error("publish: version is required for App publishing \u2014 pass opts.version");if(Qr(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(Zr(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?qr(ce.join(e,s)):Fp(a),...a===void 0?{}:{generated:true}}}).sort((s,a)=>Vp(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:Hp(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 ts(e){return bi.createHash("sha256").update(e).digest("hex")}function as(e,n){if(typeof n!="string"||n.length===0||n.includes("\\")||n.includes("\0")||ce.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.resolve(e),i=ce.resolve(t,...n.split("/"));if(i!==t&&!i.startsWith(`${t}${ce.sep}`))throw T("PACKAGE_PATH_TRAVERSAL","archive path escaped its root");return i}function is(e,n){let t=as(e,n),i;try{i=ne.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(ne.readFileSync(t))}async function cs(e,n,t={}){let i=ce.join(e,".crewx","publish");ne.mkdirSync(i,{recursive:true});let o=ce.join(i,`${n.name}-${n.version}.tgz`),r=ce.join(i,`.${n.name}-${n.version}.${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}.tmp.tgz`),s=ne.mkdtempSync(ce.join(os.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=is(e,d.path);if(t.sourceFileHashes.get(d.path)!==ts(f))throw T("PACKAGE_STAGED_BYTES_MISMATCH","workspace source changed before staging")}let p=l??is(e,d.path);if(ts(p)!==d.sha256)throw T("PACKAGE_STAGED_BYTES_MISMATCH",`staged bytes differ for ${d.path}`);let u=as(s,d.path);ne.mkdirSync(ce.dirname(u),{recursive:!0}),ne.writeFileSync(u,new Uint8Array(p)),c.push(d.path);}ne.writeFileSync(ce.join(s,"manifest.json"),JSON.stringify(n,null,2)),await ss.create({gzip:!0,file:r,cwd:s,portable:!0,noMtime:!0},["manifest.json",...c]),ne.renameSync(r,o);}finally{try{ne.rmSync(r,{force:!0});}catch{}ne.rmSync(s,{recursive:true,force:true});}return o}m();m();var yn="/api/v1";var Gp=201,Wp=200,Jp=409,Si=401,ds={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 Kp(){return process.env.WI013_FAKE_UPLOAD==="1"}function Xp(e){let n=gunzipSync(new Uint8Array(e)),t=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 Yp(e){return e.replace(/\/+$/,"")}async function Cn(e){try{return await e.json()}catch{return null}}function ps(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 qp(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 Zp(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 ls(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(ds,r))continue;let s=r,a=s==="APP_NAME_CONFLICT"?`marketplace name is already in use: ${n}`:void 0;return T(ds[s],a)}}async function Qp(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=Yp(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 Cn(a),d=qp(c),l=Zp(c),p=r&&l!==void 0?l:i,u;if(a.status===Gp)u="created";else if(r&&a.status===Wp){if(d===void 0)throw T("PUBLISH_CONTENT_ID_MISSING","App republish did not return an opaque contentId");u="existing";}else if(a.status===Jp){if(r)throw ls(c,i)??T("APP_NAME_CONFLICT",`marketplace name is already in use: ${i}`);u="existing";}else throw a.status===Si?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 R=await Cn(b);if(b.status!==200)throw new Error(`publish: [E_HTTP] Publisher items request failed \u2014 HTTP ${b.status}`);let I=ps(R,"publisher items",b.status)?.items;if(!Array.isArray(I))throw new Error(`publish: [E_MALFORMED] Publisher items response is malformed (expected data.items[]) \u2014 HTTP ${b.status}`);let h=I.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 Cn(E),E.status===Si?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 _=ne.readFileSync(e.tgzPath),P=Kp()?Xp(_):_,U=new FormData;U.set("archive",new Blob([new Uint8Array(P)],{type:"application/gzip"}),`${p}-${e.manifest.version}.tgz`);let k=r&&d!==void 0?d:i,N;try{N=await fetch(`${n}${yn}/publisher/items/${encodeURIComponent(k)}/upload`,{method:"POST",headers:{Authorization:`Bearer ${e.accessToken}`},body:U});}catch{throw new Error("publish: [E_NETWORK] Upload request failed (network)")}if(N.status===Si)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 Cn(N);if(r){let R=ls(b,p);if(R)throw R}throw new Error(`publish: [E_HTTP] Upload request failed \u2014 HTTP ${N.status}`)}let C=await Cn(N),F=ps(C,"upload",N.status),D=typeof F.contentId=="string"&&F.contentId.length>0?F.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:F.artifactChecksum,artifactSizeBytes:F.artifactSizeBytes,submitOutcome:u,versionUpdate:f,serverVersionBefore:g}}var el=1e4,nl=100*1024*1024;function Mi(e){return bi.createHash("sha256").update(e).digest("hex")}function tl(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function Un(e,n){if(!n||n.includes("\\")||n.includes("\0")||ce.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.resolve(e,...n.split("/")),i=ce.resolve(e);if(t!==i&&!t.startsWith(`${i}${ce.sep}`))throw T("PACKAGE_PATH_TRAVERSAL","workspace file path escaped the workspace root");let o;try{o=ne.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(ne.readFileSync(t))}function fs(e,n,t){let i=e??n;if(!Number.isSafeInteger(i)||i<=0)throw new Ce("PACKAGE_SIZE_LIMIT",`${t} must be a positive integer`);return i}function As(e,n,t,i){let o=fs(t.maxFileCount??t.maxFiles,el,"max file count"),r=fs(t.maxTotalBytes??t.maxBytes,nl,"max total bytes");if(n.length>o)throw new Ce("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+=Un(e,a).byteLength,s>r)throw new Ce("PACKAGE_SIZE_LIMIT",`package exceeds byte limit (${r})`)}}function il(e){return e.appId!==void 0||e.expectedDefinitionHash!==void 0}function ol(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 rl(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 sl(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 Li(e){let{path:n,rule:t}=e.reason;return `${e.code} at ${n===""?"<file>":n} (${t})`+(e.files.length>0?` [${e.files.join(", ")}]`:"")}function al(e,n,t){let i=Ge({[de]:t},{mode:"published"});if(!i.ok)throw T("APP_UI_MANIFEST_INVALID",`generated ${de} does not read: ${Li(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[W];if(o===void 0)return;let r=e[H],s=Ge({[W]:o,[de]:t,...r===void 0?{}:{[H]:r}},{mode:"local"});if(!s.ok)throw T("APP_UI_MANIFEST_INVALID",Li(s.rejection))}function cl(e,n,t,i){let o={};for(let f of Z){let g=`${t}/${f}`;i.includes(g)&&(o[f]=Un(e,g));}let r=`${t}/${H}`;if(o[W]!==void 0&&i.includes(r)&&(o[H]=Un(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=Ge(o,{mode:"local"});if(!s.ok)throw T("APP_UI_MANIFEST_INVALID",Li(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:Mi(a),d=`${t}/ui/index.html`;if(!i.includes(d))throw T("APP_UI_MANIFEST_INVALID","screen entry is outside package scope");let l=Mi(Un(e,d)),p=JSON.parse(JSON.stringify(s.v2Input));if(p.entryHash=l,Object.prototype.hasOwnProperty.call(p,"initialState")){let f=p.initialState;if(!tl(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 _=Un(e,g);p.initialState={...f,hash:Mi(_)};}let u;try{let f=$e(p,{mode:"published"});u=new Uint8Array(Buffer.from(JSON.stringify(f),"utf8"));}catch(f){throw f instanceof se?T("APP_UI_MANIFEST_INVALID",f.code):T("APP_UI_MANIFEST_INVALID")}return al(o,s.manifest,u),{bytes:u,...c===void 0?{}:{legacySourceHash:c}}}async function dl(e,n){let{included:t,excluded:i}=Wr(e);As(e,t,n);let o=es(e,t,{version:n.version}),r=Di(e,t);return {plan:{manifest:o,included:t,excluded:i,secretFindings:r},archiveOptions:{}}}async function pl(e,n){ol(n);let t=await zr(e),i=rl(t.items,n.appId);if(i.definitionHash!==n.expectedDefinitionHash)throw T("APP_DEFINITION_CONFLICT",`definitionHash changed for ${n.appId}`);let o=sl(i),{included:r,excluded:s}=Gr(e,o),a=new Map,c=new Map;if(i.capabilities.includes("screen")){let u=cl(e,i,o,r),f=`${o}/${de}`;if(a.set(f,u.bytes),u.legacySourceHash!==void 0)c.set(f,u.legacySourceHash);else {r.push(f);let g=new TextEncoder;r.sort((_,P)=>Buffer.compare(g.encode(_),g.encode(P)));}}if(i.capabilities.includes("skill")&&!r.includes(`${o}/SKILL.md`))throw T("APP_SKILL_MISSING","skill capability requires package-root SKILL.md");As(e,r,n,a);let d={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:a},l=ns(e,d),p=Di(e,r,a);return {plan:{manifest:l,included:r,excluded:s,secretFindings:p},archiveOptions:{generatedFiles:a,sourceFileHashes:c}}}async function Is(e,n){let t=ce.resolve(e);if(il(n))return pl(t,n);if(n.expectedDefinitionHash!==void 0)throw T("APP_ID_REQUIRED");return dl(t,n)}async function cA(e,n={}){return (await Is(e,n)).plan}function ll(e){let n=e.map(t=>`${t.path}:${t.line} (${t.rule})`).join(", ");throw new Ce("PUBLISH_SECRET_FINDINGS",`aborted \u2014 secret findings must be resolved before packing: ${n}`)}async function gs(e,n={}){let t=ce.resolve(e),i=await Is(t,n);i.plan.secretFindings.length>0&&ll(i.plan.secretFindings);let o=await cs(t,i.plan.manifest,i.archiveOptions);return {manifest:i.plan.manifest,tgzPath:o}}async function dA(e,n={}){return gs(e,n)}async function pA(e,n){let t=await gs(e,n);if(t.manifest.type!=="app")throw new Error("publish: App pack unexpectedly produced a template manifest");return t}
|
|
2
|
-
export{
|
|
1
|
+
import*as ce from'path';import {resolve,relative,sep,isAbsolute,join}from'path';import'url';import*as Li from'crypto';import {createHash}from'crypto';import {isIP}from'net';import*as ne from'fs';import {constants,readFileSync,existsSync,statSync,readdirSync}from'fs';import {realpath,stat,readdir,open,lstat}from'fs/promises';import*as Qr from'js-yaml';import {load}from'js-yaml';import*as as from'os';import*as ds from'tar';import {gunzipSync,gzipSync}from'zlib';var V=(e,n)=>()=>(e&&(n=e(e=0)),n);var m=V(()=>{});var x,xn=V(()=>{m();x=class extends Error{constructor(t,i=t,o){super(i);this.code=t;this.currentRevision=o;}code;currentRevision;name="UiRuntimeError"};});function Tt(e){return Ts.test(e)||Ps.test(e)}function fe(){throw new x("INPUT_INVALID","JSON value is not projection-safe")}function Ss(e){let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function _t(e,n,t,i,o,r){if(n>i&&fe(),e===null||typeof e=="string"||typeof e=="boolean")return typeof e=="string"&&(Ds.test(e)||bs.test(e)&&!Rs(o,r)||Ns.test(e))&&fe(),e;if(typeof e=="number")return Number.isFinite(e)||fe(),e;(typeof e!="object"||e===void 0||typeof e=="function"||typeof e=="bigint")&&fe();let s=e;t.has(s)&&fe(),t.add(s);try{if(Array.isArray(e))return e.map(c=>_t(c,n+1,t,i,o,r));Ss(s)||fe();let a={};for(let[c,d]of Object.entries(e))Tt(c)&&fe(),a[c]=_t(d,n+1,t,i,[...o,c],r);return a}finally{t.delete(s);}}function ye(e,n=0,t=[]){(!Number.isInteger(n)||n<0||n>Ls)&&fe(),(!Array.isArray(t)||t.some(o=>typeof o!="string"))&&fe();let i=_t(e,0,new Set,Ms+n,[],t);return (i===null||Array.isArray(i)||typeof i!="object")&&fe(),i}function Ze(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 Rs(e,n){if(e.length===0)return false;let t=e.join(".");return n.some(i=>Ze(t,i))}function Qe(e){try{let n=JSON.stringify(e);return n===void 0&&fe(),n}catch{fe();}}function Et(e){return Array.isArray(e)?e.map(Et):e!==null&&typeof e=="object"?Object.fromEntries(Object.keys(e).sort().map(n=>[n,Et(e[n])])):e}function te(e){return Qe(Et(e))}function Pt(e){return Buffer.byteLength(e,"utf8")}var Ts,Ps,Ds,Ns,bs,Ms,Ls,Le=V(()=>{m();xn();Ts=/(?:proof|token|secret|password|cookie|authorization|private[_-]?key|stack|exception|plugin[_-]?text)/i,Ps=/(?:url|uri|endpoint|path|file(?:name|path)?|cwd|shell|directory|dir|folder)$/i,Ds=/<\/?[A-Za-z][^>]*>/,Ns=/^(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)/,bs=/^(?:https?|file|ftp|ws|wss):\/\//i;Ms=8,Ls=4;});var Ci=V(()=>{m();Le();});var vn,Dt=V(()=>{m();vn=["text/plain","application/json"];});var ki=V(()=>{m();Dt();});function en(e){return ws.has(e)||Cs.test(e)||ks.test(e)}var Ui,ws,Cs,ks,jn,An,Te,Nt,bt,St,Mt,Lt,Be=V(()=>{m();Ui=["__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"],ws=new Set(Ui),Cs=/(?:proof|token|secret|password|cookie|authorization|private[_-]?key|stack|exception|plugin[_-]?text)/i,ks=/(?:url|uri|endpoint|path|file(?:name|path)?|cwd|shell|directory|dir|folder)$/i;jn=/^[A-Za-z0-9_]+$/,An=/^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)*$/,Te=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,Nt=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/,bt=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,St=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/,Mt=["blue","violet","emerald","amber","rose","sky","slate","indigo"],Lt=["inline","panel"];});function Rt(e){return typeof e=="string"&&vn.includes(e)}var xi=V(()=>{m();Dt();Be();});function Fn(e){if(!Ot(e))return false;let n=Object.keys(e);return !(n.some(t=>t!=="in"&&t!=="out")||n.length===0||Object.hasOwn(e,"in")&&!Us(e.in)||Object.hasOwn(e,"out")&&!xs(e.out))}function Us(e){return Ot(e)?Object.keys(e).every(t=>t==="mediaType"||t==="required")&&Object.hasOwn(e,"mediaType")&&Rt(e.mediaType)&&(!Object.hasOwn(e,"required")||typeof e.required=="boolean"):false}function xs(e){return Ot(e)?Object.keys(e).every(t=>t==="mediaType"||t==="range")&&Object.hasOwn(e,"mediaType")&&Rt(e.mediaType)&&(!Object.hasOwn(e,"range")||typeof e.range=="boolean"):false}function Ot(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}var wt=V(()=>{m();ki();xi();new TextDecoder("utf-8",{fatal:true,ignoreBOM:true});});function le(e){let t=e.renderer!==void 0||e.surfaces!==void 0||e.stateProjection!==void 0||e.dataPaths!==void 0||e.usage!==void 0||e.detailPanel!==void 0||e.displayModes!==void 0||e.summaryProjection!==void 0||e.legacy!==void 0||Object.values(e.actions).some(o=>o.resultProjection!==void 0)?{id:e.id,version:e.version,...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=ye(t);return createHash("sha256").update(te(i)).digest("hex")}function kt(e){return `${e.id}\0${e.version}`}function Ae(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"||!js.test(e.sourceHash)))throw new x("DEFINITION_UNSUPPORTED","UI definition source hash is invalid");if(!/^[0-9a-f]{64}$/.test(e.hash)||le(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=>!Vs(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&&Ct(t.resultProjection),t.content!==void 0&&!Fn(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&&Ct(e.stateProjection),e.summaryProjection){Ct(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(Fs(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=>Ze(t,i))))throw new x("DEFINITION_UNSUPPORTED","UI definition dataPaths are invalid")}}function Fs(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=ye(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=ye(a.structuredContent);if(Pt(Qe(c))>4*1024)throw new Error("fixed result size")}}catch{throw new x("DEFINITION_UNSUPPORTED","UI legacy tool metadata is not projection-safe")}}function Ct(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 Vs(e){return e.length>0&&e.length<=128&&e!=="*"&&e!=="all"&&!/[/*]/.test(e)}var js,He=V(()=>{m();Le();xn();wt();js=/^[0-9a-f]{64}$/;});var H,nn,Ut=V(()=>{m();H="dist/tools.json",nn="dist/main.mjs";});var xe,xt=V(()=>{m();xe="window";});function vi(e){if(!Array.isArray(e)||e.length===0)return false;let n=new Set;for(let t of e){if(!Bs.some(i=>i===t)||n.has(t))return false;n.add(t);}return true}var Bs,ji=V(()=>{m();Bs=["CREWX_APP_INSTANCE_ID","CREWX_THREAD_ID"];});function z(e){throw new vt(e)}function Qs(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 ea(e,n){let t=Object.getOwnPropertyDescriptor(e,n);return (!t||!("value"in t))&&z("CSP_ORIGIN_INVALID"),t.value}function Vn(e,n){if(!Object.prototype.hasOwnProperty.call(e,n))return [];let t=ea(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 na(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 Bi(e,n){/\s|\\/u.test(e)&&z("CSP_ORIGIN_INVALID");let t=Ks.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("[")?Xs:Ys).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||!qs.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 ta(e){let n=e.split(".").map(Number);return ((n[0]*256+n[1])*256+n[2])*256+n[3]}function Hi(e,n,t){let i=4294967295<<32-t>>>0;return (e&i)===(n&i)}function Gi(e){let n=ta(e);return Hi(n,3221225472,24)?n!==3221225481&&n!==3221225482:Zs.some(([t,i])=>Hi(n,t,i))}function ia(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 oa(e){let n=ia(e),t=Number(n>>112n),i=Number(n>>96n&0xffffn);if(n>>32n===0xffffn){let o=Number(n&0xffffffffn);return Gi([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 ra(e,n){let t=e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e,i=isIP(t);if(i===4)return Gi(t);if(i===6)return oa(t);let o=e.toLowerCase().replace(/\.$/,"");return !o||!o.includes(".")||n.has(o)?true:Js.some(r=>o===r||o.endsWith(`.${r}`))}function zi(e){return Object.freeze([...new Set(e.map(n=>n.origin))].sort())}function $i(e){return JSON.stringify({baseUriDomains:[],connectDomains:e.connectDomains,declared:e.declared,frameDomains:e.frameDomains,resourceDomains:[]})}function Wi(e,n={}){if(e===void 0){let f=$i({declared:false,connectDomains:[],frameDomains:[]});return Object.freeze({declared:false,connectDomains:Object.freeze([]),frameDomains:Object.freeze([]),resourceDomains:Object.freeze([]),baseUriDomains:Object.freeze([]),cspHash:createHash("sha256").update(f,"utf8").digest("hex")})}Qs(e)||z("CSP_ORIGIN_INVALID");let t=Reflect.ownKeys(e);t.some(f=>typeof f!="string")&&z("CSP_ORIGIN_INVALID"),t.some(f=>!Ws.has(f))&&z("CSP_AXIS_UNKNOWN");let i=Vn(e,"connectDomains"),o=Vn(e,"frameDomains"),r=Vn(e,"resourceDomains"),s=Vn(e,"baseUriDomains");(r.length>0||s.length>0)&&z("CSP_AXIS_UNSUPPORTED"),(na(e)>zs||i.length>Vi||o.length>Vi||i.length+o.length>$s||[...i,...o].some(f=>new TextEncoder().encode(f).byteLength>Gs))&&z("CSP_LIMIT_EXCEEDED");let c=i.map(f=>Bi(f,"connectDomains")),d=o.map(f=>Bi(f,"frameDomains")),l=new Set((n.runtimeHostnames??[]).map(f=>f.toLowerCase().replace(/\.$/,"")));[...c,...d].some(f=>ra(f.hostname,l))&&z("CSP_ORIGIN_FORBIDDEN");let p={declared:true,connectDomains:zi(c),frameDomains:zi(d)},u=$i(p);return Object.freeze({...p,resourceDomains:Object.freeze([]),baseUriDomains:Object.freeze([]),cspHash:createHash("sha256").update(u,"utf8").digest("hex")})}var zs,Vi,$s,Gs,Ws,Js,Ks,Xs,Ys,qs,Zs,vt,Ji=V(()=>{m();zs=4096,Vi=16,$s=32,Gs=512,Ws=new Set(["connectDomains","frameDomains","resourceDomains","baseUriDomains"]),Js=["localhost","local","internal","home.arpa","test","example","invalid","onion","lan","corp","home","intranet","private","localdomain"],Ks=/^(https|wss):\/\/([^/?#]+)$/i,Xs=/^\[[^\]]+\](?::[0-9]+)?$/,Ys=/^[^:\[\]]+(?::[0-9]+)?$/,qs=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/,Zs=[[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]],vt=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 A(e,n=e,t,i){throw new se(e,n,t,i)}function $(e,n){try{return n()}catch(t){throw t instanceof se?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 v(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function Ca(e,n){let t={};for(let[i,o]of Object.entries(e))i!==n&&(t[i]=o);return t}function X(e,n,t=[]){let i=new Set([...n,...t]),o=Object.keys(e).find(s=>!i.has(s));o!==void 0&&A("MANIFEST_INVALID","MANIFEST_INVALID",o,"unknown-key");let r=n.find(s=>!v(e,s));r!==void 0&&A("MANIFEST_INVALID","MANIFEST_INVALID",r,"missing-key");}function $n(e,n=false,t=false,i=false){return da.test(e)||!i&&la.test(e)||pa.test(e)||t&&Ki.test(e)||ua.test(e)&&!(n&&/^\s*data:/i.test(e)&&!Ki.test(e))}function zn(e,n=new Set,t=0,i=false,o=false,r=""){if(typeof e=="string"){$n(e,i,o)&&A("UNSAFE_VALUE","UNSAFE_VALUE",r,"unsafe-value");return}if(!(e===null||typeof e!="object")){(t>8||n.has(e))&&A("MANIFEST_INVALID","MANIFEST_INVALID",r),n.add(e);try{if(Array.isArray(e)){e.forEach((s,a)=>zn(s,n,t+1,!1,!1,gn(r,`[${a}]`)));return}G(e)||A("MANIFEST_INVALID","MANIFEST_INVALID",r);for(let[s,a]of Object.entries(e))zn(a,n,t+1,i&&t===0&&(s==="name"||s==="description"),o,gn(r,s));}finally{n.delete(e);}}}function Pe(e,n){let t=e[n];return typeof t!="string"&&A("MANIFEST_INVALID"),t}function ge(e,n,t){let i=e[n];return (!Number.isSafeInteger(i)||i<t)&&A("MANIFEST_INVALID"),i}function jt(e){return ca.test(e)||A("MANIFEST_INVALID"),e}function tn(e){return aa.test(e)||A("TOKEN_INVALID"),e}function ka(e){return io.test(e)||A("MANIFEST_INVALID"),e}function Ua(e){G(e)||A("MANIFEST_INVALID");let n={};for(let[t,i]of Object.entries(e)){let o=ka(t);G(i)||A("MANIFEST_INVALID");let r=i.type;if(r==="text"){X(i,["type","maxLength"]),n[o]={type:r,maxLength:ge(i,"maxLength",1)};continue}if(r==="text-list"){X(i,["type","max","itemMaxLength"]),n[o]={type:r,max:ge(i,"max",0),itemMaxLength:ge(i,"itemMaxLength",1)};continue}if(r==="step-list"){X(i,["type","min","max","labelMaxLength","detailMaxLength"]);let s=ge(i,"min",0),a=ge(i,"max",1);s>a&&A("MANIFEST_INVALID"),n[o]={type:r,min:s,max:a,labelMaxLength:ge(i,"labelMaxLength",1),detailMaxLength:ge(i,"detailMaxLength",1)};continue}typeof r=="string"&&A("SCHEMA_TYPE_UNSUPPORTED"),A("MANIFEST_INVALID");}return n}function xa(e,n,t){let i=e[n];(!i||i.type!==t)&&A("MANIFEST_INVALID");}function Bn(e,n,t){let i=Pe(e,"field");return io.test(i)||A("MANIFEST_INVALID"),xa(n,i,t),i}function va(e,n){G(e)||A("MANIFEST_INVALID");let t=e.primitive;switch(typeof t!="string"&&A("MANIFEST_INVALID"),wa.includes(t)||A("PRIMITIVE_UNKNOWN"),t){case "card-shell":return X(e,["primitive"]),{primitive:t};case "meta-banner":return X(e,["primitive","badgeToken","noticeToken"]),{primitive:t,badgeToken:tn(Pe(e,"badgeToken")),noticeToken:tn(Pe(e,"noticeToken"))};case "heading":return X(e,["primitive","field"]),{primitive:t,field:Bn(e,n,"text")};case "labeled-text":return X(e,["primitive","titleToken","field","variant"]),e.variant!=="callout"&&A("MANIFEST_INVALID"),{primitive:t,titleToken:tn(Pe(e,"titleToken")),field:Bn(e,n,"text"),variant:"callout"};case "step-flow":return X(e,["primitive","titleToken","field"]),{primitive:t,titleToken:tn(Pe(e,"titleToken")),field:Bn(e,n,"step-list")};case "text-list":{X(e,["primitive","titleToken","field"],["emptyToken","hideWhenEmpty"]);let i={primitive:t,titleToken:tn(Pe(e,"titleToken")),field:Bn(e,n,"text-list")};return v(e,"emptyToken")&&(i.emptyToken=tn(Pe(e,"emptyToken"))),v(e,"hideWhenEmpty")&&(typeof e.hideWhenEmpty!="boolean"&&A("MANIFEST_INVALID"),i.hideWhenEmpty=e.hideWhenEmpty),i}}return A("MANIFEST_INVALID")}function ja(e,n){return Array.isArray(e)||A("MANIFEST_INVALID"),e.map(t=>va(t,n))}function Y(e="v2 manifest exceeds a contract limit",n,t){return A("LIMIT_EXCEEDED",e,n,t)}function Ie(e="initial state is not projection-safe"){return A("INITIAL_STATE_INVALID",e)}function Xi(e,n){return (typeof e!="string"||e.length===0||e.length>4096||e.trim().length===0||La.test(e)||Ra.test(e))&&A("MANIFEST_INVALID",`${n} is invalid`),($n(e,true,true)||fa.test(e)||ya.test(e)||Aa.test(e))&&A("UNSAFE_VALUE",`${n} contains an unsafe value`),e}function Ft(e,n){return (typeof e!="string"||!Te.test(e))&&A("MANIFEST_INVALID",`${n} is invalid`),e}function Fa(e){return (typeof e!="string"||!Nt.test(e)||e==="*"||e==="all")&&A("MANIFEST_INVALID","action capability is invalid"),e}function oo(e){return (typeof e!="string"||!Ma.test(e))&&A("MANIFEST_INVALID","resource hash is invalid"),e}function Vt(e,n=new Set,t=0,i=""){if(typeof e=="string"){e.length>4096&&Y("v2 manifest string is too long",i,"string-too-long");return}if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){Number.isFinite(e)||A("MANIFEST_INVALID","v2 manifest contains a non-finite number",i,"non-finite-number");return}(e===void 0||typeof e=="function"||typeof e=="bigint")&&A("MANIFEST_INVALID","v2 manifest contains a non-JSON value",i,"non-json-value"),typeof e!="object"&&A("MANIFEST_INVALID","MANIFEST_INVALID",i),t>8&&Y("v2 manifest nesting is too deep",i,"too-deep"),n.has(e)&&A("MANIFEST_INVALID","v2 manifest contains a cycle",i,"cycle"),n.add(e);try{if(Array.isArray(e)){e.length>128&&Y("v2 manifest array is too long",i,"array-too-long"),e.forEach((o,r)=>Vt(o,n,t+1,gn(i,`[${r}]`)));return}G(e)||A("MANIFEST_INVALID","v2 manifest contains a non-plain object",i,"non-plain-object");for(let[o,r]of Object.entries(e))Vt(r,n,t+1,gn(i,o));}finally{n.delete(e);}}}function ro(e){return (typeof e!="string"||e.length>4096||!An.test(e))&&(typeof e=="string"&&e.length>4096&&Y("projection path is too long"),A("MANIFEST_INVALID","projection paths must be canonical exact paths")),e.split(".").some(t=>en(t))&&A("MANIFEST_INVALID","projection paths cannot address reserved state keys"),e}function Bt(e){G(e)||A("MANIFEST_INVALID","projection policy must be an object"),X(e,["allow"]),Array.isArray(e.allow)||A("MANIFEST_INVALID","projection allow must be an array"),e.allow.length>128&&Y("projection allowlist is too long");let n=[],t=new Set;for(let i of e.allow){let o=ro(i);t.has(o)&&A("MANIFEST_INVALID","projection allowlist contains a duplicate path"),t.add(o),n.push(o);}return {allow:n}}function Va(e,n){if(e===void 0)return;Array.isArray(e)||A("MANIFEST_INVALID","dataPaths must be an array"),e.length>Oa&&Y("dataPaths exceed the v2 limit");let t=[],i=new Set;for(let o of e){let r=ro(o);i.has(r)&&A("MANIFEST_INVALID","dataPaths contain a duplicate path"),n.some(s=>Ze(r,s))||A("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)&&A("MANIFEST_INVALID",`${n} is invalid`),e}function Yi(e,n){return (typeof e!="number"||!Number.isFinite(e))&&A("MANIFEST_INVALID",`${n} is invalid`),e}function Ht(e,n=0,t=new Set){if(typeof e=="string")return (e.length>4096||$n(e))&&A("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)||A("MANIFEST_INVALID","schema enum contains a non-finite number"),e;(n>8||typeof e!="object"||e===void 0)&&Y("schema enum is too deep"),t.has(e)&&A("MANIFEST_INVALID","schema enum contains a cycle"),t.add(e);try{if(Array.isArray(e))return e.length>128&&Y("schema enum array is too long"),e.map(o=>Ht(o,n+1,t));G(e)||A("MANIFEST_INVALID","schema enum contains a non-plain object");let i={};for(let[o,r]of Object.entries(e))en(o)&&A("MANIFEST_INVALID","schema enum contains a reserved key"),i[o]=Ht(r,n+1,t);return i}finally{t.delete(e);}}function Ba(e,n){if(e===void 0)return;Array.isArray(e)||A("MANIFEST_INVALID","schema required must be an array"),e.length>64&&Y("schema required list is too long");let t=[],i=new Set;for(let o of e)(typeof o!="string"||!An.test(o))&&A("MANIFEST_INVALID","schema required contains an invalid key"),o.length>4096&&Y("schema required key is too long"),i.has(o)&&A("MANIFEST_INVALID","schema required contains a duplicate key"),n&&!Object.prototype.hasOwnProperty.call(n,o)&&A("MANIFEST_INVALID","schema required references an undeclared property"),i.add(o),t.push(o);return t}function Ha(e,n){let t=n?An:jn;return e.length>4096&&Y("schema property name is too long"),(!t.test(e)||e.split(".").some(i=>en(i)))&&A("MANIFEST_INVALID","schema property name is invalid"),e}function zt(e,n=0,t=false){G(e)||A("MANIFEST_INVALID","action inputSchema must be an object"),n>8&&Y("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"&&A("SCHEMA_TYPE_UNSUPPORTED","action inputSchema type is unsupported"),A("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"),X(e,["type"],o.filter(a=>a!=="type"));let r={type:i};if(v(e,"enum")&&(Array.isArray(e.enum)||A("MANIFEST_INVALID","schema enum must be an array"),e.enum.length>128&&Y("schema enum is too long"),r.enum=e.enum.map(a=>Ht(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&&A("MANIFEST_INVALID","schema string length bounds are inverted")),(i==="number"||i==="integer")&&(v(e,"minimum")&&(r.minimum=Yi(e.minimum,"schema minimum")),v(e,"maximum")&&(r.maximum=Yi(e.maximum,"schema maximum")),r.minimum!==void 0&&r.maximum!==void 0&&r.minimum>r.maximum&&A("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&&A("MANIFEST_INVALID","schema array length bounds are inverted"),v(e,"items")&&(r.items=zt(e.items,n+1,false))),i==="object"){let a;if(v(e,"properties")){G(e.properties)||A("MANIFEST_INVALID","schema properties must be an object");let d=Object.entries(e.properties);d.length>64&&Y("schema properties are too many"),a={};for(let[l,p]of d){let u=Ha(l,t);a[u]=zt(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&&A("MANIFEST_INVALID","schema object property bounds are inverted");let c=Ba(e.required,a);c!==void 0&&(r.required=c),v(e,"additionalProperties")&&(e.additionalProperties!==false&&A("MANIFEST_INVALID","schema additionalProperties must be false"),r.additionalProperties=false);}let s=JSON.stringify(r);return (s===void 0||Buffer.byteLength(s,"utf8")>2097152)&&Y("action inputSchema subtree is too large"),r}function za(e){let n=zt(e,0,true);return (n.type!=="object"||!n.properties)&&A("MANIFEST_INVALID","action inputSchema must declare object properties"),n}function $a(e){if(G(e)||A("MANIFEST_INVALID","action backend must be an object"),e.type==="core"){X(e,Ta);let n=e.handler;return (typeof n!="string"||!bt.test(n))&&A("MANIFEST_INVALID","core backend handler is invalid"),{type:"core",handler:n}}if(e.type==="skill"&&v(e,"entry"))return X(e,Na),e.entry!==nn&&A("MANIFEST_INVALID",`skill backend entry must be ${nn}`),{type:"skill",entry:nn};if(e.type==="skill"){X(e,Pa,Da),(!Array.isArray(e.command)||e.command.length===0||e.command.length>16)&&A("MANIFEST_INVALID","skill backend command is invalid");let n=[];for(let i of e.command)(typeof i!="string"||i.length===0||i.length>256||!St.test(i))&&A("MANIFEST_INVALID","skill backend command token is invalid"),n.push(i);let t=v(e,"env")?Wa(e.env):void 0;return {type:"skill",command:n,...t===void 0?{}:{env:t}}}A("MANIFEST_INVALID","action backend type is unsupported");}function Ga(e){G(e)||A("MANIFEST_INVALID","action must be an object"),X(e,ha,_a),v(e,"_meta")&&$("_meta",()=>so(e._meta));let n=$("actionId",()=>Ft(e.actionId,"actionId"));Tt(n)&&A("MANIFEST_INVALID",`actionId "${n}" is not projection-safe`,"actionId");let t=$("capability",()=>Fa(e.capability)),i=e.mutation;typeof i!="boolean"&&A("MANIFEST_INVALID","action mutation must be boolean","mutation");let o=$("inputSchema",()=>za(e.inputSchema)),r;if(v(e,"dataInputs")){Array.isArray(e.dataInputs)||A("MANIFEST_INVALID","action dataInputs must be an array","dataInputs");let l=o.properties,p=new Set,u=[];for(let f of e.dataInputs)(typeof f!="string"||!v(l,f)||p.has(f))&&A("MANIFEST_INVALID","action dataInputs must be unique declared properties","dataInputs"),p.add(f),u.push(f);r=u;}let s=$("resultProjection",()=>Bt(e.resultProjection)),a=$("backend",()=>$a(e.backend)),c;v(e,"content")&&((a.type!=="skill"||!Fn(e.content))&&A("MANIFEST_INVALID","action content declaration is invalid","content"),c=Ja(e.content));let d;if(v(e,"confirmation")){let l=e.confirmation;l!=="none"&&l!=="native"&&A("MANIFEST_INVALID","action confirmation is invalid","confirmation"),d=l;}return {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}}}function Wa(e){return vi(e)||A("MANIFEST_INVALID","skill backend env is invalid"),Object.freeze([...e])}function Ja(e){return Object.freeze({...e.in===void 0?{}:{in:Object.freeze({...e.in})},...e.out===void 0?{}:{out:Object.freeze({...e.out})}})}function Ka(e){return G(e)||A("INITIAL_STATE_INVALID","initialState must be an object"),X(e,ba,Sa),e.path!=="ui/state.json"&&A("MANIFEST_INVALID","initialState path is not fixed"),v(e,"hash")?{path:"ui/state.json",hash:oo(e.hash)}:{path:"ui/state.json"}}function Xa(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))&&A("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 Ya(e,n){let t;try{t=Wi(e);}catch(i){let o=i!==null&&typeof i=="object"&&"code"in i&&typeof i.code=="string"?i.code:"CSP_ORIGIN_INVALID";return A("MANIFEST_INVALID",o,void 0,o.toLowerCase().replace(/_/g,"-"))}if(t.frameDomains.length>0&&A("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&&A("MANIFEST_INVALID","runtime.terminal cannot be combined with csp.connectDomains","connectDomains","terminal-with-connect-domains"),Object.freeze({connectDomains:t.connectDomains})}function qa(e,n){zn(G(e)&&v(e,"csp")?Ca(e,"csp"):e,new Set,0,true,true),Vt(e),G(e)||A("MANIFEST_INVALID"),X(e,ga,ma),v(e,"_meta")&&$("_meta",()=>so(e._meta)),e.manifestVersion!==2&&A("MANIFEST_INVALID");let t;v(e,"runtime")&&(t=$("runtime",()=>Xa(e.runtime)));let i;v(e,"csp")&&(i=$("csp",()=>Ya(e.csp,t)));let o=$("pluginId",()=>Ft(e.pluginId,"pluginId")),r=$("definitionId",()=>Ft(e.definitionId,"definitionId")),s=$("version",()=>ge(e,"version",1)),a=$("name",()=>Xi(e.name,"name")),c=$("description",()=>Xi(e.description,"description")),d;v(e,"icon")&&((typeof e.icon!="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(e.icon))&&A("MANIFEST_INVALID","icon is invalid","icon"),d=e.icon);let l;v(e,"tone")&&((typeof e.tone!="string"||!Mt.includes(e.tone))&&A("MANIFEST_INVALID","tone is invalid","tone"),l=e.tone),e.entry!=="ui/index.html"&&A("MANIFEST_INVALID","entry path is not fixed","entry","fixed-value");let p;v(e,"entryHash")&&(p=$("entryHash",()=>oo(e.entryHash)));let u;v(e,"initialState")&&(u=$("initialState",()=>Ka(e.initialState)));let f;v(e,"usage")&&(e.usage!=="card"&&e.usage!=="window"&&A("MANIFEST_INVALID","usage is invalid","usage"),f=e.usage);let g;v(e,"detailPanel")&&(typeof e.detailPanel!="boolean"&&A("MANIFEST_INVALID","detailPanel is invalid","detailPanel"),g=e.detailPanel);let _;if(v(e,"displayModes")){((f??xe)!==xe||!Array.isArray(e.displayModes)||e.displayModes.length===0)&&A("MANIFEST_INVALID","displayModes are only valid for window Apps","displayModes");let y=new Set(["inline","floating","focused"]);(new Set(e.displayModes).size!==e.displayModes.length||e.displayModes.some(I=>typeof I!="string"||!y.has(I)))&&A("MANIFEST_INVALID","displayModes are invalid","displayModes"),_=e.displayModes;}(f??xe)===xe&&g!==void 0&&A("MANIFEST_INVALID","detailPanel is card-only","detailPanel");let P=n.mode??"local";P!=="local"&&P!=="installed"&&P!=="published"&&A("MANIFEST_INVALID","manifest mode is invalid"),P!=="local"&&p===void 0&&A("MANIFEST_INVALID","installed manifests require entryHash","entryHash","required-when-installed"),P!=="local"&&u!==void 0&&u.hash===void 0&&A("MANIFEST_INVALID","installed manifests require initialState.hash","initialState.hash","required-when-installed"),(!Array.isArray(e.surfaces)||e.surfaces.length===0)&&A("MANIFEST_INVALID","surfaces are invalid","surfaces"),e.surfaces.length>2&&Y("surfaces exceed the v2 limit","surfaces","too-many-items");let k=[],U=new Set;for(let y of e.surfaces)(typeof y!="string"||!Lt.includes(y))&&A("MANIFEST_INVALID","surface is unsupported","surfaces"),U.has(y)&&A("MANIFEST_INVALID","surfaces contain a duplicate","surfaces","duplicate-item"),U.add(y),k.push(y);G(e.size)||A("MANIFEST_INVALID","size must be an object","size"),$("size",()=>X(e.size,["height"]));let D=$("size",()=>ge(e.size,"height",1));D>720&&Y("size.height exceeds the v2 limit","size.height","too-large");let C=$("stateProjection",()=>Bt(e.stateProjection)),F=e.summaryProjection===void 0?void 0:$("summaryProjection",()=>Bt(e.summaryProjection));F!==void 0&&F.allow.some(y=>!C.allow.includes(y))&&A("MANIFEST_INVALID","summaryProjection must be a subset of stateProjection.allow","summaryProjection");let N=$("dataPaths",()=>Va(e.dataPaths,C.allow));Array.isArray(e.actions)||A("MANIFEST_INVALID","actions must be an array","actions"),e.actions.length>32&&Y("actions exceed the v2 limit","actions","too-many-items");let b=[],R=new Set;for(let[y,I]of e.actions.entries()){let h=`actions[${y}]`,E=$(h,()=>Ga(I));if(R.has(E.actionId)&&A("MANIFEST_INVALID","actions contain a duplicate actionId",`${h}.actionId`,"duplicate-item"),E.backend.type==="core"&&E.backend.handler==="state.set"){E.mutation||A("MANIFEST_INVALID","state.set actions must be mutations",`${h}.mutation`);for(let L of Object.keys(E.inputSchema.properties))C.allow.includes(L)||A("MANIFEST_INVALID","state.set input paths must be projection-allowed",`${h}.inputSchema.properties`);}R.add(E.actionId),b.push(E);}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:k,size:{height:D},stateProjection:C,...F===void 0?{}:{summaryProjection:F},...N===void 0?{}:{dataPaths:N},actions:b}}function so(e){G(e)||A("MANIFEST_INVALID","_meta must be an object");let n=JSON.stringify(e);(n===void 0||Buffer.byteLength(n,"utf8")>Ea)&&Y("_meta exceeds the 4 KiB limit",void 0,"meta-too-large");}function Za(e){let n={},t={};for(let r of e.actions){n[r.actionId]={capabilities:[r.capability],inputKeys:Object.keys(r.inputSchema.properties??{}),...r.dataInputs===void 0?{}:{dataInputs:r.dataInputs},resultProjection:r.resultProjection,...r.confirmation===void 0?{}:{confirmation:r.confirmation},...r.content===void 0?{}:{content:r.content},...r.backend.type!=="skill"||r.backend.env===void 0?{}:{env:r.backend.env}};let s=r.backend.type==="skill"||r.backend.type==="core"&&r.backend.handler==="state.set";t[r.actionId]={actionId:r.actionId,mutation:r.mutation,backend:r.backend,launchPolicy:s?"allowed":"denied",...s?{}:{denialCode:"EXEC_DENIED"}};}let i={id:e.definitionId,version:e.version,renderer:"sandbox-html",...e.usage===void 0?{}:{usage:e.usage},...e.detailPanel===void 0?{}:{detailPanel:e.detailPanel},...e.displayModes===void 0?{}:{displayModes:e.displayModes},surfaces:e.surfaces,stateProjection:e.stateProjection,...e.summaryProjection===void 0?{}:{summaryProjection:e.summaryProjection},...e.dataPaths===void 0?{}:{dataPaths:e.dataPaths},actions:n},o={entry:{path:"ui/index.html",...e.entryHash===void 0?{}:{hash:e.entryHash}},...e.initialState===void 0?{}:{initialState:e.initialState}};return {manifest:e,definition:i,handlers:t,resources:o}}function $t(e,n,t,i,o,r){if(typeof e=="string"){let s=o.length>0&&r.some(a=>Ze(o.join("."),a));return (e.length>4096||$n(e,false,false,s))&&Ie("state contains an unsafe string"),e}if(e===null||typeof e=="boolean")return e;if(typeof e=="number")return Number.isFinite(e)||Ie("state contains a non-finite number"),e;(e===void 0||typeof e!="object"||typeof e=="function"||typeof e=="bigint")&&Ie("state contains a non-JSON value"),t>8&&Ie("state is too deep"),n.has(e)&&Ie("state contains a cycle"),n.add(e);try{let s;if(Array.isArray(e))e.length>128&&Ie("state array is too long"),s=e.map(c=>$t(c,n,t+1,2097152,o,r));else {G(e)||Ie("state contains a non-plain object");let c={};for(let[d,l]of Object.entries(e))(d.length>4096||!jn.test(d)||en(d))&&(d.length>4096&&Ie("state key is too long"),Ie("state contains a reserved or invalid key")),c[d]=$t(l,n,t+1,2097152,[...o,d],r);s=c;}let a=JSON.stringify(s);return (a===void 0||Buffer.byteLength(a,"utf8")>i)&&Ie("state subtree is too large"),s}finally{n.delete(e);}}function Wt(e,n=[]){G(e)||Ie("initial state must be a JSON object");let t=$t(e,new Set,0,2097152,[],n);return (t===null||Array.isArray(t)||typeof t!="object")&&Ie(),t}function Qa(e,n={}){zn(e),G(e)||A("MANIFEST_INVALID"),X(e,Ia),e.manifestVersion!==1&&A("MANIFEST_INVALID");let t=jt(Pe(e,"pluginId")),i=jt(Pe(e,"definitionId")),o=ge(e,"version",1),r=ge(e,"primitiveSet",1),s=n.supportedPrimitiveSet??sa;(!Number.isSafeInteger(s)||s<1)&&A("MANIFEST_INVALID"),r>s&&A("PRIMITIVE_SET_UNSUPPORTED"),G(e.activation)||A("MANIFEST_INVALID"),X(e.activation,["kind","language"]),e.activation.kind!=="fenced-code"&&A("MANIFEST_INVALID");let a=jt(Pe(e.activation,"language")),c=Ua(e.schema),d=ja(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 G(e)||A("MANIFEST_INVALID"),Object.hasOwn(e,"lineage")&&A("MANIFEST_INVALID","lineage is only allowed in product bundle indexes"),e.manifestVersion===2?qa(e,n):Qa(e,n)}function $e(e,n={}){try{return ec(e,n)}catch(t){if(t instanceof se)throw t;return A("MANIFEST_INVALID")}}function mn(e,n={}){let t=$e(e,n);return t.manifestVersion===2?Za(t):t}var sa,aa,ca,io,da,pa,la,ua,Ki,fa,ya,Aa,Ia,ga,ma,ha,_a,Ea,Ta,Pa,Da,Na,ba,Sa,Ma,La,Ra,Oa,wa,se,Jt=V(()=>{m();xt();Le();wt();ji();Ut();Ji();Be();sa=1,aa=/^[a-z][a-zA-Z0-9]*(\.[a-zA-Z0-9]+)+$/,ca=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,io=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,da=/<\/?[A-Za-z][^>]*>/,pa=/^(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)/,la=/^(?:https?|file|ftp|ws|wss):\/\//i,ua=/^\s*(?:javascript|data):/i,Ki=/data:[^,\s]*,/i,fa=/(?:https?|file|ftp|ws|wss):\/\//i,ya=/javascript:/i,Aa=/(?:^[\s]*|[\s"'(=])(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)(?=[^\s"'<>])[^\s"'<>]*/,Ia=["manifestVersion","pluginId","definitionId","version","primitiveSet","activation","schema","layout"],ga=["manifestVersion","pluginId","definitionId","version","name","description","entry","surfaces","size","stateProjection","actions"],ma=["_meta","icon","tone","entryHash","runtime","csp","initialState","usage","detailPanel","displayModes","summaryProjection","dataPaths","focusedAiDataPaths"],ha=["actionId","capability","mutation","inputSchema","resultProjection","backend"],_a=["confirmation","dataInputs","content","_meta"],Ea=4*1024,Ta=["type","handler"],Pa=["type","command"],Da=["env"],Na=["type","entry"],ba=["path"],Sa=["hash"],Ma=/^[0-9a-f]{64}$/,La=/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/,Ra=/[\r\n]/,Oa=16,wa=["card-shell","meta-banner","heading","labeled-text","step-flow","text-list"],se=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 fo(e){return typeof e=="string"&&e.length<=tc&&nc.test(e)}function j(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 q(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function he(e){let n=`_meta["${ve}"]`;return e===void 0||e===""?n:e.startsWith("[")?`${n}${e}`:`${n}.${e}`}function sc(e){return e.toLowerCase().replace(/_/g,"-")}function ac(e){if(e===void 0||e==="")return "";let n=/^([^.[]+)(.*)$/.exec(e);if(!n)return he(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 he("definitionVersion");case "definitionId":return he("definitionId");default:return he(`${t}${i}`)}}function yo(e,n,t){return {path:t(e.path),rule:e.rule??sc(e.code),...e.message!==e.code?{message:e.message}:{},file:n}}function Ao(e){return JSON.parse(JSON.stringify(e))}function Yt(e,n,t=0,i=new Set){if(typeof e=="string"){e.length>4096&&j("LIMIT_EXCEEDED",n,"string-too-long"),(ic.test(e)||oc.test(e)||rc.test(e))&&j("UNSAFE_VALUE",n,"unsafe-value");return}if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){Number.isFinite(e)||j("MANIFEST_INVALID",n,"non-finite-number");return}typeof e!="object"&&j("MANIFEST_INVALID",n,"non-json-value"),t>8&&j("LIMIT_EXCEEDED",n,"too-deep"),i.has(e)&&j("MANIFEST_INVALID",n,"cycle"),i.add(e);try{if(Array.isArray(e)){e.length>128&&j("LIMIT_EXCEEDED",n,"array-too-long"),e.forEach((o,r)=>Yt(o,`${n}[${r}]`,t+1,i));return}ie(e)||j("MANIFEST_INVALID",n,"non-plain-object");for(let[o,r]of Object.entries(e))Yt(r,n===""?o:`${n}.${o}`,t+1,i);}finally{i.delete(e);}}}function me(e,n){return (typeof e!="string"||e.length===0)&&j("MANIFEST_INVALID",n,"string"),e}function sn(e,n){return ie(e)||j("MANIFEST_INVALID",n,"object"),e}function cc(e,n){Array.isArray(e)||j("MANIFEST_INVALID",n,"array"),e.forEach((t,i)=>me(t,`${n}[${i}]`));}function dc(e,n){typeof e!="boolean"&&j("MANIFEST_INVALID",n,"boolean");}function hn(e,n,t,i){for(let o of Object.keys(e))!t.includes(o)&&!i.includes(o)&&j("MANIFEST_INVALID",`${n}.${o}`,"unknown-key");for(let o of t)q(e,o)||j("MANIFEST_INVALID",`${n}.${o}`,"missing-key");}function pc(e,n){switch(Yt(n,e),e){case "long_description":case "homepage":case "documentation":case "support":case "icon":case "license":me(n,e);return;case "author":{let t=sn(n,e);hn(t,e,["name"],["email","url"]);for(let i of Object.keys(t))me(t[i],`${e}.${i}`);return}case "repository":{let t=sn(n,e);hn(t,e,[],["type","url"]);for(let i of Object.keys(t))me(t[i],`${e}.${i}`);return}case "icons":{Array.isArray(n)||j("MANIFEST_INVALID",e,"array"),n.forEach((t,i)=>{let o=`${e}[${i}]`,r=sn(t,o);hn(r,o,["src","size"],["theme"]),me(r.src,`${o}.src`),me(r.size,`${o}.size`),q(r,"theme")&&me(r.theme,`${o}.theme`);});return}case "screenshots":case "keywords":case "privacy_policies":cc(n,e);return;case "tools":{Array.isArray(n)||j("MANIFEST_INVALID",e,"array"),n.forEach((t,i)=>{let o=`${e}[${i}]`,r=sn(t,o);hn(r,o,["name"],["description"]),me(r.name,`${o}.name`),q(r,"description")&&me(r.description,`${o}.description`);});return}case "prompts":{Array.isArray(n)||j("MANIFEST_INVALID",e,"array"),n.forEach((t,i)=>{let o=`${e}[${i}]`,r=sn(t,o);hn(r,o,["name","text"],["description","arguments"]),me(r.name,`${o}.name`),me(r.text,`${o}.text`);});return}case "tools_generated":case "prompts_generated":dc(n,e);return;case "localization":case "compatibility":case "user_config":sn(n,e);return;default:j("MANIFEST_INVALID",e,"unknown-key");}}function Gn(e){return typeof e=="string"&&Te.test(e)?e:void 0}function Io(e){return Number.isSafeInteger(e)&&e>=1?e:void 0}function lc(e){let n=Gn(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")?Gn(o.definitionId):n,s=q(o,"definitionVersion")?Io(o.definitionVersion):1;return {pluginId:n,...r===void 0?{}:{definitionId:r},...s===void 0?{}:{definitionVersion:s}}}function uc(e){let n=Gn(e.pluginId);if(n===void 0)return;let t=Gn(e.definitionId),i=Io(e.version);return {pluginId:n,...t===void 0?{}:{definitionId:t},...i===void 0?{}:{definitionVersion:i}}}function Qt(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 fc(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 yc(e,n){q(e,"server")&&j("MANIFEST_INVALID","server","server-unsupported","phase 1 runs CrewX-owned Apps only");for(let a of Object.keys(e))qt.includes(a)||j("MANIFEST_INVALID",a,"unknown-key");for(let a of Zt)q(e,a)||j("MANIFEST_INVALID",a,"missing-key");e.manifest_version!==Kt&&j("MANIFEST_INVALID","manifest_version","unsupported-version",`manifest_version must be "${Kt}"`),fo(e.version)||j("MANIFEST_INVALID","version","semver","version must be a semver.org version such as 0.1.0");let t=e._meta;ie(t)||j("MANIFEST_INVALID","_meta","object"),q(t,ve)||j("MANIFEST_INVALID",he(),"missing-key");let i=t[ve];ie(i)||j("MANIFEST_INVALID",he(),"object");for(let a of Object.keys(i))Xt.includes(a)||uo.includes(a)||j("MANIFEST_INVALID",he(a),"unknown-key");for(let a of Xt)a==="actions"&&n!==void 0||q(i,a)||j("MANIFEST_INVALID",he(a),"missing-key");if(n!==void 0&&q(i,"actions")&&j("MANIFEST_INVALID",he("actions"),"two-truths",`actions are declared in both ${W} and ${H}; a server.ts App keeps them in the tools file only`),Ac(i.actions),q(i,"definitionVersion")){let a=i.definitionVersion;(!Number.isSafeInteger(a)||a<1)&&j("MANIFEST_INVALID",he("definitionVersion"),"positive-integer");}let o={};for(let a of lo)q(e,a)&&(pc(a,e[a]),o[a]=Ao(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:nn}}))),Object.keys(r).length>0&&(s._meta=r),{v2Input:s,...Object.keys(r).length>0?{vendorMeta:r}:{},passthrough:o}}function Ac(e){Array.isArray(e)&&e.forEach((n,t)=>{let i=ie(n)?n.backend:void 0;ie(i)&&q(i,"entry")&&j("MANIFEST_INVALID",he(`actions[${t}].backend.entry`),"entry-not-authorable",`an action in ${W} cannot name an entry; a server.ts App declares its actions in ${H}`);});}function Ic(e,n,t){ie(e)||j("MANIFEST_INVALID","","not-object","manifest.json must be a JSON object",W);let i;try{i=yc(e,t);}catch(s){throw s instanceof Ne?new Ne(s.code,{...s.reason,file:W}):s}let o;try{let s=$e(i.v2Input,{mode:n.mode??"local"});s.manifestVersion!==2&&j("MANIFEST_INVALID","","v2-required"),o=s;}catch(s){throw s instanceof se?new Ne(s.code,yo(s,W,ac)):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:W})});}return {file:W,manifest:o,v2Input:i.v2Input,releaseVersion:e.version,...Object.keys(i.passthrough).length>0?{mcpb:i.passthrough}:{}}}function gc(e,n){try{let t=$e(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 se?new Ne(t.code,yo(t,de,i=>i??"")):t}}function an(e){return le(mn(e).definition)}function co(e){let{entryHash:n,initialState:t,...i}=e,o={...i};return t!==void 0&&(o.initialState={path:t.path}),Ao(o)}function mc(e,n){let t=co(e),i=co(n);return [...new Set([...Object.keys(t),...Object.keys(i)])].sort().filter(r=>te(t[r]??null)!==te(i[r]??null))}function hc(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 _c(e,n){let t=mc(e,n),i=hc(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||j("MANIFEST_DUAL_MISMATCH","","dual-manifest-mismatch",`${W} and ${de} normalize to different definitions${o}`+(t.length>0?`; differing fields: ${t.join(", ")}`:""));}function De(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 {...De("","tools-needs-manifest-json","MANIFEST_INVALID",`${H} is read with ${W} only`),files:e}}function Ec(e,n){if(e.byteLength>n)return {failure:De("","file-too-large","LIMIT_EXCEEDED")};let t;try{t=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e));}catch{return {failure:De("","invalid-json")}}if(!ie(t))return {failure:De("","not-object","MANIFEST_INVALID",`${H} must be a JSON object`)};for(let o of Object.keys(t))if(o!=="schemaVersion"&&o!=="actions")return {failure:De(o,"unknown-key")};for(let o of ["schemaVersion","actions"])if(!q(t,o))return {failure:De(o,"missing-key")};if(t.schemaVersion!==1)return {failure:De("schemaVersion","unsupported-version","MANIFEST_INVALID",`schemaVersion must be ${1}`)};let i=t.actions;if(!Array.isArray(i))return {failure:De("actions","array")};for(let[o,r]of i.entries()){if(!ie(r))return {failure:De(`actions[${o}]`,"object")};if(q(r,"backend"))return {failure:De(`actions[${o}].backend`,"tools-backend","MANIFEST_INVALID",`an action in ${H} cannot carry a backend`)}}return {actions:i}}function Tc(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 Ge(e,n={}){let{parsed:t,failure:i}=Tc(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:Ec(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===W?lc(a.raw):uc(a.raw),d=t.some(f=>fc(f.file,f.raw)),l;if(s!==void 0){let f=t.some(g=>g.file===W)?s.failure:po(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===W?Ic(f.raw,n,l):gc(f.raw,n));p.length===2&&_c(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 W,de,Z,Kt,ve,qt,Zt,lo,Xt,uo,nc,tc,ic,oc,rc,Ne,Wn=V(()=>{m();He();Le();Ut();Be();Jt();W="manifest.json",de="ui-plugin.json",Z=[W,de],Kt="0.3",ve="dev.crewx",qt=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"]),Zt=Object.freeze(["manifest_version","name","display_name","version","description","_meta"]),lo=Object.freeze(qt.filter(e=>e!=="server"&&!Zt.includes(e))),Xt=Object.freeze(["entry","surfaces","size","stateProjection","actions"]),uo=Object.freeze(["definitionId","definitionVersion","icon","tone","entryHash","runtime","initialState","usage","detailPanel","displayModes","summaryProjection","dataPaths","focusedAiDataPaths","csp"]),nc=/^(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-]+)*))?$/,tc=256,ic=/<\/?[A-Za-z][^>]*>/,oc=/^\s*javascript:/i,rc=/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};});var ei=V(()=>{m();Ci();Wn();Jt();Be();});function S(e,n=e){throw new be(e,n)}var be,Kn=V(()=>{m();be=class extends Error{constructor(t,i=t){super(i);this.code=t;}code;name="McpAppContractError"};});var So=V(()=>{m();});var Mo=V(()=>{m();He();Le();Kn();So();});function Ro(e,n){return Lo.add(e),n!==void 0&&kc.set(e,n),e}function cn(e){return e!==null&&typeof e=="object"&&Lo.has(e)}var Lo,kc,Xn=V(()=>{m();Lo=new WeakSet,kc=new WeakMap;});function Pn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function ti(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 Co(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let n of Object.values(e))Co(n);return Object.freeze(e)}function oe(e){throw new Se("LINEAGE_INVALID",e)}function Bc(e){throw new Se("LINEAGE_STALE",e)}function ko(e){if(!Pn(e)||!ti(e,vc,jc)||!Pn(e.actions))return oe("Lineage definition shape is invalid");for(let n of Object.values(e.actions))if(!Pn(n)||!ti(n,Fc,Vc))return oe("Lineage action definition shape is invalid");return e}function Hc(e){if(!Pn(e)||!ti(e,Uc,xc))return oe("Lineage entry shape is invalid");if(!Number.isSafeInteger(e.version)||e.version<1||typeof e.hash!="string"||!Oo.test(e.hash))return oe("Lineage entry identity is invalid");if(e.sourceHash!==void 0&&(typeof e.sourceHash!="string"||!Oo.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=ko(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=le(n),Ae({...n,hash:e.hash});}catch{return oe("Lineage definition is invalid")}return t!==e.hash?oe("Lineage definition hash does not match"):Co({version:e.version,hash:e.hash,definition:n,...e.sourceHash===void 0?{}:{sourceHash:e.sourceHash},...e.compat===void 0?{}:{compat:e.compat}})}function wo(e){return e.stateProjection?.allow??[]}function zc(e,n){let t=[],i=new Set(wo(n));wo(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 $c(e,n){return te(e)===te(n)}function ii(e,n){if(!Array.isArray(e)||e.length===0)return oe("Definition lineage is missing");if(!Pn(n)||typeof n.hash!="string")return oe("Current definition is invalid");let t,i;try{let{hash:a,...c}=n;i=ko(c),t={...i,hash:a},Ae(t);}catch{return oe("Current definition is invalid")}let o=e.map(Hc),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||!$c(s.definition,i))return Bc("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 Se("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=zc(o[a].definition,t);if(d.length>0)throw new Se("LINEAGE_INVALID",`Lineage compatibility failed: ${d.join(", ")}`,d)}return Object.freeze({entries:Object.freeze(o),current:t})}var Se,Oo,Uc,xc,vc,jc,Fc,Vc,oi=V(()=>{m();He();Le();Se=class extends Error{constructor(t,i=t,o=[]){super(i);this.code=t;this.violations=o;}code;violations;name="UiDefinitionLineageError"},Oo=/^[0-9a-f]{64}$/,Uc=["version","hash","definition"],xc=["sourceHash","compat"],vc=["id","version","actions"],jc=["sourceHash","usage","detailPanel","displayModes","renderer","surfaces","stateProjection","dataPaths","summaryProjection","legacy"],Fc=["capabilities"],Vc=["inputKeys","dataInputs","confirmation","resultProjection","content","env"];});var Uo,xo,vo,jo,Fo=V(()=>{m();Uo="text/html;profile=mcp-app",xo=["crewx_app_terminal_connect","crewx_app_html_viewer_open"],vo=["crewx_listWorkspaces","crewx_queryAgent","crewx_executeAgent","crewx_getTaskResult","crewx_listTasks","crewx_listAgents","callBrowser","openTab","listTabs","closeTab"],jo="text/html";});function Dn(e){return typeof e=="string"&&Gc.includes(e)}function Yn(e,n){return e==="card"&&n?.type==="core"&&Dn(n.handler)}var Gc,qn=V(()=>{m();Gc=Object.freeze(["card.secret-env"]);});function Vo(e,n=[],t){if(e.content!==void 0||e.confirmation!=="none")return "denied";let i=Wc();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 Wc(e){return;}var Bo=V(()=>{m();He();Xn();qn();});function nd(e){return Sn.has(e)&&(e.initialState===void 0||Sn.has(e.initialState))}function Wo(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:jo,entryHash:e,html:n,bytes:Object.freeze(t),...o===void 0?{}:{initialState:o}});return o!==void 0&&Sn.add(o),Sn.add(r),r}function td(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:Fe}),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:Fe}),n}function Ve(e,n,t){return (typeof e!="string"||!$o.test(e))&&S(n,`${t} must be a safe identifier`),e}function Nn(e,n,t){let i=e??t;return (typeof i!="string"||i.trim().length===0||i.length>Xc)&&S("TOOL_INVALID",`${n} must be a meaningful description`),i}function si(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 bn(e,n=0){try{let t=ye(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 be)throw t;S("TOOL_INVALID","MCP App inputSchema must be projection-safe JSON");}}function id(e){return (typeof e!="string"||e.trim().length===0||e.length>Yc)&&S("TOOL_INVALID","MCP App tools require a meaningful text fallback"),e}function od(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 Ko(e){return (typeof e!="string"||!Go.test(e))&&S("RESOURCE_URI_INVALID","MCP App resource URI is not a registered ui:// URI"),e}function Xo(e){let n=Ve(e.appId,"APP_ID_INVALID","Local App id"),t=Nn(e.name,"Local App name",n),i=Nn(e.description,"Local App description",`${t} interactive view`),o=nt(e.definition),r=si(e.html),s=Zn(e.entryHash,"Local App entry hash"),a=e.entryBytes===void 0?Array.from(new TextEncoder().encode(r)):et(e.entryBytes,"Local App entry bytes");(Qn(a)!==s||Zo(a)!==r)&&S("HTML_INVALID","Local App entry bytes do not match the HTML hash");let c=rd(e),d=[];Array.isArray(e.actions)||S("TOOL_INVALID","Local App actions must be an array");for(let D of e.actions){let C=Ve(D.actionId,"TOOL_ID_INVALID","Local App action id");(d.includes(C)||!Object.prototype.hasOwnProperty.call(o.actions,C))&&S("TOOL_INVALID",`Local App action is not declared by the UI definition: ${C}`),d.push(C);}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=td(e.runtime);u.some(D=>D.name===l||D.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:ed,textFallback:`${t} current state is available through its open instance.`,visibility:Object.freeze(["model","app"]),kind:"read",resourceBinding:Fe},g=[Object.freeze(f)];if(g.push(...u.map(D=>Object.freeze(D))),p!==void 0){let D={name:p,description:`${t} actions`,inputSchema:ai(e.actions),textFallback:`${t} action requests are handled by the open App instance.`,visibility:Object.freeze(["app"]),kind:"action",resourceBinding:Fe,actionIds:Object.freeze([...d])};g.push(Object.freeze(D));}let _=[],P=new Set(g.map(D=>D.name));if(p!==void 0)for(let D of e.actions){let C=`${p}__${D.actionId}`;if(C.length>128||!$o.test(C)){_.push(Object.freeze({toolName:C,actionId:D.actionId,reason:"name_too_long"}));continue}if(P.has(C)){_.push(Object.freeze({toolName:C,actionId:D.actionId,reason:"name_collision"}));continue}let F=Vo({actionId:D.actionId,confirmation:o.actions[D.actionId]?.confirmation,content:o.actions[D.actionId]?.content,backend:D.backend},e.modelActions),N=Object.freeze([...pd(F,o.usage,D.backend)]),b={name:C,description:`${C} action`,inputSchema:bn(D.inputSchema),textFallback:`${C} action requests are handled by the open App instance.`,visibility:N,kind:"action",resourceBinding:Fe,actionId:D.actionId,actionIds:Object.freeze([D.actionId]),_meta:Object.freeze({ui:Object.freeze({visibility:N})})};g.push(Object.freeze(b)),P.add(C);}let k=Wo(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:Qo(e.icon)},...e.tone===void 0?{}:{tone:er(e.tone)},builtinOnly:false,definition:o,...e.runtime===void 0?{}:{runtime:Object.freeze({...e.runtime})},resourceBinding:Fe,resource:k,tools:Object.freeze(g),toolDiagnostics:Object.freeze(_)};return ee(U)}function Yo(e={}){return new ri(e)}function ai(e){if(e.length===0)return bn({type:"object",properties:{},additionalProperties:false});let n=e.map(i=>i.actionId),t=new Map;for(let i of e)t.set(i.actionId,bn(i.inputSchema));return bn(sd(n,t),Jo)}function rd(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&&ye(e.initialState,0,n);return}e.initialStateHash===void 0&&S("STATE_INVALID","Initial state bytes require a hash");let t=Zn(e.initialStateHash,"Initial state hash"),i=et(e.initialStateBytes,"Initial state bytes");Qn(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=ye(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(ye(e.initialState,0,n))&&S("STATE_INVALID","Initial state bytes do not match the state value"),{hash:t,bytes:Object.freeze([...i])}}function sd(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 ad(e){let n=Mn(e),t=Ve(n.appId,"APP_ID_INVALID","MCP App id"),i=si(n.html);Ko(n.uiUri);let o=n.definition===void 0?void 0:nt(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(Mn(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:Uo,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 cd(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=nt(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=dd(e.resource),r=e.tools.map(a=>{Ve(a.name,"TOOL_ID_INVALID","Local App tool name"),Nn(a.description,"Local App tool description","Local App tool"),id(a.textFallback);let c=bn(a.inputSchema,a.kind==="action"&&!("actionId"in a)?Jo: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 (!Qc.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=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=od(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:Nn(e.name,"Local App name",e.appId),description:Nn(e.description,"Local App description",e.name),...e.icon===void 0?{}:{icon:Qo(e.icon)},...e.tone===void 0?{}:{tone:er(e.tone)},builtinOnly:false,definition:t,...e.runtime===void 0?{}:{runtime:Object.freeze({...e.runtime})},...i===void 0?{}:{provenance:i},resourceBinding:Fe,resource:o,tools:Object.freeze(r),toolDiagnostics:Object.freeze([...e.toolDiagnostics??[]])});return Ho.has(e)?e:(Ho.add(s),s)}function dd(e){let n=si(e.html),t=Zn(e.entryHash,"Local App entry hash");if(nd(e))return e;let i=et(e.bytes,"Local App entry bytes");(Qn(i)!==t||Zo(i)!==n)&&S("HTML_INVALID","Local App entry bytes do not match the HTML hash");let o=e.initialState===void 0?void 0:{hash:Zn(e.initialState.hash,"Initial state hash"),bytes:et(e.initialState.bytes,"Initial state bytes")};return o&&Qn(o.bytes)!==o.hash&&S("STATE_INVALID","Initial state bytes do not match the hash"),Wo(t,n,i,o)}function pd(e,n,t){if(Yn(n,t))return ["model"];let i=t?.type==="core"&&Dn(t.handler);return e==="denied"||i?["app"]:["model","app"]}function ld(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:qo(e.definition),...e.provenance===void 0?{}:{provenance:e.provenance},entryHash:e.resource.entryHash,resourceBinding:Fe,tools:e.tools})}function ud(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:qo(e.definition)},resourceBinding:Object.freeze({kind:"mcp",uri:e.uiUri}),tools:e.tools})}function nt(e){try{if(Object.isFrozen(e))return Ae(e),ee(e);let n=Mn(e);return Ae(n),ee(n)}catch(n){if(n instanceof be)throw n;S("STATE_INVALID","UI definition is not a valid immutable definition");}}function qo(e){return ee({id:e.id,version:e.version,hash:e.hash})}function fd(e){return e!==null&&typeof e=="object"&&typeof e.id=="string"&&Number.isSafeInteger(e.version)&&typeof e.hash=="string"}function zo(e,n,t){return `${e}\0${n}\0${t}`}function Zn(e,n){return (typeof e!="string"||!Kc.test(e))&&S("SERIALIZATION_INVALID",`${n} is invalid`),e}function Qn(e){return createHash("sha256").update(Uint8Array.from(e)).digest("hex")}function et(e,n){return (!Array.isArray(e)||e.some(t=>!Number.isInteger(t)||t<0||t>255))&&S("SERIALIZATION_INVALID",`${n} is invalid`),[...e]}function Zo(e){try{return new TextDecoder("utf-8",{fatal:!0}).decode(Uint8Array.from(e))}catch{S("SERIALIZATION_INVALID","UTF-8 bytes are invalid");}}function Qo(e){return (typeof e!="string"||!qc.test(e))&&S("TOOL_INVALID","MCP App icon is invalid"),e}function er(e){return (typeof e!="string"||!Zc.has(e))&&S("TOOL_INVALID","MCP App tone is invalid"),e}function Mn(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(Mn(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:Mn(s,n),writable:true});return n.delete(t),o}function ee(e,n=new Set){if(e===null||typeof e!="object"||n.has(e)||Sn.has(e))return e;n.add(e);for(let t of Object.values(e))ee(t,n);return Object.freeze(e),e}var $o,Go,Kc,dn,Xc,Yc,qc,Zc,Qc,Fe,ed,Sn,Ho,Jo,ri,tt=V(()=>{m();Mo();He();Le();Xn();Kn();oi();Fo();Bo();qn();$o=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,Go=/^ui:\/\/crewx\/([A-Za-z][A-Za-z0-9._-]{0,127})\/([0-9a-f]{12})$/,Kc=/^[0-9a-f]{64}$/,dn=8*1024*1024,Xc=8*1024,Yc=16*1024,qc=/^[a-z][a-z0-9-]{0,63}$/,Zc=new Set(["blue","violet","emerald","amber","rose","sky","slate","indigo"]),Qc=new Set(xo),new Set(vo),Fe=Object.freeze({kind:"instance"}),ed=Object.freeze({type:"object",properties:Object.freeze({}),additionalProperties:false}),Sn=new WeakSet,Ho=new WeakSet;Jo=4;ri=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=ad(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(cd),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=ee({...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,ud(p)),p.definition&&this.addDefinition(p.definition);for(let p of l)this.registrationById.set(p.appId,p),this.launcherById.set(p.appId,ld(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"||!Go.test(n)?null:this.mcpResources.get(n)??null}requireMcpAppResource(n){Ko(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(!fd(n))return null;let t=this.definitionByKey.get(kt(n));if(!t||t.hash!==n.hash)return null;try{return le(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(zo(n,t,i))??null}addDefinition(n){let t=nt(n),i=kt(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=zo(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 yd(e){let n=Xo({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 nr(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=yd(e);Yo({localApps:[t],definitions:[e.definition]});}var tr=V(()=>{m();tt();});function Ad(e){if(e===null||typeof e!="object"||!(ir in e))throw new TypeError("scanCache must be created by createWorkspaceAppScanCache");return e[ir]}function or(e,n){let t=Ad(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 ir,rr=V(()=>{m();ir=Symbol("crewx.workspace-app-scan-cache.state");});function ue(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 hd(e){if(typeof e!="string"||e.length===0||!isAbsolute(e))throw new M("READ_DENIED")}function ci(e){if(typeof e!="string"||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 st(e,n){let t=relative(e,n);return t===""||t!==".."&&!t.startsWith(`..${sep}`)&&!isAbsolute(t)}function ln(e){return {dev:e.dev,ino:e.ino,size:e.size,mtimeNs:e.mtimeNs,ctimeNs:e.ctimeNs}}function ui(e,n){return e.dev===n.dev&&e.ino===n.ino}function fi(e,n){return ui(e,n)&&e.size===n.size&&e.mtimeNs===n.mtimeNs&&e.ctimeNs===n.ctimeNs}async function it(e){hd(e);let n,t;try{n=await realpath(e),t=await stat(n,{bigint:!0});}catch(i){throw ue(i)}if(!t.isDirectory())throw new M("READ_DENIED");return {realRoot:n,identity:ln(t)}}async function cr(e,n,t){if(t.length<2||t[0]!=="apps"&&t[0]!=="skills")return;let i,o;try{if(i=resolve(e,t[0],t[1]),o=await realpath(i),!(await stat(o,{bigint:!0})).isDirectory())throw new M("READ_DENIED")}catch(r){throw r instanceof M?r:ue(r)}if(!st(n,o))throw new M("PATH_ESCAPED");return o}async function ot(e,n,t,i){let o,r,s;try{o=await lstat(e,{bigint:!0}),r=await realpath(e),s=await stat(r,{bigint:!0});}catch(a){throw ue(a)}if(!st(n,r)||t!==void 0&&!st(t,r))throw new M("PATH_ESCAPED");if(!o.isFile()||!s.isFile())throw new M("READ_DENIED");if(!ui(i,o)||!ui(i,s)||i.dev!==s.dev)throw new M("PATH_ESCAPED")}async function pn(e,n){let t,i;try{t=await realpath(e),i=await stat(t,{bigint:!0});}catch{throw new M("PATH_ESCAPED")}if(t!==n.realRoot||!fi(n.identity,ln(i)))throw new M("PATH_ESCAPED")}function _d(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,li,md,ar,at,dr,Ai=V(()=>{m();M=class extends Error{constructor(t){super(t);this.code=t;}code;name="AppDiscoveryFsError"},li=constants.O_NOFOLLOW,md=constants.O_NONBLOCK,ar=constants.O_RDONLY|(li??0)|(md??0);at=class{async getRootIdentity(n){let t=await it(n);return await pn(n,t),{dev:t.identity.dev,ino:t.identity.ino,realPath:t.realRoot}}async listDirectory(n,t){let i=ci(t),o=await it(n),r=resolve(n,...i),s,a;try{s=await realpath(r),a=await stat(s,{bigint:!0});}catch(c){let d=ue(c);if(d.code==="NOT_FOUND")return [];throw d}if(!st(o.realRoot,s)||!a.isDirectory())throw new M("PATH_ESCAPED");try{let c=await readdir(s,{withFileTypes:!0,encoding:"utf8"});return await pn(n,o),c.map(_d)}catch(c){let d=ue(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(li===void 0)throw new M("UNSUPPORTED");let o=ci(t),r=await it(n),s=resolve(n,...o),a=relative(n,s);if(a===".."||a.startsWith(`..${sep}`)||isAbsolute(a))throw new M("PATH_ESCAPED");let c;try{c=await open(s,ar);}catch(d){throw ue(d)}try{let d;try{let g=await c.stat({bigint:!0});d=ln(g);}catch(g){throw ue(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 cr(n,r.realRoot,o);await ot(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 ue(_)}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 ue(g)}if(!fi(d,f))throw new M("IDENTITY_CHANGED");return await ot(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(li===void 0)throw new M("UNSUPPORTED");let o=ci(t),r=await it(n),s=resolve(n,...o),a=relative(n,s);if(a===".."||a.startsWith(`..${sep}`)||isAbsolute(a))throw new M("PATH_ESCAPED");let c;try{c=await open(s,ar);}catch(d){throw ue(d)}try{let d;try{let u=await c.stat({bigint:!0});d=ln(u);}catch(u){throw ue(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 cr(n,r.realRoot,o);await ot(s,r.realRoot,l,d);let p;try{let u=await c.stat({bigint:!0});p=ln(u);}catch(u){throw ue(u)}if(!fi(d,p))throw new M("IDENTITY_CHANGED");return await ot(s,r.realRoot,l,p),await pn(n,r),{...p,candidateRealPath:l??r.realRoot}}catch(d){throw d instanceof M?d:ue(d)}finally{await c.close().catch(()=>{});}}async readFileVerified(n,t,i){return this.readVerifiedFile(n,t,i)}},dr=new at;});function wn(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"&&Te.test(e)?e:void 0}function Sd(e){return e.length>0&&e!=="."&&e!==".."&&!/[\\/\u0000]/.test(e)}function Je(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 Md(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 Ld(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 Rd(e){return Nd.decode(e)}function Od(e){return JSON.parse(Rd(e))}function ur(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 wd(e){if(e instanceof M)return ur(e.code);if(e!==null&&typeof e=="object"&&"code"in e){let n=e.code;if(typeof n=="string")return ur(n)}}function Oe(e,n){let t=n();return Number.isFinite(t)&&Number.isFinite(e)&&t-e<=5e3}function Cd(e){if(typeof e.readVerifiedFile=="function")return e.readVerifiedFile;if(typeof e.readFileVerified=="function")return e.readFileVerified}function kd(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 fr(e,n,t,i){let o=Cd(e);if(!o)throw new M("READ_DENIED");return Ld(await o.call(e,n,t,i))}async function mi(e,n,t){let i=kd(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(Md).filter(r=>r!==null)}function Ud(e,n,t,i){return Object.freeze({code:e,...{},source:n,relativePath:t})}function xd(e){if(!wn(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(Je))};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 vd(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 dt(e){return Object.freeze({appIds:Object.freeze([...new Set(e.map(n=>n.appId))].sort(Je)),definitionIds:Object.freeze([...new Set(e.map(n=>n.definition.id))].sort(Je))})}function ct(e,n){let t=Object.keys(e).sort(Je),i=[...n].sort(Je);return t.length===i.length&&t.every((o,r)=>o===i[r])}function yr(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 jd(e){let n;try{n=Od(e);}catch{return}if(!wn(n)||!ct(n,["version","packages"])||n.version!==1||!Array.isArray(n.packages)||n.packages.length>hi)return;let t=new Set,i=new Set,o=0,r=[];for(let s of n.packages){if(!wn(s))return;let a=["packageDir","appId","definition","files"],c=Object.hasOwn(s,"lineage"),d=Object.hasOwn(s,"launcher"),l=[...c?["lineage"]:[],...d?["launcher"]:[]];if(!ct(s,[...a,...l])||d&&s.launcher!==false)return;let p=yr(s.packageDir),u=lr(s.appId);if(!p||p.length!==2||p[0]!=="apps"||!Sd(p[1])||!u||t.has(s.packageDir)||!wn(s.definition)||!ct(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"||!gi.test(_)||!Array.isArray(s.files)||s.files.length<2||s.files.length>_i)return;let P=new Set,k=[];for(let U of s.files){if(!wn(U)||!ct(U,["path","sha256"]))return;let D=yr(U.path);if(!D||typeof U.sha256!="string"||!gi.test(U.sha256))return;let C=D.join("/"),F=`${s.packageDir}/${C}`;if(P.has(C)||i.has(F))return;P.add(C),i.add(F),k.push(Object.freeze({path:C,sha256:U.sha256}));}if(!Z.some(U=>P.has(U))||!P.has("ui/index.html")||(o+=k.length,o>Td))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(k.sort((U,D)=>Je(U.path,D.path)))}));}return Object.freeze({version:1,packages:Object.freeze(r)})}function We(e){let n=wd(e);return n==="PATH_ESCAPED"||n==="IDENTITY_CHANGED"||n==="TOCTOU"?"PATH_ESCAPED":n==="LIMIT_EXCEEDED"?"LIMIT_EXCEEDED":"BUNDLE_INTEGRITY"}async function Fd(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 mi(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>_i)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(Je)}function Vd(e){return Z.includes(e)?262144:e==="ui/index.html"?dn:e==="ui/state.json"?2097152:e.startsWith("ui/assets/")?Dd:Pd}async function Ar(e,n,t,i){if(e===void 0)return {packages:[],diagnostics:[],incomplete:false,reservedIds:bd};let o=xd(e.reservedIds),r=[],s=(y,I,h)=>Ud(y,"bundled",I),a=(y=[],I=false,h)=>({...h===void 0?{}:{indexHash:h},packages:y,diagnostics:r,incomplete:I,reservedIds:o});if(typeof e.root!="string"||e.root.length===0||typeof e.expectedIndexHash!="string"||!gi.test(e.expectedIndexHash))return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a();let c;try{c=await fr(n,e.root,"bundle-index.json",Ed);}catch(y){return r.push(s(We(y),"bundle-index.json")),a()}let d=createHash("sha256").update(c).digest("hex");if(d!==e.expectedIndexHash)return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a();let l=jd(c);if(l===void 0)return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a();if(!vd(dt(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(y=>({indexEntry:y,failureCode:"LIMIT_EXCEEDED"})),true,d);let p;try{p=await mi(n,e.root,"");}catch(y){return r.push(s(We(y),"bundle-index.json")),a(l.packages.map(I=>({indexEntry:I,failureCode:We(y)})),false,d)}if(!Oe(t,i))return r.push(s("LIMIT_EXCEEDED","bundle-index.json")),a(l.packages.map(y=>({indexEntry:y,failureCode:"LIMIT_EXCEEDED"})),true,d);let u=p.find(y=>y.name==="bundle-index.json"&&y.kind==="file"),f=p.find(y=>y.name==="apps"&&y.kind==="directory"),g=y=>l.packages.map(I=>({indexEntry:I,failureCode:y}));if(!u)return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a(g("BUNDLE_INTEGRITY"),false,d);let _=p.filter(y=>y.name!=="bundle-index.json"&&y.name!=="apps");if(_.length>0){let y=_.some(I=>I.kind==="symlink")?"PATH_ESCAPED":"BUNDLE_INTEGRITY";return r.push(s(y,"bundle-index.json")),a(g("BUNDLE_INTEGRITY"),false,d)}if(p.some(y=>y.name==="apps"&&y.kind!=="directory"))return r.push(s("PATH_ESCAPED","apps")),a(g("PATH_ESCAPED"),false,d);let P=[];if(f)try{P=await mi(n,e.root,"apps");}catch(y){return r.push(s(We(y),"apps")),a(g(We(y)),false,d)}if(!Oe(t,i)||P.length>hi)return r.push(s("LIMIT_EXCEEDED","apps")),a(g("LIMIT_EXCEEDED"),true,d);let k=new Map(l.packages.map(y=>[y.packageDir.slice(5),y])),U=P.filter(y=>!k.has(y.name));for(let y of U)r.push(s(y.kind==="symlink"?"PATH_ESCAPED":"BUNDLE_INTEGRITY",`apps/${y.name}`));if(U.length>0){let y=U.some(I=>I.kind==="symlink")?"PATH_ESCAPED":"BUNDLE_INTEGRITY";return a(g(y),false,d)}let D=new Set,C=new Map,F=new Map;for(let y of l.packages){let I=C.get(y.appId)??[];I.push(y),C.set(y.appId,I);let h=`${y.definition.id}\0${String(y.definition.version)}`,E=F.get(h)??[];E.push(y),F.set(h,E);}for(let y of [...C.values(),...F.values()])if(y.length>1)for(let I of y)D.add(I);let N=[],b=c.byteLength,R=false;for(let y of l.packages){if(!Oe(t,i)){R=true,N.push({indexEntry:y,failureCode:"LIMIT_EXCEEDED"});continue}let I;try{let L=y.lineage[y.lineage.length-1];if(!L)throw new Se("LINEAGE_INVALID","Definition lineage is missing");if(L.definition.id!==y.definition.id||L.version!==y.definition.version||L.hash!==y.definition.hash)throw new Se("LINEAGE_STALE","Last lineage generation does not match bundle identity");I=ii(y.lineage,{...L.definition,hash:L.hash}).entries;}catch(L){let J=L instanceof Se?L.code:"LINEAGE_INVALID";r.push(s(J,y.packageDir)),N.push({indexEntry:y,failureCode:J});continue}let h=P.find(L=>L.name===y.packageDir.slice(5));if(!f||!h){N.push({indexEntry:y,failureCode:"BUNDLE_INTEGRITY"});continue}if(h.kind!=="directory"){N.push({indexEntry:y,failureCode:h.kind==="symlink"?"PATH_ESCAPED":"BUNDLE_INTEGRITY"});continue}let E;try{let L=await Fd(n,e.root,y.packageDir,t,i);if(!Oe(t,i)){R=!0,N.push({indexEntry:y,failureCode:"LIMIT_EXCEEDED"});continue}let J=y.files.map(K=>K.path);if(L.length!==J.length||L.some((K,Me)=>K!==J[Me])){N.push({indexEntry:y,failureCode:"BUNDLE_INTEGRITY"});continue}E=new Map;let pe;for(let K of y.files){if(!Oe(t,i)){pe="LIMIT_EXCEEDED",R=!0;break}if(b>=Ii){pe="LIMIT_EXCEEDED";break}let Me;try{Me=await fr(n,e.root,`${y.packageDir}/${K.path}`,Vd(K.path));}catch(Es){pe=We(Es);break}if(!Oe(t,i)){pe="LIMIT_EXCEEDED",R=!0;break}if(b+Me.byteLength>Ii){b=Ii,pe="LIMIT_EXCEEDED";break}if(b+=Me.byteLength,createHash("sha256").update(Me).digest("hex")!==K.sha256){pe="BUNDLE_INTEGRITY";break}E.set(K.path,Me);}if(pe!==void 0){N.push({indexEntry:y,failureCode:pe});continue}}catch(L){Oe(t,i)||(R=true),N.push({indexEntry:y,failureCode:We(L)});continue}N.push({indexEntry:y,lineage:I,files:E,...D.has(y)?{failureCode:"DUPLICATE_ID"}:{}});}return a(N,R,d)}var Ed,hi,_i,Td,Pd,Dd,Ii,gi,Nd,bd,Ei=V(()=>{m();oi();Be();Wn();tt();Ai();Ed=256*1024,hi=64,_i=128,Td=hi*_i,Pd=2*1024*1024,Dd=8*1024*1024,Ii=32*1024*1024,gi=/^[0-9a-f]{64}$/,Nd=new TextDecoder("utf-8",{fatal:true}),bd=Object.freeze({appIds:Object.freeze([]),definitionIds:Object.freeze([])});});function Hd(e){if(typeof e!="string"||!Te.test(e))throw new TypeError("pluginId must be a safe UI plugin identifier");let n=`${Ti}${e}`.length+7<=128?e:`hash_${createHash("sha256").update(e,"utf8").digest("hex")}`;return {read:`${Ti}${n}_read`,action:`${Ti}${n}_action`}}function gr(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 $d(e,n){return n.length===0||n==="."||n===".."||/[\\/\u0000]/.test(n)?e==="skills"?"skills":"apps":`${e==="skills"?"skills":"apps"}/${n}`}function Gd(e){return e.length>0&&e!=="."&&e!==".."&&!/[\\/\u0000]/.test(e)}function Cn(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 Mr(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 Wd(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 Lr(e){return zd.decode(e)}function Jd(e){return JSON.parse(Lr(e))}function Kd(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 lt(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 mr(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 ae(e){if(e instanceof M)return mr(e.code);if(e!==null&&typeof e=="object"&&"code"in e){let n=e.code;if(typeof n=="string")return mr(n)}}function Xe(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 _r(e){return e==="MANIFEST_DUAL_MISMATCH"?e:Rr(e)}function Xd(e){return Rr(e.code)}function Rr(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 Or("UiPluginValidationError",e)}}function Or(e,n){throw new Error(`Unmapped ${e} code: ${String(n)}`)}function wr(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 Or("McpAppContractError",e)}}function we(e,n){let t=n();return Number.isFinite(t)&&Number.isFinite(e)&&t-e<=5e3}function Yd(e){return {pluginId:e.appId,definitionKey:`${e.definition.id}\0${String(e.definition.version)}`}}function qd(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(gr(o)){let r=o.bin,s=typeof r=="string"?r:gr(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=Zd(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 Zd(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 Qd(){return globalThis.performance?.now()??Date.now()}function Ke(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let n of Object.values(e))Ke(n);return Object.freeze(e)}function Er(e){return Object.freeze(Array.from(e))}async function ut(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 Nr(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 Nr(e,n.root,o,i),d=await s.call(e,r.workspaceRoot,o,i);return r.candidateRealPath=d.candidateRealPath,kr(a,d)&&d.size===BigInt(c.byteLength)&&!Ur(d,r.scanStartedAtNs)?r.files.set(o,{relativePath:o,byteLimit:i,fingerprint:d}):r.cacheable=!1,c}catch(a){let c=Z.includes(t)&&ae(a)==="NOT_FOUND"&&r.directoryListings.some(l=>l.relativePath===n.relativePath&&!ft(l.key,t)),d=t===H&&ae(a)==="NOT_FOUND"&&ep(r.directoryListings,n.relativePath);throw !c&&!d&&(r.cacheable=false),a}}function ep(e,n){let t=e.find(o=>o.relativePath===n);if(t===void 0)return false;if(!ft(t.key,"dist"))return true;let i=e.find(o=>o.relativePath===`${n}/dist`);return i!==void 0&&!ft(i.key,"tools.json")}function Cr(e,n){return JSON.stringify([e.realPath,n.source,n.relativePath])}async function tp(e,n,t,i,o,r,s,a){let c=e.fingerprintVerifiedFile,d=Cr(t,i),l=o.candidates.get(d),p=i.relativePath,u;try{u=await Dr(e,n,p);}catch(R){if(ae(R)!=="NOT_FOUND")throw R}let f=u===void 0?void 0:{relativePath:p,key:u};if(f!==void 0&&(i.source==="apps"||i.source==="skills")&&!Z.some(R=>ft(f.key,R)))return we(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 R=>{if(R==="")return f;let y=`${i.relativePath}${R}`;try{let I=await Dr(e,n,y);return I===void 0?void 0:{relativePath:y,key:I}}catch(I){if(ae(I)==="NOT_FOUND")return;throw I}},_=await Promise.all(Tr.map(g)),P=await Promise.all(np.map(g));if(!we(s,a))return {timeLimitReached:true};let k=typeof c=="function"&&_.every(R=>R!==void 0),U=_.filter(R=>R!==void 0),D=[...U,...P.filter(R=>R!==void 0)],C=new Map,F=l!==void 0&&k,N;if(l!==void 0&&typeof c=="function"){let R=await Promise.all(l.files.map(async y=>{if(!we(s,a))return {kind:"time",file:y};try{let I=await c.call(e,n,y.relativePath,y.byteLimit);return {kind:"fingerprint",file:y,current:I}}catch(I){return ae(I)==="NOT_FOUND"?{kind:"missing",file:y}:{kind:"error",file:y,error:I}}}));if(R.some(y=>y.kind==="time"))return {timeLimitReached:true};for(let y of R){if(y.kind==="error")throw y.error;if(y.kind==="missing"){F=false;continue}if(y.kind!=="fingerprint")continue;let{file:I,current:h}=y;C.set(I.relativePath,h),N??=h.candidateRealPath,(h.candidateRealPath!==l.candidateRealPath||!kr(h,I.fingerprint)||Ur(h,r))&&(F=false);}}let b=l!==void 0&&l.directoryListings.length===D.length&&l.directoryListings.every((R,y)=>R.relativePath===D[y]?.relativePath&&R.key===D[y]?.key);return l!==void 0&&k&&b&&F&&N===l.candidateRealPath?{memo:l}:!k||U.length!==Tr.length?{}:{context:{state:o,cacheKey:d,workspaceRoot:n,scanStartedAtNs:r,directoryListings:Object.freeze(D),priorFingerprints:C,files:new Map,...N===void 0?{}:{candidateRealPath:N},cacheable:true}}}function ft(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 Dr(e,n,t){let i=xr(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(Mr);if(!r.some(s=>s===null))return JSON.stringify(r.slice().sort((s,a)=>Cn(s.name,a.name)||Cn(s.kind,a.kind)).map(s=>[s.name,s.kind]))}function kr(e,n){return e.dev===n.dev&&e.ino===n.ino&&e.size===n.size&&e.mtimeNs===n.mtimeNs&&e.ctimeNs===n.ctimeNs}function Ur(e,n){let t=e.mtimeNs-n;return t>=-Pr&&t<=Pr}function Pi(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 ip(e,n,t){let i=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 op(e,n){let t={...e.definition,sourceHash:n},i;try{i=le(t);}catch(r){throw r instanceof x&&r.code==="INPUT_INVALID"?new se("MANIFEST_INVALID","normalized definition is invalid"):r}let o={...t,hash:i};try{Ae(o);}catch{throw new se("MANIFEST_INVALID","normalized definition is invalid")}return o}function rp(e,n){return e.actions.some(t=>t.backend.type==="core"&&t.backend.handler!=="state.set"&&!Yn(n,t.backend))}function sp(e){if(typeof e.readVerifiedFile=="function")return e.readVerifiedFile;if(typeof e.readFileVerified=="function")return e.readFileVerified}function xr(e){if(typeof e.listDirectory=="function")return e.listDirectory;if(typeof e.readDirectory=="function")return e.readDirectory;if(typeof e.readdir=="function")return e.readdir}async function Nr(e,n,t,i){let o=sp(e);if(!o)throw new M("READ_DENIED");return Wd(await o.call(e,n,t,i))}async function ap(e,n,t){let i=xr(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(Mr).filter(r=>r!==null)}function cp(e){let n=[];for(let t of [e.reserved,e.builtin])t&&n.push(t);return e.builtins&&"listMcpApps"in e.builtins?n.push(br(e.builtins)):e.builtins&&n.push(e.builtins),e.builtinCatalog&&n.push(br(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 br(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 _e(e,n){e.diagnostic||(e.diagnostic=lt(n,e.source,e.relativePath,e.identity?.pluginId));}function dp(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&&_e(d,"RESERVED_ID");continue}for(let d of r)d.provenance===void 0&&_e(d,"RESERVED_ID");if(s.length>1)for(let d of s)_e(d,"DUPLICATE_ID");continue}let a=r.filter(c=>c.source==="apps");if(a.length>1){for(let c of a)_e(c,"DUPLICATE_ID");for(let c of r.filter(d=>d.source==="skills"))_e(c,"DUPLICATE_ID");}else for(let c of r.filter(d=>d.source==="skills"))_e(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)_e(s,"DUPLICATE_ID");return t}function pp(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 cp(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)){_e(l,"RESERVED_ID");continue}[p.toolNames.read,p.toolNames.action].filter(f=>f!==void 0).some(f=>r.has(f))&&_e(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{nr(p),d.add(l);}catch(u){_e(l,u instanceof be?wr(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))&&_e(l,"RESERVED_ID");}return d}function lp(e){return [...e].sort((n,t)=>{let i=Ir.indexOf(n.source)-Ir.indexOf(t.source);return i!==0?i:Cn(n.relativePath,t.relativePath)})}function B(e,n,t){e.diagnostic=lt(n,e.source,e.relativePath,e.identity?.pluginId,t);}async function Sr(e,n,t){let i=Ge(t,{mode:"local"});if(!i.ok&&i.parseFailure){B(n,_r(i.rejection.code),hr(i.rejection));return}let o=Kd(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,_r(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{ai(r.actions.map(L=>({actionId:L.actionId,inputSchema:L.inputSchema})));}catch(L){if(L instanceof be){B(n,wr(L.code));return}throw L}let a;try{a=await ut(e,n,"ui/index.html",dn);}catch(L){B(n,Xe(ae(L),"entry"));return}if(a.byteLength>dn){B(n,"LIMIT_EXCEEDED");return}let c;try{c=Lr(a);}catch{B(n,"ENTRY_INVALID");return}if(a.byteLength===0||c.length===0){B(n,"ENTRY_INVALID");return}let d=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 ut(e,n,"ui/state.json",2097152);}catch(L){B(n,Xe(ae(L),"initial"));return}if(p.byteLength>2097152){B(n,"LIMIT_EXCEEDED");return}try{let L=Jd(p),J=r.dataPaths??[],pe=Wt(L,J);l=ye(pe,0,J),Qe(l);}catch{B(n,"INITIAL_STATE_INVALID");return}if(u=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),_=ip(f,a,p??new Uint8Array),P;try{P=op(g,_);}catch(L){if(L instanceof se){B(n,Xd(L));return}throw L}let k;if(n.bundleLineage!==void 0){let L=n.bundleLineage[n.bundleLineage.length-1];if(!L){B(n,"LINEAGE_INVALID");return}let{legacy:J,...pe}=L.definition,{hash:K,...Me}=P;if(te(pe)!==te(Me)){B(n,"LINEAGE_STALE");return}if(J!==void 0&&(P={...P,legacy:J}),J!==void 0)try{P={...P,hash:le(P)},Ae(P);}catch{B(n,"LINEAGE_INVALID");return}k=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=Hd(r.pluginId),D=r.actions.length===0?{read:U.read}:U,C=Ke(g),F=Ke(f),N=Ke(P),b=Ke({...g.handlers}),R=Er(a),y=p===void 0?void 0:Er(p),I=Object.freeze({...n.provenance===void 0?{}:{provenance:n.provenance},entry:Object.freeze({path:"ui/index.html",hash:d,bytes:R}),...y===void 0?{}:{initialState:Object.freeze({path:"ui/state.json",hash:u,bytes:y})}}),h={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:Ke(i.mcpb)},relativePath:n.relativePath,manifest:F,normalized:C,name:r.name,description:r.description,...r.icon===void 0?{}:{icon:r.icon},...r.tone===void 0?{}:{tone:r.tone},definition:N,handlers:b,resources:I,html:c,entryBytes:R,entryHash:d,initialState:Ke(l),...y===void 0?{}:{initialStateBytes:y},...u===void 0?{}:{initialStateHash:u},sourceHash:_,toolNames:Object.freeze(D)},E=n.provenance===void 0?{...h,source:n.source}:{...h,provenance:n.provenance,lineage:k??[]};n.candidate=Object.freeze(E),rp(r,P.usage)&&B(n,"EXEC_DENIED");}async function vr(e,n){let t={};for(let i of Z)try{t[i]=await ut(e,n,i,262144);}catch(o){if(ae(o)==="NOT_FOUND")continue;return {files:t,failure:Xe(ae(o),"manifest")}}if(t[W]!==void 0)try{t[H]=await ut(e,n,H,262144);}catch(i){if(ae(i)!=="NOT_FOUND")return {files:t,failure:Xe(ae(i),"manifest")}}return {files:t}}function Di(e){return Z.some(n=>e[n]!==void 0)}async function up(e,n){let{files:t,failure:i}=await vr(e,n);if(i!==void 0){B(n,i);return}let o=t[W];return o!==void 0&&!Qt(o)&&(delete t[W],delete t[H]),Di(t)?t:void 0}function fp(e,n,t,i=Bd,o=false,r=new Set){let s=lp(e),a=dp(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 yp(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 Ap(e,n){if(yp(e))return {fs:e,options:{}};let t=e??n??{};return {fs:t.filesystem??t.fileSystem??t.fs??dr,options:t}}async function jr(e,n,t){if(typeof e!="string"||e.length===0)throw new TypeError("workspaceRoot must be explicit");let{fs:i,options:o}=Ap(n,t),r=o.clock??Qd,s=r(),a=await Ar(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=or(o.scanCache,_),g.scanStartedAtNs=d;}catch(N){if(ae(N)!=="NOT_FOUND")throw N}let P=g!==void 0&&o.productBundle===void 0&&a.packages.length===0&&a.diagnostics.length===0,k=new Set,U=true;l.push(...a.diagnostics.map(N=>({source:N.source,root:o.productBundle?.root??e,name:"",relativePath:N.relativePath,diagnostic:N})));let D=a.reservedIds;a.incomplete&&(u="time_limit");for(let N of a.packages){if(!we(c,r)){f=true,u="time_limit";break}let b=N.indexEntry,R=b.packageDir,y=N.files===void 0?void 0:qd(R,N.files),I=a.indexHash===void 0?void 0:Ro(Object.freeze({kind:"bundled",launcher:b.launcher!==false,indexHash:a.indexHash,packageDir:R,appId:b.appId,definitionId:b.definition.id,version:b.definition.version,definitionHash:b.definition.hash,files:b.files}),y),h={source:"bundled",root:o.productBundle?.root??e,name:R.slice(5),relativePath:R,...I===void 0?{}:{provenance:I},...N.files===void 0?{}:{pinnedFiles:N.files},...N.lineage===void 0?{}:{bundleLineage:N.lineage},bundleIdentity:{appId:b.appId,definitionId:b.definition.id,version:b.definition.version,definitionHash:b.definition.hash},identity:Yd(b)};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 L of Z){let J=N.files?.get(L);J!==void 0&&(E[L]=J);}if(!Di(E)){B(h,"BUNDLE_INTEGRITY");continue}if(await Sr(i,h,E),!we(c,r)){f=true,u="time_limit";break}}let C=[{source:"apps",directory:"apps"},{source:"skills",directory:"skills"}];e:for(let N of C){let{source:b,directory:R}=N,y;try{y=await ap(i,e,R);}catch(h){if(ae(h)==="NOT_FOUND")continue;P=false,U=false,l.push({source:b,root:e,name:"",relativePath:b,diagnostic:lt(Xe(ae(h),"manifest"),b,b)});continue}let I=y.filter(h=>h.kind==="directory"||h.kind==="symlink").filter(h=>Gd(h.name)).map(h=>({source:b,root:e,name:h.name,relativePath:$d(b,h.name)})).sort((h,E)=>Cn(h.relativePath,E.relativePath));for(let h of I){let E={...h};if(l.push(E),_!==void 0?k.add(Cr(_,E)):P=false,!we(c,r)){f=true,u="time_limit";break e}let L;if(g!==void 0&&_!==void 0){try{let K=await tp(i,e,_,E,g,d,c,r);if(K.timeLimitReached){f=!0,u="time_limit";break e}E.scanContext=K.context,L=K.memo;}catch(K){P=false,B(E,Xe(ae(K),"manifest"));continue}L===void 0&&(P=false);}if(L!==void 0){if(E.candidate=L.candidate,E.diagnostic=L.diagnostic,E.identity=L.identity,b==="skills"&&L.candidate===void 0&&L.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,!we(c,r)){f=true,u="time_limit";break e}continue}let J;if(b==="skills"&&(J=await up(i,E),J===void 0)){E.diagnostic===void 0&&Pi(E);continue}if(p>=64){B(E,"LIMIT_EXCEEDED");continue}if(h.relativePath.split("/").length-1>2){B(E,"LIMIT_EXCEEDED");continue}if(!we(c,r)){f=true,u="time_limit";break e}if(p+=1,J===void 0){let K=await vr(i,E);if(K.failure!==void 0||!Di(K.files)){B(E,K.failure??Xe("NOT_FOUND","manifest")),Pi(E);continue}J=K.files;}if(await Sr(i,E,J),Pi(E),!we(c,r)){f=true,u="time_limit";break e}}}if(g!==void 0&&_!==void 0){let N=[...k].sort(Cn),b=g.lastCandidateKeys,R=b!==void 0&&b.length===N.length&&b.every((I,h)=>I===N[h]);if(P=P&&R,U&&!f&&u===void 0)for(let I of g.candidates.keys())try{JSON.parse(I)[0]===_.realPath&&!k.has(I)&&g.candidates.delete(I);}catch{g.candidates.delete(I);}let y=[...g.candidates.keys()].filter(I=>{try{return JSON.parse(I)[0]===_.realPath}catch{return false}});P=P&&y.length===k.size&&y.every(I=>k.has(I))&&!f&&u===void 0,g.lastCandidateScanUnchanged=P,U&&!f&&u===void 0&&(g.lastCandidateKeys=Object.freeze(N));}f&&l.push({source:"apps",root:e,name:"",relativePath:"apps",diagnostic:lt("DISCOVERY_TIME_LIMIT","apps","apps")});let F=pp(l,o,D);return fp(l,u,a.indexHash,D,o.productBundle!==void 0,F)}var Bd,Ti,Ir,zd,Tr,np,Pr,Fr=V(()=>{m();He();xn();Le();ei();Be();tt();tr();qn();Kn();rr();Ai();Xn();Ei();Ei();Bd=dt([]),Ti="crewx_local_app_";Ir=["bundled","apps","skills"],zd=new TextDecoder("utf-8",{fatal:true});Tr=["","/ui"],np=["/dist"],Pr=2000000000n;});m();ei();m();xt();m();var go="SKILL.md",Sc=/^---\s*\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;function mo(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function Mc(e){return e.isDirectory()||e.isSymbolicLink()}function Po(e){try{return existsSync(e)&&statSync(e).isDirectory()}catch{return false}}function ni(e){let n;try{n=readFileSync(e,"utf8");}catch{return {frontmatter:{},readable:false,valid:false,hasFrontmatter:false}}let t=n.match(Sc);if(!t)return {frontmatter:{},readable:true,valid:true,hasFrontmatter:false};try{let i=load(t[1]??"");if(!mo(i))return {frontmatter:{},readable:!0,valid:!1,hasFrontmatter:!0};let o=mo(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 Lc(e){return [join(e,go),join(e,"skill",go)]}function ho(e,n){if(!Po(e))return null;for(let t of Lc(e)){if(!existsSync(t))continue;let o=ni(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 _o(e){try{return readdirSync(e,{withFileTypes:!0}).filter(Mc)}catch{return []}}function Eo(e,n,t){!e||n.has(e.name)||(n.add(e.name),t.push(e));}function Do(e){let n=[],t=new Set;for(let i of e)if(Po(i))for(let o of _o(i)){if(o.name.startsWith("@")){let r=join(i,o.name);for(let s of _o(r))Eo(ho(join(r,s.name),s.name),t,n);continue}Eo(ho(join(i,o.name),o.name),t,n);}return n.sort((i,o)=>i.name.localeCompare(o.name))}m();Wn();var Rc=/^[A-Za-z0-9_$.[\]"-]{0,200}$/,Oc=/^[a-z][a-z0-9-]{0,63}$/,wc="<unknown>";function Cc(e){return typeof e=="string"&&(Z.includes(e)||e===H)}function No(e){if(typeof e!="object"||e===null)return;let{file:n,path:t,rule:i}=e;if(!(typeof i!="string"||!Oc.test(i)))return {...Cc(n)?{file:n}:{},path:typeof t=="string"&&Rc.test(t)?t:wc,rule:i}}function bo(e){if(!Array.isArray(e))return;let n=Z.filter(t=>e.includes(t));return n.length>0?n:void 0}Fr();var gp=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/;function It(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?mp(e.relativePath,e.fileBytes):void 0);if(n!==void 0&&i!==void 0){let o=JSON.stringify({screenHash:n,skillHash:i});return 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 mp(e,n){let t=new TextEncoder().encode(gt(e)),i=hp(n),o=new Uint8Array(t.byteLength+1+i.byteLength);return o.set(t,0),o[t.byteLength]=0,o.set(i,t.byteLength+1),createHash("sha256").update(o).digest("hex")}function hp(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 gt(e){if(typeof e!="string"||e.length===0||isAbsolute(e)||/[\\\u0000]/.test(e))throw new TypeError("relative path must be package-relative");let n=e.split("/").filter(t=>t.length>0&&t!==".").join("/");if(!n||n.split("/").some(t=>t===".."))throw new TypeError("relative path must stay inside the package");return n}function yt(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 Hr(e,n){let t=relative(e,n).split(sep).join("/");return !t||t===".."||t.startsWith("../")||isAbsolute(t)?null:gt(t)}function _p(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 zr(e){return Object.freeze({packageRoot:e})}function Ep(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 $r(e){return {capabilities:Object.freeze([...e]),origin:"local",ownership:"unknown",shareability:"unknown",sharingAvailability:"unavailable"}}function Tp(e,n){let t=e.candidate,i=t.provenance!==void 0,o=n&&!i?["screen","skill"]:["screen"],r=Ep(t),s=It(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,...$r(o),definition:r,...n===void 0||i?{}:{skillName:n.skill.name},...i?{provenance:t.provenance}:{localDefinitionRef:zr(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 Pp(e){let n=Dp(e.skill.name),t={appId:n,name:e.skill.name,description:e.skill.description??"",...e.skill.version===void 0?{}:{version:e.skill.version},...$r(["skill"]),skillName:e.skill.name,localDefinitionRef:zr(e.packageRoot),definitionHash:It({skillHash:e.skillHash})};return {packageRoot:e.packageRoot,source:e.source,appId:n,capabilities:["skill"],summary:Object.freeze(t)}}function Dp(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=No(o?.reason),s=bo(o?.files);return Object.freeze({code:e,source:n,relativePath:Np(t),...i===void 0?{}:{appId:i},...r===void 0?{}:{reason:r},...s===void 0?{}:{files:s}})}function Np(e){if(typeof e!="string"||e.length===0||isAbsolute(e)||/[\\\u0000]/.test(e))return "<unknown>";let n=e.split("/").filter(t=>t.length>0&&t!==".").join("/");return n.split("/").some(t=>t==="..")?"<unknown>":n}function Gr(e){return Q(e.code,e.source,e.relativePath,e.pluginId,e)}function bp(e,n){let t=Hr(e,n.dir);if(!t)return {diagnostic:Q("PATH_ESCAPED","node_modules","node_modules")};let i=_p(t);if(!i)return {diagnostic:Q("PATH_ESCAPED","node_modules",t)};let o=ni(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=Sp(n.dir,n.skillMdPath);if(!r)return {diagnostic:Q("PATH_ESCAPED",i,t)};try{let s=new Uint8Array(readFileSync(n.skillMdPath));return {skill:n,packageRoot:t,relativeSkillPath:r,skillHash:It({relativePath:r,fileBytes:s}),source:i}}catch{return {diagnostic:Q("SKILL_READ_FAILED",i,t)}}}function Sp(e,n){let t=relative(e,n).split(sep).join("/");try{return gt(t)}catch{return null}}function Mp(e){if(!gp.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??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??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 Lp(e){return e.builtinCatalog}function Rp(e){let n=e.packageRoot??e.relativePath??e.packageRootPath;if(n===void 0)return null;try{return gt(n)}catch{return null}}function Op(e){let n=e.marketplaceContentId;return typeof n=="string"&&n.length>0?n:void 0}function wp(e,n,t){let i=n.installed??[],o=new Map;for(let s of i){let a=Rp(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=Op(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 Cp(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,At(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,At(a),a.appId));if(s.length>1)for(let a of s)i.add(a),n.push(Q("DUPLICATE_ID",a.source,At(a),a.appId));continue}for(let s of o)i.add(s),n.push(Q("DUPLICATE_ID",s.source,At(s),s.appId));}return e.filter(o=>!i.has(o))}function At(e){return e.packageRoot??e.summary.provenance?.packageDir??`builtin/${e.appId}`}function kp(e,n){return e.filter(t=>!(t.code==="MANIFEST_MISSING"&&n.has(t.relativePath))).map(Gr)}function Up(e){return e.filesystem}function xp(e,n){let t=Up(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 Wr(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=Lp(n),i=await jr(e,xp(n,t)),o=n.registeredProductBundle??i.productBundleSnapshotMetadata,r=[join(e,"skills"),join(e,"node_modules"),join(e,"apps")],s=[],a=[],c=[],d=new Set;for(let I of r)for(let h of Do([I])){let E=Hr(e,h.dir);(E===null||!d.has(E))&&(c.push(h),E!==null&&d.add(E));}for(let I of c){let h=bp(e,I);"diagnostic"in h?s.push(h.diagnostic):a.push(h);}let l=new Map,p=n.registeredProductBundle?.indexHash,u=(n.registeredProductBundle?.candidates??[]).filter(I=>p!==void 0&&I.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(I=>I.provenance?.indexHash===p).map(I=>I.appId));for(let I of f){if(g.has(I)&&I.provenance?.indexHash===p&&_.has(I.appId))continue;let h=I.provenance===void 0?`workspace\0${I.relativePath}`:`bundled\0${I.provenance.indexHash}\0${I.provenance.packageDir}`;l.set(h,{candidate:I,packageRoot:I.relativePath});}let P=new Map(a.map(I=>[I.packageRoot,I])),k=[];for(let I of l.values()){let h=I.candidate.provenance===void 0?P.get(I.packageRoot):void 0,E=Tp(I,h);k.push({...E.packageRoot===void 0?{}:{packageRoot:E.packageRoot},source:E.source,appId:E.appId,summary:E.summary});}let U=new Set([...l.values()].filter(I=>I.candidate.provenance===void 0).map(I=>I.packageRoot)),D=o===void 0?new Set:new Set(i.diagnostics.filter(I=>I.code==="RESERVED_ID"&&I.source!=="bundled").map(I=>I.relativePath)),C=new Set(o?.reservedAppIds??[]);for(let I of a){let h=Pp(I);if(!(U.has(I.packageRoot)||D.has(I.packageRoot))){if(C.has(h.appId)){s.push(Q("RESERVED_ID",I.source,I.packageRoot,h.appId));continue}k.push({packageRoot:h.packageRoot,source:h.source,appId:h.appId,summary:h.summary});}}let F=[...kp(i.diagnostics,new Set(a.map(I=>I.packageRoot))),...s,...n.registeredProductBundle?.diagnostics.filter(I=>I.source==="bundled").map(Gr)??[]],N=[];if(t)for(let I of t.listMcpApps()){let h=Mp(I);"diagnostic"in h?F.push(h.diagnostic):N.push(h);}let b=Cp([...k,...N],F);wp(b,n,F);let R=b.map(I=>I.summary).sort((I,h)=>yt(I.appId,h.appId)),y=[...F].sort((I,h)=>yt(I.relativePath,h.relativePath)||yt(I.code,h.code)||yt(I.appId??"",h.appId??""));return Object.freeze({items:Object.freeze(R),diagnostics:Object.freeze(y)})}m();m();m();function vp(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 vp(n).test(e)}catch{return false}}function mt(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 jp(e,n){return e.split("/").some(t=>un(t,n))}var Jr=[{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&&mt(n,".crewx","threads")},{label:".crewx/crewx.db",test:(e,n,t)=>!t&&mt(n,".crewx","crewx.db")},{label:".crewx/*.log",test:(e,n,t)=>!t&&mt(n,".crewx","*.log")},{label:".crewx/publish/",test:(e,n,t)=>t&&mt(n,".crewx","publish")},{label:".crewx/",test:(e,n)=>jp(n,".crewx")}];function fn(e,n,t){for(let i of Jr)if(i.test(e,n,t))return i.label;return null}m();var Ce=class extends Error{constructor(t,i){super(`publish: [${t}]${i?` ${i}`:""}`);this.code=t;}code;name="PublishError"};function T(e,n){return new Ce(e,n)}function Kr(e,n){if(!n||/[\\\u0000]/.test(n)||ce.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.resolve(e),i=ce.resolve(t,...n.split("/"));if(!i.startsWith(`${t}${ce.sep}`))throw T("PACKAGE_PATH_TRAVERSAL","package root escaped the workspace");function o(f,g){let _;try{_=ne.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.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 _=ne.readdirSync(f,{withFileTypes:true});for(let P of _){let k=`${g}/${P.name}`,U=ce.join(f,P.name);if(P.isSymbolicLink())throw T("PACKAGE_SYMLINK",`symlink is not publishable: ${k}`);let D=fn(P.name,k,P.isDirectory());D?d.push({path:k,rule:D}):P.isDirectory()?l(U,k):P.isFile()&&c.push(k);}}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 Xr(e){let n=[],t=[];function i(o,r,s){let a;try{a=ne.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.join(o,c.name);if(c.isSymbolicLink()){let p;try{p=ne.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 Fp=[{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 Vp(e){return e.includes(0)}function Mi(e,n,t){let i=[];for(let o of n){let r=ce.join(e,o),s;try{let c=t?.get(o);s=c===void 0?ne.readFileSync(r):Buffer.from(c);}catch{continue}if(Vp(s))continue;s.toString("utf8").split(/\r\n|\r|\n/).forEach((c,d)=>{for(let{rule:l,regex:p}of Fp)p.test(c)&&i.push({path:o,line:d+1,rule:l});});}return i}m();var Zr=/^[a-z0-9-]+$/,Bp=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/,Hp=/^[A-Za-z_][A-Za-z0-9_]*$/;function zp(e){let n=ce.join(e,"crewx.yaml");if(!ne.existsSync(n))return {};let t;try{t=Qr.load(ne.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 $p(e){return Li.createHash("sha256").update(e).digest("hex")}function es(e){let n;try{n=ne.lstatSync(e);}catch{throw T("PACKAGE_FILE_INVALID",`file is not readable: ${ce.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 Li.createHash("sha256").update(new Uint8Array(ne.readFileSync(e))).digest("hex")}function Gp(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 ns(e){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||ce.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 Wp(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 ts(e){if(!Bp.test(e))throw new Error(`publish: invalid version "${e}" \u2014 must be semver (e.g. 1.0.0)`)}function is(e,n,t={}){let i=zp(e),o=i.name??ce.basename(e);if(!Zr.test(o))throw new Error(`publish: invalid name "${o}" \u2014 must match ${Zr} (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");ts(r);let s=Array.isArray(i.requiredEnv)?i.requiredEnv:[],a=[];for(let l of s){if(typeof l!="string"||!Hp.test(l))throw new Error(`publish: requiredEnv must contain names only (no values), got "${String(l)}"`);a.push(l);}let c=n.map(l=>(ns(l),{path:l,sha256:es(ce.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 Jp(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 os(e,n){if(Wp(n.packageRoot),!n.version)throw new Error("publish: version is required for App publishing \u2014 pass opts.version");if(ts(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(ns(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?es(ce.join(e,s)):$p(a),...a===void 0?{}:{generated:true}}}).sort((s,a)=>Gp(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:Jp(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 rs(e){return Li.createHash("sha256").update(e).digest("hex")}function ps(e,n){if(typeof n!="string"||n.length===0||n.includes("\\")||n.includes("\0")||ce.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.resolve(e),i=ce.resolve(t,...n.split("/"));if(i!==t&&!i.startsWith(`${t}${ce.sep}`))throw T("PACKAGE_PATH_TRAVERSAL","archive path escaped its root");return i}function ss(e,n){let t=ps(e,n),i;try{i=ne.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(ne.readFileSync(t))}async function ls(e,n,t={}){let i=ce.join(e,".crewx","publish");ne.mkdirSync(i,{recursive:true});let o=ce.join(i,`${n.name}-${n.version}.tgz`),r=ce.join(i,`.${n.name}-${n.version}.${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}.tmp.tgz`),s=ne.mkdtempSync(ce.join(as.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=ss(e,d.path);if(t.sourceFileHashes.get(d.path)!==rs(f))throw T("PACKAGE_STAGED_BYTES_MISMATCH","workspace source changed before staging")}let p=l??ss(e,d.path);if(rs(p)!==d.sha256)throw T("PACKAGE_STAGED_BYTES_MISMATCH",`staged bytes differ for ${d.path}`);let u=ps(s,d.path);ne.mkdirSync(ce.dirname(u),{recursive:!0}),ne.writeFileSync(u,new Uint8Array(p)),c.push(d.path);}ne.writeFileSync(ce.join(s,"manifest.json"),JSON.stringify(n,null,2)),await ds.create({gzip:!0,file:r,cwd:s,portable:!0,noMtime:!0},["manifest.json",...c]),ne.renameSync(r,o);}finally{try{ne.rmSync(r,{force:!0});}catch{}ne.rmSync(s,{recursive:true,force:true});}return o}m();m();var yn="/api/v1";var Yp=201,qp=200,Zp=409,Ri=401,us={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 Qp(){return process.env.WI013_FAKE_UPLOAD==="1"}function el(e){let n=gunzipSync(new Uint8Array(e)),t=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 nl(e){return e.replace(/\/+$/,"")}async function kn(e){try{return await e.json()}catch{return null}}function fs(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 tl(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 il(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 ys(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(us,r))continue;let s=r,a=s==="APP_NAME_CONFLICT"?`marketplace name is already in use: ${n}`:void 0;return T(us[s],a)}}async function ol(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=nl(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 kn(a),d=tl(c),l=il(c),p=r&&l!==void 0?l:i,u;if(a.status===Yp)u="created";else if(r&&a.status===qp){if(d===void 0)throw T("PUBLISH_CONTENT_ID_MISSING","App republish did not return an opaque contentId");u="existing";}else if(a.status===Zp){if(r)throw ys(c,i)??T("APP_NAME_CONFLICT",`marketplace name is already in use: ${i}`);u="existing";}else throw a.status===Ri?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 R=await kn(b);if(b.status!==200)throw new Error(`publish: [E_HTTP] Publisher items request failed \u2014 HTTP ${b.status}`);let I=fs(R,"publisher items",b.status)?.items;if(!Array.isArray(I))throw new Error(`publish: [E_MALFORMED] Publisher items response is malformed (expected data.items[]) \u2014 HTTP ${b.status}`);let h=I.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 kn(E),E.status===Ri?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 _=ne.readFileSync(e.tgzPath),P=Qp()?el(_):_,k=new FormData;k.set("archive",new Blob([new Uint8Array(P)],{type:"application/gzip"}),`${p}-${e.manifest.version}.tgz`);let U=r&&d!==void 0?d:i,D;try{D=await fetch(`${n}${yn}/publisher/items/${encodeURIComponent(U)}/upload`,{method:"POST",headers:{Authorization:`Bearer ${e.accessToken}`},body:k});}catch{throw new Error("publish: [E_NETWORK] Upload request failed (network)")}if(D.status===Ri)throw new Error("publish: [E_AUTH_EXPIRED] Authentication is expired or missing \u2014 please log in again (HTTP 401)");if(!D.ok){let b=await kn(D);if(r){let R=ys(b,p);if(R)throw R}throw new Error(`publish: [E_HTTP] Upload request failed \u2014 HTTP ${D.status}`)}let C=await kn(D),F=fs(C,"upload",D.status),N=typeof F.contentId=="string"&&F.contentId.length>0?F.contentId:d;if(r&&N===void 0)throw T("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:F.artifactChecksum,artifactSizeBytes:F.artifactSizeBytes,submitOutcome:u,versionUpdate:f,serverVersionBefore:g}}var rl=1e4,sl=100*1024*1024;function Oi(e){return Li.createHash("sha256").update(e).digest("hex")}function al(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function Un(e,n){if(!n||n.includes("\\")||n.includes("\0")||ce.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.resolve(e,...n.split("/")),i=ce.resolve(e);if(t!==i&&!t.startsWith(`${i}${ce.sep}`))throw T("PACKAGE_PATH_TRAVERSAL","workspace file path escaped the workspace root");let o;try{o=ne.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(ne.readFileSync(t))}function Is(e,n,t){let i=e??n;if(!Number.isSafeInteger(i)||i<=0)throw new Ce("PACKAGE_SIZE_LIMIT",`${t} must be a positive integer`);return i}function ms(e,n,t,i){let o=Is(t.maxFileCount??t.maxFiles,rl,"max file count"),r=Is(t.maxTotalBytes??t.maxBytes,sl,"max total bytes");if(n.length>o)throw new Ce("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+=Un(e,a).byteLength,s>r)throw new Ce("PACKAGE_SIZE_LIMIT",`package exceeds byte limit (${r})`)}}function cl(e){return e.appId!==void 0||e.expectedDefinitionHash!==void 0}function dl(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 pl(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 ll(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 wi(e){let{path:n,rule:t}=e.reason;return `${e.code} at ${n===""?"<file>":n} (${t})`+(e.files.length>0?` [${e.files.join(", ")}]`:"")}function ul(e,n,t){let i=Ge({[de]:t},{mode:"published"});if(!i.ok)throw T("APP_UI_MANIFEST_INVALID",`generated ${de} does not read: ${wi(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[W];if(o===void 0)return;let r=e[H],s=Ge({[W]:o,[de]:t,...r===void 0?{}:{[H]:r}},{mode:"local"});if(!s.ok)throw T("APP_UI_MANIFEST_INVALID",wi(s.rejection))}function fl(e,n,t,i){let o={};for(let f of Z){let g=`${t}/${f}`;i.includes(g)&&(o[f]=Un(e,g));}let r=`${t}/${H}`;if(o[W]!==void 0&&i.includes(r)&&(o[H]=Un(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=Ge(o,{mode:"local"});if(!s.ok)throw T("APP_UI_MANIFEST_INVALID",wi(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:Oi(a),d=`${t}/ui/index.html`;if(!i.includes(d))throw T("APP_UI_MANIFEST_INVALID","screen entry is outside package scope");let l=Oi(Un(e,d)),p=JSON.parse(JSON.stringify(s.v2Input));if(p.entryHash=l,Object.prototype.hasOwnProperty.call(p,"initialState")){let f=p.initialState;if(!al(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 _=Un(e,g);p.initialState={...f,hash:Oi(_)};}let u;try{let f=$e(p,{mode:"published"});u=new Uint8Array(Buffer.from(JSON.stringify(f),"utf8"));}catch(f){throw f instanceof se?T("APP_UI_MANIFEST_INVALID",f.code):T("APP_UI_MANIFEST_INVALID")}return ul(o,s.manifest,u),{bytes:u,...c===void 0?{}:{legacySourceHash:c}}}async function yl(e,n){let{included:t,excluded:i}=Xr(e);ms(e,t,n);let o=is(e,t,{version:n.version}),r=Mi(e,t);return {plan:{manifest:o,included:t,excluded:i,secretFindings:r},archiveOptions:{}}}async function Al(e,n){dl(n);let t=await Wr(e),i=pl(t.items,n.appId);if(i.definitionHash!==n.expectedDefinitionHash)throw T("APP_DEFINITION_CONFLICT",`definitionHash changed for ${n.appId}`);let o=ll(i),{included:r,excluded:s}=Kr(e,o),a=new Map,c=new Map;if(i.capabilities.includes("screen")){let u=fl(e,i,o,r),f=`${o}/${de}`;if(a.set(f,u.bytes),u.legacySourceHash!==void 0)c.set(f,u.legacySourceHash);else {r.push(f);let g=new TextEncoder;r.sort((_,P)=>Buffer.compare(g.encode(_),g.encode(P)));}}if(i.capabilities.includes("skill")&&!r.includes(`${o}/SKILL.md`))throw T("APP_SKILL_MISSING","skill capability requires package-root SKILL.md");ms(e,r,n,a);let d={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:a},l=os(e,d),p=Mi(e,r,a);return {plan:{manifest:l,included:r,excluded:s,secretFindings:p},archiveOptions:{generatedFiles:a,sourceFileHashes:c}}}async function hs(e,n){let t=ce.resolve(e);if(cl(n))return Al(t,n);if(n.expectedDefinitionHash!==void 0)throw T("APP_ID_REQUIRED");return yl(t,n)}async function mA(e,n={}){return (await hs(e,n)).plan}function Il(e){let n=e.map(t=>`${t.path}:${t.line} (${t.rule})`).join(", ");throw new Ce("PUBLISH_SECRET_FINDINGS",`aborted \u2014 secret findings must be resolved before packing: ${n}`)}async function _s(e,n={}){let t=ce.resolve(e),i=await hs(t,n);i.plan.secretFindings.length>0&&Il(i.plan.secretFindings);let o=await ls(t,i.plan.manifest,i.archiveOptions);return {manifest:i.plan.manifest,tgzPath:o}}async function hA(e,n={}){return _s(e,n)}async function _A(e,n){let t=await _s(e,n);if(t.manifest.type!=="app")throw new Error("publish: App pack unexpectedly produced a template manifest");return t}
|
|
2
|
+
export{sl as DEFAULT_PUBLISH_MAX_BYTES,rl as DEFAULT_PUBLISH_MAX_FILES,Jr as EXCLUDE_RULES,yn as MARKETPLACE_API_PREFIX,Ce as PublishError,_A as packApp,_s as packPublish,hA as packTemplate,mA as planPublish,ol as uploadToMarketplace};
|