@mcpc-tech/unplugin-dev-inspector-mcp 0.0.39 → 0.0.41

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -150,7 +150,23 @@ DevInspector.vite({
150
150
  import 'virtual:dev-inspector-mcp'; // ← Add this import
151
151
  ```
152
152
 
153
- **✅ Zero Production Impact:** This import is automatically removed in production builds via tree-shaking. The entire dev-inspector code is wrapped in `if (import.meta.env.DEV)` guards, which bundlers statically replace with `false` during production builds.
153
+ ##### TypeScript Types (Required for `virtual:dev-inspector-mcp`)
154
+
155
+ If you use TypeScript and import `virtual:dev-inspector-mcp`, make sure your TS config includes the plugin client types:
156
+
157
+ ```jsonc
158
+ // tsconfig.json / tsconfig.app.json
159
+ {
160
+ "compilerOptions": {
161
+ "types": [
162
+ "vite/client",
163
+ "@mcpc-tech/unplugin-dev-inspector-mcp/client"
164
+ ]
165
+ }
166
+ }
167
+ ```
168
+
169
+ **✅ Zero Production Impact:** In production builds, `virtual:dev-inspector-mcp` becomes a no-op module. The inspector runtime is guarded by `if (import.meta.env.DEV)`, which bundlers statically replace with `false` during production builds.
154
170
 
155
171
  ##### Custom Virtual Module Name
156
172
 
@@ -6882,7 +6882,7 @@ ${e.themeCSS}`),e.fontFamily!==void 0&&(n+=`
6882
6882
  `)||(e.endsWith("```\n")||e.endsWith("```"))&&t%2==0)return e;let r=e.match(B7t);if(r&&!n){let t=r[2];if(!t||z7.test(t))return e;if(n9t(e)%2==1)return`${e}\``}return e},i9t=e=>{let t=e.match(V7t);if(t){let n=t[2];if(!n||z7.test(n))return e;if((e.match(/~~/g)||[]).length%2==1)return`${e}~~`}return e},a9t=e=>{if((e.match(/\$\$/g)||[]).length%2==0)return e;let t=e.indexOf(`$$`);return t!==-1&&e.indexOf(`
6883
6883
  `,t)!==-1&&!e.endsWith(`
6884
6884
  `)?`${e}
6885
- $$`:`${e}$$`},o9t=e=>{let t=0,n=e.match(/\*+/g)||[];for(let e of n){let n=e.length;n>=3&&(t+=Math.floor(n/3))}return t},s9t=e=>{if(V7(e)||K7t.test(e))return e;let t=e.match(L7t);if(t){let n=t[2];if(!n||z7.test(n))return e;if(o9t(e)%2==1)return`${e}***`}return e},c9t=e=>{if(!e||typeof e!=`string`)return e;let t=e,n=q7t(t);return n.endsWith(`](streamdown:incomplete-link)`)?n:(t=n,t=s9t(t),t=J7t(t),t=Y7t(t),t=Z7t(t),t=e9t(t),t=r9t(t),t=i9t(t),t=a9t(t),t)},l9t={harden:[Qfe,{allowedImagePrefixes:[`*`],allowedLinkPrefixes:[`*`],defaultOrigin:void 0,allowDataImages:!0}],raw:Ebe,katex:[sy,{errorColor:`var(--color-muted-foreground)`}]},u9t={gfm:[GCe,{}],math:[rwe,{singleDollarTextMath:!1}],cjkFriendly:[axe,{}],cjkFriendlyGfmStrikethrough:[sxe,{}]},d9t=(0,_.createContext)([`github-light`,`github-dark`]),f9t=(0,_.createContext)(void 0),p9t=(0,_.createContext)(!0),H7=(0,_.createContext)({isAnimating:!1}),m9t=(0,_.memo)(({content:e,shouldParseIncompleteMarkdown:t,...n})=>{let r=(0,_.useMemo)(()=>typeof e==`string`&&t?c9t(e.trim()):e,[e,t]);return(0,S.jsx)(qfe,{...n,children:r})},(e,t)=>e.content===t.content);m9t.displayName=`Block`;var h9t=[`github-light`,`github-dark`],g9t=(0,_.memo)(({children:e,parseIncompleteMarkdown:t=!0,components:n,rehypePlugins:r=Object.values(l9t),remarkPlugins:i=Object.values(u9t),className:a,shikiTheme:o=h9t,mermaidConfig:s,controls:l=!0,isAnimating:u=!1,urlTransform:d=e=>e,BlockComponent:f=m9t,parseMarkdownIntoBlocksFn:m=N7t,...h})=>{let g=(0,_.useId)(),v=(0,_.useMemo)(()=>m(typeof e==`string`?e:``),[e,m]);(0,_.useEffect)(()=>{Array.isArray(r)&&r.some(e=>Array.isArray(e)?e[0]===sy:e===sy)&&Promise.resolve().then(()=>p(O5t(),1))},[r]);let y=(0,_.useMemo)(()=>({isAnimating:u}),[u]);return(0,S.jsx)(d9t.Provider,{value:o,children:(0,S.jsx)(f9t.Provider,{value:s,children:(0,S.jsx)(p9t.Provider,{value:l,children:(0,S.jsx)(H7.Provider,{value:y,children:(0,S.jsx)(`div`,{className:F7(`space-y-4`,a),children:v.map((e,a)=>(0,S.jsx)(f,{components:{...O7t,...n},content:e,index:a,rehypePlugins:r,remarkPlugins:i,shouldParseIncompleteMarkdown:t,urlTransform:d,...h},`${g}-block-${a}`))})})})})})},(e,t)=>e.children===t.children&&e.shikiTheme===t.shikiTheme&&e.isAnimating===t.isAnimating);g9t.displayName=`Streamdown`;let _9t=(0,_.createContext)(null),v9t=()=>{let e=(0,_.useContext)(_9t);if(!e)throw Error(`Reasoning components must be used within Reasoning`);return e},y9t=(0,_.memo)(({className:e,isStreaming:t=!1,open:n,defaultOpen:r=!0,onOpenChange:i,duration:a,children:o,...s})=>{let[l,u]=Yt({prop:n,defaultProp:r,onChange:i}),[d,f]=Yt({prop:a,defaultProp:void 0}),[p,m]=(0,_.useState)(!1),[h,g]=(0,_.useState)(null);return(0,_.useEffect)(()=>{t?h===null&&g(Date.now()):h!==null&&(f(Math.ceil((Date.now()-h)/1e3)),g(null))},[t,h,f]),(0,_.useEffect)(()=>{if(r&&!t&&l&&!p){let e=setTimeout(()=>{u(!1),m(!0)},1e3);return()=>clearTimeout(e)}},[t,l,r,u,p]),(0,S.jsx)(_9t.Provider,{value:{isStreaming:t,isOpen:l,setIsOpen:u,duration:d},children:(0,S.jsx)(xn,{className:nt(`not-prose mb-4`,e),onOpenChange:e=>{u(e)},open:l,...s,children:o})})}),b9t=(e,t)=>e||t===0?(0,S.jsx)(Foe,{duration:1,children:`Thinking...`}):t===void 0?(0,S.jsx)(`p`,{children:`Thought for a few seconds`}):(0,S.jsxs)(`p`,{children:[`Thought for `,t,` seconds`]}),x9t=(0,_.memo)(({className:e,children:t,...n})=>{let{isStreaming:r,isOpen:i,duration:a}=v9t();return(0,S.jsx)(Sn,{className:nt(`flex w-full items-center gap-2 text-muted-foreground text-sm transition-colors hover:text-foreground`,e),...n,children:t??(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(gt,{className:`size-4`}),b9t(r,a),(0,S.jsx)(_t,{className:nt(`size-4 transition-transform`,i?`rotate-180`:`rotate-0`)})]})})}),S9t=(0,_.memo)(({className:e,children:t,...n})=>(0,S.jsx)(Cn,{className:nt(`mt-4 text-sm`,`data-[state=closed]:fade-out-0 data-[state=closed]:slide-out-to-top-2 data-[state=open]:slide-in-from-top-2 text-muted-foreground outline-none data-[state=closed]:animate-out data-[state=open]:animate-in`,e),...n,children:(0,S.jsx)(g9t,{...n,children:t})}));y9t.displayName=`Reasoning`,x9t.displayName=`ReasoningTrigger`,S9t.displayName=`ReasoningContent`,(0,_.createContext)(null);let C9t=(0,_.memo)(({className:e,...t})=>(0,S.jsx)(g9t,{className:nt(`size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0`,e),...t}),(e,t)=>e.children===t.children);C9t.displayName=`MessageResponse`;let w9t=(0,_.createContext)({code:``}),T9t={name:`line-numbers`,line(e,t){e.children.unshift({type:`element`,tagName:`span`,properties:{className:[`inline-block`,`min-w-10`,`mr-4`,`text-right`,`select-none`,`text-muted-foreground`]},children:[{type:`text`,value:String(t)}]})}};async function E9t(e,t,n=!1){let r=n?[T9t]:[];return await Promise.all([Gqe(e,{lang:t,theme:`one-light`,transformers:r}),Gqe(e,{lang:t,theme:`one-dark-pro`,transformers:r})])}let U7=({code:e,language:t,showLineNumbers:n=!1,className:r,children:i,...a})=>{let[o,s]=(0,_.useState)(``),[l,u]=(0,_.useState)(``),d=(0,_.useRef)(!1);return(0,_.useEffect)(()=>(E9t(e,t,n).then(([e,t])=>{d.current||=(s(e),u(t),!0)}),()=>{d.current=!1}),[e,t,n]),(0,S.jsx)(w9t.Provider,{value:{code:e},children:(0,S.jsx)(`div`,{className:nt(`group relative w-full overflow-hidden rounded-md border bg-background text-foreground`,r),...a,children:(0,S.jsxs)(`div`,{className:`relative`,children:[(0,S.jsx)(`div`,{className:`overflow-x-auto dark:hidden [&>pre]:m-0 [&>pre]:bg-background! [&>pre]:p-4 [&>pre]:text-foreground! [&>pre]:text-sm [&_code]:font-mono [&_code]:text-sm`,dangerouslySetInnerHTML:{__html:o}}),(0,S.jsx)(`div`,{className:`hidden overflow-x-auto dark:block [&>pre]:m-0 [&>pre]:bg-background! [&>pre]:p-4 [&>pre]:text-foreground! [&>pre]:text-sm [&_code]:font-mono [&_code]:text-sm`,dangerouslySetInnerHTML:{__html:l}}),i&&(0,S.jsx)(`div`,{className:`absolute top-2 right-2 flex items-center gap-2`,children:i})]})})})},D9t=({className:e,...t})=>(0,S.jsx)(xn,{className:nt(`not-prose mb-4 w-full rounded-md border`,e),...t}),O9t=e=>{let t={"input-streaming":`Pending`,"input-available":`Running`,"approval-requested":`Awaiting Approval`,"approval-responded":`Responded`,"output-available":`Completed`,"output-error":`Error`,"output-denied":`Denied`};return(0,S.jsxs)(it,{className:`gap-1.5 rounded-full text-xs`,variant:`secondary`,children:[{"input-streaming":(0,S.jsx)(wt,{className:`size-4`}),"input-available":(0,S.jsx)(Tt,{className:`size-4 animate-pulse`}),"approval-requested":(0,S.jsx)(Tt,{className:`size-4 text-yellow-600`}),"approval-responded":(0,S.jsx)(xt,{className:`size-4 text-blue-600`}),"output-available":(0,S.jsx)(xt,{className:`size-4 text-green-600`}),"output-error":(0,S.jsx)(Ct,{className:`size-4 text-red-600`}),"output-denied":(0,S.jsx)(Ct,{className:`size-4 text-orange-600`})}[e],t[e]]})},k9t=({className:e,title:t,type:n,state:r,...i})=>(0,S.jsxs)(Sn,{className:nt(`flex w-full items-center justify-between gap-4 p-3`,e),...i,children:[(0,S.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,S.jsx)(Ft,{className:`size-4 text-muted-foreground`}),(0,S.jsx)(`span`,{className:`font-medium text-sm`,children:t??n.split(`-`).slice(1).join(`-`)}),O9t(r)]}),(0,S.jsx)(_t,{className:`size-4 text-muted-foreground transition-transform group-data-[state=open]:rotate-180`})]}),A9t=({className:e,...t})=>(0,S.jsx)(Cn,{className:nt(`data-[state=closed]:fade-out-0 data-[state=closed]:slide-out-to-top-2 data-[state=open]:slide-in-from-top-2 text-popover-foreground outline-none data-[state=closed]:animate-out data-[state=open]:animate-in`,e),...t}),j9t=({className:e,input:t,...n})=>(0,S.jsxs)(`div`,{className:nt(`space-y-2 overflow-hidden p-4`,e),...n,children:[(0,S.jsx)(`h4`,{className:`font-medium text-muted-foreground text-xs uppercase tracking-wide`,children:`Parameters`}),(0,S.jsx)(`div`,{className:`rounded-md bg-muted/50`,children:(0,S.jsx)(U7,{code:JSON.stringify(t,null,2),language:`json`})})]}),M9t=({className:e,output:t,errorText:n,...r})=>{if(!(t||n))return null;let i=(0,S.jsx)(`div`,{children:t});return typeof t==`object`&&!(0,_.isValidElement)(t)?i=(0,S.jsx)(U7,{code:JSON.stringify(t,null,2),language:`json`}):typeof t==`string`&&(i=(0,S.jsx)(U7,{code:t,language:`json`})),(0,S.jsxs)(`div`,{className:nt(`space-y-2 p-4`,e),...r,children:[(0,S.jsx)(`h4`,{className:`font-medium text-muted-foreground text-xs uppercase tracking-wide`,children:n?`Error`:`Result`}),(0,S.jsxs)(`div`,{className:nt(`overflow-x-auto rounded-md text-xs [&_table]:w-full`,n?`bg-destructive/10 text-destructive`:`bg-muted/50 text-foreground`),children:[n&&(0,S.jsx)(`div`,{children:n}),i]})]})};function N9t({className:e,...t}){return(0,S.jsx)(`div`,{"data-slot":`card`,className:nt(`bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm`,e),...t})}function P9t({className:e,...t}){return(0,S.jsx)(`div`,{"data-slot":`card-header`,className:nt(`@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-2 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6`,e),...t})}function F9t({className:e,...t}){return(0,S.jsx)(`div`,{"data-slot":`card-content`,className:nt(`px-6`,e),...t})}let I9t=(0,_.createContext)(null),L9t=({className:e,isStreaming:t=!1,children:n,...r})=>(0,S.jsx)(I9t.Provider,{value:{isStreaming:t},children:(0,S.jsx)(xn,{asChild:!0,"data-slot":`plan`,...r,children:(0,S.jsx)(N9t,{className:nt(`shadow-none`,e),children:n})})}),R9t=({className:e,...t})=>(0,S.jsx)(P9t,{className:nt(`flex items-start justify-between`,e),"data-slot":`plan-header`,...t}),z9t=e=>(0,S.jsx)(Cn,{asChild:!0,children:(0,S.jsx)(F9t,{"data-slot":`plan-content`,...e})}),B9t=({className:e,...t})=>(0,S.jsx)(Sn,{asChild:!0,children:(0,S.jsxs)(Wt,{className:nt(`size-8`,e),"data-slot":`plan-trigger`,size:`icon`,variant:`ghost`,...t,children:[(0,S.jsx)(yt,{className:`size-4`}),(0,S.jsx)(`span`,{className:`sr-only`,children:`Toggle plan`})]})});function V9t(e){let t=e;return typeof t.type==`string`&&t.type.startsWith(`tool-`)&&`state`in t}function H9t(e,t,n,r,i){if(e.type===`text`&&e.text)return(0,S.jsx)(C9t,{className:`whitespace-pre-wrap`,children:e.text},`${t}-${n}`);if(e.type===`reasoning`)return(0,S.jsxs)(y9t,{className:`w-full`,isStreaming:r,children:[(0,S.jsx)(x9t,{}),(0,S.jsx)(S9t,{children:e.text})]},`${t}-${n}`);let a=i?.plan;if(a&&n===0)return(0,S.jsx)(`div`,{className:`w-full`,children:(0,S.jsxs)(L9t,{defaultOpen:!0,isStreaming:r,children:[(0,S.jsx)(R9t,{className:`flex flex-row items-center`,children:(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(`h1`,{className:`text-base`,children:`Agent Plan`}),(0,S.jsx)(B9t,{className:`mb-2`})]})}),(0,S.jsx)(z9t,{children:(0,S.jsx)(`ul`,{className:`space-y-2`,children:a.map((e,t)=>{let n=e.content||JSON.stringify(e),r=e.priority,i=e.status;return(0,S.jsxs)(`li`,{className:`flex items-start justify-between gap-3`,children:[(0,S.jsxs)(`div`,{className:`flex-1`,children:[(0,S.jsx)(`div`,{className:`text-sm ${i===`done`?`line-through text-muted-foreground`:`text-foreground`}`,children:n}),r&&(0,S.jsxs)(`div`,{className:`mt-1 text-xs text-muted-foreground`,children:[`Priority: `,r]})]}),(0,S.jsx)(`div`,{className:`shrink-0 text-xs`,children:(0,S.jsx)(`span`,{className:`px-2 py-1 rounded-full font-medium text-[10px] uppercase tracking-wide ${i===`pending`?`bg-muted text-muted-foreground`:`bg-primary/10 text-primary`}`,children:i??`pending`})})]},`plan-${t}`)})})})]})},`${t}-plan`);if(V9t(e)){let r=e=>(e=e.replace(`acp-ai-sdk-tools`,``),e),i=e.input;if(!i||!i.toolName)return null;let a=r(i.toolName),o=e.state,s=o===`output-available`||o===`output-error`;return(0,S.jsxs)(D9t,{defaultOpen:s,children:[(0,S.jsx)(k9t,{title:r(a.length>20?`${a.slice(0,20)}...`:a),type:a,state:o}),(0,S.jsxs)(A9t,{children:[e.input!==void 0&&(0,S.jsx)(j9t,{input:i.args}),s&&(0,S.jsx)(M9t,{output:e.output?(0,S.jsx)(U7,{code:JSON.stringify(e.output,null,2),language:`json`}):null,errorText:e.errorText})]})]},`${t}-${n}`)}return null}let U9t=({messages:e,status:t,selectedAgent:n})=>{let r=Ac.find(e=>e.name===(n||jc))||Ac[0],i=t===`submitted`||t===`streaming`,a=e[e.length-1],o=i&&(!a||a.role===`user`);return(0,S.jsxs)(qoe,{className:`w-full h-full`,children:[(0,S.jsx)(Joe,{className:`p-3 space-y-3`,children:e.length===0&&!i?(0,S.jsx)(`div`,{className:`flex items-center justify-center h-full text-muted-foreground`,children:(0,S.jsxs)(`div`,{className:`text-center`,children:[(0,S.jsx)(`p`,{className:`text-sm`,children:`No messages yet`}),(0,S.jsx)(`p`,{className:`text-xs mt-1`,children:`Enter a question below to start`})]})}):(0,S.jsxs)(S.Fragment,{children:[e.map(e=>(0,S.jsxs)(kse,{className:`items-start`,from:e.role,children:[(0,S.jsx)(Ase,{children:e.parts.map((n,r)=>H9t(n,e.id,r,t===`streaming`,e.metadata))}),e.role===`assistant`&&(0,S.jsx)(jse,{name:r.name,src:r.meta?.icon??``})]},e.id)),o&&(0,S.jsxs)(kse,{className:`items-start`,from:`assistant`,children:[(0,S.jsx)(Ase,{children:(0,S.jsx)(Nse,{size:16})}),(0,S.jsx)(jse,{name:r.name,src:r.meta?.icon??``})]})]})}),(0,S.jsx)(Yoe,{})]})};function W9t(e,t,n=50){let[r,i]=(0,_.useState)(``),a=(0,_.useRef)(0),o=(0,_.useRef)(``);return(0,_.useEffect)(()=>{if(e.length<r.length||r&&!e.startsWith(r.slice(0,Math.min(r.length,20)))){i(e),o.current=e,a.current=Date.now();return}if(!t){r!==e&&(i(e),o.current=e);return}let s=e.slice(o.current.length);if(!s)return;let l=Date.now();if(l-a.current<n)return;let u=/[.?!。?!](\s|$)|[\n]/.test(s),d=s.length>50,f=s.trim().length<5;(u&&!f||d)&&(i(e),o.current=e,a.current=l)},[e,t,n,r]),r}function G9t({initialOffset:e={x:0,y:0}}={}){let t=(0,_.useRef)(null),[n,r]=(0,_.useState)(!1),i=(0,_.useRef)(e),a=(0,_.useRef)({x:0,y:0}),o=(0,_.useRef)({x:0,y:0}),s=(0,_.useCallback)(()=>{if(t.current){let{x:e,y:n}=i.current;t.current.style.transform=`translate3d(calc(-50% + ${e}px), ${n}px, 0)`}},[]),l=(0,_.useCallback)(e=>{e.target.closest(`button, input, a, [data-no-drag]`)||(e.preventDefault(),r(!0),a.current={x:e.clientX,y:e.clientY},o.current={...i.current})},[]);return(0,_.useEffect)(()=>{let e=e=>{if(!n)return;let t=e.clientX-a.current.x,r=e.clientY-a.current.y;i.current={x:o.current.x+t,y:o.current.y+r},s()},t=()=>{r(!1)};return n&&(window.addEventListener(`mousemove`,e,{passive:!0}),window.addEventListener(`mouseup`,t)),()=>{window.removeEventListener(`mousemove`,e),window.removeEventListener(`mouseup`,t)}},[n,s]),(0,_.useEffect)(()=>{s()},[s]),{elementRef:t,isDragging:n,handleMouseDown:l}}let K9t=`AI_SELECTED_AGENT`,q9t=e=>{let[t,n]=(0,_.useState)(()=>{if(typeof window<`u`){let e=localStorage.getItem(K9t);if(e)return e}return e}),[r,i]=(0,_.useState)(!1);return(0,_.useEffect)(()=>{typeof window<`u`?Lc().then(e=>{e&&e!==jc&&n(e)}).finally(()=>{i(!0)}):i(!0)},[]),{agent:t,setAgent:e=>{n(e),!(typeof window>`u`)&&(e?.trim()?localStorage.setItem(K9t,e):localStorage.removeItem(K9t))},isReady:r}},J9t=({isActive:e,onToggleInspector:t,onSubmitAgent:n,onCancel:r,isAgentWorking:i,messages:a,status:o,inspectionCount:s=0,inspectionItems:l=[],onRemoveInspection:u=()=>{},toolsReady:d=!0})=>{let[f,p]=(0,_.useState)(!1),[m,h]=(0,_.useState)(``),[g,v]=(0,_.useState)(null),[y,b]=(0,_.useState)(`none`),[x,C]=(0,_.useState)(!1),[w,T]=(0,_.useState)(!1),[E,D]=(0,_.useState)(!0),{agent:O,setAgent:k,isReady:A}=q9t(jc),[j,M]=(0,_.useState)(!1),[N,P]=(0,_.useState)(null),[F,I]=(0,_.useState)(null),L=(0,_.useRef)(null);(0,_.useEffect)(()=>{if(!A||!d)return;let e=!0,t=Ac.find(e=>e.name===O)||Ac[0];return(async()=>{if(L.current){try{await fetch(`${Pc()}/api/acp/cleanup-session`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({sessionId:L.current})})}catch(e){console.warn(`[InspectorBar] Failed to cleanup previous session:`,e)}L.current=null,e&&I(null)}console.log(`[InspectorBar] Initializing session for ${t.name}...`);try{let n=await fetch(`${Pc()}/api/acp/init-session`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({agent:t,envVars:{}})});if(!n.ok)throw Error(`Failed to init session`);let r=await n.json();e&&r.sessionId&&(console.log(`[InspectorBar] Session initialized: ${r.sessionId}`),I(r.sessionId),L.current=r.sessionId)}catch(e){console.error(`[InspectorBar] Failed to initialize session:`,e)}})(),()=>{e=!1}},[O,A,d]),(0,_.useEffect)(()=>()=>{L.current&&(console.log(`[InspectorBar] Cleaning up session on unmount: ${L.current}`),fetch(`${Pc()}/api/acp/cleanup-session`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({sessionId:L.current}),keepalive:!0}).catch(e=>console.warn(`[InspectorBar] Failed to cleanup session:`,e)))},[]);let R=Ac.find(e=>e.name===O)||Ac[0],{elementRef:ee,isDragging:te,handleMouseDown:z}=G9t(),[B,ne]=(0,_.useState)(null),[re,ie]=(0,_.useState)(``),ae=W9t(re,i,50),[oe,se]=(0,_.useState)(``),ce=(0,_.useRef)(``),le=(0,_.useRef)(``);(0,_.useEffect)(()=>{let e=ae,t=ce.current;if(e.length<t.length||!e.startsWith(t)){se(e),ce.current=e;return}if(e.length>t.length){let n=e.slice(t.length).trim();n&&se(n),ce.current=e}},[ae]);let ue=(0,_.useRef)(null),de=(0,_.useRef)(null),fe=(0,_.useRef)(null),pe=(0,_.useRef)(!1);(0,_.useEffect)(()=>{if(a.length===0){ie(``),v(null),fe.current=null,pe.current=!1,se(``),ce.current=``;return}let e=a[a.length-1];if(e.role!==`assistant`)return;let t=Roe(e),{displayText:n,toolCall:r}=Boe(e,t||fe.current);ie(n||``),t&&(fe.current=t),r?(de.current&&=(clearTimeout(de.current),null),v(r),pe.current=!0):pe.current=!1},[a]),(0,_.useEffect)(()=>{oe!==le.current&&(pe.current||v(null),le.current=oe)},[oe]),(0,_.useEffect)(()=>{f&&ue.current&&ue.current.focus()},[f]),(0,_.useEffect)(()=>{if(!i&&w){C(!1),T(!1),D(!1);let e=setTimeout(()=>{D(!0)},2e3);return()=>clearTimeout(e)}},[i,w]),(0,_.useEffect)(()=>{function e(e){let{plan:t,inspectionId:n}=e.detail;if(t?.steps){let e=t.steps.find(e=>e.status===`in-progress`),r=t.steps.filter(e=>e.status===`completed`).length;ne({id:n,status:`in-progress`,currentStep:e?{title:e.title,index:r+1,total:t.steps.length}:void 0})}}function t(e){let{status:t,result:n,inspectionId:r}=e.detail;ne({id:r,status:t,message:n?.message||n})}return window.addEventListener(`plan-progress-reported`,e),window.addEventListener(`inspection-result-received`,t),()=>{window.removeEventListener(`plan-progress-reported`,e),window.removeEventListener(`inspection-result-received`,t)}},[]);let me=e=>{e.preventDefault(),m.trim()&&(de.current&&=(clearTimeout(de.current),null),v(null),ie(``),se(``),ne(null),fe.current=null,ce.current=``,C(!0),T(!0),n(m,O,F||void 0),h(``),p(!0),b(`chat`))},he=e=>{e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),me(e)),e.key===`Escape`&&(p(!1),ue.current?.blur())},ge=o===`error`,_e=a.length>0,ve=f&&!x,ye=(!f||x)&&(i||_e||B);return(0,S.jsxs)(S.Fragment,{children:[(f||y!==`none`)&&(0,S.jsx)(`div`,{className:`fixed inset-0 z-[999998] bg-transparent`,onClick:()=>{!w&&!i&&(p(!1),b(`none`))}}),(0,S.jsxs)(`div`,{ref:ee,className:nt(`fixed bottom-8 left-1/2 z-[999999]`,`transition-all duration-300 ease-[cubic-bezier(0.23,1,0.32,1)]`,f?`w-[480px]`:ye?`w-auto min-w-[200px] max-w-[480px]`:`w-[190px]`,te?`cursor-grabbing`:`cursor-grab`),onMouseDown:z,onMouseEnter:()=>{te||(i||w?(p(!0),b(`chat`)):E&&p(!0))},onMouseLeave:()=>{!m.trim()&&!w&&!te&&(p(!1),b(`none`)),D(!0)},children:[(0,S.jsxs)(`div`,{className:nt(`relative flex items-center backdrop-blur-xl shadow-2xl border border-border`,`transition-[width,height,padding,background-color,border-color] duration-200 ease-out`,f?`h-12 p-2 pl-4`:`h-9 px-2 py-1`,y===`none`?`bg-muted/90 rounded-full`:`bg-muted/95 rounded-b-lg rounded-t-none border-t-0`,ge&&!f&&`bg-destructive/10 border-destructive/20`),children:[(0,S.jsxs)(`div`,{className:nt(`flex items-center transition-opacity duration-300 w-full relative`,ve?`absolute left-3 opacity-0 pointer-events-none`:`relative opacity-100`),children:[!ye&&(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(`div`,{className:`flex items-center justify-center w-6 h-6 rounded-full bg-accent flex-shrink-0`,children:(0,S.jsx)(Mt,{className:`w-3.5 h-3.5 text-foreground`})}),(0,S.jsx)(`span`,{className:`text-xs text-muted-foreground/70 ml-3 whitespace-nowrap`,children:`⌥I or hover to inspect`})]}),ye&&(0,S.jsxs)(S.Fragment,{children:[(0,S.jsxs)(`div`,{className:`flex items-center gap-3 flex-shrink-0`,children:[(0,S.jsx)(`div`,{className:`relative flex items-center justify-center w-6 h-6 rounded-full bg-accent flex-shrink-0`,children:i?(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(`div`,{className:`absolute inset-0 rounded-full border-2 border-current opacity-20 animate-ping text-foreground`}),(0,S.jsx)(Mt,{className:`w-3.5 h-3.5 animate-pulse text-foreground`})]}):B?B.status===`in-progress`?(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(`div`,{className:`absolute inset-0 rounded-full border-2 border-current opacity-20 animate-ping text-blue-500`}),(0,S.jsx)(Nt,{className:`w-3.5 h-3.5 animate-pulse text-blue-500`})]}):B.status===`completed`?(0,S.jsx)(St,{className:`w-5 h-5 text-green-500`}):(0,S.jsx)(Ct,{className:`w-5 h-5 text-red-500`}):ge?(0,S.jsx)(Ct,{className:`w-5 h-5 text-red-500`}):(0,S.jsx)(St,{className:`w-5 h-5 text-green-500`})}),(0,S.jsx)(`div`,{className:`w-px h-4 bg-border flex-shrink-0`})]}),(0,S.jsx)(`div`,{className:`flex-1 flex justify-center min-w-0 pl-2`,children:(0,S.jsx)(`div`,{className:`flex flex-col min-w-0 max-w-full pr-2 max-h-[24px] overflow-hidden`,children:B&&B.status===`in-progress`&&B.currentStep?(0,S.jsxs)(`div`,{className:`flex items-center gap-1.5 text-sm font-medium text-foreground min-w-0`,children:[(0,S.jsx)(Nt,{className:`w-4 h-4 flex-shrink-0`}),(0,S.jsxs)(`span`,{className:`truncate min-w-0`,children:[`Step `,B.currentStep.index,`/`,B.currentStep.total,`: `,B.currentStep.title]})]}):B?.message?(0,S.jsx)(`div`,{className:`text-sm font-medium leading-[1.4] text-foreground truncate min-w-0`,children:B.message}):g?(0,S.jsxs)(`div`,{className:`flex items-center gap-1.5 text-sm font-medium text-foreground min-w-0`,children:[(0,S.jsx)(Nt,{className:`w-4 h-4 flex-shrink-0`}),(0,S.jsx)(`span`,{className:`truncate min-w-0`,children:g})]}):(0,S.jsx)(`div`,{className:`text-sm font-medium leading-[1.4] text-foreground truncate min-w-0`,children:i&&!oe?(0,S.jsx)(Foe,{duration:2,spread:2,children:o===`submitted`&&R?.command===`npx`?`Starting ${R.name}... This may take a moment.`:`Thinking...`}):oe||`Processing...`})})})]})]}),(0,S.jsxs)(`div`,{className:nt(`flex items-center w-full gap-3 transition-all duration-500 delay-75`,ve?`opacity-100 translate-y-0 relative pointer-events-auto`:`opacity-0 translate-y-4 pointer-events-none absolute top-2 left-4 right-2`),onClick:e=>e.stopPropagation(),children:[(0,S.jsx)(`button`,{onClick:t,className:nt(`relative flex items-center justify-center w-7 h-7 rounded-full transition-colors flex-shrink-0`,e?`bg-blue-500 text-white shadow-[0_0_15px_rgba(59,130,246,0.5)]`:`bg-accent text-muted-foreground hover:bg-accent/80 hover:text-foreground`),title:`Toggle Inspector (⌥I)`,children:(0,S.jsx)(Et,{className:`w-3.5 h-3.5`})}),(0,S.jsx)(`div`,{className:`w-px h-4 bg-border flex-shrink-0`}),s>0&&(0,S.jsxs)(S.Fragment,{children:[(0,S.jsxs)(`button`,{type:`button`,onClick:()=>b(e=>e===`inspections`?`none`:`inspections`),className:nt(`relative flex items-center justify-center w-7 h-7 rounded-full transition-colors flex-shrink-0`,`hover:bg-accent/50`,y===`inspections`&&`bg-accent/50 text-foreground`),title:`View Inspections`,children:[(0,S.jsx)(Dt,{className:`w-3.5 h-3.5`}),(0,S.jsx)(`span`,{className:`absolute -top-0.5 -right-0.5 flex items-center justify-center min-w-[12px] h-[12px] px-0.5 text-[8px] font-bold text-white bg-red-500 rounded-full border border-background shadow-sm leading-none`,children:s>99?`99+`:s})]}),(0,S.jsx)(`div`,{className:`w-px h-4 bg-border flex-shrink-0`})]}),(0,S.jsxs)(`form`,{onSubmit:me,className:`flex-1 flex items-center gap-2 min-w-0`,onClick:e=>e.stopPropagation(),children:[(0,S.jsxs)(`div`,{className:`relative flex-shrink-0`,children:[(0,S.jsx)(`button`,{type:`button`,onClick:()=>M(!j),className:`flex items-center justify-center w-7 h-7 rounded-full hover:bg-accent/50 transition-colors`,title:`Select Agent`,children:(0,S.jsx)(`img`,{src:Ac.find(e=>e.name===O)?.meta?.icon,alt:O,className:`w-3.5 h-3.5`})}),j&&(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(`div`,{className:`fixed inset-0 z-[999998]`,onClick:()=>M(!1)}),(0,S.jsx)(`div`,{className:`absolute bottom-full left-0 mb-2 w-64 bg-popover border border-border rounded-lg shadow-lg overflow-hidden z-[999999] animate-in fade-in zoom-in-95 duration-200`,children:Ac.map(e=>(0,S.jsxs)(`div`,{className:nt(`w-full flex items-center gap-2 px-3 py-2 text-sm hover:bg-accent transition-colors group`,O===e.name&&`bg-accent/50 font-medium`),children:[(0,S.jsxs)(`button`,{onClick:()=>{k(e.name),M(!1)},className:`flex items-center gap-2 flex-1 text-left`,children:[e.meta?.icon&&(0,S.jsx)(`img`,{src:e.meta.icon,alt:``,className:`w-4 h-4 flex-shrink-0`}),(0,S.jsx)(`span`,{className:`flex-1`,children:e.name})]}),(e.configHint||e.configLink)&&(0,S.jsx)(`button`,{onClick:t=>{t.stopPropagation(),P(e.name)},className:`p-1 rounded hover:bg-accent-foreground/10 transition-colors`,title:`Configuration info`,children:(0,S.jsx)(Ot,{className:`w-3.5 h-3.5 text-muted-foreground`})})]},e.name))})]})]}),(0,S.jsx)(`input`,{ref:ue,type:`text`,value:m,onChange:e=>h(e.target.value),onKeyDown:he,placeholder:`Ask ${O}...`,className:`w-full bg-transparent border-none outline-none text-foreground placeholder-muted-foreground text-sm h-7 disabled:opacity-50`,tabIndex:0,disabled:i}),(a.length>0||i||w)&&(0,S.jsx)(`button`,{type:`button`,onClick:()=>b(e=>e===`chat`?`none`:`chat`),className:nt(`flex items-center justify-center w-7 h-7 rounded-full transition-all flex-shrink-0`,y===`chat`?`bg-foreground text-background`:`bg-accent text-muted-foreground hover:bg-accent/80 hover:text-foreground`),title:y===`chat`?`Collapse`:`Expand messages`,children:(0,S.jsx)(vt,{className:nt(`w-3.5 h-3.5 transition-transform duration-300`,y===`chat`&&`rotate-180`)})}),i?(0,S.jsx)(`button`,{type:`button`,onClick:r,className:`flex items-center justify-center w-7 h-7 rounded-full bg-destructive text-destructive-foreground transition-all flex-shrink-0 hover:bg-destructive/90`,title:`Cancel request`,children:(0,S.jsx)(tee,{className:`w-3 h-3`})}):(0,S.jsx)(`button`,{type:`submit`,disabled:!m.trim(),className:nt(`flex items-center justify-center w-7 h-7 rounded-full transition-all flex-shrink-0`,m.trim()?`bg-foreground text-background scale-100`:`bg-accent text-muted-foreground/50 scale-90`),children:(0,S.jsx)(ht,{className:`w-3.5 h-3.5`})})]})]})]}),y!==`none`&&(0,S.jsx)(`div`,{className:`absolute bottom-full left-0 right-0 pointer-events-auto max-w-[480px] mx-auto animate-panel-in`,children:(0,S.jsxs)(`div`,{className:`bg-muted/95 backdrop-blur-xl rounded-t-xl border border-border border-b-0 shadow-2xl overflow-hidden`,children:[y===`inspections`&&l.length>0&&(0,S.jsx)(`div`,{className:`border-b border-border`,children:(0,S.jsx)(pee,{items:l,onRemove:u})}),y===`chat`&&(0,S.jsx)(`div`,{className:`h-[500px]`,children:(0,S.jsx)(U9t,{messages:a,status:o,selectedAgent:O})})]})})]}),N&&(()=>{let e=Ac.find(e=>e.name===N);return e?(0,S.jsx)(Lt,{open:!!N,onOpenChange:()=>P(null),children:(0,S.jsxs)(Rt,{onClose:()=>P(null),className:`w-80`,children:[(0,S.jsxs)(zt,{children:[(0,S.jsxs)(nee,{className:`flex items-center gap-3`,children:[e.meta?.icon&&(0,S.jsx)(`img`,{src:e.meta.icon,alt:``,className:`w-6 h-6`}),e.name]}),e.configHint&&(0,S.jsx)(Vt,{children:e.configHint})]}),e.configLink&&(0,S.jsx)(`a`,{href:e.configLink,target:`_blank`,rel:`noopener noreferrer`,className:`inline-flex items-center gap-1 text-sm text-blue-500 hover:text-blue-600 underline`,children:`View ACP Documentation →`})]})}):null})()]})};var Y9t=`vercel.ai.error`,X9t=Symbol.for(Y9t),Z9t,Q9t=class e extends Error{constructor({name:e,message:t,cause:n}){super(t),this[Z9t]=!0,this.name=e,this.cause=n}static isInstance(t){return e.hasMarker(t,Y9t)}static hasMarker(e,t){let n=Symbol.for(t);return typeof e==`object`&&!!e&&n in e&&typeof e[n]==`boolean`&&e[n]===!0}};Z9t=X9t;var W7=Q9t;function $9t(e){return e==null?`unknown error`:typeof e==`string`?e:e instanceof Error?e.message:JSON.stringify(e)}var een=`AI_InvalidArgumentError`,ten=`vercel.ai.error.${een}`,nen=Symbol.for(ten),ren,ien=class extends W7{constructor({message:e,cause:t,argument:n}){super({name:een,message:e,cause:t}),this[ren]=!0,this.argument=n}static isInstance(e){return W7.hasMarker(e,ten)}};ren=nen;var aen=`AI_JSONParseError`,oen=`vercel.ai.error.${aen}`,sen=Symbol.for(oen),cen,len=class extends W7{constructor({text:e,cause:t}){super({name:aen,message:`JSON parsing failed: Text: ${e}.
6885
+ $$`:`${e}$$`},o9t=e=>{let t=0,n=e.match(/\*+/g)||[];for(let e of n){let n=e.length;n>=3&&(t+=Math.floor(n/3))}return t},s9t=e=>{if(V7(e)||K7t.test(e))return e;let t=e.match(L7t);if(t){let n=t[2];if(!n||z7.test(n))return e;if(o9t(e)%2==1)return`${e}***`}return e},c9t=e=>{if(!e||typeof e!=`string`)return e;let t=e,n=q7t(t);return n.endsWith(`](streamdown:incomplete-link)`)?n:(t=n,t=s9t(t),t=J7t(t),t=Y7t(t),t=Z7t(t),t=e9t(t),t=r9t(t),t=i9t(t),t=a9t(t),t)},l9t={harden:[Qfe,{allowedImagePrefixes:[`*`],allowedLinkPrefixes:[`*`],defaultOrigin:void 0,allowDataImages:!0}],raw:Ebe,katex:[sy,{errorColor:`var(--color-muted-foreground)`}]},u9t={gfm:[GCe,{}],math:[rwe,{singleDollarTextMath:!1}],cjkFriendly:[axe,{}],cjkFriendlyGfmStrikethrough:[sxe,{}]},d9t=(0,_.createContext)([`github-light`,`github-dark`]),f9t=(0,_.createContext)(void 0),p9t=(0,_.createContext)(!0),H7=(0,_.createContext)({isAnimating:!1}),m9t=(0,_.memo)(({content:e,shouldParseIncompleteMarkdown:t,...n})=>{let r=(0,_.useMemo)(()=>typeof e==`string`&&t?c9t(e.trim()):e,[e,t]);return(0,S.jsx)(qfe,{...n,children:r})},(e,t)=>e.content===t.content);m9t.displayName=`Block`;var h9t=[`github-light`,`github-dark`],g9t=(0,_.memo)(({children:e,parseIncompleteMarkdown:t=!0,components:n,rehypePlugins:r=Object.values(l9t),remarkPlugins:i=Object.values(u9t),className:a,shikiTheme:o=h9t,mermaidConfig:s,controls:l=!0,isAnimating:u=!1,urlTransform:d=e=>e,BlockComponent:f=m9t,parseMarkdownIntoBlocksFn:m=N7t,...h})=>{let g=(0,_.useId)(),v=(0,_.useMemo)(()=>m(typeof e==`string`?e:``),[e,m]);(0,_.useEffect)(()=>{Array.isArray(r)&&r.some(e=>Array.isArray(e)?e[0]===sy:e===sy)&&Promise.resolve().then(()=>p(O5t(),1))},[r]);let y=(0,_.useMemo)(()=>({isAnimating:u}),[u]);return(0,S.jsx)(d9t.Provider,{value:o,children:(0,S.jsx)(f9t.Provider,{value:s,children:(0,S.jsx)(p9t.Provider,{value:l,children:(0,S.jsx)(H7.Provider,{value:y,children:(0,S.jsx)(`div`,{className:F7(`space-y-4`,a),children:v.map((e,a)=>(0,S.jsx)(f,{components:{...O7t,...n},content:e,index:a,rehypePlugins:r,remarkPlugins:i,shouldParseIncompleteMarkdown:t,urlTransform:d,...h},`${g}-block-${a}`))})})})})})},(e,t)=>e.children===t.children&&e.shikiTheme===t.shikiTheme&&e.isAnimating===t.isAnimating);g9t.displayName=`Streamdown`;let _9t=(0,_.createContext)(null),v9t=()=>{let e=(0,_.useContext)(_9t);if(!e)throw Error(`Reasoning components must be used within Reasoning`);return e},y9t=(0,_.memo)(({className:e,isStreaming:t=!1,open:n,defaultOpen:r=!0,onOpenChange:i,duration:a,children:o,...s})=>{let[l,u]=Yt({prop:n,defaultProp:r,onChange:i}),[d,f]=Yt({prop:a,defaultProp:void 0}),[p,m]=(0,_.useState)(!1),[h,g]=(0,_.useState)(null);return(0,_.useEffect)(()=>{t?h===null&&g(Date.now()):h!==null&&(f(Math.ceil((Date.now()-h)/1e3)),g(null))},[t,h,f]),(0,_.useEffect)(()=>{if(r&&!t&&l&&!p){let e=setTimeout(()=>{u(!1),m(!0)},1e3);return()=>clearTimeout(e)}},[t,l,r,u,p]),(0,S.jsx)(_9t.Provider,{value:{isStreaming:t,isOpen:l,setIsOpen:u,duration:d},children:(0,S.jsx)(xn,{className:nt(`not-prose mb-4`,e),onOpenChange:e=>{u(e)},open:l,...s,children:o})})}),b9t=(e,t)=>e||t===0?(0,S.jsx)(Foe,{duration:1,children:`Thinking...`}):t===void 0?(0,S.jsx)(`p`,{children:`Thought for a few seconds`}):(0,S.jsxs)(`p`,{children:[`Thought for `,t,` seconds`]}),x9t=(0,_.memo)(({className:e,children:t,...n})=>{let{isStreaming:r,isOpen:i,duration:a}=v9t();return(0,S.jsx)(Sn,{className:nt(`flex w-full items-center gap-2 text-muted-foreground text-sm transition-colors hover:text-foreground`,e),...n,children:t??(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(gt,{className:`size-4`}),b9t(r,a),(0,S.jsx)(_t,{className:nt(`size-4 transition-transform`,i?`rotate-180`:`rotate-0`)})]})})}),S9t=(0,_.memo)(({className:e,children:t,...n})=>(0,S.jsx)(Cn,{className:nt(`mt-4 text-sm`,`data-[state=closed]:fade-out-0 data-[state=closed]:slide-out-to-top-2 data-[state=open]:slide-in-from-top-2 text-muted-foreground outline-none data-[state=closed]:animate-out data-[state=open]:animate-in`,e),...n,children:(0,S.jsx)(g9t,{...n,children:t})}));y9t.displayName=`Reasoning`,x9t.displayName=`ReasoningTrigger`,S9t.displayName=`ReasoningContent`,(0,_.createContext)(null);let C9t=(0,_.memo)(({className:e,...t})=>(0,S.jsx)(g9t,{className:nt(`size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0`,e),...t}),(e,t)=>e.children===t.children);C9t.displayName=`MessageResponse`;let w9t=(0,_.createContext)({code:``}),T9t={name:`line-numbers`,line(e,t){e.children.unshift({type:`element`,tagName:`span`,properties:{className:[`inline-block`,`min-w-10`,`mr-4`,`text-right`,`select-none`,`text-muted-foreground`]},children:[{type:`text`,value:String(t)}]})}};async function E9t(e,t,n=!1){let r=n?[T9t]:[];return await Promise.all([Gqe(e,{lang:t,theme:`one-light`,transformers:r}),Gqe(e,{lang:t,theme:`one-dark-pro`,transformers:r})])}let U7=({code:e,language:t,showLineNumbers:n=!1,className:r,children:i,...a})=>{let[o,s]=(0,_.useState)(``),[l,u]=(0,_.useState)(``),d=(0,_.useRef)(!1);return(0,_.useEffect)(()=>(E9t(e,t,n).then(([e,t])=>{d.current||=(s(e),u(t),!0)}),()=>{d.current=!1}),[e,t,n]),(0,S.jsx)(w9t.Provider,{value:{code:e},children:(0,S.jsx)(`div`,{className:nt(`group relative w-full overflow-hidden rounded-md border bg-background text-foreground`,r),...a,children:(0,S.jsxs)(`div`,{className:`relative`,children:[(0,S.jsx)(`div`,{className:`overflow-x-auto dark:hidden [&>pre]:m-0 [&>pre]:bg-background! [&>pre]:p-4 [&>pre]:text-foreground! [&>pre]:text-sm [&_code]:font-mono [&_code]:text-sm`,dangerouslySetInnerHTML:{__html:o}}),(0,S.jsx)(`div`,{className:`hidden overflow-x-auto dark:block [&>pre]:m-0 [&>pre]:bg-background! [&>pre]:p-4 [&>pre]:text-foreground! [&>pre]:text-sm [&_code]:font-mono [&_code]:text-sm`,dangerouslySetInnerHTML:{__html:l}}),i&&(0,S.jsx)(`div`,{className:`absolute top-2 right-2 flex items-center gap-2`,children:i})]})})})},D9t=({className:e,...t})=>(0,S.jsx)(xn,{className:nt(`not-prose mb-4 w-full rounded-md border`,e),...t}),O9t=e=>{let t={"input-streaming":`Pending`,"input-available":`Running`,"approval-requested":`Awaiting Approval`,"approval-responded":`Responded`,"output-available":`Completed`,"output-error":`Error`,"output-denied":`Denied`};return(0,S.jsxs)(it,{className:`gap-1.5 rounded-full text-xs`,variant:`secondary`,children:[{"input-streaming":(0,S.jsx)(wt,{className:`size-4`}),"input-available":(0,S.jsx)(Tt,{className:`size-4 animate-pulse`}),"approval-requested":(0,S.jsx)(Tt,{className:`size-4 text-yellow-600`}),"approval-responded":(0,S.jsx)(xt,{className:`size-4 text-blue-600`}),"output-available":(0,S.jsx)(xt,{className:`size-4 text-green-600`}),"output-error":(0,S.jsx)(Ct,{className:`size-4 text-red-600`}),"output-denied":(0,S.jsx)(Ct,{className:`size-4 text-orange-600`})}[e],t[e]]})},k9t=({className:e,title:t,type:n,state:r,...i})=>(0,S.jsxs)(Sn,{className:nt(`flex w-full items-center justify-between gap-4 p-3`,e),...i,children:[(0,S.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,S.jsx)(Ft,{className:`size-4 text-muted-foreground`}),(0,S.jsx)(`span`,{className:`font-medium text-sm`,children:t??n.split(`-`).slice(1).join(`-`)}),O9t(r)]}),(0,S.jsx)(_t,{className:`size-4 text-muted-foreground transition-transform group-data-[state=open]:rotate-180`})]}),A9t=({className:e,...t})=>(0,S.jsx)(Cn,{className:nt(`data-[state=closed]:fade-out-0 data-[state=closed]:slide-out-to-top-2 data-[state=open]:slide-in-from-top-2 text-popover-foreground outline-none data-[state=closed]:animate-out data-[state=open]:animate-in`,e),...t}),j9t=({className:e,input:t,...n})=>(0,S.jsxs)(`div`,{className:nt(`space-y-2 overflow-hidden p-4`,e),...n,children:[(0,S.jsx)(`h4`,{className:`font-medium text-muted-foreground text-xs uppercase tracking-wide`,children:`Parameters`}),(0,S.jsx)(`div`,{className:`rounded-md bg-muted/50`,children:(0,S.jsx)(U7,{code:JSON.stringify(t,null,2),language:`json`})})]}),M9t=({className:e,output:t,errorText:n,...r})=>{if(!(t||n))return null;let i=(0,S.jsx)(`div`,{children:t});return typeof t==`object`&&!(0,_.isValidElement)(t)?i=(0,S.jsx)(U7,{code:JSON.stringify(t,null,2),language:`json`}):typeof t==`string`&&(i=(0,S.jsx)(U7,{code:t,language:`json`})),(0,S.jsxs)(`div`,{className:nt(`space-y-2 p-4`,e),...r,children:[(0,S.jsx)(`h4`,{className:`font-medium text-muted-foreground text-xs uppercase tracking-wide`,children:n?`Error`:`Result`}),(0,S.jsxs)(`div`,{className:nt(`overflow-x-auto rounded-md text-xs [&_table]:w-full`,n?`bg-destructive/10 text-destructive`:`bg-muted/50 text-foreground`),children:[n&&(0,S.jsx)(`div`,{children:n}),i]})]})};function N9t({className:e,...t}){return(0,S.jsx)(`div`,{"data-slot":`card`,className:nt(`bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm`,e),...t})}function P9t({className:e,...t}){return(0,S.jsx)(`div`,{"data-slot":`card-header`,className:nt(`@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-2 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6`,e),...t})}function F9t({className:e,...t}){return(0,S.jsx)(`div`,{"data-slot":`card-content`,className:nt(`px-6`,e),...t})}let I9t=(0,_.createContext)(null),L9t=({className:e,isStreaming:t=!1,children:n,...r})=>(0,S.jsx)(I9t.Provider,{value:{isStreaming:t},children:(0,S.jsx)(xn,{asChild:!0,"data-slot":`plan`,...r,children:(0,S.jsx)(N9t,{className:nt(`shadow-none`,e),children:n})})}),R9t=({className:e,...t})=>(0,S.jsx)(P9t,{className:nt(`flex items-start justify-between`,e),"data-slot":`plan-header`,...t}),z9t=e=>(0,S.jsx)(Cn,{asChild:!0,children:(0,S.jsx)(F9t,{"data-slot":`plan-content`,...e})}),B9t=({className:e,...t})=>(0,S.jsx)(Sn,{asChild:!0,children:(0,S.jsxs)(Wt,{className:nt(`size-8`,e),"data-slot":`plan-trigger`,size:`icon`,variant:`ghost`,...t,children:[(0,S.jsx)(yt,{className:`size-4`}),(0,S.jsx)(`span`,{className:`sr-only`,children:`Toggle plan`})]})});function V9t(e){let t=e;return typeof t.type==`string`&&t.type.startsWith(`tool-`)&&`state`in t}function H9t(e,t,n,r,i){if(e.type===`text`&&e.text)return(0,S.jsx)(C9t,{className:`whitespace-pre-wrap`,children:e.text},`${t}-${n}`);if(e.type===`reasoning`)return(0,S.jsxs)(y9t,{className:`w-full`,isStreaming:r,children:[(0,S.jsx)(x9t,{}),(0,S.jsx)(S9t,{children:e.text})]},`${t}-${n}`);let a=i?.plan;if(a&&n===0)return(0,S.jsx)(`div`,{className:`w-full`,children:(0,S.jsxs)(L9t,{defaultOpen:!0,isStreaming:r,children:[(0,S.jsx)(R9t,{className:`flex flex-row items-center`,children:(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(`h1`,{className:`text-base`,children:`Agent Plan`}),(0,S.jsx)(B9t,{className:`mb-2`})]})}),(0,S.jsx)(z9t,{children:(0,S.jsx)(`ul`,{className:`space-y-2`,children:a.map((e,t)=>{let n=e.content||JSON.stringify(e),r=e.priority,i=e.status;return(0,S.jsxs)(`li`,{className:`flex items-start justify-between gap-3`,children:[(0,S.jsxs)(`div`,{className:`flex-1`,children:[(0,S.jsx)(`div`,{className:`text-sm ${i===`done`?`line-through text-muted-foreground`:`text-foreground`}`,children:n}),r&&(0,S.jsxs)(`div`,{className:`mt-1 text-xs text-muted-foreground`,children:[`Priority: `,r]})]}),(0,S.jsx)(`div`,{className:`shrink-0 text-xs`,children:(0,S.jsx)(`span`,{className:`px-2 py-1 rounded-full font-medium text-[10px] uppercase tracking-wide ${i===`pending`?`bg-muted text-muted-foreground`:`bg-primary/10 text-primary`}`,children:i??`pending`})})]},`plan-${t}`)})})})]})},`${t}-plan`);if(V9t(e)){let r=e=>{let t=e;return t=t.replace(/^tool-/,``),t=t.replace(/^mcp__/,``),t=t.replace(/(^|__|\/)(acp[-_]?ai[-_]?sdk[-_]?tools)(?=__|\/|$)/g,`$1`),t=t.replace(/^__+/,``).replace(/__+$/,``),t=t.replace(/__{3,}/g,`__`),t||e},i=e.input;if(!i||!i.toolName)return null;let a=r(i.toolName),o=`tool-${a}`,s=e.state,l=s===`output-available`||s===`output-error`;return(0,S.jsxs)(D9t,{defaultOpen:l,children:[(0,S.jsx)(k9t,{title:a.length>20?`${a.slice(0,20)}...`:a,type:o,state:s}),(0,S.jsxs)(A9t,{children:[e.input!==void 0&&(0,S.jsx)(j9t,{input:i.args}),l&&(0,S.jsx)(M9t,{output:e.output?(0,S.jsx)(U7,{code:JSON.stringify(e.output,null,2),language:`json`}):null,errorText:e.errorText})]})]},`${t}-${n}`)}return null}let U9t=({messages:e,status:t,selectedAgent:n})=>{let r=Ac.find(e=>e.name===(n||jc))||Ac[0],i=t===`submitted`||t===`streaming`,a=e[e.length-1],o=i&&(!a||a.role===`user`);return(0,S.jsxs)(qoe,{className:`w-full h-full`,children:[(0,S.jsx)(Joe,{className:`p-3 space-y-3`,children:e.length===0&&!i?(0,S.jsx)(`div`,{className:`flex items-center justify-center h-full text-muted-foreground`,children:(0,S.jsxs)(`div`,{className:`text-center`,children:[(0,S.jsx)(`p`,{className:`text-sm`,children:`No messages yet`}),(0,S.jsx)(`p`,{className:`text-xs mt-1`,children:`Enter a question below to start`})]})}):(0,S.jsxs)(S.Fragment,{children:[e.map(e=>(0,S.jsxs)(kse,{className:`items-start`,from:e.role,children:[(0,S.jsx)(Ase,{children:e.parts.map((n,r)=>H9t(n,e.id,r,t===`streaming`,e.metadata))}),e.role===`assistant`&&(0,S.jsx)(jse,{name:r.name,src:r.meta?.icon??``})]},e.id)),o&&(0,S.jsxs)(kse,{className:`items-start`,from:`assistant`,children:[(0,S.jsx)(Ase,{children:(0,S.jsx)(Nse,{size:16})}),(0,S.jsx)(jse,{name:r.name,src:r.meta?.icon??``})]})]})}),(0,S.jsx)(Yoe,{})]})};function W9t(e,t,n=50){let[r,i]=(0,_.useState)(``),a=(0,_.useRef)(0),o=(0,_.useRef)(``);return(0,_.useEffect)(()=>{if(e.length<r.length||r&&!e.startsWith(r.slice(0,Math.min(r.length,20)))){i(e),o.current=e,a.current=Date.now();return}if(!t){r!==e&&(i(e),o.current=e);return}let s=e.slice(o.current.length);if(!s)return;let l=Date.now();if(l-a.current<n)return;let u=/[.?!。?!](\s|$)|[\n]/.test(s),d=s.length>50,f=s.trim().length<5;(u&&!f||d)&&(i(e),o.current=e,a.current=l)},[e,t,n,r]),r}function G9t({initialOffset:e={x:0,y:0}}={}){let t=(0,_.useRef)(null),[n,r]=(0,_.useState)(!1),i=(0,_.useRef)(e),a=(0,_.useRef)({x:0,y:0}),o=(0,_.useRef)({x:0,y:0}),s=(0,_.useCallback)(()=>{if(t.current){let{x:e,y:n}=i.current;t.current.style.transform=`translate3d(calc(-50% + ${e}px), ${n}px, 0)`}},[]),l=(0,_.useCallback)(e=>{e.target.closest(`button, input, a, [data-no-drag]`)||(e.preventDefault(),r(!0),a.current={x:e.clientX,y:e.clientY},o.current={...i.current})},[]);return(0,_.useEffect)(()=>{let e=e=>{if(!n)return;let t=e.clientX-a.current.x,r=e.clientY-a.current.y;i.current={x:o.current.x+t,y:o.current.y+r},s()},t=()=>{r(!1)};return n&&(window.addEventListener(`mousemove`,e,{passive:!0}),window.addEventListener(`mouseup`,t)),()=>{window.removeEventListener(`mousemove`,e),window.removeEventListener(`mouseup`,t)}},[n,s]),(0,_.useEffect)(()=>{s()},[s]),{elementRef:t,isDragging:n,handleMouseDown:l}}let K9t=`AI_SELECTED_AGENT`,q9t=e=>{let[t,n]=(0,_.useState)(()=>{if(typeof window<`u`){let e=localStorage.getItem(K9t);if(e)return e}return e}),[r,i]=(0,_.useState)(!1);return(0,_.useEffect)(()=>{typeof window<`u`?Lc().then(e=>{e&&e!==jc&&n(e)}).finally(()=>{i(!0)}):i(!0)},[]),{agent:t,setAgent:e=>{n(e),!(typeof window>`u`)&&(e?.trim()?localStorage.setItem(K9t,e):localStorage.removeItem(K9t))},isReady:r}},J9t=({isActive:e,onToggleInspector:t,onSubmitAgent:n,onCancel:r,isAgentWorking:i,messages:a,status:o,inspectionCount:s=0,inspectionItems:l=[],onRemoveInspection:u=()=>{},toolsReady:d=!0})=>{let[f,p]=(0,_.useState)(!1),[m,h]=(0,_.useState)(``),[g,v]=(0,_.useState)(null),[y,b]=(0,_.useState)(`none`),[x,C]=(0,_.useState)(!1),[w,T]=(0,_.useState)(!1),[E,D]=(0,_.useState)(!0),{agent:O,setAgent:k,isReady:A}=q9t(jc),[j,M]=(0,_.useState)(!1),[N,P]=(0,_.useState)(null),[F,I]=(0,_.useState)(null),L=(0,_.useRef)(null),R=(0,_.useRef)(!1),ee=e=>{let t=`${Pc()}/api/acp/cleanup-session`,n=JSON.stringify({sessionId:e});try{if(navigator.sendBeacon){let e=new Blob([n],{type:`application/json`});navigator.sendBeacon(t,e);return}}catch{}fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`},body:n,keepalive:!0}).catch(()=>{})};(0,_.useEffect)(()=>{if(!A||!d)return;let e=!0,t=Ac.find(e=>e.name===O)||Ac[0];return(async()=>{if(L.current){try{await fetch(`${Pc()}/api/acp/cleanup-session`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({sessionId:L.current})})}catch(e){console.warn(`[InspectorBar] Failed to cleanup previous session:`,e)}L.current=null,e&&I(null)}console.log(`[InspectorBar] Initializing session for ${t.name}...`);try{let n=await fetch(`${Pc()}/api/acp/init-session`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({agent:t,envVars:{}})});if(!n.ok)throw Error(`Failed to init session`);let r=await n.json();e&&r.sessionId&&(console.log(`[InspectorBar] Session initialized: ${r.sessionId}`),I(r.sessionId),L.current=r.sessionId,R.current=!1)}catch(e){console.error(`[InspectorBar] Failed to initialize session:`,e)}})(),()=>{e=!1}},[O,A,d]),(0,_.useEffect)(()=>{let e=()=>{let e=L.current;!e||R.current||(R.current=!0,ee(e))};return window.addEventListener(`pagehide`,e),()=>{window.removeEventListener(`pagehide`,e)}},[]),(0,_.useEffect)(()=>()=>{let e=L.current;!e||R.current||(R.current=!0,console.log(`[InspectorBar] Cleaning up session on unmount: ${e}`),ee(e))},[]);let te=Ac.find(e=>e.name===O)||Ac[0],{elementRef:z,isDragging:B,handleMouseDown:ne}=G9t(),[re,ie]=(0,_.useState)(null),[ae,oe]=(0,_.useState)(``),se=W9t(ae,i,50),[ce,le]=(0,_.useState)(``),ue=(0,_.useRef)(``),de=(0,_.useRef)(``);(0,_.useEffect)(()=>{let e=se,t=ue.current;if(e.length<t.length||!e.startsWith(t)){le(e),ue.current=e;return}if(e.length>t.length){let n=e.slice(t.length).trim();n&&le(n),ue.current=e}},[se]);let fe=(0,_.useRef)(null),pe=(0,_.useRef)(null),me=(0,_.useRef)(null),he=(0,_.useRef)(!1);(0,_.useEffect)(()=>{if(a.length===0){oe(``),v(null),me.current=null,he.current=!1,le(``),ue.current=``;return}let e=a[a.length-1];if(e.role!==`assistant`)return;let t=Roe(e),{displayText:n,toolCall:r}=Boe(e,t||me.current);oe(n||``),t&&(me.current=t),r?(pe.current&&=(clearTimeout(pe.current),null),v(r),he.current=!0):he.current=!1},[a]),(0,_.useEffect)(()=>{ce!==de.current&&(he.current||v(null),de.current=ce)},[ce]),(0,_.useEffect)(()=>{f&&fe.current&&fe.current.focus()},[f]),(0,_.useEffect)(()=>{if(!i&&w){C(!1),T(!1),D(!1);let e=setTimeout(()=>{D(!0)},2e3);return()=>clearTimeout(e)}},[i,w]),(0,_.useEffect)(()=>{function e(e){let{plan:t,inspectionId:n}=e.detail;if(t?.steps){let e=t.steps.find(e=>e.status===`in-progress`),r=t.steps.filter(e=>e.status===`completed`).length;ie({id:n,status:`in-progress`,currentStep:e?{title:e.title,index:r+1,total:t.steps.length}:void 0})}}function t(e){let{status:t,result:n,inspectionId:r}=e.detail;ie({id:r,status:t,message:n?.message||n})}return window.addEventListener(`plan-progress-reported`,e),window.addEventListener(`inspection-result-received`,t),()=>{window.removeEventListener(`plan-progress-reported`,e),window.removeEventListener(`inspection-result-received`,t)}},[]);let ge=e=>{e.preventDefault(),m.trim()&&(pe.current&&=(clearTimeout(pe.current),null),v(null),oe(``),le(``),ie(null),me.current=null,ue.current=``,C(!0),T(!0),n(m,O,F||void 0),h(``),p(!0),b(`chat`))},_e=e=>{e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),ge(e)),e.key===`Escape`&&(p(!1),fe.current?.blur())},ve=o===`error`,ye=a.length>0,be=f&&!x,xe=(!f||x)&&(i||ye||re);return(0,S.jsxs)(S.Fragment,{children:[(f||y!==`none`)&&(0,S.jsx)(`div`,{className:`fixed inset-0 z-[999998] bg-transparent`,onClick:()=>{!w&&!i&&(p(!1),b(`none`))}}),(0,S.jsxs)(`div`,{ref:z,className:nt(`fixed bottom-8 left-1/2 z-[999999]`,`transition-all duration-300 ease-[cubic-bezier(0.23,1,0.32,1)]`,f?`w-[480px]`:xe?`w-auto min-w-[200px] max-w-[480px]`:`w-[190px]`,B?`cursor-grabbing`:`cursor-grab`),onMouseDown:ne,onMouseEnter:()=>{B||(i||w?(p(!0),b(`chat`)):E&&p(!0))},onMouseLeave:()=>{!m.trim()&&!w&&!B&&(p(!1),b(`none`)),D(!0)},children:[(0,S.jsxs)(`div`,{className:nt(`relative flex items-center backdrop-blur-xl shadow-2xl border border-border`,`transition-[width,height,padding,background-color,border-color] duration-200 ease-out`,f?`h-12 p-2 pl-4`:`h-9 px-2 py-1`,y===`none`?`bg-muted/90 rounded-full`:`bg-muted/95 rounded-b-lg rounded-t-none border-t-0`,ve&&!f&&`bg-destructive/10 border-destructive/20`),children:[(0,S.jsxs)(`div`,{className:nt(`flex items-center transition-opacity duration-300 w-full relative`,be?`absolute left-3 opacity-0 pointer-events-none`:`relative opacity-100`),children:[!xe&&(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(`div`,{className:`flex items-center justify-center w-6 h-6 rounded-full bg-accent flex-shrink-0`,children:(0,S.jsx)(Mt,{className:`w-3.5 h-3.5 text-foreground`})}),(0,S.jsx)(`span`,{className:`text-xs text-muted-foreground/70 ml-3 whitespace-nowrap`,children:`⌥I or hover to inspect`})]}),xe&&(0,S.jsxs)(S.Fragment,{children:[(0,S.jsxs)(`div`,{className:`flex items-center gap-3 flex-shrink-0`,children:[(0,S.jsx)(`div`,{className:`relative flex items-center justify-center w-6 h-6 rounded-full bg-accent flex-shrink-0`,children:i?(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(`div`,{className:`absolute inset-0 rounded-full border-2 border-current opacity-20 animate-ping text-foreground`}),(0,S.jsx)(Mt,{className:`w-3.5 h-3.5 animate-pulse text-foreground`})]}):re?re.status===`in-progress`?(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(`div`,{className:`absolute inset-0 rounded-full border-2 border-current opacity-20 animate-ping text-blue-500`}),(0,S.jsx)(Nt,{className:`w-3.5 h-3.5 animate-pulse text-blue-500`})]}):re.status===`completed`?(0,S.jsx)(St,{className:`w-5 h-5 text-green-500`}):(0,S.jsx)(Ct,{className:`w-5 h-5 text-red-500`}):ve?(0,S.jsx)(Ct,{className:`w-5 h-5 text-red-500`}):(0,S.jsx)(St,{className:`w-5 h-5 text-green-500`})}),(0,S.jsx)(`div`,{className:`w-px h-4 bg-border flex-shrink-0`})]}),(0,S.jsx)(`div`,{className:`flex-1 flex justify-center min-w-0 pl-2`,children:(0,S.jsx)(`div`,{className:`flex flex-col min-w-0 max-w-full pr-2 max-h-[24px] overflow-hidden`,children:re&&re.status===`in-progress`&&re.currentStep?(0,S.jsxs)(`div`,{className:`flex items-center gap-1.5 text-sm font-medium text-foreground min-w-0`,children:[(0,S.jsx)(Nt,{className:`w-4 h-4 flex-shrink-0`}),(0,S.jsxs)(`span`,{className:`truncate min-w-0`,children:[`Step `,re.currentStep.index,`/`,re.currentStep.total,`: `,re.currentStep.title]})]}):re?.message?(0,S.jsx)(`div`,{className:`text-sm font-medium leading-[1.4] text-foreground truncate min-w-0`,children:re.message}):g?(0,S.jsxs)(`div`,{className:`flex items-center gap-1.5 text-sm font-medium text-foreground min-w-0`,children:[(0,S.jsx)(Nt,{className:`w-4 h-4 flex-shrink-0`}),(0,S.jsx)(`span`,{className:`truncate min-w-0`,children:g})]}):(0,S.jsx)(`div`,{className:`text-sm font-medium leading-[1.4] text-foreground truncate min-w-0`,children:i&&!ce?(0,S.jsx)(Foe,{duration:2,spread:2,children:o===`submitted`&&te?.command===`npx`?`Starting ${te.name}... This may take a moment.`:`Thinking...`}):ce||`Processing...`})})})]})]}),(0,S.jsxs)(`div`,{className:nt(`flex items-center w-full gap-3 transition-all duration-500 delay-75`,be?`opacity-100 translate-y-0 relative pointer-events-auto`:`opacity-0 translate-y-4 pointer-events-none absolute top-2 left-4 right-2`),onClick:e=>e.stopPropagation(),children:[(0,S.jsx)(`button`,{onClick:t,className:nt(`relative flex items-center justify-center w-7 h-7 rounded-full transition-colors flex-shrink-0`,e?`bg-blue-500 text-white shadow-[0_0_15px_rgba(59,130,246,0.5)]`:`bg-accent text-muted-foreground hover:bg-accent/80 hover:text-foreground`),title:`Toggle Inspector (⌥I)`,children:(0,S.jsx)(Et,{className:`w-3.5 h-3.5`})}),(0,S.jsx)(`div`,{className:`w-px h-4 bg-border flex-shrink-0`}),s>0&&(0,S.jsxs)(S.Fragment,{children:[(0,S.jsxs)(`button`,{type:`button`,onClick:()=>b(e=>e===`inspections`?`none`:`inspections`),className:nt(`relative flex items-center justify-center w-7 h-7 rounded-full transition-colors flex-shrink-0`,`hover:bg-accent/50`,y===`inspections`&&`bg-accent/50 text-foreground`),title:`View Inspections`,children:[(0,S.jsx)(Dt,{className:`w-3.5 h-3.5`}),(0,S.jsx)(`span`,{className:`absolute -top-0.5 -right-0.5 flex items-center justify-center min-w-[12px] h-[12px] px-0.5 text-[8px] font-bold text-white bg-red-500 rounded-full border border-background shadow-sm leading-none`,children:s>99?`99+`:s})]}),(0,S.jsx)(`div`,{className:`w-px h-4 bg-border flex-shrink-0`})]}),(0,S.jsxs)(`form`,{onSubmit:ge,className:`flex-1 flex items-center gap-2 min-w-0`,onClick:e=>e.stopPropagation(),children:[(0,S.jsxs)(`div`,{className:`relative flex-shrink-0`,children:[(0,S.jsx)(`button`,{type:`button`,onClick:()=>M(!j),className:`flex items-center justify-center w-7 h-7 rounded-full hover:bg-accent/50 transition-colors`,title:`Select Agent`,children:(0,S.jsx)(`img`,{src:Ac.find(e=>e.name===O)?.meta?.icon,alt:O,className:`w-3.5 h-3.5`})}),j&&(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(`div`,{className:`fixed inset-0 z-[999998]`,onClick:()=>M(!1)}),(0,S.jsx)(`div`,{className:`absolute bottom-full left-0 mb-2 w-64 bg-popover border border-border rounded-lg shadow-lg overflow-hidden z-[999999] animate-in fade-in zoom-in-95 duration-200`,children:Ac.map(e=>(0,S.jsxs)(`div`,{className:nt(`w-full flex items-center gap-2 px-3 py-2 text-sm hover:bg-accent transition-colors group`,O===e.name&&`bg-accent/50 font-medium`),children:[(0,S.jsxs)(`button`,{onClick:()=>{k(e.name),M(!1)},className:`flex items-center gap-2 flex-1 text-left`,children:[e.meta?.icon&&(0,S.jsx)(`img`,{src:e.meta.icon,alt:``,className:`w-4 h-4 flex-shrink-0`}),(0,S.jsx)(`span`,{className:`flex-1`,children:e.name})]}),(e.configHint||e.configLink)&&(0,S.jsx)(`button`,{onClick:t=>{t.stopPropagation(),P(e.name)},className:`p-1 rounded hover:bg-accent-foreground/10 transition-colors`,title:`Configuration info`,children:(0,S.jsx)(Ot,{className:`w-3.5 h-3.5 text-muted-foreground`})})]},e.name))})]})]}),(0,S.jsx)(`input`,{ref:fe,type:`text`,value:m,onChange:e=>h(e.target.value),onKeyDown:_e,placeholder:`Ask ${O}...`,className:`w-full bg-transparent border-none outline-none text-foreground placeholder-muted-foreground text-sm h-7 disabled:opacity-50`,tabIndex:0,disabled:i}),(a.length>0||i||w)&&(0,S.jsx)(`button`,{type:`button`,onClick:()=>b(e=>e===`chat`?`none`:`chat`),className:nt(`flex items-center justify-center w-7 h-7 rounded-full transition-all flex-shrink-0`,y===`chat`?`bg-foreground text-background`:`bg-accent text-muted-foreground hover:bg-accent/80 hover:text-foreground`),title:y===`chat`?`Collapse`:`Expand messages`,children:(0,S.jsx)(vt,{className:nt(`w-3.5 h-3.5 transition-transform duration-300`,y===`chat`&&`rotate-180`)})}),i?(0,S.jsx)(`button`,{type:`button`,onClick:r,className:`flex items-center justify-center w-7 h-7 rounded-full bg-destructive text-destructive-foreground transition-all flex-shrink-0 hover:bg-destructive/90`,title:`Cancel request`,children:(0,S.jsx)(tee,{className:`w-3 h-3`})}):(0,S.jsx)(`button`,{type:`submit`,disabled:!m.trim(),className:nt(`flex items-center justify-center w-7 h-7 rounded-full transition-all flex-shrink-0`,m.trim()?`bg-foreground text-background scale-100`:`bg-accent text-muted-foreground/50 scale-90`),children:(0,S.jsx)(ht,{className:`w-3.5 h-3.5`})})]})]})]}),y!==`none`&&(0,S.jsx)(`div`,{className:`absolute bottom-full left-0 right-0 pointer-events-auto max-w-[480px] mx-auto animate-panel-in`,children:(0,S.jsxs)(`div`,{className:`bg-muted/95 backdrop-blur-xl rounded-t-xl border border-border border-b-0 shadow-2xl overflow-hidden`,children:[y===`inspections`&&l.length>0&&(0,S.jsx)(`div`,{className:`border-b border-border`,children:(0,S.jsx)(pee,{items:l,onRemove:u})}),y===`chat`&&(0,S.jsx)(`div`,{className:`h-[500px]`,children:(0,S.jsx)(U9t,{messages:a,status:o,selectedAgent:O})})]})})]}),N&&(()=>{let e=Ac.find(e=>e.name===N);return e?(0,S.jsx)(Lt,{open:!!N,onOpenChange:()=>P(null),children:(0,S.jsxs)(Rt,{onClose:()=>P(null),className:`w-80`,children:[(0,S.jsxs)(zt,{children:[(0,S.jsxs)(nee,{className:`flex items-center gap-3`,children:[e.meta?.icon&&(0,S.jsx)(`img`,{src:e.meta.icon,alt:``,className:`w-6 h-6`}),e.name]}),e.configHint&&(0,S.jsx)(Vt,{children:e.configHint})]}),e.configLink&&(0,S.jsx)(`a`,{href:e.configLink,target:`_blank`,rel:`noopener noreferrer`,className:`inline-flex items-center gap-1 text-sm text-blue-500 hover:text-blue-600 underline`,children:`View ACP Documentation →`})]})}):null})()]})};var Y9t=`vercel.ai.error`,X9t=Symbol.for(Y9t),Z9t,Q9t=class e extends Error{constructor({name:e,message:t,cause:n}){super(t),this[Z9t]=!0,this.name=e,this.cause=n}static isInstance(t){return e.hasMarker(t,Y9t)}static hasMarker(e,t){let n=Symbol.for(t);return typeof e==`object`&&!!e&&n in e&&typeof e[n]==`boolean`&&e[n]===!0}};Z9t=X9t;var W7=Q9t;function $9t(e){return e==null?`unknown error`:typeof e==`string`?e:e instanceof Error?e.message:JSON.stringify(e)}var een=`AI_InvalidArgumentError`,ten=`vercel.ai.error.${een}`,nen=Symbol.for(ten),ren,ien=class extends W7{constructor({message:e,cause:t,argument:n}){super({name:een,message:e,cause:t}),this[ren]=!0,this.argument=n}static isInstance(e){return W7.hasMarker(e,ten)}};ren=nen;var aen=`AI_JSONParseError`,oen=`vercel.ai.error.${aen}`,sen=Symbol.for(oen),cen,len=class extends W7{constructor({text:e,cause:t}){super({name:aen,message:`JSON parsing failed: Text: ${e}.
6886
6886
  Error message: ${$9t(t)}`,cause:t}),this[cen]=!0,this.text=e}static isInstance(e){return W7.hasMarker(e,oen)}};cen=sen;var uen=`AI_TypeValidationError`,den=`vercel.ai.error.${uen}`,fen=Symbol.for(den),pen,men=class e extends W7{constructor({value:e,cause:t}){super({name:uen,message:`Type validation failed: Value: ${JSON.stringify(e)}.
6887
6887
  Error message: ${$9t(t)}`,cause:t}),this[pen]=!0,this.value=e}static isInstance(e){return W7.hasMarker(e,den)}static wrap({value:t,cause:n}){return e.isInstance(n)&&n.value===t?n:new e({value:t,cause:n})}};pen=fen;var G7=men,hen=class extends TransformStream{constructor({onError:e,onRetry:t,onComment:n}={}){let r;super({start(i){r=Lo({onEvent:e=>{i.enqueue(e)},onError(t){e===`terminate`?i.error(t):typeof e==`function`&&e(t)},onRetry:t,onComment:n})},transform(e){r.feed(e)}})}};Object.freeze({status:`aborted`});function K7(e,t,n){function r(n,r){var i;for(let a in Object.defineProperty(n,`_zod`,{value:n._zod??{},enumerable:!1}),(i=n._zod).traits??(i.traits=new Set),n._zod.traits.add(e),t(n,r),o.prototype)a in n||Object.defineProperty(n,a,{value:o.prototype[a].bind(n)});n._zod.constr=o,n._zod.def=r}let i=n?.Parent??Object;class a extends i{}Object.defineProperty(a,`name`,{value:e});function o(e){var t;let i=n?.Parent?new a:this;r(i,e),(t=i._zod).deferred??(t.deferred=[]);for(let e of i._zod.deferred)e();return i}return Object.defineProperty(o,`init`,{value:r}),Object.defineProperty(o,Symbol.hasInstance,{value:t=>n?.Parent&&t instanceof n.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(o,`name`,{value:e}),o}var q7=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}};let gen={};function J7(e){return e&&Object.assign(gen,e),gen}function _en(e){let t=Object.values(e).filter(e=>typeof e==`number`);return Object.entries(e).filter(([e,n])=>t.indexOf(+e)===-1).map(([e,t])=>t)}function ven(e,t){return typeof t==`bigint`?t.toString():t}function yen(e){return{get value(){{let t=e();return Object.defineProperty(this,`value`,{value:t}),t}throw Error(`cached value already set`)}}}function ben(e){return e==null}function xen(e){let t=e.startsWith(`^`)?1:0,n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function Sen(e,t){let n=(e.toString().split(`.`)[1]||``).length,r=(t.toString().split(`.`)[1]||``).length,i=n>r?n:r;return Number.parseInt(e.toFixed(i).replace(`.`,``))%Number.parseInt(t.toFixed(i).replace(`.`,``))/10**i}function Y7(e,t,n){Object.defineProperty(e,t,{get(){{let r=n();return e[t]=r,r}throw Error(`cached value already set`)},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function X7(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Z7(e){return JSON.stringify(e)}let Cen=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function Q7(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}let wen=yen(()=>{if(typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}});function $7(e){if(Q7(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(Q7(n)===!1||Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)===!1)}let Ten=new Set([`string`,`number`,`symbol`]);function e9(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function t9(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function n9(e){let t=e;if(!t)return{};if(typeof t==`string`)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error==`string`?{...t,error:()=>t.error}:t}function Een(e){return Object.keys(e).filter(t=>e[t]._zod.optin===`optional`&&e[t]._zod.optout===`optional`)}let Den={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Oen(e,t){let n={},r=e._zod.def;for(let e in t){if(!(e in r.shape))throw Error(`Unrecognized key: "${e}"`);t[e]&&(n[e]=r.shape[e])}return t9(e,{...e._zod.def,shape:n,checks:[]})}function ken(e,t){let n={...e._zod.def.shape},r=e._zod.def;for(let e in t){if(!(e in r.shape))throw Error(`Unrecognized key: "${e}"`);t[e]&&delete n[e]}return t9(e,{...e._zod.def,shape:n,checks:[]})}function Aen(e,t){if(!$7(t))throw Error(`Invalid input to extend: expected a plain object`);return t9(e,{...e._zod.def,get shape(){let n={...e._zod.def.shape,...t};return X7(this,`shape`,n),n},checks:[]})}function jen(e,t){return t9(e,{...e._zod.def,get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return X7(this,`shape`,n),n},catchall:t._zod.def.catchall,checks:[]})}function Men(e,t,n){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in r))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t])}else for(let t in r)i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t];return t9(t,{...t._zod.def,shape:i,checks:[]})}function Nen(e,t,n){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in i))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=new e({type:`nonoptional`,innerType:r[t]}))}else for(let t in r)i[t]=new e({type:`nonoptional`,innerType:r[t]});return t9(t,{...t._zod.def,shape:i,checks:[]})}function r9(e,t=0){for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function i9(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function a9(e){return typeof e==`string`?e:e?.message}function o9(e,t,n){let r={...e,path:e.path??[]};return e.message||(r.message=a9(e.inst?._zod.def?.error?.(e))??a9(t?.error?.(e))??a9(n.customError?.(e))??a9(n.localeError?.(e))??`Invalid input`),delete r.inst,delete r.continue,t?.reportInput||delete r.input,r}function Pen(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function s9(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}let Fen=(e,t)=>{e.name=`$ZodError`,Object.defineProperty(e,`_zod`,{value:e._zod,enumerable:!1}),Object.defineProperty(e,`issues`,{value:t,enumerable:!1}),Object.defineProperty(e,`message`,{get(){return JSON.stringify(t,ven,2)},enumerable:!0}),Object.defineProperty(e,`toString`,{value:()=>e.message,enumerable:!1})},Ien=K7(`$ZodError`,Fen),Len=K7(`$ZodError`,Fen,{Parent:Error});function Ren(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}function zen(e,t){let n=t||function(e){return e.message},r={_errors:[]},i=e=>{for(let t of e.issues)if(t.code===`invalid_union`&&t.errors.length)t.errors.map(e=>i({issues:e}));else if(t.code===`invalid_key`)i({issues:t.issues});else if(t.code===`invalid_element`)i({issues:t.issues});else if(t.path.length===0)r._errors.push(n(t));else{let e=r,i=0;for(;i<t.path.length;){let r=t.path[i];i===t.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(n(t))):e[r]=e[r]||{_errors:[]},e=e[r],i++}}};return i(e),r}let Ben=e=>(t,n,r,i)=>{let a=r?Object.assign(r,{async:!1}):{async:!1},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise)throw new q7;if(o.issues.length){let t=new(i?.Err??e)(o.issues.map(e=>o9(e,a,J7())));throw Cen(t,i?.callee),t}return o.value},Ven=e=>async(t,n,r,i)=>{let a=r?Object.assign(r,{async:!0}):{async:!0},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise&&(o=await o),o.issues.length){let t=new(i?.Err??e)(o.issues.map(e=>o9(e,a,J7())));throw Cen(t,i?.callee),t}return o.value},Hen=e=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new q7;return a.issues.length?{success:!1,error:new(e??Ien)(a.issues.map(e=>o9(e,i,J7())))}:{success:!0,data:a.value}},Uen=Hen(Len),Wen=e=>async(t,n,r)=>{let i=r?Object.assign(r,{async:!0}):{async:!0},a=t._zod.run({value:n,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(e=>o9(e,i,J7())))}:{success:!0,data:a.value}},Gen=Wen(Len),Ken=/^[cC][^\s-]{8,}$/,qen=/^[0-9a-z]+$/,Jen=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Yen=/^[0-9a-vA-V]{20}$/,Xen=/^[A-Za-z0-9]{27}$/,Zen=/^[a-zA-Z0-9_-]{21}$/,Qen=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,$en=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,etn=e=>e?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,ttn=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function ntn(){return RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)}let rtn=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,itn=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,atn=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,otn=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,stn=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,ctn=/^[A-Za-z0-9_-]*$/,ltn=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,utn=/^\+(?:[0-9]){6,14}[0-9]$/,dtn=`(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`,ftn=RegExp(`^${dtn}$`);function ptn(e){let t=`(?:[01]\\d|2[0-3]):[0-5]\\d`;return typeof e.precision==`number`?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function mtn(e){return RegExp(`^${ptn(e)}$`)}function htn(e){let t=ptn({precision:e.precision}),n=[`Z`];e.local&&n.push(``),e.offset&&n.push(`([+-]\\d{2}:\\d{2})`);let r=`${t}(?:${n.join(`|`)})`;return RegExp(`^${dtn}T(?:${r})$`)}let gtn=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??``}}`:`[\\s\\S]*`;return RegExp(`^${t}$`)},_tn=/^\d+$/,vtn=/^-?\d+(?:\.\d+)?/i,ytn=/true|false/i,btn=/null/i,xtn=/^[^A-Z]*$/,Stn=/^[^a-z]*$/,c9=K7(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Ctn={number:`number`,bigint:`bigint`,object:`date`},wtn=K7(`$ZodCheckLessThan`,(e,t)=>{c9.init(e,t);let n=Ctn[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.maximum:n.exclusiveMaximum)??1/0;t.value<r&&(t.inclusive?n.maximum=t.value:n.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:`too_big`,maximum:t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Ttn=K7(`$ZodCheckGreaterThan`,(e,t)=>{c9.init(e,t);let n=Ctn[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.minimum:n.exclusiveMinimum)??-1/0;t.value>r&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:`too_small`,minimum:t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Etn=K7(`$ZodCheckMultipleOf`,(e,t)=>{c9.init(e,t),e._zod.onattach.push(e=>{var n;(n=e._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw Error(`Cannot mix number and bigint in multiple_of check.`);(typeof n.value==`bigint`?n.value%t.value===BigInt(0):Sen(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:`not_multiple_of`,divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),Dtn=K7(`$ZodCheckNumberFormat`,(e,t)=>{c9.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=Den[t.format];e._zod.onattach.push(e=>{let r=e._zod.bag;r.format=t.format,r.minimum=i,r.maximum=a,n&&(r.pattern=_tn)}),e._zod.check=o=>{let s=o.value;if(n){if(!Number.isInteger(s)){o.issues.push({expected:r,format:t.format,code:`invalid_type`,input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?o.issues.push({input:s,code:`too_big`,maximum:2**53-1,note:`Integers must be within the safe integer range.`,inst:e,origin:r,continue:!t.abort}):o.issues.push({input:s,code:`too_small`,minimum:-(2**53-1),note:`Integers must be within the safe integer range.`,inst:e,origin:r,continue:!t.abort});return}}s<i&&o.issues.push({origin:`number`,input:s,code:`too_small`,minimum:i,inclusive:!0,inst:e,continue:!t.abort}),s>a&&o.issues.push({origin:`number`,input:s,code:`too_big`,maximum:a,inst:e})}}),Otn=K7(`$ZodCheckMaxLength`,(e,t)=>{var n;c9.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!ben(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.maximum??1/0;t.maximum<n&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let r=n.value;if(r.length<=t.maximum)return;let i=Pen(r);n.issues.push({origin:i,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),ktn=K7(`$ZodCheckMinLength`,(e,t)=>{var n;c9.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!ben(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.minimum??-1/0;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let r=n.value;if(r.length>=t.minimum)return;let i=Pen(r);n.issues.push({origin:i,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Atn=K7(`$ZodCheckLengthEquals`,(e,t)=>{var n;c9.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!ben(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=n=>{let r=n.value,i=r.length;if(i===t.length)return;let a=Pen(r),o=i>t.length;n.issues.push({origin:a,...o?{code:`too_big`,maximum:t.length}:{code:`too_small`,minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),l9=K7(`$ZodCheckStringFormat`,(e,t)=>{var n,r;c9.init(e,t),e._zod.onattach.push(e=>{let n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??=new Set,n.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),jtn=K7(`$ZodCheckRegex`,(e,t)=>{l9.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:`regex`,input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Mtn=K7(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=xtn,l9.init(e,t)}),Ntn=K7(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=Stn,l9.init(e,t)}),Ptn=K7(`$ZodCheckIncludes`,(e,t)=>{c9.init(e,t);let n=e9(t.includes),r=new RegExp(typeof t.position==`number`?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(r)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:`string`,code:`invalid_format`,format:`includes`,includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),Ftn=K7(`$ZodCheckStartsWith`,(e,t)=>{c9.init(e,t);let n=RegExp(`^${e9(t.prefix)}.*`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`starts_with`,prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),Itn=K7(`$ZodCheckEndsWith`,(e,t)=>{c9.init(e,t);let n=RegExp(`.*${e9(t.suffix)}$`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`ends_with`,suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),Ltn=K7(`$ZodCheckOverwrite`,(e,t)=>{c9.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});var Rtn=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),--this.indent}write(e){if(typeof e==`function`){e(this,{execution:`sync`}),e(this,{execution:`async`});return}let t=e.split(`
6888
6888
  `).filter(e=>e),n=Math.min(...t.map(e=>e.length-e.trimStart().length)),r=t.map(e=>e.slice(n)).map(e=>` `.repeat(this.indent*2)+e);for(let e of r)this.content.push(e)}compile(){let e=Function,t=this?.args,n=[...(this?.content??[``]).map(e=>` ${e}`)];return new e(...t,n.join(`
@@ -86926,14 +86926,20 @@ var ConnectionManager = class {
86926
86926
  //#endregion
86927
86927
  //#region src/utils/cors.ts
86928
86928
  /**
86929
- * Set CORS headers and handle preflight requests
86930
- * Returns true if request was handled (preflight), false otherwise
86929
+ * Set CORS headers and handle preflight requests.
86930
+ *
86931
+ * Uses the browser's requested headers (Access-Control-Request-Headers) when present
86932
+ * to avoid mismatches that can break CORS preflight (e.g. 'user-agent').
86933
+ *
86934
+ * Returns true if request was handled (preflight), false otherwise.
86931
86935
  */
86932
- function handleCors(res, method) {
86936
+ function handleCors(req, res) {
86933
86937
  res.setHeader("Access-Control-Allow-Origin", "*");
86934
86938
  res.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS");
86935
- res.setHeader("Access-Control-Allow-Headers", "Content-Type, mcp-session-id, mcp-protocol-version");
86936
- if (method === "OPTIONS") {
86939
+ const requested = req.headers["access-control-request-headers"];
86940
+ const requestedValue = Array.isArray(requested) ? requested.join(", ") : requested;
86941
+ res.setHeader("Access-Control-Allow-Headers", requestedValue ?? "Content-Type, mcp-session-id, mcp-protocol-version");
86942
+ if (req.method === "OPTIONS") {
86937
86943
  res.statusCode = 204;
86938
86944
  res.end();
86939
86945
  return true;
@@ -86959,7 +86965,7 @@ async function setupMcpMiddleware(middlewares, serverContext) {
86959
86965
  middlewares.use(async (req, res, next$1) => {
86960
86966
  const url$1 = req.url || "";
86961
86967
  if (url$1.startsWith("/__mcp__")) {
86962
- if (handleCors(res, req.method)) return;
86968
+ if (handleCors(req, res)) return;
86963
86969
  }
86964
86970
  if (url$1.startsWith("/__mcp__") && !url$1.startsWith("/__mcp__/sse") && !url$1.startsWith("/__mcp__/messages")) {
86965
86971
  if (req.method === "POST") await handleStreamableHttpPost(req, res, serverContext, connectionManager);
@@ -87196,7 +87202,7 @@ function setupInspectorMiddleware(middlewares, config) {
87196
87202
  let filesChecked = false;
87197
87203
  middlewares.use((req, res, next$1) => {
87198
87204
  if (req.url?.startsWith("/__inspector__")) {
87199
- if (handleCors(res, req.method)) return;
87205
+ if (handleCors(req, res)) return;
87200
87206
  }
87201
87207
  if (!filesChecked) {
87202
87208
  cachedScript = getInspectorScript();
@@ -88362,15 +88368,10 @@ function checkCommandExists(command) {
88362
88368
  }
88363
88369
  }
88364
88370
  /**
88365
- * Provider manager - stores one provider per agent config
88366
- * Key: agentKey (command:args), Value: ProviderEntry
88367
- */
88368
- const providerManager = /* @__PURE__ */ new Map();
88369
- /**
88370
- * Session to provider mapping for quick lookup
88371
- * Key: sessionId, Value: agentKey
88371
+ * Session-scoped provider manager
88372
+ * Key: sessionId, Value: ProviderEntry
88372
88373
  */
88373
- const sessionToProvider = /* @__PURE__ */ new Map();
88374
+ const sessionProviders = /* @__PURE__ */ new Map();
88374
88375
  /**
88375
88376
  * Generate a unique key for an agent configuration
88376
88377
  */
@@ -88404,15 +88405,22 @@ function callMcpMethodViaTransport(transport, method, params) {
88404
88405
  /**
88405
88406
  * Load MCP tools from transport in AI SDK v5 format
88406
88407
  */
88407
- async function loadMcpToolsV5(transport) {
88408
+ async function loadMcpToolsV5(getTransport) {
88408
88409
  const tools = {};
88409
- const { tools: toolsListFromServer } = await callMcpMethodViaTransport(transport, "tools/list");
88410
+ const initialTransport = getTransport();
88411
+ if (!initialTransport) {
88412
+ console.warn("[dev-inspector] [acp] No active MCP transport available, tools will not be loaded");
88413
+ return tools;
88414
+ }
88415
+ const { tools: toolsListFromServer } = await callMcpMethodViaTransport(initialTransport, "tools/list");
88410
88416
  for (const toolInfo of toolsListFromServer) {
88411
88417
  const toolName = toolInfo.name;
88412
88418
  tools[toolName] = (0, ai.tool)({
88413
88419
  description: toolInfo.description,
88414
88420
  inputSchema: (0, ai.jsonSchema)(toolInfo.inputSchema),
88415
88421
  execute: async (args) => {
88422
+ const transport = getTransport();
88423
+ if (!transport) throw new Error("No active MCP transport available");
88416
88424
  console.log(`[dev-inspector] [acp] Executing MCP tool: ${toolName}`);
88417
88425
  const result = await callMcpMethodViaTransport(transport, "tools/call", {
88418
88426
  name: toolName,
@@ -88464,7 +88472,7 @@ function setupAcpMiddleware(middlewares, serverContext, acpOptions) {
88464
88472
  * Returns: { sessionId }
88465
88473
  */
88466
88474
  middlewares.use("/api/acp/init-session", async (req, res) => {
88467
- if (handleCors(res, req.method)) return;
88475
+ if (handleCors(req, res)) return;
88468
88476
  if (req.method !== "POST") {
88469
88477
  res.statusCode = 405;
88470
88478
  res.end("Method Not Allowed");
@@ -88475,105 +88483,58 @@ function setupAcpMiddleware(middlewares, serverContext, acpOptions) {
88475
88483
  const { agent, envVars } = JSON.parse(body);
88476
88484
  const cwd$1 = process.cwd();
88477
88485
  const agentKey = getAgentKey(agent.command, agent.args);
88478
- console.log(`[dev-inspector] [acp] Requesting session for agent: ${agent.name} (${agentKey})`);
88479
- let providerEntry = providerManager.get(agentKey);
88480
- let sessionId = "";
88481
- if (providerEntry) {
88482
- if (providerEntry.sessions.size > 0) {
88483
- const firstSession = providerEntry.sessions.values().next().value;
88484
- if (firstSession) {
88485
- sessionId = firstSession.sessionId;
88486
- console.log(`[dev-inspector] [acp] Reusing existing session: ${sessionId} for ${agent.name}`);
88487
- }
88488
- }
88489
- if (!sessionId && providerEntry.initializationPromise) {
88490
- console.log(`[dev-inspector] [acp] Joining pending initialization for ${agent.name}`);
88491
- try {
88492
- sessionId = await providerEntry.initializationPromise;
88493
- } catch (e) {
88494
- throw e;
88495
- }
88496
- }
88486
+ console.log(`[dev-inspector] [acp] Creating request-scoped session for agent: ${agent.name} (${agentKey})`);
88487
+ if (!checkCommandExists(agent.command)) {
88488
+ const hints = [`Agent "${agent.name}" command not found: "${agent.command}"`];
88489
+ if (agent.installCommand) hints.push(`Install with: ${agent.installCommand}`);
88490
+ if (agent.configHint) hints.push(agent.configHint);
88491
+ if (agent.configLink) hints.push(`Documentation: ${agent.configLink}`);
88492
+ console.error(`\n${hints.join("\n")}\n`);
88493
+ res.statusCode = 400;
88494
+ res.end(JSON.stringify({ error: hints.join("\n") }));
88495
+ return;
88497
88496
  }
88498
- if (!sessionId) {
88499
- let provider;
88500
- if (providerEntry) {
88501
- console.log(`[dev-inspector] [acp] Reusing existing provider for ${agent.name}`);
88502
- provider = providerEntry.provider;
88503
- } else {
88504
- if (!checkCommandExists(agent.command)) {
88505
- const hints = [`Agent "${agent.name}" command not found: "${agent.command}"`];
88506
- if (agent.installCommand) hints.push(`Install with: ${agent.installCommand}`);
88507
- if (agent.configHint) hints.push(agent.configHint);
88508
- if (agent.configLink) hints.push(`Documentation: ${agent.configLink}`);
88509
- console.error(`\n${hints.join("\n")}\n`);
88510
- return;
88511
- }
88512
- console.log(`[dev-inspector] [acp] Creating new global provider for ${agent.name}`);
88513
- let command = agent.command;
88514
- let args = agent.args;
88515
- if (agent.npmPackage) {
88516
- const binPath = resolveNpmPackageBin(agent.npmPackage);
88517
- if (binPath) {
88518
- command = binPath;
88519
- args = agent.npmArgs || [];
88520
- console.log(`[dev-inspector] [acp] Using resolved npm package: ${agent.npmPackage}`);
88521
- } else console.log(`[dev-inspector] [acp] Failed to resolve npm package, falling back to: ${agent.command}`);
88522
- }
88523
- provider = createACPProvider({
88524
- command,
88525
- args,
88526
- env: {
88527
- ...process.env,
88528
- ...envVars
88529
- },
88530
- session: {
88531
- cwd: cwd$1,
88532
- mcpServers: []
88533
- },
88534
- authMethodId: agent.authMethodId,
88535
- persistSession: true
88536
- });
88537
- providerEntry = {
88538
- provider,
88539
- agentKey,
88540
- sessions: /* @__PURE__ */ new Map(),
88541
- createdAt: Date.now(),
88542
- initializationPromise: void 0
88543
- };
88544
- providerManager.set(agentKey, providerEntry);
88545
- }
88546
- console.log(`[dev-inspector] [acp] Spawning new process/session for ${agent.name}`);
88547
- const initPromise = (async () => {
88548
- const transport = getInspectorTransport() || getActiveTransport();
88549
- let initialTools = {};
88550
- if (transport) try {
88551
- const rawTools = await loadMcpToolsV5(transport);
88552
- initialTools = acpTools(rawTools);
88553
- console.log(`[dev-inspector] [acp] Pre-loading ${Object.keys(rawTools).length} tools for session init`);
88554
- } catch (e) {
88555
- console.warn("[dev-inspector] [acp] Failed to pre-load tools:", e);
88556
- }
88557
- const sid = (await provider.initSession(initialTools)).sessionId || `session-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
88558
- if (providerEntry) {
88559
- providerEntry.sessions.set(sid, {
88560
- sessionId: sid,
88561
- createdAt: Date.now()
88562
- });
88563
- providerEntry.initializationPromise = void 0;
88564
- }
88565
- sessionToProvider.set(sid, agentKey);
88566
- return sid;
88567
- })();
88568
- if (providerEntry) providerEntry.initializationPromise = initPromise;
88569
- try {
88570
- sessionId = await initPromise;
88571
- console.log(`[dev-inspector] [acp] Session initialized: ${sessionId}`);
88572
- } catch (error) {
88573
- if (providerEntry) providerEntry.initializationPromise = void 0;
88574
- throw error;
88497
+ let command = agent.command;
88498
+ let args = agent.args;
88499
+ if (agent.npmPackage) {
88500
+ const binPath = resolveNpmPackageBin(agent.npmPackage);
88501
+ if (binPath) {
88502
+ command = binPath;
88503
+ args = agent.npmArgs || [];
88504
+ console.log(`[dev-inspector] [acp] Using resolved npm package: ${agent.npmPackage}`);
88505
+ } else console.log(`[dev-inspector] [acp] Failed to resolve npm package, falling back to: ${agent.command}`);
88506
+ }
88507
+ const provider = createACPProvider({
88508
+ command,
88509
+ args,
88510
+ env: {
88511
+ ...process.env,
88512
+ ...envVars
88513
+ },
88514
+ session: {
88515
+ cwd: cwd$1,
88516
+ mcpServers: []
88517
+ },
88518
+ authMethodId: agent.authMethodId
88519
+ });
88520
+ console.log(`[dev-inspector] [acp] Spawning new process/session for ${agent.name}`);
88521
+ const getTransport = () => getInspectorTransport() || getActiveTransport();
88522
+ let initialTools = {};
88523
+ try {
88524
+ const rawTools = await loadMcpToolsV5(getTransport);
88525
+ if (Object.keys(rawTools).length > 0) {
88526
+ initialTools = acpTools(rawTools);
88527
+ console.log(`[dev-inspector] [acp] Pre-loading ${Object.keys(rawTools).length} tools for session init`);
88575
88528
  }
88529
+ } catch (e) {
88530
+ console.warn("[dev-inspector] [acp] Failed to pre-load tools:", e);
88576
88531
  }
88532
+ const sessionId = (await provider.initSession(initialTools)).sessionId || `session-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
88533
+ sessionProviders.set(sessionId, {
88534
+ provider,
88535
+ createdAt: Date.now()
88536
+ });
88537
+ console.log(`[dev-inspector] [acp] Session initialized: ${sessionId}`);
88577
88538
  res.setHeader("Content-Type", "application/json");
88578
88539
  res.end(JSON.stringify({ sessionId }));
88579
88540
  } catch (error) {
@@ -88591,7 +88552,7 @@ function setupAcpMiddleware(middlewares, serverContext, acpOptions) {
88591
88552
  * Body: { sessionId }
88592
88553
  */
88593
88554
  middlewares.use("/api/acp/cleanup-session", async (req, res) => {
88594
- if (handleCors(res, req.method)) return;
88555
+ if (handleCors(req, res)) return;
88595
88556
  if (req.method !== "POST") {
88596
88557
  res.statusCode = 405;
88597
88558
  res.end("Method Not Allowed");
@@ -88600,23 +88561,15 @@ function setupAcpMiddleware(middlewares, serverContext, acpOptions) {
88600
88561
  try {
88601
88562
  const body = await readBody(req);
88602
88563
  const { sessionId } = JSON.parse(body);
88603
- const agentKey = sessionToProvider.get(sessionId);
88604
- if (agentKey) {
88605
- const providerEntry = providerManager.get(agentKey);
88606
- if (providerEntry) {
88607
- console.log(`[dev-inspector] [acp] Cleaning up session: ${sessionId} (Provider sessions left: ${providerEntry.sessions.size - 1})`);
88608
- providerEntry.sessions.delete(sessionId);
88609
- if (providerEntry.sessions.size === 0) {
88610
- console.log(`[dev-inspector] [acp] No active sessions for ${agentKey}, cleaning up provider`);
88611
- try {
88612
- providerEntry.provider.cleanup();
88613
- } catch (e) {
88614
- console.error("Error cleaning up provider:", e);
88615
- }
88616
- providerManager.delete(agentKey);
88617
- }
88564
+ const providerEntry = sessionProviders.get(sessionId);
88565
+ if (providerEntry) {
88566
+ console.log(`[dev-inspector] [acp] Cleaning up session-scoped provider: ${sessionId}`);
88567
+ try {
88568
+ providerEntry.provider.cleanup();
88569
+ } catch (e) {
88570
+ console.error("Error cleaning up provider:", e);
88618
88571
  }
88619
- sessionToProvider.delete(sessionId);
88572
+ sessionProviders.delete(sessionId);
88620
88573
  }
88621
88574
  res.setHeader("Content-Type", "application/json");
88622
88575
  res.end(JSON.stringify({ success: true }));
@@ -88634,7 +88587,7 @@ function setupAcpMiddleware(middlewares, serverContext, acpOptions) {
88634
88587
  * Body: { messages, agent, envVars, sessionId? }
88635
88588
  */
88636
88589
  middlewares.use("/api/acp/chat", async (req, res) => {
88637
- if (handleCors(res, req.method)) return;
88590
+ if (handleCors(req, res)) return;
88638
88591
  if (req.method !== "POST") {
88639
88592
  res.statusCode = 405;
88640
88593
  res.end("Method Not Allowed");
@@ -88646,13 +88599,9 @@ function setupAcpMiddleware(middlewares, serverContext, acpOptions) {
88646
88599
  const cwd$1 = process.cwd();
88647
88600
  let provider;
88648
88601
  let shouldCleanupProvider = true;
88649
- let existingProviderEntry;
88650
- if (sessionId) {
88651
- const agentKey = sessionToProvider.get(sessionId);
88652
- if (agentKey) existingProviderEntry = providerManager.get(agentKey);
88653
- }
88602
+ const existingProviderEntry = sessionId ? sessionProviders.get(sessionId) : void 0;
88654
88603
  if (existingProviderEntry) {
88655
- console.log(`[dev-inspector] [acp] Using existing global provider for session: ${sessionId}`);
88604
+ console.log(`[dev-inspector] [acp] Using existing session-scoped provider for session: ${sessionId}`);
88656
88605
  provider = existingProviderEntry.provider;
88657
88606
  shouldCleanupProvider = false;
88658
88607
  } else {
@@ -88682,10 +88631,9 @@ function setupAcpMiddleware(middlewares, serverContext, acpOptions) {
88682
88631
  });
88683
88632
  await provider.initSession();
88684
88633
  }
88685
- const transport = getInspectorTransport() || getActiveTransport();
88686
88634
  let mcpTools = {};
88687
- if (transport) mcpTools = await loadMcpToolsV5(transport);
88688
- else console.warn("[dev-inspector] [acp] No active MCP transport available, tools will not be loaded");
88635
+ const getTransport = () => getInspectorTransport() || getActiveTransport();
88636
+ mcpTools = await loadMcpToolsV5(getTransport);
88689
88637
  const mode = agent.acpMode ?? acpOptions?.acpMode;
88690
88638
  const model = agent.acpModel ?? acpOptions?.acpModel;
88691
88639
  const delay = agent.acpDelay ?? acpOptions?.acpDelay;
@@ -86961,14 +86961,20 @@ var ConnectionManager = class {
86961
86961
  //#endregion
86962
86962
  //#region src/utils/cors.ts
86963
86963
  /**
86964
- * Set CORS headers and handle preflight requests
86965
- * Returns true if request was handled (preflight), false otherwise
86964
+ * Set CORS headers and handle preflight requests.
86965
+ *
86966
+ * Uses the browser's requested headers (Access-Control-Request-Headers) when present
86967
+ * to avoid mismatches that can break CORS preflight (e.g. 'user-agent').
86968
+ *
86969
+ * Returns true if request was handled (preflight), false otherwise.
86966
86970
  */
86967
- function handleCors(res, method) {
86971
+ function handleCors(req, res) {
86968
86972
  res.setHeader("Access-Control-Allow-Origin", "*");
86969
86973
  res.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS");
86970
- res.setHeader("Access-Control-Allow-Headers", "Content-Type, mcp-session-id, mcp-protocol-version");
86971
- if (method === "OPTIONS") {
86974
+ const requested = req.headers["access-control-request-headers"];
86975
+ const requestedValue = Array.isArray(requested) ? requested.join(", ") : requested;
86976
+ res.setHeader("Access-Control-Allow-Headers", requestedValue ?? "Content-Type, mcp-session-id, mcp-protocol-version");
86977
+ if (req.method === "OPTIONS") {
86972
86978
  res.statusCode = 204;
86973
86979
  res.end();
86974
86980
  return true;
@@ -86994,7 +87000,7 @@ async function setupMcpMiddleware(middlewares, serverContext) {
86994
87000
  middlewares.use(async (req, res, next$1) => {
86995
87001
  const url = req.url || "";
86996
87002
  if (url.startsWith("/__mcp__")) {
86997
- if (handleCors(res, req.method)) return;
87003
+ if (handleCors(req, res)) return;
86998
87004
  }
86999
87005
  if (url.startsWith("/__mcp__") && !url.startsWith("/__mcp__/sse") && !url.startsWith("/__mcp__/messages")) {
87000
87006
  if (req.method === "POST") await handleStreamableHttpPost(req, res, serverContext, connectionManager);
@@ -87231,7 +87237,7 @@ function setupInspectorMiddleware(middlewares, config) {
87231
87237
  let filesChecked = false;
87232
87238
  middlewares.use((req, res, next$1) => {
87233
87239
  if (req.url?.startsWith("/__inspector__")) {
87234
- if (handleCors(res, req.method)) return;
87240
+ if (handleCors(req, res)) return;
87235
87241
  }
87236
87242
  if (!filesChecked) {
87237
87243
  cachedScript = getInspectorScript();
@@ -88397,15 +88403,10 @@ function checkCommandExists(command) {
88397
88403
  }
88398
88404
  }
88399
88405
  /**
88400
- * Provider manager - stores one provider per agent config
88401
- * Key: agentKey (command:args), Value: ProviderEntry
88402
- */
88403
- const providerManager = /* @__PURE__ */ new Map();
88404
- /**
88405
- * Session to provider mapping for quick lookup
88406
- * Key: sessionId, Value: agentKey
88406
+ * Session-scoped provider manager
88407
+ * Key: sessionId, Value: ProviderEntry
88407
88408
  */
88408
- const sessionToProvider = /* @__PURE__ */ new Map();
88409
+ const sessionProviders = /* @__PURE__ */ new Map();
88409
88410
  /**
88410
88411
  * Generate a unique key for an agent configuration
88411
88412
  */
@@ -88439,15 +88440,22 @@ function callMcpMethodViaTransport(transport, method, params) {
88439
88440
  /**
88440
88441
  * Load MCP tools from transport in AI SDK v5 format
88441
88442
  */
88442
- async function loadMcpToolsV5(transport) {
88443
+ async function loadMcpToolsV5(getTransport) {
88443
88444
  const tools = {};
88444
- const { tools: toolsListFromServer } = await callMcpMethodViaTransport(transport, "tools/list");
88445
+ const initialTransport = getTransport();
88446
+ if (!initialTransport) {
88447
+ console.warn("[dev-inspector] [acp] No active MCP transport available, tools will not be loaded");
88448
+ return tools;
88449
+ }
88450
+ const { tools: toolsListFromServer } = await callMcpMethodViaTransport(initialTransport, "tools/list");
88445
88451
  for (const toolInfo of toolsListFromServer) {
88446
88452
  const toolName = toolInfo.name;
88447
88453
  tools[toolName] = tool({
88448
88454
  description: toolInfo.description,
88449
88455
  inputSchema: jsonSchema(toolInfo.inputSchema),
88450
88456
  execute: async (args) => {
88457
+ const transport = getTransport();
88458
+ if (!transport) throw new Error("No active MCP transport available");
88451
88459
  console.log(`[dev-inspector] [acp] Executing MCP tool: ${toolName}`);
88452
88460
  const result = await callMcpMethodViaTransport(transport, "tools/call", {
88453
88461
  name: toolName,
@@ -88499,7 +88507,7 @@ function setupAcpMiddleware(middlewares, serverContext, acpOptions) {
88499
88507
  * Returns: { sessionId }
88500
88508
  */
88501
88509
  middlewares.use("/api/acp/init-session", async (req, res) => {
88502
- if (handleCors(res, req.method)) return;
88510
+ if (handleCors(req, res)) return;
88503
88511
  if (req.method !== "POST") {
88504
88512
  res.statusCode = 405;
88505
88513
  res.end("Method Not Allowed");
@@ -88510,105 +88518,58 @@ function setupAcpMiddleware(middlewares, serverContext, acpOptions) {
88510
88518
  const { agent, envVars } = JSON.parse(body);
88511
88519
  const cwd$1 = process.cwd();
88512
88520
  const agentKey = getAgentKey(agent.command, agent.args);
88513
- console.log(`[dev-inspector] [acp] Requesting session for agent: ${agent.name} (${agentKey})`);
88514
- let providerEntry = providerManager.get(agentKey);
88515
- let sessionId = "";
88516
- if (providerEntry) {
88517
- if (providerEntry.sessions.size > 0) {
88518
- const firstSession = providerEntry.sessions.values().next().value;
88519
- if (firstSession) {
88520
- sessionId = firstSession.sessionId;
88521
- console.log(`[dev-inspector] [acp] Reusing existing session: ${sessionId} for ${agent.name}`);
88522
- }
88523
- }
88524
- if (!sessionId && providerEntry.initializationPromise) {
88525
- console.log(`[dev-inspector] [acp] Joining pending initialization for ${agent.name}`);
88526
- try {
88527
- sessionId = await providerEntry.initializationPromise;
88528
- } catch (e) {
88529
- throw e;
88530
- }
88531
- }
88521
+ console.log(`[dev-inspector] [acp] Creating request-scoped session for agent: ${agent.name} (${agentKey})`);
88522
+ if (!checkCommandExists(agent.command)) {
88523
+ const hints = [`Agent "${agent.name}" command not found: "${agent.command}"`];
88524
+ if (agent.installCommand) hints.push(`Install with: ${agent.installCommand}`);
88525
+ if (agent.configHint) hints.push(agent.configHint);
88526
+ if (agent.configLink) hints.push(`Documentation: ${agent.configLink}`);
88527
+ console.error(`\n${hints.join("\n")}\n`);
88528
+ res.statusCode = 400;
88529
+ res.end(JSON.stringify({ error: hints.join("\n") }));
88530
+ return;
88532
88531
  }
88533
- if (!sessionId) {
88534
- let provider;
88535
- if (providerEntry) {
88536
- console.log(`[dev-inspector] [acp] Reusing existing provider for ${agent.name}`);
88537
- provider = providerEntry.provider;
88538
- } else {
88539
- if (!checkCommandExists(agent.command)) {
88540
- const hints = [`Agent "${agent.name}" command not found: "${agent.command}"`];
88541
- if (agent.installCommand) hints.push(`Install with: ${agent.installCommand}`);
88542
- if (agent.configHint) hints.push(agent.configHint);
88543
- if (agent.configLink) hints.push(`Documentation: ${agent.configLink}`);
88544
- console.error(`\n${hints.join("\n")}\n`);
88545
- return;
88546
- }
88547
- console.log(`[dev-inspector] [acp] Creating new global provider for ${agent.name}`);
88548
- let command = agent.command;
88549
- let args = agent.args;
88550
- if (agent.npmPackage) {
88551
- const binPath = resolveNpmPackageBin(agent.npmPackage);
88552
- if (binPath) {
88553
- command = binPath;
88554
- args = agent.npmArgs || [];
88555
- console.log(`[dev-inspector] [acp] Using resolved npm package: ${agent.npmPackage}`);
88556
- } else console.log(`[dev-inspector] [acp] Failed to resolve npm package, falling back to: ${agent.command}`);
88557
- }
88558
- provider = createACPProvider({
88559
- command,
88560
- args,
88561
- env: {
88562
- ...process.env,
88563
- ...envVars
88564
- },
88565
- session: {
88566
- cwd: cwd$1,
88567
- mcpServers: []
88568
- },
88569
- authMethodId: agent.authMethodId,
88570
- persistSession: true
88571
- });
88572
- providerEntry = {
88573
- provider,
88574
- agentKey,
88575
- sessions: /* @__PURE__ */ new Map(),
88576
- createdAt: Date.now(),
88577
- initializationPromise: void 0
88578
- };
88579
- providerManager.set(agentKey, providerEntry);
88580
- }
88581
- console.log(`[dev-inspector] [acp] Spawning new process/session for ${agent.name}`);
88582
- const initPromise = (async () => {
88583
- const transport = getInspectorTransport() || getActiveTransport();
88584
- let initialTools = {};
88585
- if (transport) try {
88586
- const rawTools = await loadMcpToolsV5(transport);
88587
- initialTools = acpTools(rawTools);
88588
- console.log(`[dev-inspector] [acp] Pre-loading ${Object.keys(rawTools).length} tools for session init`);
88589
- } catch (e) {
88590
- console.warn("[dev-inspector] [acp] Failed to pre-load tools:", e);
88591
- }
88592
- const sid = (await provider.initSession(initialTools)).sessionId || `session-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
88593
- if (providerEntry) {
88594
- providerEntry.sessions.set(sid, {
88595
- sessionId: sid,
88596
- createdAt: Date.now()
88597
- });
88598
- providerEntry.initializationPromise = void 0;
88599
- }
88600
- sessionToProvider.set(sid, agentKey);
88601
- return sid;
88602
- })();
88603
- if (providerEntry) providerEntry.initializationPromise = initPromise;
88604
- try {
88605
- sessionId = await initPromise;
88606
- console.log(`[dev-inspector] [acp] Session initialized: ${sessionId}`);
88607
- } catch (error) {
88608
- if (providerEntry) providerEntry.initializationPromise = void 0;
88609
- throw error;
88532
+ let command = agent.command;
88533
+ let args = agent.args;
88534
+ if (agent.npmPackage) {
88535
+ const binPath = resolveNpmPackageBin(agent.npmPackage);
88536
+ if (binPath) {
88537
+ command = binPath;
88538
+ args = agent.npmArgs || [];
88539
+ console.log(`[dev-inspector] [acp] Using resolved npm package: ${agent.npmPackage}`);
88540
+ } else console.log(`[dev-inspector] [acp] Failed to resolve npm package, falling back to: ${agent.command}`);
88541
+ }
88542
+ const provider = createACPProvider({
88543
+ command,
88544
+ args,
88545
+ env: {
88546
+ ...process.env,
88547
+ ...envVars
88548
+ },
88549
+ session: {
88550
+ cwd: cwd$1,
88551
+ mcpServers: []
88552
+ },
88553
+ authMethodId: agent.authMethodId
88554
+ });
88555
+ console.log(`[dev-inspector] [acp] Spawning new process/session for ${agent.name}`);
88556
+ const getTransport = () => getInspectorTransport() || getActiveTransport();
88557
+ let initialTools = {};
88558
+ try {
88559
+ const rawTools = await loadMcpToolsV5(getTransport);
88560
+ if (Object.keys(rawTools).length > 0) {
88561
+ initialTools = acpTools(rawTools);
88562
+ console.log(`[dev-inspector] [acp] Pre-loading ${Object.keys(rawTools).length} tools for session init`);
88610
88563
  }
88564
+ } catch (e) {
88565
+ console.warn("[dev-inspector] [acp] Failed to pre-load tools:", e);
88611
88566
  }
88567
+ const sessionId = (await provider.initSession(initialTools)).sessionId || `session-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
88568
+ sessionProviders.set(sessionId, {
88569
+ provider,
88570
+ createdAt: Date.now()
88571
+ });
88572
+ console.log(`[dev-inspector] [acp] Session initialized: ${sessionId}`);
88612
88573
  res.setHeader("Content-Type", "application/json");
88613
88574
  res.end(JSON.stringify({ sessionId }));
88614
88575
  } catch (error) {
@@ -88626,7 +88587,7 @@ function setupAcpMiddleware(middlewares, serverContext, acpOptions) {
88626
88587
  * Body: { sessionId }
88627
88588
  */
88628
88589
  middlewares.use("/api/acp/cleanup-session", async (req, res) => {
88629
- if (handleCors(res, req.method)) return;
88590
+ if (handleCors(req, res)) return;
88630
88591
  if (req.method !== "POST") {
88631
88592
  res.statusCode = 405;
88632
88593
  res.end("Method Not Allowed");
@@ -88635,23 +88596,15 @@ function setupAcpMiddleware(middlewares, serverContext, acpOptions) {
88635
88596
  try {
88636
88597
  const body = await readBody(req);
88637
88598
  const { sessionId } = JSON.parse(body);
88638
- const agentKey = sessionToProvider.get(sessionId);
88639
- if (agentKey) {
88640
- const providerEntry = providerManager.get(agentKey);
88641
- if (providerEntry) {
88642
- console.log(`[dev-inspector] [acp] Cleaning up session: ${sessionId} (Provider sessions left: ${providerEntry.sessions.size - 1})`);
88643
- providerEntry.sessions.delete(sessionId);
88644
- if (providerEntry.sessions.size === 0) {
88645
- console.log(`[dev-inspector] [acp] No active sessions for ${agentKey}, cleaning up provider`);
88646
- try {
88647
- providerEntry.provider.cleanup();
88648
- } catch (e) {
88649
- console.error("Error cleaning up provider:", e);
88650
- }
88651
- providerManager.delete(agentKey);
88652
- }
88599
+ const providerEntry = sessionProviders.get(sessionId);
88600
+ if (providerEntry) {
88601
+ console.log(`[dev-inspector] [acp] Cleaning up session-scoped provider: ${sessionId}`);
88602
+ try {
88603
+ providerEntry.provider.cleanup();
88604
+ } catch (e) {
88605
+ console.error("Error cleaning up provider:", e);
88653
88606
  }
88654
- sessionToProvider.delete(sessionId);
88607
+ sessionProviders.delete(sessionId);
88655
88608
  }
88656
88609
  res.setHeader("Content-Type", "application/json");
88657
88610
  res.end(JSON.stringify({ success: true }));
@@ -88669,7 +88622,7 @@ function setupAcpMiddleware(middlewares, serverContext, acpOptions) {
88669
88622
  * Body: { messages, agent, envVars, sessionId? }
88670
88623
  */
88671
88624
  middlewares.use("/api/acp/chat", async (req, res) => {
88672
- if (handleCors(res, req.method)) return;
88625
+ if (handleCors(req, res)) return;
88673
88626
  if (req.method !== "POST") {
88674
88627
  res.statusCode = 405;
88675
88628
  res.end("Method Not Allowed");
@@ -88681,13 +88634,9 @@ function setupAcpMiddleware(middlewares, serverContext, acpOptions) {
88681
88634
  const cwd$1 = process.cwd();
88682
88635
  let provider;
88683
88636
  let shouldCleanupProvider = true;
88684
- let existingProviderEntry;
88685
- if (sessionId) {
88686
- const agentKey = sessionToProvider.get(sessionId);
88687
- if (agentKey) existingProviderEntry = providerManager.get(agentKey);
88688
- }
88637
+ const existingProviderEntry = sessionId ? sessionProviders.get(sessionId) : void 0;
88689
88638
  if (existingProviderEntry) {
88690
- console.log(`[dev-inspector] [acp] Using existing global provider for session: ${sessionId}`);
88639
+ console.log(`[dev-inspector] [acp] Using existing session-scoped provider for session: ${sessionId}`);
88691
88640
  provider = existingProviderEntry.provider;
88692
88641
  shouldCleanupProvider = false;
88693
88642
  } else {
@@ -88717,10 +88666,9 @@ function setupAcpMiddleware(middlewares, serverContext, acpOptions) {
88717
88666
  });
88718
88667
  await provider.initSession();
88719
88668
  }
88720
- const transport = getInspectorTransport() || getActiveTransport();
88721
88669
  let mcpTools = {};
88722
- if (transport) mcpTools = await loadMcpToolsV5(transport);
88723
- else console.warn("[dev-inspector] [acp] No active MCP transport available, tools will not be loaded");
88670
+ const getTransport = () => getInspectorTransport() || getActiveTransport();
88671
+ mcpTools = await loadMcpToolsV5(getTransport);
88724
88672
  const mode = agent.acpMode ?? acpOptions?.acpMode;
88725
88673
  const model = agent.acpModel ?? acpOptions?.acpModel;
88726
88674
  const delay = agent.acpDelay ?? acpOptions?.acpDelay;
package/dist/index.cjs CHANGED
@@ -17,22 +17,64 @@ let _code_inspector_core = require("@code-inspector/core");
17
17
 
18
18
  //#region src/utils/browser-launcher.ts
19
19
  var browser_launcher_exports = /* @__PURE__ */ require_chunk.__export({ launchBrowserWithDevTools: () => launchBrowserWithDevTools });
20
+ async function closeSharedClient(reason) {
21
+ const clientToClose = sharedClient;
22
+ sharedClient = null;
23
+ sharedSseUrl = null;
24
+ connectPromise = null;
25
+ if (!clientToClose) return;
26
+ try {
27
+ console.log(`[dev-inspector] Closing shared browser client: ${reason}`);
28
+ await clientToClose.close();
29
+ } catch {}
30
+ }
31
+ function registerProcessCleanupOnce() {
32
+ if (cleanupRegistered) return;
33
+ cleanupRegistered = true;
34
+ const requestCleanupThenReraise = (signal) => {
35
+ closeSharedClient(signal).finally(() => {
36
+ try {
37
+ process.kill(process.pid, signal);
38
+ } catch {
39
+ process.exit(1);
40
+ }
41
+ });
42
+ };
43
+ process.once("beforeExit", () => {
44
+ closeSharedClient("beforeExit");
45
+ });
46
+ process.once("SIGINT", () => requestCleanupThenReraise("SIGINT"));
47
+ process.once("SIGTERM", () => requestCleanupThenReraise("SIGTERM"));
48
+ process.once("SIGHUP", () => requestCleanupThenReraise("SIGHUP"));
49
+ }
50
+ async function getOrCreateClient(sseUrl) {
51
+ if (sharedClient && sharedSseUrl === sseUrl) return sharedClient;
52
+ if (connectPromise && sharedSseUrl === sseUrl) return connectPromise;
53
+ if (sharedClient && sharedSseUrl !== sseUrl) await closeSharedClient("sseUrl-changed");
54
+ sharedSseUrl = sseUrl;
55
+ sharedClient = new _modelcontextprotocol_sdk_client_index_js.Client({
56
+ name: "dev-inspector-auto-browser",
57
+ version: "1.0.0"
58
+ });
59
+ const transport = new _modelcontextprotocol_sdk_client_sse_js.SSEClientTransport(new URL(sseUrl));
60
+ connectPromise = sharedClient.connect(transport).then(() => sharedClient).catch(async (error) => {
61
+ await closeSharedClient("connect-failed");
62
+ throw error;
63
+ }).finally(() => {
64
+ connectPromise = null;
65
+ });
66
+ registerProcessCleanupOnce();
67
+ return connectPromise;
68
+ }
20
69
  /**
21
70
  * Launch browser via Chrome DevTools MCP
22
71
  * Uses MCP Client to connect to the MCP server endpoint
23
72
  */
24
73
  async function launchBrowserWithDevTools(options) {
25
74
  const { url, serverContext } = options;
26
- const sseUrl = `http://${serverContext.host === "0.0.0.0" ? "localhost" : serverContext.host || "localhost"}:${serverContext.port || 5173}/__mcp__/sse?clientId=temp-browser-launcher`;
27
- let client = null;
75
+ const sseUrl = `http://${serverContext.host === "0.0.0.0" ? "localhost" : serverContext.host || "localhost"}:${serverContext.port || 5173}/__mcp__/sse?clientId=browser-launcher-${process.pid}`;
28
76
  try {
29
- client = new _modelcontextprotocol_sdk_client_index_js.Client({
30
- name: "dev-inspector-auto-browser",
31
- version: "1.0.0"
32
- });
33
- const transport = new _modelcontextprotocol_sdk_client_sse_js.SSEClientTransport(new URL(sseUrl));
34
- await client.connect(transport);
35
- await client.callTool({
77
+ await (await getOrCreateClient(sseUrl)).callTool({
36
78
  name: "chrome_devtools",
37
79
  arguments: {
38
80
  useTool: "chrome_navigate_page",
@@ -40,16 +82,19 @@ async function launchBrowserWithDevTools(options) {
40
82
  chrome_navigate_page: { url }
41
83
  }
42
84
  });
43
- await new Promise((r) => setTimeout(r, 1e3));
44
85
  return true;
45
86
  } catch (error) {
46
87
  console.error(`[dev-inspector] ⚠️ Failed to auto-open browser:`, error instanceof Error ? error.message : String(error));
47
88
  return false;
48
- } finally {
49
- await client?.close().catch(() => {});
50
89
  }
51
90
  }
52
- var init_browser_launcher = require_chunk.__esmMin((() => {}));
91
+ var sharedClient, sharedSseUrl, connectPromise, cleanupRegistered;
92
+ var init_browser_launcher = require_chunk.__esmMin((() => {
93
+ sharedClient = null;
94
+ sharedSseUrl = null;
95
+ connectPromise = null;
96
+ cleanupRegistered = false;
97
+ }));
53
98
 
54
99
  //#endregion
55
100
  //#region src/utils/create-plugin.ts
@@ -59,9 +104,23 @@ const createDevInspectorPlugin = (name, transformFactory) => {
59
104
  const enabled = options.enabled ?? process.env.NODE_ENV !== "production";
60
105
  const virtualModuleName = options.virtualModuleName ?? "virtual:dev-inspector-mcp";
61
106
  const webpackModuleName = virtualModuleName.replace("virtual:", "");
107
+ let viteCommand;
62
108
  let resolvedHost = options.host || "localhost";
63
109
  let resolvedPort = options.port || 5173;
64
- if (!enabled) return { name };
110
+ const transformImpl = transformFactory(options);
111
+ const transform = (code, id) => {
112
+ if (!enabled) return null;
113
+ if (viteCommand && viteCommand !== "serve") return null;
114
+ return transformImpl(code, id);
115
+ };
116
+ const createNoopVirtualModule = () => {
117
+ return `
118
+ // Production build - no-op
119
+ export function registerInspectorTool(_tool) {
120
+ // No-op in production
121
+ }
122
+ `;
123
+ };
65
124
  return {
66
125
  name,
67
126
  enforce: "pre",
@@ -69,7 +128,9 @@ const createDevInspectorPlugin = (name, transformFactory) => {
69
128
  if (id === virtualModuleName || id === webpackModuleName) return "\0" + virtualModuleName;
70
129
  },
71
130
  load(id) {
72
- if (id === "\0" + virtualModuleName) return `
131
+ if (id === "\0" + virtualModuleName) {
132
+ if (!enabled || viteCommand === "build") return createNoopVirtualModule();
133
+ return `
73
134
  // Development-only code - removed in production builds
74
135
 
75
136
  // Global tools registry
@@ -83,9 +144,13 @@ if (typeof window !== 'undefined') {
83
144
 
84
145
  /**
85
146
  * Register a custom tool for the inspector
147
+ * Only registers in development mode
86
148
  */
87
149
  export function registerInspectorTool(tool) {
150
+ // Skip in production (when bundler replaces import.meta.env.DEV with false)
151
+ if (!import.meta.env.DEV) return;
88
152
  if (typeof window === 'undefined') return;
153
+
89
154
  window.__INSPECTOR_TOOLS__ = window.__INSPECTOR_TOOLS__ || [];
90
155
  window.__INSPECTOR_TOOLS__.push(tool);
91
156
  }
@@ -122,10 +187,14 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
122
187
  }
123
188
  }
124
189
  `;
190
+ }
125
191
  },
126
- transform: transformFactory(options),
192
+ transform,
127
193
  vite: {
128
- apply: "serve",
194
+ apply(_config, env) {
195
+ viteCommand = env.command;
196
+ return true;
197
+ },
129
198
  configResolved(config) {
130
199
  const viteHost = config.server.host;
131
200
  resolvedHost = options.host ?? (typeof viteHost === "string" ? viteHost : viteHost === true ? "0.0.0.0" : "localhost");
@@ -135,6 +204,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
135
204
  transformIndexHtml: {
136
205
  order: "pre",
137
206
  handler(html, ctx) {
207
+ if (!enabled) return html;
208
+ if (viteCommand !== "serve") return html;
138
209
  if (!(options.autoInject ?? true)) return html;
139
210
  const server = ctx.server;
140
211
  const viteHost = server?.config.server.host;
@@ -169,6 +240,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
169
240
  }
170
241
  },
171
242
  async configureServer(server) {
243
+ if (!enabled) return;
172
244
  const viteHost = server.config.server.host;
173
245
  const serverContext = {
174
246
  host: options.host ?? (typeof viteHost === "string" ? viteHost : viteHost === true ? "0.0.0.0" : "localhost"),
@@ -279,7 +351,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
279
351
  });
280
352
  },
281
353
  rollup: {},
282
- esbuild: { setup(build) {} }
354
+ esbuild: { setup(_build) {} }
283
355
  };
284
356
  });
285
357
  };
package/dist/index.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import * as unplugin0 from "unplugin";
1
+ import * as unplugin1 from "unplugin";
2
2
 
3
3
  //#region src/utils/config-updater.d.ts
4
4
  type EditorId = "cursor" | "vscode" | "windsurf" | "claude-code" | "antigravity";
@@ -166,10 +166,10 @@ interface DevInspectorOptions extends McpConfigOptions, AcpOptions {
166
166
  }
167
167
  //#endregion
168
168
  //#region src/core.d.ts
169
- declare const unplugin: unplugin0.UnpluginInstance<DevInspectorOptions | undefined, boolean>;
169
+ declare const unplugin: unplugin1.UnpluginInstance<DevInspectorOptions | undefined, boolean>;
170
170
  //#endregion
171
171
  //#region src/core-external.d.ts
172
- declare const unpluginExternal: unplugin0.UnpluginInstance<DevInspectorOptions | undefined, boolean>;
172
+ declare const unpluginExternal: unplugin1.UnpluginInstance<DevInspectorOptions | undefined, boolean>;
173
173
  //#endregion
174
174
  //#region src/turbopack.d.ts
175
175
  interface TurbopackDevInspectorOptions extends DevInspectorOptions {
@@ -194,7 +194,7 @@ interface TurbopackDevInspectorOptions extends DevInspectorOptions {
194
194
  declare function turbopackDevInspector(options?: TurbopackDevInspectorOptions): any;
195
195
  //#endregion
196
196
  //#region src/index.d.ts
197
- declare const external: unplugin0.UnpluginInstance<DevInspectorOptions | undefined, boolean>;
197
+ declare const external: unplugin1.UnpluginInstance<DevInspectorOptions | undefined, boolean>;
198
198
  declare module "virtual:dev-inspector-mcp" {}
199
199
  //#endregion
200
200
  export { type CustomEditorConfig, type DevInspectorOptions, type EditorId, type McpConfigOptions, type TurbopackDevInspectorOptions, unplugin as default, unplugin, external, turbopackDevInspector, unpluginExternal };
package/dist/index.js CHANGED
@@ -13,22 +13,64 @@ import { transformCode } from "@code-inspector/core";
13
13
 
14
14
  //#region src/utils/browser-launcher.ts
15
15
  var browser_launcher_exports = /* @__PURE__ */ __export({ launchBrowserWithDevTools: () => launchBrowserWithDevTools });
16
+ async function closeSharedClient(reason) {
17
+ const clientToClose = sharedClient;
18
+ sharedClient = null;
19
+ sharedSseUrl = null;
20
+ connectPromise = null;
21
+ if (!clientToClose) return;
22
+ try {
23
+ console.log(`[dev-inspector] Closing shared browser client: ${reason}`);
24
+ await clientToClose.close();
25
+ } catch {}
26
+ }
27
+ function registerProcessCleanupOnce() {
28
+ if (cleanupRegistered) return;
29
+ cleanupRegistered = true;
30
+ const requestCleanupThenReraise = (signal) => {
31
+ closeSharedClient(signal).finally(() => {
32
+ try {
33
+ process.kill(process.pid, signal);
34
+ } catch {
35
+ process.exit(1);
36
+ }
37
+ });
38
+ };
39
+ process.once("beforeExit", () => {
40
+ closeSharedClient("beforeExit");
41
+ });
42
+ process.once("SIGINT", () => requestCleanupThenReraise("SIGINT"));
43
+ process.once("SIGTERM", () => requestCleanupThenReraise("SIGTERM"));
44
+ process.once("SIGHUP", () => requestCleanupThenReraise("SIGHUP"));
45
+ }
46
+ async function getOrCreateClient(sseUrl) {
47
+ if (sharedClient && sharedSseUrl === sseUrl) return sharedClient;
48
+ if (connectPromise && sharedSseUrl === sseUrl) return connectPromise;
49
+ if (sharedClient && sharedSseUrl !== sseUrl) await closeSharedClient("sseUrl-changed");
50
+ sharedSseUrl = sseUrl;
51
+ sharedClient = new Client({
52
+ name: "dev-inspector-auto-browser",
53
+ version: "1.0.0"
54
+ });
55
+ const transport = new SSEClientTransport(new URL(sseUrl));
56
+ connectPromise = sharedClient.connect(transport).then(() => sharedClient).catch(async (error) => {
57
+ await closeSharedClient("connect-failed");
58
+ throw error;
59
+ }).finally(() => {
60
+ connectPromise = null;
61
+ });
62
+ registerProcessCleanupOnce();
63
+ return connectPromise;
64
+ }
16
65
  /**
17
66
  * Launch browser via Chrome DevTools MCP
18
67
  * Uses MCP Client to connect to the MCP server endpoint
19
68
  */
20
69
  async function launchBrowserWithDevTools(options) {
21
70
  const { url, serverContext } = options;
22
- const sseUrl = `http://${serverContext.host === "0.0.0.0" ? "localhost" : serverContext.host || "localhost"}:${serverContext.port || 5173}/__mcp__/sse?clientId=temp-browser-launcher`;
23
- let client = null;
71
+ const sseUrl = `http://${serverContext.host === "0.0.0.0" ? "localhost" : serverContext.host || "localhost"}:${serverContext.port || 5173}/__mcp__/sse?clientId=browser-launcher-${process.pid}`;
24
72
  try {
25
- client = new Client({
26
- name: "dev-inspector-auto-browser",
27
- version: "1.0.0"
28
- });
29
- const transport = new SSEClientTransport(new URL(sseUrl));
30
- await client.connect(transport);
31
- await client.callTool({
73
+ await (await getOrCreateClient(sseUrl)).callTool({
32
74
  name: "chrome_devtools",
33
75
  arguments: {
34
76
  useTool: "chrome_navigate_page",
@@ -36,16 +78,19 @@ async function launchBrowserWithDevTools(options) {
36
78
  chrome_navigate_page: { url }
37
79
  }
38
80
  });
39
- await new Promise((r) => setTimeout(r, 1e3));
40
81
  return true;
41
82
  } catch (error) {
42
83
  console.error(`[dev-inspector] ⚠️ Failed to auto-open browser:`, error instanceof Error ? error.message : String(error));
43
84
  return false;
44
- } finally {
45
- await client?.close().catch(() => {});
46
85
  }
47
86
  }
48
- var init_browser_launcher = __esmMin((() => {}));
87
+ var sharedClient, sharedSseUrl, connectPromise, cleanupRegistered;
88
+ var init_browser_launcher = __esmMin((() => {
89
+ sharedClient = null;
90
+ sharedSseUrl = null;
91
+ connectPromise = null;
92
+ cleanupRegistered = false;
93
+ }));
49
94
 
50
95
  //#endregion
51
96
  //#region src/utils/create-plugin.ts
@@ -55,9 +100,23 @@ const createDevInspectorPlugin = (name, transformFactory) => {
55
100
  const enabled = options.enabled ?? process.env.NODE_ENV !== "production";
56
101
  const virtualModuleName = options.virtualModuleName ?? "virtual:dev-inspector-mcp";
57
102
  const webpackModuleName = virtualModuleName.replace("virtual:", "");
103
+ let viteCommand;
58
104
  let resolvedHost = options.host || "localhost";
59
105
  let resolvedPort = options.port || 5173;
60
- if (!enabled) return { name };
106
+ const transformImpl = transformFactory(options);
107
+ const transform = (code, id) => {
108
+ if (!enabled) return null;
109
+ if (viteCommand && viteCommand !== "serve") return null;
110
+ return transformImpl(code, id);
111
+ };
112
+ const createNoopVirtualModule = () => {
113
+ return `
114
+ // Production build - no-op
115
+ export function registerInspectorTool(_tool) {
116
+ // No-op in production
117
+ }
118
+ `;
119
+ };
61
120
  return {
62
121
  name,
63
122
  enforce: "pre",
@@ -65,7 +124,9 @@ const createDevInspectorPlugin = (name, transformFactory) => {
65
124
  if (id === virtualModuleName || id === webpackModuleName) return "\0" + virtualModuleName;
66
125
  },
67
126
  load(id) {
68
- if (id === "\0" + virtualModuleName) return `
127
+ if (id === "\0" + virtualModuleName) {
128
+ if (!enabled || viteCommand === "build") return createNoopVirtualModule();
129
+ return `
69
130
  // Development-only code - removed in production builds
70
131
 
71
132
  // Global tools registry
@@ -79,9 +140,13 @@ if (typeof window !== 'undefined') {
79
140
 
80
141
  /**
81
142
  * Register a custom tool for the inspector
143
+ * Only registers in development mode
82
144
  */
83
145
  export function registerInspectorTool(tool) {
146
+ // Skip in production (when bundler replaces import.meta.env.DEV with false)
147
+ if (!import.meta.env.DEV) return;
84
148
  if (typeof window === 'undefined') return;
149
+
85
150
  window.__INSPECTOR_TOOLS__ = window.__INSPECTOR_TOOLS__ || [];
86
151
  window.__INSPECTOR_TOOLS__.push(tool);
87
152
  }
@@ -118,10 +183,14 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
118
183
  }
119
184
  }
120
185
  `;
186
+ }
121
187
  },
122
- transform: transformFactory(options),
188
+ transform,
123
189
  vite: {
124
- apply: "serve",
190
+ apply(_config, env) {
191
+ viteCommand = env.command;
192
+ return true;
193
+ },
125
194
  configResolved(config) {
126
195
  const viteHost = config.server.host;
127
196
  resolvedHost = options.host ?? (typeof viteHost === "string" ? viteHost : viteHost === true ? "0.0.0.0" : "localhost");
@@ -131,6 +200,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
131
200
  transformIndexHtml: {
132
201
  order: "pre",
133
202
  handler(html, ctx) {
203
+ if (!enabled) return html;
204
+ if (viteCommand !== "serve") return html;
134
205
  if (!(options.autoInject ?? true)) return html;
135
206
  const server = ctx.server;
136
207
  const viteHost = server?.config.server.host;
@@ -165,6 +236,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
165
236
  }
166
237
  },
167
238
  async configureServer(server) {
239
+ if (!enabled) return;
168
240
  const viteHost = server.config.server.host;
169
241
  const serverContext = {
170
242
  host: options.host ?? (typeof viteHost === "string" ? viteHost : viteHost === true ? "0.0.0.0" : "localhost"),
@@ -275,7 +347,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
275
347
  });
276
348
  },
277
349
  rollup: {},
278
- esbuild: { setup(build) {} }
350
+ esbuild: { setup(_build) {} }
279
351
  };
280
352
  });
281
353
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mcpc-tech/unplugin-dev-inspector-mcp",
3
- "version": "0.0.39",
3
+ "version": "0.0.41",
4
4
  "description": "Universal dev inspector plugin for React/Vue - inspect component sources and API calls in any bundler",
5
5
  "type": "module",
6
6
  "license": "MIT",