minecodex 2.0.30 → 2.0.32

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.
@@ -97,7 +97,7 @@ Boolean requesting whether a visible border and background is provided by the ho
97
97
  - omitted: host decides border`)}),A$=p.object({method:p.literal("ui/request-display-mode"),params:p.object({mode:_c.describe("The display mode being requested.")})}),w_=p.object({mode:_c.describe("The display mode that was actually set. May differ from requested if not supported.")}).passthrough(),I_=p.union([p.literal("model"),p.literal("app")]).describe("Tool visibility scope - who can access the tool."),y$=p.object({resourceUri:p.string().optional(),visibility:p.array(I_).optional().describe(`Who can access this tool. Default: ["model", "app"]
98
98
  - "model": Tool visible to and callable by the agent
99
99
  - "app": Tool callable by the app from this server only`),csp:p.never().optional(),permissions:p.never().optional()}),b$=p.object({mimeTypes:p.array(p.string()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.')}),S$=p.object({method:p.literal("ui/download-file"),params:p.object({contents:p.array(p.union([fi,hi])).describe("Resource contents to download \u2014 embedded (inline data) or linked (host fetches). Uses standard MCP resource types.")})}),x$=p.object({method:p.literal("ui/message"),params:p.object({role:p.literal("user").describe('Message role, currently only "user" is supported.'),content:p.array(Sr).describe("Message content blocks (text, image, etc.).")})}),w$=p.object({method:p.literal("ui/notifications/sandbox-resource-ready"),params:p.object({html:p.string().describe("HTML content to load into the inner iframe."),sandbox:p.string().optional().describe("Optional override for the inner iframe's sandbox attribute."),csp:cv.optional().describe("CSP configuration from resource metadata."),permissions:lv.optional().describe("Sandbox permissions from resource metadata.")})}),k_=p.object({method:p.literal("ui/notifications/tool-result"),params:zn.describe("Standard MCP tool execution result.")}),ux=p.object({toolInfo:p.object({id:ar.optional().describe("JSON-RPC id of the tools/call request."),tool:kn.describe("Tool definition including name, inputSchema, etc.")}).optional().describe("Metadata of the tool call that instantiated this App."),theme:c_.optional().describe("Current color theme preference."),styles:A_.optional().describe("Style configuration for theming the app."),displayMode:_c.optional().describe("How the UI is currently displayed."),availableDisplayModes:p.array(_c).optional().describe("Display modes the host supports."),containerDimensions:p.union([p.object({height:p.number().describe("Fixed container height in pixels.")}),p.object({maxHeight:p.union([p.number(),p.undefined()]).optional().describe("Maximum container height in pixels.")})]).and(p.union([p.object({width:p.number().describe("Fixed container width in pixels.")}),p.object({maxWidth:p.union([p.number(),p.undefined()]).optional().describe("Maximum container width in pixels.")})])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other
100
- container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:p.string().optional().describe("User's language and region preference in BCP 47 format."),timeZone:p.string().optional().describe("User's timezone in IANA format."),userAgent:p.string().optional().describe("Host application identifier."),platform:p.union([p.literal("web"),p.literal("desktop"),p.literal("mobile")]).optional().describe("Platform type for responsive design decisions."),deviceCapabilities:p.object({touch:p.boolean().optional().describe("Whether the device supports touch input."),hover:p.boolean().optional().describe("Whether the device supports hover interactions.")}).optional().describe("Device input capabilities."),safeAreaInsets:p.object({top:p.number().describe("Top safe area inset in pixels."),right:p.number().describe("Right safe area inset in pixels."),bottom:p.number().describe("Bottom safe area inset in pixels."),left:p.number().describe("Left safe area inset in pixels.")}).optional().describe("Mobile safe area boundaries in pixels.")}).passthrough(),z_=p.object({method:p.literal("ui/notifications/host-context-changed"),params:ux.describe("Partial context update containing only changed fields.")}),I$=p.object({method:p.literal("ui/update-model-context"),params:p.object({content:p.array(Sr).optional().describe("Context content blocks (text, image, etc.)."),structuredContent:p.record(p.string(),p.unknown().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.")})}),k$=p.object({method:p.literal("ui/initialize"),params:p.object({appInfo:yr.describe("App identification (name and version)."),appCapabilities:x_.describe("Features and capabilities this app provides."),protocolVersion:p.string().describe("Protocol version this app supports.")})}),E_=p.object({protocolVersion:p.string().describe('Negotiated protocol version string (e.g., "2025-11-21").'),hostInfo:yr.describe("Host application identification and version."),hostCapabilities:S_.describe("Features and capabilities provided by the host."),hostContext:ux.describe("Rich context about the host environment.")}).passthrough(),R_={target:"draft-2020-12"};async function cx(e,t){let i=e["~standard"];if(i.jsonSchema)return i.jsonSchema[t](R_);throw Error(`Schema (vendor: ${i.vendor}) does not implement Standard JSON Schema (~standard.jsonSchema). Use a library that does (zod v4, ArkType, Valibot) or wrap your schema accordingly.`)}async function lx(e,t,i=""){let o=await e["~standard"].validate(t);if(o.issues){let r=o.issues.map(n=>{let a=n.path?.map(s=>typeof s=="object"?s.key:s).join(".");return a?`${a}: ${n.message}`:n.message}).join("; ");throw Error(i+r)}return o.value}function __(e,t){let i={...e,...t};return t.experimental!==void 0&&(i.experimental={...e.experimental,...t.experimental}),t.tools!==void 0&&(i.tools={...e.tools,...t.tools}),i}var vd=class e extends iv{_appInfo;_appCapabilities;options;_hostCapabilities;_hostInfo;_hostContext;_registeredTools={};_initializedSent=!1;_registeredEvents=new Set;_events=new ov;_methods=new av;setRequestHandler=(...t)=>{let[i,...o]=ax("request",t)??t;this._methods.claim(i,"setRequestHandler"),super.setRequestHandler.call(this,i,...o)};setNotificationHandler=(...t)=>{let[i,...o]=ax("notification",t)??t;this._methods.claim(i,"setNotificationHandler"),super.setNotificationHandler.call(this,i,...o)};removeRequestHandler=t=>{this._methods.release(t),super.removeRequestHandler(t)};removeNotificationHandler=t=>{this._methods.release(t),super.removeNotificationHandler(t)};replaceRequestHandler=(t,...i)=>{this._methods.replace(t),super.setRequestHandler.call(this,t,...i)};_assertInitialized(t){if(this._initializedSent)return;let i=`[ext-apps] App.${t}() called before connect() completed the ui/initialize handshake. Await app.connect() before calling this method, or move data loading to an ontoolresult handler.`;if(this.options?.strict)throw Error(i);console.warn(`${i}. This will throw in a future release.`)}eventSchemas={toolinput:f_,toolinputpartial:h_,toolresult:k_,toolcancelled:g_,hostcontextchanged:z_};static ONE_SHOT_EVENTS=new Set(["toolinput","toolinputpartial","toolresult","toolcancelled"]);_everHadListener=new Set;_assertHandlerTiming(t){if(!e.ONE_SHOT_EVENTS.has(t)||this._everHadListener.has(t)||(this._everHadListener.add(t),!this._initializedSent))return;let i=`[ext-apps] "${String(t)}" handler registered after connect() completed the ui/initialize handshake. The host may have already sent this notification. Register handlers before calling app.connect().`;if(this.options?.strict)throw Error(i);console.warn(i)}setEventHandler(t,i){i&&this._assertHandlerTiming(t),this._ensureEventSlot(t),this._events.setHandler(t,i)}addEventListener(t,i){this._assertHandlerTiming(t),this._ensureEventSlot(t),this._events.addEventListener(t,i)}removeEventListener(t,i){this._events.removeEventListener(t,i)}_ensureEventSlot(t){if(this._registeredEvents.has(t))return;let i=this.eventSchemas[t];if(!i)throw Error(`Unknown event: ${String(t)}`);this.setNotificationHandler(i.shape.method.value,{params:i.shape.params},o=>{let r=o;t==="hostcontextchanged"&&(this._hostContext={...this._hostContext,...r}),this._events.dispatch(t,r)}),this._registeredEvents.add(t)}getEventHandler(t){return this._events.getHandler(t)}warnIfRequestHandlerReplaced(t,i,o){i&&o&&console.warn(`[MCP Apps] ${t} handler replaced. Previous handler will no longer be called.`)}constructor(t,i={},o={autoResize:!0}){super(o),this._appInfo=t,this._appCapabilities=i,this.options=o,this._methods.replace("notifications/cancelled"),this._methods.replace("notifications/progress"),!o.allowUnsafeEval&&p.config({jitless:!0}),this.replaceRequestHandler("ping",r=>(console.log("Received ping:",r.params),{})),this.setEventHandler("hostcontextchanged",void 0)}buildContext(t){return t}registerAppCapabilities(t){if(this.transport)throw Error("Cannot register capabilities after transport is established");this._appCapabilities=__(this._appCapabilities,t)}registerTool(t,i,o){if(this._registeredTools[t])throw Error(`Tool ${t} is already registered`);let r=this,n=()=>{r._initializedSent&&r._appCapabilities.tools?.listChanged&&r.sendToolListChanged()},a=i.inputSchema!==void 0,s={title:i.title,description:i.description,inputSchema:i.inputSchema,outputSchema:i.outputSchema,annotations:i.annotations,_meta:i._meta,enabled:!0,enable(){this.enabled=!0,n()},disable(){this.enabled=!1,n()},update(c){Object.assign(this,c),n()},remove(){r._registeredTools[t]===s&&(delete r._registeredTools[t],n())},handler:async(c,l)=>{if(!s.enabled)throw Error(`Tool ${t} is disabled`);let d;if(a){let f=s.inputSchema,h=f?await lx(f,c??{},`Invalid input for tool ${t}: `):c??{};d=await o(h,l)}else d=await o(l);return s.outputSchema&&!d.isError&&(d.structuredContent=await lx(s.outputSchema,d.structuredContent,`Invalid output for tool ${t}: `)),d}};return this._registeredTools[t]=s,!this._appCapabilities.tools&&!this.transport&&this.registerAppCapabilities({tools:{listChanged:!0}}),this.ensureToolHandlersInitialized(),n(),s}_toolHandlersInitialized=!1;ensureToolHandlersInitialized(){this._toolHandlersInitialized||(this._toolHandlersInitialized=!0,this.oncalltool=async(t,i)=>{let o=this._registeredTools[t.name];if(!o)throw Error(`Tool ${t.name} not found`);return o.handler(t.arguments,i)},this.onlisttools=async(t,i)=>({tools:await Promise.all(Object.entries(this._registeredTools).filter(([o,r])=>r.enabled).map(async([o,r])=>{let n={name:o,title:r.title,description:r.description,inputSchema:r.inputSchema?await cx(r.inputSchema,"input"):{type:"object",properties:{}}};return r.outputSchema&&(n.outputSchema=await cx(r.outputSchema,"output")),r.annotations&&(n.annotations=r.annotations),r._meta&&(n._meta=r._meta),n}))}))}async sendToolListChanged(t={}){this._assertInitialized("sendToolListChanged"),await this.notification({method:"notifications/tools/list_changed",params:t})}getHostCapabilities(){return this._hostCapabilities}getHostVersion(){return this._hostInfo}getHostContext(){return this._hostContext}get ontoolinput(){return this.getEventHandler("toolinput")}set ontoolinput(t){this.setEventHandler("toolinput",t)}get ontoolinputpartial(){return this.getEventHandler("toolinputpartial")}set ontoolinputpartial(t){this.setEventHandler("toolinputpartial",t)}get ontoolresult(){return this.getEventHandler("toolresult")}set ontoolresult(t){this.setEventHandler("toolresult",t)}get ontoolcancelled(){return this.getEventHandler("toolcancelled")}set ontoolcancelled(t){this.setEventHandler("toolcancelled",t)}get onhostcontextchanged(){return this.getEventHandler("hostcontextchanged")}set onhostcontextchanged(t){this.setEventHandler("hostcontextchanged",t)}_onteardown;get onteardown(){return this._onteardown}set onteardown(t){this.warnIfRequestHandlerReplaced("onteardown",this._onteardown,t),this._onteardown=t,this.replaceRequestHandler("ui/resource-teardown",{params:y_.shape.params,result:b_},(i,o)=>{if(!this._onteardown)throw Error("No onteardown handler set");return this._onteardown(i,o)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(t){this.warnIfRequestHandlerReplaced("oncalltool",this._oncalltool,t),this._oncalltool=t,this.replaceRequestHandler("tools/call",(i,o)=>{if(!this._oncalltool)throw Error("No oncalltool handler set");return this._oncalltool(i.params,o)})}_onlisttools;get onlisttools(){return this._onlisttools}set onlisttools(t){this.warnIfRequestHandlerReplaced("onlisttools",this._onlisttools,t),this._onlisttools=t,this.replaceRequestHandler("tools/list",(i,o)=>{if(!this._onlisttools)throw Error("No onlisttools handler set");return this._onlisttools(i.params,o)})}assertCapabilityForMethod(t){switch(t){case"sampling/createMessage":if(!this._hostCapabilities?.sampling)throw Error(`Host does not support sampling (required for ${t})`);break}}assertRequestHandlerCapability(t){switch(t){case"tools/call":case"tools/list":if(!this._appCapabilities.tools)throw Error(`Client does not support tool capability (required for ${t})`);return;default:return}}assertNotificationCapability(t){}async callServerTool(t,i){if(this._assertInitialized("callServerTool"),typeof t=="string")throw Error(`callServerTool() expects an object as its first argument, but received a string ("${t}"). Did you mean: callServerTool({ name: "${t}", arguments: { ... } })?`);return await this.request({method:"tools/call",params:t},{onprogress:()=>{},resetTimeoutOnProgress:!0,...i})}async readServerResource(t,i){return this._assertInitialized("readServerResource"),await this.request({method:"resources/read",params:t},i)}async listServerResources(t,i){return this._assertInitialized("listServerResources"),await this.request({method:"resources/list",params:t},i)}async createSamplingMessage(t,i){return this._assertInitialized("createSamplingMessage"),await this.request({method:"sampling/createMessage",params:t},i)}sendMessage(t,i){return this._assertInitialized("sendMessage"),this.request({method:"ui/message",params:t},p_,i)}sendLog(t){return this.notification({method:"notifications/message",params:t})}updateModelContext(t,i){return this._assertInitialized("updateModelContext"),this.request({method:"ui/update-model-context",params:t},In,i)}openLink(t,i){return this._assertInitialized("openLink"),this.request({method:"ui/open-link",params:t},d_,i)}sendOpenLink=this.openLink;downloadFile(t,i){return this._assertInitialized("downloadFile"),this.request({method:"ui/download-file",params:t},m_,i)}requestTeardown(t={}){return this.notification({method:"ui/notifications/request-teardown",params:t})}requestDisplayMode(t,i){return this._assertInitialized("requestDisplayMode"),this.request({method:"ui/request-display-mode",params:t},w_,i)}sendSizeChanged(t){return this.notification({method:"ui/notifications/size-changed",params:t})}setupSizeChangedNotifications(){let t=!1,i=0,o=0,r=()=>{t||(t=!0,requestAnimationFrame(()=>{t=!1;let a=document.documentElement,s=a.style.height;a.style.height="max-content";let c=Math.ceil(a.getBoundingClientRect().height);a.style.height=s;let l=Math.ceil(window.innerWidth);(l!==i||c!==o)&&(i=l,o=c,this.sendSizeChanged({width:l,height:c}))}))};r();let n=new ResizeObserver(r);return n.observe(document.documentElement),n.observe(document.body),()=>n.disconnect()}async connect(t=new sv(window.parent,window.parent),i){if(this.transport)throw Error("App is already connected. Call close() before connecting again.");this._initializedSent=!1;try{await super.connect(t);let o=await this.request({method:"ui/initialize",params:{appCapabilities:this._appCapabilities,appInfo:this._appInfo,protocolVersion:a_}},E_,i);if(o===void 0)throw Error(`Server sent invalid initialize result: ${o}`);this._hostCapabilities=o.hostCapabilities,this._hostInfo=o.hostInfo,this._hostContext=o.hostContext,await this.notification({method:"ui/notifications/initialized"}),this._initializedSent=!0,this.options?.autoResize&&this.setupSizeChangedNotifications()}catch(o){throw this.close(),o}}};function dx(e,t){let i=t.resources.icons,o="data-minecodex-quick-prompts",r=()=>(document.documentElement.lang||navigator.language||"en").toLowerCase().startsWith("zh"),n=(g,y)=>r()?y:g,a=document.createElement("style");a.textContent=t.resources.styles,document.head.append(a);let s=null,c=null,l=null,d=null,f=null,h=null,m=null,A=[],x=0,C=!1,M=!1,T=[],Q={},re=[],me={"bar-chart":"\u67F1\u72B6\u56FE",book:"\u4E66\u7C4D",brain:"\u5927\u8111","currency-dollar":"\u7F8E\u5143",customize:"\u81EA\u5B9A\u4E49",dumbbell:"\u54D1\u94C3",edit:"\u7F16\u8F91",flask:"\u70E7\u74F6",folder:"\u6587\u4EF6\u5939",function:"\u51FD\u6570",globe:"\u5730\u7403","graduation-cap":"\u5B66\u58EB\u5E3D",heart:"\u7231\u5FC3",kettlebell:"\u58F6\u94C3",logs:"\u7B14\u8BB0",lotus:"\u83B2\u82B1",music:"\u97F3\u4E50",palette:"\u8C03\u8272\u76D8",paw:"\u722A\u5370",plant:"\u690D\u7269",popcorn:"\u7206\u7C73\u82B1",scale:"\u5929\u5E73",stethoscope:"\u542C\u8BCA\u5668",terminal:"\u7EC8\u7AEF",wrench:"\u6273\u624B",writing:"\u5199\u4F5C",blue:"\u84DD\u8272",green:"\u7EFF\u8272",orange:"\u6A59\u8272",pink:"\u7C89\u8272",purple:"\u7D2B\u8272",red:"\u7EA2\u8272",yellow:"\u9EC4\u8272",black:"\u4E2D\u6027\u8272"};function H(g){return n(g.replaceAll("-"," "),me[g]??g)}function pe(g){let y={"No available input in the focused window":"\u5F53\u524D\u7A97\u53E3\u6CA1\u6709\u53EF\u7528\u8F93\u5165\u6846\uFF0C\u8BF7\u5148\u6253\u5F00\u804A\u5929\u5E76\u786E\u8BA4 MCX \u589E\u5F3A\u670D\u52A1\u5DF2\u5F00\u542F\u3002","Input changed before insertion":"\u8F93\u5165\u6846\u5DF2\u5207\u6362\uFF0C\u8BF7\u91CD\u65B0\u9009\u62E9\u63D0\u793A\u8BCD\u3002","Enable Prompts in MineCodex first":"\u8BF7\u5148\u5728 MineCodex \u4E2D\u5F00\u542F\u63D0\u793A\u8BCD\u3002","Open a chat before using a prompt.":"\u8BF7\u5148\u6253\u5F00\u4E00\u4E2A\u5BF9\u8BDD\uFF0C\u518D\u4F7F\u7528\u63D0\u793A\u8BCD\u3002","Category was not found":"\u672A\u627E\u5230\u8BE5\u5206\u7C7B","Prompt was not found":"\u672A\u627E\u5230\u8BE5\u63D0\u793A\u8BCD","Choose one emoji or leave it empty":"\u8BF7\u9009\u62E9\u4E00\u4E2A Emoji\uFF0C\u6216\u7559\u7A7A\u4EE5\u7EE7\u627F\u5206\u7C7B\u56FE\u6807","Invalid sort order":"\u6392\u5E8F\u65E0\u6548\uFF0C\u8BF7\u91CD\u8BD5","Invalid order":"\u6392\u5E8F\u65E0\u6548\uFF0C\u8BF7\u91CD\u8BD5","Invalid category":"\u5206\u7C7B\u65E0\u6548\uFF0C\u8BF7\u91CD\u8BD5","Items changed; refresh and try again":"\u6761\u76EE\u5DF2\u53D1\u751F\u53D8\u5316\uFF0C\u8BF7\u5237\u65B0\u540E\u91CD\u8BD5"};return n(g.message||"Something went wrong. Please try again.",y[g.message]??"\u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u91CD\u8BD5\u3002")}function $(g,y,z){let k=document.createElement(g);return y&&(k.className=y),z!=null&&(k.textContent=z),k}function Se(g){return new DOMParser().parseFromString(i[g],"image/svg+xml").documentElement.cloneNode(!0)}function fe(g,y,z="qp-command",k=null){let E=$("button",z,k?null:g);return E.type="button",E.setAttribute("aria-label",g),k&&(E.append(Se(k)),E.setAttribute("data-minecodex-tooltip",g)),E.addEventListener("click",y),E}async function $e(g,{method:y="GET",body:z}={}){return t.requestHostAction("quick-prompts",{route:g,method:y,body:z})}function sr(g){if(!m)return;m.querySelector(".qp-error")?.remove();let y=$("div","qp-error",pe(g));y.setAttribute("role","alert"),m.append(y)}function Ct(){!m||!l?.isConnected||t.ui.composerMenu(m,c)}function Xe(g=!1){Oe(!0),Lt?.disconnect(),x++,m?.remove(),m=null,s?.setAttribute("aria-expanded","false"),s?.setAttribute("data-state","closed"),g&&s?.focus({preventScroll:!0})}let ot="all",Lt=null,De=null,yt=null,wr=null;function Oe(g=!1,y=0){clearTimeout(yt),clearTimeout(wr);let z=De;if(z){if(z.anchor.removeAttribute("data-preview"),g||Nt()){z.node.remove(),De=null;return}z.node.style.pointerEvents="none",Qt(z.node,{opacity:0,transform:`translateY(${Math.max(-10,Math.min(10,y))}px) scale(.98)`},150),wr=setTimeout(()=>{z.node.remove(),De===z&&(De=null)},150)}}function Dt(g,y){Oe(!0);let z=ct(g);z&&(yt=setTimeout(()=>{if(!m||!y.isConnected)return;let k=$("div","qp-image-preview");t.ui.surface(k,"popover"),t.ui.mount(k,"floating");let E=$("img");E.alt=n(`Full image: ${g.summary}`,`\u5B8C\u6574\u56FE\u7247\uFF1A${g.summary}`);let U=()=>{if(De?.node!==k||!E.naturalWidth)return;let L=y.getBoundingClientRect(),Z=m.getBoundingClientRect(),O=innerWidth-Z.right-24,q=Z.left-24,G=Math.max(O,q);if(G<96){Oe(!0);return}let F=Math.min(280/E.naturalWidth,G/E.naturalWidth,360/E.naturalHeight,(innerHeight-24)/E.naturalHeight),ee=E.naturalWidth*F,Y=E.naturalHeight*F;k.style.width=`${ee}px`,k.style.height=`${Y}px`,k.style.left=`${O>=ee?Z.right+12:Z.left-ee-12}px`,k.style.top=`${Math.max(12,Math.min(L.top+(L.height-Y)/2,innerHeight-Y-12))}px`,k.style.visibility="visible",Nt()||k.animate([{opacity:0,transform:"translateX(-4px) scale(.98)"},{opacity:1,transform:"none"}],{duration:180,easing:"cubic-bezier(.22,1,.36,1)"})};k.append(E),De={node:k,anchor:y},y.dataset.preview="true",k.addEventListener("pointerenter",()=>clearTimeout(yt)),k.addEventListener("pointerleave",()=>Oe()),E.onload=U,E.src=z.data,E.complete&&U()},160))}function Hr(){let g=$("div","qp-tabs-bar"),y=$("div","qp-tabs");y.setAttribute("role","tablist"),y.setAttribute("aria-label",n("Prompt categories","\u63D0\u793A\u8BCD\u5206\u7C7B"));let z=[{id:"all",name:n("All","\u5168\u90E8")},...T.filter(O=>Ze(O.id).length),...Ze(null).length?[{id:"other",name:n("Other","\u5176\u4ED6")}]:[]];z.some(O=>O.id===ot)||(ot="all");for(let O of z){let q=fe(O.name,()=>{ot=O.id,bt(),m.querySelector('[aria-selected="true"]')?.focus({preventScroll:!0})},"qp-tab");q.setAttribute("role","tab"),q.setAttribute("aria-selected",String(O.id===ot)),q.setAttribute("aria-controls","mcx-quick-results"),y.append(q)}let k=$("div","qp-tab-arrows"),E=O=>y.scrollBy({left:O*Math.max(100,y.clientWidth-90),behavior:Nt()?"instant":"smooth"}),U=fe(n("Previous categories","\u524D\u9762\u7684\u5206\u7C7B"),()=>E(-1),"qp-tab-arrow qp-tab-previous","chevron"),L=fe(n("More categories","\u540E\u9762\u7684\u5206\u7C7B"),()=>E(1),"qp-tab-arrow qp-tab-next","chevron");k.append(U,L),g.append(y,k);let Z=()=>{let q=[...y.children].reduce((G,F)=>G+F.offsetWidth+2,-2)>y.clientWidth+1;U.hidden=!q||y.scrollLeft<=1,L.hidden=!q||y.scrollLeft+y.clientWidth>=y.scrollWidth-1,k.hidden=!q,g.dataset.overflow=String(q),y.style.setProperty("--qp-arrow-space",`${q?68:0}px`)};return y.addEventListener("scroll",Z,{passive:!0}),y.addEventListener("keydown",O=>{if(!["ArrowLeft","ArrowRight"].includes(O.key))return;O.preventDefault();let q=[...y.children],G=q.indexOf(document.activeElement);q[Math.max(0,Math.min(q.length-1,G+(O.key==="ArrowRight"?1:-1)))]?.focus()}),Lt=new ResizeObserver(Z),Lt.observe(y),requestAnimationFrame(()=>{if(!g.isConnected)return;Z();let O=y.querySelector('[aria-selected="true"]');O&&(y.scrollLeft=Math.max(0,O.offsetLeft-y.offsetLeft-y.clientWidth+O.offsetWidth+68)),Z()}),g}async function Ir(){let g=++x;m.replaceChildren(),m.append($("div","qp-empty",n("Loading\u2026","\u52A0\u8F7D\u4E2D\u2026")));try{let y=await $e("/api/state");if(!m||g!==x)return;A=y.prompts,T=y.categories,Q=y.icons,re=y.emojis??[],bt()}catch(y){m&&g===x&&(m.querySelector(".qp-empty")?.remove(),sr(y),m.append(fe(n("Retry","\u91CD\u8BD5"),Ir)))}}let Pt={black:["var(--mcx-color-text-secondary)","var(--mcx-color-text-secondary)"],blue:["#0285ff","#339cff"],green:["#04b84c","#40c977"],orange:["#fb6a22","#ff8549"],pink:["#ff66ad","#ff8cc1"],purple:["#924ff7","#ad7bf9"],red:["#fa423e","#ff6764"],yellow:["#ffc300","#ffd240"]};function at(g){let y=$("span","qp-symbol");if(g.emoji)return y.textContent=g.emoji,y;let z=T.find(U=>U.id===g.categoryId),k=new DOMParser().parseFromString(Q[z?.icon??"book"]??i.prompt,"image/svg+xml").documentElement;y.append(k.cloneNode(!0));let E=Pt[z?.color??"black"]??Pt.black;return y.style.setProperty("--prompt-icon-light",E[0]),y.style.setProperty("--prompt-icon-dark",E[1]),y}function Ze(g){return A.filter(y=>y.categoryId===g).sort((y,z)=>y.sortOrder-z.sortOrder||y.createdAt-z.createdAt||y.id.localeCompare(z.id))}function bt(){Oe(!0),Lt?.disconnect(),m.replaceChildren();let g=$("div","qp-scroll");A.length||g.append($("div","qp-empty",n("No prompts yet","\u8FD8\u6CA1\u6709\u63D0\u793A\u8BCD")));let y=A.filter(E=>E.useCount>0).sort((E,U)=>U.calledAt-E.calledAt||E.id.localeCompare(U.id)).slice(0,3);m.append(Hr()),g.id="mcx-quick-results";let z=0;g.addEventListener("scroll",()=>{let E=z-g.scrollTop;z=g.scrollTop,Oe(!1,E)},{passive:!0});let k=[{id:"recent",name:n("Recently used","\u6700\u8FD1\u4F7F\u7528"),prompts:y},...T.map(E=>({id:E.id,name:E.name,prompts:Ze(E.id)})),{id:"other",name:n("Other","\u5176\u4ED6"),prompts:Ze(null)}];for(let E of k.filter(U=>U.prompts.length&&(ot==="all"||U.id===ot))){g.append($("div","qp-header",E.name));for(let U of E.prompts){let L=$("div","qp-row"),Z=fe(U.summary,async()=>{let O=x;try{if(!f?.isConnected||!t.codex.composer(f,{purpose:"insertion"}))throw new Error("Input changed before insertion");window.__codexPersonalRuntime.insertText(U.body,f),Xe(),await $e(`/api/prompts/${encodeURIComponent(U.id)}/use`,{method:"POST",body:{action:"insert",success:!0}})}catch(q){x===O?sr(q):console.warn("[Prompts] Usage could not be saved",q)}},"qp-select");Z.replaceChildren(at(U),$("span","qp-title",U.summary)),U.title&&Z.append($("span","qp-preview",U.body.replace(/\s+/g," "))),Z.addEventListener("pointerenter",()=>Dt(U,Z)),Z.addEventListener("focus",()=>Dt(U,Z)),Z.addEventListener("pointerleave",()=>{clearTimeout(yt),yt=setTimeout(()=>Oe(),100)}),Z.addEventListener("blur",()=>Oe()),L.append(Z),g.append(L)}}g.children.length||g.append($("div","qp-empty",n("No prompts yet","\u8FD8\u6CA1\u6709\u63D0\u793A\u8BCD"))),m.append(g),Ct()}function kr(){if(m){Xe(!0);return}c.getAttribute("aria-expanded")==="true"&&c.click(),m=$("div"),m.setAttribute(o,"panel"),t.ui.surface(m,"composer-menu"),m.setAttribute("role","dialog"),m.setAttribute("aria-label",n("Quick Prompts","\u5FEB\u6377\u63D0\u793A\u8BCD")),document.body.append(m),s.setAttribute("aria-expanded","true"),s.setAttribute("data-state","open"),Ct(),Ir()}function Rn(g){return g.getAttribute("aria-expanded")==="true"&&g.checkVisibility({visibilityProperty:!0})&&(g.getAttribute("data-composer-navigation-target")==="add-context"||g.getAttribute("aria-haspopup")==="menu")}function _n(){let g=document.activeElement?.tagName==="IFRAME"?h:null;return t.codex.composer(g,{purpose:"insertion"})}function zr(){if(M||e.aborted||t.management)return;let g=m?t.codex.composer(f,{purpose:"insertion"}):_n(),y=g?.add,z=g?.root,k=g?.threadId??null;if(k!==d&&(Xe(),d=k),(y!==c||z!==l||g?.editable!==f)&&(Xe(),s?.remove(),s=null,c=y,l=z),f=g?.editable??null,Nn?.remember(g),!!y){if(m&&[...z.querySelectorAll("button")].some(Rn)&&Xe(),!s){s=y.cloneNode(!1),s.removeAttribute("title"),s.removeAttribute("aria-describedby"),s.removeAttribute("id"),s.removeAttribute("data-composer-navigation-target"),s.setAttribute(o,"button"),s.setAttribute("aria-label",n("Quick Prompts","\u5FEB\u6377\u63D0\u793A\u8BCD")),s.setAttribute("data-minecodex-tooltip",n("Quick Prompts","\u5FEB\u6377\u63D0\u793A\u8BCD")),s.setAttribute("aria-haspopup","dialog"),s.setAttribute("aria-expanded","false"),s.setAttribute("data-state","closed");for(let E of y.children){let U=E.cloneNode(!0);for(let L of U.querySelectorAll("svg")){let Z=Se("prompt");for(let O of["class","width","height","aria-hidden","focusable"])L.hasAttribute(O)&&Z.setAttribute(O,L.getAttribute(O));L.replaceWith(Z)}s.append(U)}s.addEventListener("click",kr),y.after(s)}s.className!==y.className&&(s.className=y.className),Ct()}}let ce=null,Kt=0,_e="all",st="manual",Zt="cards";try{Zt=localStorage.getItem("minecodex.prompts.view")==="list"?"list":"cards"}catch{}let cr=null,Er="",xe=null,Rr=null;function Ve(g,y,z=!1,k="secondary"){return t.ui.action(fe(g,y,`pm-command${z?" pm-primary":""}`),z?"primary":k)}function Tt(g){if(!ce)return;ce.querySelector(".pm-error")?.remove();let y=$("div","pm-error",pe(g));y.setAttribute("role","alert"),(xe??ce.querySelector(".pm-wrap")??ce).append(y)}function Yr(){ce&&Object.assign(ce.style,{inset:"0",borderRadius:"0"})}function Xr(g=!1,y=!0){Xt?.cancel(),Fe(),cr?.disconnect(),Kt++,Ne(),dr(!1),ce&&t.ui.releasePage(ce,{restoreNavigation:y}),ce?.remove(),ce=null,xe=null,document.documentElement.removeAttribute("data-mcx-prompts-open"),g&&Rr?.isConnected&&Rr.focus({preventScroll:!0})}async function jt(){let g=++Kt;try{let y=await $e("/api/state");if(!ce||g!==Kt)return;A=y.prompts,T=y.categories,Q=y.icons,re=y.emojis??[],lr()}catch(y){g===Kt&&Tt(y)}}function Cn(){if(Xe(),!ce)return Rr=document.activeElement,ce=$("section"),ce.setAttribute(o,"page"),t.ui.page(ce,{sidebar:"none",onNavigate:()=>Xr(!1,!1)}),ce.setAttribute("aria-label",n("Prompt","\u63D0\u793A\u8BCD")),document.body.append(ce),document.documentElement.setAttribute("data-mcx-prompts-open",""),Yr(),ce.append($("div","pm-empty",n("Loading\u2026","\u52A0\u8F7D\u4E2D\u2026"))),jt()}let be=null,St=null;function Ht(g,y,z){let k=fe(g,z,"pm-icon",y);return k.setAttribute("data-minecodex-tooltip",g),k}function Ne(g=!1){be?.remove(),be=null,St?.setAttribute("aria-expanded","false"),g&&St?.isConnected&&St.focus({preventScroll:!0}),St=null}function Yt(g,y,z,k=!1){if(St===g)return Ne(!0),null;Ne(),St=g,g.setAttribute("aria-expanded","true"),be=$("div",`pm-popup ${y}`),t.ui.surface(be,"dropdown"),be.setAttribute("role",z),be.setAttribute("aria-label",g.getAttribute("aria-label")),(et??ce).append(be);let E=g.getBoundingClientRect();k&&(be.style.boxSizing="border-box",be.style.width=`${E.width}px`);let U=be.getBoundingClientRect().width;return be.style.top=`${E.bottom+6}px`,be.style.left=`${Math.max(8,Math.min(E.right-U,innerWidth-U-8))}px`,be}function _r(){let g=$("div","pm-search-inline"),y=$("input");y.type="text",y.autocomplete="off",y.placeholder=n("Search prompts","\u641C\u7D22\u63D0\u793A\u8BCD"),y.setAttribute("aria-label",y.placeholder),y.value=Er;let z=()=>{Er=y.value,$t(ce.querySelector(".pm-list"))};return y.addEventListener("input",z),y.addEventListener("keydown",k=>{k.key==="Escape"&&(k.stopPropagation(),k.preventDefault(),y.value="",z())}),g.append(Se("search"),y),g}function Cr(g){let y=Yt(g,"","menu");if(y){for(let[z,k]of[["manual",n("Manual order","\u624B\u52A8\u6392\u5E8F")],["usage",n("Most used","\u8C03\u7528\u6B21\u6570")],["recent",n("Recently used","\u6700\u8FD1\u8C03\u7528")]]){let E=fe(k,()=>{st=z,Ne(!0),$t(ce.querySelector(".pm-list"))},"");E.setAttribute("role","menuitemradio"),E.setAttribute("aria-checked",String(z===st)),z===st&&E.append(Se("check")),y.append(E)}y.querySelector("[aria-checked=true]")?.focus()}}document.addEventListener("pointerdown",g=>{be&&!be.contains(g.target)&&!St?.contains(g.target)&&Ne()},{signal:e}),document.addEventListener("keydown",g=>{if(be){if(g.key==="Escape")g.preventDefault(),g.stopImmediatePropagation(),Ne(!0);else if(be.getAttribute("role")==="menu"&&["ArrowDown","ArrowUp","Home","End"].includes(g.key)){g.preventDefault();let y=[...be.querySelectorAll("button")],z=y.indexOf(document.activeElement),k=g.key==="Home"?0:g.key==="End"?y.length-1:(z+(g.key==="ArrowDown"?1:-1)+y.length)%y.length;y[k]?.focus()}}},{signal:e,capture:!0}),document.addEventListener("focusin",g=>{be&&!be.contains(g.target)&&!St?.contains(g.target)&&Ne()},{signal:e}),window.addEventListener("resize",()=>Ne(),{signal:e});function lr(){if(!ce)return;dr(!1),Ne(),xe=null,ce.replaceChildren();let g=$("div","pm-wrap"),y=$("div","pm-heading"),z=$("div","pm-header-actions"),k=_r(),E=Ht(n("Sort prompts","\u63D0\u793A\u8BCD\u6392\u5E8F"),"arrow-down-wide-narrow",()=>Cr(E));E.setAttribute("aria-haspopup","menu"),z.append(E,Ht(n("Edit categories","\u7F16\u8F91\u5206\u7C7B"),"settings",Jt),Pn(),k,Ve(n("New prompt","\u65B0\u5EFA\u63D0\u793A\u8BCD"),()=>er(),!0)),y.append($("h1","",n("Prompt","\u63D0\u793A\u8BCD")),z);let U=$("div","pm-tabs");U.setAttribute("role","tablist"),U.setAttribute("aria-label",n("Categories","\u5206\u7C7B"));let L=[{id:"all",name:"All"},...T,{id:"uncategorized",name:n("Other","\u5176\u4ED6")}];L.some(q=>q.id===_e)||(_e="all"),L.forEach(q=>{let G=fe(q.name,()=>{_e=q.id,lr()},"pm-tab");q.id!=="all"&&G.prepend(at({categoryId:q.id==="uncategorized"?null:q.id})),G.setAttribute("role","tab"),G.setAttribute("aria-selected",String(_e===q.id)),G.tabIndex=_e===q.id?0:-1,G.addEventListener("keydown",F=>{if(!["ArrowLeft","ArrowRight","Home","End"].includes(F.key))return;F.preventDefault();let ee=L.indexOf(q),Y=F.key==="Home"?0:F.key==="End"?L.length-1:(ee+(F.key==="ArrowRight"?1:-1)+L.length)%L.length;_e=L[Y].id,lr(),ce.querySelector("[aria-selected=true]")?.focus()}),U.append(G)});let Z=$("div","pm-tab-row");Z.append(U);let O=$("div","pm-list");g.append(y,Z,O),ce.append(g),$t(O)}function $t(g){Fe(),cr?.disconnect(),g.replaceChildren(),g.dataset.view=Zt;let y=Er.trim().toLocaleLowerCase(),z=[...T,{id:null,name:n("Other","\u5176\u4ED6")}],k=A.filter(U=>(_e==="all"||U.categoryId===(_e==="uncategorized"?null:_e))&&(!y||`${U.title}
100
+ container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:p.string().optional().describe("User's language and region preference in BCP 47 format."),timeZone:p.string().optional().describe("User's timezone in IANA format."),userAgent:p.string().optional().describe("Host application identifier."),platform:p.union([p.literal("web"),p.literal("desktop"),p.literal("mobile")]).optional().describe("Platform type for responsive design decisions."),deviceCapabilities:p.object({touch:p.boolean().optional().describe("Whether the device supports touch input."),hover:p.boolean().optional().describe("Whether the device supports hover interactions.")}).optional().describe("Device input capabilities."),safeAreaInsets:p.object({top:p.number().describe("Top safe area inset in pixels."),right:p.number().describe("Right safe area inset in pixels."),bottom:p.number().describe("Bottom safe area inset in pixels."),left:p.number().describe("Left safe area inset in pixels.")}).optional().describe("Mobile safe area boundaries in pixels.")}).passthrough(),z_=p.object({method:p.literal("ui/notifications/host-context-changed"),params:ux.describe("Partial context update containing only changed fields.")}),I$=p.object({method:p.literal("ui/update-model-context"),params:p.object({content:p.array(Sr).optional().describe("Context content blocks (text, image, etc.)."),structuredContent:p.record(p.string(),p.unknown().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.")})}),k$=p.object({method:p.literal("ui/initialize"),params:p.object({appInfo:yr.describe("App identification (name and version)."),appCapabilities:x_.describe("Features and capabilities this app provides."),protocolVersion:p.string().describe("Protocol version this app supports.")})}),E_=p.object({protocolVersion:p.string().describe('Negotiated protocol version string (e.g., "2025-11-21").'),hostInfo:yr.describe("Host application identification and version."),hostCapabilities:S_.describe("Features and capabilities provided by the host."),hostContext:ux.describe("Rich context about the host environment.")}).passthrough(),R_={target:"draft-2020-12"};async function cx(e,t){let i=e["~standard"];if(i.jsonSchema)return i.jsonSchema[t](R_);throw Error(`Schema (vendor: ${i.vendor}) does not implement Standard JSON Schema (~standard.jsonSchema). Use a library that does (zod v4, ArkType, Valibot) or wrap your schema accordingly.`)}async function lx(e,t,i=""){let o=await e["~standard"].validate(t);if(o.issues){let r=o.issues.map(n=>{let a=n.path?.map(s=>typeof s=="object"?s.key:s).join(".");return a?`${a}: ${n.message}`:n.message}).join("; ");throw Error(i+r)}return o.value}function __(e,t){let i={...e,...t};return t.experimental!==void 0&&(i.experimental={...e.experimental,...t.experimental}),t.tools!==void 0&&(i.tools={...e.tools,...t.tools}),i}var vd=class e extends iv{_appInfo;_appCapabilities;options;_hostCapabilities;_hostInfo;_hostContext;_registeredTools={};_initializedSent=!1;_registeredEvents=new Set;_events=new ov;_methods=new av;setRequestHandler=(...t)=>{let[i,...o]=ax("request",t)??t;this._methods.claim(i,"setRequestHandler"),super.setRequestHandler.call(this,i,...o)};setNotificationHandler=(...t)=>{let[i,...o]=ax("notification",t)??t;this._methods.claim(i,"setNotificationHandler"),super.setNotificationHandler.call(this,i,...o)};removeRequestHandler=t=>{this._methods.release(t),super.removeRequestHandler(t)};removeNotificationHandler=t=>{this._methods.release(t),super.removeNotificationHandler(t)};replaceRequestHandler=(t,...i)=>{this._methods.replace(t),super.setRequestHandler.call(this,t,...i)};_assertInitialized(t){if(this._initializedSent)return;let i=`[ext-apps] App.${t}() called before connect() completed the ui/initialize handshake. Await app.connect() before calling this method, or move data loading to an ontoolresult handler.`;if(this.options?.strict)throw Error(i);console.warn(`${i}. This will throw in a future release.`)}eventSchemas={toolinput:f_,toolinputpartial:h_,toolresult:k_,toolcancelled:g_,hostcontextchanged:z_};static ONE_SHOT_EVENTS=new Set(["toolinput","toolinputpartial","toolresult","toolcancelled"]);_everHadListener=new Set;_assertHandlerTiming(t){if(!e.ONE_SHOT_EVENTS.has(t)||this._everHadListener.has(t)||(this._everHadListener.add(t),!this._initializedSent))return;let i=`[ext-apps] "${String(t)}" handler registered after connect() completed the ui/initialize handshake. The host may have already sent this notification. Register handlers before calling app.connect().`;if(this.options?.strict)throw Error(i);console.warn(i)}setEventHandler(t,i){i&&this._assertHandlerTiming(t),this._ensureEventSlot(t),this._events.setHandler(t,i)}addEventListener(t,i){this._assertHandlerTiming(t),this._ensureEventSlot(t),this._events.addEventListener(t,i)}removeEventListener(t,i){this._events.removeEventListener(t,i)}_ensureEventSlot(t){if(this._registeredEvents.has(t))return;let i=this.eventSchemas[t];if(!i)throw Error(`Unknown event: ${String(t)}`);this.setNotificationHandler(i.shape.method.value,{params:i.shape.params},o=>{let r=o;t==="hostcontextchanged"&&(this._hostContext={...this._hostContext,...r}),this._events.dispatch(t,r)}),this._registeredEvents.add(t)}getEventHandler(t){return this._events.getHandler(t)}warnIfRequestHandlerReplaced(t,i,o){i&&o&&console.warn(`[MCP Apps] ${t} handler replaced. Previous handler will no longer be called.`)}constructor(t,i={},o={autoResize:!0}){super(o),this._appInfo=t,this._appCapabilities=i,this.options=o,this._methods.replace("notifications/cancelled"),this._methods.replace("notifications/progress"),!o.allowUnsafeEval&&p.config({jitless:!0}),this.replaceRequestHandler("ping",r=>(console.log("Received ping:",r.params),{})),this.setEventHandler("hostcontextchanged",void 0)}buildContext(t){return t}registerAppCapabilities(t){if(this.transport)throw Error("Cannot register capabilities after transport is established");this._appCapabilities=__(this._appCapabilities,t)}registerTool(t,i,o){if(this._registeredTools[t])throw Error(`Tool ${t} is already registered`);let r=this,n=()=>{r._initializedSent&&r._appCapabilities.tools?.listChanged&&r.sendToolListChanged()},a=i.inputSchema!==void 0,s={title:i.title,description:i.description,inputSchema:i.inputSchema,outputSchema:i.outputSchema,annotations:i.annotations,_meta:i._meta,enabled:!0,enable(){this.enabled=!0,n()},disable(){this.enabled=!1,n()},update(c){Object.assign(this,c),n()},remove(){r._registeredTools[t]===s&&(delete r._registeredTools[t],n())},handler:async(c,l)=>{if(!s.enabled)throw Error(`Tool ${t} is disabled`);let d;if(a){let f=s.inputSchema,h=f?await lx(f,c??{},`Invalid input for tool ${t}: `):c??{};d=await o(h,l)}else d=await o(l);return s.outputSchema&&!d.isError&&(d.structuredContent=await lx(s.outputSchema,d.structuredContent,`Invalid output for tool ${t}: `)),d}};return this._registeredTools[t]=s,!this._appCapabilities.tools&&!this.transport&&this.registerAppCapabilities({tools:{listChanged:!0}}),this.ensureToolHandlersInitialized(),n(),s}_toolHandlersInitialized=!1;ensureToolHandlersInitialized(){this._toolHandlersInitialized||(this._toolHandlersInitialized=!0,this.oncalltool=async(t,i)=>{let o=this._registeredTools[t.name];if(!o)throw Error(`Tool ${t.name} not found`);return o.handler(t.arguments,i)},this.onlisttools=async(t,i)=>({tools:await Promise.all(Object.entries(this._registeredTools).filter(([o,r])=>r.enabled).map(async([o,r])=>{let n={name:o,title:r.title,description:r.description,inputSchema:r.inputSchema?await cx(r.inputSchema,"input"):{type:"object",properties:{}}};return r.outputSchema&&(n.outputSchema=await cx(r.outputSchema,"output")),r.annotations&&(n.annotations=r.annotations),r._meta&&(n._meta=r._meta),n}))}))}async sendToolListChanged(t={}){this._assertInitialized("sendToolListChanged"),await this.notification({method:"notifications/tools/list_changed",params:t})}getHostCapabilities(){return this._hostCapabilities}getHostVersion(){return this._hostInfo}getHostContext(){return this._hostContext}get ontoolinput(){return this.getEventHandler("toolinput")}set ontoolinput(t){this.setEventHandler("toolinput",t)}get ontoolinputpartial(){return this.getEventHandler("toolinputpartial")}set ontoolinputpartial(t){this.setEventHandler("toolinputpartial",t)}get ontoolresult(){return this.getEventHandler("toolresult")}set ontoolresult(t){this.setEventHandler("toolresult",t)}get ontoolcancelled(){return this.getEventHandler("toolcancelled")}set ontoolcancelled(t){this.setEventHandler("toolcancelled",t)}get onhostcontextchanged(){return this.getEventHandler("hostcontextchanged")}set onhostcontextchanged(t){this.setEventHandler("hostcontextchanged",t)}_onteardown;get onteardown(){return this._onteardown}set onteardown(t){this.warnIfRequestHandlerReplaced("onteardown",this._onteardown,t),this._onteardown=t,this.replaceRequestHandler("ui/resource-teardown",{params:y_.shape.params,result:b_},(i,o)=>{if(!this._onteardown)throw Error("No onteardown handler set");return this._onteardown(i,o)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(t){this.warnIfRequestHandlerReplaced("oncalltool",this._oncalltool,t),this._oncalltool=t,this.replaceRequestHandler("tools/call",(i,o)=>{if(!this._oncalltool)throw Error("No oncalltool handler set");return this._oncalltool(i.params,o)})}_onlisttools;get onlisttools(){return this._onlisttools}set onlisttools(t){this.warnIfRequestHandlerReplaced("onlisttools",this._onlisttools,t),this._onlisttools=t,this.replaceRequestHandler("tools/list",(i,o)=>{if(!this._onlisttools)throw Error("No onlisttools handler set");return this._onlisttools(i.params,o)})}assertCapabilityForMethod(t){switch(t){case"sampling/createMessage":if(!this._hostCapabilities?.sampling)throw Error(`Host does not support sampling (required for ${t})`);break}}assertRequestHandlerCapability(t){switch(t){case"tools/call":case"tools/list":if(!this._appCapabilities.tools)throw Error(`Client does not support tool capability (required for ${t})`);return;default:return}}assertNotificationCapability(t){}async callServerTool(t,i){if(this._assertInitialized("callServerTool"),typeof t=="string")throw Error(`callServerTool() expects an object as its first argument, but received a string ("${t}"). Did you mean: callServerTool({ name: "${t}", arguments: { ... } })?`);return await this.request({method:"tools/call",params:t},{onprogress:()=>{},resetTimeoutOnProgress:!0,...i})}async readServerResource(t,i){return this._assertInitialized("readServerResource"),await this.request({method:"resources/read",params:t},i)}async listServerResources(t,i){return this._assertInitialized("listServerResources"),await this.request({method:"resources/list",params:t},i)}async createSamplingMessage(t,i){return this._assertInitialized("createSamplingMessage"),await this.request({method:"sampling/createMessage",params:t},i)}sendMessage(t,i){return this._assertInitialized("sendMessage"),this.request({method:"ui/message",params:t},p_,i)}sendLog(t){return this.notification({method:"notifications/message",params:t})}updateModelContext(t,i){return this._assertInitialized("updateModelContext"),this.request({method:"ui/update-model-context",params:t},In,i)}openLink(t,i){return this._assertInitialized("openLink"),this.request({method:"ui/open-link",params:t},d_,i)}sendOpenLink=this.openLink;downloadFile(t,i){return this._assertInitialized("downloadFile"),this.request({method:"ui/download-file",params:t},m_,i)}requestTeardown(t={}){return this.notification({method:"ui/notifications/request-teardown",params:t})}requestDisplayMode(t,i){return this._assertInitialized("requestDisplayMode"),this.request({method:"ui/request-display-mode",params:t},w_,i)}sendSizeChanged(t){return this.notification({method:"ui/notifications/size-changed",params:t})}setupSizeChangedNotifications(){let t=!1,i=0,o=0,r=()=>{t||(t=!0,requestAnimationFrame(()=>{t=!1;let a=document.documentElement,s=a.style.height;a.style.height="max-content";let c=Math.ceil(a.getBoundingClientRect().height);a.style.height=s;let l=Math.ceil(window.innerWidth);(l!==i||c!==o)&&(i=l,o=c,this.sendSizeChanged({width:l,height:c}))}))};r();let n=new ResizeObserver(r);return n.observe(document.documentElement),n.observe(document.body),()=>n.disconnect()}async connect(t=new sv(window.parent,window.parent),i){if(this.transport)throw Error("App is already connected. Call close() before connecting again.");this._initializedSent=!1;try{await super.connect(t);let o=await this.request({method:"ui/initialize",params:{appCapabilities:this._appCapabilities,appInfo:this._appInfo,protocolVersion:a_}},E_,i);if(o===void 0)throw Error(`Server sent invalid initialize result: ${o}`);this._hostCapabilities=o.hostCapabilities,this._hostInfo=o.hostInfo,this._hostContext=o.hostContext,await this.notification({method:"ui/notifications/initialized"}),this._initializedSent=!0,this.options?.autoResize&&this.setupSizeChangedNotifications()}catch(o){throw this.close(),o}}};function dx(e,t){let i=t.resources.icons,o="data-minecodex-quick-prompts",r=()=>(document.documentElement.lang||navigator.language||"en").toLowerCase().startsWith("zh"),n=(g,y)=>r()?y:g,a=document.createElement("style");a.textContent=t.resources.styles,document.head.append(a);let s=null,c=null,l=null,d=null,f=null,h=null,m=null,A=[],x=0,C=!1,M=!1,T=[],Q={},re=[],me={"bar-chart":"\u67F1\u72B6\u56FE",book:"\u4E66\u7C4D",brain:"\u5927\u8111","currency-dollar":"\u7F8E\u5143",customize:"\u81EA\u5B9A\u4E49",dumbbell:"\u54D1\u94C3",edit:"\u7F16\u8F91",flask:"\u70E7\u74F6",folder:"\u6587\u4EF6\u5939",function:"\u51FD\u6570",globe:"\u5730\u7403","graduation-cap":"\u5B66\u58EB\u5E3D",heart:"\u7231\u5FC3",kettlebell:"\u58F6\u94C3",logs:"\u7B14\u8BB0",lotus:"\u83B2\u82B1",music:"\u97F3\u4E50",palette:"\u8C03\u8272\u76D8",paw:"\u722A\u5370",plant:"\u690D\u7269",popcorn:"\u7206\u7C73\u82B1",scale:"\u5929\u5E73",stethoscope:"\u542C\u8BCA\u5668",terminal:"\u7EC8\u7AEF",wrench:"\u6273\u624B",writing:"\u5199\u4F5C",blue:"\u84DD\u8272",green:"\u7EFF\u8272",orange:"\u6A59\u8272",pink:"\u7C89\u8272",purple:"\u7D2B\u8272",red:"\u7EA2\u8272",yellow:"\u9EC4\u8272",black:"\u4E2D\u6027\u8272"};function H(g){return n(g.replaceAll("-"," "),me[g]??g)}function pe(g){let y={"No available input in the focused window":"\u5F53\u524D\u7A97\u53E3\u6CA1\u6709\u53EF\u7528\u8F93\u5165\u6846\uFF0C\u8BF7\u5148\u6253\u5F00\u804A\u5929\u5E76\u786E\u8BA4 MCX \u589E\u5F3A\u670D\u52A1\u5DF2\u5F00\u542F\u3002","Input changed before insertion":"\u8F93\u5165\u6846\u5DF2\u5207\u6362\uFF0C\u8BF7\u91CD\u65B0\u9009\u62E9\u63D0\u793A\u8BCD\u3002","Enable Prompts in MineCodex first":"\u8BF7\u5148\u5728 MineCodex \u4E2D\u5F00\u542F\u63D0\u793A\u8BCD\u3002","Open a chat before using a prompt.":"\u8BF7\u5148\u6253\u5F00\u4E00\u4E2A\u5BF9\u8BDD\uFF0C\u518D\u4F7F\u7528\u63D0\u793A\u8BCD\u3002","Category was not found":"\u672A\u627E\u5230\u8BE5\u5206\u7C7B","Prompt was not found":"\u672A\u627E\u5230\u8BE5\u63D0\u793A\u8BCD","Choose one emoji or leave it empty":"\u8BF7\u9009\u62E9\u4E00\u4E2A Emoji\uFF0C\u6216\u7559\u7A7A\u4EE5\u7EE7\u627F\u5206\u7C7B\u56FE\u6807","Invalid sort order":"\u6392\u5E8F\u65E0\u6548\uFF0C\u8BF7\u91CD\u8BD5","Invalid order":"\u6392\u5E8F\u65E0\u6548\uFF0C\u8BF7\u91CD\u8BD5","Invalid category":"\u5206\u7C7B\u65E0\u6548\uFF0C\u8BF7\u91CD\u8BD5","Items changed; refresh and try again":"\u6761\u76EE\u5DF2\u53D1\u751F\u53D8\u5316\uFF0C\u8BF7\u5237\u65B0\u540E\u91CD\u8BD5"};return n(g.message||"Something went wrong. Please try again.",y[g.message]??"\u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u91CD\u8BD5\u3002")}function $(g,y,z){let k=document.createElement(g);return y&&(k.className=y),z!=null&&(k.textContent=z),k}function Se(g){return new DOMParser().parseFromString(i[g],"image/svg+xml").documentElement.cloneNode(!0)}function fe(g,y,z="qp-command",k=null){let E=$("button",z,k?null:g);return E.type="button",E.setAttribute("aria-label",g),k&&(E.append(Se(k)),E.setAttribute("data-minecodex-tooltip",g)),E.addEventListener("click",y),E}async function $e(g,{method:y="GET",body:z}={}){return t.requestHostAction("quick-prompts",{route:g,method:y,body:z})}function sr(g){if(!m)return;m.querySelector(".qp-error")?.remove();let y=$("div","qp-error",pe(g));y.setAttribute("role","alert"),m.append(y)}function Ct(){!m||!l?.isConnected||t.ui.composerMenu(m,c)}function Xe(g=!1){Oe(!0),Lt?.disconnect(),x++,m?.remove(),m=null,s?.setAttribute("aria-expanded","false"),s?.setAttribute("data-state","closed"),g&&s?.focus({preventScroll:!0})}let ot="all",Lt=null,De=null,yt=null,wr=null;function Oe(g=!1,y=0){clearTimeout(yt),clearTimeout(wr);let z=De;if(z){if(z.anchor.removeAttribute("data-preview"),g||Nt()){z.node.remove(),De=null;return}z.node.style.pointerEvents="none",Qt(z.node,{opacity:0,transform:`translateY(${Math.max(-10,Math.min(10,y))}px) scale(.98)`},150),wr=setTimeout(()=>{z.node.remove(),De===z&&(De=null)},150)}}function Dt(g,y){Oe(!0);let z=ct(g);z&&(yt=setTimeout(()=>{if(!m||!y.isConnected)return;let k=$("div","qp-image-preview");t.ui.surface(k,"popover"),t.ui.mount(k,"floating");let E=$("img");E.alt=n(`Full image: ${g.summary}`,`\u5B8C\u6574\u56FE\u7247\uFF1A${g.summary}`);let U=()=>{if(De?.node!==k||!E.naturalWidth)return;let L=y.getBoundingClientRect(),Z=m.getBoundingClientRect(),O=innerWidth-Z.right-24,q=Z.left-24,G=Math.max(O,q);if(G<96){Oe(!0);return}let F=Math.min(280/E.naturalWidth,G/E.naturalWidth,360/E.naturalHeight,(innerHeight-24)/E.naturalHeight),ee=E.naturalWidth*F,Y=E.naturalHeight*F;k.style.width=`${ee}px`,k.style.height=`${Y}px`,k.style.left=`${O>=ee?Z.right+12:Z.left-ee-12}px`,k.style.top=`${Math.max(12,Math.min(L.top+(L.height-Y)/2,innerHeight-Y-12))}px`,k.style.visibility="visible",Nt()||k.animate([{opacity:0,transform:"translateX(-4px) scale(.98)"},{opacity:1,transform:"none"}],{duration:180,easing:"cubic-bezier(.22,1,.36,1)"})};k.append(E),De={node:k,anchor:y},y.dataset.preview="true",k.addEventListener("pointerenter",()=>clearTimeout(yt)),k.addEventListener("pointerleave",()=>Oe()),E.onload=U,E.src=z.data,E.complete&&U()},160))}function Hr(){let g=$("div","qp-tabs-bar"),y=$("div","qp-tabs");y.setAttribute("role","tablist"),y.setAttribute("aria-label",n("Prompt categories","\u63D0\u793A\u8BCD\u5206\u7C7B"));let z=[{id:"all",name:n("All","\u5168\u90E8")},...T.filter(O=>Ze(O.id).length),...Ze(null).length?[{id:"other",name:n("Other","\u5176\u4ED6")}]:[]];z.some(O=>O.id===ot)||(ot="all");for(let O of z){let q=fe(O.name,()=>{ot=O.id,bt(),m.querySelector('[aria-selected="true"]')?.focus({preventScroll:!0})},"qp-tab");q.setAttribute("role","tab"),q.setAttribute("aria-selected",String(O.id===ot)),q.setAttribute("aria-controls","mcx-quick-results"),y.append(q)}let k=$("div","qp-tab-arrows"),E=O=>y.scrollBy({left:O*Math.max(100,y.clientWidth-90),behavior:Nt()?"instant":"smooth"}),U=fe(n("Previous categories","\u524D\u9762\u7684\u5206\u7C7B"),()=>E(-1),"qp-tab-arrow qp-tab-previous","chevron"),L=fe(n("More categories","\u540E\u9762\u7684\u5206\u7C7B"),()=>E(1),"qp-tab-arrow qp-tab-next","chevron");k.append(U,L),g.append(y,k);let Z=()=>{let q=[...y.children].reduce((G,F)=>G+F.offsetWidth+2,-2)>y.clientWidth+1;U.hidden=!q||y.scrollLeft<=1,L.hidden=!q||y.scrollLeft+y.clientWidth>=y.scrollWidth-1,k.hidden=!q,g.dataset.overflow=String(q),y.style.setProperty("--qp-arrow-space",`${q?68:0}px`)};return y.addEventListener("scroll",Z,{passive:!0}),y.addEventListener("keydown",O=>{if(!["ArrowLeft","ArrowRight"].includes(O.key))return;O.preventDefault();let q=[...y.children],G=q.indexOf(document.activeElement);q[Math.max(0,Math.min(q.length-1,G+(O.key==="ArrowRight"?1:-1)))]?.focus()}),Lt=new ResizeObserver(Z),Lt.observe(y),requestAnimationFrame(()=>{if(!g.isConnected)return;Z();let O=y.querySelector('[aria-selected="true"]');O&&(y.scrollLeft=Math.max(0,O.offsetLeft-y.offsetLeft-y.clientWidth+O.offsetWidth+68)),Z()}),g}async function Ir(){let g=++x;m.replaceChildren(),m.append($("div","qp-empty",n("Loading\u2026","\u52A0\u8F7D\u4E2D\u2026")));try{let y=await $e("/api/state");if(!m||g!==x)return;A=y.prompts,T=y.categories,Q=y.icons,re=y.emojis??[],bt()}catch(y){m&&g===x&&(m.querySelector(".qp-empty")?.remove(),sr(y),m.append(fe(n("Retry","\u91CD\u8BD5"),Ir)))}}let Pt={black:["var(--mcx-color-text-secondary)","var(--mcx-color-text-secondary)"],blue:["#0285ff","#339cff"],green:["#04b84c","#40c977"],orange:["#fb6a22","#ff8549"],pink:["#ff66ad","#ff8cc1"],purple:["#924ff7","#ad7bf9"],red:["#fa423e","#ff6764"],yellow:["#ffc300","#ffd240"]};function at(g){let y=$("span","qp-symbol");if(g.emoji)return y.textContent=g.emoji,y;let z=T.find(U=>U.id===g.categoryId),k=new DOMParser().parseFromString(Q[z?.icon??"book"]??i.prompt,"image/svg+xml").documentElement;y.append(k.cloneNode(!0));let E=Pt[z?.color??"black"]??Pt.black;return y.style.setProperty("--prompt-icon-light",E[0]),y.style.setProperty("--prompt-icon-dark",E[1]),y}function Ze(g){return A.filter(y=>y.categoryId===g).sort((y,z)=>y.sortOrder-z.sortOrder||y.createdAt-z.createdAt||y.id.localeCompare(z.id))}function bt(){Oe(!0),Lt?.disconnect(),m.replaceChildren();let g=$("div","qp-scroll");A.length||g.append($("div","qp-empty",n("No prompts yet","\u8FD8\u6CA1\u6709\u63D0\u793A\u8BCD")));let y=A.filter(E=>E.useCount>0).sort((E,U)=>U.calledAt-E.calledAt||E.id.localeCompare(U.id)).slice(0,3);m.append(Hr()),g.id="mcx-quick-results";let z=0;g.addEventListener("scroll",()=>{let E=z-g.scrollTop;z=g.scrollTop,Oe(!1,E)},{passive:!0});let k=[{id:"recent",name:n("Recently used","\u6700\u8FD1\u4F7F\u7528"),prompts:y},...T.map(E=>({id:E.id,name:E.name,prompts:Ze(E.id)})),{id:"other",name:n("Other","\u5176\u4ED6"),prompts:Ze(null)}];for(let E of k.filter(U=>U.prompts.length&&(ot==="all"||U.id===ot))){g.append($("div","qp-header",E.name));for(let U of E.prompts){let L=$("div","qp-row"),Z=fe(U.summary,async()=>{let O=x;try{if(!f?.isConnected||!t.codex.composer(f,{purpose:"insertion"}))throw new Error("Input changed before insertion");window.__codexPersonalRuntime.insertText(U.body,f),Xe(),await $e(`/api/prompts/${encodeURIComponent(U.id)}/use`,{method:"POST",body:{action:"insert",success:!0}})}catch(q){x===O?sr(q):console.warn("[Prompts] Usage could not be saved",q)}},"qp-select");Z.replaceChildren(at(U),$("span","qp-title",U.summary)),U.title&&Z.append($("span","qp-preview",U.body.replace(/\s+/g," "))),Z.addEventListener("pointerenter",()=>Dt(U,Z)),Z.addEventListener("focus",()=>Dt(U,Z)),Z.addEventListener("pointerleave",()=>{clearTimeout(yt),yt=setTimeout(()=>Oe(),100)}),Z.addEventListener("blur",()=>Oe()),L.append(Z),g.append(L)}}g.children.length||g.append($("div","qp-empty",n("No prompts yet","\u8FD8\u6CA1\u6709\u63D0\u793A\u8BCD"))),m.append(g),Ct()}function kr(){if(m){Xe(!0);return}c.getAttribute("aria-expanded")==="true"&&c.click(),m=$("div"),m.setAttribute(o,"panel"),t.ui.surface(m,"composer-menu"),m.setAttribute("role","dialog"),m.setAttribute("aria-label",n("Quick Prompts","\u5FEB\u6377\u63D0\u793A\u8BCD")),document.body.append(m),s.setAttribute("aria-expanded","true"),s.setAttribute("data-state","open"),Ct(),Ir()}function Rn(g){return g.getAttribute("aria-expanded")==="true"&&g.checkVisibility({visibilityProperty:!0})&&(g.getAttribute("data-composer-navigation-target")==="add-context"||g.getAttribute("aria-haspopup")==="menu")}function _n(){let g=document.activeElement?.tagName==="IFRAME"?h:null;return t.codex.composer(g,{purpose:"insertion"})}function zr(){if(M||e.aborted||t.management)return;let g=m?t.codex.composer(f,{purpose:"insertion"}):_n(),y=g?.add,z=g?.root,k=g?.threadId??null;if(k!==d&&(Xe(),d=k),(y!==c||z!==l||g?.editable!==f)&&(Xe(),s?.remove(),s=null,c=y,l=z),f=g?.editable??null,Nn?.remember(g),!!y){if(m&&[...z.querySelectorAll("button")].some(Rn)&&Xe(),!s){s=y.cloneNode(!1),s.removeAttribute("disabled"),s.removeAttribute("aria-disabled"),s.removeAttribute("title"),s.removeAttribute("aria-describedby"),s.removeAttribute("id"),s.removeAttribute("data-composer-navigation-target"),s.setAttribute(o,"button"),s.setAttribute("aria-label",n("Quick Prompts","\u5FEB\u6377\u63D0\u793A\u8BCD")),s.setAttribute("data-minecodex-tooltip",n("Quick Prompts","\u5FEB\u6377\u63D0\u793A\u8BCD")),s.setAttribute("aria-haspopup","dialog"),s.setAttribute("aria-expanded","false"),s.setAttribute("data-state","closed");for(let E of y.children){let U=E.cloneNode(!0);for(let L of U.querySelectorAll("svg")){let Z=Se("prompt");for(let O of["class","width","height","aria-hidden","focusable"])L.hasAttribute(O)&&Z.setAttribute(O,L.getAttribute(O));L.replaceWith(Z)}s.append(U)}s.addEventListener("click",kr),y.after(s)}s.className!==y.className&&(s.className=y.className),Ct()}}let ce=null,Kt=0,_e="all",st="manual",Zt="cards";try{Zt=localStorage.getItem("minecodex.prompts.view")==="list"?"list":"cards"}catch{}let cr=null,Er="",xe=null,Rr=null;function Ve(g,y,z=!1,k="secondary"){return t.ui.action(fe(g,y,`pm-command${z?" pm-primary":""}`),z?"primary":k)}function Tt(g){if(!ce)return;ce.querySelector(".pm-error")?.remove();let y=$("div","pm-error",pe(g));y.setAttribute("role","alert"),(xe??ce.querySelector(".pm-wrap")??ce).append(y)}function Yr(){ce&&Object.assign(ce.style,{inset:"0",borderRadius:"0"})}function Xr(g=!1,y=!0){Xt?.cancel(),Fe(),cr?.disconnect(),Kt++,Ne(),dr(!1),ce&&t.ui.releasePage(ce,{restoreNavigation:y}),ce?.remove(),ce=null,xe=null,document.documentElement.removeAttribute("data-mcx-prompts-open"),g&&Rr?.isConnected&&Rr.focus({preventScroll:!0})}async function jt(){let g=++Kt;try{let y=await $e("/api/state");if(!ce||g!==Kt)return;A=y.prompts,T=y.categories,Q=y.icons,re=y.emojis??[],lr()}catch(y){g===Kt&&Tt(y)}}function Cn(){if(Xe(),!ce)return Rr=document.activeElement,ce=$("section"),ce.setAttribute(o,"page"),t.ui.page(ce,{sidebar:"none",onNavigate:()=>Xr(!1,!1)}),ce.setAttribute("aria-label",n("Prompt","\u63D0\u793A\u8BCD")),document.body.append(ce),document.documentElement.setAttribute("data-mcx-prompts-open",""),Yr(),ce.append($("div","pm-empty",n("Loading\u2026","\u52A0\u8F7D\u4E2D\u2026"))),jt()}let be=null,St=null;function Ht(g,y,z){let k=fe(g,z,"pm-icon",y);return k.setAttribute("data-minecodex-tooltip",g),k}function Ne(g=!1){be?.remove(),be=null,St?.setAttribute("aria-expanded","false"),g&&St?.isConnected&&St.focus({preventScroll:!0}),St=null}function Yt(g,y,z,k=!1){if(St===g)return Ne(!0),null;Ne(),St=g,g.setAttribute("aria-expanded","true"),be=$("div",`pm-popup ${y}`),t.ui.surface(be,"dropdown"),be.setAttribute("role",z),be.setAttribute("aria-label",g.getAttribute("aria-label")),(et??ce).append(be);let E=g.getBoundingClientRect();k&&(be.style.boxSizing="border-box",be.style.width=`${E.width}px`);let U=be.getBoundingClientRect().width;return be.style.top=`${E.bottom+6}px`,be.style.left=`${Math.max(8,Math.min(E.right-U,innerWidth-U-8))}px`,be}function _r(){let g=$("div","pm-search-inline"),y=$("input");y.type="text",y.autocomplete="off",y.placeholder=n("Search prompts","\u641C\u7D22\u63D0\u793A\u8BCD"),y.setAttribute("aria-label",y.placeholder),y.value=Er;let z=()=>{Er=y.value,$t(ce.querySelector(".pm-list"))};return y.addEventListener("input",z),y.addEventListener("keydown",k=>{k.key==="Escape"&&(k.stopPropagation(),k.preventDefault(),y.value="",z())}),g.append(Se("search"),y),g}function Cr(g){let y=Yt(g,"","menu");if(y){for(let[z,k]of[["manual",n("Manual order","\u624B\u52A8\u6392\u5E8F")],["usage",n("Most used","\u8C03\u7528\u6B21\u6570")],["recent",n("Recently used","\u6700\u8FD1\u8C03\u7528")]]){let E=fe(k,()=>{st=z,Ne(!0),$t(ce.querySelector(".pm-list"))},"");E.setAttribute("role","menuitemradio"),E.setAttribute("aria-checked",String(z===st)),z===st&&E.append(Se("check")),y.append(E)}y.querySelector("[aria-checked=true]")?.focus()}}document.addEventListener("pointerdown",g=>{be&&!be.contains(g.target)&&!St?.contains(g.target)&&Ne()},{signal:e}),document.addEventListener("keydown",g=>{if(be){if(g.key==="Escape")g.preventDefault(),g.stopImmediatePropagation(),Ne(!0);else if(be.getAttribute("role")==="menu"&&["ArrowDown","ArrowUp","Home","End"].includes(g.key)){g.preventDefault();let y=[...be.querySelectorAll("button")],z=y.indexOf(document.activeElement),k=g.key==="Home"?0:g.key==="End"?y.length-1:(z+(g.key==="ArrowDown"?1:-1)+y.length)%y.length;y[k]?.focus()}}},{signal:e,capture:!0}),document.addEventListener("focusin",g=>{be&&!be.contains(g.target)&&!St?.contains(g.target)&&Ne()},{signal:e}),window.addEventListener("resize",()=>Ne(),{signal:e});function lr(){if(!ce)return;dr(!1),Ne(),xe=null,ce.replaceChildren();let g=$("div","pm-wrap"),y=$("div","pm-heading"),z=$("div","pm-header-actions"),k=_r(),E=Ht(n("Sort prompts","\u63D0\u793A\u8BCD\u6392\u5E8F"),"arrow-down-wide-narrow",()=>Cr(E));E.setAttribute("aria-haspopup","menu"),z.append(E,Ht(n("Edit categories","\u7F16\u8F91\u5206\u7C7B"),"settings",Jt),Pn(),k,Ve(n("New prompt","\u65B0\u5EFA\u63D0\u793A\u8BCD"),()=>er(),!0)),y.append($("h1","",n("Prompt","\u63D0\u793A\u8BCD")),z);let U=$("div","pm-tabs");U.setAttribute("role","tablist"),U.setAttribute("aria-label",n("Categories","\u5206\u7C7B"));let L=[{id:"all",name:"All"},...T,{id:"uncategorized",name:n("Other","\u5176\u4ED6")}];L.some(q=>q.id===_e)||(_e="all"),L.forEach(q=>{let G=fe(q.name,()=>{_e=q.id,lr()},"pm-tab");q.id!=="all"&&G.prepend(at({categoryId:q.id==="uncategorized"?null:q.id})),G.setAttribute("role","tab"),G.setAttribute("aria-selected",String(_e===q.id)),G.tabIndex=_e===q.id?0:-1,G.addEventListener("keydown",F=>{if(!["ArrowLeft","ArrowRight","Home","End"].includes(F.key))return;F.preventDefault();let ee=L.indexOf(q),Y=F.key==="Home"?0:F.key==="End"?L.length-1:(ee+(F.key==="ArrowRight"?1:-1)+L.length)%L.length;_e=L[Y].id,lr(),ce.querySelector("[aria-selected=true]")?.focus()}),U.append(G)});let Z=$("div","pm-tab-row");Z.append(U);let O=$("div","pm-list");g.append(y,Z,O),ce.append(g),$t(O)}function $t(g){Fe(),cr?.disconnect(),g.replaceChildren(),g.dataset.view=Zt;let y=Er.trim().toLocaleLowerCase(),z=[...T,{id:null,name:n("Other","\u5176\u4ED6")}],k=A.filter(U=>(_e==="all"||U.categoryId===(_e==="uncategorized"?null:_e))&&(!y||`${U.title}
101
101
  ${U.body}`.toLocaleLowerCase().includes(y)));if(!k.length){g.append(jn(!!y));return}st==="usage"&&k.sort((U,L)=>L.useCount-U.useCount||(L.calledAt??0)-(U.calledAt??0)),st==="recent"&&k.sort((U,L)=>(L.calledAt??0)-(U.calledAt??0));let E=st==="manual"||Zt==="cards"?z.map(U=>({name:U.name,items:st==="manual"?Ze(U.id).filter(L=>k.includes(L)):k.filter(L=>L.categoryId===U.id)})).filter(U=>U.items.length):[{items:k}];for(let U of E){if(U.name&&_e==="all"&&g.append($("h2","",U.name)),Zt==="cards"){g.append(Tn(U));continue}for(let L of U.items){let Z=$("div","pm-row");Z.dataset.promptId=L.id;let O=fe(n(`Use ${L.summary}`,`\u4F7F\u7528 ${L.summary}`),()=>{Pr(L,O)},"pm-list-use"),q=$("div","pm-info");q.replaceChildren($("div","pm-title",L.summary),$("div","pm-preview",L.body.replace(/\s+/g," ")));let G=$("div","pm-stats");G.append($("div","pm-count",st==="recent"?L.calledAt==null?n("Never used","\u5C1A\u672A\u8C03\u7528"):new Intl.DateTimeFormat(r()?"zh-CN":"en",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}).format(new Date(L.calledAt)):n(`${L.useCount} ${L.useCount===1?"call":"calls"}`,`${L.useCount} \u6B21\u8C03\u7528`))),O.replaceChildren(at(L),q,G),Z.append(O,Ht(n("Edit prompt","\u7F16\u8F91\u63D0\u793A\u8BCD"),"square-pen",()=>er(L))),st==="manual"&&!y&&Z.append(en(L,Ze(L.categoryId),!1,Z)),g.append(Z)}}}function Pn(){let g=$("div","pm-view-switch");g.setAttribute("role","group"),g.setAttribute("aria-label",n("View","\u89C6\u56FE"));for(let[y,z]of[["cards",n("Cards","\u5361\u7247")],["list",n("List","\u5217\u8868")]]){let k=fe(z,()=>{Zt=y;try{localStorage.setItem("minecodex.prompts.view",y)}catch{}for(let E of g.children)E.setAttribute("aria-pressed",String(E===k));$t(ce.querySelector(".pm-list"))},"pm-view-option",y==="cards"?"layout-grid":"list");k.setAttribute("aria-pressed",String(Zt===y)),g.append(k)}return g}function ct(g){let y=T.find(E=>E.id===g.categoryId);if(!/^(生图|图像生成|图片生成|image generation|images?)$/i.test(y?.name?.trim()??""))return null;let z=t.resources.previews??[],k=Ze(g.categoryId).findIndex(E=>E.id===g.id);return z[k%z.length]??null}async function Pr(g,y){y.disabled=!0;try{await t.insertPrompt(g.id),e.aborted||await jt()}catch(z){e.aborted||Tt(z)}finally{y.disabled=!1}}let lt=null,xt=null,Vt=null,ut=null,dt=null,Nt=()=>matchMedia("(prefers-reduced-motion: reduce)").matches;function Qt(g,y,z){if(!g)return;let k=getComputedStyle(g),E={opacity:k.opacity,transform:k.transform};g.getAnimations().forEach(U=>U.cancel()),g.animate([E,y],{duration:z,easing:"cubic-bezier(.22,1,.36,1)",fill:"forwards"})}function ur(){clearTimeout(Vt),dt!==null&&(clearTimeout(dt),dt=null,Qt(lt,{opacity:1,transform:"none"},180),Qt(ut?.overlay,{opacity:1,transform:"none"},180))}function Ue(){if(clearTimeout(Vt),!lt||Nt()){Fe();return}dt===null&&(Qt(lt,{opacity:0,transform:"scale(.97)"},160),Qt(ut?.overlay,{opacity:0,transform:"none"},180),dt=setTimeout(Fe,180))}function Fe(){if(clearTimeout(dt),dt=null,clearTimeout(Vt),xt?.removeAttribute("aria-describedby"),lt?.remove(),ut){let{card:g,placeholder:y,layer:z,overlay:k,cssText:E}=ut;g.style.cssText=E,y.replaceWith(g),z.remove(),k.remove(),ut=null}lt=null,xt=null}function Tr(){document.activeElement!==xt&&(clearTimeout(Vt),Vt=setTimeout(Ue,100))}function jr(g,y,z){if(xt===g&&lt){ur();return}Fe(),xt=g,Vt=setTimeout(()=>{if(!g.isConnected||!ce||e.aborted)return;let k=$("div","pm-image-preview");k.id="mcx-prompt-image-preview",k.setAttribute("role","tooltip"),t.ui.surface(k,"popover");let E=$("img");E.alt=n(`Full image: ${z}`,`\u5B8C\u6574\u56FE\u7247\uFF1A${z}`);let U=()=>{if(lt!==k||!E.naturalWidth)return;let ee=g.getBoundingClientRect(),Y=Math.min(520/E.naturalWidth,(innerHeight-40)/E.naturalHeight,(innerWidth-40)/E.naturalWidth,640/E.naturalHeight),ae=E.naturalWidth*Y,we=E.naturalHeight*Y;k.style.width=`${ae}px`,k.style.height=`${we}px`;let wt=ee.right+12,tt=ee.left-ae-12;k.style.left=`${Math.max(14,Math.min(wt+ae<=innerWidth-14?wt:tt>=14?tt:ee.left+(ee.width-ae)/2,innerWidth-ae-14))}px`,k.style.top=`${Math.max(14,Math.min(ee.top+(ee.height-we)/2,innerHeight-we-14))}px`,k.style.transformOrigin=`${Math.max(0,Math.min(ae,ee.left+ee.width/2-parseFloat(k.style.left)))}px ${Math.max(0,Math.min(we,ee.top+ee.height/2-parseFloat(k.style.top)))}px`,k.style.visibility="visible",!k.dataset.entered&&!Nt()&&k.animate([{opacity:0,transform:"scale(.96)"},{opacity:1,transform:"none"}],{duration:240,easing:"cubic-bezier(.22,1,.36,1)",fill:"forwards"}),k.dataset.entered="true"};E.addEventListener("load",U,{once:!0}),E.src=y.data,k.append(E),k.addEventListener("pointerenter",ur),k.addEventListener("pointerleave",Tr),lt=k;let L=g.closest(".pm-card"),Z=L.getBoundingClientRect(),O=$("div");O.style.width=`${Z.width}px`,O.style.height=`${Z.height}px`;let q=$("div","pm-preview-overlay");t.ui.overlay(q),t.ui.layer(q,"floating"),q.addEventListener("pointerdown",Ue);let G=$("div","pm-preview-spotlight");G.setAttribute(o,"page"),t.ui.layer(G,"floating");let F=L.style.cssText;ut={card:L,placeholder:O,layer:G,overlay:q,cssText:F},L.replaceWith(O),Object.assign(L.style,{position:"absolute",left:`${Z.left}px`,top:`${Z.top}px`,width:`${Z.width}px`,height:`${Z.height}px`,pointerEvents:"auto"}),G.append(L),document.body.append(q,G),Nt()||q.animate([{opacity:0},{opacity:1}],{duration:220,easing:"cubic-bezier(.22,1,.36,1)",fill:"forwards"}),g.setAttribute("aria-describedby",k.id),document.body.append(k),U()},200)}window.addEventListener("scroll",Fe,{capture:!0,signal:e}),window.addEventListener("resize",Fe,{signal:e}),window.addEventListener("blur",Fe,{signal:e}),window.addEventListener("keydown",g=>{g.key==="Escape"&&xt&&(g.preventDefault(),g.stopImmediatePropagation(),Ue())},{capture:!0,signal:e}),e.addEventListener("abort",Fe,{once:!0});function Tn(g){let y=$("div",_e==="all"?"pm-card-shelf":"pm-card-grid");if(_e==="all"){y.tabIndex=0,y.setAttribute("role","region"),y.setAttribute("aria-label",g.name);let z=()=>{y.dataset.left=String(y.scrollLeft>3),y.dataset.right=String(y.scrollLeft+y.clientWidth<y.scrollWidth-3)};y.addEventListener("scroll",z,{passive:!0}),cr??=new ResizeObserver(k=>{for(let{target:E}of k)E.dispatchEvent(new Event("scroll"))}),cr.observe(y),requestAnimationFrame(z)}for(let z of g.items){let k=ct(z),E=$("article",`pm-card${k?" pm-card-image":""}`);if(E.dataset.promptId=z.id,E.addEventListener("pointerenter",()=>{ut?.card===E&&ur()}),E.addEventListener("pointerleave",()=>{ut?.card===E&&Tr()}),k){let O=fe(n("Edit prompt","\u7F16\u8F91\u63D0\u793A\u8BCD"),()=>er(z),"pm-card-cover"),q=$("img");q.src=k.data,q.alt="",q.loading="lazy",O.replaceChildren(q),O.addEventListener("pointerenter",G=>{G.pointerType!=="touch"&&jr(O,k,z.summary)}),O.addEventListener("pointerleave",G=>{E.contains(G.relatedTarget)||Tr()}),O.addEventListener("focus",()=>jr(O,k,z.summary)),O.addEventListener("blur",Tr),O.addEventListener("click",Fe),E.append(O)}let U=fe(z.summary,()=>er(z),"pm-card-content");U.replaceChildren(at(z),$("h3","pm-card-title",z.summary),$("p","pm-card-body",z.body));let L=$("div","pm-card-footer"),Z=Ve(n("Use","\u4F7F\u7528"),()=>{Pr(z,Z)});Z.setAttribute("aria-label",n(`Use ${z.summary}`,`\u4F7F\u7528 ${z.summary}`)),L.append($("span","pm-count",n(`${z.useCount} ${z.useCount===1?"call":"calls"}`,`${z.useCount} \u6B21\u8C03\u7528`)),Z),E.append(U,L),y.append(E)}return y}function jn(g){let y=$("div","pm-empty-state"),z=$("span","pm-empty-art",g?"\u{1F50E}":"\u{1F4D6}");return z.setAttribute("role","img"),z.setAttribute("aria-label",n("Prompt","\u63D0\u793A\u8BCD")),y.append(z,$("div","pm-empty-title",g?n("No prompts found","\u672A\u627E\u5230\u63D0\u793A\u8BCD"):n("No prompts yet","\u6682\u65E0\u63D0\u793A\u8BCD")),$("div","pm-empty-description",g?n("Try a different search.","\u8BD5\u8BD5\u5176\u4ED6\u5173\u952E\u8BCD\u3002"):n("Save a prompt to use it again in any chat.","\u6536\u85CF\u63D0\u793A\u8BCD\uFF0C\u5728\u4EFB\u610F\u5BF9\u8BDD\u4E2D\u5FEB\u901F\u8C03\u7528\u3002"))),g||y.append(Ve(n("New prompt","\u65B0\u5EFA\u63D0\u793A\u8BCD"),()=>er(),!0)),y}let Xt=null;function en(g,y,z,k){let E=Ht(n("Drag to reorder","\u62D6\u62FD\u6392\u5E8F"),"drag",()=>{});E.classList.add("pm-drag"),E.setAttribute("data-minecodex-tooltip",n("Drag to reorder \xB7 Alt + \u2191 / \u2193","\u62D6\u62FD\u6392\u5E8F \xB7 Alt + \u2191 / \u2193")),k.dataset.orderId=g.id;let U=z?"categories":`prompts:${g.categoryId??""}`;k.dataset.orderGroup=U;async function L(Z){try{await $e("/api/reorder",{method:"POST",body:{ids:Z,categoryId:g.categoryId??null,categories:z}}),await jt(),z&&ce&&Jt()}catch(O){Tt(O)}}return E.addEventListener("pointerdown",()=>{k.draggable=!0}),E.addEventListener("pointerup",()=>{k.draggable=!1}),k.addEventListener("dragstart",Z=>{if(Xt)return;let O=k.parentElement,q=[...O.children].filter(Pe=>Pe.dataset.orderGroup===U),G=k.nextSibling,F=k.getBoundingClientRect(),ee=getComputedStyle(k).borderRadius,Y=k.cloneNode(!0);Y.removeAttribute("data-order-group"),Y.removeAttribute("data-order-id"),Y.setAttribute("aria-hidden","true"),Object.assign(Y.style,{position:"fixed",left:"-10000px",top:"0",width:`${F.width}px`,height:`${F.height}px`,margin:"0",boxSizing:"border-box",pointerEvents:"none",background:"var(--mcx-color-surface)",borderRadius:ee,overflow:"hidden",clipPath:`inset(0 round ${ee})`}),O.append(Y),Z.dataTransfer.setDragImage(Y,Z.clientX-F.left,Z.clientY-F.top);let ae=$("div","pm-drop-placeholder");ae.style.height=`${k.getBoundingClientRect().height}px`,ae.setAttribute("aria-hidden","true");let we=new AbortController,wt=matchMedia("(prefers-reduced-motion: reduce)").matches,tt=new Map,mr=!1,nn=!1,Un=wt?0:180;function on(Pe){if(ae.nextSibling===Pe||Pe===ae)return;let ke=new Map(q.filter(Te=>Te!==k).map(Te=>[Te,Te.getBoundingClientRect().top]));for(let Te of tt.values())Te.cancel();tt.clear(),O.insertBefore(ae,Pe);for(let[Te,mt]of ke){let tr=mt-Te.getBoundingClientRect().top;tr&&Un&&tt.set(Te,Te.animate([{transform:`translateY(${tr}px)`},{transform:"translateY(0)"}],{duration:Un,easing:"cubic-bezier(.2,.8,.2,1)"}))}}function Mr(Pe){if(nn||(nn=!0,we.abort(),Y.remove(),Xt=null,k.draggable=!1,!mr))return;Pe||on(G),O.insertBefore(k,ae),k.classList.remove("pm-dragging"),ae.remove();let ke=[...O.children].filter(mt=>mt.dataset.orderGroup===U).map(mt=>mt.dataset.orderId),Te=k.animate([{opacity:.45},{opacity:1}],{duration:wt?0:140,easing:"ease-out"});Pe&&ke.some((mt,tr)=>mt!==y[tr].id)&&Te.finished.catch(()=>{}).then(()=>L(ke))}Xt={cancel:()=>Mr(!1)},Z.dataTransfer.effectAllowed="move",Z.dataTransfer.setData("text/plain",g.id),requestAnimationFrame(()=>{Y.remove(),!(nn||!k.isConnected)&&(k.before(ae),k.classList.add("pm-dragging"),mr=!0)}),O.addEventListener("dragover",Pe=>{if(!mr)return;let ke=Pe.target.closest("[data-order-group], .pm-drop-placeholder");if(ke!==ae&&(!q.includes(ke)||ke===k)||(Pe.preventDefault(),Pe.dataTransfer.dropEffect="move",ke===ae))return;let Te=ke.getBoundingClientRect(),mt=getComputedStyle(ke).transform,tr=mt==="none"?0:new DOMMatrixReadOnly(mt).m42,Mn=Pe.clientY>Te.top-tr+Te.height/2;on(Mn?ke.nextSibling:ke)},{signal:we.signal}),O.addEventListener("drop",Pe=>{let ke=Pe.target.closest("[data-order-group], .pm-drop-placeholder");ke!==ae&&!q.includes(ke)||(Pe.preventDefault(),Mr(!0))},{signal:we.signal}),k.addEventListener("dragend",()=>Mr(!1),{once:!0,signal:we.signal}),e.addEventListener("abort",()=>Mr(!1),{once:!0,signal:we.signal})}),E.addEventListener("keydown",Z=>{if(!Z.altKey||!["ArrowUp","ArrowDown"].includes(Z.key))return;Z.preventDefault();let O=y.map(F=>F.id),q=O.indexOf(g.id),G=q+(Z.key==="ArrowUp"?-1:1);G<0||G>=O.length||([O[q],O[G]]=[O[G],O[q]],L(O))}),E}function $r(g,y){let z=$("label","pm-field",g);return z.append(y),z}let et=null,Nr=null,tn=null;function dr(g=!0){Xt?.cancel(),Ne(),tn?.(),tn=null,et?.remove(),et=null,xe=null;let y=ce?.querySelector(".pm-wrap");y&&(y.inert=!1),g&&Nr?.isConnected&&Nr.focus({preventScroll:!0})}function Ut(g,y=null){return Ne(),et||(Nr=document.activeElement,et=$("div","pm-modal-layer"),et.setAttribute(o,"modal"),t.ui.overlay(et),t.ui.mount(et,"modal"),tn=t.ui.trapFocus(()=>xe,{onClose:()=>dr(),isBlocked:()=>!!be}),ce.querySelector(".pm-wrap").inert=!0),et.replaceChildren(),xe=$("div","pm-editor"),xe.setAttribute("role","dialog"),xe.setAttribute("aria-modal","true"),xe.setAttribute("aria-label",g),xe.tabIndex=-1,t.ui.heading(xe,{title:g,closeLabel:n("Close","\u5173\u95ED"),onClose:()=>dr(),back:y?Ht(n("Back","\u8FD4\u56DE"),"back",y):null}).classList.add("pm-modal-heading"),et.append(xe),xe.focus(),xe}function er(g=null){Fe();let y=Ut(g?n("Edit prompt","\u7F16\u8F91\u63D0\u793A\u8BCD"):n("New prompt","\u65B0\u5EFA\u63D0\u793A\u8BCD"));y.classList.add("pm-prompt-editor");let z=$("form","pm-form"),k=$("input");k.value=g?.title??"",k.maxLength=200;let E={value:g?.categoryId??(T.some(Y=>Y.id===_e)?_e:"")},U={value:g?.emoji??""},L=fe("",()=>{let Y=Yt(L,"pm-category-menu","menu",!0);if(Y){for(let ae of[...T,{id:"",name:n("Other","\u5176\u4ED6")}]){let we=fe(ae.name,()=>{E.value=ae.id,O(),Ne(!0)},"");we.replaceChildren(at({categoryId:ae.id||null}),$("span","pm-option-label",ae.name)),we.setAttribute("role","menuitemradio"),we.setAttribute("aria-checked",String(E.value===ae.id)),E.value===ae.id&&we.append(Se("check")),Y.append(we)}Y.querySelector("[aria-checked=true]")?.focus()}},"pm-select");L.setAttribute("aria-haspopup","menu");let Z=fe(n("Choose icon","\u9009\u62E9\u56FE\u6807"),()=>$n(Z,U,O),"pm-emoji-trigger");Z.setAttribute("aria-haspopup","dialog");function O(){let Y=T.find(ae=>ae.id===E.value);L.replaceChildren(at({categoryId:E.value||null}),$("span","pm-option-label",Y?.name??n("Other","\u5176\u4ED6")),Se("chevron")),L.setAttribute("aria-label",n("Category: ","\u5206\u7C7B\uFF1A")+(Y?.name??n("Other","\u5176\u4ED6"))),Z.replaceChildren(at({categoryId:E.value||null,emoji:U.value})),Z.setAttribute("data-minecodex-tooltip",n("Choose icon","\u9009\u62E9\u56FE\u6807"))}O();let q=$("textarea");q.value=g?.body??"",q.required=!0;let G=$("div","pm-title-control");G.setAttribute("role","group"),G.setAttribute("aria-label",n("Prompt title and icon","\u63D0\u793A\u8BCD\u6807\u9898\u4E0E\u56FE\u6807")),k.setAttribute("aria-label",n("Title","\u6807\u9898")),k.placeholder=n("Title","\u6807\u9898"),G.append(Z,k),z.append(G,$r(n("Category","\u5206\u7C7B"),L),$r(n("Prompt","\u63D0\u793A\u8BCD"),q));let F=t.ui.footer($("div","pm-footer"));if(g){let Y=Ve(n("Delete","\u5220\u9664"),async()=>{if(Y.dataset.confirm!=="true"){Y.dataset.confirm="true",Y.textContent=n("Confirm delete","\u786E\u8BA4\u5220\u9664");return}Y.disabled=!0;try{await $e(`/api/prompts/${g.id}`,{method:"DELETE"}),xe===y&&await jt()}catch(ae){Y.disabled=!1,Tt(ae)}});t.ui.action(Y,"danger"),Y.style.marginRight="auto",F.append(Y)}let ee=Ve(n("Save","\u4FDD\u5B58"),()=>{},!0);ee.type="submit",F.append(Ve(n("Cancel","\u53D6\u6D88"),lr,!1,"ghost"),ee),z.append(F),y.append(z),z.addEventListener("submit",async Y=>{if(Y.preventDefault(),!(ee.disabled||!q.value.trim())){ee.disabled=!0;try{await $e(g?`/api/prompts/${g.id}`:"/api/prompts",{method:g?"PATCH":"POST",body:{title:k.value,body:q.value,categoryId:E.value||null,emoji:U.value.trim()}}),xe===y&&await jt()}catch(ae){xe===y&&(ee.disabled=!1,Tt(ae))}}}),k.focus()}function $n(g,y,z){let k=Yt(g,"pm-symbol-picker","dialog");if(!k)return;let E=$("input");E.placeholder=n("Search emoji","\u641C\u7D22 Emoji"),E.setAttribute("aria-label",E.placeholder);let U=$("div","pm-emoji-grid");U.setAttribute("role","group"),U.setAttribute("aria-label",n("Emojis","Emoji"));let L=()=>{U.replaceChildren();let q=E.value.trim().toLocaleLowerCase();for(let G of re.filter(F=>!q||F[0].includes(q)||F[1].includes(q))){let F=fe(G[1],()=>{y.value=G[0],z(),Ne(!0)},"pm-emoji-choice");F.textContent=G[0],F.setAttribute("aria-pressed",String(y.value===G[0])),U.append(F)}U.children.length||U.append($("div","pm-empty-description",n("No emoji found","\u672A\u627E\u5230 Emoji")))};E.addEventListener("input",L);let Z=fe(n("Use category icon","\u4F7F\u7528\u5206\u7C7B\u56FE\u6807"),()=>{y.value="",z(),Ne(!0)},"pm-command");k.append(E,U,Z),L(),E.focus();let O=k.getBoundingClientRect();k.style.left=`${Math.max(8,Math.min(g.getBoundingClientRect().left,innerWidth-O.width-8))}px`,O.bottom>innerHeight-16&&(k.style.top=`${Math.max(16,innerHeight-O.height-16)}px`),k.addEventListener("keydown",q=>{let G=[...U.querySelectorAll("button")],F=G.indexOf(document.activeElement);if(["ArrowLeft","ArrowRight","ArrowUp","ArrowDown"].includes(q.key)){q.preventDefault();let ee={ArrowLeft:-1,ArrowRight:1,ArrowUp:-8,ArrowDown:8}[q.key];G[Math.max(0,Math.min(G.length-1,F+ee))]?.focus()}if(q.key==="Tab"){let ee=[E,...G,Z],Y=ee.indexOf(document.activeElement);q.shiftKey&&Y===0?(q.preventDefault(),Z.focus()):!q.shiftKey&&Y===ee.length-1&&(q.preventDefault(),E.focus())}})}function Jt(){let g=Ut(n("Categories","\u5206\u7C7B")),y=t.ui.footer($("div","pm-footer"));y.append(Ve(n("New category","\u65B0\u5EFA\u5206\u7C7B"),()=>Ur()));for(let z of T){let k=$("div","pm-row");k.append(at({categoryId:z.id}),fe(z.name,()=>Ur(z),"pm-info"),en(z,T,!0,k)),g.append(k)}g.append(y)}function Ur(g=null){let y=Ut(g?n("Edit category","\u7F16\u8F91\u5206\u7C7B"):n("New category","\u65B0\u5EFA\u5206\u7C7B"),Jt),z=$("form","pm-form"),k=$("input");k.value=g?.name??"",k.required=!0,k.maxLength=60;let E=g?.icon??"book",U=g?.color??"black",L=$("div","pm-grid");L.setAttribute("aria-label",n("Category icon","\u5206\u7C7B\u56FE\u6807"));function Z(){L.replaceChildren();for(let F of Object.keys(Q)){let ee=fe(F,()=>{E=F,Z()},"pm-choice"),Y=new DOMParser().parseFromString(Q[F],"image/svg+xml").documentElement;ee.replaceChildren(Y),ee.setAttribute("aria-pressed",String(F===E)),ee.setAttribute("data-minecodex-tooltip",H(F)),ee.setAttribute("aria-label",H(F)),L.append(ee)}}Z();let O=$("div","pm-grid");for(let F of Object.keys(Pt)){let ee=fe(F,()=>{U=F;for(let ae of O.children)ae.setAttribute("aria-pressed",String(ae===ee))},"pm-choice"),Y=$("span","qp-symbol");Y.style.setProperty("--prompt-icon-light",Pt[F][0]),Y.style.setProperty("--prompt-icon-dark",Pt[F][1]),Y.append($("span","pm-swatch")),ee.replaceChildren(Y),ee.setAttribute("aria-pressed",String(F===U)),ee.setAttribute("data-minecodex-tooltip",H(F)),ee.setAttribute("aria-label",H(F)),O.append(ee)}z.append($r(n("Name","\u540D\u79F0"),k),$("div","",n("Icon","\u56FE\u6807")),L,$("div","",n("Color","\u989C\u8272")),O);let q=t.ui.footer($("div","pm-footer"));if(g){let F=Ve(n("Delete","\u5220\u9664"),()=>{let ee=A.filter(tt=>tt.categoryId===g.id).length,Y=async tt=>{tt.disabled=!0;try{await $e(`/api/categories/${g.id}`,{method:"DELETE"}),await jt(),ce&&Jt()}catch(mr){tt.disabled=!1,Tt(mr)}};if(!ee){Y(F);return}let ae=Ut(n("Delete category?","\u5220\u9664\u5206\u7C7B\uFF1F"));ae.append($("p","pm-confirm-description",n(`${ee} prompts will move to Other. Their content and call counts will be kept.`,`${ee} \u6761\u63D0\u793A\u8BCD\u5C06\u79FB\u5230 Other\uFF0C\u5185\u5BB9\u548C\u8C03\u7528\u6B21\u6570\u90FD\u4F1A\u4FDD\u7559\u3002`)));let we=t.ui.footer($("div","pm-footer")),wt=Ve(n("Delete","\u5220\u9664"),()=>{Y(wt)});t.ui.action(wt,"danger"),we.append(Ve(n("Cancel","\u53D6\u6D88"),()=>Ur(g),!1,"ghost"),wt),ae.append(we)});t.ui.action(F,"danger"),F.style.marginRight="auto",q.append(F)}let G=Ve(n("Save","\u4FDD\u5B58"),()=>{},!0);G.type="submit",q.append(Ve(n("Cancel","\u53D6\u6D88"),Jt,!1,"ghost"),G),z.append(q),y.append(z),z.addEventListener("submit",async F=>{if(F.preventDefault(),!G.disabled){G.disabled=!0;try{await $e(g?`/api/categories/${g.id}`:"/api/categories",{method:g?"PATCH":"POST",body:{name:k.value,icon:E,color:U}}),xe===y&&(await jt(),ce&&Jt())}catch(ee){xe===y&&(G.disabled=!1,Tt(ee))}}}),k.focus()}window.addEventListener("resize",Yr,{signal:e}),document.addEventListener("focusin",g=>{if(t.management)return;let y=g.target.closest?.('[contenteditable="true"]'),z=y?t.codex.composer(y,{purpose:"insertion"}):null;z&&(h=z.editable),zr()},{signal:e});let rn=new MutationObserver(()=>{C||(C=!0,queueMicrotask(()=>{C=!1,zr()}))});t.management||rn.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["data-composer-placement","data-above-composer-conversation-id","aria-expanded","data-selected","aria-current","class","hidden","inert","aria-hidden"]}),document.addEventListener("pointerdown",g=>{m&&!m.contains(g.target)&&!De?.node.contains(g.target)&&!s?.contains(g.target)&&Xe()},{signal:e}),document.addEventListener("keydown",g=>{if(m){if(g.key==="Escape")g.preventDefault(),g.stopImmediatePropagation(),Xe(!0);else if(["ArrowDown","ArrowUp"].includes(g.key)){g.preventDefault(),g.stopImmediatePropagation();let y=[...m.querySelectorAll(".qp-select")],z=y.indexOf(document.activeElement),k=g.key==="ArrowDown"?(z+1)%y.length:(z<=0?y.length:z)-1;y[k]?.focus()}}},{signal:e,capture:!0}),window.addEventListener("resize",()=>{Oe(!0),Ct()},{signal:e}),window.addEventListener("scroll",Ct,{signal:e,capture:!0});let Nn=t.management?null:installPromptInsertion(e,{codex:t.codex,api:$e,insertText:(g,y)=>window.__codexPersonalRuntime.insertText(g,y)});return t.management?Cn():zr(),t.registerSelfCheck?.(()=>{let g=t.codex.composer(null,{purpose:"insertion"}),y=g?[{name:"quick-prompts-anchor",available:!!(g.add&&s?.isConnected&&f===g.editable)}]:[],z=y.every(k=>k.available);return{state:g?z?"available":"unavailable":"not-applicable",reason:z?null:"prompts-anchor-unavailable",checks:y,scopes:[{name:"composer",element:g?.root},{name:"quick-prompts",element:m}]}}),()=>{M=!0,rn.disconnect(),Xe(),s?.remove(),Xr(),a.remove()}}var mx={prompt:`<svg
102
102
  class="lucide lucide-book-open"
103
103
  xmlns="http://www.w3.org/2000/svg"
@@ -396,9 +396,10 @@ ${U.body}`.toLocaleLowerCase().includes(y)));if(!k.length){g.append(jn(!!y));ret
396
396
  [data-mcx-ui-surface=popover] { box-shadow:0 0 0 var(--mcx-popover-overlay-ring-width,.5px) var(--mcx-color-border-overlay),var(--mcx-shadow-popover-overlay,var(--mcx-shadow-lg)); }
397
397
  [data-mcx-ui-surface=popover][data-mcx-ui-variant=translucent] { background:color-mix(in oklab,var(--mcx-color-surface-elevated-secondary) 90%,transparent); }
398
398
  [data-mcx-ui-surface=composer-menu] { border:var(--mcx-suggestion-menu-border-width,1px) solid var(--mcx-color-border); border-radius:var(--mcx-radius-suggestion-menu,var(--mcx-radius-2xl)); box-shadow:var(--mcx-suggestion-menu-shadow,none); }
399
+ [data-mcx-ui-surface=floating-panel] { box-shadow:0 0 0 .5px var(--mcx-color-border),var(--mcx-shadow-2xl); }
399
400
  [data-mcx-ui-surface=page] { border-radius:var(--mcx-radius-xl-base); background:var(--mcx-color-surface); box-shadow:none; }
400
401
  [data-mcx-ui-surface=page][data-mcx-ui-variant=transparent] { background:transparent; }
401
- `,document.head.append(i),e.addEventListener("abort",()=>i.remove(),{once:!0});function o(n,a="popover",{variant:s,opaque:c=!0}={}){let l={dialog:"opaque",dropdown:"menu",popover:c?"opaque":"translucent","composer-menu":"floating",page:"opaque"};if(!(a in l))throw new Error(`Unknown UI surface: ${a}`);return a!=="dialog"&&a!=="page"&&t.layer(n,"floating"),n.setAttribute("data-mcx-ui-surface",a),n.setAttribute("data-mcx-ui-variant",s??l[a]),n}function r(n,a="opaque"){return n.setAttribute("data-mcx-ui-overlay",a),n}return{surface:o,overlay:r}}function vx(e,t){let i=document.createElement("style");i.setAttribute("data-minecodex-ui-styles","installDialog"),i.textContent=` [data-mcx-ui-surface=dialog]:not(dialog) { position:relative; }
402
+ `,document.head.append(i),e.addEventListener("abort",()=>i.remove(),{once:!0});function o(n,a="popover",{variant:s,opaque:c=!0}={}){let l={dialog:"opaque",dropdown:"menu",popover:c?"opaque":"translucent","composer-menu":"floating",page:"opaque","floating-panel":"opaque"};if(!(a in l))throw new Error(`Unknown UI surface: ${a}`);return a!=="dialog"&&a!=="page"&&a!=="floating-panel"&&t.layer(n,"floating"),n.setAttribute("data-mcx-ui-surface",a),n.setAttribute("data-mcx-ui-variant",s??l[a]),n}function r(n,a="opaque"){return n.setAttribute("data-mcx-ui-overlay",a),n}return{surface:o,overlay:r}}function vx(e,t){let i=document.createElement("style");i.setAttribute("data-minecodex-ui-styles","installDialog"),i.textContent=` [data-mcx-ui-surface=dialog]:not(dialog) { position:relative; }
402
403
  [data-mcx-ui-surface=dialog] { box-sizing:border-box; padding:var(--mcx-modal-container-inner-padding); border:0; border-radius:var(--mcx-radius-3xl); corner-shape:round; color:var(--mcx-color-text-primary); font-family:var(--mcx-font-sans-default); font-size:var(--mcx-text-base); line-height:1.5; outline:none; }
403
404
  [data-mcx-ui-surface=dialog] [data-mcx-ui-heading] { display:flex; align-items:center; gap:8px; padding-right:28px; margin:0 0 12px; }
404
405
  [data-mcx-ui-surface=dialog] [data-mcx-ui-heading] h2 { flex:1; min-width:0; margin:0; font-size:var(--mcx-text-heading-md); line-height:1.4; font-weight:var(--mcx-font-weight-semibold); letter-spacing:normal; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
@@ -425,7 +426,7 @@ ${U.body}`.toLocaleLowerCase().includes(y)));if(!k.length){g.append(jn(!!y));ret
425
426
  font-family:var(--mcx-font-sans-default);font-size:var(--mcx-text-sm);line-height:18px;
426
427
  font-weight:var(--mcx-tooltip-compact-font-weight);letter-spacing:var(--mcx-tracking-tooltip);user-select:none; }
427
428
  `,document.head.append(o);function r(m){return m.setAttribute("data-mcx-ui-tooltip",""),m}r(i),i.style.cssText=`zoom:var(--codex-window-zoom,1);max-width:min(320px,calc(100vw - 16px));
428
- text-align:center;overflow-wrap:anywhere;`;let n=null,a,s,c=-1/0;function l(){if(clearTimeout(a),cancelAnimationFrame(s),n){let m=(n.getAttribute("aria-describedby")||"").split(/\s+/).filter(A=>A&&A!==i.id);m.length?n.setAttribute("aria-describedby",m.join(" ")):n.removeAttribute("aria-describedby")}i.hidden||(c=Date.now()),n=null,i.hidden=!0}function d(){if(!n?.isConnected||!n.getClientRects().length||n.getAttribute("aria-expanded")==="true")return l();let m=Number.parseFloat(getComputedStyle(i).zoom)||1,A=n.getBoundingClientRect(),x=i.offsetWidth,C=i.offsetHeight,M=n.getAttribute("data-minecodex-tooltip-side")||(n.closest("[data-app-navigation-rail]")?"right":getComputedStyle(n).getPropertyValue("--side-tooltip").trim()||"top"),T=2/m,Q=(A.left+A.width/2)/m-x/2,re=M==="bottom"?A.bottom/m+T:A.top/m-C-T;M==="right"||M==="left"?(Q=M==="right"?A.right/m+T:A.left/m-x-T,re=(A.top+A.height/2)/m-C/2,Q+x>innerWidth/m-8?Q=A.left/m-x-T:Q<8&&(Q=A.right/m+T)):re<8?re=A.bottom/m+T:re+C>innerHeight/m-8&&(re=A.top/m-C-T),i.style.left=`${Math.max(8,Math.min(Q,innerWidth/m-x-8))}px`,i.style.top=`${Math.max(8,Math.min(re,innerHeight/m-C-8))}px`,s=requestAnimationFrame(d)}function f(m,A=!1){!m||m===n||(l(),!(m.getAttribute("aria-expanded")==="true"||!m.getAttribute(t))&&(n=m,a=setTimeout(()=>{if(!n?.isConnected)return l();i.isConnected||document.body.append(i);let x=getComputedStyle(n);for(let M of["--radius-2xl","--codex-corner-shape","--color-background-tooltip","--color-text-tooltip","--color-border-tooltip","--shadow-tooltip","--tooltip-compact-font-weight","--tracking-tooltip","--spacing","--text-sm","--font-sans-default"]){let T=x.getPropertyValue(M).trim();T?i.style.setProperty(M,T):i.style.removeProperty(M)}i.textContent=n.getAttribute(t),i.hidden=!1;let C=(n.getAttribute("aria-describedby")||"").split(/\s+/).filter(Boolean);n.setAttribute("aria-describedby",[...new Set([...C,i.id])].join(" ")),d()},A||Date.now()-c<300?0:200)))}let h=m=>m.target instanceof Element?m.target.closest(`[${t}]`):null;return document.addEventListener("pointerover",m=>f(h(m)),{signal:e}),document.addEventListener("pointerout",m=>{n&&!n.contains(m.relatedTarget)&&l()},{signal:e}),document.addEventListener("focusin",m=>f(h(m),!0),{signal:e}),document.addEventListener("focusout",l,{signal:e}),document.addEventListener("pointerdown",l,{signal:e,capture:!0}),document.addEventListener("keydown",m=>{m.key==="Escape"&&l()},{signal:e}),window.addEventListener("blur",l,{signal:e}),e.addEventListener("abort",()=>{l(),i.remove(),o.remove()},{once:!0}),{tooltipSurface:r}}var Mo=new vd({name:"Prompt",version:"2.0.21"});Mo.ontoolresult=()=>{};await Mo.connect();uv(Mo.getHostContext());Mo.addEventListener("hostcontextchanged",uv);var bx=new AbortController,Ad=bx.signal,bi={};for(let e of[hx,gx,vx,Ax,yx])Object.assign(bi,e(Ad,bi));bi.page=e=>(bi.surface(e,"page"),bi.layer(e,"page"));bi.releasePage=()=>{};var j_=dx(Ad,{management:!0,ui:bi,resources:{icons:mx,previews:px,styles:fx},insertPrompt:e=>new Promise((t,i)=>{let o=new MessageChannel,r,n=s=>{clearTimeout(r),o.port1.close(),Ad.removeEventListener("abort",a),s?i(s):t()},a=()=>n(new Error("Prompt page closed"));Ad.addEventListener("abort",a,{once:!0}),r=setTimeout(()=>n(new Error("No available input in the focused window")),4500),o.port1.onmessage=({data:s})=>n(s.ok?null:new Error(s.error)),window.top.postMessage({type:"minecodex:insert-prompt",promptId:e,expiresAt:Date.now()+4e3},"*",[o.port2])}),requestHostAction:async(e,t)=>{let i=await Mo.callServerTool({name:t.method&&t.method!=="GET"?"minecodex_prompts_write":"minecodex_prompts_read",arguments:t});if(i.isError)throw new Error(i.content?.find(o=>o.type==="text")?.text??"Prompts request failed");return i.structuredContent.result}});Mo.onteardown=async()=>(bx.abort(),j_(),{});
429
+ text-align:center;overflow-wrap:anywhere;`;let n=null,a,s,c=-1/0;function l(){if(clearTimeout(a),cancelAnimationFrame(s),n){let m=(n.getAttribute("aria-describedby")||"").split(/\s+/).filter(A=>A&&A!==i.id);m.length?n.setAttribute("aria-describedby",m.join(" ")):n.removeAttribute("aria-describedby")}i.hidden||(c=Date.now()),n=null,i.hidden=!0}function d(){if(!n?.isConnected||!n.getClientRects().length||n.getAttribute("aria-expanded")==="true")return l();let m=Number.parseFloat(getComputedStyle(i).zoom)||1,A=n.getBoundingClientRect(),x=i.offsetWidth,C=i.offsetHeight,M=n.getAttribute("data-minecodex-tooltip-side")||(n.closest("[data-app-navigation-rail]")?"right":getComputedStyle(n).getPropertyValue("--side-tooltip").trim()||"top"),T=2/m,Q=(A.left+A.width/2)/m-x/2,re=M==="bottom"?A.bottom/m+T:A.top/m-C-T;M==="right"||M==="left"?(Q=M==="right"?A.right/m+T:A.left/m-x-T,re=(A.top+A.height/2)/m-C/2,Q+x>innerWidth/m-8?Q=A.left/m-x-T:Q<8&&(Q=A.right/m+T)):re<8?re=A.bottom/m+T:re+C>innerHeight/m-8&&(re=A.top/m-C-T),i.style.left=`${Math.max(8,Math.min(Q,innerWidth/m-x-8))}px`,i.style.top=`${Math.max(8,Math.min(re,innerHeight/m-C-8))}px`,s=requestAnimationFrame(d)}function f(m,A=!1){!m||m===n||(l(),!(m.getAttribute("aria-expanded")==="true"||!m.getAttribute(t))&&(n=m,a=setTimeout(()=>{if(!n?.isConnected)return l();i.isConnected||document.body.append(i);let x=getComputedStyle(n);for(let M of["--radius-2xl","--codex-corner-shape","--color-background-tooltip","--color-text-tooltip","--color-border-tooltip","--shadow-tooltip","--tooltip-compact-font-weight","--tracking-tooltip","--spacing","--text-sm","--font-sans-default"]){let T=x.getPropertyValue(M).trim();T?i.style.setProperty(M,T):i.style.removeProperty(M)}i.textContent=n.getAttribute(t),i.hidden=!1;let C=(n.getAttribute("aria-describedby")||"").split(/\s+/).filter(Boolean);n.setAttribute("aria-describedby",[...new Set([...C,i.id])].join(" ")),d()},A||Date.now()-c<300?0:200)))}let h=m=>m.target instanceof Element?m.target.closest(`[${t}]`):null;return document.addEventListener("pointerover",m=>f(h(m)),{signal:e}),document.addEventListener("pointerout",m=>{n&&!n.contains(m.relatedTarget)&&l()},{signal:e}),document.addEventListener("focusin",m=>f(h(m),!0),{signal:e}),document.addEventListener("focusout",l,{signal:e}),document.addEventListener("pointerdown",l,{signal:e,capture:!0}),document.addEventListener("keydown",m=>{m.key==="Escape"&&l()},{signal:e}),window.addEventListener("blur",l,{signal:e}),e.addEventListener("abort",()=>{l(),i.remove(),o.remove()},{once:!0}),{tooltipSurface:r}}var Mo=new vd({name:"Prompt",version:"2.0.32"});Mo.ontoolresult=()=>{};await Mo.connect();uv(Mo.getHostContext());Mo.addEventListener("hostcontextchanged",uv);var bx=new AbortController,Ad=bx.signal,bi={};for(let e of[hx,gx,vx,Ax,yx])Object.assign(bi,e(Ad,bi));bi.page=e=>(bi.surface(e,"page"),bi.layer(e,"page"));bi.releasePage=()=>{};var j_=dx(Ad,{management:!0,ui:bi,resources:{icons:mx,previews:px,styles:fx},insertPrompt:e=>new Promise((t,i)=>{let o=new MessageChannel,r,n=s=>{clearTimeout(r),o.port1.close(),Ad.removeEventListener("abort",a),s?i(s):t()},a=()=>n(new Error("Prompt page closed"));Ad.addEventListener("abort",a,{once:!0}),r=setTimeout(()=>n(new Error("No available input in the focused window")),4500),o.port1.onmessage=({data:s})=>n(s.ok?null:new Error(s.error)),window.top.postMessage({type:"minecodex:insert-prompt",promptId:e,expiresAt:Date.now()+4e3},"*",[o.port2])}),requestHostAction:async(e,t)=>{let i=await Mo.callServerTool({name:t.method&&t.method!=="GET"?"minecodex_prompts_write":"minecodex_prompts_read",arguments:t});if(i.isError)throw new Error(i.content?.find(o=>o.type==="text")?.text??"Prompts request failed");return i.structuredContent.result}});Mo.onteardown=async()=>(bx.abort(),j_(),{});
429
430
  /*! Bundled license information:
430
431
 
431
432
  @modelcontextprotocol/client/dist/src-WCy6ifGf.mjs:
@@ -14,4 +14,3 @@ app.addEventListener("hostcontextchanged", syncHost);
14
14
  syncHost(app.getHostContext());
15
15
  await import("../../../apps/dashboard/app.js");
16
16
  await import("../../../apps/dashboard/assets/data-transfer.js");
17
- await import("../../../apps/dashboard/assets/terrain.js");
@@ -8,7 +8,7 @@ import path from "node:path";
8
8
  import { resolvePaths } from "../../cli/src/paths.mjs";
9
9
  import { createControlClient } from "./control-client.mjs";
10
10
  import { createPromptsClient } from "./prompts-client.mjs";
11
- import { createAppHtml, createPromptsHtml } from "./ui-resource.mjs";
11
+ import { createAppHtml, createPromptsHtml, readPreviewResource } from "./ui-resource.mjs";
12
12
  import { RELEASE_VERSION, CONTROL_RESOURCE_URI, PROMPT_RESOURCE_URI } from "./version.mjs";
13
13
 
14
14
  export const APP_URI = CONTROL_RESOURCE_URI;
@@ -67,6 +67,8 @@ export function createPluginServer({ promptsClient, paths = resolvePaths(), clie
67
67
  server.sendToolListChanged();
68
68
  return promptsResource(previousPromptsUri);
69
69
  });
70
+ server.registerResource("feature-preview", new ResourceTemplate("resource://minecodex/previews/{featureId}/{kind}", {list:undefined}),
71
+ {}, (uri, {featureId, kind}) => readPreviewResource(path.join(paths.packageRoot, "apps/dashboard"), featureId, kind, uri));
70
72
  let html;
71
73
  const controlResource = async uri => ({ contents: [{
72
74
  uri, mimeType: RESOURCE_MIME_TYPE, text: html ??= await createAppHtml(paths.packageRoot),
@@ -1,6 +1,6 @@
1
1
  import { readFile } from "node:fs/promises";
2
2
  import path from "node:path";
3
- const mime = { ".svg": "image/svg+xml", ".ttf": "font/ttf" };
3
+ const mime = { ".svg": "image/svg+xml" };
4
4
  export async function createAppHtml(packageRoot) {
5
5
  const directory = path.join(packageRoot, "apps/dashboard");
6
6
  let html = await readFile(path.join(directory, "index.html"), "utf8");
@@ -9,11 +9,14 @@ export async function createAppHtml(packageRoot) {
9
9
  const asset = await readFile(path.join(directory, match[1]));
10
10
  css = css.replaceAll(match[0], `url("data:${mime[path.extname(match[1])]};base64,${asset.toString("base64")}")`);
11
11
  }
12
+ let previewMedia = {};
13
+ try { previewMedia = JSON.parse(await readFile(path.join(directory, "assets/previews/manifest.json"), "utf8")); }
14
+ catch (error) { if (error.code !== "ENOENT" && !(error instanceof SyntaxError)) throw error; }
12
15
  const script = await readFile(path.join(packageRoot, "packages/plugin/assets/app.js"), "utf8");
13
16
  html = html.replace(/\s*<link[^>]+>/g, "").replace(/\s*<script[\s\S]*?<\/script>/g, "");
14
17
  // 回调保留资源中的 $&、$` 等字面量,避免被 replace 当成替换指令。
15
18
  return html.replace("</head>", () => `<style>${css}</style></head>`)
16
- .replace("</body>", () => `<script type="module">${script.replaceAll("</script", "<\\/script")}</script></body>`);
19
+ .replace("</body>", () => `<script>window.minecodexPreviewMedia=${JSON.stringify(previewMedia).replaceAll("<", "\\u003c")};</script><script type="module">${script.replaceAll("</script", "<\\/script")}</script></body>`);
17
20
  }
18
21
 
19
22
  export async function createPromptsHtml(packageRoot) {
@@ -21,3 +24,16 @@ export async function createPromptsHtml(packageRoot) {
21
24
  return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
22
25
  <style>${await readFile(path.join(packageRoot,"packages/ui/src/native/mcp-theme.css"),"utf8")} </style></head><body><script type="module">${script.replaceAll('</script','<\\/script')}</script></body></html>`;
23
26
  }
27
+
28
+ // MCP 媒体通过 resources/read 按需读取,首次打开页面不传全量视频。
29
+ export async function readPreviewResource(directory, featureId, kind, uri) {
30
+ const base = path.join(directory, "assets/previews");
31
+ const manifest = JSON.parse(await readFile(path.join(base, "manifest.json"), "utf8"));
32
+ if (!["video", "poster"].includes(kind) || !Object.hasOwn(manifest, featureId)) throw new Error("Preview resource unavailable");
33
+ const filename = manifest[featureId][kind];
34
+ const mediaTypes = {".mp4":"video/mp4", ".webm":"video/webm", ".png":"image/png", ".jpg":"image/jpeg", ".webp":"image/webp"};
35
+ const allowed = kind === "video" ? [".mp4", ".webm"] : [".png", ".jpg", ".webp"];
36
+ if (typeof filename !== "string" || !/^[a-zA-Z0-9_.-]+$/.test(filename) || !allowed.includes(path.extname(filename))) throw new Error("Invalid preview resource");
37
+ const bytes = await readFile(path.join(base, filename));
38
+ return {contents:[{uri:uri.href, mimeType:mediaTypes[path.extname(filename)], blob:bytes.toString("base64")}]};
39
+ }
@@ -1,93 +0,0 @@
1
- Copyright 2001 The Silkscreen Project Authors (https://github.com/googlefonts/silkscreen)
2
-
3
- This Font Software is licensed under the SIL Open Font License, Version 1.1.
4
- This license is copied below, and is also available with a FAQ at:
5
- https://scripts.sil.org/OFL
6
-
7
-
8
- -----------------------------------------------------------
9
- SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
10
- -----------------------------------------------------------
11
-
12
- PREAMBLE
13
- The goals of the Open Font License (OFL) are to stimulate worldwide
14
- development of collaborative font projects, to support the font creation
15
- efforts of academic and linguistic communities, and to provide a free and
16
- open framework in which fonts may be shared and improved in partnership
17
- with others.
18
-
19
- The OFL allows the licensed fonts to be used, studied, modified and
20
- redistributed freely as long as they are not sold by themselves. The
21
- fonts, including any derivative works, can be bundled, embedded,
22
- redistributed and/or sold with any software provided that any reserved
23
- names are not used by derivative works. The fonts and derivatives,
24
- however, cannot be released under any other type of license. The
25
- requirement for fonts to remain under this license does not apply
26
- to any document created using the fonts or their derivatives.
27
-
28
- DEFINITIONS
29
- "Font Software" refers to the set of files released by the Copyright
30
- Holder(s) under this license and clearly marked as such. This may
31
- include source files, build scripts and documentation.
32
-
33
- "Reserved Font Name" refers to any names specified as such after the
34
- copyright statement(s).
35
-
36
- "Original Version" refers to the collection of Font Software components as
37
- distributed by the Copyright Holder(s).
38
-
39
- "Modified Version" refers to any derivative made by adding to, deleting,
40
- or substituting -- in part or in whole -- any of the components of the
41
- Original Version, by changing formats or by porting the Font Software to a
42
- new environment.
43
-
44
- "Author" refers to any designer, engineer, programmer, technical
45
- writer or other person who contributed to the Font Software.
46
-
47
- PERMISSION & CONDITIONS
48
- Permission is hereby granted, free of charge, to any person obtaining
49
- a copy of the Font Software, to use, study, copy, merge, embed, modify,
50
- redistribute, and sell modified and unmodified copies of the Font
51
- Software, subject to the following conditions:
52
-
53
- 1) Neither the Font Software nor any of its individual components,
54
- in Original or Modified Versions, may be sold by itself.
55
-
56
- 2) Original or Modified Versions of the Font Software may be bundled,
57
- redistributed and/or sold with any software, provided that each copy
58
- contains the above copyright notice and this license. These can be
59
- included either as stand-alone text files, human-readable headers or
60
- in the appropriate machine-readable metadata fields within text or
61
- binary files as long as those fields can be easily viewed by the user.
62
-
63
- 3) No Modified Version of the Font Software may use the Reserved Font
64
- Name(s) unless explicit written permission is granted by the corresponding
65
- Copyright Holder. This restriction only applies to the primary font name as
66
- presented to the users.
67
-
68
- 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
69
- Software shall not be used to promote, endorse or advertise any
70
- Modified Version, except to acknowledge the contribution(s) of the
71
- Copyright Holder(s) and the Author(s) or with their explicit written
72
- permission.
73
-
74
- 5) The Font Software, modified or unmodified, in part or in whole,
75
- must be distributed entirely under this license, and must not be
76
- distributed under any other license. The requirement for fonts to
77
- remain under this license does not apply to any document created
78
- using the Font Software.
79
-
80
- TERMINATION
81
- This license becomes null and void if any of the above conditions are
82
- not met.
83
-
84
- DISCLAIMER
85
- THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
86
- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
87
- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
88
- OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
89
- COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
90
- INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
91
- DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
92
- FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
93
- OTHER DEALINGS IN THE FONT SOFTWARE.
@@ -1,89 +0,0 @@
1
- // 纯装饰字符地形;不读取会话数据,也不参与界面交互。
2
- const canvas = document.querySelector('#agent-world');
3
- const context = canvas.getContext('2d');
4
- const reduced = matchMedia('(prefers-reduced-motion: reduce)');
5
- const points = [];
6
- const agents = [];
7
- const heightAt = (x, z) => {
8
- const ridge = Math.sin(x * .16 + Math.cos(z * .13)) * 2.4 + Math.cos(z * .21) * 1.8;
9
- const island = Math.max(0, 1 - Math.hypot(x / 31, z / 26));
10
- return Math.max(-1, Math.floor(island * 9 + ridge - 2));
11
- };
12
- for (let z = -28; z <= 28; z++) {
13
- for (let x = -32; x <= 32; x++) {
14
- const y = heightAt(x, z);
15
- if (x * x / 1100 + z * z / 850 > 1.15) continue;
16
- const path = Math.abs(z - Math.round(Math.sin(x * .12) * 9)) < 1;
17
- points.push({ x, y, z, glyph: y < 0 ? '~' : path ? ':' : y > 5 ? '#' : '+', kind: path ? 'path' : 'land' });
18
- // 用垂直字符层显示台阶断面,保留体素地形的厚度。
19
- const bottom = Math.min(heightAt(x + 1, z), heightAt(x, z + 1));
20
- for (let h = bottom + 1; h < y; h++) points.push({ x, y: h, z, glyph: '|', kind: 'side' });
21
- }
22
- }
23
- for (const [x, z, label] of [[-20, -9, '>_'], [20, 9, '{ }'], [-8, 20, 'git'], [10, -20, '</>'], [-23, 15, '[AI]'], [24, -12, '$']]) {
24
- const base = heightAt(x, z);
25
- for (let y = base + 1; y <= base + 5; y++) points.push({ x, y, z, glyph: y === base + 5 ? '[]' : '|', kind: 'node' });
26
- agents.push({ x, y: base + 7, z, glyph: label, kind: 'node' });
27
- }
28
- let width = 0, height = 0, frame = 0, angle = .65, last = 0;
29
- let dark = false;
30
- function resize() {
31
- width = innerWidth;
32
- height = innerHeight;
33
- const ratio = Math.min(devicePixelRatio || 1, 2);
34
- canvas.width = Math.round(width * ratio);
35
- canvas.height = Math.round(height * ratio);
36
- context.setTransform(ratio, 0, 0, ratio, 0, 0);
37
- draw();
38
- }
39
- function draw() {
40
- if (!context || !width) return;
41
- context.clearRect(0, 0, width, height);
42
- const scale = Math.max(width / 62, height / 42);
43
- const sin = Math.sin(angle), cos = Math.cos(angle);
44
- const project = (point) => {
45
- const x = point.x * cos - point.z * sin;
46
- const depth = point.x * sin + point.z * cos;
47
- return { ...point, sx: width / 2 + x * scale, sy: height * .58 + (depth * .48 - point.y * .95) * scale, depth };
48
- };
49
- const visible = [...points, ...agents].map(project).sort((a, b) => a.depth - b.depth);
50
- const fontSize = Math.max(10, Math.min(14, scale * .52));
51
- context.font = `${fontSize}px ui-monospace, SFMono-Regular, Consolas, monospace`;
52
- context.textAlign = 'center';
53
- // 同一字符格只保留前景点,避免山体投影堆叠成杂乱笔画。
54
- const cells = new Map();
55
- for (const point of visible) cells.set(`${Math.round(point.sx / (fontSize * .7))}:${Math.round(point.sy / fontSize)}`, point);
56
- for (const p of cells.values()) {
57
- if (p.sx < -30 || p.sx > width + 30 || p.sy < -20 || p.sy > height + 20) continue;
58
- const alpha = p.kind === 'node' ? .48 : p.kind === 'path' ? .34 : p.kind === 'side' ? .14 : .22;
59
- context.fillStyle = dark ? `rgba(112,166,245,${alpha})` : `rgba(52,101,174,${alpha})`;
60
- context.fillText(p.glyph, p.sx, p.sy);
61
- }
62
- }
63
- function tick(time) {
64
- if (time - last >= 50) {
65
- if (last) angle = (angle + Math.min(time - last, 100) * Math.PI * 2 / 240000) % (Math.PI * 2);
66
- last = time;
67
- draw();
68
- }
69
- frame = requestAnimationFrame(tick);
70
- }
71
- function syncMotion() {
72
- cancelAnimationFrame(frame);
73
- last = 0;
74
- if (!document.hidden && !reduced.matches) frame = requestAnimationFrame(tick);
75
- else draw();
76
- }
77
- function syncTheme() {
78
- dark = document.documentElement.dataset.theme === 'dark';
79
- draw();
80
- }
81
- new MutationObserver(syncTheme).observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] });
82
- addEventListener('resize', resize);
83
- document.addEventListener('visibilitychange', syncMotion);
84
- reduced.addEventListener('change', syncMotion);
85
- addEventListener('pagehide', () => cancelAnimationFrame(frame));
86
- addEventListener('pageshow', syncMotion);
87
- syncTheme();
88
- resize();
89
- syncMotion();