@crewx/sdk 0.9.0-rc.160 → 0.9.0-rc.162
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/agent-interceptor/chain.d.ts +25 -0
- package/dist/agent-interceptor/index.d.ts +6 -0
- package/dist/agent-interceptor/model-runner.d.ts +19 -0
- package/dist/agent-interceptor/program-runner.d.ts +13 -0
- package/dist/agent-interceptor/protocol.d.ts +68 -0
- package/dist/agent-interceptor/run-stop.d.ts +3 -0
- package/dist/agent-interceptor/schema.d.ts +267 -0
- package/dist/agent-interceptor/types.d.ts +88 -0
- package/dist/app/app.d.ts +10 -1
- package/dist/app/index.d.ts +2 -0
- package/dist/app/index.js +10 -10
- package/dist/app/schedule-contract.d.ts +59 -0
- package/dist/esm/app/index.js +10 -10
- package/dist/esm/index.js +237 -229
- package/dist/esm/plugins/index.js +86 -81
- package/dist/esm/publish/index.js +2 -2
- package/dist/esm/repository/index.js +98 -93
- package/dist/esm/skills/index.js +2 -2
- package/dist/events/types.d.ts +12 -0
- package/dist/facade/Crewx.d.ts +9 -0
- package/dist/index.browser.d.ts +2 -0
- package/dist/index.browser.js +4 -4
- package/dist/index.d.ts +14 -3
- package/dist/index.js +306 -298
- package/dist/mcp-app/app-icon-read.d.ts +7 -0
- package/dist/mcp-app/app-schedule.d.ts +85 -0
- package/dist/mcp-app/dev-checks.d.ts +2 -0
- package/dist/mcp-app/discovery.d.ts +3 -0
- package/dist/mcp-app/index.d.ts +5 -1
- package/dist/mcp-app/skill-backend.d.ts +5 -2
- package/dist/mcp-app/workspace-snapshot.d.ts +3 -0
- package/dist/plugins/index.js +83 -78
- package/dist/provider/bridge.d.ts +5 -1
- package/dist/provider/cli/adapter.types.d.ts +9 -0
- package/dist/provider-account/accounts.d.ts +15 -0
- package/dist/provider-account/index.d.ts +5 -0
- package/dist/provider-account/registry.d.ts +30 -0
- package/dist/provider-account/types.d.ts +40 -0
- package/dist/publish/errors.d.ts +1 -1
- package/dist/publish/index.d.ts +5 -0
- package/dist/publish/index.js +2 -2
- package/dist/repository/index.js +99 -94
- package/dist/repository/task.repository.d.ts +7 -0
- package/dist/repository/thread.repository.d.ts +1 -0
- package/dist/skills/index.js +2 -2
- package/dist/types/index.d.ts +33 -0
- package/dist/types/task-log.types.d.ts +3 -1
- package/dist/ui-instance/types.d.ts +8 -0
- package/dist/ui-plugin/app-icon.d.ts +50 -0
- package/dist/ui-plugin/index.d.ts +2 -0
- package/dist/ui-plugin/types.d.ts +2 -1
- package/dist/utils/id.d.ts +1 -1
- package/package.json +1 -1
|
@@ -1,2 +1,2 @@
|
|
|
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{
|
|
1
|
+
import*as de from'path';import {resolve,relative,sep,isAbsolute,join}from'path';import'url';import*as vi 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 ms from'js-yaml';import {load}from'js-yaml';import*as bs from'os';import*as Ms from'tar';import {gunzipSync,gzipSync}from'zlib';var V=(e,n)=>()=>(e&&(n=e(e=0)),n);var m=V(()=>{});var v,jn=V(()=>{m();v=class extends Error{constructor(t,i=t,o){super(i);this.code=t;this.currentRevision=o;}code;currentRevision;name="UiRuntimeError"};});function St(e){return Vs.test(e)||Bs.test(e)}function fe(){throw new v("INPUT_INVALID","JSON value is not projection-safe")}function Gs(e){let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function Nt(e,n,t,i,o,r){if(n>i&&fe(),e===null||typeof e=="string"||typeof e=="boolean")return typeof e=="string"&&(Hs.test(e)||$s.test(e)&&!Ks(o,r)||zs.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=>Nt(c,n+1,t,i,o,r));Gs(s)||fe();let a={};for(let[c,d]of Object.entries(e))St(c)&&fe(),a[c]=Nt(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>Js)&&fe(),(!Array.isArray(t)||t.some(o=>typeof o!="string"))&&fe();let i=Nt(e,0,new Set,Ws+n,[],t);return (i===null||Array.isArray(i)||typeof i!="object")&&fe(),i}function en(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 Ks(e,n){if(e.length===0)return false;let t=e.join(".");return n.some(i=>en(t,i))}function nn(e){try{let n=JSON.stringify(e);return n===void 0&&fe(),n}catch{fe();}}function bt(e){return Array.isArray(e)?e.map(bt):e!==null&&typeof e=="object"?Object.fromEntries(Object.keys(e).sort().map(n=>[n,bt(e[n])])):e}function ie(e){return nn(bt(e))}function Mt(e){return Buffer.byteLength(e,"utf8")}var Vs,Bs,Hs,zs,$s,Ws,Js,Me=V(()=>{m();jn();Vs=/(?:proof|token|secret|password|cookie|authorization|private[_-]?key|stack|exception|plugin[_-]?text)/i,Bs=/(?:url|uri|endpoint|path|file(?:name|path)?|cwd|shell|directory|dir|folder)$/i,Hs=/<\/?[A-Za-z][^>]*>/,zs=/^(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)/,$s=/^(?:https?|file|ftp|ws|wss):\/\//i;Ws=8,Js=4;});var Bi=V(()=>{m();Me();});var Vn,Lt=V(()=>{m();Vn=["text/plain","application/json"];});var Hi=V(()=>{m();Lt();});function tn(e){return Ys.has(e)||qs.test(e)||Zs.test(e)}var zi,Ys,qs,Zs,Bn,In,Te,Rt,Ot,wt,Ct,Ut,ze=V(()=>{m();zi=["__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"],Ys=new Set(zi),qs=/(?:proof|token|secret|password|cookie|authorization|private[_-]?key|stack|exception|plugin[_-]?text)/i,Zs=/(?:url|uri|endpoint|path|file(?:name|path)?|cwd|shell|directory|dir|folder)$/i;Bn=/^[A-Za-z0-9_]+$/,In=/^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)*$/,Te=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,Rt=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/,Ot=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,wt=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/,Ct=["blue","violet","emerald","amber","rose","sky","slate","indigo"],Ut=["inline","panel"];});function kt(e){return typeof e=="string"&&Vn.includes(e)}var $i=V(()=>{m();Lt();ze();});function Hn(e){if(!xt(e))return false;let n=Object.keys(e);return !(n.some(t=>t!=="in"&&t!=="out")||n.length===0||Object.hasOwn(e,"in")&&!Qs(e.in)||Object.hasOwn(e,"out")&&!ea(e.out))}function Qs(e){return xt(e)?Object.keys(e).every(t=>t==="mediaType"||t==="required")&&Object.hasOwn(e,"mediaType")&&kt(e.mediaType)&&(!Object.hasOwn(e,"required")||typeof e.required=="boolean"):false}function ea(e){return xt(e)?Object.keys(e).every(t=>t==="mediaType"||t==="range")&&Object.hasOwn(e,"mediaType")&&kt(e.mediaType)&&(!Object.hasOwn(e,"range")||typeof e.range=="boolean"):false}function xt(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}var vt=V(()=>{m();Hi();$i();new TextDecoder("utf-8",{fatal:true,ignoreBOM:true});});function $n(e){return na.includes(e)}function Gn(e){return Number.isSafeInteger(e)&&e>=zn.min&&e<=zn.max}var na,zn,Gi,Ft=V(()=>{m();na=[5,15,30,60],zn=Object.freeze({min:15e3,max:6e5,default:3e5}),Gi=1;});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(ie(i)).digest("hex")}function Vt(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 v("DEFINITION_UNSUPPORTED","UI definition is invalid");if(e.sourceHash!==void 0&&(typeof e.sourceHash!="string"||!ia.test(e.sourceHash)))throw new v("DEFINITION_UNSUPPORTED","UI definition source hash is invalid");if(!/^[0-9a-f]{64}$/.test(e.hash)||le(e)!==e.hash)throw new v("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=>!ra(i)))throw new v("DEFINITION_UNSUPPORTED","UI action declaration is invalid");if(t.confirmation!==void 0&&t.confirmation!=="none"&&t.confirmation!=="native")throw new v("DEFINITION_UNSUPPORTED","UI action confirmation is invalid");if(t.inputKeys&&(!Array.isArray(t.inputKeys)||t.inputKeys.some(i=>typeof i!="string"||!i)))throw new v("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 v("DEFINITION_UNSUPPORTED","UI action data input declaration is invalid");if(t.resultProjection&&jt(t.resultProjection),t.schedule!==void 0&&(!$n(t.schedule.everyMinutes)||!Gn(t.schedule.timeoutMs)))throw new v("DEFINITION_UNSUPPORTED","UI action schedule declaration is invalid");if(t.content!==void 0&&!Hn(t.content))throw new v("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 v("DEFINITION_UNSUPPORTED","UI action environment declaration is invalid")}if(e.renderer!==void 0&&(!e.renderer||e.renderer.length>128))throw new v("DEFINITION_UNSUPPORTED","UI definition renderer is invalid");if(e.surfaces&&(!Array.isArray(e.surfaces)||e.surfaces.some(n=>!n||n.length>64)))throw new v("DEFINITION_UNSUPPORTED","UI definition surfaces are invalid");if(e.usage!==void 0&&e.usage!=="card"&&e.usage!=="window")throw new v("DEFINITION_UNSUPPORTED","UI definition usage is invalid");if(e.detailPanel!==void 0&&typeof e.detailPanel!="boolean")throw new v("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 v("DEFINITION_UNSUPPORTED","UI definition displayModes are invalid");if(e.usage==="card"&&e.displayModes!==void 0)throw new v("DEFINITION_UNSUPPORTED","Card definitions cannot declare displayModes");if(e.usage==="window"&&e.detailPanel!==void 0)throw new v("DEFINITION_UNSUPPORTED","Window definitions cannot declare detailPanel");if(e.stateProjection&&jt(e.stateProjection),e.summaryProjection){jt(e.summaryProjection);let n=new Set(e.stateProjection?.allow??[]);if(e.summaryProjection.allow.some(t=>!n.has(t)))throw new v("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 v("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(oa(r,o==="readTool"),n.has(r.name))throw new v("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 v("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 v("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 v("DEFINITION_UNSUPPORTED","UI legacy agent access is invalid");if(e.legacy.actionTool!==void 0&&(!i||Object.keys(i).length===0))throw new v("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=>en(t,i))))throw new v("DEFINITION_UNSUPPORTED","UI definition dataPaths are invalid")}}function oa(e,n){if(!e||typeof e!="object"||Array.isArray(e))throw new v("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 v("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(Mt(nn(c))>4*1024)throw new Error("fixed result size")}}catch{throw new v("DEFINITION_UNSUPPORTED","UI legacy tool metadata is not projection-safe")}}function jt(e){if(!Array.isArray(e.allow)||e.allow.some(n=>!/^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)*$/.test(n)))throw new v("DEFINITION_UNSUPPORTED","UI projection policy is invalid")}function ra(e){return e.length>0&&e.length<=128&&e!=="*"&&e!=="all"&&!/[/*]/.test(e)}var ia,$e=V(()=>{m();Me();jn();vt();Ft();ia=/^[0-9a-f]{64}$/;});var z,Ge,Bt=V(()=>{m();z="dist/tools.json",Ge="dist/main.mjs";});var xe,Ht=V(()=>{m();xe="window";});function Wi(e){if(!Array.isArray(e)||e.length===0)return false;let n=new Set;for(let t of e){if(!sa.some(i=>i===t)||n.has(t))return false;n.add(t);}return true}var sa,Ji=V(()=>{m();sa=["CREWX_APP_INSTANCE_ID","CREWX_THREAD_ID"];});function $(e){throw new zt(e)}function ma(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 ha(e,n){let t=Object.getOwnPropertyDescriptor(e,n);return (!t||!("value"in t))&&$("CSP_ORIGIN_INVALID"),t.value}function Wn(e,n){if(!Object.prototype.hasOwnProperty.call(e,n))return [];let t=ha(e,n);Array.isArray(t)||$("CSP_ORIGIN_INVALID"),Reflect.ownKeys(t).some(r=>typeof r!="string"||r!=="length"&&!/^(?:0|[1-9][0-9]*)$/.test(r))&&$("CSP_ORIGIN_INVALID");let o=[];for(let r=0;r<t.length;r+=1)(!Object.prototype.hasOwnProperty.call(t,r)||typeof t[r]!="string")&&$("CSP_ORIGIN_INVALID"),o.push(t[r]);return Object.keys(t).length!==t.length&&$("CSP_ORIGIN_INVALID"),o}function _a(e){let n;try{n=JSON.stringify(e);}catch{$("CSP_ORIGIN_INVALID");}return n===void 0&&$("CSP_ORIGIN_INVALID"),new TextEncoder().encode(n).byteLength}function Yi(e,n){/\s|\\/u.test(e)&&$("CSP_ORIGIN_INVALID");let t=fa.exec(e);t||$("CSP_ORIGIN_INVALID");let i=t[1].toLowerCase(),o=t[2];(o.includes("@")||o.includes("%")||o.includes("*"))&&$("CSP_ORIGIN_INVALID"),(o.startsWith("[")?ya:Aa).test(o)||$("CSP_ORIGIN_INVALID"),i==="wss"&&n!=="connectDomains"&&$("CSP_ORIGIN_INVALID");let s;try{s=new URL(e);}catch{$("CSP_ORIGIN_INVALID");}(s.protocol!==`${i}:`||s.username!==""||s.password!==""||s.search!==""||s.hash!=="")&&$("CSP_ORIGIN_INVALID");let a=s.hostname.toLowerCase();if((!a||a.includes("%"))&&$("CSP_ORIGIN_INVALID"),!a.startsWith("[")){let d=a.endsWith(".")?a.slice(0,-1):a;(d.length===0||d.length>253)&&$("CSP_ORIGIN_INVALID"),d.split(".").some(p=>p.length>63||!Ia.test(p))&&$("CSP_ORIGIN_INVALID");}let c=s.origin;return (c==="null"||!c.startsWith(`${i}://`))&&$("CSP_ORIGIN_INVALID"),{origin:c,hostname:a}}function Ea(e){let n=e.split(".").map(Number);return ((n[0]*256+n[1])*256+n[2])*256+n[3]}function qi(e,n,t){let i=4294967295<<32-t>>>0;return (e&i)===(n&i)}function eo(e){let n=Ea(e);return qi(n,3221225472,24)?n!==3221225481&&n!==3221225482:ga.some(([t,i])=>qi(n,t,i))}function Ta(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 Pa(e){let n=Ta(e),t=Number(n>>112n),i=Number(n>>96n&0xffffn);if(n>>32n===0xffffn){let o=Number(n&0xffffffffn);return eo([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 Da(e,n){let t=e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e,i=isIP(t);if(i===4)return eo(t);if(i===6)return Pa(t);let o=e.toLowerCase().replace(/\.$/,"");return !o||!o.includes(".")||n.has(o)?true:ua.some(r=>o===r||o.endsWith(`.${r}`))}function Zi(e){return Object.freeze([...new Set(e.map(n=>n.origin))].sort())}function Qi(e){return JSON.stringify({baseUriDomains:[],connectDomains:e.connectDomains,declared:e.declared,frameDomains:e.frameDomains,resourceDomains:[]})}function no(e,n={}){if(e===void 0){let f=Qi({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")})}ma(e)||$("CSP_ORIGIN_INVALID");let t=Reflect.ownKeys(e);t.some(f=>typeof f!="string")&&$("CSP_ORIGIN_INVALID"),t.some(f=>!la.has(f))&&$("CSP_AXIS_UNKNOWN");let i=Wn(e,"connectDomains"),o=Wn(e,"frameDomains"),r=Wn(e,"resourceDomains"),s=Wn(e,"baseUriDomains");(r.length>0||s.length>0)&&$("CSP_AXIS_UNSUPPORTED"),(_a(e)>ca||i.length>Xi||o.length>Xi||i.length+o.length>da||[...i,...o].some(f=>new TextEncoder().encode(f).byteLength>pa))&&$("CSP_LIMIT_EXCEEDED");let c=i.map(f=>Yi(f,"connectDomains")),d=o.map(f=>Yi(f,"frameDomains")),l=new Set((n.runtimeHostnames??[]).map(f=>f.toLowerCase().replace(/\.$/,"")));[...c,...d].some(f=>Da(f.hostname,l))&&$("CSP_ORIGIN_FORBIDDEN");let p={declared:true,connectDomains:Zi(c),frameDomains:Zi(d)},u=Qi(p);return Object.freeze({...p,resourceDomains:Object.freeze([]),baseUriDomains:Object.freeze([]),cspHash:createHash("sha256").update(u,"utf8").digest("hex")})}var ca,Xi,da,pa,la,ua,fa,ya,Aa,Ia,ga,zt,to=V(()=>{m();ca=4096,Xi=16,da=32,pa=512,la=new Set(["connectDomains","frameDomains","resourceDomains","baseUriDomains"]),ua=["localhost","local","internal","home.arpa","test","example","invalid","onion","lan","corp","home","intranet","private","localdomain"],fa=/^(https|wss):\/\/([^/?#]+)$/i,ya=/^\[[^\]]+\](?::[0-9]+)?$/,Aa=/^[^:\[\]]+(?::[0-9]+)?$/,Ia=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/,ga=[[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]],zt=class extends Error{constructor(t){super(t);this.code=t;}code;name="UiPluginCspNormalizationError"};});function mn(e,n){return n===void 0||n===""?e:e===""?n:n.startsWith("[")?`${e}${n}`:`${e}.${n}`}function y(e,n=e,t,i){throw new ce(e,n,t,i)}function J(e,n){try{return n()}catch(t){throw t instanceof ce?t.withPathPrefix(e):t}}function K(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 F(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function ec(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&&y("MANIFEST_INVALID","MANIFEST_INVALID",o,"unknown-key");let r=n.find(s=>!F(e,s));r!==void 0&&y("MANIFEST_INVALID","MANIFEST_INVALID",r,"missing-key");}function Yn(e,n=false,t=false,i=false){return Ma.test(e)||!i&&Ra.test(e)||La.test(e)||t&&io.test(e)||Oa.test(e)&&!(n&&/^\s*data:/i.test(e)&&!io.test(e))}function Xn(e,n=new Set,t=0,i=false,o=false,r=""){if(typeof e=="string"){Yn(e,i,o)&&y("UNSAFE_VALUE","UNSAFE_VALUE",r,"unsafe-value");return}if(!(e===null||typeof e!="object")){(t>8||n.has(e))&&y("MANIFEST_INVALID","MANIFEST_INVALID",r),n.add(e);try{if(Array.isArray(e)){e.forEach((s,a)=>Xn(s,n,t+1,!1,!1,mn(r,`[${a}]`)));return}K(e)||y("MANIFEST_INVALID","MANIFEST_INVALID",r);for(let[s,a]of Object.entries(e))Xn(a,n,t+1,i&&t===0&&(s==="name"||s==="description"),o,mn(r,s));}finally{n.delete(e);}}}function Pe(e,n){let t=e[n];return typeof t!="string"&&y("MANIFEST_INVALID"),t}function ge(e,n,t){let i=e[n];return (!Number.isSafeInteger(i)||i<t)&&y("MANIFEST_INVALID"),i}function $t(e){return Sa.test(e)||y("MANIFEST_INVALID"),e}function on(e){return ba.test(e)||y("TOKEN_INVALID"),e}function nc(e){return fo.test(e)||y("MANIFEST_INVALID"),e}function tc(e){K(e)||y("MANIFEST_INVALID");let n={};for(let[t,i]of Object.entries(e)){let o=nc(t);K(i)||y("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&&y("MANIFEST_INVALID"),n[o]={type:r,min:s,max:a,labelMaxLength:ge(i,"labelMaxLength",1),detailMaxLength:ge(i,"detailMaxLength",1)};continue}typeof r=="string"&&y("SCHEMA_TYPE_UNSUPPORTED"),y("MANIFEST_INVALID");}return n}function ic(e,n,t){let i=e[n];(!i||i.type!==t)&&y("MANIFEST_INVALID");}function Jn(e,n,t){let i=Pe(e,"field");return fo.test(i)||y("MANIFEST_INVALID"),ic(n,i,t),i}function oc(e,n){K(e)||y("MANIFEST_INVALID");let t=e.primitive;switch(typeof t!="string"&&y("MANIFEST_INVALID"),Qa.includes(t)||y("PRIMITIVE_UNKNOWN"),t){case "card-shell":return X(e,["primitive"]),{primitive:t};case "meta-banner":return X(e,["primitive","badgeToken","noticeToken"]),{primitive:t,badgeToken:on(Pe(e,"badgeToken")),noticeToken:on(Pe(e,"noticeToken"))};case "heading":return X(e,["primitive","field"]),{primitive:t,field:Jn(e,n,"text")};case "labeled-text":return X(e,["primitive","titleToken","field","variant"]),e.variant!=="callout"&&y("MANIFEST_INVALID"),{primitive:t,titleToken:on(Pe(e,"titleToken")),field:Jn(e,n,"text"),variant:"callout"};case "step-flow":return X(e,["primitive","titleToken","field"]),{primitive:t,titleToken:on(Pe(e,"titleToken")),field:Jn(e,n,"step-list")};case "text-list":{X(e,["primitive","titleToken","field"],["emptyToken","hideWhenEmpty"]);let i={primitive:t,titleToken:on(Pe(e,"titleToken")),field:Jn(e,n,"text-list")};return F(e,"emptyToken")&&(i.emptyToken=on(Pe(e,"emptyToken"))),F(e,"hideWhenEmpty")&&(typeof e.hideWhenEmpty!="boolean"&&y("MANIFEST_INVALID"),i.hideWhenEmpty=e.hideWhenEmpty),i}}return y("MANIFEST_INVALID")}function rc(e,n){return Array.isArray(e)||y("MANIFEST_INVALID"),e.map(t=>oc(t,n))}function Y(e="v2 manifest exceeds a contract limit",n,t){return y("LIMIT_EXCEEDED",e,n,t)}function Ie(e="initial state is not projection-safe"){return y("INITIAL_STATE_INVALID",e)}function oo(e,n){return (typeof e!="string"||e.length===0||e.length>4096||e.trim().length===0||Ya.test(e)||qa.test(e))&&y("MANIFEST_INVALID",`${n} is invalid`),(Yn(e,true,true)||wa.test(e)||Ca.test(e)||Ua.test(e))&&y("UNSAFE_VALUE",`${n} contains an unsafe value`),e}function Gt(e,n){return (typeof e!="string"||!Te.test(e))&&y("MANIFEST_INVALID",`${n} is invalid`),e}function sc(e){return (typeof e!="string"||!Rt.test(e)||e==="*"||e==="all")&&y("MANIFEST_INVALID","action capability is invalid"),e}function yo(e){return (typeof e!="string"||!Xa.test(e))&&y("MANIFEST_INVALID","resource hash is invalid"),e}function Wt(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)||y("MANIFEST_INVALID","v2 manifest contains a non-finite number",i,"non-finite-number");return}(e===void 0||typeof e=="function"||typeof e=="bigint")&&y("MANIFEST_INVALID","v2 manifest contains a non-JSON value",i,"non-json-value"),typeof e!="object"&&y("MANIFEST_INVALID","MANIFEST_INVALID",i),t>8&&Y("v2 manifest nesting is too deep",i,"too-deep"),n.has(e)&&y("MANIFEST_INVALID","v2 manifest contains a cycle",i,"cycle"),n.add(e);try{if(Array.isArray(e)){e.length>128&&Y("v2 manifest array is too long",i,"array-too-long"),e.forEach((o,r)=>Wt(o,n,t+1,mn(i,`[${r}]`)));return}K(e)||y("MANIFEST_INVALID","v2 manifest contains a non-plain object",i,"non-plain-object");for(let[o,r]of Object.entries(e))Wt(r,n,t+1,mn(i,o));}finally{n.delete(e);}}}function Ao(e){return (typeof e!="string"||e.length>4096||!In.test(e))&&(typeof e=="string"&&e.length>4096&&Y("projection path is too long"),y("MANIFEST_INVALID","projection paths must be canonical exact paths")),e.split(".").some(t=>tn(t))&&y("MANIFEST_INVALID","projection paths cannot address reserved state keys"),e}function Jt(e){K(e)||y("MANIFEST_INVALID","projection policy must be an object"),X(e,["allow"]),Array.isArray(e.allow)||y("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=Ao(i);t.has(o)&&y("MANIFEST_INVALID","projection allowlist contains a duplicate path"),t.add(o),n.push(o);}return {allow:n}}function ac(e,n){if(e===void 0)return;Array.isArray(e)||y("MANIFEST_INVALID","dataPaths must be an array"),e.length>Za&&Y("dataPaths exceed the v2 limit");let t=[],i=new Set;for(let o of e){let r=Ao(o);i.has(r)&&y("MANIFEST_INVALID","dataPaths contain a duplicate path"),n.some(s=>en(r,s))||y("MANIFEST_INVALID","dataPaths must be projection-allowed"),i.add(r),t.push(r);}return t}function rn(e,n,t=Number.MAX_SAFE_INTEGER){return (!Number.isSafeInteger(e)||e<0||e>t)&&y("MANIFEST_INVALID",`${n} is invalid`),e}function ro(e,n){return (typeof e!="number"||!Number.isFinite(e))&&y("MANIFEST_INVALID",`${n} is invalid`),e}function Kt(e,n=0,t=new Set){if(typeof e=="string")return (e.length>4096||Yn(e))&&y("UNSAFE_VALUE","schema enum contains an unsafe string"),e;if(e===null||typeof e=="boolean")return e;if(typeof e=="number")return Number.isFinite(e)||y("MANIFEST_INVALID","schema enum contains a non-finite number"),e;(n>8||typeof e!="object"||e===void 0)&&Y("schema enum is too deep"),t.has(e)&&y("MANIFEST_INVALID","schema enum contains a cycle"),t.add(e);try{if(Array.isArray(e))return e.length>128&&Y("schema enum array is too long"),e.map(o=>Kt(o,n+1,t));K(e)||y("MANIFEST_INVALID","schema enum contains a non-plain object");let i={};for(let[o,r]of Object.entries(e))tn(o)&&y("MANIFEST_INVALID","schema enum contains a reserved key"),i[o]=Kt(r,n+1,t);return i}finally{t.delete(e);}}function cc(e,n){if(e===void 0)return;Array.isArray(e)||y("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"||!In.test(o))&&y("MANIFEST_INVALID","schema required contains an invalid key"),o.length>4096&&Y("schema required key is too long"),i.has(o)&&y("MANIFEST_INVALID","schema required contains a duplicate key"),n&&!Object.prototype.hasOwnProperty.call(n,o)&&y("MANIFEST_INVALID","schema required references an undeclared property"),i.add(o),t.push(o);return t}function dc(e,n){let t=n?In:Bn;return e.length>4096&&Y("schema property name is too long"),(!t.test(e)||e.split(".").some(i=>tn(i)))&&y("MANIFEST_INVALID","schema property name is invalid"),e}function Xt(e,n=0,t=false){K(e)||y("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"&&y("SCHEMA_TYPE_UNSUPPORTED","action inputSchema type is unsupported"),y("MANIFEST_INVALID","action inputSchema type is required"));let o=["type","enum"];i==="string"&&o.push("minLength","maxLength"),i==="array"&&o.push("minItems","maxItems","items"),i==="object"&&o.push("minProperties","maxProperties","properties","required","additionalProperties"),(i==="number"||i==="integer")&&o.push("minimum","maximum"),X(e,["type"],o.filter(a=>a!=="type"));let r={type:i};if(F(e,"enum")&&(Array.isArray(e.enum)||y("MANIFEST_INVALID","schema enum must be an array"),e.enum.length>128&&Y("schema enum is too long"),r.enum=e.enum.map(a=>Kt(a))),i==="string"&&(F(e,"minLength")&&(r.minLength=rn(e.minLength,"schema minLength",4096)),F(e,"maxLength")&&(r.maxLength=rn(e.maxLength,"schema maxLength",4096)),r.minLength!==void 0&&r.maxLength!==void 0&&r.minLength>r.maxLength&&y("MANIFEST_INVALID","schema string length bounds are inverted")),(i==="number"||i==="integer")&&(F(e,"minimum")&&(r.minimum=ro(e.minimum,"schema minimum")),F(e,"maximum")&&(r.maximum=ro(e.maximum,"schema maximum")),r.minimum!==void 0&&r.maximum!==void 0&&r.minimum>r.maximum&&y("MANIFEST_INVALID","schema numeric bounds are inverted")),i==="array"&&(F(e,"minItems")&&(r.minItems=rn(e.minItems,"schema minItems",128)),F(e,"maxItems")&&(r.maxItems=rn(e.maxItems,"schema maxItems",128)),r.minItems!==void 0&&r.maxItems!==void 0&&r.minItems>r.maxItems&&y("MANIFEST_INVALID","schema array length bounds are inverted"),F(e,"items")&&(r.items=Xt(e.items,n+1,false))),i==="object"){let a;if(F(e,"properties")){K(e.properties)||y("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=dc(l,t);a[u]=Xt(p,n+1,false);}r.properties=a;}F(e,"minProperties")&&(r.minProperties=rn(e.minProperties,"schema minProperties",64)),F(e,"maxProperties")&&(r.maxProperties=rn(e.maxProperties,"schema maxProperties",64)),r.minProperties!==void 0&&r.maxProperties!==void 0&&r.minProperties>r.maxProperties&&y("MANIFEST_INVALID","schema object property bounds are inverted");let c=cc(e.required,a);c!==void 0&&(r.required=c),F(e,"additionalProperties")&&(e.additionalProperties!==false&&y("MANIFEST_INVALID","schema additionalProperties must be false"),r.additionalProperties=false);}let s=JSON.stringify(r);return (s===void 0||Buffer.byteLength(s,"utf8")>2097152)&&Y("action inputSchema subtree is too large"),r}function pc(e){let n=Xt(e,0,true);return (n.type!=="object"||!n.properties)&&y("MANIFEST_INVALID","action inputSchema must declare object properties"),n}function lc(e){if(K(e)||y("MANIFEST_INVALID","action backend must be an object"),e.type==="core"){X(e,za);let n=e.handler;return (typeof n!="string"||!Ot.test(n))&&y("MANIFEST_INVALID","core backend handler is invalid"),{type:"core",handler:n}}if(e.type==="skill"&&F(e,"entry"))return X(e,Wa),e.entry!==Ge&&y("MANIFEST_INVALID",`skill backend entry must be ${Ge}`),{type:"skill",entry:Ge};if(e.type==="skill"){X(e,$a,Ga),(!Array.isArray(e.command)||e.command.length===0||e.command.length>16)&&y("MANIFEST_INVALID","skill backend command is invalid");let n=[];for(let i of e.command)(typeof i!="string"||i.length===0||i.length>256||!wt.test(i))&&y("MANIFEST_INVALID","skill backend command token is invalid"),n.push(i);let t=F(e,"env")?yc(e.env):void 0;return {type:"skill",command:n,...t===void 0?{}:{env:t}}}y("MANIFEST_INVALID","action backend type is unsupported");}function uc(e){K(e)||y("MANIFEST_INVALID","action must be an object"),X(e,Fa,ja),F(e,"_meta")&&J("_meta",()=>Io(e._meta));let n=J("actionId",()=>Gt(e.actionId,"actionId"));St(n)&&y("MANIFEST_INVALID",`actionId "${n}" is not projection-safe`,"actionId");let t=J("capability",()=>sc(e.capability)),i=e.mutation;typeof i!="boolean"&&y("MANIFEST_INVALID","action mutation must be boolean","mutation");let o=J("inputSchema",()=>pc(e.inputSchema)),r;if(F(e,"dataInputs")){Array.isArray(e.dataInputs)||y("MANIFEST_INVALID","action dataInputs must be an array","dataInputs");let p=o.properties,u=new Set,f=[];for(let g of e.dataInputs)(typeof g!="string"||!F(p,g)||u.has(g))&&y("MANIFEST_INVALID","action dataInputs must be unique declared properties","dataInputs"),u.add(g),f.push(g);r=f;}let s=J("resultProjection",()=>Jt(e.resultProjection)),a=J("backend",()=>lc(e.backend)),c;F(e,"content")&&((a.type!=="skill"||!Hn(e.content))&&y("MANIFEST_INVALID","action content declaration is invalid","content"),c=Ac(e.content));let d;if(F(e,"confirmation")){let p=e.confirmation;p!=="none"&&p!=="native"&&y("MANIFEST_INVALID","action confirmation is invalid","confirmation"),d=p;}let l;return F(e,"schedule")&&(l=J("schedule",()=>fc(e.schedule,{backend:a,inputSchema:o,hasContent:c!==void 0,hasDataInputs:r!==void 0,confirmation:d}))),{actionId:n,capability:t,mutation:i,inputSchema:o,resultProjection:s,backend:a,...c===void 0?{}:{content:c},...r===void 0?{}:{dataInputs:r},...d===void 0?{}:{confirmation:d},...l===void 0?{}:{schedule:l}}}function fc(e,n){(n.backend.type!=="skill"||!("entry"in n.backend)||n.backend.entry!==Ge)&&y("MANIFEST_INVALID","schedule needs a tool-mode action","schedule"),(n.hasContent||n.hasDataInputs||n.confirmation!==void 0&&n.confirmation!=="none")&&y("MANIFEST_INVALID","a scheduled action takes no content, dataInputs or native confirmation","schedule"),(n.inputSchema.required??[]).length>0&&y("MANIFEST_INVALID","a scheduled action input must accept {}","inputSchema.required"),K(e)||y("MANIFEST_INVALID","schedule must be an object","schedule"),X(e,Va,Ba),$n(e.everyMinutes)||y("MANIFEST_INVALID","schedule everyMinutes is invalid","schedule.everyMinutes");let t=F(e,"timeoutMs")?e.timeoutMs:zn.default;return Gn(t)||y("MANIFEST_INVALID","schedule timeoutMs is invalid","schedule.timeoutMs"),{everyMinutes:e.everyMinutes,timeoutMs:t}}function yc(e){return Wi(e)||y("MANIFEST_INVALID","skill backend env is invalid"),Object.freeze([...e])}function Ac(e){return Object.freeze({...e.in===void 0?{}:{in:Object.freeze({...e.in})},...e.out===void 0?{}:{out:Object.freeze({...e.out})}})}function Ic(e){return K(e)||y("INITIAL_STATE_INVALID","initialState must be an object"),X(e,Ja,Ka),e.path!=="ui/state.json"&&y("MANIFEST_INVALID","initialState path is not fixed"),F(e,"hash")?{path:"ui/state.json",hash:yo(e.hash)}:{path:"ui/state.json"}}function gc(e){let n=["wasm","terminal","htmlDocuments"];return (!K(e)||Object.keys(e).length===0||Object.keys(e).some(t=>!n.includes(t)||e[t]!==true))&&y("MANIFEST_INVALID","runtime must contain only known capability flags set to true"),{...e.wasm===true?{wasm:true}:{},...e.terminal===true?{terminal:true}:{},...e.htmlDocuments===true?{htmlDocuments:true}:{}}}function mc(e,n){let t;try{t=no(e);}catch(i){let o=i!==null&&typeof i=="object"&&"code"in i&&typeof i.code=="string"?i.code:"CSP_ORIGIN_INVALID";return y("MANIFEST_INVALID",o,void 0,o.toLowerCase().replace(/_/g,"-"))}if(t.frameDomains.length>0&&y("MANIFEST_INVALID","external origins in csp are not enabled in this rollout",void 0,"csp-not-enabled"),t.connectDomains.length!==0)return n?.terminal===true&&y("MANIFEST_INVALID","runtime.terminal cannot be combined with csp.connectDomains","connectDomains","terminal-with-connect-domains"),Object.freeze({connectDomains:t.connectDomains})}function hc(e,n){Xn(K(e)&&F(e,"csp")?ec(e,"csp"):e,new Set,0,true,true),Wt(e),K(e)||y("MANIFEST_INVALID"),X(e,xa,va),F(e,"_meta")&&J("_meta",()=>Io(e._meta)),e.manifestVersion!==2&&y("MANIFEST_INVALID");let t;F(e,"runtime")&&(t=J("runtime",()=>gc(e.runtime)));let i;F(e,"csp")&&(i=J("csp",()=>mc(e.csp,t)));let o=J("pluginId",()=>Gt(e.pluginId,"pluginId")),r=J("definitionId",()=>Gt(e.definitionId,"definitionId")),s=J("version",()=>ge(e,"version",1)),a=J("name",()=>oo(e.name,"name")),c=J("description",()=>oo(e.description,"description")),d;F(e,"icon")&&((typeof e.icon!="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(e.icon))&&y("MANIFEST_INVALID","icon is invalid","icon"),d=e.icon);let l;F(e,"tone")&&((typeof e.tone!="string"||!Ct.includes(e.tone))&&y("MANIFEST_INVALID","tone is invalid","tone"),l=e.tone),e.entry!=="ui/index.html"&&y("MANIFEST_INVALID","entry path is not fixed","entry","fixed-value");let p;F(e,"entryHash")&&(p=J("entryHash",()=>yo(e.entryHash)));let u;F(e,"initialState")&&(u=J("initialState",()=>Ic(e.initialState)));let f;F(e,"usage")&&(e.usage!=="card"&&e.usage!=="window"&&y("MANIFEST_INVALID","usage is invalid","usage"),f=e.usage);let g;F(e,"detailPanel")&&(typeof e.detailPanel!="boolean"&&y("MANIFEST_INVALID","detailPanel is invalid","detailPanel"),g=e.detailPanel);let _;if(F(e,"displayModes")){((f??xe)!==xe||!Array.isArray(e.displayModes)||e.displayModes.length===0)&&y("MANIFEST_INVALID","displayModes are only valid for window Apps","displayModes");let A=new Set(["inline","floating","focused"]);(new Set(e.displayModes).size!==e.displayModes.length||e.displayModes.some(h=>typeof h!="string"||!A.has(h)))&&y("MANIFEST_INVALID","displayModes are invalid","displayModes"),_=e.displayModes;}(f??xe)===xe&&g!==void 0&&y("MANIFEST_INVALID","detailPanel is card-only","detailPanel");let P=n.mode??"local";P!=="local"&&P!=="installed"&&P!=="published"&&y("MANIFEST_INVALID","manifest mode is invalid"),P!=="local"&&p===void 0&&y("MANIFEST_INVALID","installed manifests require entryHash","entryHash","required-when-installed"),P!=="local"&&u!==void 0&&u.hash===void 0&&y("MANIFEST_INVALID","installed manifests require initialState.hash","initialState.hash","required-when-installed"),(!Array.isArray(e.surfaces)||e.surfaces.length===0)&&y("MANIFEST_INVALID","surfaces are invalid","surfaces"),e.surfaces.length>2&&Y("surfaces exceed the v2 limit","surfaces","too-many-items");let U=[],k=new Set;for(let A of e.surfaces)(typeof A!="string"||!Ut.includes(A))&&y("MANIFEST_INVALID","surface is unsupported","surfaces"),k.has(A)&&y("MANIFEST_INVALID","surfaces contain a duplicate","surfaces","duplicate-item"),k.add(A),U.push(A);K(e.size)||y("MANIFEST_INVALID","size must be an object","size"),J("size",()=>X(e.size,["height"]));let D=J("size",()=>ge(e.size,"height",1));D>720&&Y("size.height exceeds the v2 limit","size.height","too-large");let w=J("stateProjection",()=>Jt(e.stateProjection)),B=e.summaryProjection===void 0?void 0:J("summaryProjection",()=>Jt(e.summaryProjection));B!==void 0&&B.allow.some(A=>!w.allow.includes(A))&&y("MANIFEST_INVALID","summaryProjection must be a subset of stateProjection.allow","summaryProjection");let N=J("dataPaths",()=>ac(e.dataPaths,w.allow));Array.isArray(e.actions)||y("MANIFEST_INVALID","actions must be an array","actions"),e.actions.length>32&&Y("actions exceed the v2 limit","actions","too-many-items");let b=[],L=new Set,I=0;for(let[A,h]of e.actions.entries()){let E=`actions[${A}]`,C=J(E,()=>uc(h));if(L.has(C.actionId)&&y("MANIFEST_INVALID","actions contain a duplicate actionId",`${E}.actionId`,"duplicate-item"),C.schedule!==void 0&&(I+=1,I>Gi&&y("MANIFEST_INVALID","an App declares at most one scheduled action",`${E}.schedule`,"duplicate-item")),C.backend.type==="core"&&C.backend.handler==="state.set"){C.mutation||y("MANIFEST_INVALID","state.set actions must be mutations",`${E}.mutation`);for(let x of Object.keys(C.inputSchema.properties))w.allow.includes(x)||y("MANIFEST_INVALID","state.set input paths must be projection-allowed",`${E}.inputSchema.properties`);}L.add(C.actionId),b.push(C);}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:D},stateProjection:w,...B===void 0?{}:{summaryProjection:B},...N===void 0?{}:{dataPaths:N},actions:b}}function Io(e){K(e)||y("MANIFEST_INVALID","_meta must be an object");let n=JSON.stringify(e);(n===void 0||Buffer.byteLength(n,"utf8")>Ha)&&Y("_meta exceeds the 4 KiB limit",void 0,"meta-too-large");}function _c(e){let n={},t={};for(let r of e.actions){n[r.actionId]={capabilities:[r.capability],inputKeys:Object.keys(r.inputSchema.properties??{}),...r.dataInputs===void 0?{}:{dataInputs:r.dataInputs},resultProjection:r.resultProjection,...r.confirmation===void 0?{}:{confirmation:r.confirmation},...r.content===void 0?{}:{content:r.content},...r.schedule===void 0?{}:{schedule:r.schedule},...r.backend.type!=="skill"||r.backend.env===void 0?{}:{env:r.backend.env}};let s=r.backend.type==="skill"||r.backend.type==="core"&&r.backend.handler==="state.set";t[r.actionId]={actionId:r.actionId,mutation:r.mutation,backend:r.backend,launchPolicy:s?"allowed":"denied",...s?{}:{denialCode:"EXEC_DENIED"}};}let i={id:e.definitionId,version:e.version,renderer:"sandbox-html",...e.usage===void 0?{}:{usage:e.usage},...e.detailPanel===void 0?{}:{detailPanel:e.detailPanel},...e.displayModes===void 0?{}:{displayModes:e.displayModes},surfaces:e.surfaces,stateProjection:e.stateProjection,...e.summaryProjection===void 0?{}:{summaryProjection:e.summaryProjection},...e.dataPaths===void 0?{}:{dataPaths:e.dataPaths},actions:n},o={entry:{path:"ui/index.html",...e.entryHash===void 0?{}:{hash:e.entryHash}},...e.initialState===void 0?{}:{initialState:e.initialState}};return {manifest:e,definition:i,handlers:t,resources:o}}function Yt(e,n,t,i,o,r){if(typeof e=="string"){let s=o.length>0&&r.some(a=>en(o.join("."),a));return (e.length>4096||Yn(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=>Yt(c,n,t+1,2097152,o,r));else {K(e)||Ie("state contains a non-plain object");let c={};for(let[d,l]of Object.entries(e))(d.length>4096||!Bn.test(d)||tn(d))&&(d.length>4096&&Ie("state key is too long"),Ie("state contains a reserved or invalid key")),c[d]=Yt(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=[]){K(e)||Ie("initial state must be a JSON object");let t=Yt(e,new Set,0,2097152,[],n);return (t===null||Array.isArray(t)||typeof t!="object")&&Ie(),t}function Ec(e,n={}){Xn(e),K(e)||y("MANIFEST_INVALID"),X(e,ka),e.manifestVersion!==1&&y("MANIFEST_INVALID");let t=$t(Pe(e,"pluginId")),i=$t(Pe(e,"definitionId")),o=ge(e,"version",1),r=ge(e,"primitiveSet",1),s=n.supportedPrimitiveSet??Na;(!Number.isSafeInteger(s)||s<1)&&y("MANIFEST_INVALID"),r>s&&y("PRIMITIVE_SET_UNSUPPORTED"),K(e.activation)||y("MANIFEST_INVALID"),X(e.activation,["kind","language"]),e.activation.kind!=="fenced-code"&&y("MANIFEST_INVALID");let a=$t(Pe(e.activation,"language")),c=tc(e.schema),d=rc(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 Tc(e,n={}){return K(e)||y("MANIFEST_INVALID"),Object.hasOwn(e,"lineage")&&y("MANIFEST_INVALID","lineage is only allowed in product bundle indexes"),e.manifestVersion===2?hc(e,n):Ec(e,n)}function Je(e,n={}){try{return Tc(e,n)}catch(t){if(t instanceof ce)throw t;return y("MANIFEST_INVALID")}}function hn(e,n={}){let t=Je(e,n);return t.manifestVersion===2?_c(t):t}var Na,ba,Sa,fo,Ma,La,Ra,Oa,io,wa,Ca,Ua,ka,xa,va,Fa,ja,Va,Ba,Ha,za,$a,Ga,Wa,Ja,Ka,Xa,Ya,qa,Za,Qa,ce,Qt=V(()=>{m();Ht();Me();vt();Ji();Bt();Ft();to();ze();Na=1,ba=/^[a-z][a-zA-Z0-9]*(\.[a-zA-Z0-9]+)+$/,Sa=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,fo=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,Ma=/<\/?[A-Za-z][^>]*>/,La=/^(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)/,Ra=/^(?:https?|file|ftp|ws|wss):\/\//i,Oa=/^\s*(?:javascript|data):/i,io=/data:[^,\s]*,/i,wa=/(?:https?|file|ftp|ws|wss):\/\//i,Ca=/javascript:/i,Ua=/(?:^[\s]*|[\s"'(=])(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)(?=[^\s"'<>])[^\s"'<>]*/,ka=["manifestVersion","pluginId","definitionId","version","primitiveSet","activation","schema","layout"],xa=["manifestVersion","pluginId","definitionId","version","name","description","entry","surfaces","size","stateProjection","actions"],va=["_meta","icon","tone","entryHash","runtime","csp","initialState","usage","detailPanel","displayModes","summaryProjection","dataPaths","focusedAiDataPaths"],Fa=["actionId","capability","mutation","inputSchema","resultProjection","backend"],ja=["confirmation","dataInputs","content","schedule","_meta"],Va=["everyMinutes"],Ba=["timeoutMs"],Ha=4*1024,za=["type","handler"],$a=["type","command"],Ga=["env"],Wa=["type","entry"],Ja=["path"],Ka=["hash"],Xa=/^[0-9a-f]{64}$/,Ya=/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/,qa=/[\r\n]/,Za=16,Qa=["card-shell","meta-banner","heading","labeled-text","step-flow","text-list"],ce=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,mn(t,this.path),this.rule)}};});function To(e){return typeof e=="string"&&e.length<=Dc&&Pc.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 oe(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 Mc(e){return e.toLowerCase().replace(/_/g,"-")}function Lc(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 Po(e,n,t){return {path:t(e.path),rule:e.rule??Mc(e.code),...e.message!==e.code?{message:e.message}:{},file:n}}function Do(e){return JSON.parse(JSON.stringify(e))}function ti(e,n,t=0,i=new Set){if(typeof e=="string"){e.length>4096&&j("LIMIT_EXCEEDED",n,"string-too-long"),(Nc.test(e)||bc.test(e)||Sc.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)=>ti(o,`${n}[${r}]`,t+1,i));return}oe(e)||j("MANIFEST_INVALID",n,"non-plain-object");for(let[o,r]of Object.entries(e))ti(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 an(e,n){return oe(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 Oc(e,n){typeof e!="boolean"&&j("MANIFEST_INVALID",n,"boolean");}function _n(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 wc(e,n){if(e!=="icon")switch(ti(n,e),e){case "long_description":case "homepage":case "documentation":case "support":case "license":me(n,e);return;case "author":{let t=an(n,e);_n(t,e,["name"],["email","url"]);for(let i of Object.keys(t))me(t[i],`${e}.${i}`);return}case "repository":{let t=an(n,e);_n(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=an(t,o);_n(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=an(t,o);_n(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=an(t,o);_n(r,o,["name","text"],["description","arguments"]),me(r.name,`${o}.name`),me(r.text,`${o}.text`);});return}case "tools_generated":case "prompts_generated":Oc(n,e);return;case "localization":case "compatibility":case "user_config":an(n,e);return;default:j("MANIFEST_INVALID",e,"unknown-key");}}function qn(e){return typeof e=="string"&&Te.test(e)?e:void 0}function No(e){return Number.isSafeInteger(e)&&e>=1?e:void 0}function Cc(e){let n=qn(e.name);if(n===void 0)return;let t=e._meta,i=oe(t)?t[ve]:void 0,o=oe(i)?i:{},r=q(o,"definitionId")?qn(o.definitionId):n,s=q(o,"definitionVersion")?No(o.definitionVersion):1;return {pluginId:n,...r===void 0?{}:{definitionId:r},...s===void 0?{}:{definitionVersion:s}}}function Uc(e){let n=qn(e.pluginId);if(n===void 0)return;let t=qn(e.definitionId),i=No(e.version);return {pluginId:n,...t===void 0?{}:{definitionId:t},...i===void 0?{}:{definitionVersion:i}}}function ri(e){try{let n=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e));if(!oe(n))return !1;let t=n._meta;return oe(t)&&q(t,ve)}catch{return false}}function kc(e,n){if(e===pe)return n.builtinOnly===true;let t=n._meta,i=oe(t)?t[ve]:void 0;return oe(i)&&i.builtinOnly===true}function xc(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))ii.includes(a)||j("MANIFEST_INVALID",a,"unknown-key");for(let a of oi)q(e,a)||j("MANIFEST_INVALID",a,"missing-key");e.manifest_version!==ei&&j("MANIFEST_INVALID","manifest_version","unsupported-version",`manifest_version must be "${ei}"`),To(e.version)||j("MANIFEST_INVALID","version","semver","version must be a semver.org version such as 0.1.0");let t=e._meta;oe(t)||j("MANIFEST_INVALID","_meta","object"),q(t,ve)||j("MANIFEST_INVALID",he(),"missing-key");let i=t[ve];oe(i)||j("MANIFEST_INVALID",he(),"object");for(let a of Object.keys(i))ni.includes(a)||Eo.includes(a)||j("MANIFEST_INVALID",he(a),"unknown-key");for(let a of ni)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 ${G} and ${z}; a server.ts App keeps them in the tools file only`),vc(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 _o)q(e,a)&&(wc(a,e[a]),o[a]=Do(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:Ge}}))),Object.keys(r).length>0&&(s._meta=r),{v2Input:s,...Object.keys(r).length>0?{vendorMeta:r}:{},passthrough:o}}function vc(e){Array.isArray(e)&&e.forEach((n,t)=>{let i=oe(n)?n.backend:void 0;oe(i)&&q(i,"entry")&&j("MANIFEST_INVALID",he(`actions[${t}].backend.entry`),"entry-not-authorable",`an action in ${G} cannot name an entry; a server.ts App declares its actions in ${z}`);});}function Fc(e,n,t){oe(e)||j("MANIFEST_INVALID","","not-object","manifest.json must be a JSON object",G);let i;try{i=xc(e,t);}catch(s){throw s instanceof Ne?new Ne(s.code,{...s.reason,file:G}):s}let o;try{let s=Je(i.v2Input,{mode:n.mode??"local"});s.manifestVersion!==2&&j("MANIFEST_INVALID","","v2-required"),o=s;}catch(s){throw s instanceof ce?new Ne(s.code,Po(s,G,Lc)):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:G})});}return {file:G,manifest:o,v2Input:i.v2Input,releaseVersion:e.version,...Object.keys(i.passthrough).length>0?{mcpb:i.passthrough}:{}}}function jc(e,n){try{let t=Je(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:pe});return {file:pe,manifest:t,v2Input:e}}catch(t){throw t instanceof ce?new Ne(t.code,Po(t,pe,i=>i??"")):t}}function cn(e){return le(hn(e).definition)}function mo(e){let{entryHash:n,initialState:t,...i}=e,o={...i};return t!==void 0&&(o.initialState={path:t.path}),Do(o)}function Vc(e,n){let t=mo(e),i=mo(n);return [...new Set([...Object.keys(t),...Object.keys(i)])].sort().filter(r=>ie(t[r]??null)!==ie(i[r]??null))}function Bc(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 Hc(e,n){let t=Vc(e,n),i=Bc(e,n),o="";try{let r=cn(e),s=cn(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",`${G} and ${pe} 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:z},files:[]}}function ho(e){return {...De("","tools-needs-manifest-json","MANIFEST_INVALID",`${z} is read with ${G} only`),files:e}}function zc(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(!oe(t))return {failure:De("","not-object","MANIFEST_INVALID",`${z} 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(!oe(r))return {failure:De(`actions[${o}]`,"object")};if(q(r,"backend"))return {failure:De(`actions[${o}].backend`,"tools-backend","MANIFEST_INVALID",`an action in ${z} cannot carry a backend`)}}return {actions:i}}function $c(e,n){let t=n.maxBytes??262144,i=[],o=new TextDecoder("utf-8",{fatal:true});for(let r of Q){let s=e[r];if(s===void 0)continue;if(s.byteLength>t)return {parsed:i,failure:{code:"LIMIT_EXCEEDED",reason:{path:"",rule:"file-too-large",file:r},files:[r]}};let a;try{a=JSON.parse(o.decode(s));}catch{return {parsed:i,failure:{code:"MANIFEST_INVALID",reason:{path:"",rule:"invalid-json",file:r},files:[r]}}}if(!oe(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 je(e,n={}){let{parsed:t,failure:i}=$c(e,n),o=Q.filter(f=>e[f]!==void 0);if(i!==void 0)return {ok:false,rejection:i,parseFailure:true,builtinOnly:false};let r=e[z],s=r===void 0?void 0:zc(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:[]}:ho(o),parseFailure:true,builtinOnly:false};let a=t[0],c=a.file===G?Cc(a.raw):Uc(a.raw),d=t.some(f=>kc(f.file,f.raw)),l;if(s!==void 0){let f=t.some(g=>g.file===G)?s.failure:ho(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===G?Fc(f.raw,n,l):jc(f.raw,n));p.length===2&&Hc(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"?[...Q]:f.reason.file===void 0||f.reason.file===z?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 G,pe,Q,ei,ve,ii,oi,_o,ni,Eo,Pc,Dc,Nc,bc,Sc,Ne,Zn=V(()=>{m();$e();Me();Bt();ze();Qt();G="manifest.json",pe="ui-plugin.json",Q=[G,pe],ei="0.3",ve="dev.crewx",ii=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"]),oi=Object.freeze(["manifest_version","name","display_name","version","description","_meta"]),_o=Object.freeze(ii.filter(e=>e!=="server"&&!oi.includes(e))),ni=Object.freeze(["entry","surfaces","size","stateProjection","actions"]),Eo=Object.freeze(["definitionId","definitionVersion","icon","tone","entryHash","runtime","initialState","usage","detailPanel","displayModes","summaryProjection","dataPaths","focusedAiDataPaths","csp"]),Pc=/^(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-]+)*))?$/,Dc=256,Nc=/<\/?[A-Za-z][^>]*>/,bc=/^\s*javascript:/i,Sc=/data:[^,\s]*,/i;Ne=class extends Error{constructor(t,i){super(`${t}: ${i.path||"<file>"} (${i.rule})`);this.code=t;this.reason=i;}code;reason};});function wo(e){if(e===void 0)return {kind:"none"};if(typeof e!="string")return {kind:"invalid",reason:"bad-path"};if(Jc.test(e))return {kind:"url",declared:e};if(!Yc(e))return {kind:"invalid",reason:"bad-path",declared:e};let n=e.lastIndexOf("."),t=n<0?void 0:Gc.get(e.slice(n+1).toLowerCase());return t===void 0?{kind:"invalid",reason:"bad-type",declared:e}:{kind:"file",path:e,contentType:t}}function Yc(e){return e.length===0||e.length>512||e.startsWith("/")||e.includes("\\")||e.includes("\0")?false:e.split("/").every(n=>n!==""&&n!=="."&&n!=="..")}async function En(e,n){let t=wo(e);if(t.kind==="none")return {diagnostics:[]};if(t.kind==="url")return {diagnostics:[{code:"ICON_NOT_FILE",severity:"warning",declared:t.declared}]};if(t.kind==="invalid")return {diagnostics:[si(t.reason,t.declared)]};let i=await n(t.path);if(typeof i=="string")return {diagnostics:[si(i,t.path)]};let o=Co(t.contentType,i);if(!o.ok)return {diagnostics:[si(o.reason,t.path)]};let r={path:t.path,contentType:t.contentType,byteLength:i.byteLength,bytes:i},s=o.square===false?[{code:"ICON_NOT_SQUARE",severity:"warning",declared:t.path}]:[];return {file:r,diagnostics:s}}function si(e,n){return {code:"ICON_INVALID",severity:"error",reason:e,...n===void 0?{}:{declared:n}}}function Co(e,n){if(n.byteLength>262144)return {ok:false,reason:"too-large"};if(e==="image/png")return !Lo(n,Kc)||sd(n,12,16)!=="IHDR"||n.byteLength<24?{ok:false,reason:"bytes-mismatch"}:{ok:true,square:Mo(Ro(n,16),Ro(n,20))};if(e==="image/jpeg"){if(!Lo(n,Xc))return {ok:false,reason:"bytes-mismatch"};let t=od(n);return {ok:true,square:t===void 0?void 0:Mo(t.width,t.height)}}return qc(n)}function qc(e){let n;try{n=Wc.decode(e);}catch{return {ok:false,reason:"bytes-mismatch"}}return td(n)?{ok:false,reason:"unsafe-svg"}:Zc.test(n)?{ok:true,square:id(n)}:{ok:false,reason:"bytes-mismatch"}}function td(e){if(Qc.some(n=>n.test(e)))return true;for(let n of e.matchAll(ed))if(!(n[1]??n[2]??n[3]??"").startsWith("#"))return true;for(let n of e.matchAll(nd))if(bo.lastIndex=n.index??0,!bo.test(e))return true;return false}function id(e){let n=/<svg\b[^>]*>/i.exec(e)?.[0];if(n===void 0)return;let t=Uo(n,"viewBox");if(t!==void 0){let r=t.trim().split(/[\s,]+/).map(Number);return r.length===4&&r.every(Number.isFinite)?r[2]===r[3]:void 0}let i=So(n,"width"),o=So(n,"height");return i===void 0||o===void 0?void 0:i===o}function Uo(e,n){let t=new RegExp(`\\s${n}\\s*=\\s*(?:"([^"]*)"|'([^']*)')`).exec(e);return t?.[1]??t?.[2]}function So(e,n){let t=Uo(e,n),i=t===void 0?null:/^\s*(\d+(?:\.\d+)?)(?:px)?\s*$/.exec(t);return i===null?void 0:Number(i[1])}function od(e){let n=2;for(;n+4<=e.byteLength;){if(e[n]!==255)return;let t=e[n+1];if(t===255){n+=1;continue}if(t===216||t===1||t>=208&&t<=215){n+=2;continue}if(t===217)return;let i=e[n+2]<<8|e[n+3];if(i<2)return;if(rd(t))return n+9>e.byteLength?void 0:{height:Oo(e,n+5),width:Oo(e,n+7)};n+=2+i;}}function rd(e){return e>=192&&e<=207&&e!==196&&e!==200&&e!==204}function Mo(e,n){if(!(e<=0||n<=0))return e===n}function Lo(e,n){return e.byteLength>=n.length&&n.every((t,i)=>e[i]===t)}function sd(e,n,t){return String.fromCharCode(...e.subarray(n,t))}function Ro(e,n){return (e[n]<<24|e[n+1]<<16|e[n+2]<<8|e[n+3])>>>0}function Oo(e,n){return e[n]<<8|e[n+1]}var Gc,Wc,Jc,Kc,Xc,Zc,Qc,ed,nd,bo,ai=V(()=>{m();Gc=new Map([["svg","image/svg+xml"],["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"]]),Wc=new TextDecoder("utf-8",{fatal:true}),Jc=/^[A-Za-z][A-Za-z0-9+.-]*:/,Kc=[137,80,78,71,13,10,26,10],Xc=[255,216,255];Zc=/^\s*(?:<\?[\s\S]*?\?>\s*|<!--[\s\S]*?-->\s*)*<svg(?=[\s/>])/,Qc=[/<script/i,/[\s"'/]on[a-z]+\s*=/i,/<foreignobject/i,/<!doctype/i,/<!entity/i,/<(?:iframe|embed|object)\b/i,/@import/i],ed=/(?:^|[\s"'/])(?:xlink:)?href\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+))/gi,nd=/url\(/gi,bo=/url\(\s*["']?#/iy;});var ci=V(()=>{m();Bi();Zn();ai();Qt();ze();});function S(e,n=e){throw new be(e,n)}var be,et=V(()=>{m();be=class extends Error{constructor(t,i=t){super(i);this.code=t;}code;name="McpAppContractError"};});var Wo=V(()=>{m();});var Jo=V(()=>{m();$e();Me();et();Wo();});function Xo(e,n){return Ko.add(e),n!==void 0&&md.set(e,n),e}function dn(e){return e!==null&&typeof e=="object"&&Ko.has(e)}var Ko,md,nt=V(()=>{m();Ko=new WeakSet,md=new WeakMap;});function Nn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function pi(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 Zo(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let n of Object.values(e))Zo(n);return Object.freeze(e)}function re(e){throw new Se("LINEAGE_INVALID",e)}function Nd(e){throw new Se("LINEAGE_STALE",e)}function Qo(e){if(!Nn(e)||!pi(e,Ed,Td)||!Nn(e.actions))return re("Lineage definition shape is invalid");for(let n of Object.values(e.actions))if(!Nn(n)||!pi(n,Pd,Dd))return re("Lineage action definition shape is invalid");return e}function bd(e){if(!Nn(e)||!pi(e,hd,_d))return re("Lineage entry shape is invalid");if(!Number.isSafeInteger(e.version)||e.version<1||typeof e.hash!="string"||!Yo.test(e.hash))return re("Lineage entry identity is invalid");if(e.sourceHash!==void 0&&(typeof e.sourceHash!="string"||!Yo.test(e.sourceHash)))return re("Lineage source hash is invalid");if(e.compat!==void 0&&e.compat!=="break")return re("Lineage compatibility marker is invalid");let n=Qo(e.definition);if(n.version!==e.version)return re("Lineage version does not match its definition");if(e.sourceHash!==void 0&&n.sourceHash!==e.sourceHash)return re("Lineage source hash does not match its definition");let t;try{t=le(n),Ae({...n,hash:e.hash});}catch{return re("Lineage definition is invalid")}return t!==e.hash?re("Lineage definition hash does not match"):Zo({version:e.version,hash:e.hash,definition:n,...e.sourceHash===void 0?{}:{sourceHash:e.sourceHash},...e.compat===void 0?{}:{compat:e.compat}})}function qo(e){return e.stateProjection?.allow??[]}function Sd(e,n){let t=[],i=new Set(qo(n));qo(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 Md(e,n){return ie(e)===ie(n)}function li(e,n){if(!Array.isArray(e)||e.length===0)return re("Definition lineage is missing");if(!Nn(n)||typeof n.hash!="string")return re("Current definition is invalid");let t,i;try{let{hash:a,...c}=n;i=Qo(c),t={...i,hash:a},Ae(t);}catch{return re("Current definition is invalid")}let o=e.map(bd),r=o[0].definition.id;if(o.some(a=>a.definition.id!==r))return re("Lineage definition ids do not match");if(o.some((a,c)=>c>0&&a.version<=o[c-1].version))return re("Lineage generations are not in increasing version order");if(o.some((a,c)=>o.findIndex(d=>d.hash===a.hash)!==c))return re("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||!Md(s.definition,i))return Nd("The last lineage generation does not match the current package");if(t.legacy!==void 0){let a=new Set(Object.keys(t.actions)),c=new Set;for(let l of o)if(l.sourceHash===void 0)for(let p of Object.keys(l.definition.actions))a.has(p)&&c.add(p);let d=Object.keys(t.legacy.agentAccess??{});if(d.length!==c.size||d.some(l=>!c.has(l))){let l="S4_LEGACY_AGENT_ACCESS_COMPLETE";throw new 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=Sd(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,Yo,hd,_d,Ed,Td,Pd,Dd,ui=V(()=>{m();$e();Me();Se=class extends Error{constructor(t,i=t,o=[]){super(i);this.code=t;this.violations=o;}code;violations;name="UiDefinitionLineageError"},Yo=/^[0-9a-f]{64}$/,hd=["version","hash","definition"],_d=["sourceHash","compat"],Ed=["id","version","actions"],Td=["sourceHash","usage","detailPanel","displayModes","renderer","surfaces","stateProjection","dataPaths","summaryProjection","legacy"],Pd=["capabilities"],Dd=["inputKeys","dataInputs","confirmation","resultProjection","content","env","schedule"];});var er,nr,tr,ir,or=V(()=>{m();er="text/html;profile=mcp-app",nr=["crewx_app_terminal_connect","crewx_app_html_viewer_open"],tr=["crewx_listWorkspaces","crewx_queryAgent","crewx_executeAgent","crewx_getTaskResult","crewx_listTasks","crewx_listAgents","callBrowser","openTab","listTabs","closeTab"],ir="text/html";});function bn(e){return typeof e=="string"&&Ld.includes(e)}function tt(e,n){return e==="card"&&n?.type==="core"&&bn(n.handler)}var Ld,it=V(()=>{m();Ld=Object.freeze(["card.secret-env"]);});function rr(e,n=[],t){if(e.content!==void 0||e.confirmation!=="none")return "denied";let i=Rd();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"&&bn(e.backend.handler)||e.backend?.type==="skill"?"approval_required":e.backend===void 0&&n.includes(e.actionId)?"allowed":"denied"}function Rd(e){return;}var sr=V(()=>{m();$e();nt();it();});function jd(e){return Ln.has(e)&&(e.initialState===void 0||Ln.has(e.initialState))}function lr(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:ir,entryHash:e,html:n,bytes:Object.freeze(t),...o===void 0?{}:{initialState:o}});return o!==void 0&&Ln.add(o),Ln.add(r),r}function Vd(e){let n=[];return e?.terminal===true&&n.push({name:"crewx_app_terminal_connect",description:"Open a local-only terminal session for this App.",inputSchema:{type:"object",properties:{workspace:{type:"string"},threadId:{type:"string"},instanceId:{type:"string"}},required:["threadId","instanceId"],additionalProperties:false},textFallback:"A local terminal connection is ready for this App.",visibility:Object.freeze(["app"]),kind:"host",resourceBinding:Ve}),e?.htmlDocuments===true&&n.push({name:"crewx_app_html_viewer_open",description:"List workspace HTML documents or open one through a short-lived Host capability.",inputSchema:{type:"object",properties:{workspace:{type:"string"},threadId:{type:"string"},instanceId:{type:"string"},operation:{type:"string",enum:["list","open"]},documentId:{type:"string"}},required:["threadId","instanceId","operation"],additionalProperties:false},textFallback:"Workspace HTML documents are available through this App.",visibility:Object.freeze(["app"]),kind:"host",resourceBinding:Ve}),n}function Be(e,n,t){return (typeof e!="string"||!dr.test(e))&&S(n,`${t} must be a safe identifier`),e}function Sn(e,n,t){let i=e??t;return (typeof i!="string"||i.trim().length===0||i.length>Cd)&&S("TOOL_INVALID",`${n} must be a meaningful description`),i}function yi(e){return (typeof e!="string"||e.length===0||e.length>pn||!/<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 Mn(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 Bd(e){return (typeof e!="string"||e.trim().length===0||e.length>Ud)&&S("TOOL_INVALID","MCP App tools require a meaningful text fallback"),e}function Hd(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 fr(e){return (typeof e!="string"||!pr.test(e))&&S("RESOURCE_URI_INVALID","MCP App resource URI is not a registered ui:// URI"),e}function yr(e){let n=Be(e.appId,"APP_ID_INVALID","Local App id"),t=Sn(e.name,"Local App name",n),i=Sn(e.description,"Local App description",`${t} interactive view`),o=at(e.definition),r=yi(e.html),s=ot(e.entryHash,"Local App entry hash"),a=e.entryBytes===void 0?Array.from(new TextEncoder().encode(r)):st(e.entryBytes,"Local App entry bytes");(rt(a)!==s||gr(a)!==r)&&S("HTML_INVALID","Local App entry bytes do not match the HTML hash");let c=zd(e),d=[];Array.isArray(e.actions)||S("TOOL_INVALID","Local App actions must be an array");for(let D of e.actions){let w=Be(D.actionId,"TOOL_ID_INVALID","Local App action id");(d.includes(w)||!Object.prototype.hasOwnProperty.call(o.actions,w))&&S("TOOL_INVALID",`Local App action is not declared by the UI definition: ${w}`),d.push(w);}let l=Be(e.readToolName,"TOOL_ID_INVALID","Local App read tool name"),p=e.actionToolName===void 0?void 0:Be(e.actionToolName,"TOOL_ID_INVALID","Local App action tool name");d.length===0&&p!==void 0&&S("TOOL_INVALID","A static local App cannot register an action tool"),d.length>0&&p===void 0&&S("TOOL_INVALID","A stateful local App requires an action tool name"),p!==void 0&&p===l&&S("TOOL_ID_CONFLICT",`Local App read and action tools share a name: ${l}`);let u=Vd(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:Fd,textFallback:`${t} current state is available through its open instance.`,visibility:Object.freeze(["model","app"]),kind:"read",resourceBinding:Ve},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:Ve,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 w=`${p}__${D.actionId}`;if(w.length>128||!dr.test(w)){_.push(Object.freeze({toolName:w,actionId:D.actionId,reason:"name_too_long"}));continue}if(P.has(w)){_.push(Object.freeze({toolName:w,actionId:D.actionId,reason:"name_collision"}));continue}let B=rr({actionId:D.actionId,confirmation:o.actions[D.actionId]?.confirmation,content:o.actions[D.actionId]?.content,backend:D.backend},e.modelActions),N=Object.freeze([...Kd(B,o.usage,D.backend)]),b={name:w,description:`${w} action`,inputSchema:Mn(D.inputSchema),textFallback:`${w} action requests are handled by the open App instance.`,visibility:N,kind:"action",resourceBinding:Ve,actionId:D.actionId,actionIds:Object.freeze([D.actionId]),_meta:Object.freeze({ui:Object.freeze({visibility:N})})};g.push(Object.freeze(b)),P.add(w);}let U=lr(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:mr(e.icon)},...e.tone===void 0?{}:{tone:hr(e.tone)},builtinOnly:false,definition:o,...e.runtime===void 0?{}:{runtime:Object.freeze({...e.runtime})},resourceBinding:Ve,resource:U,tools:Object.freeze(g),toolDiagnostics:Object.freeze(_)};return ee(k)}function Ar(e={}){return new fi(e)}function Ai(e){if(e.length===0)return Mn({type:"object",properties:{},additionalProperties:false});let n=e.map(i=>i.actionId),t=new Map;for(let i of e)t.set(i.actionId,Mn(i.inputSchema));return Mn($d(n,t),ur)}function zd(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=ot(e.initialStateHash,"Initial state hash"),i=st(e.initialStateBytes,"Initial state bytes");rt(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&&ie(o)!==ie(ye(e.initialState,0,n))&&S("STATE_INVALID","Initial state bytes do not match the state value"),{hash:t,bytes:Object.freeze([...i])}}function $d(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 Gd(e){let n=Rn(e),t=Be(n.appId,"APP_ID_INVALID","MCP App id"),i=yi(n.html);fr(n.uiUri);let o=n.definition===void 0?void 0:at(n.definition),r=e.provenance;r!==void 0&&(!dn(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(Rn(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:er,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 Wd(e){(e.resourceBinding.kind!=="instance"||e.builtinOnly!==false)&&S("STATE_INVALID","Local App registration binding is invalid"),Object.prototype.hasOwnProperty.call(e,"uiUri")&&S("STATE_INVALID","Local App registration cannot contain uiUri");let n=Be(e.appId,"APP_ID_INVALID","Local App id"),t=at(e.definition),i=e.provenance;i!==void 0&&(!dn(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=Jd(e.resource),r=e.tools.map(a=>{Be(a.name,"TOOL_ID_INVALID","Local App tool name"),Sn(a.description,"Local App tool description","Local App tool"),Bd(a.textFallback);let c=Mn(a.inputSchema,a.kind==="action"&&!("actionId"in a)?ur: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 (!vd.has(a.name)||a.visibility.length!==1||a.visibility[0]!=="app"||Object.prototype.hasOwnProperty.call(a,"actionId"))&&S("TOOL_INVALID","Local App Host tools must use an allow-listed name and app-only visibility"),ee({...a,inputSchema:c,visibility:Object.freeze(["app"])});if(a.kind==="action"){if("actionId"in a){let l=Be(a.actionId,"TOOL_ID_INVALID","Local App action id");Object.prototype.hasOwnProperty.call(t.actions,l)||S("TOOL_INVALID","Local App action tool references an undeclared action");let p=Hd(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:Sn(e.name,"Local App name",e.appId),description:Sn(e.description,"Local App description",e.name),...e.icon===void 0?{}:{icon:mr(e.icon)},...e.tone===void 0?{}:{tone:hr(e.tone)},builtinOnly:false,definition:t,...e.runtime===void 0?{}:{runtime:Object.freeze({...e.runtime})},...i===void 0?{}:{provenance:i},resourceBinding:Ve,resource:o,tools:Object.freeze(r),toolDiagnostics:Object.freeze([...e.toolDiagnostics??[]])});return ar.has(e)?e:(ar.add(s),s)}function Jd(e){let n=yi(e.html),t=ot(e.entryHash,"Local App entry hash");if(jd(e))return e;let i=st(e.bytes,"Local App entry bytes");(rt(i)!==t||gr(i)!==n)&&S("HTML_INVALID","Local App entry bytes do not match the HTML hash");let o=e.initialState===void 0?void 0:{hash:ot(e.initialState.hash,"Initial state hash"),bytes:st(e.initialState.bytes,"Initial state bytes")};return o&&rt(o.bytes)!==o.hash&&S("STATE_INVALID","Initial state bytes do not match the hash"),lr(t,n,i,o)}function Kd(e,n,t){if(tt(n,t))return ["model"];let i=t?.type==="core"&&bn(t.handler);return e==="denied"||i?["app"]:["model","app"]}function Xd(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:Ir(e.definition),...e.provenance===void 0?{}:{provenance:e.provenance},entryHash:e.resource.entryHash,resourceBinding:Ve,tools:e.tools})}function Yd(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:Ir(e.definition)},resourceBinding:Object.freeze({kind:"mcp",uri:e.uiUri}),tools:e.tools})}function at(e){try{if(Object.isFrozen(e))return Ae(e),ee(e);let n=Rn(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 Ir(e){return ee({id:e.id,version:e.version,hash:e.hash})}function qd(e){return e!==null&&typeof e=="object"&&typeof e.id=="string"&&Number.isSafeInteger(e.version)&&typeof e.hash=="string"}function cr(e,n,t){return `${e}\0${n}\0${t}`}function ot(e,n){return (typeof e!="string"||!wd.test(e))&&S("SERIALIZATION_INVALID",`${n} is invalid`),e}function rt(e){return createHash("sha256").update(Uint8Array.from(e)).digest("hex")}function st(e,n){return (!Array.isArray(e)||e.some(t=>!Number.isInteger(t)||t<0||t>255))&&S("SERIALIZATION_INVALID",`${n} is invalid`),[...e]}function gr(e){try{return new TextDecoder("utf-8",{fatal:!0}).decode(Uint8Array.from(e))}catch{S("SERIALIZATION_INVALID","UTF-8 bytes are invalid");}}function mr(e){return (typeof e!="string"||!kd.test(e))&&S("TOOL_INVALID","MCP App icon is invalid"),e}function hr(e){return (typeof e!="string"||!xd.has(e))&&S("TOOL_INVALID","MCP App tone is invalid"),e}function Rn(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(Rn(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:Rn(s,n),writable:true});return n.delete(t),o}function ee(e,n=new Set){if(e===null||typeof e!="object"||n.has(e)||Ln.has(e))return e;n.add(e);for(let t of Object.values(e))ee(t,n);return Object.freeze(e),e}var dr,pr,wd,pn,Cd,Ud,kd,xd,vd,Ve,Fd,Ln,ar,ur,fi,ct=V(()=>{m();Jo();$e();Me();nt();et();ui();or();sr();it();dr=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,pr=/^ui:\/\/crewx\/([A-Za-z][A-Za-z0-9._-]{0,127})\/([0-9a-f]{12})$/,wd=/^[0-9a-f]{64}$/,pn=8*1024*1024,Cd=8*1024,Ud=16*1024,kd=/^[a-z][a-z0-9-]{0,63}$/,xd=new Set(["blue","violet","emerald","amber","rose","sky","slate","indigo"]),vd=new Set(nr),new Set(tr),Ve=Object.freeze({kind:"instance"}),Fd=Object.freeze({type:"object",properties:Object.freeze({}),additionalProperties:false}),Ln=new WeakSet,ar=new WeakSet;ur=4;fi=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=Gd(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(Wd),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,Yd(p)),p.definition&&this.addDefinition(p.definition);for(let p of l)this.registrationById.set(p.appId,p),this.launcherById.set(p.appId,Xd(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"||!pr.test(n)?null:this.mcpResources.get(n)??null}requireMcpAppResource(n){fr(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=dn(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(!qd(n))return null;let t=this.definitionByKey.get(Vt(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(cr(n,t,i))??null}addDefinition(n){let t=at(n),i=Vt(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=cr(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 Zd(e){let n=yr({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 _r(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=Zd(e);Ar({localApps:[t],definitions:[e.definition]});}var Er=V(()=>{m();ct();});function Qd(e){if(e===null||typeof e!="object"||!(Tr in e))throw new TypeError("scanCache must be created by createWorkspaceAppScanCache");return e[Tr]}function Pr(e,n){let t=Qd(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 Tr,Dr=V(()=>{m();Tr=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 ip(e){if(typeof e!="string"||e.length===0||!isAbsolute(e))throw new M("READ_DENIED")}function Ii(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 ut(e,n){let t=relative(e,n);return t===""||t!==".."&&!t.startsWith(`..${sep}`)&&!isAbsolute(t)}function un(e){return {dev:e.dev,ino:e.ino,size:e.size,mtimeNs:e.mtimeNs,ctimeNs:e.ctimeNs}}function _i(e,n){return e.dev===n.dev&&e.ino===n.ino}function Ei(e,n){return _i(e,n)&&e.size===n.size&&e.mtimeNs===n.mtimeNs&&e.ctimeNs===n.ctimeNs}async function dt(e){ip(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:un(t)}}async function Sr(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(!ut(n,o))throw new M("PATH_ESCAPED");return o}async function pt(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(!ut(n,r)||t!==void 0&&!ut(t,r))throw new M("PATH_ESCAPED");if(!o.isFile()||!s.isFile())throw new M("READ_DENIED");if(!_i(i,o)||!_i(i,s)||i.dev!==s.dev)throw new M("PATH_ESCAPED")}async function ln(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||!Ei(n.identity,un(i)))throw new M("PATH_ESCAPED")}function op(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,hi,tp,br,ft,Mr,Pi=V(()=>{m();M=class extends Error{constructor(t){super(t);this.code=t;}code;name="AppDiscoveryFsError"},hi=constants.O_NOFOLLOW,tp=constants.O_NONBLOCK,br=constants.O_RDONLY|(hi??0)|(tp??0);ft=class{async getRootIdentity(n){let t=await dt(n);return await ln(n,t),{dev:t.identity.dev,ino:t.identity.ino,realPath:t.realRoot}}async listDirectory(n,t){let i=Ii(t),o=await dt(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(!ut(o.realRoot,s)||!a.isDirectory())throw new M("PATH_ESCAPED");try{let c=await readdir(s,{withFileTypes:!0,encoding:"utf8"});return await ln(n,o),c.map(op)}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(hi===void 0)throw new M("UNSUPPORTED");let o=Ii(t),r=await dt(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,br);}catch(d){throw ue(d)}try{let d;try{let g=await c.stat({bigint:!0});d=un(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 ln(n,r);let l=await Sr(n,r.realRoot,o);await pt(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=un(g);}catch(g){throw ue(g)}if(!Ei(d,f))throw new M("IDENTITY_CHANGED");return await pt(s,r.realRoot,l,f),await ln(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(hi===void 0)throw new M("UNSUPPORTED");let o=Ii(t),r=await dt(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,br);}catch(d){throw ue(d)}try{let d;try{let u=await c.stat({bigint:!0});d=un(u);}catch(u){throw ue(u)}if(d.size>BigInt(i)||d.size>BigInt(Number.MAX_SAFE_INTEGER))throw new M("LIMIT_EXCEEDED");await ln(n,r);let l=await Sr(n,r.realRoot,o);await pt(s,r.realRoot,l,d);let p;try{let u=await c.stat({bigint:!0});p=un(u);}catch(u){throw ue(u)}if(!Ei(d,p))throw new M("IDENTITY_CHANGED");return await pt(s,r.realRoot,l,p),await ln(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)}},Mr=new ft;});function Un(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 Rr(e){return typeof e=="string"&&Te.test(e)?e:void 0}function lp(e){return e.length>0&&e!=="."&&e!==".."&&!/[\\/\u0000]/.test(e)}function Xe(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 up(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 fp(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 yp(e){return dp.decode(e)}function Ap(e){return JSON.parse(yp(e))}function Or(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 Ip(e){if(e instanceof M)return Or(e.code);if(e!==null&&typeof e=="object"&&"code"in e){let n=e.code;if(typeof n=="string")return Or(n)}}function Re(e,n){let t=n();return Number.isFinite(t)&&Number.isFinite(e)&&t-e<=5e3}function gp(e){if(typeof e.readVerifiedFile=="function")return e.readVerifiedFile;if(typeof e.readFileVerified=="function")return e.readFileVerified}function mp(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 wr(e,n,t,i){let o=gp(e);if(!o)throw new M("READ_DENIED");return fp(await o.call(e,n,t,i))}async function bi(e,n,t){let i=mp(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(up).filter(r=>r!==null)}function hp(e,n,t,i){return Object.freeze({code:e,...{},source:n,relativePath:t})}function _p(e){if(!Un(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(Xe))};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 Ep(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 At(e){return Object.freeze({appIds:Object.freeze([...new Set(e.map(n=>n.appId))].sort(Xe)),definitionIds:Object.freeze([...new Set(e.map(n=>n.definition.id))].sort(Xe))})}function yt(e,n){let t=Object.keys(e).sort(Xe),i=[...n].sort(Xe);return t.length===i.length&&t.every((o,r)=>o===i[r])}function Cr(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 Tp(e){let n;try{n=Ap(e);}catch{return}if(!Un(n)||!yt(n,["version","packages"])||n.version!==1||!Array.isArray(n.packages)||n.packages.length>Si)return;let t=new Set,i=new Set,o=0,r=[];for(let s of n.packages){if(!Un(s))return;let a=["packageDir","appId","definition","files"],c=Object.hasOwn(s,"lineage"),d=Object.hasOwn(s,"launcher"),l=[...c?["lineage"]:[],...d?["launcher"]:[]];if(!yt(s,[...a,...l])||d&&s.launcher!==false)return;let p=Cr(s.packageDir),u=Rr(s.appId);if(!p||p.length!==2||p[0]!=="apps"||!lp(p[1])||!u||t.has(s.packageDir)||!Un(s.definition)||!yt(s.definition,["id","version","hash"]))return;let f=Rr(s.definition.id),g=s.definition.version,_=s.definition.hash;if(!f||!Number.isSafeInteger(g)||g<1||typeof _!="string"||!Ni.test(_)||!Array.isArray(s.files)||s.files.length<2||s.files.length>Mi)return;let P=new Set,U=[];for(let k of s.files){if(!Un(k)||!yt(k,["path","sha256"]))return;let D=Cr(k.path);if(!D||typeof k.sha256!="string"||!Ni.test(k.sha256))return;let w=D.join("/"),B=`${s.packageDir}/${w}`;if(P.has(w)||i.has(B))return;P.add(w),i.add(B),U.push(Object.freeze({path:w,sha256:k.sha256}));}if(!Q.some(k=>P.has(k))||!P.has("ui/index.html")||(o+=U.length,o>sp))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,D)=>Xe(k.path,D.path)))}));}return Object.freeze({version:1,packages:Object.freeze(r)})}function Ke(e){let n=Ip(e);return n==="PATH_ESCAPED"||n==="IDENTITY_CHANGED"||n==="TOCTOU"?"PATH_ESCAPED":n==="LIMIT_EXCEEDED"?"LIMIT_EXCEEDED":"BUNDLE_INTEGRITY"}async function Pp(e,n,t,i,o){let r=[],s=async(a,c)=>{if(!Re(i,o))throw new M("LIMIT_EXCEEDED");if(c>2)throw new M("LIMIT_EXCEEDED");let d=await bi(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>Mi)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(Xe)}function Dp(e){return Q.includes(e)?262144:e==="ui/index.html"?pn:e==="ui/state.json"?2097152:e.startsWith("ui/assets/")?cp:ap}async function Ur(e,n,t,i){if(e===void 0)return {packages:[],diagnostics:[],incomplete:false,reservedIds:pp};let o=_p(e.reservedIds),r=[],s=(I,A,h)=>hp(I,"bundled",A),a=(I=[],A=false,h)=>({...h===void 0?{}:{indexHash:h},packages:I,diagnostics:r,incomplete:A,reservedIds:o});if(typeof e.root!="string"||e.root.length===0||typeof e.expectedIndexHash!="string"||!Ni.test(e.expectedIndexHash))return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a();let c;try{c=await wr(n,e.root,"bundle-index.json",rp);}catch(I){return r.push(s(Ke(I),"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=Tp(c);if(l===void 0)return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a();if(!Ep(At(l.packages),o))return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a([],false,d);if(!Re(t,i))return r.push(s("LIMIT_EXCEEDED","bundle-index.json")),a(l.packages.map(I=>({indexEntry:I,failureCode:"LIMIT_EXCEEDED"})),true,d);let p;try{p=await bi(n,e.root,"");}catch(I){return r.push(s(Ke(I),"bundle-index.json")),a(l.packages.map(A=>({indexEntry:A,failureCode:Ke(I)})),false,d)}if(!Re(t,i))return r.push(s("LIMIT_EXCEEDED","bundle-index.json")),a(l.packages.map(I=>({indexEntry:I,failureCode:"LIMIT_EXCEEDED"})),true,d);let u=p.find(I=>I.name==="bundle-index.json"&&I.kind==="file"),f=p.find(I=>I.name==="apps"&&I.kind==="directory"),g=I=>l.packages.map(A=>({indexEntry:A,failureCode:I}));if(!u)return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a(g("BUNDLE_INTEGRITY"),false,d);let _=p.filter(I=>I.name!=="bundle-index.json"&&I.name!=="apps");if(_.length>0){let I=_.some(A=>A.kind==="symlink")?"PATH_ESCAPED":"BUNDLE_INTEGRITY";return r.push(s(I,"bundle-index.json")),a(g("BUNDLE_INTEGRITY"),false,d)}if(p.some(I=>I.name==="apps"&&I.kind!=="directory"))return r.push(s("PATH_ESCAPED","apps")),a(g("PATH_ESCAPED"),false,d);let P=[];if(f)try{P=await bi(n,e.root,"apps");}catch(I){return r.push(s(Ke(I),"apps")),a(g(Ke(I)),false,d)}if(!Re(t,i)||P.length>Si)return r.push(s("LIMIT_EXCEEDED","apps")),a(g("LIMIT_EXCEEDED"),true,d);let U=new Map(l.packages.map(I=>[I.packageDir.slice(5),I])),k=P.filter(I=>!U.has(I.name));for(let I of k)r.push(s(I.kind==="symlink"?"PATH_ESCAPED":"BUNDLE_INTEGRITY",`apps/${I.name}`));if(k.length>0){let I=k.some(A=>A.kind==="symlink")?"PATH_ESCAPED":"BUNDLE_INTEGRITY";return a(g(I),false,d)}let D=new Set,w=new Map,B=new Map;for(let I of l.packages){let A=w.get(I.appId)??[];A.push(I),w.set(I.appId,A);let h=`${I.definition.id}\0${String(I.definition.version)}`,E=B.get(h)??[];E.push(I),B.set(h,E);}for(let I of [...w.values(),...B.values()])if(I.length>1)for(let A of I)D.add(A);let N=[],b=c.byteLength,L=false;for(let I of l.packages){if(!Re(t,i)){L=true,N.push({indexEntry:I,failureCode:"LIMIT_EXCEEDED"});continue}let A;try{let C=I.lineage[I.lineage.length-1];if(!C)throw new Se("LINEAGE_INVALID","Definition lineage is missing");if(C.definition.id!==I.definition.id||C.version!==I.definition.version||C.hash!==I.definition.hash)throw new Se("LINEAGE_STALE","Last lineage generation does not match bundle identity");A=li(I.lineage,{...C.definition,hash:C.hash}).entries;}catch(C){let x=C instanceof Se?C.code:"LINEAGE_INVALID";r.push(s(x,I.packageDir)),N.push({indexEntry:I,failureCode:x});continue}let h=P.find(C=>C.name===I.packageDir.slice(5));if(!f||!h){N.push({indexEntry:I,failureCode:"BUNDLE_INTEGRITY"});continue}if(h.kind!=="directory"){N.push({indexEntry:I,failureCode:h.kind==="symlink"?"PATH_ESCAPED":"BUNDLE_INTEGRITY"});continue}let E;try{let C=await Pp(n,e.root,I.packageDir,t,i);if(!Re(t,i)){L=!0,N.push({indexEntry:I,failureCode:"LIMIT_EXCEEDED"});continue}let x=I.files.map(W=>W.path);if(C.length!==x.length||C.some((W,ke)=>W!==x[ke])){N.push({indexEntry:I,failureCode:"BUNDLE_INTEGRITY"});continue}E=new Map;let te;for(let W of I.files){if(!Re(t,i)){te="LIMIT_EXCEEDED",L=!0;break}if(b>=Di){te="LIMIT_EXCEEDED";break}let ke;try{ke=await wr(n,e.root,`${I.packageDir}/${W.path}`,Dp(W.path));}catch(Dt){te=Ke(Dt);break}if(!Re(t,i)){te="LIMIT_EXCEEDED",L=!0;break}if(b+ke.byteLength>Di){b=Di,te="LIMIT_EXCEEDED";break}if(b+=ke.byteLength,createHash("sha256").update(ke).digest("hex")!==W.sha256){te="BUNDLE_INTEGRITY";break}E.set(W.path,ke);}if(te!==void 0){N.push({indexEntry:I,failureCode:te});continue}}catch(C){Re(t,i)||(L=true),N.push({indexEntry:I,failureCode:Ke(C)});continue}N.push({indexEntry:I,lineage:A,files:E,...D.has(I)?{failureCode:"DUPLICATE_ID"}:{}});}return a(N,L,d)}var rp,Si,Mi,sp,ap,cp,Di,Ni,dp,pp,Li=V(()=>{m();ui();ze();Zn();ct();Pi();rp=256*1024,Si=64,Mi=128,sp=Si*Mi,ap=2*1024*1024,cp=8*1024*1024,Di=32*1024*1024,Ni=/^[0-9a-f]{64}$/,dp=new TextDecoder("utf-8",{fatal:true}),pp=Object.freeze({appIds:Object.freeze([]),definitionIds:Object.freeze([])});});function bp(e){if(typeof e!="string"||!Te.test(e))throw new TypeError("pluginId must be a safe UI plugin identifier");let n=`${Ri}${e}`.length+7<=128?e:`hash_${createHash("sha256").update(e,"utf8").digest("hex")}`;return {read:`${Ri}${n}_read`,action:`${Ri}${n}_action`}}function xr(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 Mp(e,n){return n.length===0||n==="."||n===".."||/[\\/\u0000]/.test(n)?e==="skills"?"skills":"apps":`${e==="skills"?"skills":"apps"}/${n}`}function Lp(e){return e.length>0&&e!=="."&&e!==".."&&!/[\\/\u0000]/.test(e)}function xn(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 Jr(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 Rp(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 Kr(e){return Sp.decode(e)}function Op(e){return JSON.parse(Kr(e))}function wp(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 It(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 vr(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 se(e){if(e instanceof M)return vr(e.code);if(e!==null&&typeof e=="object"&&"code"in e){let n=e.code;if(typeof n=="string")return vr(n)}}function qe(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 Fr(e){return {reason:e.reason,...e.code==="MANIFEST_DUAL_MISMATCH"?{files:e.files}:{}}}function jr(e){return e==="MANIFEST_DUAL_MISMATCH"?e:Xr(e)}function Cp(e){return Xr(e.code)}function Xr(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 Yr("UiPluginValidationError",e)}}function Yr(e,n){throw new Error(`Unmapped ${e} code: ${String(n)}`)}function qr(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 Yr("McpAppContractError",e)}}function Oe(e,n){let t=n();return Number.isFinite(t)&&Number.isFinite(e)&&t-e<=5e3}function Up(e){return {pluginId:e.appId,definitionKey:`${e.definition.id}\0${String(e.definition.version)}`}}function kp(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(xr(o)){let r=o.bin,s=typeof r=="string"?r:xr(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=xp(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 xp(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 vp(){return globalThis.performance?.now()??Date.now()}function Ye(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let n of Object.values(e))Ye(n);return Object.freeze(e)}function Vr(e){return Object.freeze(Array.from(e))}async function vn(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 $r(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 $r(e,n.root,o,i),d=await s.call(e,r.workspaceRoot,o,i);return r.candidateRealPath=d.candidateRealPath,Qr(a,d)&&d.size===BigInt(c.byteLength)&&!es(d,r.scanStartedAtNs)?r.files.set(o,{relativePath:o,byteLimit:i,fingerprint:d}):r.cacheable=!1,c}catch(a){let c=!t.includes("/")&&se(a)==="NOT_FOUND"&&r.directoryListings.some(l=>l.relativePath===n.relativePath&&!gt(l.key,t)),d=t===z&&se(a)==="NOT_FOUND"&&jp(r.directoryListings,n.relativePath);throw !c&&!d&&(r.cacheable=false),a}}async function Fp(e,n,t){if(n.pinnedFiles!==void 0)return {iconDiagnostics:[]};let i=await En(t,async r=>{try{return await vn(e,n,r,262144)}catch(s){let a=se(s);return a==="NOT_FOUND"?"missing":a==="LIMIT_EXCEEDED"?"too-large":"bad-path"}}),o=i.file;return {...o===void 0?{}:{iconFile:{path:o.path,sha256:createHash("sha256").update(o.bytes).digest("hex"),contentType:o.contentType,byteLength:o.byteLength}},iconDiagnostics:i.diagnostics}}function jp(e,n){let t=e.find(o=>o.relativePath===n);if(t===void 0)return false;if(!gt(t.key,"dist"))return true;let i=e.find(o=>o.relativePath===`${n}/dist`);return i!==void 0&&!gt(i.key,"tools.json")}function Zr(e,n){return JSON.stringify([e.realPath,n.source,n.relativePath])}async function Bp(e,n,t,i,o,r,s,a){let c=e.fingerprintVerifiedFile,d=Zr(t,i),l=o.candidates.get(d),p=i.relativePath,u;try{u=await zr(e,n,p);}catch(L){if(se(L)!=="NOT_FOUND")throw L}let f=u===void 0?void 0:{relativePath:p,key:u};if(f!==void 0&&(i.source==="apps"||i.source==="skills")&&!Q.some(L=>gt(f.key,L)))return Oe(s,a)?l!==void 0&&l.candidate===void 0&&l.candidateRealPath===void 0&&l.files.length===0&&l.directoryListings.length===1&&l.directoryListings[0]?.relativePath===f.relativePath&&l.directoryListings[0]?.key===f.key&&(i.source==="apps"?l.diagnostic?.code==="MANIFEST_MISSING":l.diagnostic===void 0)&&typeof c=="function"?{memo:l}:typeof c!="function"?{}:{context:{state:o,cacheKey:d,workspaceRoot:n,scanStartedAtNs:r,directoryListings:Object.freeze([f]),priorFingerprints:new Map,files:new Map,cacheable:true}}:{timeLimitReached:true};let g=async L=>{if(L==="")return f;let I=`${i.relativePath}${L}`;try{let A=await zr(e,n,I);return A===void 0?void 0:{relativePath:I,key:A}}catch(A){if(se(A)==="NOT_FOUND")return;throw A}},_=await Promise.all(Br.map(g)),P=await Promise.all(Vp.map(g));if(!Oe(s,a))return {timeLimitReached:true};let U=typeof c=="function"&&_.every(L=>L!==void 0),k=_.filter(L=>L!==void 0),D=[...k,...P.filter(L=>L!==void 0)],w=new Map,B=l!==void 0&&U,N;if(l!==void 0&&typeof c=="function"){let L=await Promise.all(l.files.map(async I=>{if(!Oe(s,a))return {kind:"time",file:I};try{let A=await c.call(e,n,I.relativePath,I.byteLimit);return {kind:"fingerprint",file:I,current:A}}catch(A){return se(A)==="NOT_FOUND"?{kind:"missing",file:I}:{kind:"error",file:I,error:A}}}));if(L.some(I=>I.kind==="time"))return {timeLimitReached:true};for(let I of L){if(I.kind==="error")throw I.error;if(I.kind==="missing"){B=false;continue}if(I.kind!=="fingerprint")continue;let{file:A,current:h}=I;w.set(A.relativePath,h),N??=h.candidateRealPath,(h.candidateRealPath!==l.candidateRealPath||!Qr(h,A.fingerprint)||es(h,r))&&(B=false);}}let b=l!==void 0&&l.directoryListings.length===D.length&&l.directoryListings.every((L,I)=>L.relativePath===D[I]?.relativePath&&L.key===D[I]?.key);return l!==void 0&&U&&b&&B&&N===l.candidateRealPath?{memo:l}:!U||k.length!==Br.length?{}:{context:{state:o,cacheKey:d,workspaceRoot:n,scanStartedAtNs:r,directoryListings:Object.freeze(D),priorFingerprints:w,files:new Map,...N===void 0?{}:{candidateRealPath:N},cacheable:true}}}function gt(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 zr(e,n,t){let i=ns(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(Jr);if(!r.some(s=>s===null))return JSON.stringify(r.slice().sort((s,a)=>xn(s.name,a.name)||xn(s.kind,a.kind)).map(s=>[s.name,s.kind]))}function Qr(e,n){return e.dev===n.dev&&e.ino===n.ino&&e.size===n.size&&e.mtimeNs===n.mtimeNs&&e.ctimeNs===n.ctimeNs}function es(e,n){let t=e.mtimeNs-n;return t>=-Hr&&t<=Hr}function Oi(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 Hp(e,n,t){let i=createHash("sha256"),o=new TextEncoder().encode(ie(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 zp(e,n){let t={...e.definition,sourceHash:n},i;try{i=le(t);}catch(r){throw r instanceof v&&r.code==="INPUT_INVALID"?new ce("MANIFEST_INVALID","normalized definition is invalid"):r}let o={...t,hash:i};try{Ae(o);}catch{throw new ce("MANIFEST_INVALID","normalized definition is invalid")}return o}function $p(e,n){return e.actions.some(t=>t.backend.type==="core"&&t.backend.handler!=="state.set"&&!tt(n,t.backend))}function Gp(e){if(typeof e.readVerifiedFile=="function")return e.readVerifiedFile;if(typeof e.readFileVerified=="function")return e.readFileVerified}function ns(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 $r(e,n,t,i){let o=Gp(e);if(!o)throw new M("READ_DENIED");return Rp(await o.call(e,n,t,i))}async function Wp(e,n,t){let i=ns(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(Jr).filter(r=>r!==null)}function Jp(e){let n=[];for(let t of [e.reserved,e.builtin])t&&n.push(t);return e.builtins&&"listMcpApps"in e.builtins?n.push(Gr(e.builtins)):e.builtins&&n.push(e.builtins),e.builtinCatalog&&n.push(Gr(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 Gr(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=It(n,e.source,e.relativePath,e.identity?.pluginId));}function Kp(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 Xp(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 Jp(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{_r(p),d.add(l);}catch(u){_e(l,u instanceof be?qr(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 Yp(e){return [...e].sort((n,t)=>{let i=kr.indexOf(n.source)-kr.indexOf(t.source);return i!==0?i:xn(n.relativePath,t.relativePath)})}function H(e,n,t){e.diagnostic=It(n,e.source,e.relativePath,e.identity?.pluginId,t);}async function Wr(e,n,t){let i=je(t,{mode:"local"});if(!i.ok&&i.parseFailure){H(n,jr(i.rejection.code),Fr(i.rejection));return}let o=wp(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)}`){H(n,"BUNDLE_INTEGRITY");return}if(!i.ok&&i.builtinOnly){H(n,"RESERVED_ID");return}if(!i.ok){H(n,jr(i.rejection.code),Fr(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(x=>({actionId:x.actionId,inputSchema:x.inputSchema})));}catch(x){if(x instanceof be){H(n,qr(x.code));return}throw x}let a;try{a=await vn(e,n,"ui/index.html",pn);}catch(x){H(n,qe(se(x),"entry"));return}if(a.byteLength>pn){H(n,"LIMIT_EXCEEDED");return}let c;try{c=Kr(a);}catch{H(n,"ENTRY_INVALID");return}if(a.byteLength===0||c.length===0){H(n,"ENTRY_INVALID");return}let d=createHash("sha256").update(a).digest("hex");if(r.entryHash!==void 0&&r.entryHash!==d){H(n,"ENTRY_INVALID");return}let l={},p,u;if(r.initialState!==void 0){try{p=await vn(e,n,"ui/state.json",2097152);}catch(x){H(n,qe(se(x),"initial"));return}if(p.byteLength>2097152){H(n,"LIMIT_EXCEEDED");return}try{let x=Op(p),te=r.dataPaths??[],W=Zt(x,te);l=ye(W,0,te),nn(l);}catch{H(n,"INITIAL_STATE_INVALID");return}if(u=createHash("sha256").update(p).digest("hex"),r.initialState.hash!==void 0&&r.initialState.hash!==u){H(n,"INITIAL_STATE_INVALID");return}}let f={...r,entryHash:d,...r.initialState===void 0?{}:{initialState:{path:"ui/state.json",hash:u}}},g=hn(f),_=Hp(f,a,p??new Uint8Array),P;try{P=zp(g,_);}catch(x){if(x instanceof ce){H(n,Cp(x));return}throw x}let U;if(n.bundleLineage!==void 0){let x=n.bundleLineage[n.bundleLineage.length-1];if(!x){H(n,"LINEAGE_INVALID");return}let{legacy:te,...W}=x.definition,{hash:ke,...Dt}=P;if(ie(W)!==ie(Dt)){H(n,"LINEAGE_STALE");return}if(te!==void 0&&(P={...P,legacy:te}),te!==void 0)try{P={...P,hash:le(P)},Ae(P);}catch{H(n,"LINEAGE_INVALID");return}U=n.bundleLineage;}if(n.bundleIdentity!==void 0&&n.bundleIdentity.appId!==r.pluginId){H(n,"BUNDLE_INTEGRITY");return}if(n.bundleIdentity!==void 0&&(n.bundleIdentity.definitionId!==P.id||n.bundleIdentity.version!==P.version||n.bundleIdentity.definitionHash!==P.hash)){H(n,"LINEAGE_STALE");return}let k=await Fp(e,n,i.mcpb?.icon),D=bp(r.pluginId),w=r.actions.length===0?{read:D.read}:D,B=Ye(g),N=Ye(f),b=Ye(P),L=Ye({...g.handlers}),I=Vr(a),A=p===void 0?void 0:Vr(p),h=Object.freeze({...n.provenance===void 0?{}:{provenance:n.provenance},entry:Object.freeze({path:"ui/index.html",hash:d,bytes:I}),...A===void 0?{}:{initialState:Object.freeze({path:"ui/state.json",hash:u,bytes:A})}}),E={appId:r.pluginId,pluginId:r.pluginId,definitionId:r.definitionId,version:r.version,...i.releaseVersion===void 0?{}:{releaseVersion:i.releaseVersion},manifestFile:i.file,...i.mcpb===void 0?{}:{mcpb:Ye(i.mcpb)},relativePath:n.relativePath,manifest:N,normalized:B,name:r.name,description:r.description,...r.icon===void 0?{}:{icon:r.icon},...r.tone===void 0?{}:{tone:r.tone},...k.iconFile===void 0?{}:{iconFile:Object.freeze({...k.iconFile})},...k.iconDiagnostics.length===0?{}:{iconDiagnostics:Object.freeze([...k.iconDiagnostics])},definition:b,handlers:L,resources:h,html:c,entryBytes:I,entryHash:d,initialState:Ye(l),...A===void 0?{}:{initialStateBytes:A},...u===void 0?{}:{initialStateHash:u},sourceHash:_,toolNames:Object.freeze(w)},C=n.provenance===void 0?{...E,source:n.source}:{...E,provenance:n.provenance,lineage:U??[]};n.candidate=Object.freeze(C),$p(r,P.usage)&&H(n,"EXEC_DENIED");}async function ts(e,n){let t={};for(let i of Q)try{t[i]=await vn(e,n,i,262144);}catch(o){if(se(o)==="NOT_FOUND")continue;return {files:t,failure:qe(se(o),"manifest")}}if(t[G]!==void 0)try{t[z]=await vn(e,n,z,262144);}catch(i){if(se(i)!=="NOT_FOUND")return {files:t,failure:qe(se(i),"manifest")}}return {files:t}}function wi(e){return Q.some(n=>e[n]!==void 0)}async function qp(e,n){let{files:t,failure:i}=await ts(e,n);if(i!==void 0){H(n,i);return}let o=t[G];return o!==void 0&&!ri(o)&&(delete t[G],delete t[z]),wi(t)?t:void 0}function Zp(e,n,t,i=Np,o=false,r=new Set){let s=Yp(e),a=Kp(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 Qp(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 el(e,n){if(Qp(e))return {fs:e,options:{}};let t=e??n??{};return {fs:t.filesystem??t.fileSystem??t.fs??Mr,options:t}}async function is(e,n,t){if(typeof e!="string"||e.length===0)throw new TypeError("workspaceRoot must be explicit");let{fs:i,options:o}=el(n,t),r=o.clock??vp,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=Pr(o.scanCache,_),g.scanStartedAtNs=d;}catch(N){if(se(N)!=="NOT_FOUND")throw N}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(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(!Oe(c,r)){f=true,u="time_limit";break}let b=N.indexEntry,L=b.packageDir,I=N.files===void 0?void 0:kp(L,N.files),A=a.indexHash===void 0?void 0:Xo(Object.freeze({kind:"bundled",launcher:b.launcher!==false,indexHash:a.indexHash,packageDir:L,appId:b.appId,definitionId:b.definition.id,version:b.definition.version,definitionHash:b.definition.hash,files:b.files}),I),h={source:"bundled",root:o.productBundle?.root??e,name:L.slice(5),relativePath:L,...A===void 0?{}:{provenance:A},...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:Up(b)};if(l.push(h),p+=1,N.failureCode!==void 0){H(h,N.failureCode);continue}if(N.files?.has(z)===true){H(h,"EXEC_DENIED",{reason:{path:"",rule:"bundled-tool-mode-unsupported",file:z}});continue}let E={};for(let C of Q){let x=N.files?.get(C);x!==void 0&&(E[C]=x);}if(!wi(E)){H(h,"BUNDLE_INTEGRITY");continue}if(await Wr(i,h,E),!Oe(c,r)){f=true,u="time_limit";break}}let w=[{source:"apps",directory:"apps"},{source:"skills",directory:"skills"}];e:for(let N of w){let{source:b,directory:L}=N,I;try{I=await Wp(i,e,L);}catch(h){if(se(h)==="NOT_FOUND")continue;P=false,k=false,l.push({source:b,root:e,name:"",relativePath:b,diagnostic:It(qe(se(h),"manifest"),b,b)});continue}let A=I.filter(h=>h.kind==="directory"||h.kind==="symlink").filter(h=>Lp(h.name)).map(h=>({source:b,root:e,name:h.name,relativePath:Mp(b,h.name)})).sort((h,E)=>xn(h.relativePath,E.relativePath));for(let h of A){let E={...h};if(l.push(E),_!==void 0?U.add(Zr(_,E)):P=false,!Oe(c,r)){f=true,u="time_limit";break e}let C;if(g!==void 0&&_!==void 0){try{let W=await Bp(i,e,_,E,g,d,c,r);if(W.timeLimitReached){f=!0,u="time_limit";break e}E.scanContext=W.context,C=W.memo;}catch(W){P=false,H(E,qe(se(W),"manifest"));continue}C===void 0&&(P=false);}if(C!==void 0){if(E.candidate=C.candidate,E.diagnostic=C.diagnostic,E.identity=C.identity,b==="skills"&&C.candidate===void 0&&C.diagnostic===void 0)continue;if(p>=64){H(E,"LIMIT_EXCEEDED");continue}if(h.relativePath.split("/").length-1>2){H(E,"LIMIT_EXCEEDED");continue}if(p+=1,!Oe(c,r)){f=true,u="time_limit";break e}continue}let x;if(b==="skills"&&(x=await qp(i,E),x===void 0)){E.diagnostic===void 0&&Oi(E);continue}if(p>=64){H(E,"LIMIT_EXCEEDED");continue}if(h.relativePath.split("/").length-1>2){H(E,"LIMIT_EXCEEDED");continue}if(!Oe(c,r)){f=true,u="time_limit";break e}if(p+=1,x===void 0){let W=await ts(i,E);if(W.failure!==void 0||!wi(W.files)){H(E,W.failure??qe("NOT_FOUND","manifest")),Oi(E);continue}x=W.files;}if(await Wr(i,E,x),Oi(E),!Oe(c,r)){f=true,u="time_limit";break e}}}if(g!==void 0&&_!==void 0){let N=[...U].sort(xn),b=g.lastCandidateKeys,L=b!==void 0&&b.length===N.length&&b.every((A,h)=>A===N[h]);if(P=P&&L,k&&!f&&u===void 0)for(let A of g.candidates.keys())try{JSON.parse(A)[0]===_.realPath&&!U.has(A)&&g.candidates.delete(A);}catch{g.candidates.delete(A);}let I=[...g.candidates.keys()].filter(A=>{try{return JSON.parse(A)[0]===_.realPath}catch{return false}});P=P&&I.length===U.size&&I.every(A=>U.has(A))&&!f&&u===void 0,g.lastCandidateScanUnchanged=P,k&&!f&&u===void 0&&(g.lastCandidateKeys=Object.freeze(N));}f&&l.push({source:"apps",root:e,name:"",relativePath:"apps",diagnostic:It("DISCOVERY_TIME_LIMIT","apps","apps")});let B=Xp(l,o,D);return Zp(l,u,a.indexHash,D,o.productBundle!==void 0,B)}var Np,Ri,kr,Sp,Br,Vp,Hr,os=V(()=>{m();$e();jn();Me();ci();ai();ze();ct();Er();it();et();Dr();Pi();nt();Li();Li();Np=At([]),Ri="crewx_local_app_";kr=["bundled","apps","skills"],Sp=new TextDecoder("utf-8",{fatal:true});Br=["","/ui"],Vp=["/dist"],Hr=2000000000n;});m();ci();m();Ht();m();var xo="SKILL.md",ld=/^---\s*\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;function vo(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function ud(e){return e.isDirectory()||e.isSymbolicLink()}function Ho(e){try{return existsSync(e)&&statSync(e).isDirectory()}catch{return false}}function di(e){let n;try{n=readFileSync(e,"utf8");}catch{return {frontmatter:{},readable:false,valid:false,hasFrontmatter:false}}let t=n.match(ld);if(!t)return {frontmatter:{},readable:true,valid:true,hasFrontmatter:false};try{let i=load(t[1]??"");if(!vo(i))return {frontmatter:{},readable:!0,valid:!1,hasFrontmatter:!0};let o=vo(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 fd(e){return [join(e,xo),join(e,"skill",xo)]}function Fo(e,n){if(!Ho(e))return null;for(let t of fd(e)){if(!existsSync(t))continue;let o=di(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 jo(e){try{return readdirSync(e,{withFileTypes:!0}).filter(ud)}catch{return []}}function Vo(e,n,t){!e||n.has(e.name)||(n.add(e.name),t.push(e));}function zo(e){let n=[],t=new Set;for(let i of e)if(Ho(i))for(let o of jo(i)){if(o.name.startsWith("@")){let r=join(i,o.name);for(let s of jo(r))Vo(Fo(join(r,s.name),s.name),t,n);continue}Vo(Fo(join(i,o.name),o.name),t,n);}return n.sort((i,o)=>i.name.localeCompare(o.name))}m();Zn();var yd=/^[A-Za-z0-9_$.[\]"-]{0,200}$/,Ad=/^[a-z][a-z0-9-]{0,63}$/,Id="<unknown>";function gd(e){return typeof e=="string"&&(Q.includes(e)||e===z)}function $o(e){if(typeof e!="object"||e===null)return;let{file:n,path:t,rule:i}=e;if(!(typeof i!="string"||!Ad.test(i)))return {...gd(n)?{file:n}:{},path:typeof t=="string"&&yd.test(t)?t:Id,rule:i}}function Go(e){if(!Array.isArray(e))return;let n=Q.filter(t=>e.includes(t));return n.length>0?n:void 0}os();var tl=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/;function _t(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?il(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 il(e,n){let t=new TextEncoder().encode(Et(e)),i=ol(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 ol(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 Et(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 mt(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 as(e,n){let t=relative(e,n).split(sep).join("/");return !t||t===".."||t.startsWith("../")||isAbsolute(t)?null:Et(t)}function rl(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 cs(e){return Object.freeze({packageRoot:e})}function sl(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 ds(e){return {capabilities:Object.freeze([...e]),origin:"local",ownership:"unknown",shareability:"unknown",sharingAvailability:"unavailable"}}function al(e,n){let t=e.candidate,i=t.provenance!==void 0,o=n&&!i?["screen","skill"]:["screen"],r=sl(t),s=_t(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,...ds(o),definition:r,...n===void 0||i?{}:{skillName:n.skill.name},...i?{provenance:t.provenance}:{localDefinitionRef:cs(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 cl(e){let n=dl(e.skill.name),t={appId:n,name:e.skill.name,description:e.skill.description??"",...e.skill.version===void 0?{}:{version:e.skill.version},...ds(["skill"]),skillName:e.skill.name,localDefinitionRef:cs(e.packageRoot),definitionHash:_t({skillHash:e.skillHash})};return {packageRoot:e.packageRoot,source:e.source,appId:n,capabilities:["skill"],summary:Object.freeze(t)}}function dl(e){return `skill.${e.replace(/^@/,"").replace(/\//g,".").replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,122)||"unnamed"}`}function Z(e,n,t,i,o){let r=$o(o?.reason),s=Go(o?.files);return Object.freeze({code:e,source:n,relativePath:pl(t),...i===void 0?{}:{appId:i},...r===void 0?{}:{reason:r},...s===void 0?{}:{files:s}})}function pl(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 ps(e){return Z(e.code,e.source,e.relativePath,e.pluginId,e)}function ll(e,n){let t=as(e,n.dir);if(!t)return {diagnostic:Z("PATH_ESCAPED","node_modules","node_modules")};let i=rl(t);if(!i)return {diagnostic:Z("PATH_ESCAPED","node_modules",t)};let o=di(n.skillMdPath);if(!o.readable)return {diagnostic:Z("SKILL_READ_FAILED",i,t)};if(!o.valid)return {diagnostic:Z("SKILL_INVALID",i,t)};let r=ul(n.dir,n.skillMdPath);if(!r)return {diagnostic:Z("PATH_ESCAPED",i,t)};try{let s=new Uint8Array(readFileSync(n.skillMdPath));return {skill:n,packageRoot:t,relativeSkillPath:r,skillHash:_t({relativePath:r,fileBytes:s}),source:i}}catch{return {diagnostic:Z("SKILL_READ_FAILED",i,t)}}}function ul(e,n){let t=relative(e,n).split(sep).join("/");try{return Et(t)}catch{return null}}function fl(e){if(!tl.test(e.appId))return {diagnostic:Z("BUILTIN_INVALID","builtin",`builtin/${e.appId||"unknown"}`)};let n=e.definition===void 0?void 0:{id:e.definition.id,version:e.definition.version,hash:e.definition.hash,usage:e.definition.usage??xe,...e.definition.detailPanel===void 0?{}:{detailPanel:e.definition.detailPanel},...e.definition.displayModes===void 0?{}:{displayModes:e.definition.displayModes},...e.definition.summaryProjection===void 0?{}:{summaryProjection:e.definition.summaryProjection}},t=n?.hash??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 yl(e){return e.builtinCatalog}function Al(e){let n=e.packageRoot??e.relativePath??e.packageRootPath;if(n===void 0)return null;try{return Et(n)}catch{return null}}function Il(e){let n=e.marketplaceContentId;return typeof n=="string"&&n.length>0?n:void 0}function gl(e,n,t){let i=n.installed??[],o=new Map;for(let s of i){let a=Al(s);if(!a){t.push(Z("INSTALLED_IDENTITY_MISMATCH","installed","installed"));continue}let c=o.get(a);if(c&&JSON.stringify(c)!==JSON.stringify(s)){t.push(Z("INSTALLED_IDENTITY_MISMATCH","installed",a));continue}o.set(a,s);}let r=new Map;for(let s of e)s.packageRoot!==void 0&&r.set(s.packageRoot,s);for(let[s,a]of o){let c=r.get(s);if(!c){t.push(Z("INSTALLED_MISSING","installed",s,a.appId));continue}let d=Il(a);if(!d){t.push(Z("INSTALLED_CONTENT_ID_MISSING","installed",s,a.appId));continue}if(a.appId!==void 0&&a.appId!==c.appId||a.definitionHash!==void 0&&a.definitionHash!==c.summary.definitionHash){t.push(Z("INSTALLED_IDENTITY_MISMATCH","installed",s,a.appId));continue}let l={...c.summary,origin:"installed",...a.slug===void 0?{}:{slug:a.slug},marketplaceContentId:d},p=e.indexOf(c);p>=0&&(e[p]={...c,summary:Object.freeze(l)});}}function ml(e,n){let t=new Map;for(let o of e){let r=t.get(o.appId)??[];r.push(o),t.set(o.appId,r);}let i=new Set;for(let o of t.values()){if(o.length<2)continue;let r=o.some(s=>s.source==="builtin")?"builtin":o.some(s=>s.source==="bundled")?"bundled":void 0;if(r==="bundled"){let s=o.filter(a=>a.source==="apps"&&a.summary.definition!==void 0);if(s.length===1){for(let a of o)a.source==="bundled"?i.add(a):a!==s[0]&&(i.add(a),n.push(Z("RESERVED_ID",a.source,ht(a),a.appId)));continue}}if(r!==void 0){let s=o.filter(a=>a.source===r);for(let a of o.filter(c=>c.source!==r))i.add(a),n.push(Z("RESERVED_ID",a.source,ht(a),a.appId));if(s.length>1)for(let a of s)i.add(a),n.push(Z("DUPLICATE_ID",a.source,ht(a),a.appId));continue}for(let s of o)i.add(s),n.push(Z("DUPLICATE_ID",s.source,ht(s),s.appId));}return e.filter(o=>!i.has(o))}function ht(e){return e.packageRoot??e.summary.provenance?.packageDir??`builtin/${e.appId}`}function hl(e,n){return e.filter(t=>!(t.code==="MANIFEST_MISSING"&&n.has(t.relativePath))).map(ps)}function _l(e){return e.filesystem}function El(e,n){let t=_l(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 ls(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=yl(n),i=await is(e,El(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 A of r)for(let h of zo([A])){let E=as(e,h.dir);(E===null||!d.has(E))&&(c.push(h),E!==null&&d.add(E));}for(let A of c){let h=ll(e,A);"diagnostic"in h?s.push(h.diagnostic):a.push(h);}let l=new Map,p=n.registeredProductBundle?.indexHash,u=(n.registeredProductBundle?.candidates??[]).filter(A=>p!==void 0&&A.provenance?.indexHash===p),f=[...new Set([...i.apps??i.candidates??[],...i.productBundleSnapshotMetadata?.candidates??[]]),...u],g=new Set(u),_=new Set(p===void 0?[]:(t?.listMcpApps()??[]).filter(A=>A.provenance?.indexHash===p).map(A=>A.appId));for(let A of f){if(g.has(A)&&A.provenance?.indexHash===p&&_.has(A.appId))continue;let h=A.provenance===void 0?`workspace\0${A.relativePath}`:`bundled\0${A.provenance.indexHash}\0${A.provenance.packageDir}`;l.set(h,{candidate:A,packageRoot:A.relativePath});}let P=new Map(a.map(A=>[A.packageRoot,A])),U=[];for(let A of l.values()){let h=A.candidate.provenance===void 0?P.get(A.packageRoot):void 0,E=al(A,h);U.push({...E.packageRoot===void 0?{}:{packageRoot:E.packageRoot},source:E.source,appId:E.appId,summary:E.summary});}let k=new Set([...l.values()].filter(A=>A.candidate.provenance===void 0).map(A=>A.packageRoot)),D=o===void 0?new Set:new Set(i.diagnostics.filter(A=>A.code==="RESERVED_ID"&&A.source!=="bundled").map(A=>A.relativePath)),w=new Set(o?.reservedAppIds??[]);for(let A of a){let h=cl(A);if(!(k.has(A.packageRoot)||D.has(A.packageRoot))){if(w.has(h.appId)){s.push(Z("RESERVED_ID",A.source,A.packageRoot,h.appId));continue}U.push({packageRoot:h.packageRoot,source:h.source,appId:h.appId,summary:h.summary});}}let B=[...hl(i.diagnostics,new Set(a.map(A=>A.packageRoot))),...s,...n.registeredProductBundle?.diagnostics.filter(A=>A.source==="bundled").map(ps)??[]],N=[];if(t)for(let A of t.listMcpApps()){let h=fl(A);"diagnostic"in h?B.push(h.diagnostic):N.push(h);}let b=ml([...U,...N],B);gl(b,n,B);let L=b.map(A=>A.summary).sort((A,h)=>mt(A.appId,h.appId)),I=[...B].sort((A,h)=>mt(A.relativePath,h.relativePath)||mt(A.code,h.code)||mt(A.appId??"",h.appId??""));return Object.freeze({items:Object.freeze(L),diagnostics:Object.freeze(I)})}m();m();m();function Tl(e){let n=o=>o.replace(/[.+^${}()|[\]\\]/g,"\\$&"),i=e.split("/").map(o=>o==="**"?".*":o.split("*").map(n).join("[^/]*"));return new RegExp(`^${i.join("\\/")}$`)}function fn(e,n){try{return Tl(n).test(e)}catch{return false}}function Tt(e,...n){let t=e.split("/");if(t.length<n.length)return false;let i=t.length-n.length;return n.every((o,r)=>fn(t[i+r],o))}function Pl(e,n){return e.split("/").some(t=>fn(t,n))}var us=[{label:".env*",test:e=>fn(e,".env*")},{label:".git/",test:(e,n,t)=>t&&e===".git"},{label:"memory/",test:(e,n,t)=>t&&e==="memory"},{label:"*.key",test:e=>fn(e,"*.key")},{label:"*.pem",test:e=>fn(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&&Tt(n,".crewx","threads")},{label:".crewx/crewx.db",test:(e,n,t)=>!t&&Tt(n,".crewx","crewx.db")},{label:".crewx/*.log",test:(e,n,t)=>!t&&Tt(n,".crewx","*.log")},{label:".crewx/publish/",test:(e,n,t)=>t&&Tt(n,".crewx","publish")},{label:".crewx/",test:(e,n)=>Pl(n,".crewx")}];function yn(e,n,t){for(let i of us)if(i.test(e,n,t))return i.label;return null}m();var we=class extends Error{constructor(t,i){super(`publish: [${t}]${i?` ${i}`:""}`);this.code=t;}code;name="PublishError"};function T(e,n){return new we(e,n)}function fs(e,n){if(!n||/[\\\u0000]/.test(n)||de.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=de.resolve(e),i=de.resolve(t,...n.split("/"));if(!i.startsWith(`${t}${de.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=de.join(r,f),s=s?`${s}/${f}`:f,o(r,s),a??=yn(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=de.join(f,P.name);if(P.isSymbolicLink())throw T("PACKAGE_SYMLINK",`symlink is not publishable: ${U}`);let D=yn(P.name,U,P.isDirectory());D?d.push({path:U,rule:D}):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 ys(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=de.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??yn(c.name,d,false);u?t.push({path:d,rule:u}):t.push({path:d,rule:"symlink"});continue}if(c.isDirectory()){let p=s??yn(c.name,d,true);i(l,d,p);continue}if(c.isFile()){let p=s??yn(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 Dl=[{rule:"token-prefix",regex:/\b(?:sk-|ghp_|xoxb-)[A-Za-z0-9_-]{10,}/},{rule:"private-key",regex:/-----BEGIN [A-Z ]*PRIVATE KEY-----/},{rule:"aws-access-key",regex:/\bAKIA[0-9A-Z]{16}\b/}];function Nl(e){return e.includes(0)}function xi(e,n,t){let i=[];for(let o of n){let r=de.join(e,o),s;try{let c=t?.get(o);s=c===void 0?ne.readFileSync(r):Buffer.from(c);}catch{continue}if(Nl(s))continue;s.toString("utf8").split(/\r\n|\r|\n/).forEach((c,d)=>{for(let{rule:l,regex:p}of Dl)p.test(c)&&i.push({path:o,line:d+1,rule:l});});}return i}m();var gs=/^[a-z0-9-]+$/,bl=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/,Sl=/^[A-Za-z_][A-Za-z0-9_]*$/;function Ml(e){let n=de.join(e,"crewx.yaml");if(!ne.existsSync(n))return {};let t;try{t=ms.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 Ll(e){return vi.createHash("sha256").update(e).digest("hex")}function hs(e){let n;try{n=ne.lstatSync(e);}catch{throw T("PACKAGE_FILE_INVALID",`file is not readable: ${de.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 vi.createHash("sha256").update(new Uint8Array(ne.readFileSync(e))).digest("hex")}function Rl(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 _s(e){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||de.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 Ol(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 Es(e){if(!bl.test(e))throw new Error(`publish: invalid version "${e}" \u2014 must be semver (e.g. 1.0.0)`)}function Ts(e,n,t={}){let i=Ml(e),o=i.name??de.basename(e);if(!gs.test(o))throw new Error(`publish: invalid name "${o}" \u2014 must match ${gs} (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");Es(r);let s=Array.isArray(i.requiredEnv)?i.requiredEnv:[],a=[];for(let l of s){if(typeof l!="string"||!Sl.test(l))throw new Error(`publish: requiredEnv must contain names only (no values), got "${String(l)}"`);a.push(l);}let c=n.map(l=>(_s(l),{path:l,sha256:hs(de.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 wl(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 Ps(e,n){if(Ol(n.packageRoot),!n.version)throw new Error("publish: version is required for App publishing \u2014 pass opts.version");if(Es(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(_s(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?hs(de.join(e,s)):Ll(a),...a===void 0?{}:{generated:true}}}).sort((s,a)=>Rl(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:wl(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 Ds(e){return vi.createHash("sha256").update(e).digest("hex")}function Ls(e,n){if(typeof n!="string"||n.length===0||n.includes("\\")||n.includes("\0")||de.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=de.resolve(e),i=de.resolve(t,...n.split("/"));if(i!==t&&!i.startsWith(`${t}${de.sep}`))throw T("PACKAGE_PATH_TRAVERSAL","archive path escaped its root");return i}function Ns(e,n){let t=Ls(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 Rs(e,n,t={}){let i=de.join(e,".crewx","publish");ne.mkdirSync(i,{recursive:true});let o=de.join(i,`${n.name}-${n.version}.tgz`),r=de.join(i,`.${n.name}-${n.version}.${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}.tmp.tgz`),s=ne.mkdtempSync(de.join(bs.tmpdir(),"crewx-publish-"));try{let a=new Set,c=[];for(let d of n.files){if(a.has(d.path))throw T("PACKAGE_PATH_TRAVERSAL","manifest contains duplicate file paths");a.add(d.path);let l=t.generatedFiles?.get(d.path);if(d.generated===!0&&l===void 0)throw T("PACKAGE_GENERATED_FILE_MISSING","generated manifest file bytes are missing");if(t.sourceFileHashes?.has(d.path)){let f=Ns(e,d.path);if(t.sourceFileHashes.get(d.path)!==Ds(f))throw T("PACKAGE_STAGED_BYTES_MISMATCH","workspace source changed before staging")}let p=l??Ns(e,d.path);if(Ds(p)!==d.sha256)throw T("PACKAGE_STAGED_BYTES_MISMATCH",`staged bytes differ for ${d.path}`);let u=Ls(s,d.path);ne.mkdirSync(de.dirname(u),{recursive:!0}),ne.writeFileSync(u,new Uint8Array(p)),c.push(d.path);}ne.writeFileSync(de.join(s,"manifest.json"),JSON.stringify(n,null,2)),await Ms.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 An="/api/v1";var kl=201,xl=200,vl=409,Fi=401,Os={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 Fl(){return process.env.WI013_FAKE_UPLOAD==="1"}function jl(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 Vl(e){return e.replace(/\/+$/,"")}async function Fn(e){try{return await e.json()}catch{return null}}function ws(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 Bl(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 Hl(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 Cs(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(Os,r))continue;let s=r,a=s==="APP_NAME_CONFLICT"?`marketplace name is already in use: ${n}`:void 0;return T(Os[s],a)}}async function zl(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=Vl(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}${An}/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 Fn(a),d=Bl(c),l=Hl(c),p=r&&l!==void 0?l:i,u;if(a.status===kl)u="created";else if(r&&a.status===xl){if(d===void 0)throw T("PUBLISH_CONTENT_ID_MISSING","App republish did not return an opaque contentId");u="existing";}else if(a.status===vl){if(r)throw Cs(c,i)??T("APP_NAME_CONFLICT",`marketplace name is already in use: ${i}`);u="existing";}else throw a.status===Fi?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}${An}/publisher/items`,{method:"GET",headers:{Authorization:`Bearer ${e.accessToken}`}});}catch{throw new Error("publish: [E_NETWORK] Publisher items request failed (network)")}let L=await Fn(b);if(b.status!==200)throw new Error(`publish: [E_HTTP] Publisher items request failed \u2014 HTTP ${b.status}`);let A=ws(L,"publisher items",b.status)?.items;if(!Array.isArray(A))throw new Error(`publish: [E_MALFORMED] Publisher items response is malformed (expected data.items[]) \u2014 HTTP ${b.status}`);let h=A.find(E=>!E||typeof E!="object"?false:E.slug===i);if(!h||typeof h.version!="string")throw new Error(`publish: [E_MALFORMED] Publisher items response does not contain slug "${i}" \u2014 HTTP ${b.status}`);if(g=h.version,g!==e.manifest.version){let E;try{E=await fetch(`${n}${An}/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 Fn(E),E.status===Fi?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=Fl()?jl(_):_,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,D;try{D=await fetch(`${n}${An}/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(D.status===Fi)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 Fn(D);if(r){let L=Cs(b,p);if(L)throw L}throw new Error(`publish: [E_HTTP] Upload request failed \u2014 HTTP ${D.status}`)}let w=await Fn(D),B=ws(w,"upload",D.status),N=typeof B.contentId=="string"&&B.contentId.length>0?B.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:B.artifactChecksum,artifactSizeBytes:B.artifactSizeBytes,submitOutcome:u,versionUpdate:f,serverVersionBefore:g}}var $l=1e4,Gl=100*1024*1024;function ji(e){return vi.createHash("sha256").update(e).digest("hex")}function Wl(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function He(e,n){if(!n||n.includes("\\")||n.includes("\0")||de.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=de.resolve(e,...n.split("/")),i=de.resolve(e);if(t!==i&&!t.startsWith(`${i}${de.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))}async function Jl(e,n,t){let i=`${n}/${G}`;if(!t.includes(i))return [];let o={[G]:He(e,i)},r=`${n}/${z}`;t.includes(r)&&(o[z]=He(e,r));let s=je(o,{mode:"local"});if(!s.ok)return [];let{diagnostics:a}=await En(s.mcpb?.icon,async d=>{let l=`${n}/${d}`;return t.includes(l)?He(e,l):"missing"}),c=a.find(d=>d.code==="ICON_INVALID");if(c!==void 0)throw T("ICON_INVALID",`${c.reason??"invalid"} at ${c.declared??"icon"}`);return a.flatMap(d=>d.code==="ICON_INVALID"?[]:[{code:d.code,path:d.declared??"icon"}])}function ks(e,n,t){let i=e??n;if(!Number.isSafeInteger(i)||i<=0)throw new we("PACKAGE_SIZE_LIMIT",`${t} must be a positive integer`);return i}function vs(e,n,t,i){let o=ks(t.maxFileCount??t.maxFiles,$l,"max file count"),r=ks(t.maxTotalBytes??t.maxBytes,Gl,"max total bytes");if(n.length>o)throw new we("PACKAGE_SIZE_LIMIT",`package exceeds file count limit (${o})`);let s=0;for(let a of n){let c=i?.get(a);if(c!==void 0?s+=c.byteLength:s+=He(e,a).byteLength,s>r)throw new we("PACKAGE_SIZE_LIMIT",`package exceeds byte limit (${r})`)}}function Kl(e){return e.appId!==void 0||e.expectedDefinitionHash!==void 0}function Xl(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 Yl(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 ql(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 Vi(e){let{path:n,rule:t}=e.reason;return `${e.code} at ${n===""?"<file>":n} (${t})`+(e.files.length>0?` [${e.files.join(", ")}]`:"")}function Zl(e,n,t){let i=je({[pe]:t},{mode:"published"});if(!i.ok)throw T("APP_UI_MANIFEST_INVALID",`generated ${pe} does not read: ${Vi(i.rejection)}`);if(cn(i.manifest)!==cn(n))throw T("APP_UI_MANIFEST_INVALID",`generated ${pe} normalizes to a different definition hash than the source`);let o=e[G];if(o===void 0)return;let r=e[z],s=je({[G]:o,[pe]:t,...r===void 0?{}:{[z]:r}},{mode:"local"});if(!s.ok)throw T("APP_UI_MANIFEST_INVALID",Vi(s.rejection))}function Ql(e,n,t,i){let o={};for(let f of Q){let g=`${t}/${f}`;i.includes(g)&&(o[f]=He(e,g));}let r=`${t}/${z}`;if(o[G]!==void 0&&i.includes(r)&&(o[z]=He(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=je(o,{mode:"local"});if(!s.ok)throw T("APP_UI_MANIFEST_INVALID",Vi(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[pe],c=a===void 0?void 0:ji(a),d=`${t}/ui/index.html`;if(!i.includes(d))throw T("APP_UI_MANIFEST_INVALID","screen entry is outside package scope");let l=ji(He(e,d)),p=JSON.parse(JSON.stringify(s.v2Input));if(p.entryHash=l,Object.prototype.hasOwnProperty.call(p,"initialState")){let f=p.initialState;if(!Wl(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 _=He(e,g);p.initialState={...f,hash:ji(_)};}let u;try{let f=Je(p,{mode:"published"});u=new Uint8Array(Buffer.from(JSON.stringify(f),"utf8"));}catch(f){throw f instanceof ce?T("APP_UI_MANIFEST_INVALID",f.code):T("APP_UI_MANIFEST_INVALID")}return Zl(o,s.manifest,u),{bytes:u,...c===void 0?{}:{legacySourceHash:c}}}async function eu(e,n){let{included:t,excluded:i}=ys(e);vs(e,t,n);let o=Ts(e,t,{version:n.version}),r=xi(e,t);return {plan:{manifest:o,included:t,excluded:i,secretFindings:r},archiveOptions:{}}}async function nu(e,n){Xl(n);let t=await ls(e),i=Yl(t.items,n.appId);if(i.definitionHash!==n.expectedDefinitionHash)throw T("APP_DEFINITION_CONFLICT",`definitionHash changed for ${n.appId}`);let o=ql(i),{included:r,excluded:s}=fs(e,o),a=await Jl(e,o,r),c=new Map,d=new Map;if(i.capabilities.includes("screen")){let f=Ql(e,i,o,r),g=`${o}/${pe}`;if(c.set(g,f.bytes),f.legacySourceHash!==void 0)d.set(g,f.legacySourceHash);else {r.push(g);let _=new TextEncoder;r.sort((P,U)=>Buffer.compare(_.encode(P),_.encode(U)));}}if(i.capabilities.includes("skill")&&!r.includes(`${o}/SKILL.md`))throw T("APP_SKILL_MISSING","skill capability requires package-root SKILL.md");vs(e,r,n,c);let l={appId:i.appId,version:n.version??"",description:i.description,capabilities:i.capabilities,packageRoot:o,...i.definition?.id===void 0?{}:{definitionId:i.definition.id},definitionHash:i.definitionHash,includedFiles:r,generatedFiles:c},p=Ps(e,l),u=xi(e,r,c);return {plan:{manifest:p,included:r,excluded:s,secretFindings:u,warnings:a},archiveOptions:{generatedFiles:c,sourceFileHashes:d}}}async function Fs(e,n){let t=de.resolve(e);if(Kl(n))return nu(t,n);if(n.expectedDefinitionHash!==void 0)throw T("APP_ID_REQUIRED");return eu(t,n)}async function uI(e,n={}){return (await Fs(e,n)).plan}function tu(e){let n=e.map(t=>`${t.path}:${t.line} (${t.rule})`).join(", ");throw new we("PUBLISH_SECRET_FINDINGS",`aborted \u2014 secret findings must be resolved before packing: ${n}`)}async function js(e,n={}){let t=de.resolve(e),i=await Fs(t,n);i.plan.secretFindings.length>0&&tu(i.plan.secretFindings);let o=await Rs(t,i.plan.manifest,i.archiveOptions);return {manifest:i.plan.manifest,tgzPath:o}}async function fI(e,n={}){return js(e,n)}async function yI(e,n){let t=await js(e,n);if(t.manifest.type!=="app")throw new Error("publish: App pack unexpectedly produced a template manifest");return t}
|
|
2
|
+
export{Gl as DEFAULT_PUBLISH_MAX_BYTES,$l as DEFAULT_PUBLISH_MAX_FILES,us as EXCLUDE_RULES,An as MARKETPLACE_API_PREFIX,we as PublishError,yI as packApp,js as packPublish,fI as packTemplate,uI as planPublish,zl as uploadToMarketplace};
|