@crewx/sdk 0.9.0-rc.119 → 0.9.0-rc.120

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.
@@ -13,7 +13,7 @@ ${r.join(`
13
13
  `).filter(r=>r.trim());return n.length===0?false:n.every(r=>vu(r,e))}function _e(t){return typeof t=="object"&&t!==null}function ci(t,e){if(e==="assistant"||e==="user"){let n=t.message;return _e(n)&&Array.isArray(n.content)}return e==="system"?typeof t.subtype=="string"||typeof t.session_id=="string":e==="result"?typeof t.result=="string"||_e(t.usage)||typeof t.total_cost_usd=="number"||typeof t.is_error=="boolean":e==="rate_limit_event"?_e(t.rate_limit_info):e==="tool_progress"?t.heartbeat===true&&typeof t.tool_use_id=="string":false}function xu(t,e){return typeof t.session_id=="string"||typeof t.uuid=="string"?true:ci(t,e)}function Cu(t,e){if(e==="error")return typeof t.message=="string"||typeof t.errorMessage=="string"||typeof t.error=="string"||_e(t.error);if(e==="item.updated"||e.startsWith("thread.")||e.startsWith("turn."))return true;if(e==="item.started"||e==="item.completed"){let n=t.item;return _e(n)&&typeof n.type=="string"}return false}function Nu(t,e){return e==="step_start"||e==="step_finish"?typeof t.stepID=="string"||typeof t.sessionID=="string"||_e(t.part):e==="text"||e==="tool_use"?_e(t.part):e==="result"?typeof t.result=="string":false}function Pu(t,e){return !!(typeof t.stepID=="string"||typeof t.sessionID=="string"||_e(t.part)||e==="result"&&typeof t.result=="string")}function Du(t,e){return e.startsWith("assistant.")||e.startsWith("tool.execution")||e==="user.message"?_e(t.data):e==="result"?typeof t.result=="string":false}function Lu(t,e){return e==="message"?typeof t.role=="string":e==="tool_use"?typeof t.tool_name=="string"||typeof t.tool_id=="string":e==="tool_result"?typeof t.tool_id=="string"||typeof t.status=="string":false}function Mu(t,e){return e==="available_commands"?_e(t.tools)||_e(t.commands):e==="usage"?_e(t.usage):e==="end"?typeof t.sessionId=="string"||typeof t.stopReason=="string"||_e(t.usage):e==="tool_call_update"?typeof t.toolCallId=="string"||typeof t.status=="string":false}var li,Hu,xt=v(()=>{_();Kr();li={claude:ci,codex:Cu,opencode:Nu,copilot:Du,gemini:Lu},Hu={...li,claude:xu,opencode:Pu,grok:Mu,antigravity:()=>false};});function Be(t){return /crewx\s+(q|query|x|execute)\s/.test(t)}function We(t,e,n){let r=e.match(/@(\S+)/);return {timestamp:t,type:"agent_call",targetAgent:r?.[1]?.replace(/["']/g,""),toolInput:e,...typeof n=="string"&&n.length>0?{toolUseId:n}:{}}}var Ct=v(()=>{_();});function Fu(t){let e=qu(t),n=e.map((o,i)=>({line:o,index:i})).filter(({line:o})=>Wu(o.value)),r=Bu(e);return {result:n.length===1&&n[0].index===r?ju(n[0].line.value):null,resultPreview:Ku(e,n),hasReservedLine:n.length>0}}function ze(t,e){let n=Fu(t);return {resultPreview:n.resultPreview,isError:e||n.result?.isError===true,...n.hasReservedLine?{delegationResult:n.result}:{}}}function qu(t){let e=[],n=0;for(let r=0;r<t.length;r++){let s=t[r];if(s!==`
14
14
  `&&s!=="\r")continue;let o=s==="\r"&&t[r+1]===`
15
15
  `?`\r
16
- `:s;e.push({value:t.slice(n,r),separator:o}),r+=o.length-1,n=r+1;}return e.push({value:t.slice(n),separator:""}),e}function Bu(t){for(let e=t.length-1;e>=0;e--)if(t[e].value.trim())return e;return -1}function Wu(t){return t.trimStart().startsWith($u)}function ju(t){let e=t.trim();if(!e.startsWith(pi)||!e.endsWith("]]"))return null;let n=e.slice(pi.length,-2);if(!n)return null;try{return Gu(JSON.parse(n))}catch{return null}}function Gu(t){return zu(t)?Object.prototype.hasOwnProperty.call(t,"taskId")?{schema:1,taskId:t.taskId,agentId:t.agentId,isError:t.isError}:{schema:1,isError:true}:null}function zu(t){if(!Vu(t)||Object.keys(t).some(r=>!Uu.has(r))||t.schema!==1||typeof t.isError!="boolean")return false;let e=Object.prototype.hasOwnProperty.call(t,"taskId"),n=Object.prototype.hasOwnProperty.call(t,"agentId");return e!==n?false:e?fi(t.taskId)&&fi(t.agentId):t.isError===true}function Ku(t,e){if(e.length===0)return t.map(r=>r.value+r.separator).join("");let n=new Set(e.map(({index:r})=>r));return t.map((r,s)=>n.has(s)?"":r.value+r.separator).join("")}function fi(t){return typeof t=="string"&&t.trim().length>0}function Vu(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var pi,$u,Uu,tn=v(()=>{_();pi="[[crewx:delegation-result ",$u="[[crewx:delegation-result",Uu=new Set(["schema","taskId","agentId","isError"]);});function be(t){if(typeof t=="string")return t;if(!t||typeof t!="object")return JSON.stringify(t??{});let e=t;return typeof e.command=="string"?e.command:typeof e.file_path=="string"?e.file_path:typeof e.filePath=="string"?e.filePath:typeof e.path=="string"?e.path:typeof e.query=="string"?e.query:typeof e.pattern=="string"?e.pattern:typeof e.url=="string"?e.url:typeof e.prompt=="string"?e.prompt.length>200?e.prompt.slice(0,200)+"\u2026":e.prompt:typeof e.description=="string"?e.description:JSON.stringify(e)}var Nt=v(()=>{_();});var gi,Yn,Vr,Xn=v(()=>{_();gi=["none","minimal","low","medium","high","xhigh","max","ultra"],Yn={claude:["low","medium","high","xhigh","max"],codex:["none","minimal","low","medium","high","xhigh","max","ultra"],opencode:[],copilot:["none","low","medium","high","xhigh","max"],antigravity:["low","medium","high"],grok:["low","medium","high","xhigh"]},Vr={claude:{models:[{id:"claude-fable-5-1",name:"Claude Fable 5.1",contextWindowTokens:1e6,tier:"flagship",recommended:true},{id:"claude-fable-5",name:"Claude Fable 5",contextWindowTokens:1e6,tier:"flagship"},{id:"claude-opus-5-5",name:"Claude Opus 5.5",contextWindowTokens:1e6,tier:"flagship",recommended:true},{id:"claude-opus-5",name:"Claude Opus 5",contextWindowTokens:1e6,tier:"flagship"},{id:"claude-sonnet-5",name:"Claude Sonnet 5",contextWindowTokens:1e6,tier:"balanced",recommended:true},{id:"claude-opus-4-8[1m]",name:"Claude Opus 4.8",contextWindowTokens:1e6,tier:"flagship"},{id:"claude-opus-4-7[1m]",name:"Claude Opus 4.7",contextWindowTokens:1e6,tier:"flagship"},{id:"claude-opus-4-6[1m]",name:"Claude Opus 4.6",contextWindowTokens:1e6,tier:"flagship"},{id:"claude-sonnet-4-6[1m]",name:"Claude Sonnet 4.6",contextWindowTokens:1e6,tier:"balanced"},{id:"claude-haiku-4-5",name:"Claude Haiku 4.5",contextWindowTokens:2e5,tier:"speed"}],modes:[{id:"default",name:"Default",description:"Uses Claude's default permission handling with normal approval prompts."},{id:"acceptEdits",name:"Accept Edits",description:"Allows file edits without approval; other permission checks remain in place."},{id:"plan",name:"Plan",description:"Keeps Claude in plan mode so it can inspect and propose changes without applying them."},{id:"dontAsk",name:"Don't Ask",description:"Does not ask for permissions; only pre-approved tool actions can proceed."},{id:"bypassPermissions",name:"Bypass Permissions",description:"Bypasses Claude permission checks so tools can run without approval prompts."}],effort:["low","medium","high"],modelOverrides:{"claude-fable-5-1":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-fable-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-5-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"medium"},"claude-opus-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-sonnet-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-4-8[1m]":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-4-7[1m]":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-4-6[1m]":{effort:["low","medium","high","max"],defaultEffort:"high"},"claude-sonnet-4-6[1m]":{effort:["low","medium","high","max"],defaultEffort:"high"},"claude-haiku-4-5":{effort:[]}},providerOptions:[]},codex:{models:[{id:"gpt-6-astra",name:"GPT-6 Astra",contextWindowTokens:105e4,tier:"flagship"},{id:"gpt-6-sol",name:"GPT-6 Sol",contextWindowTokens:105e4,tier:"balanced"},{id:"gpt-6-luna",name:"GPT-6 Luna",contextWindowTokens:105e4,tier:"speed"},{id:"gpt-5.6-sol",name:"GPT-5.6 Sol",contextWindowTokens:105e4,tier:"flagship",recommended:true},{id:"gpt-5.6-terra",name:"GPT-5.6 Terra",contextWindowTokens:105e4,tier:"balanced",recommended:true},{id:"gpt-5.6-luna",name:"GPT-5.6 Luna",contextWindowTokens:105e4,tier:"speed",recommended:true},{id:"gpt-5.5",name:"GPT-5.5",contextWindowTokens:105e4,tier:"flagship"},{id:"gpt-5.4",name:"GPT-5.4",contextWindowTokens:105e4,tier:"flagship"},{id:"gpt-5.4-mini",name:"GPT-5.4 Mini",contextWindowTokens:4e5,tier:"speed"},{id:"gpt-5.3-codex",name:"GPT-5.3 Codex",contextWindowTokens:4e5,tier:"flagship"},{id:"gpt-5.3-codex-spark",name:"GPT-5.3 Codex Spark",contextWindowTokens:128e3,tier:"speed"}],modes:[{id:"agent",name:"Agent",description:"Uses the workspace-write sandbox; can read and modify workspace files without full machine access."},{id:"read-only",name:"Read Only",description:"Uses the read-only sandbox; can inspect files but cannot write to the workspace."},{id:"plan",name:"Plan",description:"Uses the read-only sandbox for planning and inspection; cannot write to the workspace."},{id:"agent-full-access",name:"Agent Full Access",description:"Bypasses approvals and the sandbox; can access and modify files beyond the workspace."},{id:"yolo",name:"YOLO",description:"Bypasses approvals and the sandbox for unrestricted execution and full filesystem access."}],effort:["minimal","low","medium","high"],modelOverrides:{"gpt-6-astra":{effort:["low","medium","high","xhigh","max"],defaultEffort:"xhigh"},"gpt-6-sol":{effort:["none","low","medium","high","xhigh","max"],defaultEffort:"medium"},"gpt-6-luna":{effort:["none","low","medium","high","xhigh","max"],defaultEffort:"medium"},"gpt-5.6-sol":{effort:["low","medium","high","xhigh","max","ultra"],defaultEffort:"xhigh"},"gpt-5.6-terra":{effort:["low","medium","high","xhigh","max","ultra"],defaultEffort:"high"},"gpt-5.6-luna":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"gpt-5.5":{effort:["low","medium","high","xhigh"],defaultEffort:"high"}},providerOptions:[]},opencode:{models:[],modes:[{id:"plan",name:"Plan",description:"Uses the plan agent without --auto; planning follows standard approval behavior."},{id:"plan-auto",name:"Plan \xB7 Auto",description:"Uses the plan agent with --auto; planning uses automatic approvals."},{id:"build",name:"Build",description:"Uses the build agent without --auto; work follows standard approval behavior."},{id:"build-auto",name:"Build \xB7 Auto",description:"Uses the build agent with --auto; work uses automatic approvals."}],effort:[],modelOverrides:{},providerOptions:[]},copilot:{models:[{id:"auto",name:"Auto"},{id:"claude-sonnet-5",name:"Claude Sonnet 5",contextWindowTokens:1e6,tier:"balanced"},{id:"claude-sonnet-4-6",name:"Claude Sonnet 4.6",contextWindowTokens:1e6,tier:"balanced"},{id:"gpt-5.5",name:"GPT-5.5",contextWindowTokens:105e4,tier:"flagship"},{id:"gpt-5.4",name:"GPT-5.4",contextWindowTokens:105e4,tier:"flagship"},{id:"gemini-3.1-pro",name:"Gemini 3.1 Pro",contextWindowTokens:1048576,tier:"flagship"}],modes:[{id:"interactive",name:"Interactive",description:"Passes --mode interactive; tool access follows Copilot's interactive mode behavior."},{id:"plan",name:"Plan",description:"Passes --mode plan; planning and permission behavior follow Copilot's plan mode."},{id:"autopilot",name:"Autopilot",description:"Passes --mode autopilot; execution behavior follows Copilot's autonomous mode."}],effort:["none","low","medium","high","xhigh","max"],modelOverrides:{},providerOptions:[]},antigravity:{models:[{id:"gemini-3.7-flash",name:"Gemini 3.7 Flash",contextWindowTokens:1048576,tier:"balanced"},{id:"gemini-3.6-flash",name:"Gemini 3.6 Flash",contextWindowTokens:1048576,tier:"balanced"},{id:"gemini-3.5-flash",name:"Gemini 3.5 Flash",contextWindowTokens:1048576,tier:"balanced"},{id:"gemini-3.1-pro",name:"Gemini 3.1 Pro",contextWindowTokens:1048576,tier:"flagship"},{id:"claude-sonnet-4-6",name:"Claude Sonnet 4.6",contextWindowTokens:1e6,tier:"balanced"},{id:"claude-opus-4-6-thinking",name:"Claude Opus 4.6 Thinking",contextWindowTokens:1e6,tier:"flagship"},{id:"gpt-oss-120b",name:"GPT-OSS 120B",contextWindowTokens:128e3,tier:"balanced"}],modes:[{id:"default",name:"Default",description:"Uses Antigravity's default permission handling. No extra permission flags are passed."},{id:"plan",name:"Plan",description:"Passes --mode plan. This turns on /plan; it is not a Claude-style permission mode."},{id:"acceptEdits",name:"Accept Edits",description:"Passes --mode accept-edits."},{id:"bypassPermissions",name:"Bypass Permissions",description:"Passes --dangerously-skip-permissions so tools can run without approval prompts."}],effort:["low","medium","high"],modelOverrides:{"gemini-3.7-flash":{effort:["low","medium","high"],defaultEffort:"medium"},"gemini-3.6-flash":{effort:["low","medium","high"],defaultEffort:"medium"},"gemini-3.5-flash":{effort:["low","medium","high"],defaultEffort:"medium"},"gemini-3.1-pro":{effort:["low","high"],defaultEffort:"high"},"claude-sonnet-4-6":{effort:[]},"claude-opus-4-6-thinking":{effort:[]},"gpt-oss-120b":{effort:["medium"],defaultEffort:"medium"}},providerOptions:[]},grok:{models:[{id:"grok-4.7",name:"Grok 4.7",contextWindowTokens:5e5,tier:"flagship",recommended:true},{id:"grok-4.6",name:"Grok 4.6",contextWindowTokens:5e5,tier:"flagship"},{id:"grok-4.5",name:"Grok 4.5",contextWindowTokens:5e5,tier:"flagship"}],modes:[{id:"default",name:"Default",description:"Uses Grok's default permission handling."},{id:"acceptEdits",name:"Accept Edits",description:"Allows file edits without changing the selected sandbox profile."},{id:"auto",name:"Auto",description:"Uses Grok automatic permission handling."},{id:"dontAsk",name:"Don't Ask",description:"Does not ask for permission before tool execution."},{id:"bypassPermissions",name:"Bypass Permissions",description:"Bypasses Grok permission checks for tool execution."},{id:"plan",name:"Plan",description:"Keeps Grok in planning mode without applying changes."}],effort:["low","medium","high"],modelOverrides:{"grok-4.7":{effort:["low","medium","high","xhigh"],defaultEffort:"high"},"grok-4.6":{effort:["low","medium","high","xhigh"],defaultEffort:"high"},"grok-4.5":{effort:["low","medium","high"],defaultEffort:"high"}},providerOptions:[{key:"alwaysApprove",type:"boolean"},{key:"sandbox",type:"enum",values:["workspace","read-only","off"]}]}},Object.fromEntries(Object.entries(Vr).map(([t,e])=>[t,e.models]));});function Jr(t){return Yu[t]??t}function Qu(t){return Xu.get(t)??t}function Yr(t){if(!t)return {};let e=ec.get(t);return e?{...e}:{model:t}}function Xr(t,e){return t==="antigravity"||t==="cli/antigravity"?Yr(e):e===void 0?{}:{model:Qu(e)}}var Ju,Yu,Xu,Zu,ec,nn=v(()=>{_();Ju=[{baseModelId:"claude-opus-4-8",catalogModelId:"claude-opus-4-8[1m]"},{baseModelId:"claude-opus-4-7",catalogModelId:"claude-opus-4-7[1m]"},{baseModelId:"claude-opus-4-6",catalogModelId:"claude-opus-4-6[1m]"},{baseModelId:"claude-sonnet-4-6",catalogModelId:"claude-sonnet-4-6[1m]"}],Yu={"accept-edits":"acceptEdits",yolo:"bypassPermissions","agent-full-access":"bypassPermissions"};Xu=new Map(Ju.map(({baseModelId:t,catalogModelId:e})=>[t,e]));Zu=[{legacyId:"Gemini 3.7 Flash (High)",model:"gemini-3.7-flash",effort:"high"},{legacyId:"Gemini 3.7 Flash (Medium)",model:"gemini-3.7-flash",effort:"medium"},{legacyId:"Gemini 3.7 Flash (Low)",model:"gemini-3.7-flash",effort:"low"},{legacyId:"Gemini 3.6 Flash (High)",model:"gemini-3.6-flash",effort:"high"},{legacyId:"Gemini 3.6 Flash (Medium)",model:"gemini-3.6-flash",effort:"medium"},{legacyId:"Gemini 3.6 Flash (Low)",model:"gemini-3.6-flash",effort:"low"},{legacyId:"Gemini 3.5 Flash (Medium)",model:"gemini-3.5-flash",effort:"medium"},{legacyId:"Gemini 3.5 Flash (High)",model:"gemini-3.5-flash",effort:"high"},{legacyId:"Gemini 3.5 Flash (Low)",model:"gemini-3.5-flash",effort:"low"},{legacyId:"Gemini 3.1 Pro (Low)",model:"gemini-3.1-pro",effort:"low"},{legacyId:"Gemini 3.1 Pro (High)",model:"gemini-3.1-pro",effort:"high"},{legacyId:"Claude Sonnet 4.6 (Thinking)",model:"claude-sonnet-4-6"},{legacyId:"Claude Opus 4.6 (Thinking)",model:"claude-opus-4-6-thinking"},{legacyId:"GPT-OSS 120B (Medium)",model:"gpt-oss-120b",effort:"medium"},{legacyId:"gemini-3.7-flash-high",model:"gemini-3.7-flash",effort:"high"},{legacyId:"gemini-3.7-flash-medium",model:"gemini-3.7-flash",effort:"medium"},{legacyId:"gemini-3.7-flash-low",model:"gemini-3.7-flash",effort:"low"},{legacyId:"gemini-3.6-flash-high",model:"gemini-3.6-flash",effort:"high"},{legacyId:"gemini-3.6-flash-medium",model:"gemini-3.6-flash",effort:"medium"},{legacyId:"gemini-3.6-flash-low",model:"gemini-3.6-flash",effort:"low"},{legacyId:"gemini-3.5-flash-high",model:"gemini-3.5-flash",effort:"high"},{legacyId:"gemini-3.5-flash-medium",model:"gemini-3.5-flash",effort:"medium"},{legacyId:"gemini-3.5-flash-low",model:"gemini-3.5-flash",effort:"low"},{legacyId:"gemini-3.1-pro-high",model:"gemini-3.1-pro",effort:"high"},{legacyId:"gemini-3.1-pro-low",model:"gemini-3.1-pro",effort:"low"},{legacyId:"gpt-oss-120b-medium",model:"gpt-oss-120b",effort:"medium"}],ec=new Map(Zu.map(({legacyId:t,model:e,effort:n})=>[t,n===void 0?{model:e}:{model:e,effort:n}]));});function nc(){return {models:[],modes:[],effort:[],modelOverrides:{},providerOptions:[]}}function Ze(t){return Qn(t).models}function Qn(t){return tc[t]??Vr[t]??nc()}function rn(t,e){let n=Qn(t);if(e){if(Object.prototype.hasOwnProperty.call(n.modelOverrides,e))return n.modelOverrides[e]?.effort??n.effort;let r=Xr(t,e);return r.model===void 0?n.effort:n.modelOverrides[r.model]?.effort??n.effort}return n.effort}function hi(t){return Qn(t).modelOverrides}function _i(){return Ze("claude")}function mi(){return Ze("codex")}function ki(){return Ze("copilot")}function Ti(){return Ze("antigravity")}var tc,ft=v(()=>{_();Xn();Gn();nn();tc={};});function wi(t){return rc[t]??t}var rc,yi=v(()=>{_();ft();nn();rc={auto:"default"};});function Zn(t,e){return (Yn[t]??[]).includes(e)}function et(t){if(!t)return {};let e=t.match(/^(.+?)\[([^\]]+)\]$/);if(e){let n=e[2].toLowerCase();return sc.has(n)?{model:e[1],effort:n}:{model:t}}return {model:t}}function Ei(t){switch(t){case "agent-full-access":case "yolo":return ["--dangerously-bypass-approvals-and-sandbox"];case "read-only":case "plan":return ["--sandbox","read-only"];case "agent":return ["--sandbox","workspace-write"];default:return []}}function Ri(t){switch(t){case "agent-full-access":case "yolo":return ["--dangerously-bypass-approvals-and-sandbox"];case "read-only":case "plan":return ["-c","sandbox_mode=read-only"];case "agent":return ["-c","sandbox_mode=workspace-write"];default:return []}}function Si(t){return !t||!Zn("codex",t)?[]:["-c",`model_reasoning_effort=${t}`]}function Ii(t){if(!t)return [];let e=new Set(["acceptEdits","bypassPermissions","default","delegate","dontAsk","plan"]),n=wi(t);return e.has(n)?["--permission-mode",n]:[]}function Ai(t){return t?Zn("claude",t)?["--effort",t]:[]:[]}function Oi(t){return t==="default"?[]:t&&oc.has(t)?["--permission-mode",t]:[]}function bi(t){return t===true?["--always-approve"]:[]}function vi(t,e=n=>console.warn(n)){return t===void 0?[]:t==="workspace"||t==="read-only"||t==="off"?["--sandbox",t]:(e(`[grok] Invalid sandbox value ${JSON.stringify(t)}; using workspace.`),["--sandbox","workspace"])}function xi(t){return t?Zn("grok",t)?["--effort",t]:[]:[]}function Ci(t){if(!t)return [];switch(Jr(t)){case "default":return [];case "plan":return ["--mode","plan"];case "acceptEdits":return ["--mode","accept-edits"];case "bypassPermissions":return ["--dangerously-skip-permissions"];default:return []}}function Ni(t){return t?Zn("antigravity",t)?["--effort",t]:[]:[]}var sc,oc,sn=v(()=>{_();yi();nn();Xn();sc=new Set(gi);oc=new Set(["default","acceptEdits","auto","dontAsk","bypassPermissions","plan"]);});function ic(t){if(t.type!=="usage"||!("input_tokens"in t))return null;let e=Number(t.input_tokens??0),n=Number(t.output_tokens??0),s="cache_read_input_tokens"in t?Number(t.cache_read_input_tokens):void 0,o="cached_input_tokens"in t?Number(t.cached_input_tokens):void 0,i=s!==void 0?s:o??0;return {inputTokens:s!==void 0?e+s:e,outputTokens:n,cachedInputTokens:i}}function ac(t){let e=t.usage;if(!e||typeof e!="object"||Array.isArray(e))return null;let n=e;if(!("input_tokens"in n))return null;let r=Number(n.input_tokens??0),s=Number(n.output_tokens??0),i="cache_read_input_tokens"in n?Number(n.cache_read_input_tokens):void 0,u="cached_input_tokens"in n?Number(n.cached_input_tokens):void 0,d=i!==void 0?i:u??0;return {inputTokens:i!==void 0?r+i:r,outputTokens:s,cachedInputTokens:d}}function dc(t){if(t.type!=="step_finish")return null;let n=t.part?.tokens;if(!n)return null;let r=Number(n.input??0),s=Number(n.output??0),o=n.cache,i=o?Number(o.read??0):0;return {inputTokens:r+i,outputTokens:s,cachedInputTokens:i}}function Pi(t){let e=new Map,n;for(let o of t.split(`
16
+ `:s;e.push({value:t.slice(n,r),separator:o}),r+=o.length-1,n=r+1;}return e.push({value:t.slice(n),separator:""}),e}function Bu(t){for(let e=t.length-1;e>=0;e--)if(t[e].value.trim())return e;return -1}function Wu(t){return t.trimStart().startsWith($u)}function ju(t){let e=t.trim();if(!e.startsWith(pi)||!e.endsWith("]]"))return null;let n=e.slice(pi.length,-2);if(!n)return null;try{return Gu(JSON.parse(n))}catch{return null}}function Gu(t){return zu(t)?Object.prototype.hasOwnProperty.call(t,"taskId")?{schema:1,taskId:t.taskId,agentId:t.agentId,isError:t.isError}:{schema:1,isError:true}:null}function zu(t){if(!Vu(t)||Object.keys(t).some(r=>!Uu.has(r))||t.schema!==1||typeof t.isError!="boolean")return false;let e=Object.prototype.hasOwnProperty.call(t,"taskId"),n=Object.prototype.hasOwnProperty.call(t,"agentId");return e!==n?false:e?fi(t.taskId)&&fi(t.agentId):t.isError===true}function Ku(t,e){if(e.length===0)return t.map(r=>r.value+r.separator).join("");let n=new Set(e.map(({index:r})=>r));return t.map((r,s)=>n.has(s)?"":r.value+r.separator).join("")}function fi(t){return typeof t=="string"&&t.trim().length>0}function Vu(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var pi,$u,Uu,tn=v(()=>{_();pi="[[crewx:delegation-result ",$u="[[crewx:delegation-result",Uu=new Set(["schema","taskId","agentId","isError"]);});function be(t){if(typeof t=="string")return t;if(!t||typeof t!="object")return JSON.stringify(t??{});let e=t;return typeof e.command=="string"?e.command:typeof e.file_path=="string"?e.file_path:typeof e.filePath=="string"?e.filePath:typeof e.path=="string"?e.path:typeof e.query=="string"?e.query:typeof e.pattern=="string"?e.pattern:typeof e.url=="string"?e.url:typeof e.prompt=="string"?e.prompt.length>200?e.prompt.slice(0,200)+"\u2026":e.prompt:typeof e.description=="string"?e.description:JSON.stringify(e)}var Nt=v(()=>{_();});var gi,Yn,Vr,Xn=v(()=>{_();gi=["none","minimal","low","medium","high","xhigh","max","ultra"],Yn={claude:["low","medium","high","xhigh","max"],codex:["none","minimal","low","medium","high","xhigh","max","ultra"],opencode:[],copilot:["none","low","medium","high","xhigh","max"],antigravity:["low","medium","high"],grok:["low","medium","high","xhigh"]},Vr={claude:{models:[{id:"claude-fable-5-1",name:"Claude Fable 5.1",contextWindowTokens:1e6,tier:"flagship",recommended:true},{id:"claude-fable-5",name:"Claude Fable 5",contextWindowTokens:1e6,tier:"flagship"},{id:"claude-opus-5-5",name:"Claude Opus 5.5",contextWindowTokens:1e6,tier:"flagship",recommended:true},{id:"claude-opus-5",name:"Claude Opus 5",contextWindowTokens:1e6,tier:"flagship"},{id:"claude-sonnet-5",name:"Claude Sonnet 5",contextWindowTokens:1e6,tier:"balanced",recommended:true},{id:"claude-opus-4-8[1m]",name:"Claude Opus 4.8",contextWindowTokens:1e6,tier:"flagship"},{id:"claude-opus-4-7[1m]",name:"Claude Opus 4.7",contextWindowTokens:1e6,tier:"flagship"},{id:"claude-opus-4-6[1m]",name:"Claude Opus 4.6",contextWindowTokens:1e6,tier:"flagship"},{id:"claude-sonnet-4-6[1m]",name:"Claude Sonnet 4.6",contextWindowTokens:1e6,tier:"balanced"},{id:"claude-haiku-4-5",name:"Claude Haiku 4.5",contextWindowTokens:2e5,tier:"speed"}],modes:[{id:"default",name:"Default",description:"Uses Claude's default permission handling with normal approval prompts."},{id:"acceptEdits",name:"Accept Edits",description:"Allows file edits without approval; other permission checks remain in place."},{id:"plan",name:"Plan",description:"Keeps Claude in plan mode so it can inspect and propose changes without applying them."},{id:"dontAsk",name:"Don't Ask",description:"Does not ask for permissions; only pre-approved tool actions can proceed."},{id:"bypassPermissions",name:"Bypass Permissions",description:"Bypasses Claude permission checks so tools can run without approval prompts."}],effort:["low","medium","high"],modelOverrides:{"claude-fable-5-1":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-fable-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-5-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"medium"},"claude-opus-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-sonnet-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-4-8[1m]":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-4-7[1m]":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-4-6[1m]":{effort:["low","medium","high","max"],defaultEffort:"high"},"claude-sonnet-4-6[1m]":{effort:["low","medium","high","max"],defaultEffort:"high"},"claude-haiku-4-5":{effort:[]}},providerOptions:[]},codex:{models:[{id:"gpt-6-astra",name:"GPT-6 Astra",contextWindowTokens:105e4,tier:"flagship"},{id:"gpt-6-sol",name:"GPT-6 Sol",contextWindowTokens:105e4,tier:"balanced",recommended:true},{id:"gpt-6-luna",name:"GPT-6 Luna",contextWindowTokens:105e4,tier:"speed",recommended:true},{id:"gpt-5.6-sol",name:"GPT-5.6 Sol",contextWindowTokens:105e4,tier:"flagship"},{id:"gpt-5.6-terra",name:"GPT-5.6 Terra",contextWindowTokens:105e4,tier:"balanced"},{id:"gpt-5.6-luna",name:"GPT-5.6 Luna",contextWindowTokens:105e4,tier:"speed"},{id:"gpt-5.5",name:"GPT-5.5",contextWindowTokens:105e4,tier:"flagship"},{id:"gpt-5.4",name:"GPT-5.4",contextWindowTokens:105e4,tier:"flagship"},{id:"gpt-5.4-mini",name:"GPT-5.4 Mini",contextWindowTokens:4e5,tier:"speed"},{id:"gpt-5.3-codex",name:"GPT-5.3 Codex",contextWindowTokens:4e5,tier:"flagship"},{id:"gpt-5.3-codex-spark",name:"GPT-5.3 Codex Spark",contextWindowTokens:128e3,tier:"speed"}],modes:[{id:"agent",name:"Agent",description:"Uses the workspace-write sandbox; can read and modify workspace files without full machine access."},{id:"read-only",name:"Read Only",description:"Uses the read-only sandbox; can inspect files but cannot write to the workspace."},{id:"plan",name:"Plan",description:"Uses the read-only sandbox for planning and inspection; cannot write to the workspace."},{id:"agent-full-access",name:"Agent Full Access",description:"Bypasses approvals and the sandbox; can access and modify files beyond the workspace."},{id:"yolo",name:"YOLO",description:"Bypasses approvals and the sandbox for unrestricted execution and full filesystem access."}],effort:["minimal","low","medium","high"],modelOverrides:{"gpt-6-astra":{effort:["low","medium","high","xhigh","max"],defaultEffort:"xhigh"},"gpt-6-sol":{effort:["none","low","medium","high","xhigh","max"],defaultEffort:"medium"},"gpt-6-luna":{effort:["none","low","medium","high","xhigh","max"],defaultEffort:"medium"},"gpt-5.6-sol":{effort:["low","medium","high","xhigh","max","ultra"],defaultEffort:"xhigh"},"gpt-5.6-terra":{effort:["low","medium","high","xhigh","max","ultra"],defaultEffort:"high"},"gpt-5.6-luna":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"gpt-5.5":{effort:["low","medium","high","xhigh"],defaultEffort:"high"}},providerOptions:[]},opencode:{models:[],modes:[{id:"plan",name:"Plan",description:"Uses the plan agent without --auto; planning follows standard approval behavior."},{id:"plan-auto",name:"Plan \xB7 Auto",description:"Uses the plan agent with --auto; planning uses automatic approvals."},{id:"build",name:"Build",description:"Uses the build agent without --auto; work follows standard approval behavior."},{id:"build-auto",name:"Build \xB7 Auto",description:"Uses the build agent with --auto; work uses automatic approvals."}],effort:[],modelOverrides:{},providerOptions:[]},copilot:{models:[{id:"auto",name:"Auto"},{id:"claude-sonnet-5",name:"Claude Sonnet 5",contextWindowTokens:1e6,tier:"balanced"},{id:"claude-sonnet-4-6",name:"Claude Sonnet 4.6",contextWindowTokens:1e6,tier:"balanced"},{id:"gpt-5.5",name:"GPT-5.5",contextWindowTokens:105e4,tier:"flagship"},{id:"gpt-5.4",name:"GPT-5.4",contextWindowTokens:105e4,tier:"flagship"},{id:"gemini-3.1-pro",name:"Gemini 3.1 Pro",contextWindowTokens:1048576,tier:"flagship"}],modes:[{id:"interactive",name:"Interactive",description:"Passes --mode interactive; tool access follows Copilot's interactive mode behavior."},{id:"plan",name:"Plan",description:"Passes --mode plan; planning and permission behavior follow Copilot's plan mode."},{id:"autopilot",name:"Autopilot",description:"Passes --mode autopilot; execution behavior follows Copilot's autonomous mode."}],effort:["none","low","medium","high","xhigh","max"],modelOverrides:{},providerOptions:[]},antigravity:{models:[{id:"gemini-3.7-flash",name:"Gemini 3.7 Flash",contextWindowTokens:1048576,tier:"balanced"},{id:"gemini-3.6-flash",name:"Gemini 3.6 Flash",contextWindowTokens:1048576,tier:"balanced"},{id:"gemini-3.5-flash",name:"Gemini 3.5 Flash",contextWindowTokens:1048576,tier:"balanced"},{id:"gemini-3.1-pro",name:"Gemini 3.1 Pro",contextWindowTokens:1048576,tier:"flagship"},{id:"claude-sonnet-4-6",name:"Claude Sonnet 4.6",contextWindowTokens:1e6,tier:"balanced"},{id:"claude-opus-4-6-thinking",name:"Claude Opus 4.6 Thinking",contextWindowTokens:1e6,tier:"flagship"},{id:"gpt-oss-120b",name:"GPT-OSS 120B",contextWindowTokens:128e3,tier:"balanced"}],modes:[{id:"default",name:"Default",description:"Uses Antigravity's default permission handling. No extra permission flags are passed."},{id:"plan",name:"Plan",description:"Passes --mode plan. This turns on /plan; it is not a Claude-style permission mode."},{id:"acceptEdits",name:"Accept Edits",description:"Passes --mode accept-edits."},{id:"bypassPermissions",name:"Bypass Permissions",description:"Passes --dangerously-skip-permissions so tools can run without approval prompts."}],effort:["low","medium","high"],modelOverrides:{"gemini-3.7-flash":{effort:["low","medium","high"],defaultEffort:"medium"},"gemini-3.6-flash":{effort:["low","medium","high"],defaultEffort:"medium"},"gemini-3.5-flash":{effort:["low","medium","high"],defaultEffort:"medium"},"gemini-3.1-pro":{effort:["low","high"],defaultEffort:"high"},"claude-sonnet-4-6":{effort:[]},"claude-opus-4-6-thinking":{effort:[]},"gpt-oss-120b":{effort:["medium"],defaultEffort:"medium"}},providerOptions:[]},grok:{models:[{id:"grok-4.7",name:"Grok 4.7",contextWindowTokens:5e5,tier:"flagship",recommended:true},{id:"grok-4.6",name:"Grok 4.6",contextWindowTokens:5e5,tier:"flagship"},{id:"grok-4.5",name:"Grok 4.5",contextWindowTokens:5e5,tier:"flagship"}],modes:[{id:"default",name:"Default",description:"Uses Grok's default permission handling."},{id:"acceptEdits",name:"Accept Edits",description:"Allows file edits without changing the selected sandbox profile."},{id:"auto",name:"Auto",description:"Uses Grok automatic permission handling."},{id:"dontAsk",name:"Don't Ask",description:"Does not ask for permission before tool execution."},{id:"bypassPermissions",name:"Bypass Permissions",description:"Bypasses Grok permission checks for tool execution."},{id:"plan",name:"Plan",description:"Keeps Grok in planning mode without applying changes."}],effort:["low","medium","high"],modelOverrides:{"grok-4.7":{effort:["low","medium","high","xhigh"],defaultEffort:"high"},"grok-4.6":{effort:["low","medium","high","xhigh"],defaultEffort:"high"},"grok-4.5":{effort:["low","medium","high"],defaultEffort:"high"}},providerOptions:[{key:"alwaysApprove",type:"boolean"},{key:"sandbox",type:"enum",values:["workspace","read-only","off"]}]}},Object.fromEntries(Object.entries(Vr).map(([t,e])=>[t,e.models]));});function Jr(t){return Yu[t]??t}function Qu(t){return Xu.get(t)??t}function Yr(t){if(!t)return {};let e=ec.get(t);return e?{...e}:{model:t}}function Xr(t,e){return t==="antigravity"||t==="cli/antigravity"?Yr(e):e===void 0?{}:{model:Qu(e)}}var Ju,Yu,Xu,Zu,ec,nn=v(()=>{_();Ju=[{baseModelId:"claude-opus-4-8",catalogModelId:"claude-opus-4-8[1m]"},{baseModelId:"claude-opus-4-7",catalogModelId:"claude-opus-4-7[1m]"},{baseModelId:"claude-opus-4-6",catalogModelId:"claude-opus-4-6[1m]"},{baseModelId:"claude-sonnet-4-6",catalogModelId:"claude-sonnet-4-6[1m]"}],Yu={"accept-edits":"acceptEdits",yolo:"bypassPermissions","agent-full-access":"bypassPermissions"};Xu=new Map(Ju.map(({baseModelId:t,catalogModelId:e})=>[t,e]));Zu=[{legacyId:"Gemini 3.7 Flash (High)",model:"gemini-3.7-flash",effort:"high"},{legacyId:"Gemini 3.7 Flash (Medium)",model:"gemini-3.7-flash",effort:"medium"},{legacyId:"Gemini 3.7 Flash (Low)",model:"gemini-3.7-flash",effort:"low"},{legacyId:"Gemini 3.6 Flash (High)",model:"gemini-3.6-flash",effort:"high"},{legacyId:"Gemini 3.6 Flash (Medium)",model:"gemini-3.6-flash",effort:"medium"},{legacyId:"Gemini 3.6 Flash (Low)",model:"gemini-3.6-flash",effort:"low"},{legacyId:"Gemini 3.5 Flash (Medium)",model:"gemini-3.5-flash",effort:"medium"},{legacyId:"Gemini 3.5 Flash (High)",model:"gemini-3.5-flash",effort:"high"},{legacyId:"Gemini 3.5 Flash (Low)",model:"gemini-3.5-flash",effort:"low"},{legacyId:"Gemini 3.1 Pro (Low)",model:"gemini-3.1-pro",effort:"low"},{legacyId:"Gemini 3.1 Pro (High)",model:"gemini-3.1-pro",effort:"high"},{legacyId:"Claude Sonnet 4.6 (Thinking)",model:"claude-sonnet-4-6"},{legacyId:"Claude Opus 4.6 (Thinking)",model:"claude-opus-4-6-thinking"},{legacyId:"GPT-OSS 120B (Medium)",model:"gpt-oss-120b",effort:"medium"},{legacyId:"gemini-3.7-flash-high",model:"gemini-3.7-flash",effort:"high"},{legacyId:"gemini-3.7-flash-medium",model:"gemini-3.7-flash",effort:"medium"},{legacyId:"gemini-3.7-flash-low",model:"gemini-3.7-flash",effort:"low"},{legacyId:"gemini-3.6-flash-high",model:"gemini-3.6-flash",effort:"high"},{legacyId:"gemini-3.6-flash-medium",model:"gemini-3.6-flash",effort:"medium"},{legacyId:"gemini-3.6-flash-low",model:"gemini-3.6-flash",effort:"low"},{legacyId:"gemini-3.5-flash-high",model:"gemini-3.5-flash",effort:"high"},{legacyId:"gemini-3.5-flash-medium",model:"gemini-3.5-flash",effort:"medium"},{legacyId:"gemini-3.5-flash-low",model:"gemini-3.5-flash",effort:"low"},{legacyId:"gemini-3.1-pro-high",model:"gemini-3.1-pro",effort:"high"},{legacyId:"gemini-3.1-pro-low",model:"gemini-3.1-pro",effort:"low"},{legacyId:"gpt-oss-120b-medium",model:"gpt-oss-120b",effort:"medium"}],ec=new Map(Zu.map(({legacyId:t,model:e,effort:n})=>[t,n===void 0?{model:e}:{model:e,effort:n}]));});function nc(){return {models:[],modes:[],effort:[],modelOverrides:{},providerOptions:[]}}function Ze(t){return Qn(t).models}function Qn(t){return tc[t]??Vr[t]??nc()}function rn(t,e){let n=Qn(t);if(e){if(Object.prototype.hasOwnProperty.call(n.modelOverrides,e))return n.modelOverrides[e]?.effort??n.effort;let r=Xr(t,e);return r.model===void 0?n.effort:n.modelOverrides[r.model]?.effort??n.effort}return n.effort}function hi(t){return Qn(t).modelOverrides}function _i(){return Ze("claude")}function mi(){return Ze("codex")}function ki(){return Ze("copilot")}function Ti(){return Ze("antigravity")}var tc,ft=v(()=>{_();Xn();Gn();nn();tc={};});function wi(t){return rc[t]??t}var rc,yi=v(()=>{_();ft();nn();rc={auto:"default"};});function Zn(t,e){return (Yn[t]??[]).includes(e)}function et(t){if(!t)return {};let e=t.match(/^(.+?)\[([^\]]+)\]$/);if(e){let n=e[2].toLowerCase();return sc.has(n)?{model:e[1],effort:n}:{model:t}}return {model:t}}function Ei(t){switch(t){case "agent-full-access":case "yolo":return ["--dangerously-bypass-approvals-and-sandbox"];case "read-only":case "plan":return ["--sandbox","read-only"];case "agent":return ["--sandbox","workspace-write"];default:return []}}function Ri(t){switch(t){case "agent-full-access":case "yolo":return ["--dangerously-bypass-approvals-and-sandbox"];case "read-only":case "plan":return ["-c","sandbox_mode=read-only"];case "agent":return ["-c","sandbox_mode=workspace-write"];default:return []}}function Si(t){return !t||!Zn("codex",t)?[]:["-c",`model_reasoning_effort=${t}`]}function Ii(t){if(!t)return [];let e=new Set(["acceptEdits","bypassPermissions","default","delegate","dontAsk","plan"]),n=wi(t);return e.has(n)?["--permission-mode",n]:[]}function Ai(t){return t?Zn("claude",t)?["--effort",t]:[]:[]}function Oi(t){return t==="default"?[]:t&&oc.has(t)?["--permission-mode",t]:[]}function bi(t){return t===true?["--always-approve"]:[]}function vi(t,e=n=>console.warn(n)){return t===void 0?[]:t==="workspace"||t==="read-only"||t==="off"?["--sandbox",t]:(e(`[grok] Invalid sandbox value ${JSON.stringify(t)}; using workspace.`),["--sandbox","workspace"])}function xi(t){return t?Zn("grok",t)?["--effort",t]:[]:[]}function Ci(t){if(!t)return [];switch(Jr(t)){case "default":return [];case "plan":return ["--mode","plan"];case "acceptEdits":return ["--mode","accept-edits"];case "bypassPermissions":return ["--dangerously-skip-permissions"];default:return []}}function Ni(t){return t?Zn("antigravity",t)?["--effort",t]:[]:[]}var sc,oc,sn=v(()=>{_();yi();nn();Xn();sc=new Set(gi);oc=new Set(["default","acceptEdits","auto","dontAsk","bypassPermissions","plan"]);});function ic(t){if(t.type!=="usage"||!("input_tokens"in t))return null;let e=Number(t.input_tokens??0),n=Number(t.output_tokens??0),s="cache_read_input_tokens"in t?Number(t.cache_read_input_tokens):void 0,o="cached_input_tokens"in t?Number(t.cached_input_tokens):void 0,i=s!==void 0?s:o??0;return {inputTokens:s!==void 0?e+s:e,outputTokens:n,cachedInputTokens:i}}function ac(t){let e=t.usage;if(!e||typeof e!="object"||Array.isArray(e))return null;let n=e;if(!("input_tokens"in n))return null;let r=Number(n.input_tokens??0),s=Number(n.output_tokens??0),i="cache_read_input_tokens"in n?Number(n.cache_read_input_tokens):void 0,u="cached_input_tokens"in n?Number(n.cached_input_tokens):void 0,d=i!==void 0?i:u??0;return {inputTokens:i!==void 0?r+i:r,outputTokens:s,cachedInputTokens:d}}function dc(t){if(t.type!=="step_finish")return null;let n=t.part?.tokens;if(!n)return null;let r=Number(n.input??0),s=Number(n.output??0),o=n.cache,i=o?Number(o.read??0):0;return {inputTokens:r+i,outputTokens:s,cachedInputTokens:i}}function Pi(t){let e=new Map,n;for(let o of t.split(`
17
17
  `))if(o.trim())try{let i=JSON.parse(o);if(i.type!=="assistant")continue;let u=i.message,d=u?.id,c=u?.usage;if(typeof d!="string"||!c)continue;let l=Number(c.input_tokens??0),p=Number(c.cache_read_input_tokens??0);e.set(d,{inputTokens:l+p,cachedInputTokens:p});let f=u?.model;typeof f=="string"&&f&&(n=f);}catch{}if(e.size===0)return;let r=0,s=0;for(let o of e.values())r+=o.inputTokens,s+=o.cachedInputTokens;return {inputTokens:r,cachedInputTokens:s,model:n}}function Pt(t){if(!t||!t.trim())return;let e=null,n=null;for(let r of t.split(`
18
18
  `))if(r.trim())try{let s=JSON.parse(r),o=dc(s);if(o){n||(n={inputTokens:0,outputTokens:0,cachedInputTokens:0}),n.inputTokens+=o.inputTokens,n.outputTokens+=o.outputTokens,n.cachedInputTokens+=o.cachedInputTokens;continue}let i=ic(s)??ac(s);i&&(e=i);}catch{}return n||(e??void 0)}var on=v(()=>{_();});function ve(t,e){if(typeof t!="object"||t===null||Array.isArray(t))return e;let n=t.timestamp;return typeof n!="string"||!Number.isFinite(Date.parse(n))?e:new Date(n).toISOString()}var gt=v(()=>{_();});function Di(t){let e=t.split(`
19
19
  `).filter(s=>s.trim()),n=[],r=null;for(let s of e)try{let o=JSON.parse(s);if(o.type==="assistant"&&Array.isArray(o.message?.content))for(let i of o.message.content)i.type==="text"&&typeof i.text=="string"&&i.text.trim()&&n.push(i.text.trim());o.type==="result"&&typeof o.result=="string"&&(r=o.result);}catch{}if(n.length>0)return n[n.length-1];if(r)return r}function lc(t){let e=t.split(`
@@ -1,2 +1,2 @@
1
- import*as Ut from'crypto';import {createHash}from'crypto';import*as R from'fs';import {constants,readFileSync,existsSync,statSync,readdirSync}from'fs';import*as k from'path';import {join,relative,sep,isAbsolute,resolve}from'path';import*as vn from'js-yaml';import {load}from'js-yaml';import {realpath,stat,readdir,open,lstat}from'fs/promises';import*as Jn from'os';import*as Xn from'tar';import {gunzipSync,gzipSync}from'zlib';var N=class extends Error{constructor(n,i=n,o){super(i);this.code=n;this.currentRevision=o;}code;currentRevision;name="UiRuntimeError"};var ci=/(?:proof|token|secret|password|cookie|authorization|private[_-]?key|stack|exception|plugin[_-]?text)/i,pi=/(?:url|uri|endpoint|path|file(?:name|path)?|cwd|shell|directory|dir|folder)$/i,li=/<\/?[A-Za-z][^>]*>/,di=/^(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)/,ui=/^(?:https?|file|ftp|ws|wss):\/\//i;function v(){throw new N("INPUT_INVALID","JSON value is not projection-safe")}function fi(e){let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}var yi=8,Ai=4;function We(e,t,n,i,o,r){if(t>i&&v(),e===null||typeof e=="string"||typeof e=="boolean")return typeof e=="string"&&(li.test(e)||ui.test(e)&&!Ii(o,r)||di.test(e))&&v(),e;if(typeof e=="number")return Number.isFinite(e)||v(),e;(typeof e!="object"||e===void 0||typeof e=="function"||typeof e=="bigint")&&v();let s=e;n.has(s)&&v(),n.add(s);try{if(Array.isArray(e))return e.map(p=>We(p,t+1,n,i,o,r));fi(s)||v();let a={};for(let[p,l]of Object.entries(e))(ci.test(p)||pi.test(p))&&v(),a[p]=We(l,t+1,n,i,[...o,p],r);return a}finally{n.delete(s);}}function re(e,t=0,n=[]){(!Number.isInteger(t)||t<0||t>Ai)&&v(),(!Array.isArray(n)||n.some(o=>typeof o!="string"))&&v();let i=We(e,0,new Set,yi+t,[],n);return (i===null||Array.isArray(i)||typeof i!="object")&&v(),i}function oe(e,t){if(!e||!t)return false;let n=e.split("."),i=t.split(".");return n.length>=i.length&&i.every((o,r)=>n[r]===o)}function Ii(e,t){if(e.length===0)return false;let n=e.join(".");return t.some(i=>oe(n,i))}function Ke(e){try{let t=JSON.stringify(e);return t===void 0&&v(),t}catch{v();}}function Je(e){return Array.isArray(e)?e.map(Je):e!==null&&typeof e=="object"?Object.fromEntries(Object.keys(e).sort().map(t=>[t,Je(e[t])])):e}function Q(e){return Ke(Je(e))}function Xe(e){return Q(e)}var q="window";var xt=["__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"],gi=new Set(xt),mi=/(?:proof|token|secret|password|cookie|authorization|private[_-]?key|stack|exception|plugin[_-]?text)/i,hi=/(?:url|uri|endpoint|path|file(?:name|path)?|cwd|shell|directory|dir|folder)$/i;function se(e){return gi.has(e)||mi.test(e)||hi.test(e)}var Pe=/^[A-Za-z0-9_]+$/,fe=/^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)*$/,ae=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,Ye=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/,qe=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,Ze=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/,Qe=["blue","violet","emerald","amber","rose","sky","slate","indigo"],et=["inline","panel"];var _i=1,Ei=/^[a-z][a-zA-Z0-9]*(\.[a-zA-Z0-9]+)+$/,Ti=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,$t=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,Pi=/<\/?[A-Za-z][^>]*>/,Di=/^(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)/,bi=/^(?:https?|file|ftp|ws|wss):\/\//i,Ni=/^\s*(?:javascript|data):/i,Ct=/data:[^,\s]*,/i,Mi=/(?:https?|file|ftp|ws|wss):\/\//i,Si=/javascript:/i,Li=/(?:^[\s]*|[\s"'(=])(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)(?=[^\s"'<>])[^\s"'<>]*/,Ui=["manifestVersion","pluginId","definitionId","version","primitiveSet","activation","schema","layout"],Ri=["manifestVersion","pluginId","definitionId","version","name","description","entry","surfaces","size","stateProjection","actions"],Oi=["icon","tone","entryHash","initialState","usage","detailPanel","displayModes","dataPaths"],wi=["actionId","capability","mutation","inputSchema","resultProjection","backend"],ki=["confirmation","dataInputs"],xi=["type","handler"],Ci=["type","command"],Vi=["path"],Fi=["hash"],vi=/^[0-9a-f]{64}$/,ji=/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/,Hi=/[\r\n]/,Bi=16,zi=["card-shell","meta-banner","heading","labeled-text","step-flow","text-list"],V=class extends Error{constructor(n,i=n){super(i);this.code=n;}code;name="UiPluginValidationError"};function c(e,t=e){throw new V(e,t)}function L(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;try{let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}catch{return false}}function E(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function S(e,t,n=[]){let i=new Set([...t,...n]);Object.keys(e).some(o=>!i.has(o))&&c("MANIFEST_INVALID"),t.some(o=>!E(e,o))&&c("MANIFEST_INVALID");}function Se(e,t=false,n=false,i=false){return Pi.test(e)||!i&&bi.test(e)||Di.test(e)||n&&Ct.test(e)||Ni.test(e)&&!(t&&/^\s*data:/i.test(e)&&!Ct.test(e))}function Ne(e,t=new Set,n=0,i=false,o=false){if(typeof e=="string"){Se(e,i,o)&&c("UNSAFE_VALUE");return}if(!(e===null||typeof e!="object")){(n>8||t.has(e))&&c("MANIFEST_INVALID"),t.add(e);try{if(Array.isArray(e)){for(let r of e)Ne(r,t,n+1);return}L(e)||c("MANIFEST_INVALID");for(let[r,s]of Object.entries(e))Ne(s,t,n+1,i&&n===0&&(r==="name"||r==="description"),o);}finally{t.delete(e);}}}function W(e,t){let n=e[t];return typeof n!="string"&&c("MANIFEST_INVALID"),n}function z(e,t,n){let i=e[t];return (!Number.isSafeInteger(i)||i<n)&&c("MANIFEST_INVALID"),i}function tt(e){return Ti.test(e)||c("MANIFEST_INVALID"),e}function ce(e){return Ei.test(e)||c("TOKEN_INVALID"),e}function Gi(e){return $t.test(e)||c("MANIFEST_INVALID"),e}function $i(e){L(e)||c("MANIFEST_INVALID");let t={};for(let[n,i]of Object.entries(e)){let o=Gi(n);L(i)||c("MANIFEST_INVALID");let r=i.type;if(r==="text"){S(i,["type","maxLength"]),t[o]={type:r,maxLength:z(i,"maxLength",1)};continue}if(r==="text-list"){S(i,["type","max","itemMaxLength"]),t[o]={type:r,max:z(i,"max",0),itemMaxLength:z(i,"itemMaxLength",1)};continue}if(r==="step-list"){S(i,["type","min","max","labelMaxLength","detailMaxLength"]);let s=z(i,"min",0),a=z(i,"max",1);s>a&&c("MANIFEST_INVALID"),t[o]={type:r,min:s,max:a,labelMaxLength:z(i,"labelMaxLength",1),detailMaxLength:z(i,"detailMaxLength",1)};continue}typeof r=="string"&&c("SCHEMA_TYPE_UNSUPPORTED"),c("MANIFEST_INVALID");}return t}function Wi(e,t,n){let i=e[t];(!i||i.type!==n)&&c("MANIFEST_INVALID");}function De(e,t,n){let i=W(e,"field");return $t.test(i)||c("MANIFEST_INVALID"),Wi(t,i,n),i}function Ji(e,t){L(e)||c("MANIFEST_INVALID");let n=e.primitive;switch(typeof n!="string"&&c("MANIFEST_INVALID"),zi.includes(n)||c("PRIMITIVE_UNKNOWN"),n){case "card-shell":return S(e,["primitive"]),{primitive:n};case "meta-banner":return S(e,["primitive","badgeToken","noticeToken"]),{primitive:n,badgeToken:ce(W(e,"badgeToken")),noticeToken:ce(W(e,"noticeToken"))};case "heading":return S(e,["primitive","field"]),{primitive:n,field:De(e,t,"text")};case "labeled-text":return S(e,["primitive","titleToken","field","variant"]),e.variant!=="callout"&&c("MANIFEST_INVALID"),{primitive:n,titleToken:ce(W(e,"titleToken")),field:De(e,t,"text"),variant:"callout"};case "step-flow":return S(e,["primitive","titleToken","field"]),{primitive:n,titleToken:ce(W(e,"titleToken")),field:De(e,t,"step-list")};case "text-list":{S(e,["primitive","titleToken","field"],["emptyToken","hideWhenEmpty"]);let i={primitive:n,titleToken:ce(W(e,"titleToken")),field:De(e,t,"text-list")};return E(e,"emptyToken")&&(i.emptyToken=ce(W(e,"emptyToken"))),E(e,"hideWhenEmpty")&&(typeof e.hideWhenEmpty!="boolean"&&c("MANIFEST_INVALID"),i.hideWhenEmpty=e.hideWhenEmpty),i}}return c("MANIFEST_INVALID")}function Ki(e,t){return Array.isArray(e)||c("MANIFEST_INVALID"),e.map(n=>Ji(n,t))}function U(e="v2 manifest exceeds a contract limit"){return c("LIMIT_EXCEEDED",e)}function j(e="initial state is not projection-safe"){return c("INITIAL_STATE_INVALID",e)}function Vt(e,t){return (typeof e!="string"||e.length===0||e.length>4096||e.trim().length===0||ji.test(e)||Hi.test(e))&&c("MANIFEST_INVALID",`${t} is invalid`),(Se(e,true,true)||Mi.test(e)||Si.test(e)||Li.test(e))&&c("UNSAFE_VALUE",`${t} contains an unsafe value`),e}function nt(e,t){return (typeof e!="string"||!ae.test(e))&&c("MANIFEST_INVALID",`${t} is invalid`),e}function Xi(e){return (typeof e!="string"||!Ye.test(e)||e==="*"||e==="all")&&c("MANIFEST_INVALID","action capability is invalid"),e}function Wt(e){return (typeof e!="string"||!vi.test(e))&&c("MANIFEST_INVALID","resource hash is invalid"),e}function it(e,t=new Set,n=0){if(typeof e=="string"){e.length>4096&&U("v2 manifest string is too long");return}if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){Number.isFinite(e)||c("MANIFEST_INVALID","v2 manifest contains a non-finite number");return}(e===void 0||typeof e=="function"||typeof e=="bigint")&&c("MANIFEST_INVALID","v2 manifest contains a non-JSON value"),typeof e!="object"&&c("MANIFEST_INVALID"),n>8&&U("v2 manifest nesting is too deep"),t.has(e)&&c("MANIFEST_INVALID","v2 manifest contains a cycle"),t.add(e);try{if(Array.isArray(e)){e.length>128&&U("v2 manifest array is too long");for(let i of e)it(i,t,n+1);return}L(e)||c("MANIFEST_INVALID","v2 manifest contains a non-plain object");for(let i of Object.values(e))it(i,t,n+1);}finally{t.delete(e);}}}function Jt(e){return (typeof e!="string"||e.length>4096||!fe.test(e))&&(typeof e=="string"&&e.length>4096&&U("projection path is too long"),c("MANIFEST_INVALID","projection paths must be canonical exact paths")),e.split(".").some(n=>se(n))&&c("MANIFEST_INVALID","projection paths cannot address reserved state keys"),e}function Kt(e){L(e)||c("MANIFEST_INVALID","projection policy must be an object"),S(e,["allow"]),Array.isArray(e.allow)||c("MANIFEST_INVALID","projection allow must be an array"),e.allow.length>128&&U("projection allowlist is too long");let t=[],n=new Set;for(let i of e.allow){let o=Jt(i);n.has(o)&&c("MANIFEST_INVALID","projection allowlist contains a duplicate path"),n.add(o),t.push(o);}return {allow:t}}function Yi(e,t){if(e===void 0)return;Array.isArray(e)||c("MANIFEST_INVALID","dataPaths must be an array"),e.length>Bi&&U("dataPaths exceed the v2 limit");let n=[],i=new Set;for(let o of e){let r=Jt(o);i.has(r)&&c("MANIFEST_INVALID","dataPaths contain a duplicate path"),t.some(s=>oe(r,s))||c("MANIFEST_INVALID","dataPaths must be projection-allowed"),i.add(r),n.push(r);}return n}function pe(e,t,n=Number.MAX_SAFE_INTEGER){return (!Number.isSafeInteger(e)||e<0||e>n)&&c("MANIFEST_INVALID",`${t} is invalid`),e}function Ft(e,t){return (typeof e!="number"||!Number.isFinite(e))&&c("MANIFEST_INVALID",`${t} is invalid`),e}function rt(e,t=0,n=new Set){if(typeof e=="string")return (e.length>4096||Se(e))&&c("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)||c("MANIFEST_INVALID","schema enum contains a non-finite number"),e;(t>8||typeof e!="object"||e===void 0)&&U("schema enum is too deep"),n.has(e)&&c("MANIFEST_INVALID","schema enum contains a cycle"),n.add(e);try{if(Array.isArray(e))return e.length>128&&U("schema enum array is too long"),e.map(o=>rt(o,t+1,n));L(e)||c("MANIFEST_INVALID","schema enum contains a non-plain object");let i={};for(let[o,r]of Object.entries(e))se(o)&&c("MANIFEST_INVALID","schema enum contains a reserved key"),i[o]=rt(r,t+1,n);return i}finally{n.delete(e);}}function qi(e,t){if(e===void 0)return;Array.isArray(e)||c("MANIFEST_INVALID","schema required must be an array"),e.length>64&&U("schema required list is too long");let n=[],i=new Set;for(let o of e)(typeof o!="string"||!fe.test(o))&&c("MANIFEST_INVALID","schema required contains an invalid key"),o.length>4096&&U("schema required key is too long"),i.has(o)&&c("MANIFEST_INVALID","schema required contains a duplicate key"),t&&!Object.prototype.hasOwnProperty.call(t,o)&&c("MANIFEST_INVALID","schema required references an undeclared property"),i.add(o),n.push(o);return n}function Zi(e,t){let n=t?fe:Pe;return e.length>4096&&U("schema property name is too long"),(!n.test(e)||e.split(".").some(i=>se(i)))&&c("MANIFEST_INVALID","schema property name is invalid"),e}function ot(e,t=0,n=false){L(e)||c("MANIFEST_INVALID","action inputSchema must be an object"),t>8&&U("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"&&c("SCHEMA_TYPE_UNSUPPORTED","action inputSchema type is unsupported"),c("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"),S(e,["type"],o.filter(a=>a!=="type"));let r={type:i};if(E(e,"enum")&&(Array.isArray(e.enum)||c("MANIFEST_INVALID","schema enum must be an array"),e.enum.length>128&&U("schema enum is too long"),r.enum=e.enum.map(a=>rt(a))),i==="string"&&(E(e,"minLength")&&(r.minLength=pe(e.minLength,"schema minLength",4096)),E(e,"maxLength")&&(r.maxLength=pe(e.maxLength,"schema maxLength",4096)),r.minLength!==void 0&&r.maxLength!==void 0&&r.minLength>r.maxLength&&c("MANIFEST_INVALID","schema string length bounds are inverted")),(i==="number"||i==="integer")&&(E(e,"minimum")&&(r.minimum=Ft(e.minimum,"schema minimum")),E(e,"maximum")&&(r.maximum=Ft(e.maximum,"schema maximum")),r.minimum!==void 0&&r.maximum!==void 0&&r.minimum>r.maximum&&c("MANIFEST_INVALID","schema numeric bounds are inverted")),i==="array"&&(E(e,"minItems")&&(r.minItems=pe(e.minItems,"schema minItems",128)),E(e,"maxItems")&&(r.maxItems=pe(e.maxItems,"schema maxItems",128)),r.minItems!==void 0&&r.maxItems!==void 0&&r.minItems>r.maxItems&&c("MANIFEST_INVALID","schema array length bounds are inverted"),E(e,"items")&&(r.items=ot(e.items,t+1,false))),i==="object"){let a;if(E(e,"properties")){L(e.properties)||c("MANIFEST_INVALID","schema properties must be an object");let l=Object.entries(e.properties);l.length>64&&U("schema properties are too many"),a={};for(let[u,d]of l){let f=Zi(u,n);a[f]=ot(d,t+1,false);}r.properties=a;}E(e,"minProperties")&&(r.minProperties=pe(e.minProperties,"schema minProperties",64)),E(e,"maxProperties")&&(r.maxProperties=pe(e.maxProperties,"schema maxProperties",64)),r.minProperties!==void 0&&r.maxProperties!==void 0&&r.minProperties>r.maxProperties&&c("MANIFEST_INVALID","schema object property bounds are inverted");let p=qi(e.required,a);p!==void 0&&(r.required=p),E(e,"additionalProperties")&&(e.additionalProperties!==false&&c("MANIFEST_INVALID","schema additionalProperties must be false"),r.additionalProperties=false);}let s=JSON.stringify(r);return (s===void 0||Buffer.byteLength(s,"utf8")>65536)&&U("action inputSchema subtree is too large"),r}function Qi(e){let t=ot(e,0,true);return (t.type!=="object"||!t.properties)&&c("MANIFEST_INVALID","action inputSchema must declare object properties"),t}function er(e){if(L(e)||c("MANIFEST_INVALID","action backend must be an object"),e.type==="core"){S(e,xi);let t=e.handler;return (typeof t!="string"||!qe.test(t))&&c("MANIFEST_INVALID","core backend handler is invalid"),{type:"core",handler:t}}if(e.type==="skill"){S(e,Ci),(!Array.isArray(e.command)||e.command.length===0||e.command.length>16)&&c("MANIFEST_INVALID","skill backend command is invalid");let t=[];for(let n of e.command)(typeof n!="string"||n.length===0||n.length>256||!Ze.test(n))&&c("MANIFEST_INVALID","skill backend command token is invalid"),t.push(n);return {type:"skill",command:t}}c("MANIFEST_INVALID","action backend type is unsupported");}function tr(e){L(e)||c("MANIFEST_INVALID","action must be an object"),S(e,wi,ki);let t=nt(e.actionId,"actionId"),n=Xi(e.capability),i=e.mutation;typeof i!="boolean"&&c("MANIFEST_INVALID","action mutation must be boolean");let o=Qi(e.inputSchema),r;if(E(e,"dataInputs")){Array.isArray(e.dataInputs)||c("MANIFEST_INVALID","action dataInputs must be an array");let l=o.properties,u=new Set,d=[];for(let f of e.dataInputs)(typeof f!="string"||!E(l,f)||u.has(f))&&c("MANIFEST_INVALID","action dataInputs must be unique declared properties"),u.add(f),d.push(f);r=d;}let s=Kt(e.resultProjection),a=er(e.backend),p;if(E(e,"confirmation")){let l=e.confirmation;l!=="none"&&l!=="native"&&c("MANIFEST_INVALID","action confirmation is invalid"),p=l;}return {actionId:t,capability:n,mutation:i,inputSchema:o,resultProjection:s,backend:a,...r===void 0?{}:{dataInputs:r},...p===void 0?{}:{confirmation:p}}}function nr(e){return L(e)||c("INITIAL_STATE_INVALID","initialState must be an object"),S(e,Vi,Fi),e.path!=="ui/state.json"&&c("MANIFEST_INVALID","initialState path is not fixed"),E(e,"hash")?{path:"ui/state.json",hash:Wt(e.hash)}:{path:"ui/state.json"}}function ir(e,t){Ne(e,new Set,0,true,true),it(e),L(e)||c("MANIFEST_INVALID"),S(e,Ri,Oi),e.manifestVersion!==2&&c("MANIFEST_INVALID");let n=nt(e.pluginId,"pluginId"),i=nt(e.definitionId,"definitionId"),o=z(e,"version",1),r=Vt(e.name,"name"),s=Vt(e.description,"description"),a;E(e,"icon")&&((typeof e.icon!="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(e.icon))&&c("MANIFEST_INVALID","icon is invalid"),a=e.icon);let p;E(e,"tone")&&((typeof e.tone!="string"||!Qe.includes(e.tone))&&c("MANIFEST_INVALID","tone is invalid"),p=e.tone),e.entry!=="ui/index.html"&&c("MANIFEST_INVALID","entry path is not fixed");let l;E(e,"entryHash")&&(l=Wt(e.entryHash));let u;E(e,"initialState")&&(u=nr(e.initialState));let d;E(e,"usage")&&(e.usage!=="card"&&e.usage!=="window"&&c("MANIFEST_INVALID","usage is invalid"),d=e.usage);let f;E(e,"detailPanel")&&(typeof e.detailPanel!="boolean"&&c("MANIFEST_INVALID","detailPanel is invalid"),f=e.detailPanel);let A;if(E(e,"displayModes")){((d??q)!==q||!Array.isArray(e.displayModes)||e.displayModes.length===0)&&c("MANIFEST_INVALID","displayModes are only valid for window Apps");let w=new Set(["inline","floating","focused"]);(new Set(e.displayModes).size!==e.displayModes.length||e.displayModes.some(D=>typeof D!="string"||!w.has(D)))&&c("MANIFEST_INVALID","displayModes are invalid"),A=e.displayModes;}(d??q)===q&&f!==void 0&&c("MANIFEST_INVALID","detailPanel is card-only");let I=t.mode??"local";I!=="local"&&I!=="installed"&&I!=="published"&&c("MANIFEST_INVALID","manifest mode is invalid"),I!=="local"&&l===void 0&&c("MANIFEST_INVALID","installed manifests require entryHash"),I!=="local"&&u!==void 0&&u.hash===void 0&&c("MANIFEST_INVALID","installed manifests require initialState.hash"),(!Array.isArray(e.surfaces)||e.surfaces.length===0)&&c("MANIFEST_INVALID","surfaces are invalid"),e.surfaces.length>2&&U("surfaces exceed the v2 limit");let M=[],G=new Set;for(let w of e.surfaces)(typeof w!="string"||!et.includes(w))&&c("MANIFEST_INVALID","surface is unsupported"),G.has(w)&&c("MANIFEST_INVALID","surfaces contain a duplicate"),G.add(w),M.push(w);L(e.size)||c("MANIFEST_INVALID","size must be an object"),S(e.size,["height"]);let F=z(e.size,"height",1);F>720&&U("size.height exceeds the v2 limit");let m=Kt(e.stateProjection),g=Yi(e.dataPaths,m.allow);Array.isArray(e.actions)||c("MANIFEST_INVALID","actions must be an array"),e.actions.length>32&&U("actions exceed the v2 limit");let H=[],$=new Set;for(let w of e.actions){let D=tr(w);if($.has(D.actionId)&&c("MANIFEST_INVALID","actions contain a duplicate actionId"),D.backend.type==="core"&&D.backend.handler==="state.set"){D.mutation||c("MANIFEST_INVALID","state.set actions must be mutations");for(let B of Object.keys(D.inputSchema.properties))m.allow.includes(B)||c("MANIFEST_INVALID","state.set input paths must be projection-allowed");}$.add(D.actionId),H.push(D);}return {manifestVersion:2,pluginId:n,definitionId:i,version:o,name:r,description:s,...a===void 0?{}:{icon:a},...p===void 0?{}:{tone:p},entry:"ui/index.html",...l===void 0?{}:{entryHash:l},...u===void 0?{}:{initialState:u},...d===void 0?{}:{usage:d},...f===void 0?{}:{detailPanel:f},...A===void 0?{}:{displayModes:A},surfaces:M,size:{height:F},stateProjection:m,...g===void 0?{}:{dataPaths:g},actions:H}}function rr(e){let t={},n={};for(let r of e.actions){t[r.actionId]={capabilities:[r.capability],inputKeys:Object.keys(r.inputSchema.properties??{}),...r.dataInputs===void 0?{}:{dataInputs:r.dataInputs},resultProjection:r.resultProjection,...r.confirmation===void 0?{}:{confirmation:r.confirmation}};let s=r.backend.type==="skill"||r.backend.type==="core"&&r.backend.handler==="state.set";n[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.dataPaths===void 0?{}:{dataPaths:e.dataPaths},actions:t},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:n,resources:o}}function st(e,t,n,i,o,r){if(typeof e=="string"){let s=o.length>0&&r.some(a=>oe(o.join("."),a));return (e.length>4096||Se(e,false,false,s))&&j("state contains an unsafe string"),e}if(e===null||typeof e=="boolean")return e;if(typeof e=="number")return Number.isFinite(e)||j("state contains a non-finite number"),e;(e===void 0||typeof e!="object"||typeof e=="function"||typeof e=="bigint")&&j("state contains a non-JSON value"),n>8&&j("state is too deep"),t.has(e)&&j("state contains a cycle"),t.add(e);try{let s;if(Array.isArray(e))e.length>128&&j("state array is too long"),s=e.map(p=>st(p,t,n+1,65536,o,r));else {L(e)||j("state contains a non-plain object");let p={};for(let[l,u]of Object.entries(e))(l.length>4096||!Pe.test(l)||se(l))&&(l.length>4096&&j("state key is too long"),j("state contains a reserved or invalid key")),p[l]=st(u,t,n+1,65536,[...o,l],r);s=p;}let a=JSON.stringify(s);return (a===void 0||Buffer.byteLength(a,"utf8")>i)&&j("state subtree is too large"),s}finally{t.delete(e);}}function ct(e,t=[]){L(e)||j("initial state must be a JSON object");let n=st(e,new Set,0,65536,[],t);return (n===null||Array.isArray(n)||typeof n!="object")&&j(),n}function or(e,t={}){Ne(e),L(e)||c("MANIFEST_INVALID"),S(e,Ui),e.manifestVersion!==1&&c("MANIFEST_INVALID");let n=tt(W(e,"pluginId")),i=tt(W(e,"definitionId")),o=z(e,"version",1),r=z(e,"primitiveSet",1),s=t.supportedPrimitiveSet??_i;(!Number.isSafeInteger(s)||s<1)&&c("MANIFEST_INVALID"),r>s&&c("PRIMITIVE_SET_UNSUPPORTED"),L(e.activation)||c("MANIFEST_INVALID"),S(e.activation,["kind","language"]),e.activation.kind!=="fenced-code"&&c("MANIFEST_INVALID");let a=tt(W(e.activation,"language")),p=$i(e.schema),l=Ki(e.layout,p);return {manifestVersion:1,pluginId:n,definitionId:i,version:o,primitiveSet:r,activation:{kind:"fenced-code",language:a},schema:p,layout:l}}function sr(e,t={}){return L(e)||c("MANIFEST_INVALID"),e.manifestVersion===2?ir(e,t):or(e,t)}function te(e,t={}){try{return sr(e,t)}catch(n){if(n instanceof V)throw n;return c("MANIFEST_INVALID")}}function pt(e,t={}){let n=te(e,t);return n.manifestVersion===2?rr(n):n}var qt="SKILL.md",dr=/^---\s*\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;function Zt(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function ur(e){return e.isDirectory()||e.isSymbolicLink()}function rn(e){try{return existsSync(e)&&statSync(e).isDirectory()}catch{return false}}function dt(e){let t;try{t=readFileSync(e,"utf8");}catch{return {frontmatter:{},readable:false,valid:false,hasFrontmatter:false}}let n=t.match(dr);if(!n)return {frontmatter:{},readable:true,valid:true,hasFrontmatter:false};try{let i=load(n[1]??"");if(!Zt(i))return {frontmatter:{},readable:!0,valid:!1,hasFrontmatter:!0};let o=Zt(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 fr(e){return [join(e,qt),join(e,"skill",qt)]}function Qt(e,t){if(!rn(e))return null;for(let n of fr(e)){if(!existsSync(n))continue;let o=dt(n).frontmatter;return {name:o.name??t,...o.version===void 0?{}:{version:o.version},...o.description===void 0?{}:{description:o.description},skillMdPath:n,dir:e}}return null}function en(e){try{return readdirSync(e,{withFileTypes:!0}).filter(ur)}catch{return []}}function tn(e,t,n){!e||t.has(e.name)||(t.add(e.name),n.push(e));}function on(e){let t=[],n=new Set;for(let i of e)if(rn(i))for(let o of en(i)){if(o.name.startsWith("@")){let r=join(i,o.name);for(let s of en(r))tn(Qt(join(r,s.name),s.name),n,t);continue}tn(Qt(join(i,o.name),o.name),n,t);}return t.sort((i,o)=>i.name.localeCompare(o.name))}var Ar=/^[0-9a-f]{64}$/;function Ue(e){let n=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||Object.values(e.actions).some(o=>o.resultProjection!==void 0)?{id:e.id,version:e.version,renderer:e.renderer,surfaces:e.surfaces,stateProjection:e.stateProjection,...e.dataPaths===void 0?{}:{dataPaths:e.dataPaths},...e.usage===void 0?{}:{usage:e.usage},...e.detailPanel===void 0?{}:{detailPanel:e.detailPanel},...e.displayModes===void 0?{}:{displayModes:e.displayModes},...e.sourceHash===void 0?{}:{sourceHash:e.sourceHash},actions:e.actions}:e.sourceHash===void 0?{id:e.id,version:e.version,actions:e.actions}:{id:e.id,version:e.version,sourceHash:e.sourceHash,actions:e.actions},i=re(n);return createHash("sha256").update(Q(i)).digest("hex")}function ut(e){if(!/^\d+$/.test(String(e.version))||e.version<1||e.id.length<1||e.id.length>128)throw new N("DEFINITION_UNSUPPORTED","UI definition is invalid");if(e.sourceHash!==void 0&&(typeof e.sourceHash!="string"||!Ar.test(e.sourceHash)))throw new N("DEFINITION_UNSUPPORTED","UI definition source hash is invalid");if(!/^[0-9a-f]{64}$/.test(e.hash)||Ue(e)!==e.hash)throw new N("DEFINITION_UNSUPPORTED","UI definition hash is invalid");for(let[t,n]of Object.entries(e.actions)){if(!t||!Array.isArray(n.capabilities)||n.capabilities.some(i=>!Ir(i)))throw new N("DEFINITION_UNSUPPORTED","UI action declaration is invalid");if(n.confirmation!==void 0&&n.confirmation!=="none"&&n.confirmation!=="native")throw new N("DEFINITION_UNSUPPORTED","UI action confirmation is invalid");if(n.inputKeys&&(!Array.isArray(n.inputKeys)||n.inputKeys.some(i=>typeof i!="string"||!i)))throw new N("DEFINITION_UNSUPPORTED","UI action input declaration is invalid");if(n.dataInputs!==void 0&&(!Array.isArray(n.dataInputs)||new Set(n.dataInputs).size!==n.dataInputs.length||n.dataInputs.some(i=>typeof i!="string"||!i||n.inputKeys!==void 0&&!n.inputKeys.includes(i))))throw new N("DEFINITION_UNSUPPORTED","UI action data input declaration is invalid");n.resultProjection&&sn(n.resultProjection);}if(e.renderer!==void 0&&(!e.renderer||e.renderer.length>128))throw new N("DEFINITION_UNSUPPORTED","UI definition renderer is invalid");if(e.surfaces&&(!Array.isArray(e.surfaces)||e.surfaces.some(t=>!t||t.length>64)))throw new N("DEFINITION_UNSUPPORTED","UI definition surfaces are invalid");if(e.usage!==void 0&&e.usage!=="card"&&e.usage!=="window")throw new N("DEFINITION_UNSUPPORTED","UI definition usage is invalid");if(e.detailPanel!==void 0&&typeof e.detailPanel!="boolean")throw new N("DEFINITION_UNSUPPORTED","UI definition detailPanel is invalid");if(e.displayModes&&(!Array.isArray(e.displayModes)||e.displayModes.length===0||new Set(e.displayModes).size!==e.displayModes.length||e.displayModes.some(t=>t!=="inline"&&t!=="floating"&&t!=="focused")))throw new N("DEFINITION_UNSUPPORTED","UI definition displayModes are invalid");if(e.usage==="card"&&e.displayModes!==void 0)throw new N("DEFINITION_UNSUPPORTED","Card definitions cannot declare displayModes");if(e.usage==="window"&&e.detailPanel!==void 0)throw new N("DEFINITION_UNSUPPORTED","Window definitions cannot declare detailPanel");if(e.stateProjection&&sn(e.stateProjection),e.dataPaths!==void 0){let t=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(n=>typeof n!="string"||!/^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)*$/.test(n)||n.split(".").some(i=>t.has(i))||!(e.stateProjection?.allow??[]).some(i=>oe(n,i))))throw new N("DEFINITION_UNSUPPORTED","UI definition dataPaths are invalid")}}function sn(e){if(!Array.isArray(e.allow)||e.allow.some(t=>!/^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)*$/.test(t)))throw new N("DEFINITION_UNSUPPORTED","UI projection policy is invalid")}function Ir(e){return e.length>0&&e.length<=128&&e!=="*"&&e!=="all"&&!/[/*]/.test(e)}var Z=class extends Error{constructor(n,i=n){super(i);this.code=n;}code;name="McpAppContractError"};function ft(e,t=e){throw new Z(e,t)}var an=["crewx_app_terminal_connect","crewx_app_html_viewer_open"];var At=8*1024*1024;new Set(an);var gr=4;function yt(e,t=0){try{let n=re(e,t);return n.type!==void 0&&n.type!=="object"&&ft("TOOL_INVALID","MCP App inputSchema must describe an object"),n}catch(n){if(n instanceof Z)throw n;ft("TOOL_INVALID","MCP App inputSchema must be projection-safe JSON");}}function cn(e){if(e.length===0)return yt({type:"object",properties:{},additionalProperties:false});let t=e.map(i=>i.actionId),n=new Map;for(let i of e)n.set(i.actionId,yt(i.inputSchema));return yt(mr(t,n),gr)}function mr(e,t){let n=e.map(i=>({type:"object",properties:{actionId:{type:"string",const:i},input:t.get(i)??{type:"object"}},required:["actionId","input"],additionalProperties:false}));return Object.freeze({type:"object",oneOf:Object.freeze(n),properties:Object.freeze({actionId:Object.freeze({type:"string",enum:Object.freeze([...e])}),input:Object.freeze({type:"object"})}),required:Object.freeze(["actionId","input"]),additionalProperties:false})}var h=class extends Error{constructor(n){super(n);this.code=n;}code;name="AppDiscoveryFsError"},yn=constants.O_NOFOLLOW,Tr=constants.O_NONBLOCK,Pr=constants.O_RDONLY|(yn??0)|(Tr??0);function J(e){let t=typeof e=="object"&&e!==null&&"code"in e?String(e.code):"";return t==="ENOENT"?new h("NOT_FOUND"):t==="ELOOP"?new h("PATH_ESCAPED"):t==="EFBIG"||t==="EOVERFLOW"?new h("LIMIT_EXCEEDED"):t==="EACCES"||t==="EPERM"||t==="ENOTDIR"?new h("READ_DENIED"):new h("READ_DENIED")}function Dr(e){if(typeof e!="string"||e.length===0||!isAbsolute(e))throw new h("READ_DENIED")}function pn(e){if(typeof e!="string"||isAbsolute(e)||/[\\\u0000]/.test(e))throw new h("PATH_ESCAPED");if(e==="")return [];let t=e.split("/");if(t.some(n=>n.length===0||n==="."||n===".."))throw new h("PATH_ESCAPED");return t}function Re(e,t){let n=relative(e,t);return n===""||n!==".."&&!n.startsWith(`..${sep}`)&&!isAbsolute(n)}function Oe(e){return {dev:e.dev,ino:e.ino,size:e.size,mtimeNs:e.mtimeNs,ctimeNs:e.ctimeNs}}function mt(e,t){return e.dev===t.dev&&e.ino===t.ino}function An(e,t){return mt(e,t)&&e.size===t.size&&e.mtimeNs===t.mtimeNs&&e.ctimeNs===t.ctimeNs}async function ln(e){Dr(e);let t,n;try{t=await realpath(e),n=await stat(t,{bigint:!0});}catch(i){throw J(i)}if(!n.isDirectory())throw new h("READ_DENIED");return {realRoot:t,identity:Oe(n)}}async function br(e,t,n){if(n.length<2||n[0]!=="apps"&&n[0]!=="skills")return;let i,o;try{if(i=resolve(e,n[0],n[1]),o=await realpath(i),!(await stat(o,{bigint:!0})).isDirectory())throw new h("READ_DENIED")}catch(r){throw r instanceof h?r:J(r)}if(!Re(t,o))throw new h("PATH_ESCAPED");return o}async function dn(e,t,n,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 J(a)}if(!Re(t,r)||n!==void 0&&!Re(n,r))throw new h("PATH_ESCAPED");if(!o.isFile()||!s.isFile())throw new h("READ_DENIED");if(!mt(i,o)||!mt(i,s)||i.dev!==s.dev)throw new h("PATH_ESCAPED")}async function It(e,t){let n,i;try{n=await realpath(e),i=await stat(n,{bigint:!0});}catch{throw new h("PATH_ESCAPED")}if(n!==t.realRoot||!An(t.identity,Oe(i)))throw new h("PATH_ESCAPED")}function Nr(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 we=class{async listDirectory(t,n){let i=pn(n),o=await ln(t),r=resolve(t,...i),s,a;try{s=await realpath(r),a=await stat(s,{bigint:!0});}catch(p){let l=J(p);if(l.code==="NOT_FOUND")return [];throw l}if(!Re(o.realRoot,s)||!a.isDirectory())throw new h("PATH_ESCAPED");try{let p=await readdir(s,{withFileTypes:!0,encoding:"utf8"});return await It(t,o),p.map(Nr)}catch(p){let l=J(p);if(l.code==="NOT_FOUND")return [];throw l}}async readdir(t,n){return this.listDirectory(t,n)}async readDirectory(t,n){return this.listDirectory(t,n)}async readVerifiedFile(t,n,i){if(!Number.isSafeInteger(i)||i<0)throw new h("READ_DENIED");if(yn===void 0)throw new h("UNSUPPORTED");let o=pn(n),r=await ln(t),s=resolve(t,...o),a=relative(t,s);if(a===".."||a.startsWith(`..${sep}`)||isAbsolute(a))throw new h("PATH_ESCAPED");let p;try{p=await open(s,Pr);}catch(l){throw J(l)}try{let l;try{let I=await p.stat({bigint:!0});l=Oe(I);}catch(I){throw J(I)}if(l.size>BigInt(i))throw new h("LIMIT_EXCEEDED");if(l.size>BigInt(Number.MAX_SAFE_INTEGER))throw new h("LIMIT_EXCEEDED");await It(t,r);let u=await br(t,r.realRoot,o);await dn(s,r.realRoot,u,l);let d=new Uint8Array(new ArrayBuffer(Number(l.size))),f=0;for(;f<d.byteLength;){let I;try{I=(await p.read(d,f,d.byteLength-f,f)).bytesRead;}catch(M){throw J(M)}if(I<=0)throw new h("IDENTITY_CHANGED");f+=I;}let A;try{let I=await p.stat({bigint:!0});A=Oe(I);}catch(I){throw J(I)}if(!An(l,A))throw new h("IDENTITY_CHANGED");return await dn(s,r.realRoot,u,A),await It(t,r),new Uint8Array(d)}finally{await p.close().catch(()=>{});}}async readFileVerified(t,n,i){return this.readVerifiedFile(t,n,i)}},In=new we;var _t="crewx_local_app_";function Mr(e){if(typeof e!="string"||!ae.test(e))throw new TypeError("pluginId must be a safe UI plugin identifier");let t=`${_t}${e}`.length+7<=128?e:`hash_${createHash("sha256").update(e,"utf8").digest("hex")}`;return {read:`${_t}${t}_read`,action:`${_t}${t}_action`}}var Tt=["apps","skills"],Sr=new TextDecoder("utf-8",{fatal:true});function Pt(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;try{let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}catch{return false}}function gn(e){return typeof e=="string"&&ae.test(e)?e:void 0}function Lr(e,t){return t.length===0||t==="."||t===".."||/[\\/\u0000]/.test(t)?e:`${e}/${t}`}function Ur(e){return e.length>0&&e!=="."&&e!==".."&&!/[\\/\u0000]/.test(e)}function Pn(e,t){let n=new TextEncoder().encode(e),i=new TextEncoder().encode(t),o=Math.min(n.byteLength,i.byteLength);for(let r=0;r<o;r+=1){let s=n[r]-i[r];if(s!==0)return s}return n.byteLength-i.byteLength}function Rr(e){if(typeof e=="string")return {name:e,kind:"directory"};if(e===null||typeof e!="object")return null;let t=e;if(typeof t.name!="string")return null;if(t.kind==="file"||t.kind==="directory"||t.kind==="symlink"||t.kind==="other")return {name:t.name,kind:t.kind};if(t.type==="file"||t.type==="directory"||t.type==="symlink"||t.type==="other")return {name:t.name,kind:t.type};let n=t.isDirectory;if(typeof n=="function"&&n.call(e))return {name:t.name,kind:"directory"};let i=t.isSymbolicLink;if(typeof i=="function"&&i.call(e))return {name:t.name,kind:"symlink"};let o=t.isFile;return typeof o=="function"&&o.call(e)?{name:t.name,kind:"file"}:{name:t.name,kind:"other"}}function Or(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(t=>Number.isInteger(t)&&t>=0&&t<=255))return Uint8Array.from(e);throw new TypeError("filesystem port returned an invalid byte array")}function Dn(e){return Sr.decode(e)}function bn(e){return JSON.parse(Dn(e))}function wr(e){if(!Pt(e))return;let t=gn(e.pluginId);if(!t)return;let n=gn(e.definitionId),i=e.version,o=n&&Number.isSafeInteger(i)&&i>=1?`${n}\0${String(i)}`:void 0;return {pluginId:t,...o===void 0?{}:{definitionKey:o}}}function kr(e){let t=bn(e);return {value:t,identity:wr(t)}}function Dt(e,t,n,i){let o={code:e,...i===void 0?{}:{pluginId:i},source:t,relativePath:n};return Object.freeze(o)}function mn(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 ne(e){if(e instanceof h)return mn(e.code);if(e!==null&&typeof e=="object"&&"code"in e){let t=e.code;if(typeof t=="string")return mn(t)}}function _e(e,t){return e==="PATH_ESCAPED"||e==="IDENTITY_CHANGED"||e==="TOCTOU"?"PATH_ESCAPED":e==="LIMIT_EXCEEDED"?"LIMIT_EXCEEDED":t==="manifest"&&e==="NOT_FOUND"?"MANIFEST_MISSING":t==="entry"?"ENTRY_INVALID":t==="initial"?"INITIAL_STATE_INVALID":"MANIFEST_INVALID"}function hn(e){switch(e.code){case "MANIFEST_INVALID":case "PRIMITIVE_UNKNOWN":case "PRIMITIVE_SET_UNSUPPORTED":case "SCHEMA_TYPE_UNSUPPORTED":case "TOKEN_INVALID":case "UNSAFE_VALUE":return "MANIFEST_INVALID";case "LIMIT_EXCEEDED":return "LIMIT_EXCEEDED";case "INITIAL_STATE_INVALID":return "INITIAL_STATE_INVALID";default:return Nn("UiPluginValidationError",e.code)}}function Nn(e,t){throw new Error(`Unmapped ${e} code: ${String(t)}`)}function Et(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 Nn("McpAppContractError",e)}}function _n(e,t){let n=t();return Number.isFinite(n)&&Number.isFinite(e)&&n-e<=5e3}function xr(){return globalThis.performance?.now()??Date.now()}function le(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let t of Object.values(e))le(t);return Object.freeze(e)}function En(e){return Object.freeze(Array.from(e))}function Cr(e,t,n){let i=createHash("sha256"),o=new TextEncoder().encode(Q(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(t.byteLength),i.update(t),r(n.byteLength),i.update(n),i.digest("hex")}function Vr(e,t){let n={...e.definition,sourceHash:t},i={...n,hash:Ue(n)};try{ut(i);}catch{throw new V("MANIFEST_INVALID","normalized definition is invalid")}return i}function Fr(e){return e.actions.some(t=>t.backend.type==="core"&&t.backend.handler!=="state.set")}function vr(e){if(typeof e.readVerifiedFile=="function")return e.readVerifiedFile;if(typeof e.readFileVerified=="function")return e.readFileVerified}function jr(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 Ce(e,t,n,i){let o=vr(e);if(!o)throw new h("READ_DENIED");return Or(await o.call(e,t,n,i))}async function Hr(e,t,n){let i=jr(e);if(!i)throw new h("READ_DENIED");let o=await i.call(e,t,n);if(!Array.isArray(o))throw new h("READ_DENIED");return o.map(Rr).filter(r=>r!==null)}function Br(e){let t=[];for(let n of [e.reserved,e.builtin])n&&t.push(n);return e.builtins&&"listMcpApps"in e.builtins?t.push(Tn(e.builtins)):e.builtins&&t.push(e.builtins),e.builtinCatalog&&t.push(Tn(e.builtinCatalog)),t.push({...e.reservedAppIds===void 0?{}:{appIds:e.reservedAppIds},...e.reservedDefinitionIds===void 0?{}:{definitionIds:e.reservedDefinitionIds},...e.reservedToolNames===void 0?{}:{toolNames:e.reservedToolNames}}),t}function Tn(e){let t=[],n=[],i=[];for(let o of e.listMcpApps())typeof o.appId=="string"&&t.push(o.appId),o.definition&&typeof o.definition.id=="string"&&n.push(o.definition.id);for(let o of e.listMcpAppTools())typeof o.name=="string"&&i.push(o.name);return {appIds:t,definitionIds:n,toolNames:i}}function he(e,t){e.diagnostic||(e.diagnostic=Dt(t,e.source,e.relativePath,e.identity?.pluginId));}function zr(e){let t=new Map,n=new Map;for(let i of e){if(i.identity?.pluginId){let o=t.get(i.identity.pluginId)??[];o.push(i),t.set(i.identity.pluginId,o);}if(i.identity?.definitionKey){let o=n.get(i.identity.definitionKey)??[];o.push(i),n.set(i.identity.definitionKey,o);}}for(let i of [...t.values(),...n.values()]){let o=i.filter(r=>r.source==="apps");if(o.length>0){if(o.length>1)for(let r of o)he(r,"DUPLICATE_ID");for(let r of i.filter(s=>s.source==="skills"))he(r,"DUPLICATE_ID");continue}if(i.length>1)for(let r of i)he(r,"DUPLICATE_ID");}}function Gr(e,t){let n=new Set,i=new Set,o=new Set;for(let r of Br(t)){for(let s of r.appIds??[])typeof s=="string"&&n.add(s);for(let s of r.definitionIds??[])typeof s=="string"&&i.add(s);for(let s of r.toolNames??[])typeof s=="string"&&o.add(s);}for(let r of e){let s=r.candidate;if(!s)continue;if(n.has(s.pluginId)||i.has(s.definitionId)){he(r,"RESERVED_ID");continue}[s.toolNames.read,s.toolNames.action].filter(p=>p!==void 0).some(p=>o.has(p))&&he(r,"DUPLICATE_ID");}}function $r(e){return [...e].sort((t,n)=>{let i=Tt.indexOf(t.source)-Tt.indexOf(n.source);return i!==0?i:Pn(t.relativePath,n.relativePath)})}function b(e,t){e.diagnostic=Dt(t,e.source,e.relativePath,e.identity?.pluginId);}async function Wr(e,t,n,i){if(i.byteLength>262144){b(n,"LIMIT_EXCEEDED");return}let o;try{o=kr(i);}catch{b(n,"MANIFEST_INVALID");return}if(n.identity=o.identity,Pt(o.value)&&o.value.builtinOnly===true){b(n,"RESERVED_ID");return}let r;try{let _=te(o.value,{mode:"local"});if(_.manifestVersion!==2)throw new V("MANIFEST_INVALID","workspace App requires v2");r=_;}catch(_){if(_ instanceof V){b(n,hn(_));return}if(_ instanceof Z){b(n,Et(_.code));return}if(Pt(_)&&typeof _.code=="string"){b(n,Et(_.code));return}throw _}if(n.identity={pluginId:r.pluginId,definitionKey:`${r.definitionId}\0${String(r.version)}`},r.actions.length>0)try{cn(r.actions.map(_=>({actionId:_.actionId,inputSchema:_.inputSchema})));}catch(_){if(_ instanceof Z){b(n,Et(_.code));return}throw _}let s=`${n.relativePath}/ui/index.html`,a;try{a=await Ce(t,e,s,At);}catch(_){b(n,_e(ne(_),"entry"));return}if(a.byteLength>At){b(n,"LIMIT_EXCEEDED");return}let p;try{p=Dn(a);}catch{b(n,"ENTRY_INVALID");return}if(a.byteLength===0||p.length===0){b(n,"ENTRY_INVALID");return}let l=createHash("sha256").update(a).digest("hex");if(r.entryHash!==void 0&&r.entryHash!==l){b(n,"ENTRY_INVALID");return}let u={},d,f;if(r.initialState!==void 0){let _=`${n.relativePath}/ui/state.json`;try{d=await Ce(t,e,_,65536);}catch(O){b(n,_e(ne(O),"initial"));return}if(d.byteLength>65536){b(n,"LIMIT_EXCEEDED");return}try{let O=bn(d),kt=r.dataPaths??[],ai=ct(O,kt);u=re(ai,0,kt),Ke(u);}catch{b(n,"INITIAL_STATE_INVALID");return}if(f=createHash("sha256").update(d).digest("hex"),r.initialState.hash!==void 0&&r.initialState.hash!==f){b(n,"INITIAL_STATE_INVALID");return}}let A={...r,entryHash:l,...r.initialState===void 0?{}:{initialState:{path:"ui/state.json",hash:f}}},I=pt(A),M=Cr(A,a,d??new Uint8Array),G;try{G=Vr(I,M);}catch(_){if(_ instanceof V){b(n,hn(_));return}throw _}let F=Mr(r.pluginId),m=r.actions.length===0?{read:F.read}:F,g=le(I),H=le(A),$=le(G),w=le({...I.handlers}),D=En(a),B=d===void 0?void 0:En(d),wt=Object.freeze({entry:Object.freeze({path:"ui/index.html",hash:l,bytes:D}),...B===void 0?{}:{initialState:Object.freeze({path:"ui/state.json",hash:f,bytes:B})}}),Te={appId:r.pluginId,pluginId:r.pluginId,definitionId:r.definitionId,version:r.version,source:n.source,relativePath:n.relativePath,manifest:H,normalized:g,name:r.name,description:r.description,...r.icon===void 0?{}:{icon:r.icon},...r.tone===void 0?{}:{tone:r.tone},definition:$,handlers:w,resources:wt,html:p,entryBytes:D,entryHash:l,initialState:le(u),...B===void 0?{}:{initialStateBytes:B},...f===void 0?{}:{initialStateHash:f},sourceHash:M,toolNames:Object.freeze(m)};n.candidate=Object.freeze(Te),Fr(r)&&b(n,"EXEC_DENIED");}async function Jr(e,t,n){try{return await Ce(t,e,`${n.relativePath}/ui-plugin.json`,262144)}catch(i){if(ne(i)==="NOT_FOUND")return;b(n,_e(ne(i),"manifest"));return}}function Kr(e,t){let n=$r(e);zr(n);let i=Object.freeze(n.filter(s=>s.candidate!==void 0&&s.diagnostic===void 0).map(s=>s.candidate)),o=Object.freeze(n.filter(s=>s.diagnostic!==void 0).map(s=>s.diagnostic)),r={apps:i,diagnostics:o,complete:t===void 0,...t===void 0?{}:{incompleteReason:t}};return Object.defineProperty(r,"candidates",{configurable:false,enumerable:false,get:()=>i}),Object.freeze(r)}function Xr(e){if(e===null||typeof e!="object"&&typeof e!="function")return false;let t=e;return typeof t.readVerifiedFile=="function"||typeof t.readFileVerified=="function"||typeof t.listDirectory=="function"||typeof t.readDirectory=="function"||typeof t.readdir=="function"}function Yr(e,t){if(Xr(e))return {fs:e,options:{}};let n=e??t??{};return {fs:n.filesystem??n.fileSystem??n.fs??In,options:n}}async function Mn(e,t,n){if(typeof e!="string"||e.length===0)throw new TypeError("workspaceRoot must be explicit");let{fs:i,options:o}=Yr(t,n),r=o.clock??xr,s=r(),a=[],p=0,l;for(let u of Tt){let d;try{d=await Hr(i,e,u);}catch(A){if(ne(A)==="NOT_FOUND")continue;a.push({source:u,name:"",relativePath:u,diagnostic:Dt(_e(ne(A),"manifest"),u,u)});continue}let f=d.filter(A=>A.kind==="directory"||A.kind==="symlink").filter(A=>Ur(A.name)).map(A=>({source:u,name:A.name,relativePath:Lr(u,A.name)})).sort((A,I)=>Pn(A.relativePath,I.relativePath));for(let A of f){let I={...A};a.push(I);let M;if(u==="skills"&&(M=await Jr(e,i,I),M===void 0))continue;if(p>=64){b(I,"LIMIT_EXCEEDED");continue}if(A.relativePath.split("/").length-1>2){b(I,"LIMIT_EXCEEDED");continue}if(l!==void 0||!_n(s,r)){b(I,"LIMIT_EXCEEDED"),l="time_limit";continue}if(p+=1,M===void 0)try{M=await Ce(i,e,`${I.relativePath}/ui-plugin.json`,262144);}catch(F){b(I,_e(ne(F),"manifest"));continue}await Wr(e,i,I,M),I.diagnostic===void 0&&p<64&&!_n(s,r)&&(l="time_limit");}}return Gr(a,o),Kr(a,l)}var Zr=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/;function Fe(e){let t="screenHash"in e?e.screenHash:void 0,i=("skillHash"in e?e.skillHash:void 0)??(e.relativePath!==void 0&&e.fileBytes!==void 0?Qr(e.relativePath,e.fileBytes):void 0);if(t!==void 0&&i!==void 0){let o=JSON.stringify({screenHash:t,skillHash:i});return createHash("sha256").update(o,"utf8").digest("hex")}if(t!==void 0)return t;if(i!==void 0)return i;throw new TypeError("App definition hash input must contain a screenHash or skill bytes")}function Qr(e,t){let n=new TextEncoder().encode(ve(e)),i=eo(t),o=new Uint8Array(n.byteLength+1+i.byteLength);return o.set(n,0),o[n.byteLength]=0,o.set(i,n.byteLength+1),createHash("sha256").update(o).digest("hex")}function eo(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(t=>Number.isInteger(t)&&t>=0&&t<=255))return Uint8Array.from(e);throw new TypeError("fileBytes must be UTF-8 text or bytes")}function ve(e){if(typeof e!="string"||e.length===0||isAbsolute(e)||/[\\\u0000]/.test(e))throw new TypeError("relative path must be package-relative");let t=e.split("/").filter(n=>n.length>0&&n!==".").join("/");if(!t||t.split("/").some(n=>n===".."))throw new TypeError("relative path must stay inside the package");return t}function Ve(e,t){let n=new TextEncoder().encode(e),i=new TextEncoder().encode(t),o=Math.min(n.byteLength,i.byteLength);for(let r=0;r<o;r+=1){let s=n[r]-i[r];if(s!==0)return s}return n.byteLength-i.byteLength}function Un(e,t){let n=relative(e,t).split(sep).join("/");return !n||n===".."||n.startsWith("../")||isAbsolute(n)?null:ve(n)}function to(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 Rn(e){return Object.freeze({packageRoot:e})}function no(e){return Object.freeze({id:e.definition.id,version:e.definition.version,hash:e.definition.hash,usage:e.definition.usage??q,...e.definition.detailPanel===void 0?{}:{detailPanel:e.definition.detailPanel},...e.definition.displayModes===void 0?{}:{displayModes:e.definition.displayModes}})}function On(e){return {capabilities:Object.freeze([...e]),origin:"local",ownership:"unknown",shareability:"unknown",sharingAvailability:"unavailable"}}function io(e,t){let n=e.candidate,i=t?["screen","skill"]:["screen"],o=no(n),r=Fe(t?{screenHash:o.hash,skillHash:t.skillHash}:{screenHash:o.hash}),s=n.description||t?.skill.description||"",a=String(n.version),p={appId:n.pluginId,name:n.name,description:s,version:a,...On(i),definition:o,...t===void 0?{}:{skillName:t.skill.name},localDefinitionRef:Rn(e.packageRoot),definitionHash:r};return {packageRoot:e.packageRoot,source:n.source,appId:p.appId,capabilities:i,summary:Object.freeze(p)}}function ro(e){let t=oo(e.skill.name),n={appId:t,name:e.skill.name,description:e.skill.description??"",...e.skill.version===void 0?{}:{version:e.skill.version},...On(["skill"]),skillName:e.skill.name,localDefinitionRef:Rn(e.packageRoot),definitionHash:Fe({skillHash:e.skillHash})};return {packageRoot:e.packageRoot,source:e.source,appId:t,capabilities:["skill"],summary:Object.freeze(n)}}function oo(e){return `skill.${e.replace(/^@/,"").replace(/\//g,".").replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,122)||"unnamed"}`}function x(e,t,n,i){return Object.freeze({code:e,source:t,relativePath:so(n),...i===void 0?{}:{appId:i}})}function so(e){if(typeof e!="string"||e.length===0||isAbsolute(e)||/[\\\u0000]/.test(e))return "<unknown>";let t=e.split("/").filter(n=>n.length>0&&n!==".").join("/");return t.split("/").some(n=>n==="..")?"<unknown>":t}function ao(e){return x(e.code,e.source,e.relativePath,e.pluginId)}function co(e,t){let n=Un(e,t.dir);if(!n)return {diagnostic:x("PATH_ESCAPED","node_modules","node_modules")};let i=to(n);if(!i)return {diagnostic:x("PATH_ESCAPED","node_modules",n)};let o=dt(t.skillMdPath);if(!o.readable)return {diagnostic:x("SKILL_READ_FAILED",i,n)};if(!o.valid)return {diagnostic:x("SKILL_INVALID",i,n)};let r=po(t.dir,t.skillMdPath);if(!r)return {diagnostic:x("PATH_ESCAPED",i,n)};try{let s=new Uint8Array(readFileSync(t.skillMdPath));return {skill:t,packageRoot:n,relativeSkillPath:r,skillHash:Fe({relativePath:r,fileBytes:s}),source:i}}catch{return {diagnostic:x("SKILL_READ_FAILED",i,n)}}}function po(e,t){let n=relative(e,t).split(sep).join("/");try{return ve(n)}catch{return null}}function lo(e){if(!Zr.test(e.appId))return {diagnostic:x("BUILTIN_INVALID","builtin",`builtin/${e.appId||"unknown"}`)};let t=e.definition===void 0?void 0:{id:e.definition.id,version:e.definition.version,hash:e.definition.hash,usage:e.definition.usage??q,...e.definition.detailPanel===void 0?{}:{detailPanel:e.definition.detailPanel},...e.definition.displayModes===void 0?{}:{displayModes:e.definition.displayModes}},n=t?.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,...t===void 0?{}:{version:String(t.version),definition:t},capabilities:["screen"],origin:"builtin",ownership:"unknown",shareability:"forbidden",sharingAvailability:"unavailable",definitionHash:n};return {source:"builtin",appId:e.appId,summary:Object.freeze(i)}}function uo(e){return e.builtinCatalog}function fo(e){let t=e.packageRoot??e.relativePath??e.packageRootPath;if(t===void 0)return null;try{return ve(t)}catch{return null}}function yo(e){let t=e.marketplaceContentId;return typeof t=="string"&&t.length>0?t:void 0}function Ao(e,t,n){let i=t.installed??[],o=new Map;for(let s of i){let a=fo(s);if(!a){n.push(x("INSTALLED_IDENTITY_MISMATCH","installed","installed"));continue}let p=o.get(a);if(p&&JSON.stringify(p)!==JSON.stringify(s)){n.push(x("INSTALLED_IDENTITY_MISMATCH","installed",a));continue}o.set(a,s);}let r=new Map;for(let s of e)s.packageRoot!==void 0&&r.set(s.packageRoot,s);for(let[s,a]of o){let p=r.get(s);if(!p){n.push(x("INSTALLED_MISSING","installed",s,a.appId));continue}let l=yo(a);if(!l){n.push(x("INSTALLED_CONTENT_ID_MISSING","installed",s,a.appId));continue}if(a.appId!==void 0&&a.appId!==p.appId||a.definitionHash!==void 0&&a.definitionHash!==p.summary.definitionHash){n.push(x("INSTALLED_IDENTITY_MISMATCH","installed",s,a.appId));continue}let u={...p.summary,origin:"installed",...a.slug===void 0?{}:{slug:a.slug},marketplaceContentId:l},d=e.indexOf(p);d>=0&&(e[d]={...p,summary:Object.freeze(u)});}}function Io(e,t){let n=new Map;for(let o of e){let r=n.get(o.appId)??[];r.push(o),n.set(o.appId,r);}let i=new Set;for(let o of n.values())if(!(o.length<2))for(let r of o)i.add(r),t.push(x("DUPLICATE_ID",r.source,r.packageRoot??`builtin/${r.appId}`,r.appId));return e.filter(o=>!i.has(o))}function go(e,t){return e.filter(n=>!(n.code==="MANIFEST_MISSING"&&t.has(n.relativePath))).map(ao)}function mo(e){return e.filesystem}function ho(e,t){let n=mo(e);return {...n===void 0?{}:{filesystem:n},...t===void 0?{}:{builtinCatalog:t}}}async function wn(e,t={}){if(typeof e!="string"||e.length===0)throw new TypeError("workspaceRoot must be explicit");let n=uo(t),i=await Mn(e,ho(t,n)),o=[join(e,"skills"),join(e,"node_modules"),join(e,"apps")],r=[],s=[],a=[],p=new Set;for(let m of o)for(let g of on([m])){let H=Un(e,g.dir);(H===null||!p.has(H))&&(a.push(g),H!==null&&p.add(H));}for(let m of a){let g=co(e,m);"diagnostic"in g?r.push(g.diagnostic):s.push(g);}let l=new Map;for(let m of i.apps??i.candidates??[])l.set(m.relativePath,{candidate:m,packageRoot:m.relativePath});let u=new Map(s.map(m=>[m.packageRoot,m])),d=[];for(let m of l.values()){let g=io(m,u.get(m.packageRoot));d.push({packageRoot:g.packageRoot,source:g.source,appId:g.appId,summary:g.summary});}let f=new Set(l.keys());for(let m of s){if(f.has(m.packageRoot))continue;let g=ro(m);d.push({packageRoot:g.packageRoot,source:g.source,appId:g.appId,summary:g.summary});}let A=[...go(i.diagnostics,new Set(s.map(m=>m.packageRoot))),...r],I=[];if(n)for(let m of n.listMcpApps()){let g=lo(m);"diagnostic"in g?A.push(g.diagnostic):I.push(g);}let M=Io([...d,...I],A);Ao(M,t,A);let G=M.map(m=>m.summary).sort((m,g)=>Ve(m.appId,g.appId)),F=[...A].sort((m,g)=>Ve(m.relativePath,g.relativePath)||Ve(m.code,g.code)||Ve(m.appId??"",g.appId??""));return Object.freeze({items:Object.freeze(G),diagnostics:Object.freeze(F)})}function _o(e){let t=o=>o.replace(/[.+^${}()|[\]\\]/g,"\\$&"),i=e.split("/").map(o=>o==="**"?".*":o.split("*").map(t).join("[^/]*"));return new RegExp(`^${i.join("\\/")}$`)}function de(e,t){try{return _o(t).test(e)}catch{return false}}function je(e,...t){let n=e.split("/");if(n.length<t.length)return false;let i=n.length-t.length;return t.every((o,r)=>de(n[i+r],o))}function Eo(e,t){return e.split("/").some(n=>de(n,t))}var kn=[{label:".env*",test:e=>de(e,".env*")},{label:".git/",test:(e,t,n)=>n&&e===".git"},{label:"memory/",test:(e,t,n)=>n&&e==="memory"},{label:"*.key",test:e=>de(e,"*.key")},{label:"*.pem",test:e=>de(e,"*.pem")},{label:"auth.json",test:e=>e==="auth.json"},{label:"node_modules/",test:(e,t,n)=>n&&e==="node_modules"},{label:"conversations/",test:(e,t,n)=>n&&e==="conversations"},{label:".crewx/threads/",test:(e,t,n)=>n&&je(t,".crewx","threads")},{label:".crewx/crewx.db",test:(e,t,n)=>!n&&je(t,".crewx","crewx.db")},{label:".crewx/*.log",test:(e,t,n)=>!n&&je(t,".crewx","*.log")},{label:".crewx/publish/",test:(e,t,n)=>n&&je(t,".crewx","publish")},{label:".crewx/",test:(e,t)=>Eo(t,".crewx")}];function He(e,t,n){for(let i of kn)if(i.test(e,t,n))return i.label;return null}function St(e){let t=[],n=[];function i(o,r,s){let a;try{a=R.readdirSync(o,{withFileTypes:!0});}catch{return}a.sort((p,l)=>p.name.localeCompare(l.name));for(let p of a){let l=r?`${r}/${p.name}`:p.name,u=k.join(o,p.name);if(p.isSymbolicLink()){let d;try{d=R.statSync(u);}catch{n.push({path:l,rule:"symlink"});continue}if(d.isDirectory()){n.push({path:l,rule:s??"symlink-dir"});continue}let f=s??He(p.name,l,false);f?n.push({path:l,rule:f}):n.push({path:l,rule:"symlink"});continue}if(p.isDirectory()){let d=s??He(p.name,l,true);i(u,l,d);continue}if(p.isFile()){let d=s??He(p.name,l,false);d?n.push({path:l,rule:d}):t.push(l);}}}return i(e,"",null),t.sort(),n.sort((o,r)=>o.path<r.path?-1:o.path>r.path?1:0),{included:t,excluded:n}}var To=[{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 Po(e){return e.includes(0)}function Lt(e,t,n){let i=[];for(let o of t){let r=k.join(e,o),s;try{let p=n?.get(o);s=p===void 0?R.readFileSync(r):Buffer.from(p);}catch{continue}if(Po(s))continue;s.toString("utf8").split(/\r\n|\r|\n/).forEach((p,l)=>{for(let{rule:u,regex:d}of To)d.test(p)&&i.push({path:o,line:l+1,rule:u});});}return i}var K=class extends Error{constructor(n,i){super(`publish: [${n}]${i?` ${i}`:""}`);this.code=n;}code;name="PublishError"};function y(e,t){return new K(e,t)}var Fn=/^[a-z0-9-]+$/,Do=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/,bo=/^[A-Za-z_][A-Za-z0-9_]*$/;function No(e){let t=k.join(e,"crewx.yaml");if(!R.existsSync(t))return {};let n;try{n=vn.load(R.readFileSync(t,"utf8"));}catch{return {}}if(!n||typeof n!="object")return {};let i=n.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 Mo(e){return Ut.createHash("sha256").update(e).digest("hex")}function jn(e){let t;try{t=R.lstatSync(e);}catch{throw y("PACKAGE_FILE_INVALID",`file is not readable: ${k.basename(e)}`)}if(t.isSymbolicLink())throw y("PACKAGE_SYMLINK","symlink content is not publishable");if(!t.isFile())throw y("PACKAGE_FILE_INVALID","only regular files are publishable");return Ut.createHash("sha256").update(new Uint8Array(R.readFileSync(e))).digest("hex")}function So(e,t){let n=new TextEncoder().encode(e),i=new TextEncoder().encode(t),o=Math.min(n.byteLength,i.byteLength);for(let r=0;r<o;r+=1){let s=n[r]-i[r];if(s!==0)return s}return n.byteLength-i.byteLength}function Hn(e){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||k.posix.isAbsolute(e)||e.split("/").some(t=>t===".."||t.length===0))throw y("PACKAGE_PATH_TRAVERSAL","manifest file path must be a non-empty POSIX relative path")}function Lo(e){if(!/^(?:apps|skills)\/[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(e))throw y("APP_PACKAGE_ROOT_INVALID","packageRoot must be apps/<safe-id> or skills/<safe-id>")}function Bn(e){if(!Do.test(e))throw new Error(`publish: invalid version "${e}" \u2014 must be semver (e.g. 1.0.0)`)}function zn(e,t,n={}){let i=No(e),o=i.name??k.basename(e);if(!Fn.test(o))throw new Error(`publish: invalid name "${o}" \u2014 must match ${Fn} (lowercase letters, numbers, hyphen only)`);let r=n.version??i.version;if(!r)throw new Error("publish: version is required \u2014 set crewx.yaml metadata.version or pass opts.version");Bn(r);let s=Array.isArray(i.requiredEnv)?i.requiredEnv:[],a=[];for(let u of s){if(typeof u!="string"||!bo.test(u))throw new Error(`publish: requiredEnv must contain names only (no values), got "${String(u)}"`);a.push(u);}let p=t.map(u=>(Hn(u),{path:u,sha256:jn(k.join(e,u))})).sort((u,d)=>u.path<d.path?-1:u.path>d.path?1:0),l={name:o,version:r,type:"template",description:i.description??"",files:p,requiredEnv:a};return i.crewxMinVersion&&(l.crewxMinVersion=i.crewxMinVersion),l}function Uo(e){let t=e.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"");if(!t)throw y("APP_PACKAGE_ROOT_INVALID","appId cannot produce a marketplace name");return t}function Gn(e,t){if(Lo(t.packageRoot),!t.version)throw new Error("publish: version is required for App publishing \u2014 pass opts.version");if(Bn(t.version),typeof t.description!="string")throw new Error("publish: App description must be a string");let n=[...new Set(t.capabilities)].sort();if(n.length===0||n.some(s=>s!=="screen"&&s!=="skill"))throw new Error("publish: App capabilities must contain screen or skill");let i=`${t.packageRoot}/`;if(n.includes("screen")){if(typeof t.definitionId!="string"||t.definitionId.length===0)throw y("APP_UI_MANIFEST_INVALID","screen App manifests require definitionId");for(let s of ["ui-plugin.json","ui/index.html"])if(!t.includedFiles.includes(`${i}${s}`))throw y("APP_UI_MANIFEST_INVALID",`screen App is missing ${s}`)}if(n.includes("skill")&&!t.includedFiles.includes(`${i}SKILL.md`))throw y("APP_SKILL_MISSING","skill capability requires package-root SKILL.md");let o=new Set,r=t.includedFiles.map(s=>{if(Hn(s),!s.startsWith(i))throw y("PACKAGE_PATH_TRAVERSAL","App manifest file is outside packageRoot");let a=t.generatedFiles?.get(s);return a!==void 0&&o.add(s),{path:s,sha256:a===void 0?jn(k.join(e,s)):Mo(a),...a===void 0?{}:{generated:true}}}).sort((s,a)=>So(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:Uo(t.appId),version:t.version,type:"app",description:t.description,appId:t.appId,...t.definitionId===void 0?{}:{definitionId:t.definitionId},...t.definitionHash===void 0?{}:{definitionHash:t.definitionHash},capabilities:n,packageRoot:t.packageRoot,files:r,requiredEnv:[]}}function $n(e){return Ut.createHash("sha256").update(e).digest("hex")}function Yn(e,t){if(typeof t!="string"||t.length===0||t.includes("\\")||t.includes("\0")||k.posix.isAbsolute(t)||t.split("/").some(o=>o===".."||o.length===0))throw y("PACKAGE_PATH_TRAVERSAL","archive paths must be non-empty POSIX relative paths");let n=k.resolve(e),i=k.resolve(n,...t.split("/"));if(i!==n&&!i.startsWith(`${n}${k.sep}`))throw y("PACKAGE_PATH_TRAVERSAL","archive path escaped its root");return i}function Wn(e,t){let n=Yn(e,t),i;try{i=R.lstatSync(n);}catch{throw y("PACKAGE_FILE_INVALID","manifest file is missing")}if(i.isSymbolicLink())throw y("PACKAGE_SYMLINK","symlink content is not publishable");if(!i.isFile())throw y("PACKAGE_FILE_INVALID","only regular files are publishable");return new Uint8Array(R.readFileSync(n))}async function qn(e,t,n={}){let i=k.join(e,".crewx","publish");R.mkdirSync(i,{recursive:true});let o=k.join(i,`${t.name}-${t.version}.tgz`),r=k.join(i,`.${t.name}-${t.version}.${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}.tmp.tgz`),s=R.mkdtempSync(k.join(Jn.tmpdir(),"crewx-publish-"));try{let a=new Set,p=[];for(let l of t.files){if(a.has(l.path))throw y("PACKAGE_PATH_TRAVERSAL","manifest contains duplicate file paths");a.add(l.path);let u=n.generatedFiles?.get(l.path);if(l.generated===!0&&u===void 0)throw y("PACKAGE_GENERATED_FILE_MISSING","generated manifest file bytes are missing");if(n.sourceFileHashes?.has(l.path)){let A=Wn(e,l.path);if(n.sourceFileHashes.get(l.path)!==$n(A))throw y("PACKAGE_STAGED_BYTES_MISMATCH","workspace source changed before staging")}let d=u??Wn(e,l.path);if($n(d)!==l.sha256)throw y("PACKAGE_STAGED_BYTES_MISMATCH",`staged bytes differ for ${l.path}`);let f=Yn(s,l.path);R.mkdirSync(k.dirname(f),{recursive:!0}),R.writeFileSync(f,new Uint8Array(d)),p.push(l.path);}R.writeFileSync(k.join(s,"manifest.json"),JSON.stringify(t,null,2)),await Xn.create({gzip:!0,file:r,cwd:s,portable:!0,noMtime:!0},["manifest.json",...p]),R.renameSync(r,o);}finally{try{R.rmSync(r,{force:!0});}catch{}R.rmSync(s,{recursive:true,force:true});}return o}var ue="/api/v1";var wo=201,ko=200,xo=409,Rt=401,Zn={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 Co(){return process.env.WI013_FAKE_UPLOAD==="1"}function Vo(e){let t=gunzipSync(new Uint8Array(e)),n=gzipSync(new Uint8Array(t),{level:1});if(Buffer.compare(new Uint8Array(n),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 n}function Fo(e){return e.replace(/\/+$/,"")}async function Ee(e){try{return await e.json()}catch{return null}}function Qn(e,t,n){let i=e;if(!i||i.success!==true||i.data===void 0)throw new Error(`publish: [E_MALFORMED] ${t} response envelope is malformed (expected { success: true, data }) \u2014 HTTP ${n}`);return i.data}function vo(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(typeof t.contentId=="string"&&t.contentId.length>0)return t.contentId;if(!t.data||typeof t.data!="object"||Array.isArray(t.data))return;let n=t.data;return typeof n.contentId=="string"&&n.contentId.length>0?n.contentId:void 0}function jo(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(typeof t.slug=="string"&&t.slug.length>0)return t.slug;if(!t.data||typeof t.data!="object"||Array.isArray(t.data))return;let n=t.data;return typeof n.slug=="string"&&n.slug.length>0?n.slug:void 0}function ei(e,t){if(!e||typeof e!="object"||Array.isArray(e))return;let n=e,i=n.data&&typeof n.data=="object"&&!Array.isArray(n.data)?n.data:void 0,o=[n.code,n.message,i?.code,i?.message];for(let r of o){if(typeof r!="string"||!Object.prototype.hasOwnProperty.call(Zn,r))continue;let s=r,a=s==="APP_NAME_CONFLICT"?`marketplace name is already in use: ${t}`:void 0;return y(Zn[s],a)}}async function Ho(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 t=Fo(e.baseUrl),n=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(`${t}${ue}/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:n,...s===void 0?{}:{appId:s}})});}catch{throw new Error("publish: [E_NETWORK] Submit request failed (network)")}let p=await Ee(a),l=vo(p),u=jo(p),d=r&&u!==void 0?u:i,f;if(a.status===wo)f="created";else if(r&&a.status===ko){if(l===void 0)throw y("PUBLISH_CONTENT_ID_MISSING","App republish did not return an opaque contentId");f="existing";}else if(a.status===xo){if(r)throw ei(p,i)??y("APP_NAME_CONFLICT",`marketplace name is already in use: ${i}`);f="existing";}else throw a.status===Rt?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 A="not-needed",I=null;if(f==="existing"&&!r){let D;try{D=await fetch(`${t}${ue}/publisher/items`,{method:"GET",headers:{Authorization:`Bearer ${e.accessToken}`}});}catch{throw new Error("publish: [E_NETWORK] Publisher items request failed (network)")}let B=await Ee(D);if(D.status!==200)throw new Error(`publish: [E_HTTP] Publisher items request failed \u2014 HTTP ${D.status}`);let Te=Qn(B,"publisher items",D.status)?.items;if(!Array.isArray(Te))throw new Error(`publish: [E_MALFORMED] Publisher items response is malformed (expected data.items[]) \u2014 HTTP ${D.status}`);let _=Te.find(O=>!O||typeof O!="object"?false:O.slug===i);if(!_||typeof _.version!="string")throw new Error(`publish: [E_MALFORMED] Publisher items response does not contain slug "${i}" \u2014 HTTP ${D.status}`);if(I=_.version,I!==e.manifest.version){let O;try{O=await fetch(`${t}${ue}/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(!O.ok)throw await Ee(O),O.status===Rt?new Error(`publish: [E_AUTH_EXPIRED] Authentication is expired or missing \u2014 please log in again (HTTP ${O.status})`):O.status===403?new Error(`publish: [E_FORBIDDEN] Version update is forbidden; only the item owner can update an existing item (HTTP ${O.status})`):new Error(`publish: [E_HTTP] Version update failed \u2014 HTTP ${O.status}`);A="applied";}}let M=R.readFileSync(e.tgzPath),G=Co()?Vo(M):M,F=new FormData;F.set("archive",new Blob([new Uint8Array(G)],{type:"application/gzip"}),`${d}-${e.manifest.version}.tgz`);let m=r&&l!==void 0?l:i,g;try{g=await fetch(`${t}${ue}/publisher/items/${encodeURIComponent(m)}/upload`,{method:"POST",headers:{Authorization:`Bearer ${e.accessToken}`},body:F});}catch{throw new Error("publish: [E_NETWORK] Upload request failed (network)")}if(g.status===Rt)throw new Error("publish: [E_AUTH_EXPIRED] Authentication is expired or missing \u2014 please log in again (HTTP 401)");if(!g.ok){let D=await Ee(g);if(r){let B=ei(D,d);if(B)throw B}throw new Error(`publish: [E_HTTP] Upload request failed \u2014 HTTP ${g.status}`)}let H=await Ee(g),$=Qn(H,"upload",g.status),w=typeof $.contentId=="string"&&$.contentId.length>0?$.contentId:l;if(r&&w===void 0)throw y("PUBLISH_CONTENT_ID_MISSING","App upload did not return an opaque contentId");return {slug:d,version:e.manifest.version,...w===void 0?{}:{contentId:w},artifactChecksum:$.artifactChecksum,artifactSizeBytes:$.artifactSizeBytes,submitOutcome:f,versionUpdate:A,serverVersionBefore:I}}var Bo=1e4,zo=100*1024*1024;function Ot(e){return Ut.createHash("sha256").update(e).digest("hex")}function Go(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function ze(e,t){if(!t||t.includes("\\")||t.includes("\0")||k.posix.isAbsolute(t)||t.split("/").some(r=>r===".."||r.length===0))throw y("PACKAGE_PATH_TRAVERSAL","workspace file path is not a safe relative path");let n=k.resolve(e,...t.split("/")),i=k.resolve(e);if(n!==i&&!n.startsWith(`${i}${k.sep}`))throw y("PACKAGE_PATH_TRAVERSAL","workspace file path escaped the workspace root");let o;try{o=R.lstatSync(n);}catch{throw y("PACKAGE_FILE_INVALID",`workspace file is missing: ${t}`)}if(o.isSymbolicLink())throw y("PACKAGE_SYMLINK",`symlink is not publishable: ${t}`);if(!o.isFile())throw y("PACKAGE_FILE_INVALID",`not a regular file: ${t}`);return new Uint8Array(R.readFileSync(n))}function Ge(e,t){return e===t||e.startsWith(`${t}/`)}function $o(e,t){return e.path<t.path?-1:e.path>t.path?1:e.rule.localeCompare(t.rule)}function ni(e,t,n){let i=e??t;if(!Number.isSafeInteger(i)||i<=0)throw new K("PACKAGE_SIZE_LIMIT",`${n} must be a positive integer`);return i}function ri(e,t,n,i){let o=ni(n.maxFileCount??n.maxFiles,Bo,"max file count"),r=ni(n.maxTotalBytes??n.maxBytes,zo,"max total bytes");if(t.length>o)throw new K("PACKAGE_SIZE_LIMIT",`package exceeds file count limit (${o})`);let s=0;for(let a of t){let p=i?.get(a);if(p!==void 0?s+=p.byteLength:s+=ze(e,a).byteLength,s>r)throw new K("PACKAGE_SIZE_LIMIT",`package exceeds byte limit (${r})`)}}function Wo(e){return e.appId!==void 0||e.expectedDefinitionHash!==void 0}function Jo(e){let t=e.appId!==void 0,n=e.expectedDefinitionHash!==void 0;if(!t&&n)throw y("APP_ID_REQUIRED","appId is required with expectedDefinitionHash");if(t&&!n)throw y("APP_DEFINITION_HASH_REQUIRED","expectedDefinitionHash is required with appId");if(!t||!n)throw y("APP_ID_REQUIRED")}function Ko(e,t){let n=e.filter(i=>i.appId===t);if(n.length===0)throw y("APP_NOT_FOUND",`no publishable App matches ${t}`);if(n.length!==1)throw y("APP_AMBIGUOUS",`more than one App matches ${t}`);return n[0]}function Xo(e){let t=e.localDefinitionRef?.packageRoot;if(!t||!/^(?:apps|skills)\/[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(t))throw y("APP_PACKAGE_ROOT_INVALID","selected App is not rooted in apps/<safe-id> or skills/<safe-id>");return t}function Yo(e,t){let n=[];for(let i of e.excluded)n.push(Ge(i.path,t)?i:{path:i.path,rule:"out-of-app-scope"});for(let i of e.included)Ge(i,t)||n.push({path:i,rule:"out-of-app-scope"});return n.sort($o)}function qo(e,t,n,i){let o=`${n}/ui-plugin.json`;if(!i.includes(o))throw y("APP_UI_MANIFEST_INVALID","selected screen App has no package ui-plugin.json");let r=ze(e,o),s=Ot(r),a;try{a=JSON.parse(Buffer.from(r).toString("utf8"));}catch{throw y("APP_UI_MANIFEST_INVALID","ui-plugin.json is not valid JSON")}let p;try{let f=te(a,{mode:"local"});if(f.manifestVersion!==2)throw new Error("screen App requires manifestVersion 2");p=f;}catch(f){throw f instanceof V?y("APP_UI_MANIFEST_INVALID",f.code):y("APP_UI_MANIFEST_INVALID")}if(p.pluginId!==t.appId)throw y("APP_DEFINITION_CONFLICT","ui-plugin.json pluginId no longer matches the selected App");let l=`${n}/ui/index.html`;if(!i.includes(l))throw y("APP_UI_MANIFEST_INVALID","screen entry is outside package scope");let u=Ot(ze(e,l)),d=JSON.parse(JSON.stringify(a));if(d.entryHash=u,Object.prototype.hasOwnProperty.call(d,"initialState")){let f=d.initialState;if(!Go(f)||f.path!=="ui/state.json")throw y("APP_INITIAL_STATE_OUT_OF_SCOPE","initialState must reference ui/state.json inside the package");let A=`${n}/ui/state.json`;if(!i.includes(A))throw y("APP_INITIAL_STATE_OUT_OF_SCOPE","initialState reference is outside the selected package");let I=ze(e,A);d.initialState={...f,hash:Ot(I)};}try{let f=te(d,{mode:"published"});return {bytes:new Uint8Array(Buffer.from(Xe(f),"utf8")),sourceHash:s}}catch(f){throw f instanceof V?y("APP_UI_MANIFEST_INVALID",f.code):y("APP_UI_MANIFEST_INVALID")}}async function Zo(e,t){let{included:n,excluded:i}=St(e);ri(e,n,t);let o=zn(e,n,{version:t.version}),r=Lt(e,n);return {plan:{manifest:o,included:n,excluded:i,secretFindings:r},archiveOptions:{}}}async function Qo(e,t){Jo(t);let n=await wn(e),i=Ko(n.items,t.appId);if(i.definitionHash!==t.expectedDefinitionHash)throw y("APP_DEFINITION_CONFLICT",`definitionHash changed for ${t.appId}`);let o=Xo(i),r=St(e);if(r.excluded.some(A=>Ge(A.path,o)&&(A.rule==="symlink"||A.rule==="symlink-dir")))throw y("PACKAGE_SYMLINK","selected App package contains a symlink");let s=r.included.filter(A=>Ge(A,o)),a=Yo(r,o),p=new Map,l=new Map;if(i.capabilities.includes("screen")){let A=qo(e,i,o,s);p.set(`${o}/ui-plugin.json`,A.bytes),l.set(`${o}/ui-plugin.json`,A.sourceHash);}if(i.capabilities.includes("skill")&&!s.includes(`${o}/SKILL.md`))throw y("APP_SKILL_MISSING","skill capability requires package-root SKILL.md");ri(e,s,t,p);let u={appId:i.appId,version:t.version??"",description:i.description,capabilities:i.capabilities,packageRoot:o,...i.definition?.id===void 0?{}:{definitionId:i.definition.id},definitionHash:i.definitionHash,includedFiles:s,generatedFiles:p},d=Gn(e,u),f=Lt(e,s,p);return {plan:{manifest:d,included:s,excluded:a,secretFindings:f},archiveOptions:{generatedFiles:p,sourceFileHashes:l}}}async function oi(e,t){let n=k.resolve(e);if(Wo(t))return Qo(n,t);if(t.expectedDefinitionHash!==void 0)throw y("APP_ID_REQUIRED");return Zo(n,t)}async function lc(e,t={}){return (await oi(e,t)).plan}function es(e){let t=e.map(n=>`${n.path}:${n.line} (${n.rule})`).join(", ");throw new K("PUBLISH_SECRET_FINDINGS",`aborted \u2014 secret findings must be resolved before packing: ${t}`)}async function si(e,t={}){let n=k.resolve(e),i=await oi(n,t);i.plan.secretFindings.length>0&&es(i.plan.secretFindings);let o=await qn(n,i.plan.manifest,i.archiveOptions);return {manifest:i.plan.manifest,tgzPath:o}}async function dc(e,t={}){return si(e,t)}async function uc(e,t){let n=await si(e,t);if(n.manifest.type!=="app")throw new Error("publish: App pack unexpectedly produced a template manifest");return n}
2
- export{zo as DEFAULT_PUBLISH_MAX_BYTES,Bo as DEFAULT_PUBLISH_MAX_FILES,kn as EXCLUDE_RULES,ue as MARKETPLACE_API_PREFIX,K as PublishError,uc as packApp,si as packPublish,dc as packTemplate,lc as planPublish,Ho as uploadToMarketplace};
1
+ import*as Ot from'crypto';import {createHash}from'crypto';import*as O from'fs';import {constants,readFileSync,existsSync,statSync,readdirSync}from'fs';import*as x from'path';import {join,relative,sep,isAbsolute,resolve}from'path';import*as jn from'js-yaml';import {load}from'js-yaml';import {realpath,stat,readdir,open,lstat}from'fs/promises';import*as Kn from'os';import*as Yn from'tar';import {gunzipSync,gzipSync}from'zlib';var b=class extends Error{constructor(n,i=n,o){super(i);this.code=n;this.currentRevision=o;}code;currentRevision;name="UiRuntimeError"};var pi=/(?:proof|token|secret|password|cookie|authorization|private[_-]?key|stack|exception|plugin[_-]?text)/i,li=/(?:url|uri|endpoint|path|file(?:name|path)?|cwd|shell|directory|dir|folder)$/i,di=/<\/?[A-Za-z][^>]*>/,ui=/^(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)/,fi=/^(?:https?|file|ftp|ws|wss):\/\//i;function v(){throw new b("INPUT_INVALID","JSON value is not projection-safe")}function yi(e){let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}var Ai=8,Ii=4;function Je(e,t,n,i,o,r){if(t>i&&v(),e===null||typeof e=="string"||typeof e=="boolean")return typeof e=="string"&&(di.test(e)||fi.test(e)&&!gi(o,r)||ui.test(e))&&v(),e;if(typeof e=="number")return Number.isFinite(e)||v(),e;(typeof e!="object"||e===void 0||typeof e=="function"||typeof e=="bigint")&&v();let s=e;n.has(s)&&v(),n.add(s);try{if(Array.isArray(e))return e.map(p=>Je(p,t+1,n,i,o,r));yi(s)||v();let c={};for(let[p,l]of Object.entries(e))(pi.test(p)||li.test(p))&&v(),c[p]=Je(l,t+1,n,i,[...o,p],r);return c}finally{n.delete(s);}}function re(e,t=0,n=[]){(!Number.isInteger(t)||t<0||t>Ii)&&v(),(!Array.isArray(n)||n.some(o=>typeof o!="string"))&&v();let i=Je(e,0,new Set,Ai+t,[],n);return (i===null||Array.isArray(i)||typeof i!="object")&&v(),i}function oe(e,t){if(!e||!t)return false;let n=e.split("."),i=t.split(".");return n.length>=i.length&&i.every((o,r)=>n[r]===o)}function gi(e,t){if(e.length===0)return false;let n=e.join(".");return t.some(i=>oe(n,i))}function Xe(e){try{let t=JSON.stringify(e);return t===void 0&&v(),t}catch{v();}}function Ke(e){return Array.isArray(e)?e.map(Ke):e!==null&&typeof e=="object"?Object.fromEntries(Object.keys(e).sort().map(t=>[t,Ke(e[t])])):e}function Q(e){return Xe(Ke(e))}function Ye(e){return Q(e)}var q="window";var Ct=["__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"],mi=new Set(Ct),hi=/(?:proof|token|secret|password|cookie|authorization|private[_-]?key|stack|exception|plugin[_-]?text)/i,_i=/(?:url|uri|endpoint|path|file(?:name|path)?|cwd|shell|directory|dir|folder)$/i;function se(e){return mi.has(e)||hi.test(e)||_i.test(e)}var De=/^[A-Za-z0-9_]+$/,fe=/^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)*$/,ae=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,qe=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/,Ze=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,Qe=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/,et=["blue","violet","emerald","amber","rose","sky","slate","indigo"],tt=["inline","panel"];var Ei=1,Pi=/^[a-z][a-zA-Z0-9]*(\.[a-zA-Z0-9]+)+$/,Ti=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,Wt=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,Di=/<\/?[A-Za-z][^>]*>/,Ni=/^(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)/,bi=/^(?:https?|file|ftp|ws|wss):\/\//i,Mi=/^\s*(?:javascript|data):/i,Vt=/data:[^,\s]*,/i,Si=/(?:https?|file|ftp|ws|wss):\/\//i,Li=/javascript:/i,Ui=/(?:^[\s]*|[\s"'(=])(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)(?=[^\s"'<>])[^\s"'<>]*/,Ri=["manifestVersion","pluginId","definitionId","version","primitiveSet","activation","schema","layout"],Oi=["manifestVersion","pluginId","definitionId","version","name","description","entry","surfaces","size","stateProjection","actions"],wi=["icon","tone","entryHash","initialState","usage","detailPanel","displayModes","dataPaths","focusedAiDataPaths"],xi=["actionId","capability","mutation","inputSchema","resultProjection","backend"],ki=["confirmation","dataInputs"],Ci=["type","handler"],Vi=["type","command"],Fi=["path"],vi=["hash"],ji=/^[0-9a-f]{64}$/,Hi=/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/,Bi=/[\r\n]/,Jt=16,zi=["card-shell","meta-banner","heading","labeled-text","step-flow","text-list"],V=class extends Error{constructor(n,i=n){super(i);this.code=n;}code;name="UiPluginValidationError"};function a(e,t=e){throw new V(e,t)}function R(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;try{let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}catch{return false}}function E(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function L(e,t,n=[]){let i=new Set([...t,...n]);Object.keys(e).some(o=>!i.has(o))&&a("MANIFEST_INVALID"),t.some(o=>!E(e,o))&&a("MANIFEST_INVALID");}function Le(e,t=false,n=false,i=false){return Di.test(e)||!i&&bi.test(e)||Ni.test(e)||n&&Vt.test(e)||Mi.test(e)&&!(t&&/^\s*data:/i.test(e)&&!Vt.test(e))}function Me(e,t=new Set,n=0,i=false,o=false){if(typeof e=="string"){Le(e,i,o)&&a("UNSAFE_VALUE");return}if(!(e===null||typeof e!="object")){(n>8||t.has(e))&&a("MANIFEST_INVALID"),t.add(e);try{if(Array.isArray(e)){for(let r of e)Me(r,t,n+1);return}R(e)||a("MANIFEST_INVALID");for(let[r,s]of Object.entries(e))Me(s,t,n+1,i&&n===0&&(r==="name"||r==="description"),o);}finally{t.delete(e);}}}function $(e,t){let n=e[t];return typeof n!="string"&&a("MANIFEST_INVALID"),n}function B(e,t,n){let i=e[t];return (!Number.isSafeInteger(i)||i<n)&&a("MANIFEST_INVALID"),i}function nt(e){return Ti.test(e)||a("MANIFEST_INVALID"),e}function ce(e){return Pi.test(e)||a("TOKEN_INVALID"),e}function Gi(e){return Wt.test(e)||a("MANIFEST_INVALID"),e}function $i(e){R(e)||a("MANIFEST_INVALID");let t={};for(let[n,i]of Object.entries(e)){let o=Gi(n);R(i)||a("MANIFEST_INVALID");let r=i.type;if(r==="text"){L(i,["type","maxLength"]),t[o]={type:r,maxLength:B(i,"maxLength",1)};continue}if(r==="text-list"){L(i,["type","max","itemMaxLength"]),t[o]={type:r,max:B(i,"max",0),itemMaxLength:B(i,"itemMaxLength",1)};continue}if(r==="step-list"){L(i,["type","min","max","labelMaxLength","detailMaxLength"]);let s=B(i,"min",0),c=B(i,"max",1);s>c&&a("MANIFEST_INVALID"),t[o]={type:r,min:s,max:c,labelMaxLength:B(i,"labelMaxLength",1),detailMaxLength:B(i,"detailMaxLength",1)};continue}typeof r=="string"&&a("SCHEMA_TYPE_UNSUPPORTED"),a("MANIFEST_INVALID");}return t}function Wi(e,t,n){let i=e[t];(!i||i.type!==n)&&a("MANIFEST_INVALID");}function Ne(e,t,n){let i=$(e,"field");return Wt.test(i)||a("MANIFEST_INVALID"),Wi(t,i,n),i}function Ji(e,t){R(e)||a("MANIFEST_INVALID");let n=e.primitive;switch(typeof n!="string"&&a("MANIFEST_INVALID"),zi.includes(n)||a("PRIMITIVE_UNKNOWN"),n){case "card-shell":return L(e,["primitive"]),{primitive:n};case "meta-banner":return L(e,["primitive","badgeToken","noticeToken"]),{primitive:n,badgeToken:ce($(e,"badgeToken")),noticeToken:ce($(e,"noticeToken"))};case "heading":return L(e,["primitive","field"]),{primitive:n,field:Ne(e,t,"text")};case "labeled-text":return L(e,["primitive","titleToken","field","variant"]),e.variant!=="callout"&&a("MANIFEST_INVALID"),{primitive:n,titleToken:ce($(e,"titleToken")),field:Ne(e,t,"text"),variant:"callout"};case "step-flow":return L(e,["primitive","titleToken","field"]),{primitive:n,titleToken:ce($(e,"titleToken")),field:Ne(e,t,"step-list")};case "text-list":{L(e,["primitive","titleToken","field"],["emptyToken","hideWhenEmpty"]);let i={primitive:n,titleToken:ce($(e,"titleToken")),field:Ne(e,t,"text-list")};return E(e,"emptyToken")&&(i.emptyToken=ce($(e,"emptyToken"))),E(e,"hideWhenEmpty")&&(typeof e.hideWhenEmpty!="boolean"&&a("MANIFEST_INVALID"),i.hideWhenEmpty=e.hideWhenEmpty),i}}return a("MANIFEST_INVALID")}function Ki(e,t){return Array.isArray(e)||a("MANIFEST_INVALID"),e.map(n=>Ji(n,t))}function U(e="v2 manifest exceeds a contract limit"){return a("LIMIT_EXCEEDED",e)}function j(e="initial state is not projection-safe"){return a("INITIAL_STATE_INVALID",e)}function Ft(e,t){return (typeof e!="string"||e.length===0||e.length>4096||e.trim().length===0||Hi.test(e)||Bi.test(e))&&a("MANIFEST_INVALID",`${t} is invalid`),(Le(e,true,true)||Si.test(e)||Li.test(e)||Ui.test(e))&&a("UNSAFE_VALUE",`${t} contains an unsafe value`),e}function it(e,t){return (typeof e!="string"||!ae.test(e))&&a("MANIFEST_INVALID",`${t} is invalid`),e}function Xi(e){return (typeof e!="string"||!qe.test(e)||e==="*"||e==="all")&&a("MANIFEST_INVALID","action capability is invalid"),e}function Kt(e){return (typeof e!="string"||!ji.test(e))&&a("MANIFEST_INVALID","resource hash is invalid"),e}function rt(e,t=new Set,n=0){if(typeof e=="string"){e.length>4096&&U("v2 manifest string is too long");return}if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){Number.isFinite(e)||a("MANIFEST_INVALID","v2 manifest contains a non-finite number");return}(e===void 0||typeof e=="function"||typeof e=="bigint")&&a("MANIFEST_INVALID","v2 manifest contains a non-JSON value"),typeof e!="object"&&a("MANIFEST_INVALID"),n>8&&U("v2 manifest nesting is too deep"),t.has(e)&&a("MANIFEST_INVALID","v2 manifest contains a cycle"),t.add(e);try{if(Array.isArray(e)){e.length>128&&U("v2 manifest array is too long");for(let i of e)rt(i,t,n+1);return}R(e)||a("MANIFEST_INVALID","v2 manifest contains a non-plain object");for(let i of Object.values(e))rt(i,t,n+1);}finally{t.delete(e);}}}function pt(e){return (typeof e!="string"||e.length>4096||!fe.test(e))&&(typeof e=="string"&&e.length>4096&&U("projection path is too long"),a("MANIFEST_INVALID","projection paths must be canonical exact paths")),e.split(".").some(n=>se(n))&&a("MANIFEST_INVALID","projection paths cannot address reserved state keys"),e}function Xt(e){R(e)||a("MANIFEST_INVALID","projection policy must be an object"),L(e,["allow"]),Array.isArray(e.allow)||a("MANIFEST_INVALID","projection allow must be an array"),e.allow.length>128&&U("projection allowlist is too long");let t=[],n=new Set;for(let i of e.allow){let o=pt(i);n.has(o)&&a("MANIFEST_INVALID","projection allowlist contains a duplicate path"),n.add(o),t.push(o);}return {allow:t}}function Yi(e,t){if(e===void 0)return;Array.isArray(e)||a("MANIFEST_INVALID","dataPaths must be an array"),e.length>Jt&&U("dataPaths exceed the v2 limit");let n=[],i=new Set;for(let o of e){let r=pt(o);i.has(r)&&a("MANIFEST_INVALID","dataPaths contain a duplicate path"),t.some(s=>oe(r,s))||a("MANIFEST_INVALID","dataPaths must be projection-allowed"),i.add(r),n.push(r);}return n}function qi(e,t){Array.isArray(e)||a("MANIFEST_INVALID","focusedAiDataPaths must be an array"),e.length>Jt&&U("focusedAiDataPaths exceed the v2 limit"),t===void 0&&a("MANIFEST_INVALID","focusedAiDataPaths require dataPaths");let n=[],i=new Set;for(let o of e){let r=pt(o);i.has(r)&&a("MANIFEST_INVALID","focusedAiDataPaths contain a duplicate path"),t.includes(r)||a("MANIFEST_INVALID","focusedAiDataPaths must be an exact subset of dataPaths"),i.add(r),n.push(r);}return n}function pe(e,t,n=Number.MAX_SAFE_INTEGER){return (!Number.isSafeInteger(e)||e<0||e>n)&&a("MANIFEST_INVALID",`${t} is invalid`),e}function vt(e,t){return (typeof e!="number"||!Number.isFinite(e))&&a("MANIFEST_INVALID",`${t} is invalid`),e}function ot(e,t=0,n=new Set){if(typeof e=="string")return (e.length>4096||Le(e))&&a("UNSAFE_VALUE","schema enum contains an unsafe string"),e;if(e===null||typeof e=="boolean")return e;if(typeof e=="number")return Number.isFinite(e)||a("MANIFEST_INVALID","schema enum contains a non-finite number"),e;(t>8||typeof e!="object"||e===void 0)&&U("schema enum is too deep"),n.has(e)&&a("MANIFEST_INVALID","schema enum contains a cycle"),n.add(e);try{if(Array.isArray(e))return e.length>128&&U("schema enum array is too long"),e.map(o=>ot(o,t+1,n));R(e)||a("MANIFEST_INVALID","schema enum contains a non-plain object");let i={};for(let[o,r]of Object.entries(e))se(o)&&a("MANIFEST_INVALID","schema enum contains a reserved key"),i[o]=ot(r,t+1,n);return i}finally{n.delete(e);}}function Zi(e,t){if(e===void 0)return;Array.isArray(e)||a("MANIFEST_INVALID","schema required must be an array"),e.length>64&&U("schema required list is too long");let n=[],i=new Set;for(let o of e)(typeof o!="string"||!fe.test(o))&&a("MANIFEST_INVALID","schema required contains an invalid key"),o.length>4096&&U("schema required key is too long"),i.has(o)&&a("MANIFEST_INVALID","schema required contains a duplicate key"),t&&!Object.prototype.hasOwnProperty.call(t,o)&&a("MANIFEST_INVALID","schema required references an undeclared property"),i.add(o),n.push(o);return n}function Qi(e,t){let n=t?fe:De;return e.length>4096&&U("schema property name is too long"),(!n.test(e)||e.split(".").some(i=>se(i)))&&a("MANIFEST_INVALID","schema property name is invalid"),e}function st(e,t=0,n=false){R(e)||a("MANIFEST_INVALID","action inputSchema must be an object"),t>8&&U("action inputSchema is too deep");let i=e.type;i!=="object"&&i!=="string"&&i!=="number"&&i!=="integer"&&i!=="boolean"&&i!=="array"&&i!=="null"&&(typeof i=="string"&&a("SCHEMA_TYPE_UNSUPPORTED","action inputSchema type is unsupported"),a("MANIFEST_INVALID","action inputSchema type is required"));let o=["type","enum"];i==="string"&&o.push("minLength","maxLength"),i==="array"&&o.push("minItems","maxItems","items"),i==="object"&&o.push("minProperties","maxProperties","properties","required","additionalProperties"),(i==="number"||i==="integer")&&o.push("minimum","maximum"),L(e,["type"],o.filter(c=>c!=="type"));let r={type:i};if(E(e,"enum")&&(Array.isArray(e.enum)||a("MANIFEST_INVALID","schema enum must be an array"),e.enum.length>128&&U("schema enum is too long"),r.enum=e.enum.map(c=>ot(c))),i==="string"&&(E(e,"minLength")&&(r.minLength=pe(e.minLength,"schema minLength",4096)),E(e,"maxLength")&&(r.maxLength=pe(e.maxLength,"schema maxLength",4096)),r.minLength!==void 0&&r.maxLength!==void 0&&r.minLength>r.maxLength&&a("MANIFEST_INVALID","schema string length bounds are inverted")),(i==="number"||i==="integer")&&(E(e,"minimum")&&(r.minimum=vt(e.minimum,"schema minimum")),E(e,"maximum")&&(r.maximum=vt(e.maximum,"schema maximum")),r.minimum!==void 0&&r.maximum!==void 0&&r.minimum>r.maximum&&a("MANIFEST_INVALID","schema numeric bounds are inverted")),i==="array"&&(E(e,"minItems")&&(r.minItems=pe(e.minItems,"schema minItems",128)),E(e,"maxItems")&&(r.maxItems=pe(e.maxItems,"schema maxItems",128)),r.minItems!==void 0&&r.maxItems!==void 0&&r.minItems>r.maxItems&&a("MANIFEST_INVALID","schema array length bounds are inverted"),E(e,"items")&&(r.items=st(e.items,t+1,false))),i==="object"){let c;if(E(e,"properties")){R(e.properties)||a("MANIFEST_INVALID","schema properties must be an object");let l=Object.entries(e.properties);l.length>64&&U("schema properties are too many"),c={};for(let[u,d]of l){let f=Qi(u,n);c[f]=st(d,t+1,false);}r.properties=c;}E(e,"minProperties")&&(r.minProperties=pe(e.minProperties,"schema minProperties",64)),E(e,"maxProperties")&&(r.maxProperties=pe(e.maxProperties,"schema maxProperties",64)),r.minProperties!==void 0&&r.maxProperties!==void 0&&r.minProperties>r.maxProperties&&a("MANIFEST_INVALID","schema object property bounds are inverted");let p=Zi(e.required,c);p!==void 0&&(r.required=p),E(e,"additionalProperties")&&(e.additionalProperties!==false&&a("MANIFEST_INVALID","schema additionalProperties must be false"),r.additionalProperties=false);}let s=JSON.stringify(r);return (s===void 0||Buffer.byteLength(s,"utf8")>65536)&&U("action inputSchema subtree is too large"),r}function er(e){let t=st(e,0,true);return (t.type!=="object"||!t.properties)&&a("MANIFEST_INVALID","action inputSchema must declare object properties"),t}function tr(e){if(R(e)||a("MANIFEST_INVALID","action backend must be an object"),e.type==="core"){L(e,Ci);let t=e.handler;return (typeof t!="string"||!Ze.test(t))&&a("MANIFEST_INVALID","core backend handler is invalid"),{type:"core",handler:t}}if(e.type==="skill"){L(e,Vi),(!Array.isArray(e.command)||e.command.length===0||e.command.length>16)&&a("MANIFEST_INVALID","skill backend command is invalid");let t=[];for(let n of e.command)(typeof n!="string"||n.length===0||n.length>256||!Qe.test(n))&&a("MANIFEST_INVALID","skill backend command token is invalid"),t.push(n);return {type:"skill",command:t}}a("MANIFEST_INVALID","action backend type is unsupported");}function nr(e){R(e)||a("MANIFEST_INVALID","action must be an object"),L(e,xi,ki);let t=it(e.actionId,"actionId"),n=Xi(e.capability),i=e.mutation;typeof i!="boolean"&&a("MANIFEST_INVALID","action mutation must be boolean");let o=er(e.inputSchema),r;if(E(e,"dataInputs")){Array.isArray(e.dataInputs)||a("MANIFEST_INVALID","action dataInputs must be an array");let l=o.properties,u=new Set,d=[];for(let f of e.dataInputs)(typeof f!="string"||!E(l,f)||u.has(f))&&a("MANIFEST_INVALID","action dataInputs must be unique declared properties"),u.add(f),d.push(f);r=d;}let s=Xt(e.resultProjection),c=tr(e.backend),p;if(E(e,"confirmation")){let l=e.confirmation;l!=="none"&&l!=="native"&&a("MANIFEST_INVALID","action confirmation is invalid"),p=l;}return {actionId:t,capability:n,mutation:i,inputSchema:o,resultProjection:s,backend:c,...r===void 0?{}:{dataInputs:r},...p===void 0?{}:{confirmation:p}}}function ir(e){return R(e)||a("INITIAL_STATE_INVALID","initialState must be an object"),L(e,Fi,vi),e.path!=="ui/state.json"&&a("MANIFEST_INVALID","initialState path is not fixed"),E(e,"hash")?{path:"ui/state.json",hash:Kt(e.hash)}:{path:"ui/state.json"}}function rr(e,t){Me(e,new Set,0,true,true),rt(e),R(e)||a("MANIFEST_INVALID"),L(e,Oi,wi),e.manifestVersion!==2&&a("MANIFEST_INVALID");let n=it(e.pluginId,"pluginId"),i=it(e.definitionId,"definitionId"),o=B(e,"version",1),r=Ft(e.name,"name"),s=Ft(e.description,"description"),c;E(e,"icon")&&((typeof e.icon!="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(e.icon))&&a("MANIFEST_INVALID","icon is invalid"),c=e.icon);let p;E(e,"tone")&&((typeof e.tone!="string"||!et.includes(e.tone))&&a("MANIFEST_INVALID","tone is invalid"),p=e.tone),e.entry!=="ui/index.html"&&a("MANIFEST_INVALID","entry path is not fixed");let l;E(e,"entryHash")&&(l=Kt(e.entryHash));let u;E(e,"initialState")&&(u=ir(e.initialState));let d;E(e,"usage")&&(e.usage!=="card"&&e.usage!=="window"&&a("MANIFEST_INVALID","usage is invalid"),d=e.usage);let f;E(e,"detailPanel")&&(typeof e.detailPanel!="boolean"&&a("MANIFEST_INVALID","detailPanel is invalid"),f=e.detailPanel);let A;if(E(e,"displayModes")){((d??q)!==q||!Array.isArray(e.displayModes)||e.displayModes.length===0)&&a("MANIFEST_INVALID","displayModes are only valid for window Apps");let N=new Set(["inline","floating","focused"]);(new Set(e.displayModes).size!==e.displayModes.length||e.displayModes.some(S=>typeof S!="string"||!N.has(S)))&&a("MANIFEST_INVALID","displayModes are invalid"),A=e.displayModes;}(d??q)===q&&f!==void 0&&a("MANIFEST_INVALID","detailPanel is card-only");let I=t.mode??"local";I!=="local"&&I!=="installed"&&I!=="published"&&a("MANIFEST_INVALID","manifest mode is invalid"),I!=="local"&&l===void 0&&a("MANIFEST_INVALID","installed manifests require entryHash"),I!=="local"&&u!==void 0&&u.hash===void 0&&a("MANIFEST_INVALID","installed manifests require initialState.hash"),(!Array.isArray(e.surfaces)||e.surfaces.length===0)&&a("MANIFEST_INVALID","surfaces are invalid"),e.surfaces.length>2&&U("surfaces exceed the v2 limit");let M=[],z=new Set;for(let N of e.surfaces)(typeof N!="string"||!tt.includes(N))&&a("MANIFEST_INVALID","surface is unsupported"),z.has(N)&&a("MANIFEST_INVALID","surfaces contain a duplicate"),z.add(N),M.push(N);R(e.size)||a("MANIFEST_INVALID","size must be an object"),L(e.size,["height"]);let F=B(e.size,"height",1);F>720&&U("size.height exceeds the v2 limit");let m=Xt(e.stateProjection),g=Yi(e.dataPaths,m.allow),H=E(e,"focusedAiDataPaths")?qi(e.focusedAiDataPaths,g):void 0;Array.isArray(e.actions)||a("MANIFEST_INVALID","actions must be an array"),e.actions.length>32&&U("actions exceed the v2 limit");let G=[],Y=new Set;for(let N of e.actions){let S=nr(N);if(Y.has(S.actionId)&&a("MANIFEST_INVALID","actions contain a duplicate actionId"),S.backend.type==="core"&&S.backend.handler==="state.set"){S.mutation||a("MANIFEST_INVALID","state.set actions must be mutations");for(let Pe of Object.keys(S.inputSchema.properties))m.allow.includes(Pe)||a("MANIFEST_INVALID","state.set input paths must be projection-allowed");}Y.add(S.actionId),G.push(S);}return {manifestVersion:2,pluginId:n,definitionId:i,version:o,name:r,description:s,...c===void 0?{}:{icon:c},...p===void 0?{}:{tone:p},entry:"ui/index.html",...l===void 0?{}:{entryHash:l},...u===void 0?{}:{initialState:u},...d===void 0?{}:{usage:d},...f===void 0?{}:{detailPanel:f},...A===void 0?{}:{displayModes:A},surfaces:M,size:{height:F},stateProjection:m,...g===void 0?{}:{dataPaths:g},...H===void 0?{}:{focusedAiDataPaths:H},actions:G}}function or(e){let t={},n={};for(let r of e.actions){t[r.actionId]={capabilities:[r.capability],inputKeys:Object.keys(r.inputSchema.properties??{}),...r.dataInputs===void 0?{}:{dataInputs:r.dataInputs},resultProjection:r.resultProjection,...r.confirmation===void 0?{}:{confirmation:r.confirmation}};let s=r.backend.type==="skill"||r.backend.type==="core"&&r.backend.handler==="state.set";n[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.dataPaths===void 0?{}:{dataPaths:e.dataPaths},...e.focusedAiDataPaths===void 0?{}:{focusedAiDataPaths:e.focusedAiDataPaths},actions:t},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:n,resources:o}}function at(e,t,n,i,o,r){if(typeof e=="string"){let s=o.length>0&&r.some(c=>oe(o.join("."),c));return (e.length>4096||Le(e,false,false,s))&&j("state contains an unsafe string"),e}if(e===null||typeof e=="boolean")return e;if(typeof e=="number")return Number.isFinite(e)||j("state contains a non-finite number"),e;(e===void 0||typeof e!="object"||typeof e=="function"||typeof e=="bigint")&&j("state contains a non-JSON value"),n>8&&j("state is too deep"),t.has(e)&&j("state contains a cycle"),t.add(e);try{let s;if(Array.isArray(e))e.length>128&&j("state array is too long"),s=e.map(p=>at(p,t,n+1,65536,o,r));else {R(e)||j("state contains a non-plain object");let p={};for(let[l,u]of Object.entries(e))(l.length>4096||!De.test(l)||se(l))&&(l.length>4096&&j("state key is too long"),j("state contains a reserved or invalid key")),p[l]=at(u,t,n+1,65536,[...o,l],r);s=p;}let c=JSON.stringify(s);return (c===void 0||Buffer.byteLength(c,"utf8")>i)&&j("state subtree is too large"),s}finally{t.delete(e);}}function lt(e,t=[]){R(e)||j("initial state must be a JSON object");let n=at(e,new Set,0,65536,[],t);return (n===null||Array.isArray(n)||typeof n!="object")&&j(),n}function sr(e,t={}){Me(e),R(e)||a("MANIFEST_INVALID"),L(e,Ri),e.manifestVersion!==1&&a("MANIFEST_INVALID");let n=nt($(e,"pluginId")),i=nt($(e,"definitionId")),o=B(e,"version",1),r=B(e,"primitiveSet",1),s=t.supportedPrimitiveSet??Ei;(!Number.isSafeInteger(s)||s<1)&&a("MANIFEST_INVALID"),r>s&&a("PRIMITIVE_SET_UNSUPPORTED"),R(e.activation)||a("MANIFEST_INVALID"),L(e.activation,["kind","language"]),e.activation.kind!=="fenced-code"&&a("MANIFEST_INVALID");let c=nt($(e.activation,"language")),p=$i(e.schema),l=Ki(e.layout,p);return {manifestVersion:1,pluginId:n,definitionId:i,version:o,primitiveSet:r,activation:{kind:"fenced-code",language:c},schema:p,layout:l}}function ar(e,t={}){return R(e)||a("MANIFEST_INVALID"),e.manifestVersion===2?rr(e,t):sr(e,t)}function te(e,t={}){try{return ar(e,t)}catch(n){if(n instanceof V)throw n;return a("MANIFEST_INVALID")}}function dt(e,t={}){let n=te(e,t);return n.manifestVersion===2?or(n):n}var Zt="SKILL.md",ur=/^---\s*\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;function Qt(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function fr(e){return e.isDirectory()||e.isSymbolicLink()}function on(e){try{return existsSync(e)&&statSync(e).isDirectory()}catch{return false}}function ft(e){let t;try{t=readFileSync(e,"utf8");}catch{return {frontmatter:{},readable:false,valid:false,hasFrontmatter:false}}let n=t.match(ur);if(!n)return {frontmatter:{},readable:true,valid:true,hasFrontmatter:false};try{let i=load(n[1]??"");if(!Qt(i))return {frontmatter:{},readable:!0,valid:!1,hasFrontmatter:!0};let o=Qt(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 yr(e){return [join(e,Zt),join(e,"skill",Zt)]}function en(e,t){if(!on(e))return null;for(let n of yr(e)){if(!existsSync(n))continue;let o=ft(n).frontmatter;return {name:o.name??t,...o.version===void 0?{}:{version:o.version},...o.description===void 0?{}:{description:o.description},skillMdPath:n,dir:e}}return null}function tn(e){try{return readdirSync(e,{withFileTypes:!0}).filter(fr)}catch{return []}}function nn(e,t,n){!e||t.has(e.name)||(t.add(e.name),n.push(e));}function sn(e){let t=[],n=new Set;for(let i of e)if(on(i))for(let o of tn(i)){if(o.name.startsWith("@")){let r=join(i,o.name);for(let s of tn(r))nn(en(join(r,s.name),s.name),n,t);continue}nn(en(join(i,o.name),o.name),n,t);}return t.sort((i,o)=>i.name.localeCompare(o.name))}var Ir=/^[0-9a-f]{64}$/;function Re(e){let n=e.renderer!==void 0||e.surfaces!==void 0||e.stateProjection!==void 0||e.dataPaths!==void 0||e.focusedAiDataPaths!==void 0||e.usage!==void 0||e.detailPanel!==void 0||e.displayModes!==void 0||Object.values(e.actions).some(o=>o.resultProjection!==void 0)?{id:e.id,version:e.version,renderer:e.renderer,surfaces:e.surfaces,stateProjection:e.stateProjection,...e.dataPaths===void 0?{}:{dataPaths:e.dataPaths},...e.focusedAiDataPaths===void 0?{}:{focusedAiDataPaths:e.focusedAiDataPaths},...e.usage===void 0?{}:{usage:e.usage},...e.detailPanel===void 0?{}:{detailPanel:e.detailPanel},...e.displayModes===void 0?{}:{displayModes:e.displayModes},...e.sourceHash===void 0?{}:{sourceHash:e.sourceHash},actions:e.actions}:e.sourceHash===void 0?{id:e.id,version:e.version,actions:e.actions}:{id:e.id,version:e.version,sourceHash:e.sourceHash,actions:e.actions},i=re(n);return createHash("sha256").update(Q(i)).digest("hex")}function yt(e){if(!/^\d+$/.test(String(e.version))||e.version<1||e.id.length<1||e.id.length>128)throw new b("DEFINITION_UNSUPPORTED","UI definition is invalid");if(e.sourceHash!==void 0&&(typeof e.sourceHash!="string"||!Ir.test(e.sourceHash)))throw new b("DEFINITION_UNSUPPORTED","UI definition source hash is invalid");if(!/^[0-9a-f]{64}$/.test(e.hash)||Re(e)!==e.hash)throw new b("DEFINITION_UNSUPPORTED","UI definition hash is invalid");for(let[t,n]of Object.entries(e.actions)){if(!t||!Array.isArray(n.capabilities)||n.capabilities.some(i=>!gr(i)))throw new b("DEFINITION_UNSUPPORTED","UI action declaration is invalid");if(n.confirmation!==void 0&&n.confirmation!=="none"&&n.confirmation!=="native")throw new b("DEFINITION_UNSUPPORTED","UI action confirmation is invalid");if(n.inputKeys&&(!Array.isArray(n.inputKeys)||n.inputKeys.some(i=>typeof i!="string"||!i)))throw new b("DEFINITION_UNSUPPORTED","UI action input declaration is invalid");if(n.dataInputs!==void 0&&(!Array.isArray(n.dataInputs)||new Set(n.dataInputs).size!==n.dataInputs.length||n.dataInputs.some(i=>typeof i!="string"||!i||n.inputKeys!==void 0&&!n.inputKeys.includes(i))))throw new b("DEFINITION_UNSUPPORTED","UI action data input declaration is invalid");n.resultProjection&&an(n.resultProjection);}if(e.renderer!==void 0&&(!e.renderer||e.renderer.length>128))throw new b("DEFINITION_UNSUPPORTED","UI definition renderer is invalid");if(e.surfaces&&(!Array.isArray(e.surfaces)||e.surfaces.some(t=>!t||t.length>64)))throw new b("DEFINITION_UNSUPPORTED","UI definition surfaces are invalid");if(e.usage!==void 0&&e.usage!=="card"&&e.usage!=="window")throw new b("DEFINITION_UNSUPPORTED","UI definition usage is invalid");if(e.detailPanel!==void 0&&typeof e.detailPanel!="boolean")throw new b("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(t=>t!=="inline"&&t!=="floating"&&t!=="focused")))throw new b("DEFINITION_UNSUPPORTED","UI definition displayModes are invalid");if(e.usage==="card"&&e.displayModes!==void 0)throw new b("DEFINITION_UNSUPPORTED","Card definitions cannot declare displayModes");if(e.usage==="window"&&e.detailPanel!==void 0)throw new b("DEFINITION_UNSUPPORTED","Window definitions cannot declare detailPanel");if(e.stateProjection&&an(e.stateProjection),e.dataPaths!==void 0){let t=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(n=>typeof n!="string"||!/^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)*$/.test(n)||n.split(".").some(i=>t.has(i))||!(e.stateProjection?.allow??[]).some(i=>oe(n,i))))throw new b("DEFINITION_UNSUPPORTED","UI definition dataPaths are invalid")}if(e.focusedAiDataPaths!==void 0){let t=new Set(["__proto__","prototype","constructor"]);if(!Array.isArray(e.focusedAiDataPaths)||e.focusedAiDataPaths.length>16||e.dataPaths===void 0||new Set(e.focusedAiDataPaths).size!==e.focusedAiDataPaths.length||e.focusedAiDataPaths.some(n=>typeof n!="string"||!/^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)*$/.test(n)||n.split(".").some(i=>t.has(i))||!e.dataPaths.includes(n)))throw new b("DEFINITION_UNSUPPORTED","UI definition focusedAiDataPaths are invalid")}}function an(e){if(!Array.isArray(e.allow)||e.allow.some(t=>!/^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)*$/.test(t)))throw new b("DEFINITION_UNSUPPORTED","UI projection policy is invalid")}function gr(e){return e.length>0&&e.length<=128&&e!=="*"&&e!=="all"&&!/[/*]/.test(e)}var Z=class extends Error{constructor(n,i=n){super(i);this.code=n;}code;name="McpAppContractError"};function At(e,t=e){throw new Z(e,t)}var cn=["crewx_app_terminal_connect","crewx_app_html_viewer_open"];var gt=8*1024*1024;new Set(cn);var mr=4;function It(e,t=0){try{let n=re(e,t);return n.type!==void 0&&n.type!=="object"&&At("TOOL_INVALID","MCP App inputSchema must describe an object"),n}catch(n){if(n instanceof Z)throw n;At("TOOL_INVALID","MCP App inputSchema must be projection-safe JSON");}}function pn(e){if(e.length===0)return It({type:"object",properties:{},additionalProperties:false});let t=e.map(i=>i.actionId),n=new Map;for(let i of e)n.set(i.actionId,It(i.inputSchema));return It(hr(t,n),mr)}function hr(e,t){let n=e.map(i=>({type:"object",properties:{actionId:{type:"string",const:i},input:t.get(i)??{type:"object"}},required:["actionId","input"],additionalProperties:false}));return Object.freeze({type:"object",oneOf:Object.freeze(n),properties:Object.freeze({actionId:Object.freeze({type:"string",enum:Object.freeze([...e])}),input:Object.freeze({type:"object"})}),required:Object.freeze(["actionId","input"]),additionalProperties:false})}var h=class extends Error{constructor(n){super(n);this.code=n;}code;name="AppDiscoveryFsError"},An=constants.O_NOFOLLOW,Tr=constants.O_NONBLOCK,Dr=constants.O_RDONLY|(An??0)|(Tr??0);function W(e){let t=typeof e=="object"&&e!==null&&"code"in e?String(e.code):"";return t==="ENOENT"?new h("NOT_FOUND"):t==="ELOOP"?new h("PATH_ESCAPED"):t==="EFBIG"||t==="EOVERFLOW"?new h("LIMIT_EXCEEDED"):t==="EACCES"||t==="EPERM"||t==="ENOTDIR"?new h("READ_DENIED"):new h("READ_DENIED")}function Nr(e){if(typeof e!="string"||e.length===0||!isAbsolute(e))throw new h("READ_DENIED")}function ln(e){if(typeof e!="string"||isAbsolute(e)||/[\\\u0000]/.test(e))throw new h("PATH_ESCAPED");if(e==="")return [];let t=e.split("/");if(t.some(n=>n.length===0||n==="."||n===".."))throw new h("PATH_ESCAPED");return t}function Oe(e,t){let n=relative(e,t);return n===""||n!==".."&&!n.startsWith(`..${sep}`)&&!isAbsolute(n)}function we(e){return {dev:e.dev,ino:e.ino,size:e.size,mtimeNs:e.mtimeNs,ctimeNs:e.ctimeNs}}function _t(e,t){return e.dev===t.dev&&e.ino===t.ino}function In(e,t){return _t(e,t)&&e.size===t.size&&e.mtimeNs===t.mtimeNs&&e.ctimeNs===t.ctimeNs}async function dn(e){Nr(e);let t,n;try{t=await realpath(e),n=await stat(t,{bigint:!0});}catch(i){throw W(i)}if(!n.isDirectory())throw new h("READ_DENIED");return {realRoot:t,identity:we(n)}}async function br(e,t,n){if(n.length<2||n[0]!=="apps"&&n[0]!=="skills")return;let i,o;try{if(i=resolve(e,n[0],n[1]),o=await realpath(i),!(await stat(o,{bigint:!0})).isDirectory())throw new h("READ_DENIED")}catch(r){throw r instanceof h?r:W(r)}if(!Oe(t,o))throw new h("PATH_ESCAPED");return o}async function un(e,t,n,i){let o,r,s;try{o=await lstat(e,{bigint:!0}),r=await realpath(e),s=await stat(r,{bigint:!0});}catch(c){throw W(c)}if(!Oe(t,r)||n!==void 0&&!Oe(n,r))throw new h("PATH_ESCAPED");if(!o.isFile()||!s.isFile())throw new h("READ_DENIED");if(!_t(i,o)||!_t(i,s)||i.dev!==s.dev)throw new h("PATH_ESCAPED")}async function mt(e,t){let n,i;try{n=await realpath(e),i=await stat(n,{bigint:!0});}catch{throw new h("PATH_ESCAPED")}if(n!==t.realRoot||!In(t.identity,we(i)))throw new h("PATH_ESCAPED")}function Mr(e){return e.isSymbolicLink()?{name:e.name,kind:"symlink"}:e.isDirectory()?{name:e.name,kind:"directory"}:e.isFile()?{name:e.name,kind:"file"}:{name:e.name,kind:"other"}}var xe=class{async listDirectory(t,n){let i=ln(n),o=await dn(t),r=resolve(t,...i),s,c;try{s=await realpath(r),c=await stat(s,{bigint:!0});}catch(p){let l=W(p);if(l.code==="NOT_FOUND")return [];throw l}if(!Oe(o.realRoot,s)||!c.isDirectory())throw new h("PATH_ESCAPED");try{let p=await readdir(s,{withFileTypes:!0,encoding:"utf8"});return await mt(t,o),p.map(Mr)}catch(p){let l=W(p);if(l.code==="NOT_FOUND")return [];throw l}}async readdir(t,n){return this.listDirectory(t,n)}async readDirectory(t,n){return this.listDirectory(t,n)}async readVerifiedFile(t,n,i){if(!Number.isSafeInteger(i)||i<0)throw new h("READ_DENIED");if(An===void 0)throw new h("UNSUPPORTED");let o=ln(n),r=await dn(t),s=resolve(t,...o),c=relative(t,s);if(c===".."||c.startsWith(`..${sep}`)||isAbsolute(c))throw new h("PATH_ESCAPED");let p;try{p=await open(s,Dr);}catch(l){throw W(l)}try{let l;try{let I=await p.stat({bigint:!0});l=we(I);}catch(I){throw W(I)}if(l.size>BigInt(i))throw new h("LIMIT_EXCEEDED");if(l.size>BigInt(Number.MAX_SAFE_INTEGER))throw new h("LIMIT_EXCEEDED");await mt(t,r);let u=await br(t,r.realRoot,o);await un(s,r.realRoot,u,l);let d=new Uint8Array(new ArrayBuffer(Number(l.size))),f=0;for(;f<d.byteLength;){let I;try{I=(await p.read(d,f,d.byteLength-f,f)).bytesRead;}catch(M){throw W(M)}if(I<=0)throw new h("IDENTITY_CHANGED");f+=I;}let A;try{let I=await p.stat({bigint:!0});A=we(I);}catch(I){throw W(I)}if(!In(l,A))throw new h("IDENTITY_CHANGED");return await un(s,r.realRoot,u,A),await mt(t,r),new Uint8Array(d)}finally{await p.close().catch(()=>{});}}async readFileVerified(t,n,i){return this.readVerifiedFile(t,n,i)}},gn=new xe;var Pt="crewx_local_app_";function Sr(e){if(typeof e!="string"||!ae.test(e))throw new TypeError("pluginId must be a safe UI plugin identifier");let t=`${Pt}${e}`.length+7<=128?e:`hash_${createHash("sha256").update(e,"utf8").digest("hex")}`;return {read:`${Pt}${t}_read`,action:`${Pt}${t}_action`}}var Dt=["apps","skills"],Lr=new TextDecoder("utf-8",{fatal:true});function Nt(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;try{let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}catch{return false}}function mn(e){return typeof e=="string"&&ae.test(e)?e:void 0}function Ur(e,t){return t.length===0||t==="."||t===".."||/[\\/\u0000]/.test(t)?e:`${e}/${t}`}function Rr(e){return e.length>0&&e!=="."&&e!==".."&&!/[\\/\u0000]/.test(e)}function Dn(e,t){let n=new TextEncoder().encode(e),i=new TextEncoder().encode(t),o=Math.min(n.byteLength,i.byteLength);for(let r=0;r<o;r+=1){let s=n[r]-i[r];if(s!==0)return s}return n.byteLength-i.byteLength}function Or(e){if(typeof e=="string")return {name:e,kind:"directory"};if(e===null||typeof e!="object")return null;let t=e;if(typeof t.name!="string")return null;if(t.kind==="file"||t.kind==="directory"||t.kind==="symlink"||t.kind==="other")return {name:t.name,kind:t.kind};if(t.type==="file"||t.type==="directory"||t.type==="symlink"||t.type==="other")return {name:t.name,kind:t.type};let n=t.isDirectory;if(typeof n=="function"&&n.call(e))return {name:t.name,kind:"directory"};let i=t.isSymbolicLink;if(typeof i=="function"&&i.call(e))return {name:t.name,kind:"symlink"};let o=t.isFile;return typeof o=="function"&&o.call(e)?{name:t.name,kind:"file"}:{name:t.name,kind:"other"}}function wr(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(t=>Number.isInteger(t)&&t>=0&&t<=255))return Uint8Array.from(e);throw new TypeError("filesystem port returned an invalid byte array")}function Nn(e){return Lr.decode(e)}function bn(e){return JSON.parse(Nn(e))}function xr(e){if(!Nt(e))return;let t=mn(e.pluginId);if(!t)return;let n=mn(e.definitionId),i=e.version,o=n&&Number.isSafeInteger(i)&&i>=1?`${n}\0${String(i)}`:void 0;return {pluginId:t,...o===void 0?{}:{definitionKey:o}}}function kr(e){let t=bn(e);return {value:t,identity:xr(t)}}function bt(e,t,n,i){let o={code:e,...i===void 0?{}:{pluginId:i},source:t,relativePath:n};return Object.freeze(o)}function hn(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 ne(e){if(e instanceof h)return hn(e.code);if(e!==null&&typeof e=="object"&&"code"in e){let t=e.code;if(typeof t=="string")return hn(t)}}function _e(e,t){return e==="PATH_ESCAPED"||e==="IDENTITY_CHANGED"||e==="TOCTOU"?"PATH_ESCAPED":e==="LIMIT_EXCEEDED"?"LIMIT_EXCEEDED":t==="manifest"&&e==="NOT_FOUND"?"MANIFEST_MISSING":t==="entry"?"ENTRY_INVALID":t==="initial"?"INITIAL_STATE_INVALID":"MANIFEST_INVALID"}function _n(e){switch(e.code){case "MANIFEST_INVALID":case "PRIMITIVE_UNKNOWN":case "PRIMITIVE_SET_UNSUPPORTED":case "SCHEMA_TYPE_UNSUPPORTED":case "TOKEN_INVALID":case "UNSAFE_VALUE":return "MANIFEST_INVALID";case "LIMIT_EXCEEDED":return "LIMIT_EXCEEDED";case "INITIAL_STATE_INVALID":return "INITIAL_STATE_INVALID";default:return Mn("UiPluginValidationError",e.code)}}function Mn(e,t){throw new Error(`Unmapped ${e} code: ${String(t)}`)}function Tt(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 Mn("McpAppContractError",e)}}function En(e,t){let n=t();return Number.isFinite(n)&&Number.isFinite(e)&&n-e<=5e3}function Cr(){return globalThis.performance?.now()??Date.now()}function le(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let t of Object.values(e))le(t);return Object.freeze(e)}function Pn(e){return Object.freeze(Array.from(e))}function Vr(e,t,n){let i=createHash("sha256"),o=new TextEncoder().encode(Q(e)),r=s=>{let c=new Uint8Array(8);new DataView(c.buffer).setBigUint64(0,BigInt(s)),i.update(c);};return r(o.byteLength),i.update(o),r(t.byteLength),i.update(t),r(n.byteLength),i.update(n),i.digest("hex")}function Fr(e,t){let n={...e.definition,sourceHash:t},i={...n,hash:Re(n)};try{yt(i);}catch{throw new V("MANIFEST_INVALID","normalized definition is invalid")}return i}function vr(e){return e.actions.some(t=>t.backend.type==="core"&&t.backend.handler!=="state.set")}function jr(e){if(typeof e.readVerifiedFile=="function")return e.readVerifiedFile;if(typeof e.readFileVerified=="function")return e.readFileVerified}function Hr(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 Ve(e,t,n,i){let o=jr(e);if(!o)throw new h("READ_DENIED");return wr(await o.call(e,t,n,i))}async function Br(e,t,n){let i=Hr(e);if(!i)throw new h("READ_DENIED");let o=await i.call(e,t,n);if(!Array.isArray(o))throw new h("READ_DENIED");return o.map(Or).filter(r=>r!==null)}function zr(e){let t=[];for(let n of [e.reserved,e.builtin])n&&t.push(n);return e.builtins&&"listMcpApps"in e.builtins?t.push(Tn(e.builtins)):e.builtins&&t.push(e.builtins),e.builtinCatalog&&t.push(Tn(e.builtinCatalog)),t.push({...e.reservedAppIds===void 0?{}:{appIds:e.reservedAppIds},...e.reservedDefinitionIds===void 0?{}:{definitionIds:e.reservedDefinitionIds},...e.reservedToolNames===void 0?{}:{toolNames:e.reservedToolNames}}),t}function Tn(e){let t=[],n=[],i=[];for(let o of e.listMcpApps())typeof o.appId=="string"&&t.push(o.appId),o.definition&&typeof o.definition.id=="string"&&n.push(o.definition.id);for(let o of e.listMcpAppTools())typeof o.name=="string"&&i.push(o.name);return {appIds:t,definitionIds:n,toolNames:i}}function he(e,t){e.diagnostic||(e.diagnostic=bt(t,e.source,e.relativePath,e.identity?.pluginId));}function Gr(e){let t=new Map,n=new Map;for(let i of e){if(i.identity?.pluginId){let o=t.get(i.identity.pluginId)??[];o.push(i),t.set(i.identity.pluginId,o);}if(i.identity?.definitionKey){let o=n.get(i.identity.definitionKey)??[];o.push(i),n.set(i.identity.definitionKey,o);}}for(let i of [...t.values(),...n.values()]){let o=i.filter(r=>r.source==="apps");if(o.length>0){if(o.length>1)for(let r of o)he(r,"DUPLICATE_ID");for(let r of i.filter(s=>s.source==="skills"))he(r,"DUPLICATE_ID");continue}if(i.length>1)for(let r of i)he(r,"DUPLICATE_ID");}}function $r(e,t){let n=new Set,i=new Set,o=new Set;for(let r of zr(t)){for(let s of r.appIds??[])typeof s=="string"&&n.add(s);for(let s of r.definitionIds??[])typeof s=="string"&&i.add(s);for(let s of r.toolNames??[])typeof s=="string"&&o.add(s);}for(let r of e){let s=r.candidate;if(!s)continue;if(n.has(s.pluginId)||i.has(s.definitionId)){he(r,"RESERVED_ID");continue}[s.toolNames.read,s.toolNames.action].filter(p=>p!==void 0).some(p=>o.has(p))&&he(r,"DUPLICATE_ID");}}function Wr(e){return [...e].sort((t,n)=>{let i=Dt.indexOf(t.source)-Dt.indexOf(n.source);return i!==0?i:Dn(t.relativePath,n.relativePath)})}function D(e,t){e.diagnostic=bt(t,e.source,e.relativePath,e.identity?.pluginId);}async function Jr(e,t,n,i){if(i.byteLength>262144){D(n,"LIMIT_EXCEEDED");return}let o;try{o=kr(i);}catch{D(n,"MANIFEST_INVALID");return}if(n.identity=o.identity,Nt(o.value)&&o.value.builtinOnly===true){D(n,"RESERVED_ID");return}let r;try{let _=te(o.value,{mode:"local"});if(_.manifestVersion!==2)throw new V("MANIFEST_INVALID","workspace App requires v2");r=_;}catch(_){if(_ instanceof V){D(n,_n(_));return}if(_ instanceof Z){D(n,Tt(_.code));return}if(Nt(_)&&typeof _.code=="string"){D(n,Tt(_.code));return}throw _}if(n.identity={pluginId:r.pluginId,definitionKey:`${r.definitionId}\0${String(r.version)}`},r.actions.length>0)try{pn(r.actions.map(_=>({actionId:_.actionId,inputSchema:_.inputSchema})));}catch(_){if(_ instanceof Z){D(n,Tt(_.code));return}throw _}let s=`${n.relativePath}/ui/index.html`,c;try{c=await Ve(t,e,s,gt);}catch(_){D(n,_e(ne(_),"entry"));return}if(c.byteLength>gt){D(n,"LIMIT_EXCEEDED");return}let p;try{p=Nn(c);}catch{D(n,"ENTRY_INVALID");return}if(c.byteLength===0||p.length===0){D(n,"ENTRY_INVALID");return}let l=createHash("sha256").update(c).digest("hex");if(r.entryHash!==void 0&&r.entryHash!==l){D(n,"ENTRY_INVALID");return}let u={},d,f;if(r.initialState!==void 0){let _=`${n.relativePath}/ui/state.json`;try{d=await Ve(t,e,_,65536);}catch(w){D(n,_e(ne(w),"initial"));return}if(d.byteLength>65536){D(n,"LIMIT_EXCEEDED");return}try{let w=bn(d),kt=r.dataPaths??[],ci=lt(w,kt);u=re(ci,0,kt),Xe(u);}catch{D(n,"INITIAL_STATE_INVALID");return}if(f=createHash("sha256").update(d).digest("hex"),r.initialState.hash!==void 0&&r.initialState.hash!==f){D(n,"INITIAL_STATE_INVALID");return}}let A={...r,entryHash:l,...r.initialState===void 0?{}:{initialState:{path:"ui/state.json",hash:f}}},I=dt(A),M=Vr(A,c,d??new Uint8Array),z;try{z=Fr(I,M);}catch(_){if(_ instanceof V){D(n,_n(_));return}throw _}let F=Sr(r.pluginId),m=r.actions.length===0?{read:F.read}:F,g=le(I),H=le(A),G=le(z),Y=le({...I.handlers}),N=Pn(c),S=d===void 0?void 0:Pn(d),Pe=Object.freeze({entry:Object.freeze({path:"ui/index.html",hash:l,bytes:N}),...S===void 0?{}:{initialState:Object.freeze({path:"ui/state.json",hash:f,bytes:S})}}),Te={appId:r.pluginId,pluginId:r.pluginId,definitionId:r.definitionId,version:r.version,source:n.source,relativePath:n.relativePath,manifest:H,normalized:g,name:r.name,description:r.description,...r.icon===void 0?{}:{icon:r.icon},...r.tone===void 0?{}:{tone:r.tone},definition:G,handlers:Y,resources:Pe,html:p,entryBytes:N,entryHash:l,initialState:le(u),...S===void 0?{}:{initialStateBytes:S},...f===void 0?{}:{initialStateHash:f},sourceHash:M,toolNames:Object.freeze(m)};n.candidate=Object.freeze(Te),vr(r)&&D(n,"EXEC_DENIED");}async function Kr(e,t,n){try{return await Ve(t,e,`${n.relativePath}/ui-plugin.json`,262144)}catch(i){if(ne(i)==="NOT_FOUND")return;D(n,_e(ne(i),"manifest"));return}}function Xr(e,t){let n=Wr(e);Gr(n);let i=Object.freeze(n.filter(s=>s.candidate!==void 0&&s.diagnostic===void 0).map(s=>s.candidate)),o=Object.freeze(n.filter(s=>s.diagnostic!==void 0).map(s=>s.diagnostic)),r={apps:i,diagnostics:o,complete:t===void 0,...t===void 0?{}:{incompleteReason:t}};return Object.defineProperty(r,"candidates",{configurable:false,enumerable:false,get:()=>i}),Object.freeze(r)}function Yr(e){if(e===null||typeof e!="object"&&typeof e!="function")return false;let t=e;return typeof t.readVerifiedFile=="function"||typeof t.readFileVerified=="function"||typeof t.listDirectory=="function"||typeof t.readDirectory=="function"||typeof t.readdir=="function"}function qr(e,t){if(Yr(e))return {fs:e,options:{}};let n=e??t??{};return {fs:n.filesystem??n.fileSystem??n.fs??gn,options:n}}async function Sn(e,t,n){if(typeof e!="string"||e.length===0)throw new TypeError("workspaceRoot must be explicit");let{fs:i,options:o}=qr(t,n),r=o.clock??Cr,s=r(),c=[],p=0,l;for(let u of Dt){let d;try{d=await Br(i,e,u);}catch(A){if(ne(A)==="NOT_FOUND")continue;c.push({source:u,name:"",relativePath:u,diagnostic:bt(_e(ne(A),"manifest"),u,u)});continue}let f=d.filter(A=>A.kind==="directory"||A.kind==="symlink").filter(A=>Rr(A.name)).map(A=>({source:u,name:A.name,relativePath:Ur(u,A.name)})).sort((A,I)=>Dn(A.relativePath,I.relativePath));for(let A of f){let I={...A};c.push(I);let M;if(u==="skills"&&(M=await Kr(e,i,I),M===void 0))continue;if(p>=64){D(I,"LIMIT_EXCEEDED");continue}if(A.relativePath.split("/").length-1>2){D(I,"LIMIT_EXCEEDED");continue}if(l!==void 0||!En(s,r)){D(I,"LIMIT_EXCEEDED"),l="time_limit";continue}if(p+=1,M===void 0)try{M=await Ve(i,e,`${I.relativePath}/ui-plugin.json`,262144);}catch(F){D(I,_e(ne(F),"manifest"));continue}await Jr(e,i,I,M),I.diagnostic===void 0&&p<64&&!En(s,r)&&(l="time_limit");}}return $r(c,o),Xr(c,l)}var Qr=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/;function ve(e){let t="screenHash"in e?e.screenHash:void 0,i=("skillHash"in e?e.skillHash:void 0)??(e.relativePath!==void 0&&e.fileBytes!==void 0?eo(e.relativePath,e.fileBytes):void 0);if(t!==void 0&&i!==void 0){let o=JSON.stringify({screenHash:t,skillHash:i});return createHash("sha256").update(o,"utf8").digest("hex")}if(t!==void 0)return t;if(i!==void 0)return i;throw new TypeError("App definition hash input must contain a screenHash or skill bytes")}function eo(e,t){let n=new TextEncoder().encode(je(e)),i=to(t),o=new Uint8Array(n.byteLength+1+i.byteLength);return o.set(n,0),o[n.byteLength]=0,o.set(i,n.byteLength+1),createHash("sha256").update(o).digest("hex")}function to(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(t=>Number.isInteger(t)&&t>=0&&t<=255))return Uint8Array.from(e);throw new TypeError("fileBytes must be UTF-8 text or bytes")}function je(e){if(typeof e!="string"||e.length===0||isAbsolute(e)||/[\\\u0000]/.test(e))throw new TypeError("relative path must be package-relative");let t=e.split("/").filter(n=>n.length>0&&n!==".").join("/");if(!t||t.split("/").some(n=>n===".."))throw new TypeError("relative path must stay inside the package");return t}function Fe(e,t){let n=new TextEncoder().encode(e),i=new TextEncoder().encode(t),o=Math.min(n.byteLength,i.byteLength);for(let r=0;r<o;r+=1){let s=n[r]-i[r];if(s!==0)return s}return n.byteLength-i.byteLength}function Rn(e,t){let n=relative(e,t).split(sep).join("/");return !n||n===".."||n.startsWith("../")||isAbsolute(n)?null:je(n)}function no(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 On(e){return Object.freeze({packageRoot:e})}function io(e){return Object.freeze({id:e.definition.id,version:e.definition.version,hash:e.definition.hash,usage:e.definition.usage??q,...e.definition.detailPanel===void 0?{}:{detailPanel:e.definition.detailPanel},...e.definition.displayModes===void 0?{}:{displayModes:e.definition.displayModes}})}function wn(e){return {capabilities:Object.freeze([...e]),origin:"local",ownership:"unknown",shareability:"unknown",sharingAvailability:"unavailable"}}function ro(e,t){let n=e.candidate,i=t?["screen","skill"]:["screen"],o=io(n),r=ve(t?{screenHash:o.hash,skillHash:t.skillHash}:{screenHash:o.hash}),s=n.description||t?.skill.description||"",c=String(n.version),p={appId:n.pluginId,name:n.name,description:s,version:c,...wn(i),definition:o,...t===void 0?{}:{skillName:t.skill.name},localDefinitionRef:On(e.packageRoot),definitionHash:r};return {packageRoot:e.packageRoot,source:n.source,appId:p.appId,capabilities:i,summary:Object.freeze(p)}}function oo(e){let t=so(e.skill.name),n={appId:t,name:e.skill.name,description:e.skill.description??"",...e.skill.version===void 0?{}:{version:e.skill.version},...wn(["skill"]),skillName:e.skill.name,localDefinitionRef:On(e.packageRoot),definitionHash:ve({skillHash:e.skillHash})};return {packageRoot:e.packageRoot,source:e.source,appId:t,capabilities:["skill"],summary:Object.freeze(n)}}function so(e){return `skill.${e.replace(/^@/,"").replace(/\//g,".").replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,122)||"unnamed"}`}function k(e,t,n,i){return Object.freeze({code:e,source:t,relativePath:ao(n),...i===void 0?{}:{appId:i}})}function ao(e){if(typeof e!="string"||e.length===0||isAbsolute(e)||/[\\\u0000]/.test(e))return "<unknown>";let t=e.split("/").filter(n=>n.length>0&&n!==".").join("/");return t.split("/").some(n=>n==="..")?"<unknown>":t}function co(e){return k(e.code,e.source,e.relativePath,e.pluginId)}function po(e,t){let n=Rn(e,t.dir);if(!n)return {diagnostic:k("PATH_ESCAPED","node_modules","node_modules")};let i=no(n);if(!i)return {diagnostic:k("PATH_ESCAPED","node_modules",n)};let o=ft(t.skillMdPath);if(!o.readable)return {diagnostic:k("SKILL_READ_FAILED",i,n)};if(!o.valid)return {diagnostic:k("SKILL_INVALID",i,n)};let r=lo(t.dir,t.skillMdPath);if(!r)return {diagnostic:k("PATH_ESCAPED",i,n)};try{let s=new Uint8Array(readFileSync(t.skillMdPath));return {skill:t,packageRoot:n,relativeSkillPath:r,skillHash:ve({relativePath:r,fileBytes:s}),source:i}}catch{return {diagnostic:k("SKILL_READ_FAILED",i,n)}}}function lo(e,t){let n=relative(e,t).split(sep).join("/");try{return je(n)}catch{return null}}function uo(e){if(!Qr.test(e.appId))return {diagnostic:k("BUILTIN_INVALID","builtin",`builtin/${e.appId||"unknown"}`)};let t=e.definition===void 0?void 0:{id:e.definition.id,version:e.definition.version,hash:e.definition.hash,usage:e.definition.usage??q,...e.definition.detailPanel===void 0?{}:{detailPanel:e.definition.detailPanel},...e.definition.displayModes===void 0?{}:{displayModes:e.definition.displayModes}},n=t?.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,...t===void 0?{}:{version:String(t.version),definition:t},capabilities:["screen"],origin:"builtin",ownership:"unknown",shareability:"forbidden",sharingAvailability:"unavailable",definitionHash:n};return {source:"builtin",appId:e.appId,summary:Object.freeze(i)}}function fo(e){return e.builtinCatalog}function yo(e){let t=e.packageRoot??e.relativePath??e.packageRootPath;if(t===void 0)return null;try{return je(t)}catch{return null}}function Ao(e){let t=e.marketplaceContentId;return typeof t=="string"&&t.length>0?t:void 0}function Io(e,t,n){let i=t.installed??[],o=new Map;for(let s of i){let c=yo(s);if(!c){n.push(k("INSTALLED_IDENTITY_MISMATCH","installed","installed"));continue}let p=o.get(c);if(p&&JSON.stringify(p)!==JSON.stringify(s)){n.push(k("INSTALLED_IDENTITY_MISMATCH","installed",c));continue}o.set(c,s);}let r=new Map;for(let s of e)s.packageRoot!==void 0&&r.set(s.packageRoot,s);for(let[s,c]of o){let p=r.get(s);if(!p){n.push(k("INSTALLED_MISSING","installed",s,c.appId));continue}let l=Ao(c);if(!l){n.push(k("INSTALLED_CONTENT_ID_MISSING","installed",s,c.appId));continue}if(c.appId!==void 0&&c.appId!==p.appId||c.definitionHash!==void 0&&c.definitionHash!==p.summary.definitionHash){n.push(k("INSTALLED_IDENTITY_MISMATCH","installed",s,c.appId));continue}let u={...p.summary,origin:"installed",...c.slug===void 0?{}:{slug:c.slug},marketplaceContentId:l},d=e.indexOf(p);d>=0&&(e[d]={...p,summary:Object.freeze(u)});}}function go(e,t){let n=new Map;for(let o of e){let r=n.get(o.appId)??[];r.push(o),n.set(o.appId,r);}let i=new Set;for(let o of n.values())if(!(o.length<2))for(let r of o)i.add(r),t.push(k("DUPLICATE_ID",r.source,r.packageRoot??`builtin/${r.appId}`,r.appId));return e.filter(o=>!i.has(o))}function mo(e,t){return e.filter(n=>!(n.code==="MANIFEST_MISSING"&&t.has(n.relativePath))).map(co)}function ho(e){return e.filesystem}function _o(e,t){let n=ho(e);return {...n===void 0?{}:{filesystem:n},...t===void 0?{}:{builtinCatalog:t}}}async function xn(e,t={}){if(typeof e!="string"||e.length===0)throw new TypeError("workspaceRoot must be explicit");let n=fo(t),i=await Sn(e,_o(t,n)),o=[join(e,"skills"),join(e,"node_modules"),join(e,"apps")],r=[],s=[],c=[],p=new Set;for(let m of o)for(let g of sn([m])){let H=Rn(e,g.dir);(H===null||!p.has(H))&&(c.push(g),H!==null&&p.add(H));}for(let m of c){let g=po(e,m);"diagnostic"in g?r.push(g.diagnostic):s.push(g);}let l=new Map;for(let m of i.apps??i.candidates??[])l.set(m.relativePath,{candidate:m,packageRoot:m.relativePath});let u=new Map(s.map(m=>[m.packageRoot,m])),d=[];for(let m of l.values()){let g=ro(m,u.get(m.packageRoot));d.push({packageRoot:g.packageRoot,source:g.source,appId:g.appId,summary:g.summary});}let f=new Set(l.keys());for(let m of s){if(f.has(m.packageRoot))continue;let g=oo(m);d.push({packageRoot:g.packageRoot,source:g.source,appId:g.appId,summary:g.summary});}let A=[...mo(i.diagnostics,new Set(s.map(m=>m.packageRoot))),...r],I=[];if(n)for(let m of n.listMcpApps()){let g=uo(m);"diagnostic"in g?A.push(g.diagnostic):I.push(g);}let M=go([...d,...I],A);Io(M,t,A);let z=M.map(m=>m.summary).sort((m,g)=>Fe(m.appId,g.appId)),F=[...A].sort((m,g)=>Fe(m.relativePath,g.relativePath)||Fe(m.code,g.code)||Fe(m.appId??"",g.appId??""));return Object.freeze({items:Object.freeze(z),diagnostics:Object.freeze(F)})}function Eo(e){let t=o=>o.replace(/[.+^${}()|[\]\\]/g,"\\$&"),i=e.split("/").map(o=>o==="**"?".*":o.split("*").map(t).join("[^/]*"));return new RegExp(`^${i.join("\\/")}$`)}function de(e,t){try{return Eo(t).test(e)}catch{return false}}function He(e,...t){let n=e.split("/");if(n.length<t.length)return false;let i=n.length-t.length;return t.every((o,r)=>de(n[i+r],o))}function Po(e,t){return e.split("/").some(n=>de(n,t))}var kn=[{label:".env*",test:e=>de(e,".env*")},{label:".git/",test:(e,t,n)=>n&&e===".git"},{label:"memory/",test:(e,t,n)=>n&&e==="memory"},{label:"*.key",test:e=>de(e,"*.key")},{label:"*.pem",test:e=>de(e,"*.pem")},{label:"auth.json",test:e=>e==="auth.json"},{label:"node_modules/",test:(e,t,n)=>n&&e==="node_modules"},{label:"conversations/",test:(e,t,n)=>n&&e==="conversations"},{label:".crewx/threads/",test:(e,t,n)=>n&&He(t,".crewx","threads")},{label:".crewx/crewx.db",test:(e,t,n)=>!n&&He(t,".crewx","crewx.db")},{label:".crewx/*.log",test:(e,t,n)=>!n&&He(t,".crewx","*.log")},{label:".crewx/publish/",test:(e,t,n)=>n&&He(t,".crewx","publish")},{label:".crewx/",test:(e,t)=>Po(t,".crewx")}];function Be(e,t,n){for(let i of kn)if(i.test(e,t,n))return i.label;return null}function Ut(e){let t=[],n=[];function i(o,r,s){let c;try{c=O.readdirSync(o,{withFileTypes:!0});}catch{return}c.sort((p,l)=>p.name.localeCompare(l.name));for(let p of c){let l=r?`${r}/${p.name}`:p.name,u=x.join(o,p.name);if(p.isSymbolicLink()){let d;try{d=O.statSync(u);}catch{n.push({path:l,rule:"symlink"});continue}if(d.isDirectory()){n.push({path:l,rule:s??"symlink-dir"});continue}let f=s??Be(p.name,l,false);f?n.push({path:l,rule:f}):n.push({path:l,rule:"symlink"});continue}if(p.isDirectory()){let d=s??Be(p.name,l,true);i(u,l,d);continue}if(p.isFile()){let d=s??Be(p.name,l,false);d?n.push({path:l,rule:d}):t.push(l);}}}return i(e,"",null),t.sort(),n.sort((o,r)=>o.path<r.path?-1:o.path>r.path?1:0),{included:t,excluded:n}}var To=[{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 Do(e){return e.includes(0)}function Rt(e,t,n){let i=[];for(let o of t){let r=x.join(e,o),s;try{let p=n?.get(o);s=p===void 0?O.readFileSync(r):Buffer.from(p);}catch{continue}if(Do(s))continue;s.toString("utf8").split(/\r\n|\r|\n/).forEach((p,l)=>{for(let{rule:u,regex:d}of To)d.test(p)&&i.push({path:o,line:l+1,rule:u});});}return i}var J=class extends Error{constructor(n,i){super(`publish: [${n}]${i?` ${i}`:""}`);this.code=n;}code;name="PublishError"};function y(e,t){return new J(e,t)}var vn=/^[a-z0-9-]+$/,No=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/,bo=/^[A-Za-z_][A-Za-z0-9_]*$/;function Mo(e){let t=x.join(e,"crewx.yaml");if(!O.existsSync(t))return {};let n;try{n=jn.load(O.readFileSync(t,"utf8"));}catch{return {}}if(!n||typeof n!="object")return {};let i=n.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 So(e){return Ot.createHash("sha256").update(e).digest("hex")}function Hn(e){let t;try{t=O.lstatSync(e);}catch{throw y("PACKAGE_FILE_INVALID",`file is not readable: ${x.basename(e)}`)}if(t.isSymbolicLink())throw y("PACKAGE_SYMLINK","symlink content is not publishable");if(!t.isFile())throw y("PACKAGE_FILE_INVALID","only regular files are publishable");return Ot.createHash("sha256").update(new Uint8Array(O.readFileSync(e))).digest("hex")}function Lo(e,t){let n=new TextEncoder().encode(e),i=new TextEncoder().encode(t),o=Math.min(n.byteLength,i.byteLength);for(let r=0;r<o;r+=1){let s=n[r]-i[r];if(s!==0)return s}return n.byteLength-i.byteLength}function Bn(e){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||x.posix.isAbsolute(e)||e.split("/").some(t=>t===".."||t.length===0))throw y("PACKAGE_PATH_TRAVERSAL","manifest file path must be a non-empty POSIX relative path")}function Uo(e){if(!/^(?:apps|skills)\/[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(e))throw y("APP_PACKAGE_ROOT_INVALID","packageRoot must be apps/<safe-id> or skills/<safe-id>")}function zn(e){if(!No.test(e))throw new Error(`publish: invalid version "${e}" \u2014 must be semver (e.g. 1.0.0)`)}function Gn(e,t,n={}){let i=Mo(e),o=i.name??x.basename(e);if(!vn.test(o))throw new Error(`publish: invalid name "${o}" \u2014 must match ${vn} (lowercase letters, numbers, hyphen only)`);let r=n.version??i.version;if(!r)throw new Error("publish: version is required \u2014 set crewx.yaml metadata.version or pass opts.version");zn(r);let s=Array.isArray(i.requiredEnv)?i.requiredEnv:[],c=[];for(let u of s){if(typeof u!="string"||!bo.test(u))throw new Error(`publish: requiredEnv must contain names only (no values), got "${String(u)}"`);c.push(u);}let p=t.map(u=>(Bn(u),{path:u,sha256:Hn(x.join(e,u))})).sort((u,d)=>u.path<d.path?-1:u.path>d.path?1:0),l={name:o,version:r,type:"template",description:i.description??"",files:p,requiredEnv:c};return i.crewxMinVersion&&(l.crewxMinVersion=i.crewxMinVersion),l}function Ro(e){let t=e.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"");if(!t)throw y("APP_PACKAGE_ROOT_INVALID","appId cannot produce a marketplace name");return t}function $n(e,t){if(Uo(t.packageRoot),!t.version)throw new Error("publish: version is required for App publishing \u2014 pass opts.version");if(zn(t.version),typeof t.description!="string")throw new Error("publish: App description must be a string");let n=[...new Set(t.capabilities)].sort();if(n.length===0||n.some(s=>s!=="screen"&&s!=="skill"))throw new Error("publish: App capabilities must contain screen or skill");let i=`${t.packageRoot}/`;if(n.includes("screen")){if(typeof t.definitionId!="string"||t.definitionId.length===0)throw y("APP_UI_MANIFEST_INVALID","screen App manifests require definitionId");for(let s of ["ui-plugin.json","ui/index.html"])if(!t.includedFiles.includes(`${i}${s}`))throw y("APP_UI_MANIFEST_INVALID",`screen App is missing ${s}`)}if(n.includes("skill")&&!t.includedFiles.includes(`${i}SKILL.md`))throw y("APP_SKILL_MISSING","skill capability requires package-root SKILL.md");let o=new Set,r=t.includedFiles.map(s=>{if(Bn(s),!s.startsWith(i))throw y("PACKAGE_PATH_TRAVERSAL","App manifest file is outside packageRoot");let c=t.generatedFiles?.get(s);return c!==void 0&&o.add(s),{path:s,sha256:c===void 0?Hn(x.join(e,s)):So(c),...c===void 0?{}:{generated:true}}}).sort((s,c)=>Lo(s.path,c.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:Ro(t.appId),version:t.version,type:"app",description:t.description,appId:t.appId,...t.definitionId===void 0?{}:{definitionId:t.definitionId},...t.definitionHash===void 0?{}:{definitionHash:t.definitionHash},capabilities:n,packageRoot:t.packageRoot,files:r,requiredEnv:[]}}function Wn(e){return Ot.createHash("sha256").update(e).digest("hex")}function qn(e,t){if(typeof t!="string"||t.length===0||t.includes("\\")||t.includes("\0")||x.posix.isAbsolute(t)||t.split("/").some(o=>o===".."||o.length===0))throw y("PACKAGE_PATH_TRAVERSAL","archive paths must be non-empty POSIX relative paths");let n=x.resolve(e),i=x.resolve(n,...t.split("/"));if(i!==n&&!i.startsWith(`${n}${x.sep}`))throw y("PACKAGE_PATH_TRAVERSAL","archive path escaped its root");return i}function Jn(e,t){let n=qn(e,t),i;try{i=O.lstatSync(n);}catch{throw y("PACKAGE_FILE_INVALID","manifest file is missing")}if(i.isSymbolicLink())throw y("PACKAGE_SYMLINK","symlink content is not publishable");if(!i.isFile())throw y("PACKAGE_FILE_INVALID","only regular files are publishable");return new Uint8Array(O.readFileSync(n))}async function Zn(e,t,n={}){let i=x.join(e,".crewx","publish");O.mkdirSync(i,{recursive:true});let o=x.join(i,`${t.name}-${t.version}.tgz`),r=x.join(i,`.${t.name}-${t.version}.${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}.tmp.tgz`),s=O.mkdtempSync(x.join(Kn.tmpdir(),"crewx-publish-"));try{let c=new Set,p=[];for(let l of t.files){if(c.has(l.path))throw y("PACKAGE_PATH_TRAVERSAL","manifest contains duplicate file paths");c.add(l.path);let u=n.generatedFiles?.get(l.path);if(l.generated===!0&&u===void 0)throw y("PACKAGE_GENERATED_FILE_MISSING","generated manifest file bytes are missing");if(n.sourceFileHashes?.has(l.path)){let A=Jn(e,l.path);if(n.sourceFileHashes.get(l.path)!==Wn(A))throw y("PACKAGE_STAGED_BYTES_MISMATCH","workspace source changed before staging")}let d=u??Jn(e,l.path);if(Wn(d)!==l.sha256)throw y("PACKAGE_STAGED_BYTES_MISMATCH",`staged bytes differ for ${l.path}`);let f=qn(s,l.path);O.mkdirSync(x.dirname(f),{recursive:!0}),O.writeFileSync(f,new Uint8Array(d)),p.push(l.path);}O.writeFileSync(x.join(s,"manifest.json"),JSON.stringify(t,null,2)),await Yn.create({gzip:!0,file:r,cwd:s,portable:!0,noMtime:!0},["manifest.json",...p]),O.renameSync(r,o);}finally{try{O.rmSync(r,{force:!0});}catch{}O.rmSync(s,{recursive:true,force:true});}return o}var ue="/api/v1";var xo=201,ko=200,Co=409,wt=401,Qn={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 Vo(){return process.env.WI013_FAKE_UPLOAD==="1"}function Fo(e){let t=gunzipSync(new Uint8Array(e)),n=gzipSync(new Uint8Array(t),{level:1});if(Buffer.compare(new Uint8Array(n),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 n}function vo(e){return e.replace(/\/+$/,"")}async function Ee(e){try{return await e.json()}catch{return null}}function ei(e,t,n){let i=e;if(!i||i.success!==true||i.data===void 0)throw new Error(`publish: [E_MALFORMED] ${t} response envelope is malformed (expected { success: true, data }) \u2014 HTTP ${n}`);return i.data}function jo(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(typeof t.contentId=="string"&&t.contentId.length>0)return t.contentId;if(!t.data||typeof t.data!="object"||Array.isArray(t.data))return;let n=t.data;return typeof n.contentId=="string"&&n.contentId.length>0?n.contentId:void 0}function Ho(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(typeof t.slug=="string"&&t.slug.length>0)return t.slug;if(!t.data||typeof t.data!="object"||Array.isArray(t.data))return;let n=t.data;return typeof n.slug=="string"&&n.slug.length>0?n.slug:void 0}function ti(e,t){if(!e||typeof e!="object"||Array.isArray(e))return;let n=e,i=n.data&&typeof n.data=="object"&&!Array.isArray(n.data)?n.data:void 0,o=[n.code,n.message,i?.code,i?.message];for(let r of o){if(typeof r!="string"||!Object.prototype.hasOwnProperty.call(Qn,r))continue;let s=r,c=s==="APP_NAME_CONFLICT"?`marketplace name is already in use: ${t}`:void 0;return y(Qn[s],c)}}async function Bo(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 t=vo(e.baseUrl),n=e.accessPolicy??"private",i=e.manifest.name,o=e.manifest.type==="app"?e.manifest:void 0,r=o!==void 0,s=o?.appId,c;try{c=await fetch(`${t}${ue}/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:n,...s===void 0?{}:{appId:s}})});}catch{throw new Error("publish: [E_NETWORK] Submit request failed (network)")}let p=await Ee(c),l=jo(p),u=Ho(p),d=r&&u!==void 0?u:i,f;if(c.status===xo)f="created";else if(r&&c.status===ko){if(l===void 0)throw y("PUBLISH_CONTENT_ID_MISSING","App republish did not return an opaque contentId");f="existing";}else if(c.status===Co){if(r)throw ti(p,i)??y("APP_NAME_CONFLICT",`marketplace name is already in use: ${i}`);f="existing";}else throw c.status===wt?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 ${c.status}`);let A="not-needed",I=null;if(f==="existing"&&!r){let N;try{N=await fetch(`${t}${ue}/publisher/items`,{method:"GET",headers:{Authorization:`Bearer ${e.accessToken}`}});}catch{throw new Error("publish: [E_NETWORK] Publisher items request failed (network)")}let S=await Ee(N);if(N.status!==200)throw new Error(`publish: [E_HTTP] Publisher items request failed \u2014 HTTP ${N.status}`);let Te=ei(S,"publisher items",N.status)?.items;if(!Array.isArray(Te))throw new Error(`publish: [E_MALFORMED] Publisher items response is malformed (expected data.items[]) \u2014 HTTP ${N.status}`);let _=Te.find(w=>!w||typeof w!="object"?false:w.slug===i);if(!_||typeof _.version!="string")throw new Error(`publish: [E_MALFORMED] Publisher items response does not contain slug "${i}" \u2014 HTTP ${N.status}`);if(I=_.version,I!==e.manifest.version){let w;try{w=await fetch(`${t}${ue}/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(!w.ok)throw await Ee(w),w.status===wt?new Error(`publish: [E_AUTH_EXPIRED] Authentication is expired or missing \u2014 please log in again (HTTP ${w.status})`):w.status===403?new Error(`publish: [E_FORBIDDEN] Version update is forbidden; only the item owner can update an existing item (HTTP ${w.status})`):new Error(`publish: [E_HTTP] Version update failed \u2014 HTTP ${w.status}`);A="applied";}}let M=O.readFileSync(e.tgzPath),z=Vo()?Fo(M):M,F=new FormData;F.set("archive",new Blob([new Uint8Array(z)],{type:"application/gzip"}),`${d}-${e.manifest.version}.tgz`);let m=r&&l!==void 0?l:i,g;try{g=await fetch(`${t}${ue}/publisher/items/${encodeURIComponent(m)}/upload`,{method:"POST",headers:{Authorization:`Bearer ${e.accessToken}`},body:F});}catch{throw new Error("publish: [E_NETWORK] Upload request failed (network)")}if(g.status===wt)throw new Error("publish: [E_AUTH_EXPIRED] Authentication is expired or missing \u2014 please log in again (HTTP 401)");if(!g.ok){let N=await Ee(g);if(r){let S=ti(N,d);if(S)throw S}throw new Error(`publish: [E_HTTP] Upload request failed \u2014 HTTP ${g.status}`)}let H=await Ee(g),G=ei(H,"upload",g.status),Y=typeof G.contentId=="string"&&G.contentId.length>0?G.contentId:l;if(r&&Y===void 0)throw y("PUBLISH_CONTENT_ID_MISSING","App upload did not return an opaque contentId");return {slug:d,version:e.manifest.version,...Y===void 0?{}:{contentId:Y},artifactChecksum:G.artifactChecksum,artifactSizeBytes:G.artifactSizeBytes,submitOutcome:f,versionUpdate:A,serverVersionBefore:I}}var zo=1e4,Go=100*1024*1024;function xt(e){return Ot.createHash("sha256").update(e).digest("hex")}function $o(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Ge(e,t){if(!t||t.includes("\\")||t.includes("\0")||x.posix.isAbsolute(t)||t.split("/").some(r=>r===".."||r.length===0))throw y("PACKAGE_PATH_TRAVERSAL","workspace file path is not a safe relative path");let n=x.resolve(e,...t.split("/")),i=x.resolve(e);if(n!==i&&!n.startsWith(`${i}${x.sep}`))throw y("PACKAGE_PATH_TRAVERSAL","workspace file path escaped the workspace root");let o;try{o=O.lstatSync(n);}catch{throw y("PACKAGE_FILE_INVALID",`workspace file is missing: ${t}`)}if(o.isSymbolicLink())throw y("PACKAGE_SYMLINK",`symlink is not publishable: ${t}`);if(!o.isFile())throw y("PACKAGE_FILE_INVALID",`not a regular file: ${t}`);return new Uint8Array(O.readFileSync(n))}function $e(e,t){return e===t||e.startsWith(`${t}/`)}function Wo(e,t){return e.path<t.path?-1:e.path>t.path?1:e.rule.localeCompare(t.rule)}function ii(e,t,n){let i=e??t;if(!Number.isSafeInteger(i)||i<=0)throw new J("PACKAGE_SIZE_LIMIT",`${n} must be a positive integer`);return i}function oi(e,t,n,i){let o=ii(n.maxFileCount??n.maxFiles,zo,"max file count"),r=ii(n.maxTotalBytes??n.maxBytes,Go,"max total bytes");if(t.length>o)throw new J("PACKAGE_SIZE_LIMIT",`package exceeds file count limit (${o})`);let s=0;for(let c of t){let p=i?.get(c);if(p!==void 0?s+=p.byteLength:s+=Ge(e,c).byteLength,s>r)throw new J("PACKAGE_SIZE_LIMIT",`package exceeds byte limit (${r})`)}}function Jo(e){return e.appId!==void 0||e.expectedDefinitionHash!==void 0}function Ko(e){let t=e.appId!==void 0,n=e.expectedDefinitionHash!==void 0;if(!t&&n)throw y("APP_ID_REQUIRED","appId is required with expectedDefinitionHash");if(t&&!n)throw y("APP_DEFINITION_HASH_REQUIRED","expectedDefinitionHash is required with appId");if(!t||!n)throw y("APP_ID_REQUIRED")}function Xo(e,t){let n=e.filter(i=>i.appId===t);if(n.length===0)throw y("APP_NOT_FOUND",`no publishable App matches ${t}`);if(n.length!==1)throw y("APP_AMBIGUOUS",`more than one App matches ${t}`);return n[0]}function Yo(e){let t=e.localDefinitionRef?.packageRoot;if(!t||!/^(?:apps|skills)\/[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(t))throw y("APP_PACKAGE_ROOT_INVALID","selected App is not rooted in apps/<safe-id> or skills/<safe-id>");return t}function qo(e,t){let n=[];for(let i of e.excluded)n.push($e(i.path,t)?i:{path:i.path,rule:"out-of-app-scope"});for(let i of e.included)$e(i,t)||n.push({path:i,rule:"out-of-app-scope"});return n.sort(Wo)}function Zo(e,t,n,i){let o=`${n}/ui-plugin.json`;if(!i.includes(o))throw y("APP_UI_MANIFEST_INVALID","selected screen App has no package ui-plugin.json");let r=Ge(e,o),s=xt(r),c;try{c=JSON.parse(Buffer.from(r).toString("utf8"));}catch{throw y("APP_UI_MANIFEST_INVALID","ui-plugin.json is not valid JSON")}let p;try{let f=te(c,{mode:"local"});if(f.manifestVersion!==2)throw new Error("screen App requires manifestVersion 2");p=f;}catch(f){throw f instanceof V?y("APP_UI_MANIFEST_INVALID",f.code):y("APP_UI_MANIFEST_INVALID")}if(p.pluginId!==t.appId)throw y("APP_DEFINITION_CONFLICT","ui-plugin.json pluginId no longer matches the selected App");let l=`${n}/ui/index.html`;if(!i.includes(l))throw y("APP_UI_MANIFEST_INVALID","screen entry is outside package scope");let u=xt(Ge(e,l)),d=JSON.parse(JSON.stringify(c));if(d.entryHash=u,Object.prototype.hasOwnProperty.call(d,"initialState")){let f=d.initialState;if(!$o(f)||f.path!=="ui/state.json")throw y("APP_INITIAL_STATE_OUT_OF_SCOPE","initialState must reference ui/state.json inside the package");let A=`${n}/ui/state.json`;if(!i.includes(A))throw y("APP_INITIAL_STATE_OUT_OF_SCOPE","initialState reference is outside the selected package");let I=Ge(e,A);d.initialState={...f,hash:xt(I)};}try{let f=te(d,{mode:"published"});return {bytes:new Uint8Array(Buffer.from(Ye(f),"utf8")),sourceHash:s}}catch(f){throw f instanceof V?y("APP_UI_MANIFEST_INVALID",f.code):y("APP_UI_MANIFEST_INVALID")}}async function Qo(e,t){let{included:n,excluded:i}=Ut(e);oi(e,n,t);let o=Gn(e,n,{version:t.version}),r=Rt(e,n);return {plan:{manifest:o,included:n,excluded:i,secretFindings:r},archiveOptions:{}}}async function es(e,t){Ko(t);let n=await xn(e),i=Xo(n.items,t.appId);if(i.definitionHash!==t.expectedDefinitionHash)throw y("APP_DEFINITION_CONFLICT",`definitionHash changed for ${t.appId}`);let o=Yo(i),r=Ut(e);if(r.excluded.some(A=>$e(A.path,o)&&(A.rule==="symlink"||A.rule==="symlink-dir")))throw y("PACKAGE_SYMLINK","selected App package contains a symlink");let s=r.included.filter(A=>$e(A,o)),c=qo(r,o),p=new Map,l=new Map;if(i.capabilities.includes("screen")){let A=Zo(e,i,o,s);p.set(`${o}/ui-plugin.json`,A.bytes),l.set(`${o}/ui-plugin.json`,A.sourceHash);}if(i.capabilities.includes("skill")&&!s.includes(`${o}/SKILL.md`))throw y("APP_SKILL_MISSING","skill capability requires package-root SKILL.md");oi(e,s,t,p);let u={appId:i.appId,version:t.version??"",description:i.description,capabilities:i.capabilities,packageRoot:o,...i.definition?.id===void 0?{}:{definitionId:i.definition.id},definitionHash:i.definitionHash,includedFiles:s,generatedFiles:p},d=$n(e,u),f=Rt(e,s,p);return {plan:{manifest:d,included:s,excluded:c,secretFindings:f},archiveOptions:{generatedFiles:p,sourceFileHashes:l}}}async function si(e,t){let n=x.resolve(e);if(Jo(t))return es(n,t);if(t.expectedDefinitionHash!==void 0)throw y("APP_ID_REQUIRED");return Qo(n,t)}async function dc(e,t={}){return (await si(e,t)).plan}function ts(e){let t=e.map(n=>`${n.path}:${n.line} (${n.rule})`).join(", ");throw new J("PUBLISH_SECRET_FINDINGS",`aborted \u2014 secret findings must be resolved before packing: ${t}`)}async function ai(e,t={}){let n=x.resolve(e),i=await si(n,t);i.plan.secretFindings.length>0&&ts(i.plan.secretFindings);let o=await Zn(n,i.plan.manifest,i.archiveOptions);return {manifest:i.plan.manifest,tgzPath:o}}async function uc(e,t={}){return ai(e,t)}async function fc(e,t){let n=await ai(e,t);if(n.manifest.type!=="app")throw new Error("publish: App pack unexpectedly produced a template manifest");return n}
2
+ export{Go as DEFAULT_PUBLISH_MAX_BYTES,zo as DEFAULT_PUBLISH_MAX_FILES,kn as EXCLUDE_RULES,ue as MARKETPLACE_API_PREFIX,J as PublishError,fc as packApp,ai as packPublish,uc as packTemplate,dc as planPublish,Bo as uploadToMarketplace};