@crewx/sdk 0.9.0-rc.174 → 0.9.0-rc.175

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.
Files changed (46) hide show
  1. package/dist/desktop/index.js +3 -3
  2. package/dist/esm/desktop/index.js +3 -3
  3. package/dist/esm/index.js +388 -259
  4. package/dist/esm/plugins/index.js +95 -91
  5. package/dist/esm/process/index.js +1 -1
  6. package/dist/esm/publish/index.js +2 -2
  7. package/dist/esm/repository/index.js +334 -201
  8. package/dist/esm/skills/index.js +2 -2
  9. package/dist/index.browser.js +1 -1
  10. package/dist/index.d.ts +9 -0
  11. package/dist/index.js +377 -248
  12. package/dist/lifecycle/task-stop.d.ts +27 -1
  13. package/dist/lifecycle/update-admission.d.ts +1 -1
  14. package/dist/mcp-app/types.d.ts +1 -1
  15. package/dist/migrations/0042_breezy_blue_shield.sql +31 -0
  16. package/dist/migrations/0043_nervous_darkstar.sql +1 -0
  17. package/dist/migrations/0044_military_galactus.sql +8 -0
  18. package/dist/migrations/0045_task_pid_started_at.sql +1 -0
  19. package/dist/migrations/meta/0042_snapshot.json +4383 -0
  20. package/dist/migrations/meta/0043_snapshot.json +4390 -0
  21. package/dist/migrations/meta/0044_snapshot.json +4435 -0
  22. package/dist/migrations/meta/0045_snapshot.json +4442 -0
  23. package/dist/migrations/meta/_journal.json +28 -0
  24. package/dist/plugins/index.js +99 -95
  25. package/dist/process/index.d.ts +2 -2
  26. package/dist/process/index.js +1 -1
  27. package/dist/process/process-control.d.ts +14 -0
  28. package/dist/publish/index.js +2 -2
  29. package/dist/repository/db.d.ts +1 -0
  30. package/dist/repository/index.d.ts +7 -0
  31. package/dist/repository/index.js +292 -159
  32. package/dist/repository/run-columns.d.ts +10 -0
  33. package/dist/repository/run-history.repository.d.ts +112 -0
  34. package/dist/repository/schedule-run.repository.d.ts +103 -0
  35. package/dist/repository/task.repository.d.ts +13 -2
  36. package/dist/repository/workflow-anchor-kinds.d.ts +4 -0
  37. package/dist/schema/index.d.ts +2 -0
  38. package/dist/schema/run-column-backfill.d.ts +81 -0
  39. package/dist/schema/schedule-runs.d.ts +451 -0
  40. package/dist/schema/tasks.d.ts +114 -0
  41. package/dist/skills/index.js +2 -2
  42. package/dist/ui-plugin/html-viewer-document-policy.d.ts +23 -0
  43. package/dist/ui-plugin/index.d.ts +2 -0
  44. package/dist/ui-plugin/types.d.ts +1 -0
  45. package/dist/utils/id.d.ts +1 -1
  46. package/package.json +1 -1
@@ -1,2 +1,2 @@
1
- import*as de from'path';import {resolve,relative,sep,isAbsolute,join}from'path';import'url';import*as Bi from'crypto';import {createHash}from'crypto';import {isIP}from'net';import*as te from'fs';import {constants,readFileSync,existsSync,statSync,readdirSync}from'fs';import {realpath,stat,readdir,open,lstat}from'fs/promises';import*as Ps from'js-yaml';import {load}from'js-yaml';import*as Rs from'os';import*as Cs from'tar';import {gunzipSync,gzipSync}from'zlib';var F=(e,n)=>()=>(e&&(n=e(e=0)),n);var m=F(()=>{});var x,Fn=F(()=>{m();x=class extends Error{constructor(t,i=t,o){super(i);this.code=t;this.currentRevision=o;}code;currentRevision;name="UiRuntimeError"};});function Ot(e){return Gs.test(e)||Js.test(e)}function fe(){throw new x("INPUT_INVALID","JSON value is not projection-safe")}function Ys(e){let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function Mt(e,n,t,i,o,r){if(n>i&&fe(),e===null||typeof e=="string"||typeof e=="boolean")return typeof e=="string"&&(Ws.test(e)||Xs.test(e)&&!Qs(o,r)||Ks.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=>Mt(c,n+1,t,i,o,r));Ys(s)||fe();let a={};for(let[c,d]of Object.entries(e))Ot(c)&&fe(),a[c]=Mt(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>Zs)&&fe(),(!Array.isArray(t)||t.some(o=>typeof o!="string"))&&fe();let i=Mt(e,0,new Set,qs+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 Qs(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 Lt(e){return Array.isArray(e)?e.map(Lt):e!==null&&typeof e=="object"?Object.fromEntries(Object.keys(e).sort().map(n=>[n,Lt(e[n])])):e}function ie(e){return nn(Lt(e))}function Rt(e){return Buffer.byteLength(e,"utf8")}var Gs,Js,Ws,Ks,Xs,qs,Zs,Le=F(()=>{m();Fn();Gs=/(?:proof|token|secret|password|cookie|authorization|private[_-]?key|stack|exception|plugin[_-]?text)/i,Js=/(?:url|uri|endpoint|path|file(?:name|path)?|cwd|shell|directory|dir|folder)$/i,Ws=/<\/?[A-Za-z][^>]*>/,Ks=/^(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)/,Xs=/^(?:https?|file|ftp|ws|wss):\/\//i;qs=8,Zs=4;});var Gi=F(()=>{m();Le();});var Vn,wt=F(()=>{m();Vn=["text/plain","application/json"];});var Ji=F(()=>{m();wt();});function tn(e){return na.has(e)||ta.test(e)||ia.test(e)}var Wi,na,ta,ia,Bn,In,Pe,Ct,Ut,kt,xt,vt,$e=F(()=>{m();Wi=["__proto__","prototype","constructor","proof","token","secret","password","cookie","authorization","private_key","private-key","stack","exception","plugin_text","url","uri","endpoint","path","filename","filepath","cwd","shell","directory","dir","folder"],na=new Set(Wi),ta=/(?:proof|token|secret|password|cookie|authorization|private[_-]?key|stack|exception|plugin[_-]?text)/i,ia=/(?: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_]+)*$/,Pe=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,Ct=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/,Ut=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,kt=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/,xt=["blue","violet","emerald","amber","rose","sky","slate","indigo"],vt=["inline","panel"];});function jt(e){return typeof e=="string"&&Vn.includes(e)}var Ki=F(()=>{m();wt();$e();});function Hn(e){if(!Ft(e))return false;let n=Object.keys(e);return !(n.some(t=>t!=="in"&&t!=="out")||n.length===0||Object.hasOwn(e,"in")&&!oa(e.in)||Object.hasOwn(e,"out")&&!ra(e.out))}function oa(e){return Ft(e)?Object.keys(e).every(t=>t==="mediaType"||t==="required")&&Object.hasOwn(e,"mediaType")&&jt(e.mediaType)&&(!Object.hasOwn(e,"required")||typeof e.required=="boolean"):false}function ra(e){return Ft(e)?Object.keys(e).every(t=>t==="mediaType"||t==="range")&&Object.hasOwn(e,"mediaType")&&jt(e.mediaType)&&(!Object.hasOwn(e,"range")||typeof e.range=="boolean"):false}function Ft(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=F(()=>{m();Ji();Ki();new TextDecoder("utf-8",{fatal:true,ignoreBOM:true});});function $n(e){return sa.includes(e)}function Gn(e){return Number.isSafeInteger(e)&&e>=zn.min&&e<=zn.max}var sa,zn,Xi,Bt=F(()=>{m();sa=[5,15,30,60],zn=Object.freeze({min:15e3,max:6e5,default:3e5}),Xi=1;});function Wn(e){return Number.isSafeInteger(e)&&e>=Jn.min&&e<=Jn.max}function Kn(e){return aa.includes(e)}var Jn,Yi,aa,Ht=F(()=>{m();Jn=Object.freeze({min:6e4,max:18e5,default:6e5}),Yi=1,aa=["start","status","cancel"];});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.downloads!==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.downloads===void 0?{}:{downloads:e.downloads},...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 $t(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"||!da.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=>!la(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&&zt(t.resultProjection),t.schedule!==void 0&&(!$n(t.schedule.everyMinutes)||!Gn(t.schedule.timeoutMs)))throw new x("DEFINITION_UNSUPPORTED","UI action schedule declaration is invalid");if(t.job!==void 0&&(typeof t.job!="object"||Object.keys(t.job).some(i=>i!=="deadlineMs")||!Wn(t.job.deadlineMs)))throw new x("DEFINITION_UNSUPPORTED","UI action job declaration is invalid");if(t.jobAccess!==void 0&&(!Array.isArray(t.jobAccess)||t.jobAccess.length===0||new Set(t.jobAccess).size!==t.jobAccess.length||!t.jobAccess.every(Kn)||t.job!==void 0))throw new x("DEFINITION_UNSUPPORTED","UI action job control declaration is invalid");if(t.content!==void 0&&!Hn(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&&zt(e.stateProjection),e.summaryProjection){zt(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(pa(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.downloads!==void 0&&e.downloads!==true)throw new x("DEFINITION_UNSUPPORTED","UI definition downloads is invalid");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 x("DEFINITION_UNSUPPORTED","UI definition dataPaths are invalid")}}function pa(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(Rt(nn(c))>4*1024)throw new Error("fixed result size")}}catch{throw new x("DEFINITION_UNSUPPORTED","UI legacy tool metadata is not projection-safe")}}function zt(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 la(e){return e.length>0&&e.length<=128&&e!=="*"&&e!=="all"&&!/[/*]/.test(e)}var da,Ge=F(()=>{m();Le();Fn();Vt();Bt();Ht();da=/^[0-9a-f]{64}$/;});var G,Oe,Gt=F(()=>{m();G="dist/tools.json",Oe="dist/main.mjs";});var ve,Jt=F(()=>{m();ve="window";});function qi(e){if(!Array.isArray(e)||e.length===0)return false;let n=new Set;for(let t of e){if(!ua.some(i=>i===t)||n.has(t))return false;n.add(t);}return true}var ua,Zi=F(()=>{m();ua=["CREWX_APP_INSTANCE_ID","CREWX_THREAD_ID"];});function J(e){throw new Wt(e)}function ba(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 Na(e,n){let t=Object.getOwnPropertyDescriptor(e,n);return (!t||!("value"in t))&&J("CSP_ORIGIN_INVALID"),t.value}function Xn(e,n){if(!Object.prototype.hasOwnProperty.call(e,n))return [];let t=Na(e,n);Array.isArray(t)||J("CSP_ORIGIN_INVALID"),Reflect.ownKeys(t).some(r=>typeof r!="string"||r!=="length"&&!/^(?:0|[1-9][0-9]*)$/.test(r))&&J("CSP_ORIGIN_INVALID");let o=[];for(let r=0;r<t.length;r+=1)(!Object.prototype.hasOwnProperty.call(t,r)||typeof t[r]!="string")&&J("CSP_ORIGIN_INVALID"),o.push(t[r]);return Object.keys(t).length!==t.length&&J("CSP_ORIGIN_INVALID"),o}function Da(e){let n;try{n=JSON.stringify(e);}catch{J("CSP_ORIGIN_INVALID");}return n===void 0&&J("CSP_ORIGIN_INVALID"),new TextEncoder().encode(n).byteLength}function no(e,n){/\s|\\/u.test(e)&&J("CSP_ORIGIN_INVALID");let t=ha.exec(e);t||J("CSP_ORIGIN_INVALID");let i=t[1].toLowerCase(),o=t[2];(o.includes("@")||o.includes("%")||o.includes("*"))&&J("CSP_ORIGIN_INVALID"),(o.startsWith("[")?_a:Ea).test(o)||J("CSP_ORIGIN_INVALID"),i==="wss"&&n!=="connectDomains"&&J("CSP_ORIGIN_INVALID");let s;try{s=new URL(e);}catch{J("CSP_ORIGIN_INVALID");}(s.protocol!==`${i}:`||s.username!==""||s.password!==""||s.search!==""||s.hash!=="")&&J("CSP_ORIGIN_INVALID");let a=s.hostname.toLowerCase();if((!a||a.includes("%"))&&J("CSP_ORIGIN_INVALID"),!a.startsWith("[")){let d=a.endsWith(".")?a.slice(0,-1):a;(d.length===0||d.length>253)&&J("CSP_ORIGIN_INVALID"),d.split(".").some(p=>p.length>63||!Ta.test(p))&&J("CSP_ORIGIN_INVALID");}let c=s.origin;return (c==="null"||!c.startsWith(`${i}://`))&&J("CSP_ORIGIN_INVALID"),{origin:c,hostname:a}}function Sa(e){let n=e.split(".").map(Number);return ((n[0]*256+n[1])*256+n[2])*256+n[3]}function to(e,n,t){let i=4294967295<<32-t>>>0;return (e&i)===(n&i)}function ro(e){let n=Sa(e);return to(n,3221225472,24)?n!==3221225481&&n!==3221225482:Pa.some(([t,i])=>to(n,t,i))}function Ma(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 La(e){let n=Ma(e),t=Number(n>>112n),i=Number(n>>96n&0xffffn);if(n>>32n===0xffffn){let o=Number(n&0xffffffffn);return ro([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 Oa(e,n){let t=e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e,i=isIP(t);if(i===4)return ro(t);if(i===6)return La(t);let o=e.toLowerCase().replace(/\.$/,"");return !o||!o.includes(".")||n.has(o)?true:ma.some(r=>o===r||o.endsWith(`.${r}`))}function io(e){return Object.freeze([...new Set(e.map(n=>n.origin))].sort())}function oo(e){return JSON.stringify({baseUriDomains:[],connectDomains:e.connectDomains,declared:e.declared,frameDomains:e.frameDomains,resourceDomains:[]})}function so(e,n={}){if(e===void 0){let y=oo({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(y,"utf8").digest("hex")})}ba(e)||J("CSP_ORIGIN_INVALID");let t=Reflect.ownKeys(e);t.some(y=>typeof y!="string")&&J("CSP_ORIGIN_INVALID"),t.some(y=>!ga.has(y))&&J("CSP_AXIS_UNKNOWN");let i=Xn(e,"connectDomains"),o=Xn(e,"frameDomains"),r=Xn(e,"resourceDomains"),s=Xn(e,"baseUriDomains");(r.length>0||s.length>0)&&J("CSP_AXIS_UNSUPPORTED"),(Da(e)>ya||i.length>eo||o.length>eo||i.length+o.length>Aa||[...i,...o].some(y=>new TextEncoder().encode(y).byteLength>Ia))&&J("CSP_LIMIT_EXCEEDED");let c=i.map(y=>no(y,"connectDomains")),d=o.map(y=>no(y,"frameDomains")),l=new Set((n.runtimeHostnames??[]).map(y=>y.toLowerCase().replace(/\.$/,"")));[...c,...d].some(y=>Oa(y.hostname,l))&&J("CSP_ORIGIN_FORBIDDEN");let p={declared:true,connectDomains:io(c),frameDomains:io(d)},u=oo(p);return Object.freeze({...p,resourceDomains:Object.freeze([]),baseUriDomains:Object.freeze([]),cspHash:createHash("sha256").update(u,"utf8").digest("hex")})}var ya,eo,Aa,Ia,ga,ma,ha,_a,Ea,Ta,Pa,Wt,ao=F(()=>{m();ya=4096,eo=16,Aa=32,Ia=512,ga=new Set(["connectDomains","frameDomains","resourceDomains","baseUriDomains"]),ma=["localhost","local","internal","home.arpa","test","example","invalid","onion","lan","corp","home","intranet","private","localdomain"],ha=/^(https|wss):\/\/([^/?#]+)$/i,_a=/^\[[^\]]+\](?::[0-9]+)?$/,Ea=/^[^:\[\]]+(?::[0-9]+)?$/,Ta=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/,Pa=[[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]],Wt=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 f(e,n=e,t,i){throw new ce(e,n,t,i)}function $(e,n){try{return n()}catch(t){throw t instanceof ce?t.withPathPrefix(e):t}}function W(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;try{let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}catch{return false}}function C(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function pc(e,n){let t={};for(let[i,o]of Object.entries(e))n.includes(i)||(t[i]=o);return t}function Y(e,n,t=[]){let i=new Set([...n,...t]),o=Object.keys(e).find(s=>!i.has(s));o!==void 0&&f("MANIFEST_INVALID","MANIFEST_INVALID",o,"unknown-key");let r=n.find(s=>!C(e,s));r!==void 0&&f("MANIFEST_INVALID","MANIFEST_INVALID",r,"missing-key");}function Qn(e,n=false,t=false,i=false){return Ua.test(e)||!i&&xa.test(e)||ka.test(e)||t&&co.test(e)||va.test(e)&&!(n&&/^\s*data:/i.test(e)&&!co.test(e))}function Zn(e,n=new Set,t=0,i=false,o=false,r=""){if(typeof e=="string"){Qn(e,i,o)&&f("UNSAFE_VALUE","UNSAFE_VALUE",r,"unsafe-value");return}if(!(e===null||typeof e!="object")){(t>8||n.has(e))&&f("MANIFEST_INVALID","MANIFEST_INVALID",r),n.add(e);try{if(Array.isArray(e)){e.forEach((s,a)=>Zn(s,n,t+1,!1,!1,mn(r,`[${a}]`)));return}W(e)||f("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,mn(r,s));}finally{n.delete(e);}}}function be(e,n){let t=e[n];return typeof t!="string"&&f("MANIFEST_INVALID"),t}function ge(e,n,t){let i=e[n];return (!Number.isSafeInteger(i)||i<t)&&f("MANIFEST_INVALID"),i}function Kt(e){return Ca.test(e)||f("MANIFEST_INVALID"),e}function on(e){return wa.test(e)||f("TOKEN_INVALID"),e}function lc(e){return mo.test(e)||f("MANIFEST_INVALID"),e}function uc(e){W(e)||f("MANIFEST_INVALID");let n={};for(let[t,i]of Object.entries(e)){let o=lc(t);W(i)||f("MANIFEST_INVALID");let r=i.type;if(r==="text"){Y(i,["type","maxLength"]),n[o]={type:r,maxLength:ge(i,"maxLength",1)};continue}if(r==="text-list"){Y(i,["type","max","itemMaxLength"]),n[o]={type:r,max:ge(i,"max",0),itemMaxLength:ge(i,"itemMaxLength",1)};continue}if(r==="step-list"){Y(i,["type","min","max","labelMaxLength","detailMaxLength"]);let s=ge(i,"min",0),a=ge(i,"max",1);s>a&&f("MANIFEST_INVALID"),n[o]={type:r,min:s,max:a,labelMaxLength:ge(i,"labelMaxLength",1),detailMaxLength:ge(i,"detailMaxLength",1)};continue}typeof r=="string"&&f("SCHEMA_TYPE_UNSUPPORTED"),f("MANIFEST_INVALID");}return n}function fc(e,n,t){let i=e[n];(!i||i.type!==t)&&f("MANIFEST_INVALID");}function Yn(e,n,t){let i=be(e,"field");return mo.test(i)||f("MANIFEST_INVALID"),fc(n,i,t),i}function yc(e,n){W(e)||f("MANIFEST_INVALID");let t=e.primitive;switch(typeof t!="string"&&f("MANIFEST_INVALID"),dc.includes(t)||f("PRIMITIVE_UNKNOWN"),t){case "card-shell":return Y(e,["primitive"]),{primitive:t};case "meta-banner":return Y(e,["primitive","badgeToken","noticeToken"]),{primitive:t,badgeToken:on(be(e,"badgeToken")),noticeToken:on(be(e,"noticeToken"))};case "heading":return Y(e,["primitive","field"]),{primitive:t,field:Yn(e,n,"text")};case "labeled-text":return Y(e,["primitive","titleToken","field","variant"]),e.variant!=="callout"&&f("MANIFEST_INVALID"),{primitive:t,titleToken:on(be(e,"titleToken")),field:Yn(e,n,"text"),variant:"callout"};case "step-flow":return Y(e,["primitive","titleToken","field"]),{primitive:t,titleToken:on(be(e,"titleToken")),field:Yn(e,n,"step-list")};case "text-list":{Y(e,["primitive","titleToken","field"],["emptyToken","hideWhenEmpty"]);let i={primitive:t,titleToken:on(be(e,"titleToken")),field:Yn(e,n,"text-list")};return C(e,"emptyToken")&&(i.emptyToken=on(be(e,"emptyToken"))),C(e,"hideWhenEmpty")&&(typeof e.hideWhenEmpty!="boolean"&&f("MANIFEST_INVALID"),i.hideWhenEmpty=e.hideWhenEmpty),i}}return f("MANIFEST_INVALID")}function Ac(e,n){return Array.isArray(e)||f("MANIFEST_INVALID"),e.map(t=>yc(t,n))}function q(e="v2 manifest exceeds a contract limit",n,t){return f("LIMIT_EXCEEDED",e,n,t)}function Ie(e="initial state is not projection-safe"){return f("INITIAL_STATE_INVALID",e)}function po(e,n){return (typeof e!="string"||e.length===0||e.length>4096||e.trim().length===0||ic.test(e)||oc.test(e))&&f("MANIFEST_INVALID",`${n} is invalid`),(Qn(e,true,true)||ja.test(e)||Fa.test(e)||Va.test(e))&&f("UNSAFE_VALUE",`${n} contains an unsafe value`),e}function Xt(e,n){return (typeof e!="string"||!Pe.test(e))&&f("MANIFEST_INVALID",`${n} is invalid`),e}function Ic(e){return (typeof e!="string"||!Ct.test(e)||e==="*"||e==="all")&&f("MANIFEST_INVALID","action capability is invalid"),e}function ho(e){return (typeof e!="string"||!tc.test(e))&&f("MANIFEST_INVALID","resource hash is invalid"),e}function Yt(e,n=new Set,t=0,i=""){if(typeof e=="string"){e.length>4096&&q("v2 manifest string is too long",i,"string-too-long");return}if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){Number.isFinite(e)||f("MANIFEST_INVALID","v2 manifest contains a non-finite number",i,"non-finite-number");return}(e===void 0||typeof e=="function"||typeof e=="bigint")&&f("MANIFEST_INVALID","v2 manifest contains a non-JSON value",i,"non-json-value"),typeof e!="object"&&f("MANIFEST_INVALID","MANIFEST_INVALID",i),t>8&&q("v2 manifest nesting is too deep",i,"too-deep"),n.has(e)&&f("MANIFEST_INVALID","v2 manifest contains a cycle",i,"cycle"),n.add(e);try{if(Array.isArray(e)){e.length>128&&q("v2 manifest array is too long",i,"array-too-long"),e.forEach((o,r)=>Yt(o,n,t+1,mn(i,`[${r}]`)));return}W(e)||f("MANIFEST_INVALID","v2 manifest contains a non-plain object",i,"non-plain-object");for(let[o,r]of Object.entries(e))Yt(r,n,t+1,mn(i,o));}finally{n.delete(e);}}}function _o(e){return (typeof e!="string"||e.length>4096||!In.test(e))&&(typeof e=="string"&&e.length>4096&&q("projection path is too long"),f("MANIFEST_INVALID","projection paths must be canonical exact paths")),e.split(".").some(t=>tn(t))&&f("MANIFEST_INVALID","projection paths cannot address reserved state keys"),e}function qt(e){W(e)||f("MANIFEST_INVALID","projection policy must be an object"),Y(e,["allow"]),Array.isArray(e.allow)||f("MANIFEST_INVALID","projection allow must be an array"),e.allow.length>128&&q("projection allowlist is too long");let n=[],t=new Set;for(let i of e.allow){let o=_o(i);t.has(o)&&f("MANIFEST_INVALID","projection allowlist contains a duplicate path"),t.add(o),n.push(o);}return {allow:n}}function gc(e,n){if(e===void 0)return;Array.isArray(e)||f("MANIFEST_INVALID","dataPaths must be an array"),e.length>rc&&q("dataPaths exceed the v2 limit");let t=[],i=new Set;for(let o of e){let r=_o(o);i.has(r)&&f("MANIFEST_INVALID","dataPaths contain a duplicate path"),n.some(s=>en(r,s))||f("MANIFEST_INVALID","dataPaths must be projection-allowed"),i.add(r),t.push(r);}return t}function mc(e){Array.isArray(e)||f("MANIFEST_INVALID","deviceFeatures must be an array",void 0,"array"),e.length>sc&&f("MANIFEST_INVALID","deviceFeatures allow at most 16 names",void 0,"too-many-items");let n=[],t=new Set;for(let[i,o]of e.entries()){let r=`[${i}]`;typeof o!="string"&&f("MANIFEST_INVALID","a device feature name must be a string",r,"string"),o.length===0&&f("MANIFEST_INVALID","a device feature name must not be empty",r,"empty"),o.length>ac&&f("MANIFEST_INVALID","a device feature name is at most 32 characters",r,"too-long"),cc.test(o)||f("MANIFEST_INVALID","a device feature name starts with a lowercase letter and holds only letters and digits",r,"format"),t.has(o)&&f("MANIFEST_INVALID","deviceFeatures contain a duplicate name",r,"duplicate-item"),t.add(o),n.push(o);}return n}function hc(e){if(e!==false)return e!==true&&f("MANIFEST_INVALID","downloads must be true or false",void 0,"boolean"),true}function rn(e,n,t=Number.MAX_SAFE_INTEGER){return (!Number.isSafeInteger(e)||e<0||e>t)&&f("MANIFEST_INVALID",`${n} is invalid`),e}function lo(e,n){return (typeof e!="number"||!Number.isFinite(e))&&f("MANIFEST_INVALID",`${n} is invalid`),e}function Zt(e,n=0,t=new Set){if(typeof e=="string")return (e.length>4096||Qn(e))&&f("UNSAFE_VALUE","schema enum contains an unsafe string"),e;if(e===null||typeof e=="boolean")return e;if(typeof e=="number")return Number.isFinite(e)||f("MANIFEST_INVALID","schema enum contains a non-finite number"),e;(n>8||typeof e!="object"||e===void 0)&&q("schema enum is too deep"),t.has(e)&&f("MANIFEST_INVALID","schema enum contains a cycle"),t.add(e);try{if(Array.isArray(e))return e.length>128&&q("schema enum array is too long"),e.map(o=>Zt(o,n+1,t));W(e)||f("MANIFEST_INVALID","schema enum contains a non-plain object");let i={};for(let[o,r]of Object.entries(e))tn(o)&&f("MANIFEST_INVALID","schema enum contains a reserved key"),i[o]=Zt(r,n+1,t);return i}finally{t.delete(e);}}function _c(e,n){if(e===void 0)return;Array.isArray(e)||f("MANIFEST_INVALID","schema required must be an array"),e.length>64&&q("schema required list is too long");let t=[],i=new Set;for(let o of e)(typeof o!="string"||!In.test(o))&&f("MANIFEST_INVALID","schema required contains an invalid key"),o.length>4096&&q("schema required key is too long"),i.has(o)&&f("MANIFEST_INVALID","schema required contains a duplicate key"),n&&!Object.prototype.hasOwnProperty.call(n,o)&&f("MANIFEST_INVALID","schema required references an undeclared property"),i.add(o),t.push(o);return t}function Ec(e,n){let t=n?In:Bn;return e.length>4096&&q("schema property name is too long"),(!t.test(e)||e.split(".").some(i=>tn(i)))&&f("MANIFEST_INVALID","schema property name is invalid"),e}function Qt(e,n=0,t=false){W(e)||f("MANIFEST_INVALID","action inputSchema must be an object"),n>8&&q("action inputSchema is too deep");let i=e.type;i!=="object"&&i!=="string"&&i!=="number"&&i!=="integer"&&i!=="boolean"&&i!=="array"&&i!=="null"&&(typeof i=="string"&&f("SCHEMA_TYPE_UNSUPPORTED","action inputSchema type is unsupported"),f("MANIFEST_INVALID","action inputSchema type is required"));let o=["type","enum"];i==="string"&&o.push("minLength","maxLength"),i==="array"&&o.push("minItems","maxItems","items"),i==="object"&&o.push("minProperties","maxProperties","properties","required","additionalProperties"),(i==="number"||i==="integer")&&o.push("minimum","maximum"),Y(e,["type"],o.filter(a=>a!=="type"));let r={type:i};if(C(e,"enum")&&(Array.isArray(e.enum)||f("MANIFEST_INVALID","schema enum must be an array"),e.enum.length>128&&q("schema enum is too long"),r.enum=e.enum.map(a=>Zt(a))),i==="string"&&(C(e,"minLength")&&(r.minLength=rn(e.minLength,"schema minLength",4096)),C(e,"maxLength")&&(r.maxLength=rn(e.maxLength,"schema maxLength",4096)),r.minLength!==void 0&&r.maxLength!==void 0&&r.minLength>r.maxLength&&f("MANIFEST_INVALID","schema string length bounds are inverted")),(i==="number"||i==="integer")&&(C(e,"minimum")&&(r.minimum=lo(e.minimum,"schema minimum")),C(e,"maximum")&&(r.maximum=lo(e.maximum,"schema maximum")),r.minimum!==void 0&&r.maximum!==void 0&&r.minimum>r.maximum&&f("MANIFEST_INVALID","schema numeric bounds are inverted")),i==="array"&&(C(e,"minItems")&&(r.minItems=rn(e.minItems,"schema minItems",128)),C(e,"maxItems")&&(r.maxItems=rn(e.maxItems,"schema maxItems",128)),r.minItems!==void 0&&r.maxItems!==void 0&&r.minItems>r.maxItems&&f("MANIFEST_INVALID","schema array length bounds are inverted"),C(e,"items")&&(r.items=Qt(e.items,n+1,false))),i==="object"){let a;if(C(e,"properties")){W(e.properties)||f("MANIFEST_INVALID","schema properties must be an object");let d=Object.entries(e.properties);d.length>64&&q("schema properties are too many"),a={};for(let[l,p]of d){let u=Ec(l,t);a[u]=Qt(p,n+1,false);}r.properties=a;}C(e,"minProperties")&&(r.minProperties=rn(e.minProperties,"schema minProperties",64)),C(e,"maxProperties")&&(r.maxProperties=rn(e.maxProperties,"schema maxProperties",64)),r.minProperties!==void 0&&r.maxProperties!==void 0&&r.minProperties>r.maxProperties&&f("MANIFEST_INVALID","schema object property bounds are inverted");let c=_c(e.required,a);c!==void 0&&(r.required=c),C(e,"additionalProperties")&&(e.additionalProperties!==false&&f("MANIFEST_INVALID","schema additionalProperties must be false"),r.additionalProperties=false);}let s=JSON.stringify(r);return (s===void 0||Buffer.byteLength(s,"utf8")>2097152)&&q("action inputSchema subtree is too large"),r}function Tc(e){let n=Qt(e,0,true);return (n.type!=="object"||!n.properties)&&f("MANIFEST_INVALID","action inputSchema must declare object properties"),n}function Pc(e){if(W(e)||f("MANIFEST_INVALID","action backend must be an object"),e.type==="core"){Y(e,Ya);let n=e.handler;return (typeof n!="string"||!Ut.test(n))&&f("MANIFEST_INVALID","core backend handler is invalid"),{type:"core",handler:n}}if(e.type==="skill"&&C(e,"entry"))return Y(e,Qa),e.entry!==Oe&&f("MANIFEST_INVALID",`skill backend entry must be ${Oe}`),{type:"skill",entry:Oe};if(e.type==="skill"){Y(e,qa,Za),(!Array.isArray(e.command)||e.command.length===0||e.command.length>16)&&f("MANIFEST_INVALID","skill backend command is invalid");let n=[];for(let i of e.command)(typeof i!="string"||i.length===0||i.length>256||!kt.test(i))&&f("MANIFEST_INVALID","skill backend command token is invalid"),n.push(i);let t=C(e,"env")?Mc(e.env):void 0;return {type:"skill",command:n,...t===void 0?{}:{env:t}}}f("MANIFEST_INVALID","action backend type is unsupported");}function bc(e){W(e)||f("MANIFEST_INVALID","action must be an object"),Y(e,$a,Ga),C(e,"_meta")&&$("_meta",()=>Eo(e._meta));let n=$("actionId",()=>Xt(e.actionId,"actionId"));Ot(n)&&f("MANIFEST_INVALID",`actionId "${n}" is not projection-safe`,"actionId");let t=$("capability",()=>Ic(e.capability)),i=e.mutation;typeof i!="boolean"&&f("MANIFEST_INVALID","action mutation must be boolean","mutation");let o=$("inputSchema",()=>Tc(e.inputSchema)),r;if(C(e,"dataInputs")){Array.isArray(e.dataInputs)||f("MANIFEST_INVALID","action dataInputs must be an array","dataInputs");let y=o.properties,g=new Set,_=[];for(let E of e.dataInputs)(typeof E!="string"||!C(y,E)||g.has(E))&&f("MANIFEST_INVALID","action dataInputs must be unique declared properties","dataInputs"),g.add(E),_.push(E);r=_;}let s=$("resultProjection",()=>qt(e.resultProjection)),a=$("backend",()=>Pc(e.backend)),c;C(e,"content")&&((a.type!=="skill"||!Hn(e.content))&&f("MANIFEST_INVALID","action content declaration is invalid","content"),c=Lc(e.content));let d;if(C(e,"confirmation")){let y=e.confirmation;y!=="none"&&y!=="native"&&f("MANIFEST_INVALID","action confirmation is invalid","confirmation"),d=y;}let l;C(e,"schedule")&&(l=$("schedule",()=>Sc(e.schedule,{backend:a,inputSchema:o,hasContent:c!==void 0,hasDataInputs:r!==void 0,confirmation:d})));let p;C(e,"job")&&(l!==void 0&&f("MANIFEST_INVALID","an action is either the scheduled run or a job, not both","job"),p=$("job",()=>Dc(e.job,{backend:a,inputSchema:o,hasContent:c!==void 0,hasDataInputs:r!==void 0,confirmation:d})));let u;return C(e,"jobAccess")&&(p!==void 0&&f("MANIFEST_INVALID","an action is either the job or a job control, not both","jobAccess"),u=$("jobAccess",()=>Nc(e.jobAccess,{backend:a,hasContent:c!==void 0}))),{actionId:n,capability:t,mutation:i,inputSchema:o,resultProjection:s,backend:a,...c===void 0?{}:{content:c},...r===void 0?{}:{dataInputs:r},...d===void 0?{}:{confirmation:d},...l===void 0?{}:{schedule:l},...p===void 0?{}:{job:p},...u===void 0?{}:{jobAccess:u}}}function Nc(e,n){return (n.backend.type!=="skill"||!("entry"in n.backend)||n.backend.entry!==Oe)&&f("MANIFEST_INVALID","jobAccess needs a tool-mode action","jobAccess"),n.hasContent&&f("MANIFEST_INVALID","a job control action takes no content","jobAccess"),(!Array.isArray(e)||e.length===0)&&f("MANIFEST_INVALID","jobAccess must list at least one operation","jobAccess"),(new Set(e).size!==e.length||!e.every(Kn))&&f("MANIFEST_INVALID","jobAccess must name each operation once: start, status or cancel","jobAccess"),Object.freeze([...e])}function Dc(e,n){(n.backend.type!=="skill"||!("entry"in n.backend)||n.backend.entry!==Oe)&&f("MANIFEST_INVALID","job needs a tool-mode action","job"),(n.hasContent||n.hasDataInputs||n.confirmation!==void 0&&n.confirmation!=="none")&&f("MANIFEST_INVALID","a job action takes no content, dataInputs or native confirmation","job"),(n.inputSchema.required??[]).length>0&&f("MANIFEST_INVALID","a job action input must accept {}","inputSchema.required"),W(e)||f("MANIFEST_INVALID","job must be an object","job"),Y(e,[],Ka);let t=C(e,"deadlineMs")?e.deadlineMs:Jn.default;return Wn(t)||f("MANIFEST_INVALID","job deadlineMs is invalid","job.deadlineMs"),{deadlineMs:t}}function Sc(e,n){(n.backend.type!=="skill"||!("entry"in n.backend)||n.backend.entry!==Oe)&&f("MANIFEST_INVALID","schedule needs a tool-mode action","schedule"),(n.hasContent||n.hasDataInputs||n.confirmation!==void 0&&n.confirmation!=="none")&&f("MANIFEST_INVALID","a scheduled action takes no content, dataInputs or native confirmation","schedule"),(n.inputSchema.required??[]).length>0&&f("MANIFEST_INVALID","a scheduled action input must accept {}","inputSchema.required"),W(e)||f("MANIFEST_INVALID","schedule must be an object","schedule"),Y(e,Ja,Wa),$n(e.everyMinutes)||f("MANIFEST_INVALID","schedule everyMinutes is invalid","schedule.everyMinutes");let t=C(e,"timeoutMs")?e.timeoutMs:zn.default;return Gn(t)||f("MANIFEST_INVALID","schedule timeoutMs is invalid","schedule.timeoutMs"),{everyMinutes:e.everyMinutes,timeoutMs:t}}function Mc(e){return qi(e)||f("MANIFEST_INVALID","skill backend env is invalid"),Object.freeze([...e])}function Lc(e){return Object.freeze({...e.in===void 0?{}:{in:Object.freeze({...e.in})},...e.out===void 0?{}:{out:Object.freeze({...e.out})}})}function Oc(e){return W(e)||f("INITIAL_STATE_INVALID","initialState must be an object"),Y(e,ec,nc),e.path!=="ui/state.json"&&f("MANIFEST_INVALID","initialState path is not fixed"),C(e,"hash")?{path:"ui/state.json",hash:ho(e.hash)}:{path:"ui/state.json"}}function Rc(e){let n=["wasm","terminal","htmlDocuments"];return (!W(e)||Object.keys(e).length===0||Object.keys(e).some(t=>!n.includes(t)||e[t]!==true))&&f("MANIFEST_INVALID","runtime must contain only known capability flags set to true"),{...e.wasm===true?{wasm:true}:{},...e.terminal===true?{terminal:true}:{},...e.htmlDocuments===true?{htmlDocuments:true}:{}}}function wc(e,n){let t;try{t=so(e);}catch(i){let o=i!==null&&typeof i=="object"&&"code"in i&&typeof i.code=="string"?i.code:"CSP_ORIGIN_INVALID";return f("MANIFEST_INVALID",o,void 0,o.toLowerCase().replace(/_/g,"-"))}if(t.frameDomains.length>0&&f("MANIFEST_INVALID","external origins in csp are not enabled in this rollout",void 0,"csp-not-enabled"),t.connectDomains.length!==0)return n?.terminal===true&&f("MANIFEST_INVALID","runtime.terminal cannot be combined with csp.connectDomains","connectDomains","terminal-with-connect-domains"),Object.freeze({connectDomains:t.connectDomains})}function Cc(e,n){Zn(W(e)?pc(e,["csp","downloads"]):e,new Set,0,true,true),Yt(e),W(e)||f("MANIFEST_INVALID"),Y(e,Ha,za),C(e,"_meta")&&$("_meta",()=>Eo(e._meta)),e.manifestVersion!==2&&f("MANIFEST_INVALID");let t;C(e,"runtime")&&(t=$("runtime",()=>Rc(e.runtime)));let i;C(e,"csp")&&(i=$("csp",()=>wc(e.csp,t)));let o=$("pluginId",()=>Xt(e.pluginId,"pluginId")),r=$("definitionId",()=>Xt(e.definitionId,"definitionId")),s=$("version",()=>ge(e,"version",1)),a=$("name",()=>po(e.name,"name")),c=$("description",()=>po(e.description,"description")),d;C(e,"icon")&&((typeof e.icon!="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(e.icon))&&f("MANIFEST_INVALID","icon is invalid","icon"),d=e.icon);let l;C(e,"tone")&&((typeof e.tone!="string"||!xt.includes(e.tone))&&f("MANIFEST_INVALID","tone is invalid","tone"),l=e.tone),e.entry!=="ui/index.html"&&f("MANIFEST_INVALID","entry path is not fixed","entry","fixed-value");let p;C(e,"entryHash")&&(p=$("entryHash",()=>ho(e.entryHash)));let u;C(e,"initialState")&&(u=$("initialState",()=>Oc(e.initialState)));let y;C(e,"usage")&&(e.usage!=="card"&&e.usage!=="window"&&f("MANIFEST_INVALID","usage is invalid","usage"),y=e.usage);let g;C(e,"detailPanel")&&(typeof e.detailPanel!="boolean"&&f("MANIFEST_INVALID","detailPanel is invalid","detailPanel"),g=e.detailPanel);let _;if(C(e,"displayModes")){((y??ve)!==ve||!Array.isArray(e.displayModes)||e.displayModes.length===0)&&f("MANIFEST_INVALID","displayModes are only valid for window Apps","displayModes");let w=new Set(["inline","floating","focused"]);(new Set(e.displayModes).size!==e.displayModes.length||e.displayModes.some(k=>typeof k!="string"||!w.has(k)))&&f("MANIFEST_INVALID","displayModes are invalid","displayModes"),_=e.displayModes;}(y??ve)===ve&&g!==void 0&&f("MANIFEST_INVALID","detailPanel is card-only","detailPanel");let E=n.mode??"local";E!=="local"&&E!=="installed"&&E!=="published"&&f("MANIFEST_INVALID","manifest mode is invalid"),E!=="local"&&p===void 0&&f("MANIFEST_INVALID","installed manifests require entryHash","entryHash","required-when-installed"),E!=="local"&&u!==void 0&&u.hash===void 0&&f("MANIFEST_INVALID","installed manifests require initialState.hash","initialState.hash","required-when-installed"),(!Array.isArray(e.surfaces)||e.surfaces.length===0)&&f("MANIFEST_INVALID","surfaces are invalid","surfaces"),e.surfaces.length>2&&q("surfaces exceed the v2 limit","surfaces","too-many-items");let v=[],j=new Set;for(let w of e.surfaces)(typeof w!="string"||!vt.includes(w))&&f("MANIFEST_INVALID","surface is unsupported","surfaces"),j.has(w)&&f("MANIFEST_INVALID","surfaces contain a duplicate","surfaces","duplicate-item"),j.add(w),v.push(w);W(e.size)||f("MANIFEST_INVALID","size must be an object","size"),$("size",()=>Y(e.size,["height"]));let b=$("size",()=>ge(e.size,"height",1));b>720&&q("size.height exceeds the v2 limit","size.height","too-large");let U=$("stateProjection",()=>qt(e.stateProjection)),H=e.summaryProjection===void 0?void 0:$("summaryProjection",()=>qt(e.summaryProjection));H!==void 0&&H.allow.some(w=>!U.allow.includes(w))&&f("MANIFEST_INVALID","summaryProjection must be a subset of stateProjection.allow","summaryProjection");let N=$("dataPaths",()=>gc(e.dataPaths,U.allow)),D=C(e,"deviceFeatures")?$("deviceFeatures",()=>mc(e.deviceFeatures)):void 0,L=C(e,"downloads")?$("downloads",()=>hc(e.downloads)):void 0;Array.isArray(e.actions)||f("MANIFEST_INVALID","actions must be an array","actions"),e.actions.length>32&&q("actions exceed the v2 limit","actions","too-many-items");let I=[],A=new Set,h=0,T=0;for(let[w,k]of e.actions.entries()){let X=`actions[${w}]`,B=$(X,()=>bc(k));if(A.has(B.actionId)&&f("MANIFEST_INVALID","actions contain a duplicate actionId",`${X}.actionId`,"duplicate-item"),B.schedule!==void 0&&(h+=1,h>Xi&&f("MANIFEST_INVALID","an App declares at most one scheduled action",`${X}.schedule`,"duplicate-item")),B.job!==void 0&&(T+=1,T>Yi&&f("MANIFEST_INVALID","an App declares at most one job action",`${X}.job`,"duplicate-item")),B.backend.type==="core"&&B.backend.handler==="state.set"){B.mutation||f("MANIFEST_INVALID","state.set actions must be mutations",`${X}.mutation`);for(let Te of Object.keys(B.inputSchema.properties))U.allow.includes(Te)||f("MANIFEST_INVALID","state.set input paths must be projection-allowed",`${X}.inputSchema.properties`);}A.add(B.actionId),I.push(B);}return {manifestVersion:2,pluginId:o,definitionId:r,version:s,name:a,description:c,...d===void 0?{}:{icon:d},...l===void 0?{}:{tone:l},entry:"ui/index.html",...p===void 0?{}:{entryHash:p},...t===void 0?{}:{runtime:t},...i===void 0?{}:{csp:i},...u===void 0?{}:{initialState:u},...y===void 0?{}:{usage:y},...g===void 0?{}:{detailPanel:g},..._===void 0?{}:{displayModes:_},surfaces:v,size:{height:b},stateProjection:U,...H===void 0?{}:{summaryProjection:H},...N===void 0?{}:{dataPaths:N},...D===void 0?{}:{deviceFeatures:D},...L===void 0?{}:{downloads:L},actions:I}}function Eo(e){W(e)||f("MANIFEST_INVALID","_meta must be an object");let n=JSON.stringify(e);(n===void 0||Buffer.byteLength(n,"utf8")>Xa)&&q("_meta exceeds the 4 KiB limit",void 0,"meta-too-large");}function Uc(e){let n={},t={};for(let r of e.actions){n[r.actionId]={capabilities:[r.capability],inputKeys:Object.keys(r.inputSchema.properties??{}),...r.dataInputs===void 0?{}:{dataInputs:r.dataInputs},resultProjection:r.resultProjection,...r.confirmation===void 0?{}:{confirmation:r.confirmation},...r.content===void 0?{}:{content:r.content},...r.schedule===void 0?{}:{schedule:r.schedule},...r.job===void 0?{}:{job:r.job},...r.jobAccess===void 0?{}:{jobAccess:r.jobAccess},...r.backend.type!=="skill"||r.backend.env===void 0?{}:{env:r.backend.env}};let s=r.backend.type==="skill"||r.backend.type==="core"&&r.backend.handler==="state.set";t[r.actionId]={actionId:r.actionId,mutation:r.mutation,backend:r.backend,launchPolicy:s?"allowed":"denied",...s?{}:{denialCode:"EXEC_DENIED"}};}let i={id:e.definitionId,version:e.version,renderer:"sandbox-html",...e.usage===void 0?{}:{usage:e.usage},...e.detailPanel===void 0?{}:{detailPanel:e.detailPanel},...e.displayModes===void 0?{}:{displayModes:e.displayModes},surfaces:e.surfaces,stateProjection:e.stateProjection,...e.summaryProjection===void 0?{}:{summaryProjection:e.summaryProjection},...e.dataPaths===void 0?{}:{dataPaths:e.dataPaths},...e.downloads===void 0?{}:{downloads:e.downloads},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 ei(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||Qn(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=>ei(c,n,t+1,2097152,o,r));else {W(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]=ei(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 ti(e,n=[]){W(e)||Ie("initial state must be a JSON object");let t=ei(e,new Set,0,2097152,[],n);return (t===null||Array.isArray(t)||typeof t!="object")&&Ie(),t}function kc(e,n={}){Zn(e),W(e)||f("MANIFEST_INVALID"),Y(e,Ba),e.manifestVersion!==1&&f("MANIFEST_INVALID");let t=Kt(be(e,"pluginId")),i=Kt(be(e,"definitionId")),o=ge(e,"version",1),r=ge(e,"primitiveSet",1),s=n.supportedPrimitiveSet??Ra;(!Number.isSafeInteger(s)||s<1)&&f("MANIFEST_INVALID"),r>s&&f("PRIMITIVE_SET_UNSUPPORTED"),W(e.activation)||f("MANIFEST_INVALID"),Y(e.activation,["kind","language"]),e.activation.kind!=="fenced-code"&&f("MANIFEST_INVALID");let a=Kt(be(e.activation,"language")),c=uc(e.schema),d=Ac(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 xc(e,n={}){return W(e)||f("MANIFEST_INVALID"),Object.hasOwn(e,"lineage")&&f("MANIFEST_INVALID","lineage is only allowed in product bundle indexes"),e.manifestVersion===2?Cc(e,n):kc(e,n)}function We(e,n={}){try{return xc(e,n)}catch(t){if(t instanceof ce)throw t;return f("MANIFEST_INVALID")}}function hn(e,n={}){let t=We(e,n);return t.manifestVersion===2?Uc(t):t}var Ra,wa,Ca,mo,Ua,ka,xa,va,co,ja,Fa,Va,Ba,Ha,za,$a,Ga,Ja,Wa,Ka,Xa,Ya,qa,Za,Qa,ec,nc,tc,ic,oc,rc,sc,ac,cc,dc,ce,ii=F(()=>{m();Jt();Le();Vt();Zi();Gt();Bt();Ht();ao();$e();Ra=1,wa=/^[a-z][a-zA-Z0-9]*(\.[a-zA-Z0-9]+)+$/,Ca=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,mo=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,Ua=/<\/?[A-Za-z][^>]*>/,ka=/^(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)/,xa=/^(?:https?|file|ftp|ws|wss):\/\//i,va=/^\s*(?:javascript|data):/i,co=/data:[^,\s]*,/i,ja=/(?:https?|file|ftp|ws|wss):\/\//i,Fa=/javascript:/i,Va=/(?:^[\s]*|[\s"'(=])(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)(?=[^\s"'<>])[^\s"'<>]*/,Ba=["manifestVersion","pluginId","definitionId","version","primitiveSet","activation","schema","layout"],Ha=["manifestVersion","pluginId","definitionId","version","name","description","entry","surfaces","size","stateProjection","actions"],za=["_meta","icon","tone","entryHash","runtime","csp","initialState","usage","detailPanel","displayModes","summaryProjection","dataPaths","focusedAiDataPaths","deviceFeatures","downloads"],$a=["actionId","capability","mutation","inputSchema","resultProjection","backend"],Ga=["confirmation","dataInputs","content","schedule","job","jobAccess","_meta"],Ja=["everyMinutes"],Wa=["timeoutMs"],Ka=["deadlineMs"],Xa=4*1024,Ya=["type","handler"],qa=["type","command"],Za=["env"],Qa=["type","entry"],ec=["path"],nc=["hash"],tc=/^[0-9a-f]{64}$/,ic=/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/,oc=/[\r\n]/,rc=16,sc=16,ac=32,cc=/^[a-z][A-Za-z0-9]{0,31}$/,dc=["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 So(e){return typeof e=="string"&&e.length<=jc&&vc.test(e)}function V(e,n,t,i,o){throw new De(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 Z(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function he(e){let n=`_meta["${je}"]`;return e===void 0||e===""?n:e.startsWith("[")?`${n}${e}`:`${n}.${e}`}function Hc(e){return e.toLowerCase().replace(/_/g,"-")}function zc(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 Mo(e,n,t){return {path:t(e.path),rule:e.rule??Hc(e.code),...e.message!==e.code?{message:e.message}:{},file:n}}function Lo(e){return JSON.parse(JSON.stringify(e))}function si(e,n,t=0,i=new Set){if(typeof e=="string"){e.length>4096&&V("LIMIT_EXCEEDED",n,"string-too-long"),(Fc.test(e)||Vc.test(e)||Bc.test(e))&&V("UNSAFE_VALUE",n,"unsafe-value");return}if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){Number.isFinite(e)||V("MANIFEST_INVALID",n,"non-finite-number");return}typeof e!="object"&&V("MANIFEST_INVALID",n,"non-json-value"),t>8&&V("LIMIT_EXCEEDED",n,"too-deep"),i.has(e)&&V("MANIFEST_INVALID",n,"cycle"),i.add(e);try{if(Array.isArray(e)){e.length>128&&V("LIMIT_EXCEEDED",n,"array-too-long"),e.forEach((o,r)=>si(o,`${n}[${r}]`,t+1,i));return}oe(e)||V("MANIFEST_INVALID",n,"non-plain-object");for(let[o,r]of Object.entries(e))si(r,n===""?o:`${n}.${o}`,t+1,i);}finally{i.delete(e);}}}function me(e,n){return (typeof e!="string"||e.length===0)&&V("MANIFEST_INVALID",n,"string"),e}function an(e,n){return oe(e)||V("MANIFEST_INVALID",n,"object"),e}function $c(e,n){Array.isArray(e)||V("MANIFEST_INVALID",n,"array"),e.forEach((t,i)=>me(t,`${n}[${i}]`));}function Gc(e,n){typeof e!="boolean"&&V("MANIFEST_INVALID",n,"boolean");}function _n(e,n,t,i){for(let o of Object.keys(e))!t.includes(o)&&!i.includes(o)&&V("MANIFEST_INVALID",`${n}.${o}`,"unknown-key");for(let o of t)Z(e,o)||V("MANIFEST_INVALID",`${n}.${o}`,"missing-key");}function Jc(e,n){if(e!=="icon")switch(si(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)||V("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`),Z(r,"theme")&&me(r.theme,`${o}.theme`);});return}case "screenshots":case "keywords":case "privacy_policies":$c(n,e);return;case "tools":{Array.isArray(n)||V("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`),Z(r,"description")&&me(r.description,`${o}.description`);});return}case "prompts":{Array.isArray(n)||V("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":Gc(n,e);return;case "localization":case "compatibility":case "user_config":an(n,e);return;default:V("MANIFEST_INVALID",e,"unknown-key");}}function et(e){return typeof e=="string"&&Pe.test(e)?e:void 0}function Oo(e){return Number.isSafeInteger(e)&&e>=1?e:void 0}function Wc(e){let n=et(e.name);if(n===void 0)return;let t=e._meta,i=oe(t)?t[je]:void 0,o=oe(i)?i:{},r=Z(o,"definitionId")?et(o.definitionId):n,s=Z(o,"definitionVersion")?Oo(o.definitionVersion):1;return {pluginId:n,...r===void 0?{}:{definitionId:r},...s===void 0?{}:{definitionVersion:s}}}function Kc(e){let n=et(e.pluginId);if(n===void 0)return;let t=et(e.definitionId),i=Oo(e.version);return {pluginId:n,...t===void 0?{}:{definitionId:t},...i===void 0?{}:{definitionVersion:i}}}function di(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)&&Z(t,je)}catch{return false}}function Xc(e,n){if(e===pe)return n.builtinOnly===true;let t=n._meta,i=oe(t)?t[je]:void 0;return oe(i)&&i.builtinOnly===true}function Yc(e,n){Z(e,"server")&&V("MANIFEST_INVALID","server","server-unsupported","phase 1 runs CrewX-owned Apps only");for(let a of Object.keys(e))ai.includes(a)||V("MANIFEST_INVALID",a,"unknown-key");for(let a of ci)Z(e,a)||V("MANIFEST_INVALID",a,"missing-key");e.manifest_version!==oi&&V("MANIFEST_INVALID","manifest_version","unsupported-version",`manifest_version must be "${oi}"`),So(e.version)||V("MANIFEST_INVALID","version","semver","version must be a semver.org version such as 0.1.0");let t=e._meta;oe(t)||V("MANIFEST_INVALID","_meta","object"),Z(t,je)||V("MANIFEST_INVALID",he(),"missing-key");let i=t[je];oe(i)||V("MANIFEST_INVALID",he(),"object");for(let a of Object.keys(i))ri.includes(a)||Do.includes(a)||V("MANIFEST_INVALID",he(a),"unknown-key");for(let a of ri)a==="actions"&&n!==void 0||Z(i,a)||V("MANIFEST_INVALID",he(a),"missing-key");if(n!==void 0&&Z(i,"actions")&&V("MANIFEST_INVALID",he("actions"),"two-truths",`actions are declared in both ${K} and ${G}; a server.ts App keeps them in the tools file only`),qc(i.actions),Z(i,"definitionVersion")){let a=i.definitionVersion;(!Number.isSafeInteger(a)||a<1)&&V("MANIFEST_INVALID",he("definitionVersion"),"positive-integer");}let o={};for(let a of No)Z(e,a)&&(Jc(a,e[a]),o[a]=Lo(e[a]));let r={};for(let[a,c]of Object.entries(t))a!==je&&(r[a]=c);let s={manifestVersion:2,pluginId:e.name,definitionId:Z(i,"definitionId")?i.definitionId:e.name,version:Z(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:Oe}}))),Object.keys(r).length>0&&(s._meta=r),{v2Input:s,...Object.keys(r).length>0?{vendorMeta:r}:{},passthrough:o}}function qc(e){Array.isArray(e)&&e.forEach((n,t)=>{let i=oe(n)?n.backend:void 0;oe(i)&&Z(i,"entry")&&V("MANIFEST_INVALID",he(`actions[${t}].backend.entry`),"entry-not-authorable",`an action in ${K} cannot name an entry; a server.ts App declares its actions in ${G}`);});}function Zc(e,n,t){oe(e)||V("MANIFEST_INVALID","","not-object","manifest.json must be a JSON object",K);let i;try{i=Yc(e,t);}catch(s){throw s instanceof De?new De(s.code,{...s.reason,file:K}):s}let o;try{let s=We(i.v2Input,{mode:n.mode??"local"});s.manifestVersion!==2&&V("MANIFEST_INVALID","","v2-required"),o=s;}catch(s){throw s instanceof ce?new De(s.code,Mo(s,K,zc)):s}let r=e.tools;if(Array.isArray(r)){let s=new Set(o.actions.map(a=>a.actionId));r.forEach((a,c)=>{let d=a.name;if(!s.has(d))throw new De("MANIFEST_INVALID",{path:`tools[${c}].name`,rule:"tool-not-action",message:"every tools[].name must be an action id",file:K})});}return {file:K,manifest:o,v2Input:i.v2Input,releaseVersion:e.version,...Object.keys(i.passthrough).length>0?{mcpb:i.passthrough}:{}}}function Qc(e,n){try{let t=We(e,{mode:n.mode??"local"});if(t.manifestVersion!==2)throw new De("MANIFEST_INVALID",{path:"manifestVersion",rule:"v2-required",message:"a workspace App requires manifestVersion 2",file:pe});return {file:pe,manifest:t,v2Input:e}}catch(t){throw t instanceof ce?new De(t.code,Mo(t,pe,i=>i??"")):t}}function cn(e){return le(hn(e).definition)}function Po(e){let{entryHash:n,initialState:t,...i}=e,o={...i};return t!==void 0&&(o.initialState={path:t.path}),Lo(o)}function ed(e,n){let t=Po(e),i=Po(n);return [...new Set([...Object.keys(t),...Object.keys(i)])].sort().filter(r=>ie(t[r]??null)!==ie(i[r]??null))}function nd(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 td(e,n){let t=ed(e,n),i=nd(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||V("MANIFEST_DUAL_MISMATCH","","dual-manifest-mismatch",`${K} and ${pe} normalize to different definitions${o}`+(t.length>0?`; differing fields: ${t.join(", ")}`:""));}function Ne(e,n,t="MANIFEST_INVALID",i){return {code:t,reason:{path:e,rule:n,...i===void 0?{}:{message:i},file:G},files:[]}}function bo(e){return {...Ne("","tools-needs-manifest-json","MANIFEST_INVALID",`${G} is read with ${K} only`),files:e}}function id(e,n){if(e.byteLength>n)return {failure:Ne("","file-too-large","LIMIT_EXCEEDED")};let t;try{t=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e));}catch{return {failure:Ne("","invalid-json")}}if(!oe(t))return {failure:Ne("","not-object","MANIFEST_INVALID",`${G} must be a JSON object`)};for(let o of Object.keys(t))if(o!=="schemaVersion"&&o!=="actions")return {failure:Ne(o,"unknown-key")};for(let o of ["schemaVersion","actions"])if(!Z(t,o))return {failure:Ne(o,"missing-key")};if(t.schemaVersion!==1)return {failure:Ne("schemaVersion","unsupported-version","MANIFEST_INVALID",`schemaVersion must be ${1}`)};let i=t.actions;if(!Array.isArray(i))return {failure:Ne("actions","array")};for(let[o,r]of i.entries()){if(!oe(r))return {failure:Ne(`actions[${o}]`,"object")};if(Z(r,"backend"))return {failure:Ne(`actions[${o}].backend`,"tools-backend","MANIFEST_INVALID",`an action in ${G} cannot carry a backend`)}}return {actions:i}}function od(e,n){let t=n.maxBytes??262144,i=[],o=new TextDecoder("utf-8",{fatal:true});for(let r of ee){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 Ve(e,n={}){let{parsed:t,failure:i}=od(e,n),o=ee.filter(y=>e[y]!==void 0);if(i!==void 0)return {ok:false,rejection:i,parseFailure:true,builtinOnly:false};let r=e[G],s=r===void 0?void 0:id(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:[]}:bo(o),parseFailure:true,builtinOnly:false};let a=t[0],c=a.file===K?Wc(a.raw):Kc(a.raw),d=t.some(y=>Xc(y.file,y.raw)),l;if(s!==void 0){let y=t.some(g=>g.file===K)?s.failure:bo(o);if(y!==void 0)return {ok:false,rejection:y,parseFailure:false,...c===void 0?{}:{identity:c},builtinOnly:d};l=s.actions;}let p=[];try{for(let y of t)p.push(y.file===K?Zc(y.raw,n,l):Qc(y.raw,n));p.length===2&&td(p[0].manifest,p[1].manifest);}catch(y){if(y instanceof De)return {ok:false,rejection:{code:y.code,reason:y.reason,files:y.code==="MANIFEST_DUAL_MISMATCH"?[...ee]:y.reason.file===void 0||y.reason.file===G?o:[y.reason.file]},parseFailure:false,...c===void 0?{}:{identity:c},builtinOnly:d};throw y}let u=p[0];return {ok:true,...u,identity:c??{pluginId:u.manifest.pluginId},files:o}}var K,pe,ee,oi,je,ai,ci,No,ri,Do,vc,jc,Fc,Vc,Bc,De,nt=F(()=>{m();Ge();Le();Gt();$e();ii();K="manifest.json",pe="ui-plugin.json",ee=[K,pe],oi="0.3",je="dev.crewx",ai=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"]),ci=Object.freeze(["manifest_version","name","display_name","version","description","_meta"]),No=Object.freeze(ai.filter(e=>e!=="server"&&!ci.includes(e))),ri=Object.freeze(["entry","surfaces","size","stateProjection","actions"]),Do=Object.freeze(["definitionId","definitionVersion","icon","tone","entryHash","runtime","initialState","usage","detailPanel","displayModes","summaryProjection","dataPaths","focusedAiDataPaths","csp","deviceFeatures","downloads"]),vc=/^(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-]+)*))?$/,jc=256,Fc=/<\/?[A-Za-z][^>]*>/,Vc=/^\s*javascript:/i,Bc=/data:[^,\s]*,/i;De=class extends Error{constructor(t,i){super(`${t}: ${i.path||"<file>"} (${i.rule})`);this.code=t;this.reason=i;}code;reason};});function vo(e){if(e===void 0)return {kind:"none"};if(typeof e!="string")return {kind:"invalid",reason:"bad-path"};if(ad.test(e))return {kind:"url",declared:e};if(!pd(e))return {kind:"invalid",reason:"bad-path",declared:e};let n=e.lastIndexOf("."),t=n<0?void 0:rd.get(e.slice(n+1).toLowerCase());return t===void 0?{kind:"invalid",reason:"bad-type",declared:e}:{kind:"file",path:e,contentType:t}}function pd(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=vo(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:[pi(t.reason,t.declared)]};let i=await n(t.path);if(typeof i=="string")return {diagnostics:[pi(i,t.path)]};let o=jo(t.contentType,i);if(!o.ok)return {diagnostics:[pi(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 pi(e,n){return {code:"ICON_INVALID",severity:"error",reason:e,...n===void 0?{}:{declared:n}}}function jo(e,n){if(n.byteLength>262144)return {ok:false,reason:"too-large"};if(e==="image/png")return !Uo(n,cd)||_d(n,12,16)!=="IHDR"||n.byteLength<24?{ok:false,reason:"bytes-mismatch"}:{ok:true,square:Co(ko(n,16),ko(n,20))};if(e==="image/jpeg"){if(!Uo(n,dd))return {ok:false,reason:"bytes-mismatch"};let t=md(n);return {ok:true,square:t===void 0?void 0:Co(t.width,t.height)}}return ld(n)}function ld(e){let n;try{n=sd.decode(e);}catch{return {ok:false,reason:"bytes-mismatch"}}return Id(n)?{ok:false,reason:"unsafe-svg"}:ud.test(n)?{ok:true,square:gd(n)}:{ok:false,reason:"bytes-mismatch"}}function Id(e){if(fd.some(n=>n.test(e)))return true;for(let n of e.matchAll(yd))if(!(n[1]??n[2]??n[3]??"").startsWith("#"))return true;for(let n of e.matchAll(Ad))if(Ro.lastIndex=n.index??0,!Ro.test(e))return true;return false}function gd(e){let n=/<svg\b[^>]*>/i.exec(e)?.[0];if(n===void 0)return;let t=Fo(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=wo(n,"width"),o=wo(n,"height");return i===void 0||o===void 0?void 0:i===o}function Fo(e,n){let t=new RegExp(`\\s${n}\\s*=\\s*(?:"([^"]*)"|'([^']*)')`).exec(e);return t?.[1]??t?.[2]}function wo(e,n){let t=Fo(e,n),i=t===void 0?null:/^\s*(\d+(?:\.\d+)?)(?:px)?\s*$/.exec(t);return i===null?void 0:Number(i[1])}function md(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(hd(t))return n+9>e.byteLength?void 0:{height:xo(e,n+5),width:xo(e,n+7)};n+=2+i;}}function hd(e){return e>=192&&e<=207&&e!==196&&e!==200&&e!==204}function Co(e,n){if(!(e<=0||n<=0))return e===n}function Uo(e,n){return e.byteLength>=n.length&&n.every((t,i)=>e[i]===t)}function _d(e,n,t){return String.fromCharCode(...e.subarray(n,t))}function ko(e,n){return (e[n]<<24|e[n+1]<<16|e[n+2]<<8|e[n+3])>>>0}function xo(e,n){return e[n]<<8|e[n+1]}var rd,sd,ad,cd,dd,ud,fd,yd,Ad,Ro,li=F(()=>{m();rd=new Map([["svg","image/svg+xml"],["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"]]),sd=new TextDecoder("utf-8",{fatal:true}),ad=/^[A-Za-z][A-Za-z0-9+.-]*:/,cd=[137,80,78,71,13,10,26,10],dd=[255,216,255];ud=/^\s*(?:<\?[\s\S]*?\?>\s*|<!--[\s\S]*?-->\s*)*<svg(?=[\s/>])/,fd=[/<script/i,/[\s"'/]on[a-z]+\s*=/i,/<foreignobject/i,/<!doctype/i,/<!entity/i,/<(?:iframe|embed|object)\b/i,/@import/i],yd=/(?:^|[\s"'/])(?:xlink:)?href\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+))/gi,Ad=/url\(/gi,Ro=/url\(\s*["']?#/iy;});var ui=F(()=>{m();Gi();nt();li();ii();$e();});function S(e,n=e){throw new Se(e,n)}var Se,it=F(()=>{m();Se=class extends Error{constructor(t,i=t){super(i);this.code=t;}code;name="McpAppContractError"};});var qo=F(()=>{m();});var Zo=F(()=>{m();Ge();Le();it();qo();});function er(e,n){return Qo.add(e),n!==void 0&&wd.set(e,n),e}function dn(e){return e!==null&&typeof e=="object"&&Qo.has(e)}var Qo,wd,ot=F(()=>{m();Qo=new WeakSet,wd=new WeakMap;});function Nn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function yi(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 ir(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let n of Object.values(e))ir(n);return Object.freeze(e)}function re(e){throw new Me("LINEAGE_INVALID",e)}function Fd(e){throw new Me("LINEAGE_STALE",e)}function or(e){if(!Nn(e)||!yi(e,kd,xd)||!Nn(e.actions))return re("Lineage definition shape is invalid");for(let n of Object.values(e.actions))if(!Nn(n)||!yi(n,vd,jd))return re("Lineage action definition shape is invalid");return e}function Vd(e){if(!Nn(e)||!yi(e,Cd,Ud))return re("Lineage entry shape is invalid");if(!Number.isSafeInteger(e.version)||e.version<1||typeof e.hash!="string"||!nr.test(e.hash))return re("Lineage entry identity is invalid");if(e.sourceHash!==void 0&&(typeof e.sourceHash!="string"||!nr.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=or(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"):ir({version:e.version,hash:e.hash,definition:n,...e.sourceHash===void 0?{}:{sourceHash:e.sourceHash},...e.compat===void 0?{}:{compat:e.compat}})}function tr(e){return e.stateProjection?.allow??[]}function Bd(e,n){let t=[],i=new Set(tr(n));tr(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 Hd(e,n){return ie(e)===ie(n)}function Ai(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=or(c),t={...i,hash:a},Ae(t);}catch{return re("Current definition is invalid")}let o=e.map(Vd),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||!Hd(s.definition,i))return Fd("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 Me("LINEAGE_INVALID",`Lineage compatibility failed: ${l}`,[l])}}for(let a=0;a<o.length-1;a+=1){if(o.slice(a,-1).some(l=>l.compat==="break"))continue;let d=Bd(o[a].definition,t);if(d.length>0)throw new Me("LINEAGE_INVALID",`Lineage compatibility failed: ${d.join(", ")}`,d)}return Object.freeze({entries:Object.freeze(o),current:t})}var Me,nr,Cd,Ud,kd,xd,vd,jd,Ii=F(()=>{m();Ge();Le();Me=class extends Error{constructor(t,i=t,o=[]){super(i);this.code=t;this.violations=o;}code;violations;name="UiDefinitionLineageError"},nr=/^[0-9a-f]{64}$/,Cd=["version","hash","definition"],Ud=["sourceHash","compat"],kd=["id","version","actions"],xd=["sourceHash","usage","detailPanel","displayModes","renderer","surfaces","stateProjection","dataPaths","summaryProjection","downloads","legacy"],vd=["capabilities"],jd=["inputKeys","dataInputs","confirmation","resultProjection","content","env","schedule","job","jobAccess"];});var rr,sr,ar,cr,dr=F(()=>{m();rr="text/html;profile=mcp-app",sr=["crewx_app_terminal_connect","crewx_app_html_viewer_open"],ar=["crewx_listWorkspaces","crewx_queryAgent","crewx_executeAgent","crewx_getTaskResult","crewx_listTasks","crewx_listAgents","callBrowser","openTab","listTabs","closeTab"],cr="text/html";});function Dn(e){return typeof e=="string"&&zd.includes(e)}function rt(e,n){return e==="card"&&n?.type==="core"&&Dn(n.handler)}var zd,st=F(()=>{m();zd=Object.freeze(["card.secret-env"]);});function pr(e,n=[],t){if(e.content!==void 0||e.confirmation!=="none")return "denied";let i=$d();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 $d(e){return;}var lr=F(()=>{m();Ge();ot();st();});function Qd(e){return Ln.has(e)&&(e.initialState===void 0||Ln.has(e.initialState))}function Ir(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:cr,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 ep(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:Be}),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:Be}),n}function He(e,n,t){return (typeof e!="string"||!yr.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>Wd)&&S("TOOL_INVALID",`${n} must be a meaningful description`),i}function mi(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 Se)throw t;S("TOOL_INVALID","MCP App inputSchema must be projection-safe JSON");}}function np(e){return (typeof e!="string"||e.trim().length===0||e.length>Kd)&&S("TOOL_INVALID","MCP App tools require a meaningful text fallback"),e}function tp(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 mr(e){return (typeof e!="string"||!Ar.test(e))&&S("RESOURCE_URI_INVALID","MCP App resource URI is not a registered ui:// URI"),e}function hr(e){let n=He(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=pt(e.definition),r=mi(e.html),s=at(e.entryHash,"Local App entry hash"),a=e.entryBytes===void 0?Array.from(new TextEncoder().encode(r)):dt(e.entryBytes,"Local App entry bytes");(ct(a)!==s||Tr(a)!==r)&&S("HTML_INVALID","Local App entry bytes do not match the HTML hash");let c=ip(e),d=[];Array.isArray(e.actions)||S("TOOL_INVALID","Local App actions must be an array");for(let b of e.actions){let U=He(b.actionId,"TOOL_ID_INVALID","Local App action id");(d.includes(U)||!Object.prototype.hasOwnProperty.call(o.actions,U))&&S("TOOL_INVALID",`Local App action is not declared by the UI definition: ${U}`),d.push(U);}let l=He(e.readToolName,"TOOL_ID_INVALID","Local App read tool name"),p=e.actionToolName===void 0?void 0:He(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=ep(e.runtime);u.some(b=>b.name===l||b.name===p)&&S("TOOL_ID_CONFLICT","Local App read or action tool conflicts with a requested Host capability");let y={name:l,description:`${t} current state`,inputSchema:Zd,textFallback:`${t} current state is available through its open instance.`,visibility:Object.freeze(["model","app"]),kind:"read",resourceBinding:Be},g=[Object.freeze(y)];if(g.push(...u.map(b=>Object.freeze(b))),p!==void 0){let b={name:p,description:`${t} actions`,inputSchema:hi(e.actions),textFallback:`${t} action requests are handled by the open App instance.`,visibility:Object.freeze(["app"]),kind:"action",resourceBinding:Be,actionIds:Object.freeze([...d])};g.push(Object.freeze(b));}let _=[],E=new Set(g.map(b=>b.name));if(p!==void 0)for(let b of e.actions){let U=`${p}__${b.actionId}`;if(U.length>128||!yr.test(U)){_.push(Object.freeze({toolName:U,actionId:b.actionId,reason:"name_too_long"}));continue}if(E.has(U)){_.push(Object.freeze({toolName:U,actionId:b.actionId,reason:"name_collision"}));continue}let H=pr({actionId:b.actionId,confirmation:o.actions[b.actionId]?.confirmation,content:o.actions[b.actionId]?.content,backend:b.backend},e.modelActions),N=Object.freeze([...cp(H,o.usage,b.backend)]),D={name:U,description:`${U} action`,inputSchema:Mn(b.inputSchema),textFallback:`${U} action requests are handled by the open App instance.`,visibility:N,kind:"action",resourceBinding:Be,actionId:b.actionId,actionIds:Object.freeze([b.actionId]),_meta:Object.freeze({ui:Object.freeze({visibility:N})})};g.push(Object.freeze(D)),E.add(U);}let v=Ir(s,r,a,c===void 0?void 0:{hash:c.hash,bytes:[...c.bytes]}),j={appId:n,name:t,description:i,...e.icon===void 0?{}:{icon:Pr(e.icon)},...e.tone===void 0?{}:{tone:br(e.tone)},builtinOnly:false,definition:o,...e.runtime===void 0?{}:{runtime:Object.freeze({...e.runtime})},...e.deviceFeatures===void 0?{}:{deviceFeatures:Object.freeze([...e.deviceFeatures])},...e.downloads===void 0?{}:{downloads:e.downloads},resourceBinding:Be,resource:v,tools:Object.freeze(g),toolDiagnostics:Object.freeze(_)};return ne(j)}function _r(e={}){return new gi(e)}function hi(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(op(n,t),gr)}function ip(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=at(e.initialStateHash,"Initial state hash"),i=dt(e.initialStateBytes,"Initial state bytes");ct(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 op(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 rp(e){let n=On(e),t=He(n.appId,"APP_ID_INVALID","MCP App id"),i=mi(n.html);mr(n.uiUri);let o=n.definition===void 0?void 0:pt(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=>ne(On(d)))),a=ne({...n,appId:t,html:i,...o===void 0?{}:{definition:o},...r===void 0?{}:{provenance:r},tools:s}),c=ne({uri:a.uiUri,mimeType:rr,text:i,...a.csp===void 0?{}:{_meta:{ui:{csp:a.csp}}}});return ne({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 sp(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=He(e.appId,"APP_ID_INVALID","Local App id"),t=pt(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=ap(e.resource),r=e.tools.map(a=>{He(a.name,"TOOL_ID_INVALID","Local App tool name"),Sn(a.description,"Local App tool description","Local App tool"),np(a.textFallback);let c=Mn(a.inputSchema,a.kind==="action"&&!("actionId"in a)?gr: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 (!qd.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"),ne({...a,inputSchema:c,visibility:Object.freeze(["app"])});if(a.kind==="action"){if("actionId"in a){let l=He(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=tp(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"),ne({...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"),ne({...a,inputSchema:c,actionIds:Object.freeze(d)})}return ne({...a,inputSchema:c})}),s=ne({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:Pr(e.icon)},...e.tone===void 0?{}:{tone:br(e.tone)},builtinOnly:false,definition:t,...e.runtime===void 0?{}:{runtime:Object.freeze({...e.runtime})},...e.deviceFeatures===void 0?{}:{deviceFeatures:Object.freeze([...e.deviceFeatures])},...e.downloads===void 0?{}:{downloads:e.downloads},...i===void 0?{}:{provenance:i},resourceBinding:Be,resource:o,tools:Object.freeze(r),toolDiagnostics:Object.freeze([...e.toolDiagnostics??[]])});return ur.has(e)?e:(ur.add(s),s)}function ap(e){let n=mi(e.html),t=at(e.entryHash,"Local App entry hash");if(Qd(e))return e;let i=dt(e.bytes,"Local App entry bytes");(ct(i)!==t||Tr(i)!==n)&&S("HTML_INVALID","Local App entry bytes do not match the HTML hash");let o=e.initialState===void 0?void 0:{hash:at(e.initialState.hash,"Initial state hash"),bytes:dt(e.initialState.bytes,"Initial state bytes")};return o&&ct(o.bytes)!==o.hash&&S("STATE_INVALID","Initial state bytes do not match the hash"),Ir(t,n,i,o)}function cp(e,n,t){if(rt(n,t))return ["model"];let i=t?.type==="core"&&Dn(t.handler);return e==="denied"||i?["app"]:["model","app"]}function dp(e){return ne({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:Er(e.definition),...e.provenance===void 0?{}:{provenance:e.provenance},entryHash:e.resource.entryHash,resourceBinding:Be,tools:e.tools})}function pp(e){return ne({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:Er(e.definition)},resourceBinding:Object.freeze({kind:"mcp",uri:e.uiUri}),tools:e.tools})}function pt(e){try{if(Object.isFrozen(e))return Ae(e),ne(e);let n=On(e);return Ae(n),ne(n)}catch(n){if(n instanceof Se)throw n;S("STATE_INVALID","UI definition is not a valid immutable definition");}}function Er(e){return ne({id:e.id,version:e.version,hash:e.hash})}function lp(e){return e!==null&&typeof e=="object"&&typeof e.id=="string"&&Number.isSafeInteger(e.version)&&typeof e.hash=="string"}function fr(e,n,t){return `${e}\0${n}\0${t}`}function at(e,n){return (typeof e!="string"||!Jd.test(e))&&S("SERIALIZATION_INVALID",`${n} is invalid`),e}function ct(e){return createHash("sha256").update(Uint8Array.from(e)).digest("hex")}function dt(e,n){return (!Array.isArray(e)||e.some(t=>!Number.isInteger(t)||t<0||t>255))&&S("SERIALIZATION_INVALID",`${n} is invalid`),[...e]}function Tr(e){try{return new TextDecoder("utf-8",{fatal:!0}).decode(Uint8Array.from(e))}catch{S("SERIALIZATION_INVALID","UTF-8 bytes are invalid");}}function Pr(e){return (typeof e!="string"||!Xd.test(e))&&S("TOOL_INVALID","MCP App icon is invalid"),e}function br(e){return (typeof e!="string"||!Yd.has(e))&&S("TOOL_INVALID","MCP App tone is invalid"),e}function On(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(On(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:On(s,n),writable:true});return n.delete(t),o}function ne(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))ne(t,n);return Object.freeze(e),e}var yr,Ar,Jd,pn,Wd,Kd,Xd,Yd,qd,Be,Zd,Ln,ur,gr,gi,lt=F(()=>{m();Zo();Ge();Le();ot();it();Ii();dr();lr();st();yr=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,Ar=/^ui:\/\/crewx\/([A-Za-z][A-Za-z0-9._-]{0,127})\/([0-9a-f]{12})$/,Jd=/^[0-9a-f]{64}$/,pn=8*1024*1024,Wd=8*1024,Kd=16*1024,Xd=/^[a-z][a-z0-9-]{0,63}$/,Yd=new Set(["blue","violet","emerald","amber","rose","sky","slate","indigo"]),qd=new Set(sr),new Set(ar),Be=Object.freeze({kind:"instance"}),Zd=Object.freeze({type:"object",properties:Object.freeze({}),additionalProperties:false}),Ln=new WeakSet,ur=new WeakSet;gr=4;gi=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=rp(p);s.has(u.appId)&&S("APP_ID_CONFLICT",`MCP App id is already registered: ${u.appId}`),s.add(u.appId);let y=u.tools;for(let g of y)a.has(g.name)&&S("TOOL_ID_CONFLICT",`MCP App tool name is already registered: ${g.name}`),a.add(g.name),this.mcpToolByName.set(g.name,g),r.push(g);this.mcpResources.set(u.resource.uri,u.resource),i.push(u),o.push(u.descriptor);}let c=(n.localApps??n.locals??[]).map(sp),d=new Set(c.flatMap(p=>p.tools.filter(u=>!(u.kind==="action"&&"actionId"in u)).map(u=>u.name))),l=[];for(let p of c){let u=p;s.has(u.appId)&&S("APP_ID_CONFLICT",`MCP App id is already registered: ${u.appId}`),s.add(u.appId);let y=[],g=[...u.toolDiagnostics??[]];for(let _ of u.tools){if(a.has(_.name)){if(_.kind==="host"&&this.localToolByName.get(_.name)?.kind==="host"){y.push(_);continue}if(_.kind==="action"&&"actionId"in _){g.push(Object.freeze({toolName:_.name,actionId:_.actionId,reason:"name_collision"}));continue}S("TOOL_ID_CONFLICT",`MCP App tool name is already registered: ${_.name}`);}if(_.kind==="action"&&"actionId"in _&&d.has(_.name)){g.push(Object.freeze({toolName:_.name,actionId:_.actionId,reason:"name_collision"}));continue}a.add(_.name),this.localToolByName.set(_.name,_),y.push(_);}(y.length!==u.tools.length||g.length!==(u.toolDiagnostics?.length??0))&&(u=ne({...u,tools:Object.freeze(y),toolDiagnostics:Object.freeze(g)})),l.push(u),this.localById.set(u.appId,u);}for(let p of i)this.registrationById.set(p.appId,p),this.launcherById.set(p.appId,pp(p)),p.definition&&this.addDefinition(p.definition);for(let p of l)this.registrationById.set(p.appId,p),this.launcherById.set(p.appId,dp(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"||!Ar.test(n)?null:this.mcpResources.get(n)??null}requireMcpAppResource(n){mr(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(!lp(n))return null;let t=this.definitionByKey.get($t(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(fr(n,t,i))??null}addDefinition(n){let t=pt(n),i=$t(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=fr(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 up(e){let n=hr({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},...e.normalized.manifest.deviceFeatures===void 0?{}:{deviceFeatures:e.normalized.manifest.deviceFeatures},...e.normalized.manifest.downloads===void 0?{}:{downloads:e.normalized.manifest.downloads},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=up(e);_r({localApps:[t],definitions:[e.definition]});}var Dr=F(()=>{m();lt();});function fp(e){if(e===null||typeof e!="object"||!(Sr in e))throw new TypeError("scanCache must be created by createWorkspaceAppScanCache");return e[Sr]}function Mr(e,n){let t=fp(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 Sr,Lr=F(()=>{m();Sr=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 gp(e){if(typeof e!="string"||e.length===0||!isAbsolute(e))throw new M("READ_DENIED")}function _i(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 At(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 bi(e,n){return e.dev===n.dev&&e.ino===n.ino}function Ni(e,n){return bi(e,n)&&e.size===n.size&&e.mtimeNs===n.mtimeNs&&e.ctimeNs===n.ctimeNs}async function ut(e){gp(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 wr(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(!At(n,o))throw new M("PATH_ESCAPED");return o}async function ft(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(!At(n,r)||t!==void 0&&!At(t,r))throw new M("PATH_ESCAPED");if(!o.isFile()||!s.isFile())throw new M("READ_DENIED");if(!bi(i,o)||!bi(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||!Ni(n.identity,un(i)))throw new M("PATH_ESCAPED")}function mp(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,Pi,Ip,Rr,It,Cr,Si=F(()=>{m();M=class extends Error{constructor(t){super(t);this.code=t;}code;name="AppDiscoveryFsError"},Pi=constants.O_NOFOLLOW,Ip=constants.O_NONBLOCK,Rr=constants.O_RDONLY|(Pi??0)|(Ip??0);It=class{async getRootIdentity(n){let t=await ut(n);return await ln(n,t),{dev:t.identity.dev,ino:t.identity.ino,realPath:t.realRoot}}async listDirectory(n,t){let i=_i(t),o=await ut(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(!At(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(mp)}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(Pi===void 0)throw new M("UNSUPPORTED");let o=_i(t),r=await ut(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,Rr);}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 wr(n,r.realRoot,o);await ft(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 y;try{let g=await c.stat({bigint:!0});y=un(g);}catch(g){throw ue(g)}if(!Ni(d,y))throw new M("IDENTITY_CHANGED");return await ft(s,r.realRoot,l,y),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(Pi===void 0)throw new M("UNSUPPORTED");let o=_i(t),r=await ut(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,Rr);}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 wr(n,r.realRoot,o);await ft(s,r.realRoot,l,d);let p;try{let u=await c.stat({bigint:!0});p=un(u);}catch(u){throw ue(u)}if(!Ni(d,p))throw new M("IDENTITY_CHANGED");return await ft(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)}},Cr=new It;});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 kr(e){return typeof e=="string"&&Pe.test(e)?e:void 0}function Np(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 Dp(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 Sp(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 Mp(e){return Pp.decode(e)}function Lp(e){return JSON.parse(Mp(e))}function xr(e){switch(e){case "ENOENT":return "NOT_FOUND";case "ELOOP":case "EXDEV":return "PATH_ESCAPED";case "EFBIG":case "EOVERFLOW":return "LIMIT_EXCEEDED";case "EACCES":case "EPERM":case "ENOTDIR":return "READ_DENIED";default:return e}}function Op(e){if(e instanceof M)return xr(e.code);if(e!==null&&typeof e=="object"&&"code"in e){let n=e.code;if(typeof n=="string")return xr(n)}}function we(e,n){let t=n();return Number.isFinite(t)&&Number.isFinite(e)&&t-e<=5e3}function Rp(e){if(typeof e.readVerifiedFile=="function")return e.readVerifiedFile;if(typeof e.readFileVerified=="function")return e.readFileVerified}function wp(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 vr(e,n,t,i){let o=Rp(e);if(!o)throw new M("READ_DENIED");return Sp(await o.call(e,n,t,i))}async function Oi(e,n,t){let i=wp(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(Dp).filter(r=>r!==null)}function Cp(e,n,t,i){return Object.freeze({code:e,...{},source:n,relativePath:t})}function Up(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 kp(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 mt(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 gt(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 jr(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 xp(e){let n;try{n=Lp(e);}catch{return}if(!Un(n)||!gt(n,["version","packages"])||n.version!==1||!Array.isArray(n.packages)||n.packages.length>Ri)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(!gt(s,[...a,...l])||d&&s.launcher!==false)return;let p=jr(s.packageDir),u=kr(s.appId);if(!p||p.length!==2||p[0]!=="apps"||!Np(p[1])||!u||t.has(s.packageDir)||!Un(s.definition)||!gt(s.definition,["id","version","hash"]))return;let y=kr(s.definition.id),g=s.definition.version,_=s.definition.hash;if(!y||!Number.isSafeInteger(g)||g<1||typeof _!="string"||!Li.test(_)||!Array.isArray(s.files)||s.files.length<2||s.files.length>wi)return;let E=new Set,v=[];for(let j of s.files){if(!Un(j)||!gt(j,["path","sha256"]))return;let b=jr(j.path);if(!b||typeof j.sha256!="string"||!Li.test(j.sha256))return;let U=b.join("/"),H=`${s.packageDir}/${U}`;if(E.has(U)||i.has(H))return;E.add(U),i.add(H),v.push(Object.freeze({path:U,sha256:j.sha256}));}if(!ee.some(j=>E.has(j))||!E.has("ui/index.html")||(o+=v.length,o>_p))return;t.add(s.packageDir),r.push(Object.freeze({packageDir:s.packageDir,...d?{launcher:false}:{},appId:u,definition:Object.freeze({id:y,version:g,hash:_}),lineage:Array.isArray(s.lineage)?s.lineage:[],files:Object.freeze(v.sort((j,b)=>Xe(j.path,b.path)))}));}return Object.freeze({version:1,packages:Object.freeze(r)})}function Ke(e){let n=Op(e);return n==="PATH_ESCAPED"||n==="IDENTITY_CHANGED"||n==="TOCTOU"?"PATH_ESCAPED":n==="LIMIT_EXCEEDED"?"LIMIT_EXCEEDED":"BUNDLE_INTEGRITY"}async function vp(e,n,t,i,o){let r=[],s=async(a,c)=>{if(!we(i,o))throw new M("LIMIT_EXCEEDED");if(c>2)throw new M("LIMIT_EXCEEDED");let d=await Oi(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>wi)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 jp(e){return ee.includes(e)?262144:e==="ui/index.html"?pn:e==="ui/state.json"?2097152:e.startsWith("ui/assets/")?Tp:Ep}async function Fr(e,n,t,i){if(e===void 0)return {packages:[],diagnostics:[],incomplete:false,reservedIds:bp};let o=Up(e.reservedIds),r=[],s=(I,A,h)=>Cp(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"||!Li.test(e.expectedIndexHash))return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a();let c;try{c=await vr(n,e.root,"bundle-index.json",hp);}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=xp(c);if(l===void 0)return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a();if(!kp(mt(l.packages),o))return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a([],false,d);if(!we(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 Oi(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(!we(t,i))return r.push(s("LIMIT_EXCEEDED","bundle-index.json")),a(l.packages.map(I=>({indexEntry:I,failureCode:"LIMIT_EXCEEDED"})),true,d);let u=p.find(I=>I.name==="bundle-index.json"&&I.kind==="file"),y=p.find(I=>I.name==="apps"&&I.kind==="directory"),g=I=>l.packages.map(A=>({indexEntry:A,failureCode:I}));if(!u)return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a(g("BUNDLE_INTEGRITY"),false,d);let _=p.filter(I=>I.name!=="bundle-index.json"&&I.name!=="apps");if(_.length>0){let I=_.some(A=>A.kind==="symlink")?"PATH_ESCAPED":"BUNDLE_INTEGRITY";return r.push(s(I,"bundle-index.json")),a(g("BUNDLE_INTEGRITY"),false,d)}if(p.some(I=>I.name==="apps"&&I.kind!=="directory"))return r.push(s("PATH_ESCAPED","apps")),a(g("PATH_ESCAPED"),false,d);let E=[];if(y)try{E=await Oi(n,e.root,"apps");}catch(I){return r.push(s(Ke(I),"apps")),a(g(Ke(I)),false,d)}if(!we(t,i)||E.length>Ri)return r.push(s("LIMIT_EXCEEDED","apps")),a(g("LIMIT_EXCEEDED"),true,d);let v=new Map(l.packages.map(I=>[I.packageDir.slice(5),I])),j=E.filter(I=>!v.has(I.name));for(let I of j)r.push(s(I.kind==="symlink"?"PATH_ESCAPED":"BUNDLE_INTEGRITY",`apps/${I.name}`));if(j.length>0){let I=j.some(A=>A.kind==="symlink")?"PATH_ESCAPED":"BUNDLE_INTEGRITY";return a(g(I),false,d)}let b=new Set,U=new Map,H=new Map;for(let I of l.packages){let A=U.get(I.appId)??[];A.push(I),U.set(I.appId,A);let h=`${I.definition.id}\0${String(I.definition.version)}`,T=H.get(h)??[];T.push(I),H.set(h,T);}for(let I of [...U.values(),...H.values()])if(I.length>1)for(let A of I)b.add(A);let N=[],D=c.byteLength,L=false;for(let I of l.packages){if(!we(t,i)){L=true,N.push({indexEntry:I,failureCode:"LIMIT_EXCEEDED"});continue}let A;try{let w=I.lineage[I.lineage.length-1];if(!w)throw new Me("LINEAGE_INVALID","Definition lineage is missing");if(w.definition.id!==I.definition.id||w.version!==I.definition.version||w.hash!==I.definition.hash)throw new Me("LINEAGE_STALE","Last lineage generation does not match bundle identity");A=Ai(I.lineage,{...w.definition,hash:w.hash}).entries;}catch(w){let k=w instanceof Me?w.code:"LINEAGE_INVALID";r.push(s(k,I.packageDir)),N.push({indexEntry:I,failureCode:k});continue}let h=E.find(w=>w.name===I.packageDir.slice(5));if(!y||!h){N.push({indexEntry:I,failureCode:"BUNDLE_INTEGRITY"});continue}if(h.kind!=="directory"){N.push({indexEntry:I,failureCode:h.kind==="symlink"?"PATH_ESCAPED":"BUNDLE_INTEGRITY"});continue}let T;try{let w=await vp(n,e.root,I.packageDir,t,i);if(!we(t,i)){L=!0,N.push({indexEntry:I,failureCode:"LIMIT_EXCEEDED"});continue}let k=I.files.map(B=>B.path);if(w.length!==k.length||w.some((B,Te)=>B!==k[Te])){N.push({indexEntry:I,failureCode:"BUNDLE_INTEGRITY"});continue}T=new Map;let X;for(let B of I.files){if(!we(t,i)){X="LIMIT_EXCEEDED",L=!0;break}if(D>=Mi){X="LIMIT_EXCEEDED";break}let Te;try{Te=await vr(n,e.root,`${I.packageDir}/${B.path}`,jp(B.path));}catch(St){X=Ke(St);break}if(!we(t,i)){X="LIMIT_EXCEEDED",L=!0;break}if(D+Te.byteLength>Mi){D=Mi,X="LIMIT_EXCEEDED";break}if(D+=Te.byteLength,createHash("sha256").update(Te).digest("hex")!==B.sha256){X="BUNDLE_INTEGRITY";break}T.set(B.path,Te);}if(X!==void 0){N.push({indexEntry:I,failureCode:X});continue}}catch(w){we(t,i)||(L=true),N.push({indexEntry:I,failureCode:Ke(w)});continue}N.push({indexEntry:I,lineage:A,files:T,...b.has(I)?{failureCode:"DUPLICATE_ID"}:{}});}return a(N,L,d)}var hp,Ri,wi,_p,Ep,Tp,Mi,Li,Pp,bp,Ci=F(()=>{m();Ii();$e();nt();lt();Si();hp=256*1024,Ri=64,wi=128,_p=Ri*wi,Ep=2*1024*1024,Tp=8*1024*1024,Mi=32*1024*1024,Li=/^[0-9a-f]{64}$/,Pp=new TextDecoder("utf-8",{fatal:true}),bp=Object.freeze({appIds:Object.freeze([]),definitionIds:Object.freeze([])});});function Vp(e){if(typeof e!="string"||!Pe.test(e))throw new TypeError("pluginId must be a safe UI plugin identifier");let n=`${Ui}${e}`.length+7<=128?e:`hash_${createHash("sha256").update(e,"utf8").digest("hex")}`;return {read:`${Ui}${n}_read`,action:`${Ui}${n}_action`}}function Br(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 Hp(e,n){return n.length===0||n==="."||n===".."||/[\\/\u0000]/.test(n)?e==="skills"?"skills":"apps":`${e==="skills"?"skills":"apps"}/${n}`}function zp(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 Zr(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 $p(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 Qr(e){return Bp.decode(e)}function Gp(e){return JSON.parse(Qr(e))}function Jp(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 ht(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 Hr(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 Hr(e.code);if(e!==null&&typeof e=="object"&&"code"in e){let n=e.code;if(typeof n=="string")return Hr(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 zr(e){return {reason:e.reason,...e.code==="MANIFEST_DUAL_MISMATCH"?{files:e.files}:{}}}function $r(e){return e==="MANIFEST_DUAL_MISMATCH"?e:es(e)}function Wp(e){return es(e.code)}function es(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 ns("UiPluginValidationError",e)}}function ns(e,n){throw new Error(`Unmapped ${e} code: ${String(n)}`)}function ts(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 ns("McpAppContractError",e)}}function Ce(e,n){let t=n();return Number.isFinite(t)&&Number.isFinite(e)&&t-e<=5e3}function Kp(e){return {pluginId:e.appId,definitionKey:`${e.definition.id}\0${String(e.definition.version)}`}}function Xp(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(Br(o)){let r=o.bin,s=typeof r=="string"?r:Br(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=Yp(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 Yp(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 qp(){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 Gr(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 Xr(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 Xr(e,n.root,o,i),d=await s.call(e,r.workspaceRoot,o,i);return r.candidateRealPath=d.candidateRealPath,os(a,d)&&d.size===BigInt(c.byteLength)&&!rs(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&&!_t(l.key,t)),d=t===G&&se(a)==="NOT_FOUND"&&Qp(r.directoryListings,n.relativePath);throw !c&&!d&&(r.cacheable=false),a}}async function Zp(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 Qp(e,n){let t=e.find(o=>o.relativePath===n);if(t===void 0)return false;if(!_t(t.key,"dist"))return true;let i=e.find(o=>o.relativePath===`${n}/dist`);return i!==void 0&&!_t(i.key,"tools.json")}function is(e,n){return JSON.stringify([e.realPath,n.source,n.relativePath])}async function nl(e,n,t,i,o,r,s,a){let c=e.fingerprintVerifiedFile,d=is(t,i),l=o.candidates.get(d),p=i.relativePath,u;try{u=await Kr(e,n,p);}catch(L){if(se(L)!=="NOT_FOUND")throw L}let y=u===void 0?void 0:{relativePath:p,key:u};if(y!==void 0&&(i.source==="apps"||i.source==="skills")&&!ee.some(L=>_t(y.key,L)))return Ce(s,a)?l!==void 0&&l.candidate===void 0&&l.candidateRealPath===void 0&&l.files.length===0&&l.directoryListings.length===1&&l.directoryListings[0]?.relativePath===y.relativePath&&l.directoryListings[0]?.key===y.key&&(i.source==="apps"?l.diagnostic?.code==="MANIFEST_MISSING":l.diagnostic===void 0)&&typeof c=="function"?{memo:l}:typeof c!="function"?{}:{context:{state:o,cacheKey:d,workspaceRoot:n,scanStartedAtNs:r,directoryListings:Object.freeze([y]),priorFingerprints:new Map,files:new Map,cacheable:true}}:{timeLimitReached:true};let g=async L=>{if(L==="")return y;let I=`${i.relativePath}${L}`;try{let A=await Kr(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(Jr.map(g)),E=await Promise.all(el.map(g));if(!Ce(s,a))return {timeLimitReached:true};let v=typeof c=="function"&&_.every(L=>L!==void 0),j=_.filter(L=>L!==void 0),b=[...j,...E.filter(L=>L!==void 0)],U=new Map,H=l!==void 0&&v,N;if(l!==void 0&&typeof c=="function"){let L=await Promise.all(l.files.map(async I=>{if(!Ce(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"){H=false;continue}if(I.kind!=="fingerprint")continue;let{file:A,current:h}=I;U.set(A.relativePath,h),N??=h.candidateRealPath,(h.candidateRealPath!==l.candidateRealPath||!os(h,A.fingerprint)||rs(h,r))&&(H=false);}}let D=l!==void 0&&l.directoryListings.length===b.length&&l.directoryListings.every((L,I)=>L.relativePath===b[I]?.relativePath&&L.key===b[I]?.key);return l!==void 0&&v&&D&&H&&N===l.candidateRealPath?{memo:l}:!v||j.length!==Jr.length?{}:{context:{state:o,cacheKey:d,workspaceRoot:n,scanStartedAtNs:r,directoryListings:Object.freeze(b),priorFingerprints:U,files:new Map,...N===void 0?{}:{candidateRealPath:N},cacheable:true}}}function _t(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 Kr(e,n,t){let i=ss(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(Zr);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 os(e,n){return e.dev===n.dev&&e.ino===n.ino&&e.size===n.size&&e.mtimeNs===n.mtimeNs&&e.ctimeNs===n.ctimeNs}function rs(e,n){let t=e.mtimeNs-n;return t>=-Wr&&t<=Wr}function ki(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 tl(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 il(e,n){let t={...e.definition,sourceHash:n},i;try{i=le(t);}catch(r){throw r instanceof x&&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 ol(e,n){return e.actions.some(t=>t.backend.type==="core"&&t.backend.handler!=="state.set"&&!rt(n,t.backend))}function rl(e){if(typeof e.readVerifiedFile=="function")return e.readVerifiedFile;if(typeof e.readFileVerified=="function")return e.readFileVerified}function ss(e){if(typeof e.listDirectory=="function")return e.listDirectory;if(typeof e.readDirectory=="function")return e.readDirectory;if(typeof e.readdir=="function")return e.readdir}async function Xr(e,n,t,i){let o=rl(e);if(!o)throw new M("READ_DENIED");return $p(await o.call(e,n,t,i))}async function sl(e,n,t){let i=ss(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(Zr).filter(r=>r!==null)}function al(e){let n=[];for(let t of [e.reserved,e.builtin])t&&n.push(t);return e.builtins&&"listMcpApps"in e.builtins?n.push(Yr(e.builtins)):e.builtins&&n.push(e.builtins),e.builtinCatalog&&n.push(Yr(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 Yr(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=ht(n,e.source,e.relativePath,e.identity?.pluginId));}function cl(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 dl(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 al(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(y=>y!==void 0).some(y=>r.has(y))&&_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 Se?ts(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 pl(e){return [...e].sort((n,t)=>{let i=Vr.indexOf(n.source)-Vr.indexOf(t.source);return i!==0?i:xn(n.relativePath,t.relativePath)})}function z(e,n,t){e.diagnostic=ht(n,e.source,e.relativePath,e.identity?.pluginId,t);}async function qr(e,n,t){let i=Ve(t,{mode:"local"});if(!i.ok&&i.parseFailure){z(n,$r(i.rejection.code),zr(i.rejection));return}let o=Jp(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)}`){z(n,"BUNDLE_INTEGRITY");return}if(!i.ok&&i.builtinOnly){z(n,"RESERVED_ID");return}if(!i.ok){z(n,$r(i.rejection.code),zr(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{hi(r.actions.map(k=>({actionId:k.actionId,inputSchema:k.inputSchema})));}catch(k){if(k instanceof Se){z(n,ts(k.code));return}throw k}let a;try{a=await vn(e,n,"ui/index.html",pn);}catch(k){z(n,qe(se(k),"entry"));return}if(a.byteLength>pn){z(n,"LIMIT_EXCEEDED");return}let c;try{c=Qr(a);}catch{z(n,"ENTRY_INVALID");return}if(a.byteLength===0||c.length===0){z(n,"ENTRY_INVALID");return}let d=createHash("sha256").update(a).digest("hex");if(r.entryHash!==void 0&&r.entryHash!==d){z(n,"ENTRY_INVALID");return}let l={},p,u;if(r.initialState!==void 0){try{p=await vn(e,n,"ui/state.json",2097152);}catch(k){z(n,qe(se(k),"initial"));return}if(p.byteLength>2097152){z(n,"LIMIT_EXCEEDED");return}try{let k=Gp(p),X=r.dataPaths??[],B=ti(k,X);l=ye(B,0,X),nn(l);}catch{z(n,"INITIAL_STATE_INVALID");return}if(u=createHash("sha256").update(p).digest("hex"),r.initialState.hash!==void 0&&r.initialState.hash!==u){z(n,"INITIAL_STATE_INVALID");return}}let y={...r,entryHash:d,...r.initialState===void 0?{}:{initialState:{path:"ui/state.json",hash:u}}},g=hn(y),_=tl(y,a,p??new Uint8Array),E;try{E=il(g,_);}catch(k){if(k instanceof ce){z(n,Wp(k));return}throw k}let v;if(n.bundleLineage!==void 0){let k=n.bundleLineage[n.bundleLineage.length-1];if(!k){z(n,"LINEAGE_INVALID");return}let{legacy:X,...B}=k.definition,{hash:Te,...St}=E;if(ie(B)!==ie(St)){z(n,"LINEAGE_STALE");return}if(X!==void 0&&(E={...E,legacy:X}),X!==void 0)try{E={...E,hash:le(E)},Ae(E);}catch{z(n,"LINEAGE_INVALID");return}v=n.bundleLineage;}if(n.bundleIdentity!==void 0&&n.bundleIdentity.appId!==r.pluginId){z(n,"BUNDLE_INTEGRITY");return}if(n.bundleIdentity!==void 0&&(n.bundleIdentity.definitionId!==E.id||n.bundleIdentity.version!==E.version||n.bundleIdentity.definitionHash!==E.hash)){z(n,"LINEAGE_STALE");return}let j=await Zp(e,n,i.mcpb?.icon),b=Vp(r.pluginId),U=r.actions.length===0?{read:b.read}:b,H=Ye(g),N=Ye(y),D=Ye(E),L=Ye({...g.handlers}),I=Gr(a),A=p===void 0?void 0:Gr(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})}}),T={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:H,name:r.name,description:r.description,...r.icon===void 0?{}:{icon:r.icon},...r.tone===void 0?{}:{tone:r.tone},...j.iconFile===void 0?{}:{iconFile:Object.freeze({...j.iconFile})},...j.iconDiagnostics.length===0?{}:{iconDiagnostics:Object.freeze([...j.iconDiagnostics])},definition:D,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(U)},w=n.provenance===void 0?{...T,source:n.source}:{...T,provenance:n.provenance,lineage:v??[]};n.candidate=Object.freeze(w),ol(r,E.usage)&&z(n,"EXEC_DENIED");}async function as(e,n){let t={};for(let i of ee)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[K]!==void 0)try{t[G]=await vn(e,n,G,262144);}catch(i){if(se(i)!=="NOT_FOUND")return {files:t,failure:qe(se(i),"manifest")}}return {files:t}}function xi(e){return ee.some(n=>e[n]!==void 0)}async function ll(e,n){let{files:t,failure:i}=await as(e,n);if(i!==void 0){z(n,i);return}let o=t[K];return o!==void 0&&!di(o)&&(delete t[K],delete t[G]),xi(t)?t:void 0}function ul(e,n,t,i=Fp,o=false,r=new Set){let s=pl(e),a=cl(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 fl(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 yl(e,n){if(fl(e))return {fs:e,options:{}};let t=e??n??{};return {fs:t.filesystem??t.fileSystem??t.fs??Cr,options:t}}async function cs(e,n,t){if(typeof e!="string"||e.length===0)throw new TypeError("workspaceRoot must be explicit");let{fs:i,options:o}=yl(n,t),r=o.clock??qp,s=r(),a=await Fr(o.productBundle,i,s,r),c=r(),d=BigInt(Date.now())*1000000n,l=[],p=0,u,y=false,g,_;if(o.scanCache!==void 0&&typeof i.getRootIdentity=="function"&&typeof i.fingerprintVerifiedFile=="function")try{_=await i.getRootIdentity(e),g=Mr(o.scanCache,_),g.scanStartedAtNs=d;}catch(N){if(se(N)!=="NOT_FOUND")throw N}let E=g!==void 0&&o.productBundle===void 0&&a.packages.length===0&&a.diagnostics.length===0,v=new Set,j=true;l.push(...a.diagnostics.map(N=>({source:N.source,root:o.productBundle?.root??e,name:"",relativePath:N.relativePath,diagnostic:N})));let b=a.reservedIds;a.incomplete&&(u="time_limit");for(let N of a.packages){if(!Ce(c,r)){y=true,u="time_limit";break}let D=N.indexEntry,L=D.packageDir,I=N.files===void 0?void 0:Xp(L,N.files),A=a.indexHash===void 0?void 0:er(Object.freeze({kind:"bundled",launcher:D.launcher!==false,indexHash:a.indexHash,packageDir:L,appId:D.appId,definitionId:D.definition.id,version:D.definition.version,definitionHash:D.definition.hash,files:D.files}),I),h={source:"bundled",root:o.productBundle?.root??e,name:L.slice(5),relativePath:L,...A===void 0?{}:{provenance:A},...N.files===void 0?{}:{pinnedFiles:N.files},...N.lineage===void 0?{}:{bundleLineage:N.lineage},bundleIdentity:{appId:D.appId,definitionId:D.definition.id,version:D.definition.version,definitionHash:D.definition.hash},identity:Kp(D)};if(l.push(h),p+=1,N.failureCode!==void 0){z(h,N.failureCode);continue}if(N.files?.has(G)===true){z(h,"EXEC_DENIED",{reason:{path:"",rule:"bundled-tool-mode-unsupported",file:G}});continue}let T={};for(let w of ee){let k=N.files?.get(w);k!==void 0&&(T[w]=k);}if(!xi(T)){z(h,"BUNDLE_INTEGRITY");continue}if(await qr(i,h,T),!Ce(c,r)){y=true,u="time_limit";break}}let U=[{source:"apps",directory:"apps"},{source:"skills",directory:"skills"}];e:for(let N of U){let{source:D,directory:L}=N,I;try{I=await sl(i,e,L);}catch(h){if(se(h)==="NOT_FOUND")continue;E=false,j=false,l.push({source:D,root:e,name:"",relativePath:D,diagnostic:ht(qe(se(h),"manifest"),D,D)});continue}let A=I.filter(h=>h.kind==="directory"||h.kind==="symlink").filter(h=>zp(h.name)).map(h=>({source:D,root:e,name:h.name,relativePath:Hp(D,h.name)})).sort((h,T)=>xn(h.relativePath,T.relativePath));for(let h of A){let T={...h};if(l.push(T),_!==void 0?v.add(is(_,T)):E=false,!Ce(c,r)){y=true,u="time_limit";break e}let w;if(g!==void 0&&_!==void 0){try{let B=await nl(i,e,_,T,g,d,c,r);if(B.timeLimitReached){y=!0,u="time_limit";break e}T.scanContext=B.context,w=B.memo;}catch(B){E=false,z(T,qe(se(B),"manifest"));continue}w===void 0&&(E=false);}if(w!==void 0){if(T.candidate=w.candidate,T.diagnostic=w.diagnostic,T.identity=w.identity,D==="skills"&&w.candidate===void 0&&w.diagnostic===void 0)continue;if(p>=64){z(T,"LIMIT_EXCEEDED");continue}if(h.relativePath.split("/").length-1>2){z(T,"LIMIT_EXCEEDED");continue}if(p+=1,!Ce(c,r)){y=true,u="time_limit";break e}continue}let k;if(D==="skills"&&(k=await ll(i,T),k===void 0)){T.diagnostic===void 0&&ki(T);continue}if(p>=64){z(T,"LIMIT_EXCEEDED");continue}if(h.relativePath.split("/").length-1>2){z(T,"LIMIT_EXCEEDED");continue}if(!Ce(c,r)){y=true,u="time_limit";break e}if(p+=1,k===void 0){let B=await as(i,T);if(B.failure!==void 0||!xi(B.files)){z(T,B.failure??qe("NOT_FOUND","manifest")),ki(T);continue}k=B.files;}if(await qr(i,T,k),ki(T),!Ce(c,r)){y=true,u="time_limit";break e}}}if(g!==void 0&&_!==void 0){let N=[...v].sort(xn),D=g.lastCandidateKeys,L=D!==void 0&&D.length===N.length&&D.every((A,h)=>A===N[h]);if(E=E&&L,j&&!y&&u===void 0)for(let A of g.candidates.keys())try{JSON.parse(A)[0]===_.realPath&&!v.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}});E=E&&I.length===v.size&&I.every(A=>v.has(A))&&!y&&u===void 0,g.lastCandidateScanUnchanged=E,j&&!y&&u===void 0&&(g.lastCandidateKeys=Object.freeze(N));}y&&l.push({source:"apps",root:e,name:"",relativePath:"apps",diagnostic:ht("DISCOVERY_TIME_LIMIT","apps","apps")});let H=dl(l,o,b);return ul(l,u,a.indexHash,b,o.productBundle!==void 0,H)}var Fp,Ui,Vr,Bp,Jr,el,Wr,ds=F(()=>{m();Ge();Fn();Le();ui();li();$e();lt();Dr();st();it();Lr();Si();ot();Ci();Ci();Fp=mt([]),Ui="crewx_local_app_";Vr=["bundled","apps","skills"],Bp=new TextDecoder("utf-8",{fatal:true});Jr=["","/ui"],el=["/dist"],Wr=2000000000n;});m();ui();m();Jt();m();var Bo="SKILL.md",Nd=/^---\s*\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;function Ho(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function Dd(e){return e.isDirectory()||e.isSymbolicLink()}function Wo(e){try{return existsSync(e)&&statSync(e).isDirectory()}catch{return false}}function fi(e){let n;try{n=readFileSync(e,"utf8");}catch{return {frontmatter:{},readable:false,valid:false,hasFrontmatter:false}}let t=n.match(Nd);if(!t)return {frontmatter:{},readable:true,valid:true,hasFrontmatter:false};try{let i=load(t[1]??"");if(!Ho(i))return {frontmatter:{},readable:!0,valid:!1,hasFrontmatter:!0};let o=Ho(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 Sd(e){return [join(e,Bo),join(e,"skill",Bo)]}function zo(e,n){if(!Wo(e))return null;for(let t of Sd(e)){if(!existsSync(t))continue;let o=fi(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(Dd)}catch{return []}}function Go(e,n,t){!e||n.has(e.name)||(n.add(e.name),t.push(e));}function Ko(e){let n=[],t=new Set;for(let i of e)if(Wo(i))for(let o of $o(i)){if(o.name.startsWith("@")){let r=join(i,o.name);for(let s of $o(r))Go(zo(join(r,s.name),s.name),t,n);continue}Go(zo(join(i,o.name),o.name),t,n);}return n.sort((i,o)=>i.name.localeCompare(o.name))}m();nt();var Md=/^[A-Za-z0-9_$.[\]"-]{0,200}$/,Ld=/^[a-z][a-z0-9-]{0,63}$/,Od="<unknown>";function Rd(e){return typeof e=="string"&&(ee.includes(e)||e===G)}function Xo(e){if(typeof e!="object"||e===null)return;let{file:n,path:t,rule:i}=e;if(!(typeof i!="string"||!Ld.test(i)))return {...Rd(n)?{file:n}:{},path:typeof t=="string"&&Md.test(t)?t:Od,rule:i}}function Yo(e){if(!Array.isArray(e))return;let n=ee.filter(t=>e.includes(t));return n.length>0?n:void 0}ds();var Il=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/;function Pt(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?gl(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 gl(e,n){let t=new TextEncoder().encode(bt(e)),i=ml(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 ml(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 bt(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 Et(e,n){let t=new TextEncoder().encode(e),i=new TextEncoder().encode(n),o=Math.min(t.byteLength,i.byteLength);for(let r=0;r<o;r+=1){let s=t[r]-i[r];if(s!==0)return s}return t.byteLength-i.byteLength}function us(e,n){let t=relative(e,n).split(sep).join("/");return !t||t===".."||t.startsWith("../")||isAbsolute(t)?null:bt(t)}function hl(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 fs(e){return Object.freeze({packageRoot:e})}function _l(e){return Object.freeze({id:e.definition.id,version:e.definition.version,hash:e.definition.hash,usage:e.definition.usage??ve,...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 ys(e){return {capabilities:Object.freeze([...e]),origin:"local",ownership:"unknown",shareability:"unknown",sharingAvailability:"unavailable"}}function El(e,n){let t=e.candidate,i=t.provenance!==void 0,o=n&&!i?["screen","skill"]:["screen"],r=_l(t),s=Pt(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,...ys(o),definition:r,...n===void 0||i?{}:{skillName:n.skill.name},...i?{provenance:t.provenance}:{localDefinitionRef:fs(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 Tl(e){let n=Pl(e.skill.name),t={appId:n,name:e.skill.name,description:e.skill.description??"",...e.skill.version===void 0?{}:{version:e.skill.version},...ys(["skill"]),skillName:e.skill.name,localDefinitionRef:fs(e.packageRoot),definitionHash:Pt({skillHash:e.skillHash})};return {packageRoot:e.packageRoot,source:e.source,appId:n,capabilities:["skill"],summary:Object.freeze(t)}}function Pl(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=Xo(o?.reason),s=Yo(o?.files);return Object.freeze({code:e,source:n,relativePath:bl(t),...i===void 0?{}:{appId:i},...r===void 0?{}:{reason:r},...s===void 0?{}:{files:s}})}function bl(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 As(e){return Q(e.code,e.source,e.relativePath,e.pluginId,e)}function Nl(e,n){let t=us(e,n.dir);if(!t)return {diagnostic:Q("PATH_ESCAPED","node_modules","node_modules")};let i=hl(t);if(!i)return {diagnostic:Q("PATH_ESCAPED","node_modules",t)};let o=fi(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=Dl(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:Pt({relativePath:r,fileBytes:s}),source:i}}catch{return {diagnostic:Q("SKILL_READ_FAILED",i,t)}}}function Dl(e,n){let t=relative(e,n).split(sep).join("/");try{return bt(t)}catch{return null}}function Sl(e){if(!Il.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??ve,...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 Ml(e){return e.builtinCatalog}function Ll(e){let n=e.packageRoot??e.relativePath??e.packageRootPath;if(n===void 0)return null;try{return bt(n)}catch{return null}}function Ol(e){let n=e.marketplaceContentId;return typeof n=="string"&&n.length>0?n:void 0}function Rl(e,n,t){let i=n.installed??[],o=new Map;for(let s of i){let a=Ll(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=Ol(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 wl(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,Tt(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,Tt(a),a.appId));if(s.length>1)for(let a of s)i.add(a),n.push(Q("DUPLICATE_ID",a.source,Tt(a),a.appId));continue}for(let s of o)i.add(s),n.push(Q("DUPLICATE_ID",s.source,Tt(s),s.appId));}return e.filter(o=>!i.has(o))}function Tt(e){return e.packageRoot??e.summary.provenance?.packageDir??`builtin/${e.appId}`}function Cl(e,n){return e.filter(t=>!(t.code==="MANIFEST_MISSING"&&n.has(t.relativePath))).map(As)}function Ul(e){return e.filesystem}function kl(e,n){let t=Ul(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 Is(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=Ml(n),i=await cs(e,kl(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 Ko([A])){let T=us(e,h.dir);(T===null||!d.has(T))&&(c.push(h),T!==null&&d.add(T));}for(let A of c){let h=Nl(e,A);"diagnostic"in h?s.push(h.diagnostic):a.push(h);}let l=new Map,p=n.registeredProductBundle?.indexHash,u=(n.registeredProductBundle?.candidates??[]).filter(A=>p!==void 0&&A.provenance?.indexHash===p),y=[...new Set([...i.apps??i.candidates??[],...i.productBundleSnapshotMetadata?.candidates??[]]),...u],g=new Set(u),_=new Set(p===void 0?[]:(t?.listMcpApps()??[]).filter(A=>A.provenance?.indexHash===p).map(A=>A.appId));for(let A of y){if(g.has(A)&&A.provenance?.indexHash===p&&_.has(A.appId))continue;let h=A.provenance===void 0?`workspace\0${A.relativePath}`:`bundled\0${A.provenance.indexHash}\0${A.provenance.packageDir}`;l.set(h,{candidate:A,packageRoot:A.relativePath});}let E=new Map(a.map(A=>[A.packageRoot,A])),v=[];for(let A of l.values()){let h=A.candidate.provenance===void 0?E.get(A.packageRoot):void 0,T=El(A,h);v.push({...T.packageRoot===void 0?{}:{packageRoot:T.packageRoot},source:T.source,appId:T.appId,summary:T.summary});}let j=new Set([...l.values()].filter(A=>A.candidate.provenance===void 0).map(A=>A.packageRoot)),b=o===void 0?new Set:new Set(i.diagnostics.filter(A=>A.code==="RESERVED_ID"&&A.source!=="bundled").map(A=>A.relativePath)),U=new Set(o?.reservedAppIds??[]);for(let A of a){let h=Tl(A);if(!(j.has(A.packageRoot)||b.has(A.packageRoot))){if(U.has(h.appId)){s.push(Q("RESERVED_ID",A.source,A.packageRoot,h.appId));continue}v.push({packageRoot:h.packageRoot,source:h.source,appId:h.appId,summary:h.summary});}}let H=[...Cl(i.diagnostics,new Set(a.map(A=>A.packageRoot))),...s,...n.registeredProductBundle?.diagnostics.filter(A=>A.source==="bundled").map(As)??[]],N=[];if(t)for(let A of t.listMcpApps()){let h=Sl(A);"diagnostic"in h?H.push(h.diagnostic):N.push(h);}let D=wl([...v,...N],H);Rl(D,n,H);let L=D.map(A=>A.summary).sort((A,h)=>Et(A.appId,h.appId)),I=[...H].sort((A,h)=>Et(A.relativePath,h.relativePath)||Et(A.code,h.code)||Et(A.appId??"",h.appId??""));return Object.freeze({items:Object.freeze(L),diagnostics:Object.freeze(I)})}m();m();m();function xl(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 xl(n).test(e)}catch{return false}}function Nt(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 vl(e,n){return e.split("/").some(t=>fn(t,n))}var gs=[{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&&Nt(n,".crewx","threads")},{label:".crewx/crewx.db",test:(e,n,t)=>!t&&Nt(n,".crewx","crewx.db")},{label:".crewx/*.log",test:(e,n,t)=>!t&&Nt(n,".crewx","*.log")},{label:".crewx/publish/",test:(e,n,t)=>t&&Nt(n,".crewx","publish")},{label:".crewx/",test:(e,n)=>vl(n,".crewx")}];function yn(e,n,t){for(let i of gs)if(i.test(e,n,t))return i.label;return null}m();var Ue=class extends Error{constructor(t,i){super(`publish: [${t}]${i?` ${i}`:""}`);this.code=t;}code;name="PublishError"};function P(e,n){return new Ue(e,n)}function ms(e,n){if(!n||/[\\\u0000]/.test(n)||de.posix.isAbsolute(n)||n.split("/").some(y=>!y||y==="."||y===".."))throw P("PACKAGE_PATH_TRAVERSAL","package root must be a safe workspace-relative path");let t=de.resolve(e),i=de.resolve(t,...n.split("/"));if(!i.startsWith(`${t}${de.sep}`))throw P("PACKAGE_PATH_TRAVERSAL","package root escaped the workspace");function o(y,g){let _;try{_=te.lstatSync(y);}catch{throw P("PACKAGE_FILE_INVALID",`package directory is missing: ${g}`)}if(_.isSymbolicLink())throw P("PACKAGE_SYMLINK",`symlink is not publishable: ${g}`);if(!_.isDirectory())throw P("PACKAGE_FILE_INVALID",`not a package directory: ${g}`)}o(t,".");let r=t,s="",a=null;for(let y of n.split("/"))r=de.join(r,y),s=s?`${s}/${y}`:y,o(r,s),a??=yn(y,s,true);let c=[],d=[];function l(y,g){o(y,g);let _=te.readdirSync(y,{withFileTypes:true});for(let E of _){let v=`${g}/${E.name}`,j=de.join(y,E.name);if(E.isSymbolicLink())throw P("PACKAGE_SYMLINK",`symlink is not publishable: ${v}`);let b=yn(E.name,v,E.isDirectory());b?d.push({path:v,rule:b}):E.isDirectory()?l(j,v):E.isFile()&&c.push(v);}}a?d.push({path:n,rule:a}):l(i,n);let p=new TextEncoder,u=(y,g)=>Buffer.compare(p.encode(y),p.encode(g));return c.sort(u),d.sort((y,g)=>u(y.path,g.path)),{included:c,excluded:d}}function hs(e){let n=[],t=[];function i(o,r,s){let a;try{a=te.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=te.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 jl=[{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 Fl(e){return e.includes(0)}function Vi(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?te.readFileSync(r):Buffer.from(c);}catch{continue}if(Fl(s))continue;s.toString("utf8").split(/\r\n|\r|\n/).forEach((c,d)=>{for(let{rule:l,regex:p}of jl)p.test(c)&&i.push({path:o,line:d+1,rule:l});});}return i}m();var Ts=/^[a-z0-9-]+$/,Vl=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/,Bl=/^[A-Za-z_][A-Za-z0-9_]*$/;function Hl(e){let n=de.join(e,"crewx.yaml");if(!te.existsSync(n))return {};let t;try{t=Ps.load(te.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 zl(e){return Bi.createHash("sha256").update(e).digest("hex")}function bs(e){let n;try{n=te.lstatSync(e);}catch{throw P("PACKAGE_FILE_INVALID",`file is not readable: ${de.basename(e)}`)}if(n.isSymbolicLink())throw P("PACKAGE_SYMLINK","symlink content is not publishable");if(!n.isFile())throw P("PACKAGE_FILE_INVALID","only regular files are publishable");return Bi.createHash("sha256").update(new Uint8Array(te.readFileSync(e))).digest("hex")}function $l(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")||de.posix.isAbsolute(e)||e.split("/").some(n=>n===".."||n.length===0))throw P("PACKAGE_PATH_TRAVERSAL","manifest file path must be a non-empty POSIX relative path")}function Gl(e){if(!/^(?:apps|skills)\/[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(e))throw P("APP_PACKAGE_ROOT_INVALID","packageRoot must be apps/<safe-id> or skills/<safe-id>")}function Ds(e){if(!Vl.test(e))throw new Error(`publish: invalid version "${e}" \u2014 must be semver (e.g. 1.0.0)`)}function Ss(e,n,t={}){let i=Hl(e),o=i.name??de.basename(e);if(!Ts.test(o))throw new Error(`publish: invalid name "${o}" \u2014 must match ${Ts} (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");Ds(r);let s=Array.isArray(i.requiredEnv)?i.requiredEnv:[],a=[];for(let l of s){if(typeof l!="string"||!Bl.test(l))throw new Error(`publish: requiredEnv must contain names only (no values), got "${String(l)}"`);a.push(l);}let c=n.map(l=>(Ns(l),{path:l,sha256:bs(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 Jl(e){let n=e.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"");if(!n)throw P("APP_PACKAGE_ROOT_INVALID","appId cannot produce a marketplace name");return n}function Ms(e,n){if(Gl(n.packageRoot),!n.version)throw new Error("publish: version is required for App publishing \u2014 pass opts.version");if(Ds(n.version),typeof n.description!="string")throw new Error("publish: App description must be a string");let t=[...new Set(n.capabilities)].sort();if(t.length===0||t.some(s=>s!=="screen"&&s!=="skill"))throw new Error("publish: App capabilities must contain screen or skill");let i=`${n.packageRoot}/`;if(t.includes("screen")){if(typeof n.definitionId!="string"||n.definitionId.length===0)throw P("APP_UI_MANIFEST_INVALID","screen App manifests require definitionId");let s=n.includedFiles.includes(`${i}manifest.json`),a=n.includedFiles.includes(`${i}ui-plugin.json`);if(!s&&!a)throw P("APP_UI_MANIFEST_INVALID","screen App is missing manifest.json or ui-plugin.json");if(s&&!a)throw P("APP_UI_MANIFEST_INVALID","a manifest.json App must also ship a generated ui-plugin.json");if(!n.includedFiles.includes(`${i}ui/index.html`))throw P("APP_UI_MANIFEST_INVALID","screen App is missing ui/index.html")}if(t.includes("skill")&&!n.includedFiles.includes(`${i}SKILL.md`))throw P("APP_SKILL_MISSING","skill capability requires package-root SKILL.md");let o=new Set,r=n.includedFiles.map(s=>{if(Ns(s),!s.startsWith(i))throw P("PACKAGE_PATH_TRAVERSAL","App manifest file is outside packageRoot");let a=n.generatedFiles?.get(s);return a!==void 0&&o.add(s),{path:s,sha256:a===void 0?bs(de.join(e,s)):zl(a),...a===void 0?{}:{generated:true}}}).sort((s,a)=>$l(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:Jl(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 Ls(e){return Bi.createHash("sha256").update(e).digest("hex")}function Us(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 P("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 P("PACKAGE_PATH_TRAVERSAL","archive path escaped its root");return i}function Os(e,n){let t=Us(e,n),i;try{i=te.lstatSync(t);}catch{throw P("PACKAGE_FILE_INVALID","manifest file is missing")}if(i.isSymbolicLink())throw P("PACKAGE_SYMLINK","symlink content is not publishable");if(!i.isFile())throw P("PACKAGE_FILE_INVALID","only regular files are publishable");return new Uint8Array(te.readFileSync(t))}async function ks(e,n,t={}){let i=de.join(e,".crewx","publish");te.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=te.mkdtempSync(de.join(Rs.tmpdir(),"crewx-publish-"));try{let a=new Set,c=[];for(let d of n.files){if(a.has(d.path))throw P("PACKAGE_PATH_TRAVERSAL","manifest contains duplicate file paths");a.add(d.path);let l=t.generatedFiles?.get(d.path);if(d.generated===!0&&l===void 0)throw P("PACKAGE_GENERATED_FILE_MISSING","generated manifest file bytes are missing");if(t.sourceFileHashes?.has(d.path)){let y=Os(e,d.path);if(t.sourceFileHashes.get(d.path)!==Ls(y))throw P("PACKAGE_STAGED_BYTES_MISMATCH","workspace source changed before staging")}let p=l??Os(e,d.path);if(Ls(p)!==d.sha256)throw P("PACKAGE_STAGED_BYTES_MISMATCH",`staged bytes differ for ${d.path}`);let u=Us(s,d.path);te.mkdirSync(de.dirname(u),{recursive:!0}),te.writeFileSync(u,new Uint8Array(p)),c.push(d.path);}te.writeFileSync(de.join(s,"manifest.json"),JSON.stringify(n,null,2)),await Cs.create({gzip:!0,file:r,cwd:s,portable:!0,noMtime:!0},["manifest.json",...c]),te.renameSync(r,o);}finally{try{te.rmSync(r,{force:!0});}catch{}te.rmSync(s,{recursive:true,force:true});}return o}m();m();var An="/api/v1";var Xl=201,Yl=200,ql=409,Hi=401,xs={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 Zl(){return process.env.WI013_FAKE_UPLOAD==="1"}function Ql(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 eu(e){return e.replace(/\/+$/,"")}async function jn(e){try{return await e.json()}catch{return null}}function vs(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 nu(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 tu(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 js(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(xs,r))continue;let s=r,a=s==="APP_NAME_CONFLICT"?`marketplace name is already in use: ${n}`:void 0;return P(xs[s],a)}}async function iu(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=eu(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 jn(a),d=nu(c),l=tu(c),p=r&&l!==void 0?l:i,u;if(a.status===Xl)u="created";else if(r&&a.status===Yl){if(d===void 0)throw P("PUBLISH_CONTENT_ID_MISSING","App republish did not return an opaque contentId");u="existing";}else if(a.status===ql){if(r)throw js(c,i)??P("APP_NAME_CONFLICT",`marketplace name is already in use: ${i}`);u="existing";}else throw a.status===Hi?new Error("publish: [E_AUTH_EXPIRED] Authentication is expired or missing \u2014 please log in again (HTTP 401)"):new Error(`publish: [E_HTTP] Submit request failed \u2014 HTTP ${a.status}`);let y="not-needed",g=null;if(u==="existing"&&!r){let D;try{D=await fetch(`${n}${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 jn(D);if(D.status!==200)throw new Error(`publish: [E_HTTP] Publisher items request failed \u2014 HTTP ${D.status}`);let A=vs(L,"publisher items",D.status)?.items;if(!Array.isArray(A))throw new Error(`publish: [E_MALFORMED] Publisher items response is malformed (expected data.items[]) \u2014 HTTP ${D.status}`);let h=A.find(T=>!T||typeof T!="object"?false:T.slug===i);if(!h||typeof h.version!="string")throw new Error(`publish: [E_MALFORMED] Publisher items response does not contain slug "${i}" \u2014 HTTP ${D.status}`);if(g=h.version,g!==e.manifest.version){let T;try{T=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(!T.ok)throw await jn(T),T.status===Hi?new Error(`publish: [E_AUTH_EXPIRED] Authentication is expired or missing \u2014 please log in again (HTTP ${T.status})`):T.status===403?new Error(`publish: [E_FORBIDDEN] Version update is forbidden; only the item owner can update an existing item (HTTP ${T.status})`):new Error(`publish: [E_HTTP] Version update failed \u2014 HTTP ${T.status}`);y="applied";}}let _=te.readFileSync(e.tgzPath),E=Zl()?Ql(_):_,v=new FormData;v.set("archive",new Blob([new Uint8Array(E)],{type:"application/gzip"}),`${p}-${e.manifest.version}.tgz`);let j=r&&d!==void 0?d:i,b;try{b=await fetch(`${n}${An}/publisher/items/${encodeURIComponent(j)}/upload`,{method:"POST",headers:{Authorization:`Bearer ${e.accessToken}`},body:v});}catch{throw new Error("publish: [E_NETWORK] Upload request failed (network)")}if(b.status===Hi)throw new Error("publish: [E_AUTH_EXPIRED] Authentication is expired or missing \u2014 please log in again (HTTP 401)");if(!b.ok){let D=await jn(b);if(r){let L=js(D,p);if(L)throw L}throw new Error(`publish: [E_HTTP] Upload request failed \u2014 HTTP ${b.status}`)}let U=await jn(b),H=vs(U,"upload",b.status),N=typeof H.contentId=="string"&&H.contentId.length>0?H.contentId:d;if(r&&N===void 0)throw P("PUBLISH_CONTENT_ID_MISSING","App upload did not return an opaque contentId");return {slug:p,version:e.manifest.version,...N===void 0?{}:{contentId:N},artifactChecksum:H.artifactChecksum,artifactSizeBytes:H.artifactSizeBytes,submitOutcome:u,versionUpdate:y,serverVersionBefore:g}}var ou=1e4,ru=100*1024*1024;function zi(e){return Bi.createHash("sha256").update(e).digest("hex")}function su(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function ze(e,n){if(!n||n.includes("\\")||n.includes("\0")||de.posix.isAbsolute(n)||n.split("/").some(r=>r===".."||r.length===0))throw P("PACKAGE_PATH_TRAVERSAL","workspace file path is not a safe relative path");let t=de.resolve(e,...n.split("/")),i=de.resolve(e);if(t!==i&&!t.startsWith(`${i}${de.sep}`))throw P("PACKAGE_PATH_TRAVERSAL","workspace file path escaped the workspace root");let o;try{o=te.lstatSync(t);}catch{throw P("PACKAGE_FILE_INVALID",`workspace file is missing: ${n}`)}if(o.isSymbolicLink())throw P("PACKAGE_SYMLINK",`symlink is not publishable: ${n}`);if(!o.isFile())throw P("PACKAGE_FILE_INVALID",`not a regular file: ${n}`);return new Uint8Array(te.readFileSync(t))}async function au(e,n,t){let i=`${n}/${K}`;if(!t.includes(i))return [];let o={[K]:ze(e,i)},r=`${n}/${G}`;t.includes(r)&&(o[G]=ze(e,r));let s=Ve(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)?ze(e,l):"missing"}),c=a.find(d=>d.code==="ICON_INVALID");if(c!==void 0)throw P("ICON_INVALID",`${c.reason??"invalid"} at ${c.declared??"icon"}`);return a.flatMap(d=>d.code==="ICON_INVALID"?[]:[{code:d.code,path:d.declared??"icon"}])}function Vs(e,n,t){let i=e??n;if(!Number.isSafeInteger(i)||i<=0)throw new Ue("PACKAGE_SIZE_LIMIT",`${t} must be a positive integer`);return i}function Hs(e,n,t,i){let o=Vs(t.maxFileCount??t.maxFiles,ou,"max file count"),r=Vs(t.maxTotalBytes??t.maxBytes,ru,"max total bytes");if(n.length>o)throw new Ue("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+=ze(e,a).byteLength,s>r)throw new Ue("PACKAGE_SIZE_LIMIT",`package exceeds byte limit (${r})`)}}function cu(e){return e.appId!==void 0||e.expectedDefinitionHash!==void 0}function du(e){let n=e.appId!==void 0,t=e.expectedDefinitionHash!==void 0;if(!n&&t)throw P("APP_ID_REQUIRED","appId is required with expectedDefinitionHash");if(n&&!t)throw P("APP_DEFINITION_HASH_REQUIRED","expectedDefinitionHash is required with appId");if(!n||!t)throw P("APP_ID_REQUIRED")}function pu(e,n){let t=e.filter(i=>i.appId===n);if(t.length===0)throw P("APP_NOT_FOUND",`no publishable App matches ${n}`);if(t.length!==1)throw P("APP_AMBIGUOUS",`more than one App matches ${n}`);return t[0]}function lu(e){let n=e.localDefinitionRef?.packageRoot;if(!n||!/^(?:apps|skills)\/[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(n))throw P("APP_PACKAGE_ROOT_INVALID","selected App is not rooted in apps/<safe-id> or skills/<safe-id>");return n}function $i(e){let{path:n,rule:t}=e.reason;return `${e.code} at ${n===""?"<file>":n} (${t})`+(e.files.length>0?` [${e.files.join(", ")}]`:"")}function uu(e,n,t){let i=Ve({[pe]:t},{mode:"published"});if(!i.ok)throw P("APP_UI_MANIFEST_INVALID",`generated ${pe} does not read: ${$i(i.rejection)}`);if(cn(i.manifest)!==cn(n))throw P("APP_UI_MANIFEST_INVALID",`generated ${pe} normalizes to a different definition hash than the source`);let o=e[K];if(o===void 0)return;let r=e[G],s=Ve({[K]:o,[pe]:t,...r===void 0?{}:{[G]:r}},{mode:"local"});if(!s.ok)throw P("APP_UI_MANIFEST_INVALID",$i(s.rejection))}function fu(e,n,t,i){let o={};for(let y of ee){let g=`${t}/${y}`;i.includes(g)&&(o[y]=ze(e,g));}let r=`${t}/${G}`;if(o[K]!==void 0&&i.includes(r)&&(o[G]=ze(e,r)),Object.keys(o).length===0)throw P("APP_UI_MANIFEST_INVALID","selected screen App has no package manifest.json or ui-plugin.json");let s=Ve(o,{mode:"local"});if(!s.ok)throw P("APP_UI_MANIFEST_INVALID",$i(s.rejection));if(s.manifest.pluginId!==n.appId)throw P("APP_DEFINITION_CONFLICT",`${s.file} identity no longer matches the selected App`);let a=o[pe],c=a===void 0?void 0:zi(a),d=`${t}/ui/index.html`;if(!i.includes(d))throw P("APP_UI_MANIFEST_INVALID","screen entry is outside package scope");let l=zi(ze(e,d)),p=JSON.parse(JSON.stringify(s.v2Input));if(p.entryHash=l,Object.prototype.hasOwnProperty.call(p,"initialState")){let y=p.initialState;if(!su(y)||y.path!=="ui/state.json")throw P("APP_INITIAL_STATE_OUT_OF_SCOPE","initialState must reference ui/state.json inside the package");let g=`${t}/ui/state.json`;if(!i.includes(g))throw P("APP_INITIAL_STATE_OUT_OF_SCOPE","initialState reference is outside the selected package");let _=ze(e,g);p.initialState={...y,hash:zi(_)};}let u;try{let y=We(p,{mode:"published"});u=new Uint8Array(Buffer.from(JSON.stringify(y),"utf8"));}catch(y){throw y instanceof ce?P("APP_UI_MANIFEST_INVALID",y.code):P("APP_UI_MANIFEST_INVALID")}return uu(o,s.manifest,u),{bytes:u,...c===void 0?{}:{legacySourceHash:c}}}async function yu(e,n){let{included:t,excluded:i}=hs(e);Hs(e,t,n);let o=Ss(e,t,{version:n.version}),r=Vi(e,t);return {plan:{manifest:o,included:t,excluded:i,secretFindings:r},archiveOptions:{}}}async function Au(e,n){du(n);let t=await Is(e),i=pu(t.items,n.appId);if(i.definitionHash!==n.expectedDefinitionHash)throw P("APP_DEFINITION_CONFLICT",`definitionHash changed for ${n.appId}`);let o=lu(i),{included:r,excluded:s}=ms(e,o),a=await au(e,o,r),c=new Map,d=new Map;if(i.capabilities.includes("screen")){let y=fu(e,i,o,r),g=`${o}/${pe}`;if(c.set(g,y.bytes),y.legacySourceHash!==void 0)d.set(g,y.legacySourceHash);else {r.push(g);let _=new TextEncoder;r.sort((E,v)=>Buffer.compare(_.encode(E),_.encode(v)));}}if(i.capabilities.includes("skill")&&!r.includes(`${o}/SKILL.md`))throw P("APP_SKILL_MISSING","skill capability requires package-root SKILL.md");Hs(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=Ms(e,l),u=Vi(e,r,c);return {plan:{manifest:p,included:r,excluded:s,secretFindings:u,warnings:a},archiveOptions:{generatedFiles:c,sourceFileHashes:d}}}async function zs(e,n){let t=de.resolve(e);if(cu(n))return Au(t,n);if(n.expectedDefinitionHash!==void 0)throw P("APP_ID_REQUIRED");return yu(t,n)}async function RI(e,n={}){return (await zs(e,n)).plan}function Iu(e){let n=e.map(t=>`${t.path}:${t.line} (${t.rule})`).join(", ");throw new Ue("PUBLISH_SECRET_FINDINGS",`aborted \u2014 secret findings must be resolved before packing: ${n}`)}async function $s(e,n={}){let t=de.resolve(e),i=await zs(t,n);i.plan.secretFindings.length>0&&Iu(i.plan.secretFindings);let o=await ks(t,i.plan.manifest,i.archiveOptions);return {manifest:i.plan.manifest,tgzPath:o}}async function wI(e,n={}){return $s(e,n)}async function CI(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{ru as DEFAULT_PUBLISH_MAX_BYTES,ou as DEFAULT_PUBLISH_MAX_FILES,gs as EXCLUDE_RULES,An as MARKETPLACE_API_PREFIX,Ue as PublishError,CI as packApp,$s as packPublish,wI as packTemplate,RI as planPublish,iu as uploadToMarketplace};
1
+ import*as de from'path';import {resolve,relative,sep,isAbsolute,join}from'path';import'url';import*as Bi from'crypto';import {createHash}from'crypto';import {isIP}from'net';import*as te from'fs';import {constants,readFileSync,existsSync,statSync,readdirSync}from'fs';import {realpath,stat,readdir,open,lstat}from'fs/promises';import*as Ds from'js-yaml';import {load}from'js-yaml';import*as Us from'os';import*as xs from'tar';import {gunzipSync,gzipSync}from'zlib';var F=(e,n)=>()=>(e&&(n=e(e=0)),n);var m=F(()=>{});var x,Fn=F(()=>{m();x=class extends Error{constructor(t,i=t,o){super(i);this.code=t;this.currentRevision=o;}code;currentRevision;name="UiRuntimeError"};});function Lt(e){return Ks.test(e)||Xs.test(e)}function fe(){throw new x("INPUT_INVALID","JSON value is not projection-safe")}function Qs(e){let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function Mt(e,n,t,i,o,r){if(n>i&&fe(),e===null||typeof e=="string"||typeof e=="boolean")return typeof e=="string"&&(Ys.test(e)||Zs.test(e)&&!ta(o,r)||qs.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=>Mt(c,n+1,t,i,o,r));Qs(s)||fe();let a={};for(let[c,d]of Object.entries(e))Lt(c)&&fe(),a[c]=Mt(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>na)&&fe(),(!Array.isArray(t)||t.some(o=>typeof o!="string"))&&fe();let i=Mt(e,0,new Set,ea+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 ta(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 Ot(e){return Array.isArray(e)?e.map(Ot):e!==null&&typeof e=="object"?Object.fromEntries(Object.keys(e).sort().map(n=>[n,Ot(e[n])])):e}function ie(e){return nn(Ot(e))}function Rt(e){return Buffer.byteLength(e,"utf8")}var Ks,Xs,Ys,qs,Zs,ea,na,Oe=F(()=>{m();Fn();Ks=/(?:proof|token|secret|password|cookie|authorization|private[_-]?key|stack|exception|plugin[_-]?text)/i,Xs=/(?:url|uri|endpoint|path|file(?:name|path)?|cwd|shell|directory|dir|folder)$/i,Ys=/<\/?[A-Za-z][^>]*>/,qs=/^(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)/,Zs=/^(?:https?|file|ftp|ws|wss):\/\//i;ea=8,na=4;});var Gi=F(()=>{m();Oe();});var Vn,wt=F(()=>{m();Vn=["text/plain","application/json"];});var Ji=F(()=>{m();wt();});function tn(e){return oa.has(e)||ra.test(e)||sa.test(e)}var Wi,oa,ra,sa,Bn,In,Pe,Ct,Ut,kt,xt,vt,$e=F(()=>{m();Wi=["__proto__","prototype","constructor","proof","token","secret","password","cookie","authorization","private_key","private-key","stack","exception","plugin_text","url","uri","endpoint","path","filename","filepath","cwd","shell","directory","dir","folder"],oa=new Set(Wi),ra=/(?:proof|token|secret|password|cookie|authorization|private[_-]?key|stack|exception|plugin[_-]?text)/i,sa=/(?: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_]+)*$/,Pe=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,Ct=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/,Ut=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,kt=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/,xt=["blue","violet","emerald","amber","rose","sky","slate","indigo"],vt=["inline","panel"];});function jt(e){return typeof e=="string"&&Vn.includes(e)}var Ki=F(()=>{m();wt();$e();});function Hn(e){if(!Ft(e))return false;let n=Object.keys(e);return !(n.some(t=>t!=="in"&&t!=="out")||n.length===0||Object.hasOwn(e,"in")&&!aa(e.in)||Object.hasOwn(e,"out")&&!ca(e.out))}function aa(e){return Ft(e)?Object.keys(e).every(t=>t==="mediaType"||t==="required")&&Object.hasOwn(e,"mediaType")&&jt(e.mediaType)&&(!Object.hasOwn(e,"required")||typeof e.required=="boolean"):false}function ca(e){return Ft(e)?Object.keys(e).every(t=>t==="mediaType"||t==="range")&&Object.hasOwn(e,"mediaType")&&jt(e.mediaType)&&(!Object.hasOwn(e,"range")||typeof e.range=="boolean"):false}function Ft(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=F(()=>{m();Ji();Ki();new TextDecoder("utf-8",{fatal:true,ignoreBOM:true});});function $n(e){return da.includes(e)}function Gn(e){return Number.isSafeInteger(e)&&e>=zn.min&&e<=zn.max}var da,zn,Xi,Bt=F(()=>{m();da=[5,15,30,60],zn=Object.freeze({min:15e3,max:6e5,default:3e5}),Xi=1;});function Wn(e){return Number.isSafeInteger(e)&&e>=Jn.min&&e<=Jn.max}function Kn(e){return pa.includes(e)}var Jn,Yi,pa,Ht=F(()=>{m();Jn=Object.freeze({min:6e4,max:18e5,default:6e5}),Yi=1,pa=["start","status","cancel"];});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.downloads!==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.downloads===void 0?{}:{downloads:e.downloads},...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 $t(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"||!ua.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=>!ya(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&&zt(t.resultProjection),t.schedule!==void 0&&(!$n(t.schedule.everyMinutes)||!Gn(t.schedule.timeoutMs)))throw new x("DEFINITION_UNSUPPORTED","UI action schedule declaration is invalid");if(t.job!==void 0&&(typeof t.job!="object"||Object.keys(t.job).some(i=>i!=="deadlineMs")||!Wn(t.job.deadlineMs)))throw new x("DEFINITION_UNSUPPORTED","UI action job declaration is invalid");if(t.jobAccess!==void 0&&(!Array.isArray(t.jobAccess)||t.jobAccess.length===0||new Set(t.jobAccess).size!==t.jobAccess.length||!t.jobAccess.every(Kn)||t.job!==void 0))throw new x("DEFINITION_UNSUPPORTED","UI action job control declaration is invalid");if(t.content!==void 0&&!Hn(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&&zt(e.stateProjection),e.summaryProjection){zt(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(fa(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.downloads!==void 0&&e.downloads!==true)throw new x("DEFINITION_UNSUPPORTED","UI definition downloads is invalid");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 x("DEFINITION_UNSUPPORTED","UI definition dataPaths are invalid")}}function fa(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(Rt(nn(c))>4*1024)throw new Error("fixed result size")}}catch{throw new x("DEFINITION_UNSUPPORTED","UI legacy tool metadata is not projection-safe")}}function zt(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 ya(e){return e.length>0&&e.length<=128&&e!=="*"&&e!=="all"&&!/[/*]/.test(e)}var ua,Ge=F(()=>{m();Oe();Fn();Vt();Bt();Ht();ua=/^[0-9a-f]{64}$/;});var G,Le,Gt=F(()=>{m();G="dist/tools.json",Le="dist/main.mjs";});var je,Jt=F(()=>{m();je="window";});function qi(e){if(!Array.isArray(e)||e.length===0)return false;let n=new Set;for(let t of e){if(!Aa.some(i=>i===t)||n.has(t))return false;n.add(t);}return true}var Aa,Zi=F(()=>{m();Aa=["CREWX_APP_INSTANCE_ID","CREWX_THREAD_ID"];});function J(e){throw new Wt(e)}function Sa(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;try{let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}catch{return false}}function Ma(e,n){let t=Object.getOwnPropertyDescriptor(e,n);return (!t||!("value"in t))&&J("CSP_ORIGIN_INVALID"),t.value}function Xn(e,n){if(!Object.prototype.hasOwnProperty.call(e,n))return [];let t=Ma(e,n);Array.isArray(t)||J("CSP_ORIGIN_INVALID"),Reflect.ownKeys(t).some(r=>typeof r!="string"||r!=="length"&&!/^(?:0|[1-9][0-9]*)$/.test(r))&&J("CSP_ORIGIN_INVALID");let o=[];for(let r=0;r<t.length;r+=1)(!Object.prototype.hasOwnProperty.call(t,r)||typeof t[r]!="string")&&J("CSP_ORIGIN_INVALID"),o.push(t[r]);return Object.keys(t).length!==t.length&&J("CSP_ORIGIN_INVALID"),o}function Oa(e){let n;try{n=JSON.stringify(e);}catch{J("CSP_ORIGIN_INVALID");}return n===void 0&&J("CSP_ORIGIN_INVALID"),new TextEncoder().encode(n).byteLength}function no(e,n){/\s|\\/u.test(e)&&J("CSP_ORIGIN_INVALID");let t=Ta.exec(e);t||J("CSP_ORIGIN_INVALID");let i=t[1].toLowerCase(),o=t[2];(o.includes("@")||o.includes("%")||o.includes("*"))&&J("CSP_ORIGIN_INVALID"),(o.startsWith("[")?Pa:ba).test(o)||J("CSP_ORIGIN_INVALID"),i==="wss"&&n!=="connectDomains"&&J("CSP_ORIGIN_INVALID");let s;try{s=new URL(e);}catch{J("CSP_ORIGIN_INVALID");}(s.protocol!==`${i}:`||s.username!==""||s.password!==""||s.search!==""||s.hash!=="")&&J("CSP_ORIGIN_INVALID");let a=s.hostname.toLowerCase();if((!a||a.includes("%"))&&J("CSP_ORIGIN_INVALID"),!a.startsWith("[")){let d=a.endsWith(".")?a.slice(0,-1):a;(d.length===0||d.length>253)&&J("CSP_ORIGIN_INVALID"),d.split(".").some(p=>p.length>63||!Na.test(p))&&J("CSP_ORIGIN_INVALID");}let c=s.origin;return (c==="null"||!c.startsWith(`${i}://`))&&J("CSP_ORIGIN_INVALID"),{origin:c,hostname:a}}function La(e){let n=e.split(".").map(Number);return ((n[0]*256+n[1])*256+n[2])*256+n[3]}function to(e,n,t){let i=4294967295<<32-t>>>0;return (e&i)===(n&i)}function ro(e){let n=La(e);return to(n,3221225472,24)?n!==3221225481&&n!==3221225482:Da.some(([t,i])=>to(n,t,i))}function Ra(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 wa(e){let n=Ra(e),t=Number(n>>112n),i=Number(n>>96n&0xffffn);if(n>>32n===0xffffn){let o=Number(n&0xffffffffn);return ro([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 Ca(e,n){let t=e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e,i=isIP(t);if(i===4)return ro(t);if(i===6)return wa(t);let o=e.toLowerCase().replace(/\.$/,"");return !o||!o.includes(".")||n.has(o)?true:Ea.some(r=>o===r||o.endsWith(`.${r}`))}function io(e){return Object.freeze([...new Set(e.map(n=>n.origin))].sort())}function oo(e){return JSON.stringify({baseUriDomains:[],connectDomains:e.connectDomains,declared:e.declared,frameDomains:e.frameDomains,resourceDomains:[]})}function so(e,n={}){if(e===void 0){let y=oo({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(y,"utf8").digest("hex")})}Sa(e)||J("CSP_ORIGIN_INVALID");let t=Reflect.ownKeys(e);t.some(y=>typeof y!="string")&&J("CSP_ORIGIN_INVALID"),t.some(y=>!_a.has(y))&&J("CSP_AXIS_UNKNOWN");let i=Xn(e,"connectDomains"),o=Xn(e,"frameDomains"),r=Xn(e,"resourceDomains"),s=Xn(e,"baseUriDomains");(r.length>0||s.length>0)&&J("CSP_AXIS_UNSUPPORTED"),(Oa(e)>ga||i.length>eo||o.length>eo||i.length+o.length>ma||[...i,...o].some(y=>new TextEncoder().encode(y).byteLength>ha))&&J("CSP_LIMIT_EXCEEDED");let c=i.map(y=>no(y,"connectDomains")),d=o.map(y=>no(y,"frameDomains")),l=new Set((n.runtimeHostnames??[]).map(y=>y.toLowerCase().replace(/\.$/,"")));[...c,...d].some(y=>Ca(y.hostname,l))&&J("CSP_ORIGIN_FORBIDDEN");let p={declared:true,connectDomains:io(c),frameDomains:io(d)},u=oo(p);return Object.freeze({...p,resourceDomains:Object.freeze([]),baseUriDomains:Object.freeze([]),cspHash:createHash("sha256").update(u,"utf8").digest("hex")})}var ga,eo,ma,ha,_a,Ea,Ta,Pa,ba,Na,Da,Wt,ao=F(()=>{m();ga=4096,eo=16,ma=32,ha=512,_a=new Set(["connectDomains","frameDomains","resourceDomains","baseUriDomains"]),Ea=["localhost","local","internal","home.arpa","test","example","invalid","onion","lan","corp","home","intranet","private","localdomain"],Ta=/^(https|wss):\/\/([^/?#]+)$/i,Pa=/^\[[^\]]+\](?::[0-9]+)?$/,ba=/^[^:\[\]]+(?::[0-9]+)?$/,Na=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/,Da=[[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]],Wt=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 f(e,n=e,t,i){throw new ce(e,n,t,i)}function $(e,n){try{return n()}catch(t){throw t instanceof ce?t.withPathPrefix(e):t}}function W(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;try{let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}catch{return false}}function C(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function fc(e,n){let t={};for(let[i,o]of Object.entries(e))n.includes(i)||(t[i]=o);return t}function Y(e,n,t=[]){let i=new Set([...n,...t]),o=Object.keys(e).find(s=>!i.has(s));o!==void 0&&f("MANIFEST_INVALID","MANIFEST_INVALID",o,"unknown-key");let r=n.find(s=>!C(e,s));r!==void 0&&f("MANIFEST_INVALID","MANIFEST_INVALID",r,"missing-key");}function Qn(e,n=false,t=false,i=false){return va.test(e)||!i&&Fa.test(e)||ja.test(e)||t&&co.test(e)||Va.test(e)&&!(n&&/^\s*data:/i.test(e)&&!co.test(e))}function Zn(e,n=new Set,t=0,i=false,o=false,r=""){if(typeof e=="string"){Qn(e,i,o)&&f("UNSAFE_VALUE","UNSAFE_VALUE",r,"unsafe-value");return}if(!(e===null||typeof e!="object")){(t>8||n.has(e))&&f("MANIFEST_INVALID","MANIFEST_INVALID",r),n.add(e);try{if(Array.isArray(e)){e.forEach((s,a)=>Zn(s,n,t+1,!1,!1,mn(r,`[${a}]`)));return}W(e)||f("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,mn(r,s));}finally{n.delete(e);}}}function be(e,n){let t=e[n];return typeof t!="string"&&f("MANIFEST_INVALID"),t}function ge(e,n,t){let i=e[n];return (!Number.isSafeInteger(i)||i<t)&&f("MANIFEST_INVALID"),i}function Kt(e){return xa.test(e)||f("MANIFEST_INVALID"),e}function on(e){return ka.test(e)||f("TOKEN_INVALID"),e}function yc(e){return mo.test(e)||f("MANIFEST_INVALID"),e}function Ac(e){W(e)||f("MANIFEST_INVALID");let n={};for(let[t,i]of Object.entries(e)){let o=yc(t);W(i)||f("MANIFEST_INVALID");let r=i.type;if(r==="text"){Y(i,["type","maxLength"]),n[o]={type:r,maxLength:ge(i,"maxLength",1)};continue}if(r==="text-list"){Y(i,["type","max","itemMaxLength"]),n[o]={type:r,max:ge(i,"max",0),itemMaxLength:ge(i,"itemMaxLength",1)};continue}if(r==="step-list"){Y(i,["type","min","max","labelMaxLength","detailMaxLength"]);let s=ge(i,"min",0),a=ge(i,"max",1);s>a&&f("MANIFEST_INVALID"),n[o]={type:r,min:s,max:a,labelMaxLength:ge(i,"labelMaxLength",1),detailMaxLength:ge(i,"detailMaxLength",1)};continue}typeof r=="string"&&f("SCHEMA_TYPE_UNSUPPORTED"),f("MANIFEST_INVALID");}return n}function Ic(e,n,t){let i=e[n];(!i||i.type!==t)&&f("MANIFEST_INVALID");}function Yn(e,n,t){let i=be(e,"field");return mo.test(i)||f("MANIFEST_INVALID"),Ic(n,i,t),i}function gc(e,n){W(e)||f("MANIFEST_INVALID");let t=e.primitive;switch(typeof t!="string"&&f("MANIFEST_INVALID"),uc.includes(t)||f("PRIMITIVE_UNKNOWN"),t){case "card-shell":return Y(e,["primitive"]),{primitive:t};case "meta-banner":return Y(e,["primitive","badgeToken","noticeToken"]),{primitive:t,badgeToken:on(be(e,"badgeToken")),noticeToken:on(be(e,"noticeToken"))};case "heading":return Y(e,["primitive","field"]),{primitive:t,field:Yn(e,n,"text")};case "labeled-text":return Y(e,["primitive","titleToken","field","variant"]),e.variant!=="callout"&&f("MANIFEST_INVALID"),{primitive:t,titleToken:on(be(e,"titleToken")),field:Yn(e,n,"text"),variant:"callout"};case "step-flow":return Y(e,["primitive","titleToken","field"]),{primitive:t,titleToken:on(be(e,"titleToken")),field:Yn(e,n,"step-list")};case "text-list":{Y(e,["primitive","titleToken","field"],["emptyToken","hideWhenEmpty"]);let i={primitive:t,titleToken:on(be(e,"titleToken")),field:Yn(e,n,"text-list")};return C(e,"emptyToken")&&(i.emptyToken=on(be(e,"emptyToken"))),C(e,"hideWhenEmpty")&&(typeof e.hideWhenEmpty!="boolean"&&f("MANIFEST_INVALID"),i.hideWhenEmpty=e.hideWhenEmpty),i}}return f("MANIFEST_INVALID")}function mc(e,n){return Array.isArray(e)||f("MANIFEST_INVALID"),e.map(t=>gc(t,n))}function q(e="v2 manifest exceeds a contract limit",n,t){return f("LIMIT_EXCEEDED",e,n,t)}function Ie(e="initial state is not projection-safe"){return f("INITIAL_STATE_INVALID",e)}function po(e,n){return (typeof e!="string"||e.length===0||e.length>4096||e.trim().length===0||sc.test(e)||ac.test(e))&&f("MANIFEST_INVALID",`${n} is invalid`),(Qn(e,true,true)||Ba.test(e)||Ha.test(e)||za.test(e))&&f("UNSAFE_VALUE",`${n} contains an unsafe value`),e}function Xt(e,n){return (typeof e!="string"||!Pe.test(e))&&f("MANIFEST_INVALID",`${n} is invalid`),e}function hc(e){return (typeof e!="string"||!Ct.test(e)||e==="*"||e==="all")&&f("MANIFEST_INVALID","action capability is invalid"),e}function ho(e){return (typeof e!="string"||!rc.test(e))&&f("MANIFEST_INVALID","resource hash is invalid"),e}function Yt(e,n=new Set,t=0,i=""){if(typeof e=="string"){e.length>4096&&q("v2 manifest string is too long",i,"string-too-long");return}if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){Number.isFinite(e)||f("MANIFEST_INVALID","v2 manifest contains a non-finite number",i,"non-finite-number");return}(e===void 0||typeof e=="function"||typeof e=="bigint")&&f("MANIFEST_INVALID","v2 manifest contains a non-JSON value",i,"non-json-value"),typeof e!="object"&&f("MANIFEST_INVALID","MANIFEST_INVALID",i),t>8&&q("v2 manifest nesting is too deep",i,"too-deep"),n.has(e)&&f("MANIFEST_INVALID","v2 manifest contains a cycle",i,"cycle"),n.add(e);try{if(Array.isArray(e)){e.length>128&&q("v2 manifest array is too long",i,"array-too-long"),e.forEach((o,r)=>Yt(o,n,t+1,mn(i,`[${r}]`)));return}W(e)||f("MANIFEST_INVALID","v2 manifest contains a non-plain object",i,"non-plain-object");for(let[o,r]of Object.entries(e))Yt(r,n,t+1,mn(i,o));}finally{n.delete(e);}}}function _o(e){return (typeof e!="string"||e.length>4096||!In.test(e))&&(typeof e=="string"&&e.length>4096&&q("projection path is too long"),f("MANIFEST_INVALID","projection paths must be canonical exact paths")),e.split(".").some(t=>tn(t))&&f("MANIFEST_INVALID","projection paths cannot address reserved state keys"),e}function qt(e){W(e)||f("MANIFEST_INVALID","projection policy must be an object"),Y(e,["allow"]),Array.isArray(e.allow)||f("MANIFEST_INVALID","projection allow must be an array"),e.allow.length>128&&q("projection allowlist is too long");let n=[],t=new Set;for(let i of e.allow){let o=_o(i);t.has(o)&&f("MANIFEST_INVALID","projection allowlist contains a duplicate path"),t.add(o),n.push(o);}return {allow:n}}function _c(e,n){if(e===void 0)return;Array.isArray(e)||f("MANIFEST_INVALID","dataPaths must be an array"),e.length>cc&&q("dataPaths exceed the v2 limit");let t=[],i=new Set;for(let o of e){let r=_o(o);i.has(r)&&f("MANIFEST_INVALID","dataPaths contain a duplicate path"),n.some(s=>en(r,s))||f("MANIFEST_INVALID","dataPaths must be projection-allowed"),i.add(r),t.push(r);}return t}function Ec(e){Array.isArray(e)||f("MANIFEST_INVALID","deviceFeatures must be an array",void 0,"array"),e.length>dc&&f("MANIFEST_INVALID","deviceFeatures allow at most 16 names",void 0,"too-many-items");let n=[],t=new Set;for(let[i,o]of e.entries()){let r=`[${i}]`;typeof o!="string"&&f("MANIFEST_INVALID","a device feature name must be a string",r,"string"),o.length===0&&f("MANIFEST_INVALID","a device feature name must not be empty",r,"empty"),o.length>pc&&f("MANIFEST_INVALID","a device feature name is at most 32 characters",r,"too-long"),lc.test(o)||f("MANIFEST_INVALID","a device feature name starts with a lowercase letter and holds only letters and digits",r,"format"),t.has(o)&&f("MANIFEST_INVALID","deviceFeatures contain a duplicate name",r,"duplicate-item"),t.add(o),n.push(o);}return n}function Tc(e){if(e!==false)return e!==true&&f("MANIFEST_INVALID","downloads must be true or false",void 0,"boolean"),true}function rn(e,n,t=Number.MAX_SAFE_INTEGER){return (!Number.isSafeInteger(e)||e<0||e>t)&&f("MANIFEST_INVALID",`${n} is invalid`),e}function lo(e,n){return (typeof e!="number"||!Number.isFinite(e))&&f("MANIFEST_INVALID",`${n} is invalid`),e}function Zt(e,n=0,t=new Set){if(typeof e=="string")return (e.length>4096||Qn(e))&&f("UNSAFE_VALUE","schema enum contains an unsafe string"),e;if(e===null||typeof e=="boolean")return e;if(typeof e=="number")return Number.isFinite(e)||f("MANIFEST_INVALID","schema enum contains a non-finite number"),e;(n>8||typeof e!="object"||e===void 0)&&q("schema enum is too deep"),t.has(e)&&f("MANIFEST_INVALID","schema enum contains a cycle"),t.add(e);try{if(Array.isArray(e))return e.length>128&&q("schema enum array is too long"),e.map(o=>Zt(o,n+1,t));W(e)||f("MANIFEST_INVALID","schema enum contains a non-plain object");let i={};for(let[o,r]of Object.entries(e))tn(o)&&f("MANIFEST_INVALID","schema enum contains a reserved key"),i[o]=Zt(r,n+1,t);return i}finally{t.delete(e);}}function Pc(e,n){if(e===void 0)return;Array.isArray(e)||f("MANIFEST_INVALID","schema required must be an array"),e.length>64&&q("schema required list is too long");let t=[],i=new Set;for(let o of e)(typeof o!="string"||!In.test(o))&&f("MANIFEST_INVALID","schema required contains an invalid key"),o.length>4096&&q("schema required key is too long"),i.has(o)&&f("MANIFEST_INVALID","schema required contains a duplicate key"),n&&!Object.prototype.hasOwnProperty.call(n,o)&&f("MANIFEST_INVALID","schema required references an undeclared property"),i.add(o),t.push(o);return t}function bc(e,n){let t=n?In:Bn;return e.length>4096&&q("schema property name is too long"),(!t.test(e)||e.split(".").some(i=>tn(i)))&&f("MANIFEST_INVALID","schema property name is invalid"),e}function Qt(e,n=0,t=false){W(e)||f("MANIFEST_INVALID","action inputSchema must be an object"),n>8&&q("action inputSchema is too deep");let i=e.type;i!=="object"&&i!=="string"&&i!=="number"&&i!=="integer"&&i!=="boolean"&&i!=="array"&&i!=="null"&&(typeof i=="string"&&f("SCHEMA_TYPE_UNSUPPORTED","action inputSchema type is unsupported"),f("MANIFEST_INVALID","action inputSchema type is required"));let o=["type","enum"];i==="string"&&o.push("minLength","maxLength"),i==="array"&&o.push("minItems","maxItems","items"),i==="object"&&o.push("minProperties","maxProperties","properties","required","additionalProperties"),(i==="number"||i==="integer")&&o.push("minimum","maximum"),Y(e,["type"],o.filter(a=>a!=="type"));let r={type:i};if(C(e,"enum")&&(Array.isArray(e.enum)||f("MANIFEST_INVALID","schema enum must be an array"),e.enum.length>128&&q("schema enum is too long"),r.enum=e.enum.map(a=>Zt(a))),i==="string"&&(C(e,"minLength")&&(r.minLength=rn(e.minLength,"schema minLength",4096)),C(e,"maxLength")&&(r.maxLength=rn(e.maxLength,"schema maxLength",4096)),r.minLength!==void 0&&r.maxLength!==void 0&&r.minLength>r.maxLength&&f("MANIFEST_INVALID","schema string length bounds are inverted")),(i==="number"||i==="integer")&&(C(e,"minimum")&&(r.minimum=lo(e.minimum,"schema minimum")),C(e,"maximum")&&(r.maximum=lo(e.maximum,"schema maximum")),r.minimum!==void 0&&r.maximum!==void 0&&r.minimum>r.maximum&&f("MANIFEST_INVALID","schema numeric bounds are inverted")),i==="array"&&(C(e,"minItems")&&(r.minItems=rn(e.minItems,"schema minItems",128)),C(e,"maxItems")&&(r.maxItems=rn(e.maxItems,"schema maxItems",128)),r.minItems!==void 0&&r.maxItems!==void 0&&r.minItems>r.maxItems&&f("MANIFEST_INVALID","schema array length bounds are inverted"),C(e,"items")&&(r.items=Qt(e.items,n+1,false))),i==="object"){let a;if(C(e,"properties")){W(e.properties)||f("MANIFEST_INVALID","schema properties must be an object");let d=Object.entries(e.properties);d.length>64&&q("schema properties are too many"),a={};for(let[l,p]of d){let u=bc(l,t);a[u]=Qt(p,n+1,false);}r.properties=a;}C(e,"minProperties")&&(r.minProperties=rn(e.minProperties,"schema minProperties",64)),C(e,"maxProperties")&&(r.maxProperties=rn(e.maxProperties,"schema maxProperties",64)),r.minProperties!==void 0&&r.maxProperties!==void 0&&r.minProperties>r.maxProperties&&f("MANIFEST_INVALID","schema object property bounds are inverted");let c=Pc(e.required,a);c!==void 0&&(r.required=c),C(e,"additionalProperties")&&(e.additionalProperties!==false&&f("MANIFEST_INVALID","schema additionalProperties must be false"),r.additionalProperties=false);}let s=JSON.stringify(r);return (s===void 0||Buffer.byteLength(s,"utf8")>2097152)&&q("action inputSchema subtree is too large"),r}function Nc(e){let n=Qt(e,0,true);return (n.type!=="object"||!n.properties)&&f("MANIFEST_INVALID","action inputSchema must declare object properties"),n}function Dc(e){if(W(e)||f("MANIFEST_INVALID","action backend must be an object"),e.type==="core"){Y(e,Qa);let n=e.handler;return (typeof n!="string"||!Ut.test(n))&&f("MANIFEST_INVALID","core backend handler is invalid"),{type:"core",handler:n}}if(e.type==="skill"&&C(e,"entry"))return Y(e,tc),e.entry!==Le&&f("MANIFEST_INVALID",`skill backend entry must be ${Le}`),{type:"skill",entry:Le};if(e.type==="skill"){Y(e,ec,nc),(!Array.isArray(e.command)||e.command.length===0||e.command.length>16)&&f("MANIFEST_INVALID","skill backend command is invalid");let n=[];for(let i of e.command)(typeof i!="string"||i.length===0||i.length>256||!kt.test(i))&&f("MANIFEST_INVALID","skill backend command token is invalid"),n.push(i);let t=C(e,"env")?Rc(e.env):void 0;return {type:"skill",command:n,...t===void 0?{}:{env:t}}}f("MANIFEST_INVALID","action backend type is unsupported");}function Sc(e){W(e)||f("MANIFEST_INVALID","action must be an object"),Y(e,Wa,Ka),C(e,"_meta")&&$("_meta",()=>Eo(e._meta));let n=$("actionId",()=>Xt(e.actionId,"actionId"));Lt(n)&&f("MANIFEST_INVALID",`actionId "${n}" is not projection-safe`,"actionId");let t=$("capability",()=>hc(e.capability)),i=e.mutation;typeof i!="boolean"&&f("MANIFEST_INVALID","action mutation must be boolean","mutation");let o=$("inputSchema",()=>Nc(e.inputSchema)),r;if(C(e,"dataInputs")){Array.isArray(e.dataInputs)||f("MANIFEST_INVALID","action dataInputs must be an array","dataInputs");let y=o.properties,g=new Set,_=[];for(let E of e.dataInputs)(typeof E!="string"||!C(y,E)||g.has(E))&&f("MANIFEST_INVALID","action dataInputs must be unique declared properties","dataInputs"),g.add(E),_.push(E);r=_;}let s=$("resultProjection",()=>qt(e.resultProjection)),a=$("backend",()=>Dc(e.backend)),c;C(e,"content")&&((a.type!=="skill"||!Hn(e.content))&&f("MANIFEST_INVALID","action content declaration is invalid","content"),c=wc(e.content));let d;if(C(e,"confirmation")){let y=e.confirmation;y!=="none"&&y!=="native"&&f("MANIFEST_INVALID","action confirmation is invalid","confirmation"),d=y;}let l;C(e,"schedule")&&(l=$("schedule",()=>Lc(e.schedule,{backend:a,inputSchema:o,hasContent:c!==void 0,hasDataInputs:r!==void 0,confirmation:d})));let p;C(e,"job")&&(l!==void 0&&f("MANIFEST_INVALID","an action is either the scheduled run or a job, not both","job"),p=$("job",()=>Oc(e.job,{backend:a,inputSchema:o,hasContent:c!==void 0,hasDataInputs:r!==void 0,confirmation:d})));let u;return C(e,"jobAccess")&&(p!==void 0&&f("MANIFEST_INVALID","an action is either the job or a job control, not both","jobAccess"),u=$("jobAccess",()=>Mc(e.jobAccess,{backend:a,hasContent:c!==void 0}))),{actionId:n,capability:t,mutation:i,inputSchema:o,resultProjection:s,backend:a,...c===void 0?{}:{content:c},...r===void 0?{}:{dataInputs:r},...d===void 0?{}:{confirmation:d},...l===void 0?{}:{schedule:l},...p===void 0?{}:{job:p},...u===void 0?{}:{jobAccess:u}}}function Mc(e,n){return (n.backend.type!=="skill"||!("entry"in n.backend)||n.backend.entry!==Le)&&f("MANIFEST_INVALID","jobAccess needs a tool-mode action","jobAccess"),n.hasContent&&f("MANIFEST_INVALID","a job control action takes no content","jobAccess"),(!Array.isArray(e)||e.length===0)&&f("MANIFEST_INVALID","jobAccess must list at least one operation","jobAccess"),(new Set(e).size!==e.length||!e.every(Kn))&&f("MANIFEST_INVALID","jobAccess must name each operation once: start, status or cancel","jobAccess"),Object.freeze([...e])}function Oc(e,n){(n.backend.type!=="skill"||!("entry"in n.backend)||n.backend.entry!==Le)&&f("MANIFEST_INVALID","job needs a tool-mode action","job"),(n.hasContent||n.hasDataInputs||n.confirmation!==void 0&&n.confirmation!=="none")&&f("MANIFEST_INVALID","a job action takes no content, dataInputs or native confirmation","job"),(n.inputSchema.required??[]).length>0&&f("MANIFEST_INVALID","a job action input must accept {}","inputSchema.required"),W(e)||f("MANIFEST_INVALID","job must be an object","job"),Y(e,[],qa);let t=C(e,"deadlineMs")?e.deadlineMs:Jn.default;return Wn(t)||f("MANIFEST_INVALID","job deadlineMs is invalid","job.deadlineMs"),{deadlineMs:t}}function Lc(e,n){(n.backend.type!=="skill"||!("entry"in n.backend)||n.backend.entry!==Le)&&f("MANIFEST_INVALID","schedule needs a tool-mode action","schedule"),(n.hasContent||n.hasDataInputs||n.confirmation!==void 0&&n.confirmation!=="none")&&f("MANIFEST_INVALID","a scheduled action takes no content, dataInputs or native confirmation","schedule"),(n.inputSchema.required??[]).length>0&&f("MANIFEST_INVALID","a scheduled action input must accept {}","inputSchema.required"),W(e)||f("MANIFEST_INVALID","schedule must be an object","schedule"),Y(e,Xa,Ya),$n(e.everyMinutes)||f("MANIFEST_INVALID","schedule everyMinutes is invalid","schedule.everyMinutes");let t=C(e,"timeoutMs")?e.timeoutMs:zn.default;return Gn(t)||f("MANIFEST_INVALID","schedule timeoutMs is invalid","schedule.timeoutMs"),{everyMinutes:e.everyMinutes,timeoutMs:t}}function Rc(e){return qi(e)||f("MANIFEST_INVALID","skill backend env is invalid"),Object.freeze([...e])}function wc(e){return Object.freeze({...e.in===void 0?{}:{in:Object.freeze({...e.in})},...e.out===void 0?{}:{out:Object.freeze({...e.out})}})}function Cc(e){return W(e)||f("INITIAL_STATE_INVALID","initialState must be an object"),Y(e,ic,oc),e.path!=="ui/state.json"&&f("MANIFEST_INVALID","initialState path is not fixed"),C(e,"hash")?{path:"ui/state.json",hash:ho(e.hash)}:{path:"ui/state.json"}}function Uc(e){let n=["wasm","terminal","htmlDocuments","appBrowser"];return (!W(e)||Object.keys(e).length===0||Object.keys(e).some(t=>!n.includes(t)||e[t]!==true))&&f("MANIFEST_INVALID","runtime must contain only known capability flags set to true"),{...e.wasm===true?{wasm:true}:{},...e.terminal===true?{terminal:true}:{},...e.htmlDocuments===true?{htmlDocuments:true}:{},...e.appBrowser===true?{appBrowser:true}:{}}}function kc(e,n){let t;try{t=so(e);}catch(i){let o=i!==null&&typeof i=="object"&&"code"in i&&typeof i.code=="string"?i.code:"CSP_ORIGIN_INVALID";return f("MANIFEST_INVALID",o,void 0,o.toLowerCase().replace(/_/g,"-"))}if(t.frameDomains.length>0&&f("MANIFEST_INVALID","external origins in csp are not enabled in this rollout",void 0,"csp-not-enabled"),t.connectDomains.length!==0)return n?.terminal===true&&f("MANIFEST_INVALID","runtime.terminal cannot be combined with csp.connectDomains","connectDomains","terminal-with-connect-domains"),Object.freeze({connectDomains:t.connectDomains})}function xc(e,n){Zn(W(e)?fc(e,["csp","downloads"]):e,new Set,0,true,true),Yt(e),W(e)||f("MANIFEST_INVALID"),Y(e,Ga,Ja),C(e,"_meta")&&$("_meta",()=>Eo(e._meta)),e.manifestVersion!==2&&f("MANIFEST_INVALID");let t;C(e,"runtime")&&(t=$("runtime",()=>Uc(e.runtime)));let i;C(e,"csp")&&(i=$("csp",()=>kc(e.csp,t)));let o=$("pluginId",()=>Xt(e.pluginId,"pluginId")),r=$("definitionId",()=>Xt(e.definitionId,"definitionId")),s=$("version",()=>ge(e,"version",1)),a=$("name",()=>po(e.name,"name")),c=$("description",()=>po(e.description,"description")),d;C(e,"icon")&&((typeof e.icon!="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(e.icon))&&f("MANIFEST_INVALID","icon is invalid","icon"),d=e.icon);let l;C(e,"tone")&&((typeof e.tone!="string"||!xt.includes(e.tone))&&f("MANIFEST_INVALID","tone is invalid","tone"),l=e.tone),e.entry!=="ui/index.html"&&f("MANIFEST_INVALID","entry path is not fixed","entry","fixed-value");let p;C(e,"entryHash")&&(p=$("entryHash",()=>ho(e.entryHash)));let u;C(e,"initialState")&&(u=$("initialState",()=>Cc(e.initialState)));let y;C(e,"usage")&&(e.usage!=="card"&&e.usage!=="window"&&f("MANIFEST_INVALID","usage is invalid","usage"),y=e.usage);let g;C(e,"detailPanel")&&(typeof e.detailPanel!="boolean"&&f("MANIFEST_INVALID","detailPanel is invalid","detailPanel"),g=e.detailPanel);let _;if(C(e,"displayModes")){((y??je)!==je||!Array.isArray(e.displayModes)||e.displayModes.length===0)&&f("MANIFEST_INVALID","displayModes are only valid for window Apps","displayModes");let w=new Set(["inline","floating","focused"]);(new Set(e.displayModes).size!==e.displayModes.length||e.displayModes.some(k=>typeof k!="string"||!w.has(k)))&&f("MANIFEST_INVALID","displayModes are invalid","displayModes"),_=e.displayModes;}(y??je)===je&&g!==void 0&&f("MANIFEST_INVALID","detailPanel is card-only","detailPanel");let E=n.mode??"local";E!=="local"&&E!=="installed"&&E!=="published"&&f("MANIFEST_INVALID","manifest mode is invalid"),E!=="local"&&p===void 0&&f("MANIFEST_INVALID","installed manifests require entryHash","entryHash","required-when-installed"),E!=="local"&&u!==void 0&&u.hash===void 0&&f("MANIFEST_INVALID","installed manifests require initialState.hash","initialState.hash","required-when-installed"),(!Array.isArray(e.surfaces)||e.surfaces.length===0)&&f("MANIFEST_INVALID","surfaces are invalid","surfaces"),e.surfaces.length>2&&q("surfaces exceed the v2 limit","surfaces","too-many-items");let v=[],j=new Set;for(let w of e.surfaces)(typeof w!="string"||!vt.includes(w))&&f("MANIFEST_INVALID","surface is unsupported","surfaces"),j.has(w)&&f("MANIFEST_INVALID","surfaces contain a duplicate","surfaces","duplicate-item"),j.add(w),v.push(w);W(e.size)||f("MANIFEST_INVALID","size must be an object","size"),$("size",()=>Y(e.size,["height"]));let b=$("size",()=>ge(e.size,"height",1));b>720&&q("size.height exceeds the v2 limit","size.height","too-large");let U=$("stateProjection",()=>qt(e.stateProjection)),H=e.summaryProjection===void 0?void 0:$("summaryProjection",()=>qt(e.summaryProjection));H!==void 0&&H.allow.some(w=>!U.allow.includes(w))&&f("MANIFEST_INVALID","summaryProjection must be a subset of stateProjection.allow","summaryProjection");let N=$("dataPaths",()=>_c(e.dataPaths,U.allow)),D=C(e,"deviceFeatures")?$("deviceFeatures",()=>Ec(e.deviceFeatures)):void 0,O=C(e,"downloads")?$("downloads",()=>Tc(e.downloads)):void 0;Array.isArray(e.actions)||f("MANIFEST_INVALID","actions must be an array","actions"),e.actions.length>32&&q("actions exceed the v2 limit","actions","too-many-items");let I=[],A=new Set,h=0,T=0;for(let[w,k]of e.actions.entries()){let X=`actions[${w}]`,B=$(X,()=>Sc(k));if(A.has(B.actionId)&&f("MANIFEST_INVALID","actions contain a duplicate actionId",`${X}.actionId`,"duplicate-item"),B.schedule!==void 0&&(h+=1,h>Xi&&f("MANIFEST_INVALID","an App declares at most one scheduled action",`${X}.schedule`,"duplicate-item")),B.job!==void 0&&(T+=1,T>Yi&&f("MANIFEST_INVALID","an App declares at most one job action",`${X}.job`,"duplicate-item")),B.backend.type==="core"&&B.backend.handler==="state.set"){B.mutation||f("MANIFEST_INVALID","state.set actions must be mutations",`${X}.mutation`);for(let Te of Object.keys(B.inputSchema.properties))U.allow.includes(Te)||f("MANIFEST_INVALID","state.set input paths must be projection-allowed",`${X}.inputSchema.properties`);}A.add(B.actionId),I.push(B);}return {manifestVersion:2,pluginId:o,definitionId:r,version:s,name:a,description:c,...d===void 0?{}:{icon:d},...l===void 0?{}:{tone:l},entry:"ui/index.html",...p===void 0?{}:{entryHash:p},...t===void 0?{}:{runtime:t},...i===void 0?{}:{csp:i},...u===void 0?{}:{initialState:u},...y===void 0?{}:{usage:y},...g===void 0?{}:{detailPanel:g},..._===void 0?{}:{displayModes:_},surfaces:v,size:{height:b},stateProjection:U,...H===void 0?{}:{summaryProjection:H},...N===void 0?{}:{dataPaths:N},...D===void 0?{}:{deviceFeatures:D},...O===void 0?{}:{downloads:O},actions:I}}function Eo(e){W(e)||f("MANIFEST_INVALID","_meta must be an object");let n=JSON.stringify(e);(n===void 0||Buffer.byteLength(n,"utf8")>Za)&&q("_meta exceeds the 4 KiB limit",void 0,"meta-too-large");}function vc(e){let n={},t={};for(let r of e.actions){n[r.actionId]={capabilities:[r.capability],inputKeys:Object.keys(r.inputSchema.properties??{}),...r.dataInputs===void 0?{}:{dataInputs:r.dataInputs},resultProjection:r.resultProjection,...r.confirmation===void 0?{}:{confirmation:r.confirmation},...r.content===void 0?{}:{content:r.content},...r.schedule===void 0?{}:{schedule:r.schedule},...r.job===void 0?{}:{job:r.job},...r.jobAccess===void 0?{}:{jobAccess:r.jobAccess},...r.backend.type!=="skill"||r.backend.env===void 0?{}:{env:r.backend.env}};let s=r.backend.type==="skill"||r.backend.type==="core"&&r.backend.handler==="state.set";t[r.actionId]={actionId:r.actionId,mutation:r.mutation,backend:r.backend,launchPolicy:s?"allowed":"denied",...s?{}:{denialCode:"EXEC_DENIED"}};}let i={id:e.definitionId,version:e.version,renderer:"sandbox-html",...e.usage===void 0?{}:{usage:e.usage},...e.detailPanel===void 0?{}:{detailPanel:e.detailPanel},...e.displayModes===void 0?{}:{displayModes:e.displayModes},surfaces:e.surfaces,stateProjection:e.stateProjection,...e.summaryProjection===void 0?{}:{summaryProjection:e.summaryProjection},...e.dataPaths===void 0?{}:{dataPaths:e.dataPaths},...e.downloads===void 0?{}:{downloads:e.downloads},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 ei(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||Qn(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=>ei(c,n,t+1,2097152,o,r));else {W(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]=ei(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 ti(e,n=[]){W(e)||Ie("initial state must be a JSON object");let t=ei(e,new Set,0,2097152,[],n);return (t===null||Array.isArray(t)||typeof t!="object")&&Ie(),t}function jc(e,n={}){Zn(e),W(e)||f("MANIFEST_INVALID"),Y(e,$a),e.manifestVersion!==1&&f("MANIFEST_INVALID");let t=Kt(be(e,"pluginId")),i=Kt(be(e,"definitionId")),o=ge(e,"version",1),r=ge(e,"primitiveSet",1),s=n.supportedPrimitiveSet??Ua;(!Number.isSafeInteger(s)||s<1)&&f("MANIFEST_INVALID"),r>s&&f("PRIMITIVE_SET_UNSUPPORTED"),W(e.activation)||f("MANIFEST_INVALID"),Y(e.activation,["kind","language"]),e.activation.kind!=="fenced-code"&&f("MANIFEST_INVALID");let a=Kt(be(e.activation,"language")),c=Ac(e.schema),d=mc(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 Fc(e,n={}){return W(e)||f("MANIFEST_INVALID"),Object.hasOwn(e,"lineage")&&f("MANIFEST_INVALID","lineage is only allowed in product bundle indexes"),e.manifestVersion===2?xc(e,n):jc(e,n)}function We(e,n={}){try{return Fc(e,n)}catch(t){if(t instanceof ce)throw t;return f("MANIFEST_INVALID")}}function hn(e,n={}){let t=We(e,n);return t.manifestVersion===2?vc(t):t}var Ua,ka,xa,mo,va,ja,Fa,Va,co,Ba,Ha,za,$a,Ga,Ja,Wa,Ka,Xa,Ya,qa,Za,Qa,ec,nc,tc,ic,oc,rc,sc,ac,cc,dc,pc,lc,uc,ce,ii=F(()=>{m();Jt();Oe();Vt();Zi();Gt();Bt();Ht();ao();$e();Ua=1,ka=/^[a-z][a-zA-Z0-9]*(\.[a-zA-Z0-9]+)+$/,xa=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,mo=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,va=/<\/?[A-Za-z][^>]*>/,ja=/^(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)/,Fa=/^(?:https?|file|ftp|ws|wss):\/\//i,Va=/^\s*(?:javascript|data):/i,co=/data:[^,\s]*,/i,Ba=/(?:https?|file|ftp|ws|wss):\/\//i,Ha=/javascript:/i,za=/(?:^[\s]*|[\s"'(=])(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)(?=[^\s"'<>])[^\s"'<>]*/,$a=["manifestVersion","pluginId","definitionId","version","primitiveSet","activation","schema","layout"],Ga=["manifestVersion","pluginId","definitionId","version","name","description","entry","surfaces","size","stateProjection","actions"],Ja=["_meta","icon","tone","entryHash","runtime","csp","initialState","usage","detailPanel","displayModes","summaryProjection","dataPaths","focusedAiDataPaths","deviceFeatures","downloads"],Wa=["actionId","capability","mutation","inputSchema","resultProjection","backend"],Ka=["confirmation","dataInputs","content","schedule","job","jobAccess","_meta"],Xa=["everyMinutes"],Ya=["timeoutMs"],qa=["deadlineMs"],Za=4*1024,Qa=["type","handler"],ec=["type","command"],nc=["env"],tc=["type","entry"],ic=["path"],oc=["hash"],rc=/^[0-9a-f]{64}$/,sc=/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/,ac=/[\r\n]/,cc=16,dc=16,pc=32,lc=/^[a-z][A-Za-z0-9]{0,31}$/,uc=["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 So(e){return typeof e=="string"&&e.length<=Bc&&Vc.test(e)}function V(e,n,t,i,o){throw new De(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 Z(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function he(e){let n=`_meta["${Fe}"]`;return e===void 0||e===""?n:e.startsWith("[")?`${n}${e}`:`${n}.${e}`}function Gc(e){return e.toLowerCase().replace(/_/g,"-")}function Jc(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 Mo(e,n,t){return {path:t(e.path),rule:e.rule??Gc(e.code),...e.message!==e.code?{message:e.message}:{},file:n}}function Oo(e){return JSON.parse(JSON.stringify(e))}function si(e,n,t=0,i=new Set){if(typeof e=="string"){e.length>4096&&V("LIMIT_EXCEEDED",n,"string-too-long"),(Hc.test(e)||zc.test(e)||$c.test(e))&&V("UNSAFE_VALUE",n,"unsafe-value");return}if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){Number.isFinite(e)||V("MANIFEST_INVALID",n,"non-finite-number");return}typeof e!="object"&&V("MANIFEST_INVALID",n,"non-json-value"),t>8&&V("LIMIT_EXCEEDED",n,"too-deep"),i.has(e)&&V("MANIFEST_INVALID",n,"cycle"),i.add(e);try{if(Array.isArray(e)){e.length>128&&V("LIMIT_EXCEEDED",n,"array-too-long"),e.forEach((o,r)=>si(o,`${n}[${r}]`,t+1,i));return}oe(e)||V("MANIFEST_INVALID",n,"non-plain-object");for(let[o,r]of Object.entries(e))si(r,n===""?o:`${n}.${o}`,t+1,i);}finally{i.delete(e);}}}function me(e,n){return (typeof e!="string"||e.length===0)&&V("MANIFEST_INVALID",n,"string"),e}function an(e,n){return oe(e)||V("MANIFEST_INVALID",n,"object"),e}function Wc(e,n){Array.isArray(e)||V("MANIFEST_INVALID",n,"array"),e.forEach((t,i)=>me(t,`${n}[${i}]`));}function Kc(e,n){typeof e!="boolean"&&V("MANIFEST_INVALID",n,"boolean");}function _n(e,n,t,i){for(let o of Object.keys(e))!t.includes(o)&&!i.includes(o)&&V("MANIFEST_INVALID",`${n}.${o}`,"unknown-key");for(let o of t)Z(e,o)||V("MANIFEST_INVALID",`${n}.${o}`,"missing-key");}function Xc(e,n){if(e!=="icon")switch(si(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)||V("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`),Z(r,"theme")&&me(r.theme,`${o}.theme`);});return}case "screenshots":case "keywords":case "privacy_policies":Wc(n,e);return;case "tools":{Array.isArray(n)||V("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`),Z(r,"description")&&me(r.description,`${o}.description`);});return}case "prompts":{Array.isArray(n)||V("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":Kc(n,e);return;case "localization":case "compatibility":case "user_config":an(n,e);return;default:V("MANIFEST_INVALID",e,"unknown-key");}}function et(e){return typeof e=="string"&&Pe.test(e)?e:void 0}function Lo(e){return Number.isSafeInteger(e)&&e>=1?e:void 0}function Yc(e){let n=et(e.name);if(n===void 0)return;let t=e._meta,i=oe(t)?t[Fe]:void 0,o=oe(i)?i:{},r=Z(o,"definitionId")?et(o.definitionId):n,s=Z(o,"definitionVersion")?Lo(o.definitionVersion):1;return {pluginId:n,...r===void 0?{}:{definitionId:r},...s===void 0?{}:{definitionVersion:s}}}function qc(e){let n=et(e.pluginId);if(n===void 0)return;let t=et(e.definitionId),i=Lo(e.version);return {pluginId:n,...t===void 0?{}:{definitionId:t},...i===void 0?{}:{definitionVersion:i}}}function di(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)&&Z(t,Fe)}catch{return false}}function Zc(e,n){if(e===pe)return n.builtinOnly===true;let t=n._meta,i=oe(t)?t[Fe]:void 0;return oe(i)&&i.builtinOnly===true}function Qc(e,n){Z(e,"server")&&V("MANIFEST_INVALID","server","server-unsupported","phase 1 runs CrewX-owned Apps only");for(let a of Object.keys(e))ai.includes(a)||V("MANIFEST_INVALID",a,"unknown-key");for(let a of ci)Z(e,a)||V("MANIFEST_INVALID",a,"missing-key");e.manifest_version!==oi&&V("MANIFEST_INVALID","manifest_version","unsupported-version",`manifest_version must be "${oi}"`),So(e.version)||V("MANIFEST_INVALID","version","semver","version must be a semver.org version such as 0.1.0");let t=e._meta;oe(t)||V("MANIFEST_INVALID","_meta","object"),Z(t,Fe)||V("MANIFEST_INVALID",he(),"missing-key");let i=t[Fe];oe(i)||V("MANIFEST_INVALID",he(),"object");for(let a of Object.keys(i))ri.includes(a)||Do.includes(a)||V("MANIFEST_INVALID",he(a),"unknown-key");for(let a of ri)a==="actions"&&n!==void 0||Z(i,a)||V("MANIFEST_INVALID",he(a),"missing-key");if(n!==void 0&&Z(i,"actions")&&V("MANIFEST_INVALID",he("actions"),"two-truths",`actions are declared in both ${K} and ${G}; a server.ts App keeps them in the tools file only`),ed(i.actions),Z(i,"definitionVersion")){let a=i.definitionVersion;(!Number.isSafeInteger(a)||a<1)&&V("MANIFEST_INVALID",he("definitionVersion"),"positive-integer");}let o={};for(let a of No)Z(e,a)&&(Xc(a,e[a]),o[a]=Oo(e[a]));let r={};for(let[a,c]of Object.entries(t))a!==Fe&&(r[a]=c);let s={manifestVersion:2,pluginId:e.name,definitionId:Z(i,"definitionId")?i.definitionId:e.name,version:Z(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:Le}}))),Object.keys(r).length>0&&(s._meta=r),{v2Input:s,...Object.keys(r).length>0?{vendorMeta:r}:{},passthrough:o}}function ed(e){Array.isArray(e)&&e.forEach((n,t)=>{let i=oe(n)?n.backend:void 0;oe(i)&&Z(i,"entry")&&V("MANIFEST_INVALID",he(`actions[${t}].backend.entry`),"entry-not-authorable",`an action in ${K} cannot name an entry; a server.ts App declares its actions in ${G}`);});}function nd(e,n,t){oe(e)||V("MANIFEST_INVALID","","not-object","manifest.json must be a JSON object",K);let i;try{i=Qc(e,t);}catch(s){throw s instanceof De?new De(s.code,{...s.reason,file:K}):s}let o;try{let s=We(i.v2Input,{mode:n.mode??"local"});s.manifestVersion!==2&&V("MANIFEST_INVALID","","v2-required"),o=s;}catch(s){throw s instanceof ce?new De(s.code,Mo(s,K,Jc)):s}let r=e.tools;if(Array.isArray(r)){let s=new Set(o.actions.map(a=>a.actionId));r.forEach((a,c)=>{let d=a.name;if(!s.has(d))throw new De("MANIFEST_INVALID",{path:`tools[${c}].name`,rule:"tool-not-action",message:"every tools[].name must be an action id",file:K})});}return {file:K,manifest:o,v2Input:i.v2Input,releaseVersion:e.version,...Object.keys(i.passthrough).length>0?{mcpb:i.passthrough}:{}}}function td(e,n){try{let t=We(e,{mode:n.mode??"local"});if(t.manifestVersion!==2)throw new De("MANIFEST_INVALID",{path:"manifestVersion",rule:"v2-required",message:"a workspace App requires manifestVersion 2",file:pe});return {file:pe,manifest:t,v2Input:e}}catch(t){throw t instanceof ce?new De(t.code,Mo(t,pe,i=>i??"")):t}}function cn(e){return le(hn(e).definition)}function Po(e){let{entryHash:n,initialState:t,...i}=e,o={...i};return t!==void 0&&(o.initialState={path:t.path}),Oo(o)}function id(e,n){let t=Po(e),i=Po(n);return [...new Set([...Object.keys(t),...Object.keys(i)])].sort().filter(r=>ie(t[r]??null)!==ie(i[r]??null))}function od(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 rd(e,n){let t=id(e,n),i=od(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||V("MANIFEST_DUAL_MISMATCH","","dual-manifest-mismatch",`${K} and ${pe} normalize to different definitions${o}`+(t.length>0?`; differing fields: ${t.join(", ")}`:""));}function Ne(e,n,t="MANIFEST_INVALID",i){return {code:t,reason:{path:e,rule:n,...i===void 0?{}:{message:i},file:G},files:[]}}function bo(e){return {...Ne("","tools-needs-manifest-json","MANIFEST_INVALID",`${G} is read with ${K} only`),files:e}}function sd(e,n){if(e.byteLength>n)return {failure:Ne("","file-too-large","LIMIT_EXCEEDED")};let t;try{t=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e));}catch{return {failure:Ne("","invalid-json")}}if(!oe(t))return {failure:Ne("","not-object","MANIFEST_INVALID",`${G} must be a JSON object`)};for(let o of Object.keys(t))if(o!=="schemaVersion"&&o!=="actions")return {failure:Ne(o,"unknown-key")};for(let o of ["schemaVersion","actions"])if(!Z(t,o))return {failure:Ne(o,"missing-key")};if(t.schemaVersion!==1)return {failure:Ne("schemaVersion","unsupported-version","MANIFEST_INVALID",`schemaVersion must be ${1}`)};let i=t.actions;if(!Array.isArray(i))return {failure:Ne("actions","array")};for(let[o,r]of i.entries()){if(!oe(r))return {failure:Ne(`actions[${o}]`,"object")};if(Z(r,"backend"))return {failure:Ne(`actions[${o}].backend`,"tools-backend","MANIFEST_INVALID",`an action in ${G} cannot carry a backend`)}}return {actions:i}}function ad(e,n){let t=n.maxBytes??262144,i=[],o=new TextDecoder("utf-8",{fatal:true});for(let r of ee){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 Be(e,n={}){let{parsed:t,failure:i}=ad(e,n),o=ee.filter(y=>e[y]!==void 0);if(i!==void 0)return {ok:false,rejection:i,parseFailure:true,builtinOnly:false};let r=e[G],s=r===void 0?void 0:sd(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:[]}:bo(o),parseFailure:true,builtinOnly:false};let a=t[0],c=a.file===K?Yc(a.raw):qc(a.raw),d=t.some(y=>Zc(y.file,y.raw)),l;if(s!==void 0){let y=t.some(g=>g.file===K)?s.failure:bo(o);if(y!==void 0)return {ok:false,rejection:y,parseFailure:false,...c===void 0?{}:{identity:c},builtinOnly:d};l=s.actions;}let p=[];try{for(let y of t)p.push(y.file===K?nd(y.raw,n,l):td(y.raw,n));p.length===2&&rd(p[0].manifest,p[1].manifest);}catch(y){if(y instanceof De)return {ok:false,rejection:{code:y.code,reason:y.reason,files:y.code==="MANIFEST_DUAL_MISMATCH"?[...ee]:y.reason.file===void 0||y.reason.file===G?o:[y.reason.file]},parseFailure:false,...c===void 0?{}:{identity:c},builtinOnly:d};throw y}let u=p[0];return {ok:true,...u,identity:c??{pluginId:u.manifest.pluginId},files:o}}var K,pe,ee,oi,Fe,ai,ci,No,ri,Do,Vc,Bc,Hc,zc,$c,De,nt=F(()=>{m();Ge();Oe();Gt();$e();ii();K="manifest.json",pe="ui-plugin.json",ee=[K,pe],oi="0.3",Fe="dev.crewx",ai=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"]),ci=Object.freeze(["manifest_version","name","display_name","version","description","_meta"]),No=Object.freeze(ai.filter(e=>e!=="server"&&!ci.includes(e))),ri=Object.freeze(["entry","surfaces","size","stateProjection","actions"]),Do=Object.freeze(["definitionId","definitionVersion","icon","tone","entryHash","runtime","initialState","usage","detailPanel","displayModes","summaryProjection","dataPaths","focusedAiDataPaths","csp","deviceFeatures","downloads"]),Vc=/^(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-]+)*))?$/,Bc=256,Hc=/<\/?[A-Za-z][^>]*>/,zc=/^\s*javascript:/i,$c=/data:[^,\s]*,/i;De=class extends Error{constructor(t,i){super(`${t}: ${i.path||"<file>"} (${i.rule})`);this.code=t;this.reason=i;}code;reason};});function vo(e){if(e===void 0)return {kind:"none"};if(typeof e!="string")return {kind:"invalid",reason:"bad-path"};if(pd.test(e))return {kind:"url",declared:e};if(!fd(e))return {kind:"invalid",reason:"bad-path",declared:e};let n=e.lastIndexOf("."),t=n<0?void 0:cd.get(e.slice(n+1).toLowerCase());return t===void 0?{kind:"invalid",reason:"bad-type",declared:e}:{kind:"file",path:e,contentType:t}}function fd(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=vo(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:[pi(t.reason,t.declared)]};let i=await n(t.path);if(typeof i=="string")return {diagnostics:[pi(i,t.path)]};let o=jo(t.contentType,i);if(!o.ok)return {diagnostics:[pi(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 pi(e,n){return {code:"ICON_INVALID",severity:"error",reason:e,...n===void 0?{}:{declared:n}}}function jo(e,n){if(n.byteLength>262144)return {ok:false,reason:"too-large"};if(e==="image/png")return !Uo(n,ld)||Pd(n,12,16)!=="IHDR"||n.byteLength<24?{ok:false,reason:"bytes-mismatch"}:{ok:true,square:Co(ko(n,16),ko(n,20))};if(e==="image/jpeg"){if(!Uo(n,ud))return {ok:false,reason:"bytes-mismatch"};let t=Ed(n);return {ok:true,square:t===void 0?void 0:Co(t.width,t.height)}}return yd(n)}function yd(e){let n;try{n=dd.decode(e);}catch{return {ok:false,reason:"bytes-mismatch"}}return hd(n)?{ok:false,reason:"unsafe-svg"}:Ad.test(n)?{ok:true,square:_d(n)}:{ok:false,reason:"bytes-mismatch"}}function hd(e){if(Id.some(n=>n.test(e)))return true;for(let n of e.matchAll(gd))if(!(n[1]??n[2]??n[3]??"").startsWith("#"))return true;for(let n of e.matchAll(md))if(Ro.lastIndex=n.index??0,!Ro.test(e))return true;return false}function _d(e){let n=/<svg\b[^>]*>/i.exec(e)?.[0];if(n===void 0)return;let t=Fo(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=wo(n,"width"),o=wo(n,"height");return i===void 0||o===void 0?void 0:i===o}function Fo(e,n){let t=new RegExp(`\\s${n}\\s*=\\s*(?:"([^"]*)"|'([^']*)')`).exec(e);return t?.[1]??t?.[2]}function wo(e,n){let t=Fo(e,n),i=t===void 0?null:/^\s*(\d+(?:\.\d+)?)(?:px)?\s*$/.exec(t);return i===null?void 0:Number(i[1])}function Ed(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(Td(t))return n+9>e.byteLength?void 0:{height:xo(e,n+5),width:xo(e,n+7)};n+=2+i;}}function Td(e){return e>=192&&e<=207&&e!==196&&e!==200&&e!==204}function Co(e,n){if(!(e<=0||n<=0))return e===n}function Uo(e,n){return e.byteLength>=n.length&&n.every((t,i)=>e[i]===t)}function Pd(e,n,t){return String.fromCharCode(...e.subarray(n,t))}function ko(e,n){return (e[n]<<24|e[n+1]<<16|e[n+2]<<8|e[n+3])>>>0}function xo(e,n){return e[n]<<8|e[n+1]}var cd,dd,pd,ld,ud,Ad,Id,gd,md,Ro,li=F(()=>{m();cd=new Map([["svg","image/svg+xml"],["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"]]),dd=new TextDecoder("utf-8",{fatal:true}),pd=/^[A-Za-z][A-Za-z0-9+.-]*:/,ld=[137,80,78,71,13,10,26,10],ud=[255,216,255];Ad=/^\s*(?:<\?[\s\S]*?\?>\s*|<!--[\s\S]*?-->\s*)*<svg(?=[\s/>])/,Id=[/<script/i,/[\s"'/]on[a-z]+\s*=/i,/<foreignobject/i,/<!doctype/i,/<!entity/i,/<(?:iframe|embed|object)\b/i,/@import/i],gd=/(?:^|[\s"'/])(?:xlink:)?href\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+))/gi,md=/url\(/gi,Ro=/url\(\s*["']?#/iy;});var Ho=F(()=>{m();});var ui=F(()=>{m();Gi();nt();li();ii();$e();Ho();});function S(e,n=e){throw new Se(e,n)}var Se,it=F(()=>{m();Se=class extends Error{constructor(t,i=t){super(i);this.code=t;}code;name="McpAppContractError"};});var er=F(()=>{m();});var nr=F(()=>{m();Ge();Oe();it();er();});function ir(e,n){return tr.add(e),n!==void 0&&kd.set(e,n),e}function dn(e){return e!==null&&typeof e=="object"&&tr.has(e)}var tr,kd,ot=F(()=>{m();tr=new WeakSet,kd=new WeakMap;});function Nn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function yi(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 sr(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let n of Object.values(e))sr(n);return Object.freeze(e)}function re(e){throw new Me("LINEAGE_INVALID",e)}function Hd(e){throw new Me("LINEAGE_STALE",e)}function ar(e){if(!Nn(e)||!yi(e,jd,Fd)||!Nn(e.actions))return re("Lineage definition shape is invalid");for(let n of Object.values(e.actions))if(!Nn(n)||!yi(n,Vd,Bd))return re("Lineage action definition shape is invalid");return e}function zd(e){if(!Nn(e)||!yi(e,xd,vd))return re("Lineage entry shape is invalid");if(!Number.isSafeInteger(e.version)||e.version<1||typeof e.hash!="string"||!or.test(e.hash))return re("Lineage entry identity is invalid");if(e.sourceHash!==void 0&&(typeof e.sourceHash!="string"||!or.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=ar(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"):sr({version:e.version,hash:e.hash,definition:n,...e.sourceHash===void 0?{}:{sourceHash:e.sourceHash},...e.compat===void 0?{}:{compat:e.compat}})}function rr(e){return e.stateProjection?.allow??[]}function $d(e,n){let t=[],i=new Set(rr(n));rr(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 Gd(e,n){return ie(e)===ie(n)}function Ai(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=ar(c),t={...i,hash:a},Ae(t);}catch{return re("Current definition is invalid")}let o=e.map(zd),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||!Gd(s.definition,i))return Hd("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 Me("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=$d(o[a].definition,t);if(d.length>0)throw new Me("LINEAGE_INVALID",`Lineage compatibility failed: ${d.join(", ")}`,d)}return Object.freeze({entries:Object.freeze(o),current:t})}var Me,or,xd,vd,jd,Fd,Vd,Bd,Ii=F(()=>{m();Ge();Oe();Me=class extends Error{constructor(t,i=t,o=[]){super(i);this.code=t;this.violations=o;}code;violations;name="UiDefinitionLineageError"},or=/^[0-9a-f]{64}$/,xd=["version","hash","definition"],vd=["sourceHash","compat"],jd=["id","version","actions"],Fd=["sourceHash","usage","detailPanel","displayModes","renderer","surfaces","stateProjection","dataPaths","summaryProjection","downloads","legacy"],Vd=["capabilities"],Bd=["inputKeys","dataInputs","confirmation","resultProjection","content","env","schedule","job","jobAccess"];});var cr,dr,pr,lr,ur=F(()=>{m();cr="text/html;profile=mcp-app",dr=["crewx_app_terminal_connect","crewx_app_html_viewer_open","crewx_app_browser"],pr=["crewx_listWorkspaces","crewx_queryAgent","crewx_executeAgent","crewx_getTaskResult","crewx_listTasks","crewx_listAgents","callBrowser","openTab","listTabs","closeTab"],lr="text/html";});function Dn(e){return typeof e=="string"&&Jd.includes(e)}function rt(e,n){return e==="card"&&n?.type==="core"&&Dn(n.handler)}var Jd,st=F(()=>{m();Jd=Object.freeze(["card.secret-env"]);});function fr(e,n=[],t){if(e.content!==void 0||e.confirmation!=="none")return "denied";let i=Wd();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 Wd(e){return;}var yr=F(()=>{m();Ge();ot();st();});function tp(e){return On.has(e)&&(e.initialState===void 0||On.has(e.initialState))}function hr(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:lr,entryHash:e,html:n,bytes:Object.freeze(t),...o===void 0?{}:{initialState:o}});return o!==void 0&&On.add(o),On.add(r),r}function ip(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:we}),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:we}),e?.appBrowser===true&&n.push({name:"crewx_app_browser",description:"Grant this App a native Desktop browser window. Browser commands use the custom Host RPC, not this tool.",inputSchema:{type:"object",properties:{workspace:{type:"string"},threadId:{type:"string"},instanceId:{type:"string"}},required:["threadId","instanceId"],additionalProperties:false},textFallback:"Desktop browser access is granted to this App. Browser commands use the custom Host RPC ui/crewx-app-browser.",visibility:Object.freeze(["app"]),kind:"host",resourceBinding:we}),n}function He(e,n,t){return (typeof e!="string"||!gr.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>Yd)&&S("TOOL_INVALID",`${n} must be a meaningful description`),i}function mi(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 Se)throw t;S("TOOL_INVALID","MCP App inputSchema must be projection-safe JSON");}}function op(e){return (typeof e!="string"||e.trim().length===0||e.length>qd)&&S("TOOL_INVALID","MCP App tools require a meaningful text fallback"),e}function rp(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 Er(e){return (typeof e!="string"||!mr.test(e))&&S("RESOURCE_URI_INVALID","MCP App resource URI is not a registered ui:// URI"),e}function Tr(e){let n=He(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=pt(e.definition),r=mi(e.html),s=at(e.entryHash,"Local App entry hash"),a=e.entryBytes===void 0?Array.from(new TextEncoder().encode(r)):dt(e.entryBytes,"Local App entry bytes");(ct(a)!==s||Nr(a)!==r)&&S("HTML_INVALID","Local App entry bytes do not match the HTML hash");let c=sp(e),d=[];Array.isArray(e.actions)||S("TOOL_INVALID","Local App actions must be an array");for(let b of e.actions){let U=He(b.actionId,"TOOL_ID_INVALID","Local App action id");(d.includes(U)||!Object.prototype.hasOwnProperty.call(o.actions,U))&&S("TOOL_INVALID",`Local App action is not declared by the UI definition: ${U}`),d.push(U);}let l=He(e.readToolName,"TOOL_ID_INVALID","Local App read tool name"),p=e.actionToolName===void 0?void 0:He(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=ip(e.runtime);u.some(b=>b.name===l||b.name===p)&&S("TOOL_ID_CONFLICT","Local App read or action tool conflicts with a requested Host capability");let y={name:l,description:`${t} current state`,inputSchema:np,textFallback:`${t} current state is available through its open instance.`,visibility:Object.freeze(["model","app"]),kind:"read",resourceBinding:we},g=[Object.freeze(y)];if(g.push(...u.map(b=>Object.freeze(b))),p!==void 0){let b={name:p,description:`${t} actions`,inputSchema:hi(e.actions),textFallback:`${t} action requests are handled by the open App instance.`,visibility:Object.freeze(["app"]),kind:"action",resourceBinding:we,actionIds:Object.freeze([...d])};g.push(Object.freeze(b));}let _=[],E=new Set(g.map(b=>b.name));if(p!==void 0)for(let b of e.actions){let U=`${p}__${b.actionId}`;if(U.length>128||!gr.test(U)){_.push(Object.freeze({toolName:U,actionId:b.actionId,reason:"name_too_long"}));continue}if(E.has(U)){_.push(Object.freeze({toolName:U,actionId:b.actionId,reason:"name_collision"}));continue}let H=fr({actionId:b.actionId,confirmation:o.actions[b.actionId]?.confirmation,content:o.actions[b.actionId]?.content,backend:b.backend},e.modelActions),N=Object.freeze([...lp(H,o.usage,b.backend)]),D={name:U,description:`${U} action`,inputSchema:Mn(b.inputSchema),textFallback:`${U} action requests are handled by the open App instance.`,visibility:N,kind:"action",resourceBinding:we,actionId:b.actionId,actionIds:Object.freeze([b.actionId]),_meta:Object.freeze({ui:Object.freeze({visibility:N})})};g.push(Object.freeze(D)),E.add(U);}let v=hr(s,r,a,c===void 0?void 0:{hash:c.hash,bytes:[...c.bytes]}),j={appId:n,name:t,description:i,...e.icon===void 0?{}:{icon:Dr(e.icon)},...e.tone===void 0?{}:{tone:Sr(e.tone)},builtinOnly:false,definition:o,...e.runtime===void 0?{}:{runtime:Object.freeze({...e.runtime})},...e.deviceFeatures===void 0?{}:{deviceFeatures:Object.freeze([...e.deviceFeatures])},...e.downloads===void 0?{}:{downloads:e.downloads},resourceBinding:we,resource:v,tools:Object.freeze(g),toolDiagnostics:Object.freeze(_)};return ne(j)}function Pr(e={}){return new gi(e)}function hi(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(ap(n,t),_r)}function sp(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=at(e.initialStateHash,"Initial state hash"),i=dt(e.initialStateBytes,"Initial state bytes");ct(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 ap(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 cp(e){let n=Ln(e),t=He(n.appId,"APP_ID_INVALID","MCP App id"),i=mi(n.html);Er(n.uiUri);let o=n.definition===void 0?void 0:pt(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=>ne(Ln(d)))),a=ne({...n,appId:t,html:i,...o===void 0?{}:{definition:o},...r===void 0?{}:{provenance:r},tools:s}),c=ne({uri:a.uiUri,mimeType:cr,text:i,...a.csp===void 0?{}:{_meta:{ui:{csp:a.csp}}}});return ne({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 dp(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=He(e.appId,"APP_ID_INVALID","Local App id"),t=pt(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=pp(e.resource),r=e.tools.map(a=>{He(a.name,"TOOL_ID_INVALID","Local App tool name"),Sn(a.description,"Local App tool description","Local App tool"),op(a.textFallback);let c=Mn(a.inputSchema,a.kind==="action"&&!("actionId"in a)?_r: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 (!ep.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"),ne({...a,inputSchema:c,visibility:Object.freeze(["app"])});if(a.kind==="action"){if("actionId"in a){let l=He(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=rp(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"),ne({...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"),ne({...a,inputSchema:c,actionIds:Object.freeze(d)})}return ne({...a,inputSchema:c})}),s=ne({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:Dr(e.icon)},...e.tone===void 0?{}:{tone:Sr(e.tone)},builtinOnly:false,definition:t,...e.runtime===void 0?{}:{runtime:Object.freeze({...e.runtime})},...e.deviceFeatures===void 0?{}:{deviceFeatures:Object.freeze([...e.deviceFeatures])},...e.downloads===void 0?{}:{downloads:e.downloads},...i===void 0?{}:{provenance:i},resourceBinding:we,resource:o,tools:Object.freeze(r),toolDiagnostics:Object.freeze([...e.toolDiagnostics??[]])});return Ar.has(e)?e:(Ar.add(s),s)}function pp(e){let n=mi(e.html),t=at(e.entryHash,"Local App entry hash");if(tp(e))return e;let i=dt(e.bytes,"Local App entry bytes");(ct(i)!==t||Nr(i)!==n)&&S("HTML_INVALID","Local App entry bytes do not match the HTML hash");let o=e.initialState===void 0?void 0:{hash:at(e.initialState.hash,"Initial state hash"),bytes:dt(e.initialState.bytes,"Initial state bytes")};return o&&ct(o.bytes)!==o.hash&&S("STATE_INVALID","Initial state bytes do not match the hash"),hr(t,n,i,o)}function lp(e,n,t){if(rt(n,t))return ["model"];let i=t?.type==="core"&&Dn(t.handler);return e==="denied"||i?["app"]:["model","app"]}function up(e){return ne({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:br(e.definition),...e.provenance===void 0?{}:{provenance:e.provenance},entryHash:e.resource.entryHash,resourceBinding:we,tools:e.tools})}function fp(e){return ne({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:br(e.definition)},resourceBinding:Object.freeze({kind:"mcp",uri:e.uiUri}),tools:e.tools})}function pt(e){try{if(Object.isFrozen(e))return Ae(e),ne(e);let n=Ln(e);return Ae(n),ne(n)}catch(n){if(n instanceof Se)throw n;S("STATE_INVALID","UI definition is not a valid immutable definition");}}function br(e){return ne({id:e.id,version:e.version,hash:e.hash})}function yp(e){return e!==null&&typeof e=="object"&&typeof e.id=="string"&&Number.isSafeInteger(e.version)&&typeof e.hash=="string"}function Ir(e,n,t){return `${e}\0${n}\0${t}`}function at(e,n){return (typeof e!="string"||!Xd.test(e))&&S("SERIALIZATION_INVALID",`${n} is invalid`),e}function ct(e){return createHash("sha256").update(Uint8Array.from(e)).digest("hex")}function dt(e,n){return (!Array.isArray(e)||e.some(t=>!Number.isInteger(t)||t<0||t>255))&&S("SERIALIZATION_INVALID",`${n} is invalid`),[...e]}function Nr(e){try{return new TextDecoder("utf-8",{fatal:!0}).decode(Uint8Array.from(e))}catch{S("SERIALIZATION_INVALID","UTF-8 bytes are invalid");}}function Dr(e){return (typeof e!="string"||!Zd.test(e))&&S("TOOL_INVALID","MCP App icon is invalid"),e}function Sr(e){return (typeof e!="string"||!Qd.has(e))&&S("TOOL_INVALID","MCP App tone is invalid"),e}function Ln(e,n=new Map){if(e===null||typeof e!="object")return e;let t=e;if(n.has(t)&&S("SERIALIZATION_INVALID","MCP App value contains a cycle"),Array.isArray(e)){let r=[];n.set(t,r);for(let s of e)r.push(Ln(s,n));return n.delete(t),r}let i;try{i=Object.getPrototypeOf(e);}catch{S("SERIALIZATION_INVALID","MCP App value cannot be cloned");}i!==Object.prototype&&i!==null&&S("SERIALIZATION_INVALID","MCP App value must be plain JSON");let o={};n.set(t,o);for(let[r,s]of Object.entries(e))Object.defineProperty(o,r,{configurable:true,enumerable:true,value:Ln(s,n),writable:true});return n.delete(t),o}function ne(e,n=new Set){if(e===null||typeof e!="object"||n.has(e)||On.has(e))return e;n.add(e);for(let t of Object.values(e))ne(t,n);return Object.freeze(e),e}var gr,mr,Xd,pn,Yd,qd,Zd,Qd,ep,we,np,On,Ar,_r,gi,lt=F(()=>{m();nr();Ge();Oe();ot();it();Ii();ur();yr();st();gr=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,mr=/^ui:\/\/crewx\/([A-Za-z][A-Za-z0-9._-]{0,127})\/([0-9a-f]{12})$/,Xd=/^[0-9a-f]{64}$/,pn=8*1024*1024,Yd=8*1024,qd=16*1024,Zd=/^[a-z][a-z0-9-]{0,63}$/,Qd=new Set(["blue","violet","emerald","amber","rose","sky","slate","indigo"]),ep=new Set(dr),new Set(pr),we=Object.freeze({kind:"instance"}),np=Object.freeze({type:"object",properties:Object.freeze({}),additionalProperties:false}),On=new WeakSet,Ar=new WeakSet;_r=4;gi=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=cp(p);s.has(u.appId)&&S("APP_ID_CONFLICT",`MCP App id is already registered: ${u.appId}`),s.add(u.appId);let y=u.tools;for(let g of y)a.has(g.name)&&S("TOOL_ID_CONFLICT",`MCP App tool name is already registered: ${g.name}`),a.add(g.name),this.mcpToolByName.set(g.name,g),r.push(g);this.mcpResources.set(u.resource.uri,u.resource),i.push(u),o.push(u.descriptor);}let c=(n.localApps??n.locals??[]).map(dp),d=new Set(c.flatMap(p=>p.tools.filter(u=>!(u.kind==="action"&&"actionId"in u)).map(u=>u.name))),l=[];for(let p of c){let u=p;s.has(u.appId)&&S("APP_ID_CONFLICT",`MCP App id is already registered: ${u.appId}`),s.add(u.appId);let y=[],g=[...u.toolDiagnostics??[]];for(let _ of u.tools){if(a.has(_.name)){if(_.kind==="host"&&this.localToolByName.get(_.name)?.kind==="host"){y.push(_);continue}if(_.kind==="action"&&"actionId"in _){g.push(Object.freeze({toolName:_.name,actionId:_.actionId,reason:"name_collision"}));continue}S("TOOL_ID_CONFLICT",`MCP App tool name is already registered: ${_.name}`);}if(_.kind==="action"&&"actionId"in _&&d.has(_.name)){g.push(Object.freeze({toolName:_.name,actionId:_.actionId,reason:"name_collision"}));continue}a.add(_.name),this.localToolByName.set(_.name,_),y.push(_);}(y.length!==u.tools.length||g.length!==(u.toolDiagnostics?.length??0))&&(u=ne({...u,tools:Object.freeze(y),toolDiagnostics:Object.freeze(g)})),l.push(u),this.localById.set(u.appId,u);}for(let p of i)this.registrationById.set(p.appId,p),this.launcherById.set(p.appId,fp(p)),p.definition&&this.addDefinition(p.definition);for(let p of l)this.registrationById.set(p.appId,p),this.launcherById.set(p.appId,up(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"||!mr.test(n)?null:this.mcpResources.get(n)??null}requireMcpAppResource(n){Er(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(!yp(n))return null;let t=this.definitionByKey.get($t(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(Ir(n,t,i))??null}addDefinition(n){let t=pt(n),i=$t(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=Ir(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 Ap(e){let n=Tr({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},...e.normalized.manifest.deviceFeatures===void 0?{}:{deviceFeatures:e.normalized.manifest.deviceFeatures},...e.normalized.manifest.downloads===void 0?{}:{downloads:e.normalized.manifest.downloads},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 Mr(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=Ap(e);Pr({localApps:[t],definitions:[e.definition]});}var Or=F(()=>{m();lt();});function Ip(e){if(e===null||typeof e!="object"||!(Lr in e))throw new TypeError("scanCache must be created by createWorkspaceAppScanCache");return e[Lr]}function Rr(e,n){let t=Ip(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 Lr,wr=F(()=>{m();Lr=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 _p(e){if(typeof e!="string"||e.length===0||!isAbsolute(e))throw new M("READ_DENIED")}function _i(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 At(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 bi(e,n){return e.dev===n.dev&&e.ino===n.ino}function Ni(e,n){return bi(e,n)&&e.size===n.size&&e.mtimeNs===n.mtimeNs&&e.ctimeNs===n.ctimeNs}async function ut(e){_p(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 kr(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(!At(n,o))throw new M("PATH_ESCAPED");return o}async function ft(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(!At(n,r)||t!==void 0&&!At(t,r))throw new M("PATH_ESCAPED");if(!o.isFile()||!s.isFile())throw new M("READ_DENIED");if(!bi(i,o)||!bi(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||!Ni(n.identity,un(i)))throw new M("PATH_ESCAPED")}function Ep(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,Pi,hp,Ur,It,xr,Si=F(()=>{m();M=class extends Error{constructor(t){super(t);this.code=t;}code;name="AppDiscoveryFsError"},Pi=constants.O_NOFOLLOW,hp=constants.O_NONBLOCK,Ur=constants.O_RDONLY|(Pi??0)|(hp??0);It=class{async getRootIdentity(n){let t=await ut(n);return await ln(n,t),{dev:t.identity.dev,ino:t.identity.ino,realPath:t.realRoot}}async listDirectory(n,t){let i=_i(t),o=await ut(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(!At(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(Ep)}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(Pi===void 0)throw new M("UNSUPPORTED");let o=_i(t),r=await ut(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,Ur);}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 kr(n,r.realRoot,o);await ft(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 y;try{let g=await c.stat({bigint:!0});y=un(g);}catch(g){throw ue(g)}if(!Ni(d,y))throw new M("IDENTITY_CHANGED");return await ft(s,r.realRoot,l,y),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(Pi===void 0)throw new M("UNSUPPORTED");let o=_i(t),r=await ut(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,Ur);}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 kr(n,r.realRoot,o);await ft(s,r.realRoot,l,d);let p;try{let u=await c.stat({bigint:!0});p=un(u);}catch(u){throw ue(u)}if(!Ni(d,p))throw new M("IDENTITY_CHANGED");return await ft(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)}},xr=new It;});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 jr(e){return typeof e=="string"&&Pe.test(e)?e:void 0}function Mp(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 Op(e){if(typeof e=="string")return {name:e,kind:"directory"};if(e===null||typeof e!="object")return null;let n=e;if(typeof n.name!="string")return null;if(n.kind==="file"||n.kind==="directory"||n.kind==="symlink"||n.kind==="other")return {name:n.name,kind:n.kind};if(n.type==="file"||n.type==="directory"||n.type==="symlink"||n.type==="other")return {name:n.name,kind:n.type};let t=n.isDirectory;if(typeof t=="function"&&t.call(e))return {name:n.name,kind:"directory"};let i=n.isSymbolicLink;if(typeof i=="function"&&i.call(e))return {name:n.name,kind:"symlink"};let o=n.isFile;return typeof o=="function"&&o.call(e)?{name:n.name,kind:"file"}:{name:n.name,kind:"other"}}function Lp(e){if(e instanceof Uint8Array)return new Uint8Array(e);if(e instanceof ArrayBuffer)return new Uint8Array(e.slice(0));if(Array.isArray(e)&&e.every(n=>Number.isInteger(n)&&n>=0&&n<=255))return Uint8Array.from(e);throw new TypeError("filesystem port returned an invalid byte array")}function Rp(e){return Dp.decode(e)}function wp(e){return JSON.parse(Rp(e))}function Fr(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 Cp(e){if(e instanceof M)return Fr(e.code);if(e!==null&&typeof e=="object"&&"code"in e){let n=e.code;if(typeof n=="string")return Fr(n)}}function Ce(e,n){let t=n();return Number.isFinite(t)&&Number.isFinite(e)&&t-e<=5e3}function Up(e){if(typeof e.readVerifiedFile=="function")return e.readVerifiedFile;if(typeof e.readFileVerified=="function")return e.readFileVerified}function kp(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 Vr(e,n,t,i){let o=Up(e);if(!o)throw new M("READ_DENIED");return Lp(await o.call(e,n,t,i))}async function Li(e,n,t){let i=kp(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(Op).filter(r=>r!==null)}function xp(e,n,t,i){return Object.freeze({code:e,...{},source:n,relativePath:t})}function vp(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 jp(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 mt(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 gt(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 Br(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 Fp(e){let n;try{n=wp(e);}catch{return}if(!Un(n)||!gt(n,["version","packages"])||n.version!==1||!Array.isArray(n.packages)||n.packages.length>Ri)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(!gt(s,[...a,...l])||d&&s.launcher!==false)return;let p=Br(s.packageDir),u=jr(s.appId);if(!p||p.length!==2||p[0]!=="apps"||!Mp(p[1])||!u||t.has(s.packageDir)||!Un(s.definition)||!gt(s.definition,["id","version","hash"]))return;let y=jr(s.definition.id),g=s.definition.version,_=s.definition.hash;if(!y||!Number.isSafeInteger(g)||g<1||typeof _!="string"||!Oi.test(_)||!Array.isArray(s.files)||s.files.length<2||s.files.length>wi)return;let E=new Set,v=[];for(let j of s.files){if(!Un(j)||!gt(j,["path","sha256"]))return;let b=Br(j.path);if(!b||typeof j.sha256!="string"||!Oi.test(j.sha256))return;let U=b.join("/"),H=`${s.packageDir}/${U}`;if(E.has(U)||i.has(H))return;E.add(U),i.add(H),v.push(Object.freeze({path:U,sha256:j.sha256}));}if(!ee.some(j=>E.has(j))||!E.has("ui/index.html")||(o+=v.length,o>Pp))return;t.add(s.packageDir),r.push(Object.freeze({packageDir:s.packageDir,...d?{launcher:false}:{},appId:u,definition:Object.freeze({id:y,version:g,hash:_}),lineage:Array.isArray(s.lineage)?s.lineage:[],files:Object.freeze(v.sort((j,b)=>Xe(j.path,b.path)))}));}return Object.freeze({version:1,packages:Object.freeze(r)})}function Ke(e){let n=Cp(e);return n==="PATH_ESCAPED"||n==="IDENTITY_CHANGED"||n==="TOCTOU"?"PATH_ESCAPED":n==="LIMIT_EXCEEDED"?"LIMIT_EXCEEDED":"BUNDLE_INTEGRITY"}async function Vp(e,n,t,i,o){let r=[],s=async(a,c)=>{if(!Ce(i,o))throw new M("LIMIT_EXCEEDED");if(c>2)throw new M("LIMIT_EXCEEDED");let d=await Li(e,n,a);for(let l of d){if(typeof l.name!="string"||l.name.length===0||l.name==="."||l.name===".."||/[\\/\u0000]/.test(l.name))throw new M("PATH_ESCAPED");let p=`${a}/${l.name}`;if(l.kind==="file"){if(r.push(p.slice(t.length+1)),r.length>wi)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 Bp(e){return ee.includes(e)?262144:e==="ui/index.html"?pn:e==="ui/state.json"?2097152:e.startsWith("ui/assets/")?Np:bp}async function Hr(e,n,t,i){if(e===void 0)return {packages:[],diagnostics:[],incomplete:false,reservedIds:Sp};let o=vp(e.reservedIds),r=[],s=(I,A,h)=>xp(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"||!Oi.test(e.expectedIndexHash))return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a();let c;try{c=await Vr(n,e.root,"bundle-index.json",Tp);}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=Fp(c);if(l===void 0)return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a();if(!jp(mt(l.packages),o))return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a([],false,d);if(!Ce(t,i))return r.push(s("LIMIT_EXCEEDED","bundle-index.json")),a(l.packages.map(I=>({indexEntry:I,failureCode:"LIMIT_EXCEEDED"})),true,d);let p;try{p=await Li(n,e.root,"");}catch(I){return r.push(s(Ke(I),"bundle-index.json")),a(l.packages.map(A=>({indexEntry:A,failureCode:Ke(I)})),false,d)}if(!Ce(t,i))return r.push(s("LIMIT_EXCEEDED","bundle-index.json")),a(l.packages.map(I=>({indexEntry:I,failureCode:"LIMIT_EXCEEDED"})),true,d);let u=p.find(I=>I.name==="bundle-index.json"&&I.kind==="file"),y=p.find(I=>I.name==="apps"&&I.kind==="directory"),g=I=>l.packages.map(A=>({indexEntry:A,failureCode:I}));if(!u)return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a(g("BUNDLE_INTEGRITY"),false,d);let _=p.filter(I=>I.name!=="bundle-index.json"&&I.name!=="apps");if(_.length>0){let I=_.some(A=>A.kind==="symlink")?"PATH_ESCAPED":"BUNDLE_INTEGRITY";return r.push(s(I,"bundle-index.json")),a(g("BUNDLE_INTEGRITY"),false,d)}if(p.some(I=>I.name==="apps"&&I.kind!=="directory"))return r.push(s("PATH_ESCAPED","apps")),a(g("PATH_ESCAPED"),false,d);let E=[];if(y)try{E=await Li(n,e.root,"apps");}catch(I){return r.push(s(Ke(I),"apps")),a(g(Ke(I)),false,d)}if(!Ce(t,i)||E.length>Ri)return r.push(s("LIMIT_EXCEEDED","apps")),a(g("LIMIT_EXCEEDED"),true,d);let v=new Map(l.packages.map(I=>[I.packageDir.slice(5),I])),j=E.filter(I=>!v.has(I.name));for(let I of j)r.push(s(I.kind==="symlink"?"PATH_ESCAPED":"BUNDLE_INTEGRITY",`apps/${I.name}`));if(j.length>0){let I=j.some(A=>A.kind==="symlink")?"PATH_ESCAPED":"BUNDLE_INTEGRITY";return a(g(I),false,d)}let b=new Set,U=new Map,H=new Map;for(let I of l.packages){let A=U.get(I.appId)??[];A.push(I),U.set(I.appId,A);let h=`${I.definition.id}\0${String(I.definition.version)}`,T=H.get(h)??[];T.push(I),H.set(h,T);}for(let I of [...U.values(),...H.values()])if(I.length>1)for(let A of I)b.add(A);let N=[],D=c.byteLength,O=false;for(let I of l.packages){if(!Ce(t,i)){O=true,N.push({indexEntry:I,failureCode:"LIMIT_EXCEEDED"});continue}let A;try{let w=I.lineage[I.lineage.length-1];if(!w)throw new Me("LINEAGE_INVALID","Definition lineage is missing");if(w.definition.id!==I.definition.id||w.version!==I.definition.version||w.hash!==I.definition.hash)throw new Me("LINEAGE_STALE","Last lineage generation does not match bundle identity");A=Ai(I.lineage,{...w.definition,hash:w.hash}).entries;}catch(w){let k=w instanceof Me?w.code:"LINEAGE_INVALID";r.push(s(k,I.packageDir)),N.push({indexEntry:I,failureCode:k});continue}let h=E.find(w=>w.name===I.packageDir.slice(5));if(!y||!h){N.push({indexEntry:I,failureCode:"BUNDLE_INTEGRITY"});continue}if(h.kind!=="directory"){N.push({indexEntry:I,failureCode:h.kind==="symlink"?"PATH_ESCAPED":"BUNDLE_INTEGRITY"});continue}let T;try{let w=await Vp(n,e.root,I.packageDir,t,i);if(!Ce(t,i)){O=!0,N.push({indexEntry:I,failureCode:"LIMIT_EXCEEDED"});continue}let k=I.files.map(B=>B.path);if(w.length!==k.length||w.some((B,Te)=>B!==k[Te])){N.push({indexEntry:I,failureCode:"BUNDLE_INTEGRITY"});continue}T=new Map;let X;for(let B of I.files){if(!Ce(t,i)){X="LIMIT_EXCEEDED",O=!0;break}if(D>=Mi){X="LIMIT_EXCEEDED";break}let Te;try{Te=await Vr(n,e.root,`${I.packageDir}/${B.path}`,Bp(B.path));}catch(St){X=Ke(St);break}if(!Ce(t,i)){X="LIMIT_EXCEEDED",O=!0;break}if(D+Te.byteLength>Mi){D=Mi,X="LIMIT_EXCEEDED";break}if(D+=Te.byteLength,createHash("sha256").update(Te).digest("hex")!==B.sha256){X="BUNDLE_INTEGRITY";break}T.set(B.path,Te);}if(X!==void 0){N.push({indexEntry:I,failureCode:X});continue}}catch(w){Ce(t,i)||(O=true),N.push({indexEntry:I,failureCode:Ke(w)});continue}N.push({indexEntry:I,lineage:A,files:T,...b.has(I)?{failureCode:"DUPLICATE_ID"}:{}});}return a(N,O,d)}var Tp,Ri,wi,Pp,bp,Np,Mi,Oi,Dp,Sp,Ci=F(()=>{m();Ii();$e();nt();lt();Si();Tp=256*1024,Ri=64,wi=128,Pp=Ri*wi,bp=2*1024*1024,Np=8*1024*1024,Mi=32*1024*1024,Oi=/^[0-9a-f]{64}$/,Dp=new TextDecoder("utf-8",{fatal:true}),Sp=Object.freeze({appIds:Object.freeze([]),definitionIds:Object.freeze([])});});function zp(e){if(typeof e!="string"||!Pe.test(e))throw new TypeError("pluginId must be a safe UI plugin identifier");let n=`${Ui}${e}`.length+7<=128?e:`hash_${createHash("sha256").update(e,"utf8").digest("hex")}`;return {read:`${Ui}${n}_read`,action:`${Ui}${n}_action`}}function $r(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 Gp(e,n){return n.length===0||n==="."||n===".."||/[\\/\u0000]/.test(n)?e==="skills"?"skills":"apps":`${e==="skills"?"skills":"apps"}/${n}`}function Jp(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 ns(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 Wp(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 ts(e){return $p.decode(e)}function Kp(e){return JSON.parse(ts(e))}function Xp(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 ht(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 Gr(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 Gr(e.code);if(e!==null&&typeof e=="object"&&"code"in e){let n=e.code;if(typeof n=="string")return Gr(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 Jr(e){return {reason:e.reason,...e.code==="MANIFEST_DUAL_MISMATCH"?{files:e.files}:{}}}function Wr(e){return e==="MANIFEST_DUAL_MISMATCH"?e:is(e)}function Yp(e){return is(e.code)}function is(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 os("UiPluginValidationError",e)}}function os(e,n){throw new Error(`Unmapped ${e} code: ${String(n)}`)}function rs(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 os("McpAppContractError",e)}}function Ue(e,n){let t=n();return Number.isFinite(t)&&Number.isFinite(e)&&t-e<=5e3}function qp(e){return {pluginId:e.appId,definitionKey:`${e.definition.id}\0${String(e.definition.version)}`}}function Zp(e,n){let t=n.get("package.json");if(t!==void 0)try{let o=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(t));if($r(o)){let r=o.bin,s=typeof r=="string"?r:$r(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=Qp(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 Qp(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 el(){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 Kr(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 Zr(e,n.root,o,i);try{let a=r.priorFingerprints.get(o)??await s.call(e,r.workspaceRoot,o,i);r.candidateRealPath=a.candidateRealPath;let c=await Zr(e,n.root,o,i),d=await s.call(e,r.workspaceRoot,o,i);return r.candidateRealPath=d.candidateRealPath,as(a,d)&&d.size===BigInt(c.byteLength)&&!cs(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&&!_t(l.key,t)),d=t===G&&se(a)==="NOT_FOUND"&&tl(r.directoryListings,n.relativePath);throw !c&&!d&&(r.cacheable=false),a}}async function nl(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 tl(e,n){let t=e.find(o=>o.relativePath===n);if(t===void 0)return false;if(!_t(t.key,"dist"))return true;let i=e.find(o=>o.relativePath===`${n}/dist`);return i!==void 0&&!_t(i.key,"tools.json")}function ss(e,n){return JSON.stringify([e.realPath,n.source,n.relativePath])}async function ol(e,n,t,i,o,r,s,a){let c=e.fingerprintVerifiedFile,d=ss(t,i),l=o.candidates.get(d),p=i.relativePath,u;try{u=await qr(e,n,p);}catch(O){if(se(O)!=="NOT_FOUND")throw O}let y=u===void 0?void 0:{relativePath:p,key:u};if(y!==void 0&&(i.source==="apps"||i.source==="skills")&&!ee.some(O=>_t(y.key,O)))return Ue(s,a)?l!==void 0&&l.candidate===void 0&&l.candidateRealPath===void 0&&l.files.length===0&&l.directoryListings.length===1&&l.directoryListings[0]?.relativePath===y.relativePath&&l.directoryListings[0]?.key===y.key&&(i.source==="apps"?l.diagnostic?.code==="MANIFEST_MISSING":l.diagnostic===void 0)&&typeof c=="function"?{memo:l}:typeof c!="function"?{}:{context:{state:o,cacheKey:d,workspaceRoot:n,scanStartedAtNs:r,directoryListings:Object.freeze([y]),priorFingerprints:new Map,files:new Map,cacheable:true}}:{timeLimitReached:true};let g=async O=>{if(O==="")return y;let I=`${i.relativePath}${O}`;try{let A=await qr(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(Xr.map(g)),E=await Promise.all(il.map(g));if(!Ue(s,a))return {timeLimitReached:true};let v=typeof c=="function"&&_.every(O=>O!==void 0),j=_.filter(O=>O!==void 0),b=[...j,...E.filter(O=>O!==void 0)],U=new Map,H=l!==void 0&&v,N;if(l!==void 0&&typeof c=="function"){let O=await Promise.all(l.files.map(async I=>{if(!Ue(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(O.some(I=>I.kind==="time"))return {timeLimitReached:true};for(let I of O){if(I.kind==="error")throw I.error;if(I.kind==="missing"){H=false;continue}if(I.kind!=="fingerprint")continue;let{file:A,current:h}=I;U.set(A.relativePath,h),N??=h.candidateRealPath,(h.candidateRealPath!==l.candidateRealPath||!as(h,A.fingerprint)||cs(h,r))&&(H=false);}}let D=l!==void 0&&l.directoryListings.length===b.length&&l.directoryListings.every((O,I)=>O.relativePath===b[I]?.relativePath&&O.key===b[I]?.key);return l!==void 0&&v&&D&&H&&N===l.candidateRealPath?{memo:l}:!v||j.length!==Xr.length?{}:{context:{state:o,cacheKey:d,workspaceRoot:n,scanStartedAtNs:r,directoryListings:Object.freeze(b),priorFingerprints:U,files:new Map,...N===void 0?{}:{candidateRealPath:N},cacheable:true}}}function _t(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 qr(e,n,t){let i=ds(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(ns);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 as(e,n){return e.dev===n.dev&&e.ino===n.ino&&e.size===n.size&&e.mtimeNs===n.mtimeNs&&e.ctimeNs===n.ctimeNs}function cs(e,n){let t=e.mtimeNs-n;return t>=-Yr&&t<=Yr}function ki(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 rl(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 sl(e,n){let t={...e.definition,sourceHash:n},i;try{i=le(t);}catch(r){throw r instanceof x&&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 al(e,n){return e.actions.some(t=>t.backend.type==="core"&&t.backend.handler!=="state.set"&&!rt(n,t.backend))}function cl(e){if(typeof e.readVerifiedFile=="function")return e.readVerifiedFile;if(typeof e.readFileVerified=="function")return e.readFileVerified}function ds(e){if(typeof e.listDirectory=="function")return e.listDirectory;if(typeof e.readDirectory=="function")return e.readDirectory;if(typeof e.readdir=="function")return e.readdir}async function Zr(e,n,t,i){let o=cl(e);if(!o)throw new M("READ_DENIED");return Wp(await o.call(e,n,t,i))}async function dl(e,n,t){let i=ds(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(ns).filter(r=>r!==null)}function pl(e){let n=[];for(let t of [e.reserved,e.builtin])t&&n.push(t);return e.builtins&&"listMcpApps"in e.builtins?n.push(Qr(e.builtins)):e.builtins&&n.push(e.builtins),e.builtinCatalog&&n.push(Qr(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 Qr(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=ht(n,e.source,e.relativePath,e.identity?.pluginId));}function ll(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 ul(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 pl(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(y=>y!==void 0).some(y=>r.has(y))&&_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{Mr(p),d.add(l);}catch(u){_e(l,u instanceof Se?rs(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 fl(e){return [...e].sort((n,t)=>{let i=zr.indexOf(n.source)-zr.indexOf(t.source);return i!==0?i:xn(n.relativePath,t.relativePath)})}function z(e,n,t){e.diagnostic=ht(n,e.source,e.relativePath,e.identity?.pluginId,t);}async function es(e,n,t){let i=Be(t,{mode:"local"});if(!i.ok&&i.parseFailure){z(n,Wr(i.rejection.code),Jr(i.rejection));return}let o=Xp(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)}`){z(n,"BUNDLE_INTEGRITY");return}if(!i.ok&&i.builtinOnly){z(n,"RESERVED_ID");return}if(!i.ok){z(n,Wr(i.rejection.code),Jr(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{hi(r.actions.map(k=>({actionId:k.actionId,inputSchema:k.inputSchema})));}catch(k){if(k instanceof Se){z(n,rs(k.code));return}throw k}let a;try{a=await vn(e,n,"ui/index.html",pn);}catch(k){z(n,qe(se(k),"entry"));return}if(a.byteLength>pn){z(n,"LIMIT_EXCEEDED");return}let c;try{c=ts(a);}catch{z(n,"ENTRY_INVALID");return}if(a.byteLength===0||c.length===0){z(n,"ENTRY_INVALID");return}let d=createHash("sha256").update(a).digest("hex");if(r.entryHash!==void 0&&r.entryHash!==d){z(n,"ENTRY_INVALID");return}let l={},p,u;if(r.initialState!==void 0){try{p=await vn(e,n,"ui/state.json",2097152);}catch(k){z(n,qe(se(k),"initial"));return}if(p.byteLength>2097152){z(n,"LIMIT_EXCEEDED");return}try{let k=Kp(p),X=r.dataPaths??[],B=ti(k,X);l=ye(B,0,X),nn(l);}catch{z(n,"INITIAL_STATE_INVALID");return}if(u=createHash("sha256").update(p).digest("hex"),r.initialState.hash!==void 0&&r.initialState.hash!==u){z(n,"INITIAL_STATE_INVALID");return}}let y={...r,entryHash:d,...r.initialState===void 0?{}:{initialState:{path:"ui/state.json",hash:u}}},g=hn(y),_=rl(y,a,p??new Uint8Array),E;try{E=sl(g,_);}catch(k){if(k instanceof ce){z(n,Yp(k));return}throw k}let v;if(n.bundleLineage!==void 0){let k=n.bundleLineage[n.bundleLineage.length-1];if(!k){z(n,"LINEAGE_INVALID");return}let{legacy:X,...B}=k.definition,{hash:Te,...St}=E;if(ie(B)!==ie(St)){z(n,"LINEAGE_STALE");return}if(X!==void 0&&(E={...E,legacy:X}),X!==void 0)try{E={...E,hash:le(E)},Ae(E);}catch{z(n,"LINEAGE_INVALID");return}v=n.bundleLineage;}if(n.bundleIdentity!==void 0&&n.bundleIdentity.appId!==r.pluginId){z(n,"BUNDLE_INTEGRITY");return}if(n.bundleIdentity!==void 0&&(n.bundleIdentity.definitionId!==E.id||n.bundleIdentity.version!==E.version||n.bundleIdentity.definitionHash!==E.hash)){z(n,"LINEAGE_STALE");return}let j=await nl(e,n,i.mcpb?.icon),b=zp(r.pluginId),U=r.actions.length===0?{read:b.read}:b,H=Ye(g),N=Ye(y),D=Ye(E),O=Ye({...g.handlers}),I=Kr(a),A=p===void 0?void 0:Kr(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})}}),T={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:H,name:r.name,description:r.description,...r.icon===void 0?{}:{icon:r.icon},...r.tone===void 0?{}:{tone:r.tone},...j.iconFile===void 0?{}:{iconFile:Object.freeze({...j.iconFile})},...j.iconDiagnostics.length===0?{}:{iconDiagnostics:Object.freeze([...j.iconDiagnostics])},definition:D,handlers:O,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(U)},w=n.provenance===void 0?{...T,source:n.source}:{...T,provenance:n.provenance,lineage:v??[]};n.candidate=Object.freeze(w),al(r,E.usage)&&z(n,"EXEC_DENIED");}async function ps(e,n){let t={};for(let i of ee)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[K]!==void 0)try{t[G]=await vn(e,n,G,262144);}catch(i){if(se(i)!=="NOT_FOUND")return {files:t,failure:qe(se(i),"manifest")}}return {files:t}}function xi(e){return ee.some(n=>e[n]!==void 0)}async function yl(e,n){let{files:t,failure:i}=await ps(e,n);if(i!==void 0){z(n,i);return}let o=t[K];return o!==void 0&&!di(o)&&(delete t[K],delete t[G]),xi(t)?t:void 0}function Al(e,n,t,i=Hp,o=false,r=new Set){let s=fl(e),a=ll(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 Il(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 gl(e,n){if(Il(e))return {fs:e,options:{}};let t=e??n??{};return {fs:t.filesystem??t.fileSystem??t.fs??xr,options:t}}async function ls(e,n,t){if(typeof e!="string"||e.length===0)throw new TypeError("workspaceRoot must be explicit");let{fs:i,options:o}=gl(n,t),r=o.clock??el,s=r(),a=await Hr(o.productBundle,i,s,r),c=r(),d=BigInt(Date.now())*1000000n,l=[],p=0,u,y=false,g,_;if(o.scanCache!==void 0&&typeof i.getRootIdentity=="function"&&typeof i.fingerprintVerifiedFile=="function")try{_=await i.getRootIdentity(e),g=Rr(o.scanCache,_),g.scanStartedAtNs=d;}catch(N){if(se(N)!=="NOT_FOUND")throw N}let E=g!==void 0&&o.productBundle===void 0&&a.packages.length===0&&a.diagnostics.length===0,v=new Set,j=true;l.push(...a.diagnostics.map(N=>({source:N.source,root:o.productBundle?.root??e,name:"",relativePath:N.relativePath,diagnostic:N})));let b=a.reservedIds;a.incomplete&&(u="time_limit");for(let N of a.packages){if(!Ue(c,r)){y=true,u="time_limit";break}let D=N.indexEntry,O=D.packageDir,I=N.files===void 0?void 0:Zp(O,N.files),A=a.indexHash===void 0?void 0:ir(Object.freeze({kind:"bundled",launcher:D.launcher!==false,indexHash:a.indexHash,packageDir:O,appId:D.appId,definitionId:D.definition.id,version:D.definition.version,definitionHash:D.definition.hash,files:D.files}),I),h={source:"bundled",root:o.productBundle?.root??e,name:O.slice(5),relativePath:O,...A===void 0?{}:{provenance:A},...N.files===void 0?{}:{pinnedFiles:N.files},...N.lineage===void 0?{}:{bundleLineage:N.lineage},bundleIdentity:{appId:D.appId,definitionId:D.definition.id,version:D.definition.version,definitionHash:D.definition.hash},identity:qp(D)};if(l.push(h),p+=1,N.failureCode!==void 0){z(h,N.failureCode);continue}if(N.files?.has(G)===true){z(h,"EXEC_DENIED",{reason:{path:"",rule:"bundled-tool-mode-unsupported",file:G}});continue}let T={};for(let w of ee){let k=N.files?.get(w);k!==void 0&&(T[w]=k);}if(!xi(T)){z(h,"BUNDLE_INTEGRITY");continue}if(await es(i,h,T),!Ue(c,r)){y=true,u="time_limit";break}}let U=[{source:"apps",directory:"apps"},{source:"skills",directory:"skills"}];e:for(let N of U){let{source:D,directory:O}=N,I;try{I=await dl(i,e,O);}catch(h){if(se(h)==="NOT_FOUND")continue;E=false,j=false,l.push({source:D,root:e,name:"",relativePath:D,diagnostic:ht(qe(se(h),"manifest"),D,D)});continue}let A=I.filter(h=>h.kind==="directory"||h.kind==="symlink").filter(h=>Jp(h.name)).map(h=>({source:D,root:e,name:h.name,relativePath:Gp(D,h.name)})).sort((h,T)=>xn(h.relativePath,T.relativePath));for(let h of A){let T={...h};if(l.push(T),_!==void 0?v.add(ss(_,T)):E=false,!Ue(c,r)){y=true,u="time_limit";break e}let w;if(g!==void 0&&_!==void 0){try{let B=await ol(i,e,_,T,g,d,c,r);if(B.timeLimitReached){y=!0,u="time_limit";break e}T.scanContext=B.context,w=B.memo;}catch(B){E=false,z(T,qe(se(B),"manifest"));continue}w===void 0&&(E=false);}if(w!==void 0){if(T.candidate=w.candidate,T.diagnostic=w.diagnostic,T.identity=w.identity,D==="skills"&&w.candidate===void 0&&w.diagnostic===void 0)continue;if(p>=64){z(T,"LIMIT_EXCEEDED");continue}if(h.relativePath.split("/").length-1>2){z(T,"LIMIT_EXCEEDED");continue}if(p+=1,!Ue(c,r)){y=true,u="time_limit";break e}continue}let k;if(D==="skills"&&(k=await yl(i,T),k===void 0)){T.diagnostic===void 0&&ki(T);continue}if(p>=64){z(T,"LIMIT_EXCEEDED");continue}if(h.relativePath.split("/").length-1>2){z(T,"LIMIT_EXCEEDED");continue}if(!Ue(c,r)){y=true,u="time_limit";break e}if(p+=1,k===void 0){let B=await ps(i,T);if(B.failure!==void 0||!xi(B.files)){z(T,B.failure??qe("NOT_FOUND","manifest")),ki(T);continue}k=B.files;}if(await es(i,T,k),ki(T),!Ue(c,r)){y=true,u="time_limit";break e}}}if(g!==void 0&&_!==void 0){let N=[...v].sort(xn),D=g.lastCandidateKeys,O=D!==void 0&&D.length===N.length&&D.every((A,h)=>A===N[h]);if(E=E&&O,j&&!y&&u===void 0)for(let A of g.candidates.keys())try{JSON.parse(A)[0]===_.realPath&&!v.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}});E=E&&I.length===v.size&&I.every(A=>v.has(A))&&!y&&u===void 0,g.lastCandidateScanUnchanged=E,j&&!y&&u===void 0&&(g.lastCandidateKeys=Object.freeze(N));}y&&l.push({source:"apps",root:e,name:"",relativePath:"apps",diagnostic:ht("DISCOVERY_TIME_LIMIT","apps","apps")});let H=ul(l,o,b);return Al(l,u,a.indexHash,b,o.productBundle!==void 0,H)}var Hp,Ui,zr,$p,Xr,il,Yr,us=F(()=>{m();Ge();Fn();Oe();ui();li();$e();lt();Or();st();it();wr();Si();ot();Ci();Ci();Hp=mt([]),Ui="crewx_local_app_";zr=["bundled","apps","skills"],$p=new TextDecoder("utf-8",{fatal:true});Xr=["","/ui"],il=["/dist"],Yr=2000000000n;});m();ui();m();Jt();m();var $o="SKILL.md",Md=/^---\s*\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;function Go(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function Od(e){return e.isDirectory()||e.isSymbolicLink()}function Yo(e){try{return existsSync(e)&&statSync(e).isDirectory()}catch{return false}}function fi(e){let n;try{n=readFileSync(e,"utf8");}catch{return {frontmatter:{},readable:false,valid:false,hasFrontmatter:false}}let t=n.match(Md);if(!t)return {frontmatter:{},readable:true,valid:true,hasFrontmatter:false};try{let i=load(t[1]??"");if(!Go(i))return {frontmatter:{},readable:!0,valid:!1,hasFrontmatter:!0};let o=Go(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 Ld(e){return [join(e,$o),join(e,"skill",$o)]}function Jo(e,n){if(!Yo(e))return null;for(let t of Ld(e)){if(!existsSync(t))continue;let o=fi(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 Wo(e){try{return readdirSync(e,{withFileTypes:!0}).filter(Od)}catch{return []}}function Ko(e,n,t){!e||n.has(e.name)||(n.add(e.name),t.push(e));}function qo(e){let n=[],t=new Set;for(let i of e)if(Yo(i))for(let o of Wo(i)){if(o.name.startsWith("@")){let r=join(i,o.name);for(let s of Wo(r))Ko(Jo(join(r,s.name),s.name),t,n);continue}Ko(Jo(join(i,o.name),o.name),t,n);}return n.sort((i,o)=>i.name.localeCompare(o.name))}m();nt();var Rd=/^[A-Za-z0-9_$.[\]"-]{0,200}$/,wd=/^[a-z][a-z0-9-]{0,63}$/,Cd="<unknown>";function Ud(e){return typeof e=="string"&&(ee.includes(e)||e===G)}function Zo(e){if(typeof e!="object"||e===null)return;let{file:n,path:t,rule:i}=e;if(!(typeof i!="string"||!wd.test(i)))return {...Ud(n)?{file:n}:{},path:typeof t=="string"&&Rd.test(t)?t:Cd,rule:i}}function Qo(e){if(!Array.isArray(e))return;let n=ee.filter(t=>e.includes(t));return n.length>0?n:void 0}us();var hl=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/;function Pt(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?_l(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 _l(e,n){let t=new TextEncoder().encode(bt(e)),i=El(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 El(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 bt(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 Et(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:bt(t)}function Tl(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 Is(e){return Object.freeze({packageRoot:e})}function Pl(e){return Object.freeze({id:e.definition.id,version:e.definition.version,hash:e.definition.hash,usage:e.definition.usage??je,...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 gs(e){return {capabilities:Object.freeze([...e]),origin:"local",ownership:"unknown",shareability:"unknown",sharingAvailability:"unavailable"}}function bl(e,n){let t=e.candidate,i=t.provenance!==void 0,o=n&&!i?["screen","skill"]:["screen"],r=Pl(t),s=Pt(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,...gs(o),definition:r,...n===void 0||i?{}:{skillName:n.skill.name},...i?{provenance:t.provenance}:{localDefinitionRef:Is(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 Nl(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},...gs(["skill"]),skillName:e.skill.name,localDefinitionRef:Is(e.packageRoot),definitionHash:Pt({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 Q(e,n,t,i,o){let r=Zo(o?.reason),s=Qo(o?.files);return Object.freeze({code:e,source:n,relativePath:Sl(t),...i===void 0?{}:{appId:i},...r===void 0?{}:{reason:r},...s===void 0?{}:{files:s}})}function Sl(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 ms(e){return Q(e.code,e.source,e.relativePath,e.pluginId,e)}function Ml(e,n){let t=As(e,n.dir);if(!t)return {diagnostic:Q("PATH_ESCAPED","node_modules","node_modules")};let i=Tl(t);if(!i)return {diagnostic:Q("PATH_ESCAPED","node_modules",t)};let o=fi(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=Ol(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:Pt({relativePath:r,fileBytes:s}),source:i}}catch{return {diagnostic:Q("SKILL_READ_FAILED",i,t)}}}function Ol(e,n){let t=relative(e,n).split(sep).join("/");try{return bt(t)}catch{return null}}function Ll(e){if(!hl.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??je,...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 Rl(e){return e.builtinCatalog}function wl(e){let n=e.packageRoot??e.relativePath??e.packageRootPath;if(n===void 0)return null;try{return bt(n)}catch{return null}}function Cl(e){let n=e.marketplaceContentId;return typeof n=="string"&&n.length>0?n:void 0}function Ul(e,n,t){let i=n.installed??[],o=new Map;for(let s of i){let a=wl(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=Cl(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 kl(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,Tt(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,Tt(a),a.appId));if(s.length>1)for(let a of s)i.add(a),n.push(Q("DUPLICATE_ID",a.source,Tt(a),a.appId));continue}for(let s of o)i.add(s),n.push(Q("DUPLICATE_ID",s.source,Tt(s),s.appId));}return e.filter(o=>!i.has(o))}function Tt(e){return e.packageRoot??e.summary.provenance?.packageDir??`builtin/${e.appId}`}function xl(e,n){return e.filter(t=>!(t.code==="MANIFEST_MISSING"&&n.has(t.relativePath))).map(ms)}function vl(e){return e.filesystem}function jl(e,n){let t=vl(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 hs(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=Rl(n),i=await ls(e,jl(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 qo([A])){let T=As(e,h.dir);(T===null||!d.has(T))&&(c.push(h),T!==null&&d.add(T));}for(let A of c){let h=Ml(e,A);"diagnostic"in h?s.push(h.diagnostic):a.push(h);}let l=new Map,p=n.registeredProductBundle?.indexHash,u=(n.registeredProductBundle?.candidates??[]).filter(A=>p!==void 0&&A.provenance?.indexHash===p),y=[...new Set([...i.apps??i.candidates??[],...i.productBundleSnapshotMetadata?.candidates??[]]),...u],g=new Set(u),_=new Set(p===void 0?[]:(t?.listMcpApps()??[]).filter(A=>A.provenance?.indexHash===p).map(A=>A.appId));for(let A of y){if(g.has(A)&&A.provenance?.indexHash===p&&_.has(A.appId))continue;let h=A.provenance===void 0?`workspace\0${A.relativePath}`:`bundled\0${A.provenance.indexHash}\0${A.provenance.packageDir}`;l.set(h,{candidate:A,packageRoot:A.relativePath});}let E=new Map(a.map(A=>[A.packageRoot,A])),v=[];for(let A of l.values()){let h=A.candidate.provenance===void 0?E.get(A.packageRoot):void 0,T=bl(A,h);v.push({...T.packageRoot===void 0?{}:{packageRoot:T.packageRoot},source:T.source,appId:T.appId,summary:T.summary});}let j=new Set([...l.values()].filter(A=>A.candidate.provenance===void 0).map(A=>A.packageRoot)),b=o===void 0?new Set:new Set(i.diagnostics.filter(A=>A.code==="RESERVED_ID"&&A.source!=="bundled").map(A=>A.relativePath)),U=new Set(o?.reservedAppIds??[]);for(let A of a){let h=Nl(A);if(!(j.has(A.packageRoot)||b.has(A.packageRoot))){if(U.has(h.appId)){s.push(Q("RESERVED_ID",A.source,A.packageRoot,h.appId));continue}v.push({packageRoot:h.packageRoot,source:h.source,appId:h.appId,summary:h.summary});}}let H=[...xl(i.diagnostics,new Set(a.map(A=>A.packageRoot))),...s,...n.registeredProductBundle?.diagnostics.filter(A=>A.source==="bundled").map(ms)??[]],N=[];if(t)for(let A of t.listMcpApps()){let h=Ll(A);"diagnostic"in h?H.push(h.diagnostic):N.push(h);}let D=kl([...v,...N],H);Ul(D,n,H);let O=D.map(A=>A.summary).sort((A,h)=>Et(A.appId,h.appId)),I=[...H].sort((A,h)=>Et(A.relativePath,h.relativePath)||Et(A.code,h.code)||Et(A.appId??"",h.appId??""));return Object.freeze({items:Object.freeze(O),diagnostics:Object.freeze(I)})}m();m();m();function Fl(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 Fl(n).test(e)}catch{return false}}function Nt(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 Vl(e,n){return e.split("/").some(t=>fn(t,n))}var _s=[{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&&Nt(n,".crewx","threads")},{label:".crewx/crewx.db",test:(e,n,t)=>!t&&Nt(n,".crewx","crewx.db")},{label:".crewx/*.log",test:(e,n,t)=>!t&&Nt(n,".crewx","*.log")},{label:".crewx/publish/",test:(e,n,t)=>t&&Nt(n,".crewx","publish")},{label:".crewx/",test:(e,n)=>Vl(n,".crewx")}];function yn(e,n,t){for(let i of _s)if(i.test(e,n,t))return i.label;return null}m();var ke=class extends Error{constructor(t,i){super(`publish: [${t}]${i?` ${i}`:""}`);this.code=t;}code;name="PublishError"};function P(e,n){return new ke(e,n)}function Es(e,n){if(!n||/[\\\u0000]/.test(n)||de.posix.isAbsolute(n)||n.split("/").some(y=>!y||y==="."||y===".."))throw P("PACKAGE_PATH_TRAVERSAL","package root must be a safe workspace-relative path");let t=de.resolve(e),i=de.resolve(t,...n.split("/"));if(!i.startsWith(`${t}${de.sep}`))throw P("PACKAGE_PATH_TRAVERSAL","package root escaped the workspace");function o(y,g){let _;try{_=te.lstatSync(y);}catch{throw P("PACKAGE_FILE_INVALID",`package directory is missing: ${g}`)}if(_.isSymbolicLink())throw P("PACKAGE_SYMLINK",`symlink is not publishable: ${g}`);if(!_.isDirectory())throw P("PACKAGE_FILE_INVALID",`not a package directory: ${g}`)}o(t,".");let r=t,s="",a=null;for(let y of n.split("/"))r=de.join(r,y),s=s?`${s}/${y}`:y,o(r,s),a??=yn(y,s,true);let c=[],d=[];function l(y,g){o(y,g);let _=te.readdirSync(y,{withFileTypes:true});for(let E of _){let v=`${g}/${E.name}`,j=de.join(y,E.name);if(E.isSymbolicLink())throw P("PACKAGE_SYMLINK",`symlink is not publishable: ${v}`);let b=yn(E.name,v,E.isDirectory());b?d.push({path:v,rule:b}):E.isDirectory()?l(j,v):E.isFile()&&c.push(v);}}a?d.push({path:n,rule:a}):l(i,n);let p=new TextEncoder,u=(y,g)=>Buffer.compare(p.encode(y),p.encode(g));return c.sort(u),d.sort((y,g)=>u(y.path,g.path)),{included:c,excluded:d}}function Ts(e){let n=[],t=[];function i(o,r,s){let a;try{a=te.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=te.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 Bl=[{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 Hl(e){return e.includes(0)}function Vi(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?te.readFileSync(r):Buffer.from(c);}catch{continue}if(Hl(s))continue;s.toString("utf8").split(/\r\n|\r|\n/).forEach((c,d)=>{for(let{rule:l,regex:p}of Bl)p.test(c)&&i.push({path:o,line:d+1,rule:l});});}return i}m();var Ns=/^[a-z0-9-]+$/,zl=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/,$l=/^[A-Za-z_][A-Za-z0-9_]*$/;function Gl(e){let n=de.join(e,"crewx.yaml");if(!te.existsSync(n))return {};let t;try{t=Ds.load(te.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 Jl(e){return Bi.createHash("sha256").update(e).digest("hex")}function Ss(e){let n;try{n=te.lstatSync(e);}catch{throw P("PACKAGE_FILE_INVALID",`file is not readable: ${de.basename(e)}`)}if(n.isSymbolicLink())throw P("PACKAGE_SYMLINK","symlink content is not publishable");if(!n.isFile())throw P("PACKAGE_FILE_INVALID","only regular files are publishable");return Bi.createHash("sha256").update(new Uint8Array(te.readFileSync(e))).digest("hex")}function Wl(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 Ms(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 P("PACKAGE_PATH_TRAVERSAL","manifest file path must be a non-empty POSIX relative path")}function Kl(e){if(!/^(?:apps|skills)\/[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(e))throw P("APP_PACKAGE_ROOT_INVALID","packageRoot must be apps/<safe-id> or skills/<safe-id>")}function Os(e){if(!zl.test(e))throw new Error(`publish: invalid version "${e}" \u2014 must be semver (e.g. 1.0.0)`)}function Ls(e,n,t={}){let i=Gl(e),o=i.name??de.basename(e);if(!Ns.test(o))throw new Error(`publish: invalid name "${o}" \u2014 must match ${Ns} (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");Os(r);let s=Array.isArray(i.requiredEnv)?i.requiredEnv:[],a=[];for(let l of s){if(typeof l!="string"||!$l.test(l))throw new Error(`publish: requiredEnv must contain names only (no values), got "${String(l)}"`);a.push(l);}let c=n.map(l=>(Ms(l),{path:l,sha256:Ss(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 Xl(e){let n=e.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"");if(!n)throw P("APP_PACKAGE_ROOT_INVALID","appId cannot produce a marketplace name");return n}function Rs(e,n){if(Kl(n.packageRoot),!n.version)throw new Error("publish: version is required for App publishing \u2014 pass opts.version");if(Os(n.version),typeof n.description!="string")throw new Error("publish: App description must be a string");let t=[...new Set(n.capabilities)].sort();if(t.length===0||t.some(s=>s!=="screen"&&s!=="skill"))throw new Error("publish: App capabilities must contain screen or skill");let i=`${n.packageRoot}/`;if(t.includes("screen")){if(typeof n.definitionId!="string"||n.definitionId.length===0)throw P("APP_UI_MANIFEST_INVALID","screen App manifests require definitionId");let s=n.includedFiles.includes(`${i}manifest.json`),a=n.includedFiles.includes(`${i}ui-plugin.json`);if(!s&&!a)throw P("APP_UI_MANIFEST_INVALID","screen App is missing manifest.json or ui-plugin.json");if(s&&!a)throw P("APP_UI_MANIFEST_INVALID","a manifest.json App must also ship a generated ui-plugin.json");if(!n.includedFiles.includes(`${i}ui/index.html`))throw P("APP_UI_MANIFEST_INVALID","screen App is missing ui/index.html")}if(t.includes("skill")&&!n.includedFiles.includes(`${i}SKILL.md`))throw P("APP_SKILL_MISSING","skill capability requires package-root SKILL.md");let o=new Set,r=n.includedFiles.map(s=>{if(Ms(s),!s.startsWith(i))throw P("PACKAGE_PATH_TRAVERSAL","App manifest file is outside packageRoot");let a=n.generatedFiles?.get(s);return a!==void 0&&o.add(s),{path:s,sha256:a===void 0?Ss(de.join(e,s)):Jl(a),...a===void 0?{}:{generated:true}}}).sort((s,a)=>Wl(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:Xl(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 ws(e){return Bi.createHash("sha256").update(e).digest("hex")}function vs(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 P("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 P("PACKAGE_PATH_TRAVERSAL","archive path escaped its root");return i}function Cs(e,n){let t=vs(e,n),i;try{i=te.lstatSync(t);}catch{throw P("PACKAGE_FILE_INVALID","manifest file is missing")}if(i.isSymbolicLink())throw P("PACKAGE_SYMLINK","symlink content is not publishable");if(!i.isFile())throw P("PACKAGE_FILE_INVALID","only regular files are publishable");return new Uint8Array(te.readFileSync(t))}async function js(e,n,t={}){let i=de.join(e,".crewx","publish");te.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=te.mkdtempSync(de.join(Us.tmpdir(),"crewx-publish-"));try{let a=new Set,c=[];for(let d of n.files){if(a.has(d.path))throw P("PACKAGE_PATH_TRAVERSAL","manifest contains duplicate file paths");a.add(d.path);let l=t.generatedFiles?.get(d.path);if(d.generated===!0&&l===void 0)throw P("PACKAGE_GENERATED_FILE_MISSING","generated manifest file bytes are missing");if(t.sourceFileHashes?.has(d.path)){let y=Cs(e,d.path);if(t.sourceFileHashes.get(d.path)!==ws(y))throw P("PACKAGE_STAGED_BYTES_MISMATCH","workspace source changed before staging")}let p=l??Cs(e,d.path);if(ws(p)!==d.sha256)throw P("PACKAGE_STAGED_BYTES_MISMATCH",`staged bytes differ for ${d.path}`);let u=vs(s,d.path);te.mkdirSync(de.dirname(u),{recursive:!0}),te.writeFileSync(u,new Uint8Array(p)),c.push(d.path);}te.writeFileSync(de.join(s,"manifest.json"),JSON.stringify(n,null,2)),await xs.create({gzip:!0,file:r,cwd:s,portable:!0,noMtime:!0},["manifest.json",...c]),te.renameSync(r,o);}finally{try{te.rmSync(r,{force:!0});}catch{}te.rmSync(s,{recursive:true,force:true});}return o}m();m();var An="/api/v1";var Zl=201,Ql=200,eu=409,Hi=401,Fs={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 nu(){return process.env.WI013_FAKE_UPLOAD==="1"}function tu(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 iu(e){return e.replace(/\/+$/,"")}async function jn(e){try{return await e.json()}catch{return null}}function Vs(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 ou(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 ru(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 Bs(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(Fs,r))continue;let s=r,a=s==="APP_NAME_CONFLICT"?`marketplace name is already in use: ${n}`:void 0;return P(Fs[s],a)}}async function su(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=iu(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 jn(a),d=ou(c),l=ru(c),p=r&&l!==void 0?l:i,u;if(a.status===Zl)u="created";else if(r&&a.status===Ql){if(d===void 0)throw P("PUBLISH_CONTENT_ID_MISSING","App republish did not return an opaque contentId");u="existing";}else if(a.status===eu){if(r)throw Bs(c,i)??P("APP_NAME_CONFLICT",`marketplace name is already in use: ${i}`);u="existing";}else throw a.status===Hi?new Error("publish: [E_AUTH_EXPIRED] Authentication is expired or missing \u2014 please log in again (HTTP 401)"):new Error(`publish: [E_HTTP] Submit request failed \u2014 HTTP ${a.status}`);let y="not-needed",g=null;if(u==="existing"&&!r){let D;try{D=await fetch(`${n}${An}/publisher/items`,{method:"GET",headers:{Authorization:`Bearer ${e.accessToken}`}});}catch{throw new Error("publish: [E_NETWORK] Publisher items request failed (network)")}let O=await jn(D);if(D.status!==200)throw new Error(`publish: [E_HTTP] Publisher items request failed \u2014 HTTP ${D.status}`);let A=Vs(O,"publisher items",D.status)?.items;if(!Array.isArray(A))throw new Error(`publish: [E_MALFORMED] Publisher items response is malformed (expected data.items[]) \u2014 HTTP ${D.status}`);let h=A.find(T=>!T||typeof T!="object"?false:T.slug===i);if(!h||typeof h.version!="string")throw new Error(`publish: [E_MALFORMED] Publisher items response does not contain slug "${i}" \u2014 HTTP ${D.status}`);if(g=h.version,g!==e.manifest.version){let T;try{T=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(!T.ok)throw await jn(T),T.status===Hi?new Error(`publish: [E_AUTH_EXPIRED] Authentication is expired or missing \u2014 please log in again (HTTP ${T.status})`):T.status===403?new Error(`publish: [E_FORBIDDEN] Version update is forbidden; only the item owner can update an existing item (HTTP ${T.status})`):new Error(`publish: [E_HTTP] Version update failed \u2014 HTTP ${T.status}`);y="applied";}}let _=te.readFileSync(e.tgzPath),E=nu()?tu(_):_,v=new FormData;v.set("archive",new Blob([new Uint8Array(E)],{type:"application/gzip"}),`${p}-${e.manifest.version}.tgz`);let j=r&&d!==void 0?d:i,b;try{b=await fetch(`${n}${An}/publisher/items/${encodeURIComponent(j)}/upload`,{method:"POST",headers:{Authorization:`Bearer ${e.accessToken}`},body:v});}catch{throw new Error("publish: [E_NETWORK] Upload request failed (network)")}if(b.status===Hi)throw new Error("publish: [E_AUTH_EXPIRED] Authentication is expired or missing \u2014 please log in again (HTTP 401)");if(!b.ok){let D=await jn(b);if(r){let O=Bs(D,p);if(O)throw O}throw new Error(`publish: [E_HTTP] Upload request failed \u2014 HTTP ${b.status}`)}let U=await jn(b),H=Vs(U,"upload",b.status),N=typeof H.contentId=="string"&&H.contentId.length>0?H.contentId:d;if(r&&N===void 0)throw P("PUBLISH_CONTENT_ID_MISSING","App upload did not return an opaque contentId");return {slug:p,version:e.manifest.version,...N===void 0?{}:{contentId:N},artifactChecksum:H.artifactChecksum,artifactSizeBytes:H.artifactSizeBytes,submitOutcome:u,versionUpdate:y,serverVersionBefore:g}}var au=1e4,cu=100*1024*1024;function zi(e){return Bi.createHash("sha256").update(e).digest("hex")}function du(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function ze(e,n){if(!n||n.includes("\\")||n.includes("\0")||de.posix.isAbsolute(n)||n.split("/").some(r=>r===".."||r.length===0))throw P("PACKAGE_PATH_TRAVERSAL","workspace file path is not a safe relative path");let t=de.resolve(e,...n.split("/")),i=de.resolve(e);if(t!==i&&!t.startsWith(`${i}${de.sep}`))throw P("PACKAGE_PATH_TRAVERSAL","workspace file path escaped the workspace root");let o;try{o=te.lstatSync(t);}catch{throw P("PACKAGE_FILE_INVALID",`workspace file is missing: ${n}`)}if(o.isSymbolicLink())throw P("PACKAGE_SYMLINK",`symlink is not publishable: ${n}`);if(!o.isFile())throw P("PACKAGE_FILE_INVALID",`not a regular file: ${n}`);return new Uint8Array(te.readFileSync(t))}async function pu(e,n,t){let i=`${n}/${K}`;if(!t.includes(i))return [];let o={[K]:ze(e,i)},r=`${n}/${G}`;t.includes(r)&&(o[G]=ze(e,r));let s=Be(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)?ze(e,l):"missing"}),c=a.find(d=>d.code==="ICON_INVALID");if(c!==void 0)throw P("ICON_INVALID",`${c.reason??"invalid"} at ${c.declared??"icon"}`);return a.flatMap(d=>d.code==="ICON_INVALID"?[]:[{code:d.code,path:d.declared??"icon"}])}function zs(e,n,t){let i=e??n;if(!Number.isSafeInteger(i)||i<=0)throw new ke("PACKAGE_SIZE_LIMIT",`${t} must be a positive integer`);return i}function Gs(e,n,t,i){let o=zs(t.maxFileCount??t.maxFiles,au,"max file count"),r=zs(t.maxTotalBytes??t.maxBytes,cu,"max total bytes");if(n.length>o)throw new ke("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+=ze(e,a).byteLength,s>r)throw new ke("PACKAGE_SIZE_LIMIT",`package exceeds byte limit (${r})`)}}function lu(e){return e.appId!==void 0||e.expectedDefinitionHash!==void 0}function uu(e){let n=e.appId!==void 0,t=e.expectedDefinitionHash!==void 0;if(!n&&t)throw P("APP_ID_REQUIRED","appId is required with expectedDefinitionHash");if(n&&!t)throw P("APP_DEFINITION_HASH_REQUIRED","expectedDefinitionHash is required with appId");if(!n||!t)throw P("APP_ID_REQUIRED")}function fu(e,n){let t=e.filter(i=>i.appId===n);if(t.length===0)throw P("APP_NOT_FOUND",`no publishable App matches ${n}`);if(t.length!==1)throw P("APP_AMBIGUOUS",`more than one App matches ${n}`);return t[0]}function yu(e){let n=e.localDefinitionRef?.packageRoot;if(!n||!/^(?:apps|skills)\/[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(n))throw P("APP_PACKAGE_ROOT_INVALID","selected App is not rooted in apps/<safe-id> or skills/<safe-id>");return n}function $i(e){let{path:n,rule:t}=e.reason;return `${e.code} at ${n===""?"<file>":n} (${t})`+(e.files.length>0?` [${e.files.join(", ")}]`:"")}function Au(e,n,t){let i=Be({[pe]:t},{mode:"published"});if(!i.ok)throw P("APP_UI_MANIFEST_INVALID",`generated ${pe} does not read: ${$i(i.rejection)}`);if(cn(i.manifest)!==cn(n))throw P("APP_UI_MANIFEST_INVALID",`generated ${pe} normalizes to a different definition hash than the source`);let o=e[K];if(o===void 0)return;let r=e[G],s=Be({[K]:o,[pe]:t,...r===void 0?{}:{[G]:r}},{mode:"local"});if(!s.ok)throw P("APP_UI_MANIFEST_INVALID",$i(s.rejection))}function Iu(e,n,t,i){let o={};for(let y of ee){let g=`${t}/${y}`;i.includes(g)&&(o[y]=ze(e,g));}let r=`${t}/${G}`;if(o[K]!==void 0&&i.includes(r)&&(o[G]=ze(e,r)),Object.keys(o).length===0)throw P("APP_UI_MANIFEST_INVALID","selected screen App has no package manifest.json or ui-plugin.json");let s=Be(o,{mode:"local"});if(!s.ok)throw P("APP_UI_MANIFEST_INVALID",$i(s.rejection));if(s.manifest.pluginId!==n.appId)throw P("APP_DEFINITION_CONFLICT",`${s.file} identity no longer matches the selected App`);let a=o[pe],c=a===void 0?void 0:zi(a),d=`${t}/ui/index.html`;if(!i.includes(d))throw P("APP_UI_MANIFEST_INVALID","screen entry is outside package scope");let l=zi(ze(e,d)),p=JSON.parse(JSON.stringify(s.v2Input));if(p.entryHash=l,Object.prototype.hasOwnProperty.call(p,"initialState")){let y=p.initialState;if(!du(y)||y.path!=="ui/state.json")throw P("APP_INITIAL_STATE_OUT_OF_SCOPE","initialState must reference ui/state.json inside the package");let g=`${t}/ui/state.json`;if(!i.includes(g))throw P("APP_INITIAL_STATE_OUT_OF_SCOPE","initialState reference is outside the selected package");let _=ze(e,g);p.initialState={...y,hash:zi(_)};}let u;try{let y=We(p,{mode:"published"});u=new Uint8Array(Buffer.from(JSON.stringify(y),"utf8"));}catch(y){throw y instanceof ce?P("APP_UI_MANIFEST_INVALID",y.code):P("APP_UI_MANIFEST_INVALID")}return Au(o,s.manifest,u),{bytes:u,...c===void 0?{}:{legacySourceHash:c}}}async function gu(e,n){let{included:t,excluded:i}=Ts(e);Gs(e,t,n);let o=Ls(e,t,{version:n.version}),r=Vi(e,t);return {plan:{manifest:o,included:t,excluded:i,secretFindings:r},archiveOptions:{}}}async function mu(e,n){uu(n);let t=await hs(e),i=fu(t.items,n.appId);if(i.definitionHash!==n.expectedDefinitionHash)throw P("APP_DEFINITION_CONFLICT",`definitionHash changed for ${n.appId}`);let o=yu(i),{included:r,excluded:s}=Es(e,o),a=await pu(e,o,r),c=new Map,d=new Map;if(i.capabilities.includes("screen")){let y=Iu(e,i,o,r),g=`${o}/${pe}`;if(c.set(g,y.bytes),y.legacySourceHash!==void 0)d.set(g,y.legacySourceHash);else {r.push(g);let _=new TextEncoder;r.sort((E,v)=>Buffer.compare(_.encode(E),_.encode(v)));}}if(i.capabilities.includes("skill")&&!r.includes(`${o}/SKILL.md`))throw P("APP_SKILL_MISSING","skill capability requires package-root SKILL.md");Gs(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=Rs(e,l),u=Vi(e,r,c);return {plan:{manifest:p,included:r,excluded:s,secretFindings:u,warnings:a},archiveOptions:{generatedFiles:c,sourceFileHashes:d}}}async function Js(e,n){let t=de.resolve(e);if(lu(n))return mu(t,n);if(n.expectedDefinitionHash!==void 0)throw P("APP_ID_REQUIRED");return gu(t,n)}async function BI(e,n={}){return (await Js(e,n)).plan}function hu(e){let n=e.map(t=>`${t.path}:${t.line} (${t.rule})`).join(", ");throw new ke("PUBLISH_SECRET_FINDINGS",`aborted \u2014 secret findings must be resolved before packing: ${n}`)}async function Ws(e,n={}){let t=de.resolve(e),i=await Js(t,n);i.plan.secretFindings.length>0&&hu(i.plan.secretFindings);let o=await js(t,i.plan.manifest,i.archiveOptions);return {manifest:i.plan.manifest,tgzPath:o}}async function HI(e,n={}){return Ws(e,n)}async function zI(e,n){let t=await Ws(e,n);if(t.manifest.type!=="app")throw new Error("publish: App pack unexpectedly produced a template manifest");return t}
2
+ export{cu as DEFAULT_PUBLISH_MAX_BYTES,au as DEFAULT_PUBLISH_MAX_FILES,_s as EXCLUDE_RULES,An as MARKETPLACE_API_PREFIX,ke as PublishError,zI as packApp,Ws as packPublish,HI as packTemplate,BI as planPublish,su as uploadToMarketplace};