auto-webmcp 0.3.15 → 0.3.17

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.
@@ -1,2 +1,2 @@
1
- "use strict";var AutoWebMCP=(()=>{var W=Object.defineProperty;var De=Object.getOwnPropertyDescriptor;var We=Object.getOwnPropertyNames;var Je=Object.prototype.hasOwnProperty;var je=(e,t)=>()=>(e&&(t=e(e=0)),t);var re=(e,t)=>{for(var o in t)W(e,o,{get:t[o],enumerable:!0})},Ue=(e,t,o,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of We(t))!Je.call(e,r)&&r!==o&&W(e,r,{get:()=>t[r],enumerable:!(n=De(t,r))||n.enumerable});return e};var Ve=e=>Ue(W({},"__esModule",{value:!0}),e);var He={};re(He,{getAllRegisteredTools:()=>K,getRegisteredToolName:()=>ft,isWebMCPSupported:()=>L,registerFormTool:()=>G,unregisterAll:()=>Y,unregisterFormTool:()=>k});function L(){return typeof navigator<"u"&&typeof navigator.modelContext<"u"}async function G(e,t,o){if(!L())return;H.get(e)&&await k(e);let r={name:t.name,description:t.description,inputSchema:t.inputSchema,execute:o};t.annotations&&Object.keys(t.annotations).length>0&&(r.annotations=t.annotations);try{await navigator.modelContext.registerTool(r)}catch{try{await navigator.modelContext.unregisterTool(t.name),await navigator.modelContext.registerTool(r)}catch{}}H.set(e,t.name)}async function k(e){if(!L())return;let t=H.get(e);if(t){try{await navigator.modelContext.unregisterTool(t)}catch{}H.delete(e)}}function ft(e){return H.get(e)}function K(){return Array.from(H.entries()).map(([e,t])=>({form:e,name:t}))}async function Y(){let e=Array.from(H.entries());await Promise.all(e.map(([t])=>k(t)))}var H,O=je(()=>{"use strict";H=new Map});var kt={};re(kt,{autoWebMCP:()=>qe});function ae(e){return{exclude:e?.exclude??[],autoSubmit:e?.autoSubmit??!1,overrides:e?.overrides??{},debug:e?.debug??!1}}var C=["textbox","combobox","checkbox","radio","switch","spinbutton","searchbox","slider"];function j(e){return e instanceof HTMLInputElement?ze(e):e instanceof HTMLTextAreaElement?{type:"string"}:e instanceof HTMLSelectElement?Ke(e):null}function ze(e){switch(e.type.toLowerCase()){case"text":case"search":case"tel":return J(e);case"email":return{...J(e),format:"email"};case"url":return{...J(e),format:"uri"};case"number":case"range":{let o={type:"number"};return e.min!==""&&(o.minimum=parseFloat(e.min)),e.max!==""&&(o.maximum=parseFloat(e.max)),o}case"date":return{type:"string",format:"date"};case"datetime-local":return{type:"string",format:"date-time"};case"time":return{type:"string",format:"time"};case"month":return{type:"string",pattern:"^\\d{4}-\\d{2}$"};case"week":return{type:"string",pattern:"^\\d{4}-W\\d{2}$"};case"color":return{type:"string",pattern:"^#[0-9a-fA-F]{6}$"};case"checkbox":return{type:"boolean"};case"radio":return{type:"string"};case"file":case"hidden":case"submit":case"reset":case"button":case"image":return null;case"password":return null;default:return{type:"string"}}}function J(e){let t={type:"string"};e.minLength>0&&(t.minLength=e.minLength),e.maxLength>0&&e.maxLength!==524288&&(t.maxLength=e.maxLength),e.pattern&&(t.pattern=e.pattern);let o=e.getAttribute("list");if(o){let n=e.ownerDocument.getElementById(o);if(n instanceof HTMLDataListElement){let r=Array.from(n.options).filter(a=>!a.disabled&&a.value.trim()!=="");r.length>0&&(t.enum=r.map(a=>a.value.trim()),t.oneOf=r.map(a=>({const:a.value.trim(),title:a.textContent?.trim()||a.value.trim()})))}}return t}var Ge=/^(select|choose|pick)\b|^--+|---/i;function se(e){return e.disabled?!0:e.value!==""?!1:Ge.test(e.text.trim())}function Ke(e){let t=[],o=[];for(let n of Array.from(e.children))if(n instanceof HTMLOptGroupElement){if(n.disabled)continue;let r=n.label?.trim()??"";for(let a of Array.from(n.children)){if(!(a instanceof HTMLOptionElement)||se(a))continue;t.push(a.value);let i={const:a.value,title:a.text.trim()||a.value};r&&(i.group=r),o.push(i)}}else if(n instanceof HTMLOptionElement){if(se(n))continue;t.push(n.value),o.push({const:n.value,title:n.text.trim()||n.value})}return t.length===0?{type:"string"}:e.multiple?{type:"array",items:{type:"string",enum:t}}:{type:"string",enum:t,oneOf:o}}function le(e,t){return Array.from(e.querySelectorAll(`input[type="checkbox"][name="${CSS.escape(t)}"]`)).map(o=>o.value).filter(o=>o!==""&&o!=="on")}function ce(e,t){return Array.from(e.querySelectorAll(`input[type="radio"][name="${CSS.escape(t)}"]`)).map(n=>n.value).filter(n=>n!=="")}function ue(e,t){return Array.from(e.querySelectorAll(`input[type="radio"][name="${CSS.escape(t)}"]`)).filter(n=>n.value!=="").map(n=>{let r=Ye(n);return{const:n.value,title:r||n.value}})}function me(e,t){switch(t){case"checkbox":case"switch":return{type:"boolean"};case"spinbutton":case"slider":{let o={type:"number"},n=e.getAttribute("aria-valuemin"),r=e.getAttribute("aria-valuemax");return n!==null&&(o.minimum=parseFloat(n)),r!==null&&(o.maximum=parseFloat(r)),o}case"combobox":{let o=e.getAttribute("aria-owns")??e.getAttribute("aria-controls");if(o){let n=document.getElementById(o);if(n){let r=Array.from(n.querySelectorAll('[role="option"]')).filter(a=>a.getAttribute("aria-disabled")!=="true");if(r.length>0){let a=r.map(l=>(l.getAttribute("data-value")??l.textContent??"").trim()).filter(Boolean),i=r.map(l=>({const:(l.getAttribute("data-value")??l.textContent??"").trim(),title:(l.textContent??"").trim()}));return{type:"string",enum:a,oneOf:i}}}}return{type:"string"}}case"textbox":case"searchbox":case"radio":default:return{type:"string"}}}function Ye(e){let t=e.closest("label");if(t){let o=t.cloneNode(!0);o.querySelectorAll("input, select, textarea, button").forEach(r=>r.remove());let n=o.textContent?.trim()??"";if(n)return n}if(e.id){let o=document.querySelector(`label[for="${CSS.escape(e.id)}"]`);if(o){let n=o.textContent?.trim()??"";if(n)return n}}return""}var pe=0;function fe(e,t){let o=t?.name??Xe(e),n=t?.description??Ze(e),{schema:r,fieldElements:a}=ot(e),i=tt(e);return{name:o,description:n,inputSchema:r,annotations:i,fieldElements:a}}function Xe(e){let t=e.getAttribute("toolname");if(t)return h(t);let o=e.dataset.webmcpName;if(o)return h(o);let n=U(e);if(n)return h(n);let r=ge(e);if(r)return h(r);if(e.id)return h(e.id);if(e.name)return h(e.name);if(e.action){let a=Qe(e.action);if(a)return h(a)}return`form_${++pe}`}function h(e){return e.toLowerCase().trim().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"").slice(0,64)||"form"}function U(e){let t=[...Array.from(e.querySelectorAll('button[type="submit"], button:not([type])')),...Array.from(e.querySelectorAll('input[type="submit"]'))];for(let o of t){let n=o instanceof HTMLInputElement?o.value.trim():o.textContent?.trim()??"";if(n&&n.length>0&&n.length<80)return n}return""}function ge(e){let t=e;for(;t;){let o=t.previousElementSibling;for(;o;){if(/^H[1-3]$/i.test(o.tagName)){let n=o.textContent?.trim()??"";if(n)return n}o=o.previousElementSibling}if(t=t.parentElement,!t||t===document.body)break}return""}function Qe(e){try{let o=new URL(e,window.location.href).pathname.split("/").filter(Boolean);return o[o.length-1]??""}catch{return""}}function Ze(e){let t=e.getAttribute("tooldescription");if(t)return t.trim();let o=e.dataset.webmcpDescription;if(o)return o.trim();let n=e.querySelector("legend");if(n?.textContent?.trim())return n.textContent.trim();let r=e.getAttribute("aria-label");if(r?.trim())return r.trim();let a=e.getAttribute("aria-describedby");if(a){let s=document.getElementById(a);if(s?.textContent?.trim())return s.textContent.trim()}let i=ge(e),l=document.title?.trim();return i&&l?`${i}: ${l}`:i||l||"Submit form"}var be=/^(search|find|look|filter|browse|view|show|check|preview|get|fetch|retrieve|load)\b/i,he=/^(delete|remove|cancel|terminate|destroy|purge|revoke|unsubscribe|deactivate)\b/i,et=/\/(delete|remove|cancel|destroy)\b/i;function tt(e){let t={};if(e.dataset.webmcpReadonly!==void 0&&(t.readOnlyHint=e.dataset.webmcpReadonly!=="false"),e.dataset.webmcpDestructive!==void 0&&(t.destructiveHint=e.dataset.webmcpDestructive!=="false"),e.dataset.webmcpIdempotent!==void 0&&(t.idempotentHint=e.dataset.webmcpIdempotent!=="false"),e.dataset.webmcpOpenworld!==void 0&&(t.openWorldHint=e.dataset.webmcpOpenworld!=="false"),t.readOnlyHint===void 0){let n=e.method.toLowerCase()==="get",r=U(e),a=r?be.test(r.trim()):!1;(n||a)&&(t.readOnlyHint=!0)}if(t.destructiveHint===void 0){let n=U(e),r=n?he.test(n.trim()):!1,a=e.action?et.test(e.action):!1;(r||a)&&(t.destructiveHint=!0)}return t.idempotentHint===void 0&&(t.readOnlyHint===!0||e.method.toLowerCase()==="get")&&(t.idempotentHint=!0),t.openWorldHint===void 0&&(t.openWorldHint=t.readOnlyHint!==!0),t.readOnlyHint===!0||t.destructiveHint===!0||t.idempotentHint===!0||t.openWorldHint===!1?t:{}}function nt(e){if(e instanceof HTMLInputElement){let t=e.type.toLowerCase();return t==="checkbox"?e.checked?!0:void 0:t==="radio"?void 0:t==="number"||t==="range"?e.value!==""?parseFloat(e.value):void 0:e.value!==""?e.value:void 0}if(e instanceof HTMLTextAreaElement)return e.value!==""?e.value:void 0;if(e instanceof HTMLSelectElement){if(e.multiple){let t=Array.from(e.options).filter(o=>o.selected).map(o=>o.value);return t.length>0?t:void 0}return e.value!==""?e.value:void 0}}function Ee(e,t=new Set){if(t.has(e))return[];t.add(e);let o=[];for(let n of Array.from(e.querySelectorAll("*")))if(n.shadowRoot){let r=Array.from(n.shadowRoot.querySelectorAll("input, textarea, select"));r.length>0&&console.log(`[auto-webmcp] shadow: found ${r.length} control(s) in ${n.tagName.toLowerCase()} shadow root:`,r.map(a=>`${a.tagName.toLowerCase()}[type=${a.type??"?"}][name="${a.name}"][id="${a.id}"]`)),o.push(...r,...Ee(n.shadowRoot,t))}return o}function ot(e){let t={},o=[],n=new Map,r=new Set,a=new Set,i=[...Array.from(e.querySelectorAll("input, textarea, select")),...Ee(e)];for(let c of i){let u=c.name,d=u||ye(c);if(!d)continue;if(c instanceof HTMLInputElement&&c.type==="radio"){if(r.has(d))continue;r.add(d)}if(c instanceof HTMLInputElement&&c.type==="checkbox"){if(a.has(d))continue;a.add(d)}let p=j(c);if(!p||!z(c))continue;p.title=xe(c);let b=we(c);b&&(p.description=b);let T=nt(c);if(T!==void 0&&(p.default=T),c instanceof HTMLInputElement&&c.type==="radio"){p.enum=ce(e,d);let m=ue(e,d);m.length>0&&(p.oneOf=m);let g=e.querySelector(`input[type="radio"][name="${CSS.escape(d)}"]:checked`);g?.value&&(p.default=g.value)}if(c instanceof HTMLInputElement&&c.type==="checkbox"){let m=le(e,d);if(m.length>1){let g={type:"array",items:{type:"string",enum:m},title:p.title};p.description&&(g.description=p.description);let f=Array.from(e.querySelectorAll(`input[type="checkbox"][name="${CSS.escape(d)}"]:checked`)).map(E=>E.value);f.length>0&&(g.default=f),t[d]=g,c.required&&o.push(d);continue}}t[d]=p,u||n.set(d,c);let w=c.required;if(!w){let m=c;for(;;){let g=m.getRootNode();if(!(g instanceof ShadowRoot))break;let f=g.host;if(f.hasAttribute("required")||f.getAttribute("aria-required")==="true"){w=!0;break}m=f}}w&&o.push(d)}let l=at(e),s=new Set;for(let{el:c,role:u,key:d,enumValues:p,enumOneOf:b}of l){if(t[d])continue;if(u==="radio"){if(s.has(d))continue;s.add(d)}let T=me(c,u);p&&p.length>0&&(T.enum=p,b&&b.length>0&&(T.oneOf=b)),T.title=st(c);let w=lt(c);w&&(T.description=w),t[d]=T,n.set(d,c),c.getAttribute("aria-required")==="true"&&o.push(d)}return{schema:{$schema:"https://json-schema.org/draft/2020-12/schema",type:"object",properties:t,required:o},fieldElements:n}}var Te=/^_r_[0-9a-z]+_$|^:[a-z0-9]+:$/i;function ye(e){let t=e;if(t.dataset.webmcpName)return h(t.dataset.webmcpName);if(e.id&&!Te.test(e.id))return h(e.id);let o=e.getAttribute("aria-label");if(o)return h(o);if((e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement)&&e.placeholder?.trim())return h(e.placeholder.trim());let n=it(e);return n||(e instanceof HTMLInputElement&&e.type!=="text"?e.type:null)}function it(e){let t=e;for(;;){let o=t.getRootNode();if(!(o instanceof ShadowRoot))break;let n=o.host,r=n.getAttribute("field-name");if(r)return console.log("[auto-webmcp] shadow host key: field-name=",r),h(r);let a=n.getAttribute("label")||n.getAttribute("aria-label");if(a)return console.log("[auto-webmcp] shadow host key: label=",a),h(a);let i=n.getAttribute("name");if(i)return console.log("[auto-webmcp] shadow host key: name=",i),h(i);t=n}return null}function rt(e){if(e.dataset.webmcpName)return h(e.dataset.webmcpName);if(e.id&&!Te.test(e.id))return h(e.id);let t=e.getAttribute("aria-label");if(t)return h(t);let o=e.getAttribute("placeholder");return o?h(o):null}function at(e){let t=C.map(s=>`[role="${s}"]`).join(", "),o=[];for(let s of Array.from(e.querySelectorAll(t))){if(s instanceof HTMLInputElement||s instanceof HTMLTextAreaElement||s instanceof HTMLSelectElement||s.getAttribute("aria-hidden")==="true"||s.hidden)continue;let c=s.getAttribute("role"),u=de(s);u&&o.push({el:s,role:c,key:u})}let n=o.filter(s=>s.role==="radio"),r=o.filter(s=>s.role!=="radio"),a=new Map,i=[];for(let s of n){let c=s.el.closest('[role="radiogroup"]');c?(a.has(c)||a.set(c,[]),a.get(c).push(s.el)):i.push(s)}let l=[];for(let[s,c]of a){let u=de(s);if(!u)continue;let d=c.map(b=>(b.getAttribute("data-value")??b.getAttribute("aria-label")??b.textContent??"").trim()).filter(Boolean),p=c.map(b=>{let T=(b.getAttribute("data-value")??b.getAttribute("aria-label")??b.textContent??"").trim(),w=(b.getAttribute("aria-label")??b.textContent??"").trim();return{const:T,title:w||T}}).filter(b=>b.const!=="");d.length>0&&l.push({el:s,role:"radio",key:u,enumValues:d,enumOneOf:p})}return[...r,...l,...i]}function de(e){let t=e;if(t.dataset?.webmcpName)return h(t.dataset.webmcpName);if(e.id)return h(e.id);let o=e.getAttribute("aria-label");if(o)return h(o);let n=e.getAttribute("aria-labelledby");if(n){let r=document.getElementById(n)?.textContent?.trim();if(r)return h(r)}return null}function st(e){let t=e;if(t.dataset?.webmcpTitle)return t.dataset.webmcpTitle;let o=e.getAttribute("aria-label");if(o)return o.trim();let n=e.getAttribute("aria-labelledby");if(n){let r=document.getElementById(n)?.textContent?.trim();if(r)return r}return e.id?V(e.id):""}function lt(e){let t=e.getAttribute("toolparamdescription");if(t)return t.trim();let o=e;if(o.dataset?.webmcpDescription)return o.dataset.webmcpDescription;let n=e.getAttribute("aria-description");if(n)return n;let r=e.getAttribute("aria-describedby");if(r){let i=document.getElementById(r)?.textContent?.trim();if(i)return i}let a=e.getAttribute("placeholder")??e.dataset?.placeholder;return a?a.trim():""}function xe(e){if("dataset"in e&&e.dataset.webmcpTitle)return e.dataset.webmcpTitle;let t=ct(e);return t||(e.name?V(e.name):e.id?V(e.id):(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement)&&e.placeholder?.trim()?e.placeholder.trim():"")}function we(e){let t=e.getAttribute("toolparamdescription");if(t)return t.trim();let o=e;if(o.dataset.webmcpDescription)return o.dataset.webmcpDescription;let n=e.getAttribute("aria-description");if(n)return n;let r=e.getAttribute("aria-describedby");if(r){let a=document.getElementById(r);if(a?.textContent?.trim())return a.textContent.trim()}if(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement){let a=e.placeholder?.trim();if(a&&a.length>0)return a}return""}function ct(e){if(e.id){let r=document.querySelector(`label[for="${CSS.escape(e.id)}"]`);if(r){let a=$(r);if(a)return a}}let t=e.getRootNode();if(t instanceof ShadowRoot){if(e.id){let a=t.querySelector(`label[for="${CSS.escape(e.id)}"]`);if(a){let i=$(a);if(i)return i}}let r=t.querySelector("label");if(r){let a=$(r);if(a)return a}}let o=e.closest("label");if(o){let r=$(o);if(r)return r}let n=e;for(;;){let r=n.getRootNode();if(!(r instanceof ShadowRoot))break;let a=r.host,i=a.getAttribute("label")||a.getAttribute("aria-label");if(i)return i;n=a}return""}function $(e){let t=e.cloneNode(!0);return t.querySelectorAll("input, select, textarea, button").forEach(o=>o.remove()),t.textContent?.trim()??""}function V(e){return e.replace(/[-_]/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").trim().replace(/\b\w/g,t=>t.toUpperCase())}function z(e){let t=window.getComputedStyle(e);if(t.display==="none"||t.visibility==="hidden"||e.offsetParent===null&&t.position!=="fixed")return!1;let o=e;for(;o&&o!==document.body;){if(o.getAttribute("aria-hidden")==="true")return!1;o=o.parentElement}return!e.closest("fieldset")?.disabled}function Le(e,t,o){let n=mt(e,o),r=dt(e),{schema:a,fieldElements:i}=pt(t),l=ut(o);return{name:n,description:r,inputSchema:a,annotations:l,fieldElements:i}}function ut(e){let t={},o=e instanceof HTMLInputElement?e.value.trim():e?.textContent?.trim()??"";return be.test(o)&&(t.readOnlyHint=!0,t.idempotentHint=!0),he.test(o)&&(t.destructiveHint=!0),t.readOnlyHint!==!0&&(t.openWorldHint=!0),t.readOnlyHint===!0||t.destructiveHint===!0||t.idempotentHint===!0||t.openWorldHint===!1?t:{}}function mt(e,t){if(t){let r=t instanceof HTMLInputElement?t.value.trim():t.textContent?.trim()??"";if(r&&r.length>0&&r.length<80)return h(r)}let o=Me(e);if(o)return h(o);let n=document.title?.trim();return n?h(n):`form_${++pe}`}function dt(e){let t=Me(e),o=document.title?.trim();return t&&o&&t!==o?`${t} on ${o}`:t||o||"Submit form"}function Me(e){let t=e.querySelector("h1, h2, h3");if(t?.textContent?.trim())return t.textContent.trim();let o=e;for(;o;){let n=o.previousElementSibling;for(;n;){if(/^H[1-3]$/i.test(n.tagName)){let r=n.textContent?.trim()??"";if(r)return r}n=n.previousElementSibling}if(o=o.parentElement,!o||o===document.body)break}return""}function pt(e){let t={},o=[],n=new Map,r=new Set,a=new Set;for(let i of e){if(!(i instanceof HTMLInputElement)&&!(i instanceof HTMLTextAreaElement)&&!(i instanceof HTMLSelectElement)){let d=rt(i);if(!d||!z(i))continue;let p={type:"string"};p.title=i.getAttribute("aria-label")??d;let b=(i.getAttribute("aria-description")??i.getAttribute("aria-describedby"),null);b&&(p.description=b),t[d]=p,n.set(d,i),o.push(d);continue}let l=i.name,s=(l?h(l):null)||ye(i);if(!s)continue;if(i instanceof HTMLInputElement&&i.type==="radio"){if(r.has(s))continue;r.add(s)}if(i instanceof HTMLInputElement&&i.type==="checkbox"){if(a.has(s))continue;a.add(s)}let c=j(i);if(!c||!z(i))continue;c.title=xe(i);let u=we(i);if(u&&(c.description=u),i instanceof HTMLInputElement&&i.type==="checkbox"){let d=e.filter(p=>p instanceof HTMLInputElement&&p.type==="checkbox"&&p.name===s).map(p=>p.value).filter(p=>p!==""&&p!=="on");if(d.length>1){let p={type:"array",items:{type:"string",enum:d},title:c.title};c.description&&(p.description=c.description),t[s]=p,i.required&&o.push(s);continue}}t[s]=c,l||n.set(s,i),i.required&&o.push(s)}return{schema:{$schema:"https://json-schema.org/draft/2020-12/schema",type:"object",properties:t,required:o},fieldElements:n}}O();var P=new WeakMap,Ce=new WeakMap,_=new WeakMap,M=new WeakMap,A=new WeakMap,N=new WeakMap,gt=Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,"value")?.set,bt=Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype,"value")?.set,v=Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,"checked")?.set;function ke(e,t,o,n){return n?.fieldElements&&_.set(e,n.fieldElements),Ae(e,o),async r=>{A.set(e,[]),M.delete(e),X(e,r);let a=Tt(n,r);return a.length>0&&M.set(e,a),window.dispatchEvent(new CustomEvent("toolactivated",{detail:{toolName:o}})),new Promise((i,l)=>{P.set(e,{resolve:i,reject:l}),(t.autoSubmit||e.hasAttribute("toolautosubmit")||e.dataset.webmcpAutosubmit!==void 0)&&ve(e).then(async()=>{try{X(e,r);for(let c=0;c<2&&Et(e,r,_.get(e)).length!==0;c++)X(e,r),await ve(e,400,100);let s=e;if(!e.isConnected){let u=document.querySelector('button[type="submit"]:not([disabled]), input[type="submit"]:not([disabled])')?.closest("form");u&&(s=u,P.set(s,{resolve:i,reject:l}),Ae(s,o))}s!==e&&M.has(e)&&(M.set(s,M.get(e)),M.delete(e)),s.requestSubmit()}catch(s){l(s instanceof Error?s:new Error(String(s)))}})})}}function Ae(e,t){e.__awmcp_intercepted||(e.__awmcp_intercepted=!0,e.addEventListener("submit",o=>{let n=P.get(e);if(!n)return;let{resolve:r}=n;P.delete(e);let a=ht(e,Ce.get(e),_.get(e));N.delete(e);let i=M.get(e)??[];M.delete(e);let l=A.get(e)??[];A.delete(e);let s=l.filter(T=>T.type==="not_filled").map(T=>T.field),c={status:i.length>0||s.length>0?"partial":"success",filled_fields:a,skipped_fields:s,missing_required:i,warnings:[...i.map(T=>({field:T,type:"missing_required",message:`required field "${T}" was not provided`})),...l]},u=[...i.length?[`required fields were not filled: ${i.join(", ")}`]:[],...l.map(T=>T.message)],d=u.length?` Note: ${u.join("; ")}.`:"",b={content:[{type:"text",text:`Form submitted. Fields: ${JSON.stringify(a)}${d}`},{type:"text",text:JSON.stringify(c)}]};o.agentInvoked&&typeof o.respondWith=="function"&&(o.preventDefault(),o.respondWith(Promise.resolve(b))),r(b)}),e.addEventListener("reset",()=>{N.delete(e),window.dispatchEvent(new CustomEvent("toolcancel",{detail:{toolName:t}}))}))}function R(e,t){if(e.focus(),e.select?.(),document.execCommand("insertText",!1,t)&&e.value===t)return;let o=e instanceof HTMLTextAreaElement?bt:gt;o?o.call(e,t):e.value=t,e.dispatchEvent(new InputEvent("input",{bubbles:!0,cancelable:!0,inputType:"insertText",data:t})),e.dispatchEvent(new Event("change",{bubbles:!0}))}function Q(e,t){v?v.call(e,t):e.checked=t,e.dispatchEvent(new Event("change",{bubbles:!0}))}function B(e,t){for(let o of Array.from(e.querySelectorAll("*"))){let n=o.shadowRoot;if(!n)continue;let r=n.querySelector(t);if(r)return r;let a=B(n,t);if(a)return a}return null}function ee(e,t){let o=CSS.escape(t),n=e.querySelector(`[name="${o}"]`)??e.querySelector(`input#${o}, textarea#${o}, select#${o}`);return n||(B(document,`[name="${o}"]`)??B(document,`input#${o}, textarea#${o}, select#${o}`))}function X(e,t){Ce.set(e,t);let o=_.get(e),n={};for(let[r,a]of Object.entries(t)){let i=ee(e,r);if(i){if(i instanceof HTMLInputElement)if(Se(i,e,r,a),i.type==="checkbox")if(Array.isArray(a)){let s=CSS.escape(r);n[r]=Array.from(e.querySelectorAll(`input[type="checkbox"][name="${s}"]`)).filter(c=>c.checked).map(c=>c.value)}else n[r]=i.checked;else n[r]=i.value;else i instanceof HTMLTextAreaElement?(R(i,String(a??"")),n[r]=i.value):i instanceof HTMLSelectElement&&(Z(i,a,e,r),n[r]=i.multiple?Array.from(i.options).filter(s=>s.selected).map(s=>s.value):i.value);continue}let l=o?.get(r);if(l){let s=l;if(!l.isConnected){let c=l.id;if(c){let u=document.getElementById(c)??B(document,`#${CSS.escape(c)}`);u&&(s=u)}}s instanceof HTMLInputElement?(Se(s,e,r,a),n[r]=s.type==="checkbox"?s.checked:s.value):s instanceof HTMLTextAreaElement?(R(s,String(a??"")),n[r]=s.value):s instanceof HTMLSelectElement?(Z(s,a,e,r),n[r]=s.multiple?Array.from(s.options).filter(c=>c.selected).map(c=>c.value):s.value):(Re(s,a),n[r]=a)}}N.set(e,n),window.__lastFillWarnings=A.get(e)??[]}function Se(e,t,o,n){let r=e.type.toLowerCase();if(r==="checkbox"){if(Array.isArray(n)){let a=CSS.escape(o),i=t.querySelectorAll(`input[type="checkbox"][name="${a}"]`);for(let l of i)Q(l,n.map(String).includes(l.value));return}Q(e,!!n);return}if(r==="number"||r==="range"){let a=String(n??""),i=Number(a);if(a===""||isNaN(i)){A.get(t)?.push({field:o,type:"type_mismatch",message:`"${o}" expects a number, got: ${JSON.stringify(n)}`,original:n});return}let l=e.min!==""?parseFloat(e.min):-1/0,s=e.max!==""?parseFloat(e.max):1/0;if(i<l||i>s){let c=Math.min(Math.max(i,l),s);A.get(t)?.push({field:o,type:"clamped",message:`"${o}" value ${i} is outside allowed range [${e.min||"?"}, ${e.max||"?"}], clamped to ${c}`,original:i,actual:c}),e.value=String(c)}else e.value=String(i);e.dispatchEvent(new InputEvent("input",{bubbles:!0,cancelable:!0,inputType:"insertText",data:String(i)})),e.dispatchEvent(new Event("change",{bubbles:!0}));return}if(r==="radio"){let a=CSS.escape(o),i=t.querySelectorAll(`input[type="radio"][name="${a}"]`);for(let l of i)if(l.value===String(n)){v?v.call(l,!0):l.checked=!0,l.dispatchEvent(new Event("change",{bubbles:!0}));break}return}R(e,String(n??""))}function Z(e,t,o,n){if(e.multiple){let a=Array.isArray(t)?t.map(String):[String(t??"")];for(let i of Array.from(e.options))i.selected=a.includes(i.value);e.dispatchEvent(new Event("change",{bubbles:!0}));return}let r=String(t??"");if(e.value=r,e.value!==r){let a=r.toLowerCase(),i=Array.from(e.options).find(l=>l.text.trim().toLowerCase()===a||l.label.trim().toLowerCase()===a);i?e.value=i.value:o&&n&&A.get(o)?.push({field:n,type:"not_filled",message:`"${n}" value "${r}" did not match any option in the select`,original:r})}e.dispatchEvent(new Event("change",{bubbles:!0}))}function Re(e,t){let o=e.getAttribute("role");if(o==="checkbox"||o==="switch"){e.setAttribute("aria-checked",String(!!t)),e.dispatchEvent(new MouseEvent("click",{bubbles:!0}));return}if(o==="radio"){e.setAttribute("aria-checked","true"),e.dispatchEvent(new MouseEvent("click",{bubbles:!0}));return}if(o==="radiogroup"){let r=Array.from(e.querySelectorAll('[role="radio"]'));for(let a of r)if((a.getAttribute("data-value")??a.getAttribute("aria-label")??a.textContent??"").trim()===String(t)){a.setAttribute("aria-checked","true"),a.dispatchEvent(new MouseEvent("click",{bubbles:!0}));for(let l of r)l!==a&&l.setAttribute("aria-checked","false");break}return}let n=e;if(console.log("[auto-webmcp] fillAriaField",{tag:e.tagName,role:o,isContentEditable:n.isContentEditable,id:e.id,ariaLabel:e.getAttribute("aria-label"),textContentBefore:(n.textContent??"").slice(0,80)}),n.isContentEditable){n.focus();let r=document.createRange();r.selectNodeContents(n);let a=window.getSelection();a?.removeAllRanges(),a?.addRange(r);let i=String(t??"");console.log("[auto-webmcp] fillAriaField: text to insert:",JSON.stringify(i));let l=!1;try{let s=new DataTransfer;s.setData("text/plain",i),n.dispatchEvent(new ClipboardEvent("paste",{bubbles:!0,cancelable:!0,composed:!0,clipboardData:s})),l=(n.textContent??"").trim().length>0,console.log("[auto-webmcp] fillAriaField: S1 paste result:",l,JSON.stringify((n.textContent??"").slice(0,80)))}catch(s){console.log("[auto-webmcp] fillAriaField: S1 paste threw:",s)}if(!l){let s=document.execCommand("insertText",!1,i);l=(n.textContent??"").trim().length>0,console.log("[auto-webmcp] fillAriaField: S2 execCommand result:",s,"inserted:",l,JSON.stringify((n.textContent??"").slice(0,80)))}if(!l)try{n.dispatchEvent(new InputEvent("beforeinput",{bubbles:!0,cancelable:!0,composed:!0,inputType:"insertText",data:i})),l=(n.textContent??"").trim().length>0,console.log("[auto-webmcp] fillAriaField: S3 beforeinput result:",l,JSON.stringify((n.textContent??"").slice(0,80)))}catch(s){console.log("[auto-webmcp] fillAriaField: S3 beforeinput threw:",s)}if(!l){n.textContent=i;let s=document.createRange();s.selectNodeContents(n),s.collapse(!1),a?.removeAllRanges(),a?.addRange(s),console.log("[auto-webmcp] fillAriaField: S4 textContent assignment done, textContent:",JSON.stringify((n.textContent??"").slice(0,80)))}n.dispatchEvent(new InputEvent("input",{bubbles:!0,cancelable:!0,inputType:"insertText",data:i})),console.log("[auto-webmcp] fillAriaField: done, final textContent:",JSON.stringify((n.textContent??"").slice(0,80)))}else console.log("[auto-webmcp] fillAriaField: not contentEditable, dispatching input/change only"),e.dispatchEvent(new Event("input",{bubbles:!0})),e.dispatchEvent(new Event("change",{bubbles:!0}))}function ht(e,t,o){let n={},r=new FormData(e),a=N.get(e);for(let[i,l]of r.entries())if(n[i]!==void 0){let s=n[i];Array.isArray(s)?s.push(l):n[i]=[s,l]}else n[i]=l;if(t)for(let i of Object.keys(t)){if(i in n)continue;if(a&&i in a){n[i]=a[i];continue}let l=ee(e,i)??o?.get(i)??null;if(l)if(l instanceof HTMLInputElement&&l.type==="checkbox")n[i]=l.checked;else if(l instanceof HTMLInputElement||l instanceof HTMLTextAreaElement||l instanceof HTMLSelectElement)n[i]=l.value;else{let s=l.getAttribute("role");s==="checkbox"||s==="switch"?n[i]=l.getAttribute("aria-checked")==="true":n[i]=l.textContent?.trim()??""}}return n}function Ie(e,t){if(e instanceof HTMLInputElement){let o=e.type.toLowerCase();o==="checkbox"?Q(e,!!t):o==="radio"?e.value===String(t)&&(v?v.call(e,!0):e.checked=!0,e.dispatchEvent(new Event("change",{bubbles:!0}))):R(e,String(t??""))}else e instanceof HTMLTextAreaElement?R(e,String(t??"")):e instanceof HTMLSelectElement?Z(e,t):Re(e,t)}function ve(e,t=800,o=150){return new Promise(n=>{let r=!1,a=null,i=()=>{r||(r=!0,l.disconnect(),a!==null&&clearTimeout(a),n())},l=new MutationObserver(()=>{a!==null&&clearTimeout(a),a=setTimeout(i,o)});l.observe(e,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),setTimeout(i,t),a=setTimeout(i,o)})}function Et(e,t,o){let n=[];for(let[r,a]of Object.entries(t)){let i=ee(e,r)??o?.get(r)??null;i&&(i instanceof HTMLInputElement&&i.type==="checkbox"?i.checked!==!!a&&n.push(r):(i instanceof HTMLInputElement||i instanceof HTMLTextAreaElement||i instanceof HTMLSelectElement)&&i.value!==String(a??"")&&n.push(r))}return n}function Tt(e,t){return e?.inputSchema?.required?.length?e.inputSchema.required.filter(o=>!(o in t)):[]}async function Fe(e,t){let o=String(t??"").trim();console.log("[auto-webmcp] fillComboboxButton: clicking button, value=",JSON.stringify(o)),e.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}));let n=await new Promise(l=>{let s=Date.now()+1e3,c=()=>{let u=document.querySelector('[role="listbox"]')??document.querySelector('[role="option"]')?.closest('[role="listbox"]')??null;if(u){l(u);return}if(Date.now()>=s){l(null);return}setTimeout(c,50)};c()});if(!n){console.warn("[auto-webmcp] fillComboboxButton: listbox did not appear after 1s");return}let r=Array.from(n.querySelectorAll('[role="option"]'));console.log("[auto-webmcp] fillComboboxButton: listbox has",r.length,"options");let a=o.toLowerCase(),i=r.find(l=>{let s=(l.getAttribute("data-value")??"").toLowerCase(),c=(l.getAttribute("aria-label")??"").toLowerCase(),u=(l.textContent??"").trim().toLowerCase();return s===a||c===a||u===a});i?(console.log("[auto-webmcp] fillComboboxButton: clicking option",i.textContent?.trim()),i.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))):console.warn("[auto-webmcp] fillComboboxButton: no option matched",JSON.stringify(o),"available:",r.map(l=>l.textContent?.trim()))}function Oe(e,t,o){window.dispatchEvent(new CustomEvent(e,{detail:{form:t,toolName:o}}))}function yt(e,t){if(e.dataset.noWebmcp!==void 0)return!0;for(let o of t.exclude)try{if(e.matches(o))return!0}catch{}return!1}async function D(e,t){if(yt(e,t))return;let o;for(let[l,s]of Object.entries(t.overrides))try{if(e.matches(l)){o=s;break}}catch{}let n=fe(e,o);t.debug&&Ct(n.name,n.description);let r=ke(e,t,n.name,n);await G(e,n,r),oe.add(e),Pe++;let a=e.querySelector('[type="submit"], button[data-variant="primary"], button:not([type])')??null,i=window.__pendingSubmitBtns??={};i[n.name]=a,t.debug&&console.log(`[auto-webmcp] Registered: ${n.name}`,n),Oe("form:registered",e,n.name)}async function xt(e,t){let{getRegisteredToolName:o}=await Promise.resolve().then(()=>(O(),He)),n=o(e);n&&(await k(e),oe.delete(e),t.debug&&console.log(`[auto-webmcp] Unregistered: ${n}`),Oe("form:unregistered",e,n))}var F=null,oe=new WeakSet,Pe=0,te=new Map,wt=300,q=null,Lt=500,ne=new Set;function Mt(e){q&&clearTimeout(q),q=setTimeout(()=>{q=null,_e(e)},Lt)}function $e(e){let t=e.tagName.toLowerCase();if(t==="input"||t==="textarea"||t==="select")return!0;let o=e.getAttribute("role");if(o&&C.includes(o)||e.querySelector("input, textarea, select"))return!0;for(let n of C)if(e.querySelector(`[role="${n}"]`))return!0;return!1}function Ht(e,t){let o=te.get(e);o&&clearTimeout(o),te.set(e,setTimeout(()=>{te.delete(e),D(e,t)},wt))}function At(e){F||(F=new MutationObserver(t=>{for(let o of t){for(let n of o.addedNodes){if(!(n instanceof Element))continue;if(n instanceof HTMLFormElement){D(n,e);continue}let r=n.closest("form");r instanceof HTMLFormElement&&oe.has(r)&&$e(n)&&Ht(r,e);for(let a of Array.from(n.querySelectorAll("form")))D(a,e);$e(n)&&!n.closest("form")&&Mt(e)}for(let n of o.removedNodes){if(!(n instanceof Element))continue;let r=n instanceof HTMLFormElement?[n]:Array.from(n.querySelectorAll("form"));for(let a of r)xt(a,e)}}}),F.observe(document.body,{childList:!0,subtree:!0}))}function St(e){window.addEventListener("hashchange",()=>I(e));let t={pushState:history.pushState.bind(history),replaceState:history.replaceState.bind(history)};history.pushState=function(...o){t.pushState(...o),I(e)},history.replaceState=function(...o){t.replaceState(...o),I(e)},window.addEventListener("popstate",()=>I(e))}async function I(e){let t=Array.from(document.querySelectorAll("form"));await Promise.allSettled(t.map(o=>D(o,e)))}var vt=new Set(["password","hidden","file","submit","reset","button","image"]);async function _e(e){if(!L())return;let t='[type="submit"]:not([disabled]), button[data-variant="primary"]:not([disabled])',o='[type="submit"], button[data-variant="primary"]',n=/subscribe|submit|sign[\s-]?up|send|join|go|search|post|tweet|publish|save/i,r=Array.from(document.querySelectorAll('input:not(form input), textarea:not(form textarea), select:not(form select), [role="textbox"]:not(form [role="textbox"]):not(input):not(textarea), [role="searchbox"]:not(form [role="searchbox"]):not(input):not(textarea), [contenteditable="true"]:not(form [contenteditable="true"]):not(input):not(textarea), button[role="combobox"]:not(form button[role="combobox"])')).filter(i=>{if(i instanceof HTMLInputElement&&vt.has(i.type.toLowerCase()))return console.log(`[auto-webmcp] orphan: skipping excluded type "${i.type}" (name="${i.name}" id="${i.id}")`),!1;let l=i.getBoundingClientRect();return l.width===0||l.height===0?(console.log(`[auto-webmcp] orphan: skipping invisible input (name="${i.name}" id="${i.id}")`),!1):!0});if(console.log(`[auto-webmcp] orphan: found ${r.length} visible orphan input(s)`),r.length===0)return;let a=new Map;for(let i of r){let l=i.parentElement,s=i.parentElement??document.body;for(;l&&l!==document.body;){if(l.querySelector(o)!==null||Array.from(l.querySelectorAll("button")).some(u=>n.test(u.textContent??""))){s=l;break}l=l.parentElement}console.log(`[auto-webmcp] orphan: input (name="${i.name}" id="${i.id}") grouped into container`,s),a.has(s)||a.set(s,[]),a.get(s).push(i)}console.log(`[auto-webmcp] orphan: ${a.size} group(s) found`);for(let[i,l]of a){let s=Array.from(i.querySelectorAll(t)).filter(m=>{let g=m.getBoundingClientRect();return g.width>0&&g.height>0}),c=s[s.length-1]??null;if(!c){let m=Array.from(i.querySelectorAll(o)).filter(g=>{let f=g.getBoundingClientRect();return f.width>0&&f.height>0&&g.disabled});c=m[m.length-1]??null,c&&console.log(`[auto-webmcp] orphan: using disabled submit button as reference: "${c.textContent?.trim()}"`)}if(!c){let m=Array.from(i.querySelectorAll('button, [role="button"]')).filter(g=>{let f=g.getBoundingClientRect();return f.width>0&&f.height>0&&!g.disabled&&g.getAttribute("aria-disabled")!=="true"&&n.test(g.textContent??"")});c=m[m.length-1]??null,c&&console.log(`[auto-webmcp] orphan: using text-matched button in container: "${c.textContent?.trim()}"`)}if(!c){let m=i.closest('[role="dialog"], [aria-modal="true"]');if(m){let g=Array.from(m.querySelectorAll('button, [role="button"]')).filter(x=>{let S=x.getBoundingClientRect();return S.width>0&&S.height>0&&n.test(x.textContent??"")});console.log("[auto-webmcp] orphan: dialog buttons matching submit text:",g.map(x=>`"${x.textContent?.trim().slice(0,30)}" disabled=${x.disabled} aria-disabled=${x.getAttribute("aria-disabled")}`));let f=g.filter(x=>x.disabled||x.getAttribute("aria-disabled")==="true"),E=g.filter(x=>!x.disabled&&x.getAttribute("aria-disabled")!=="true"),y=f.length>0?f:E;c=y[y.length-1]??null,c&&console.log(`[auto-webmcp] orphan: using text-matched button in dialog: "${c.textContent?.trim().slice(0,40)}" disabled=${c.disabled} aria-disabled=${c.getAttribute("aria-disabled")}`)}}if(!c){let m=Array.from(document.querySelectorAll('button, [role="button"]')).filter(g=>{let f=g.getBoundingClientRect();return f.width>0&&f.height>0&&g.getAttribute("aria-disabled")!=="true"&&n.test(g.textContent??"")});c=m[m.length-1]??null,c&&console.log(`[auto-webmcp] orphan: using page-wide fallback submit button: "${c.textContent?.trim()}"`)}console.log("[auto-webmcp] orphan: submit button for group:",c?`"${c.textContent?.trim()}" disabled=${c.disabled}`:"none");let u=Le(i,l,c);console.log(`[auto-webmcp] orphan: tool="${u.name}" schema keys:`,Object.keys(u.inputSchema.properties));let d=[],p=u.inputSchema.properties,b=/^_r_[0-9a-z]+_$/i;for(let m of l){let g=m.id&&!b.test(m.id)?m.id:null,f=m.name||m.getAttribute("name")||m.dataset.webmcpName||g||m.getAttribute("aria-label")||m.getAttribute("placeholder")||null,E=f?f.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"").slice(0,64):null,y=!!(E&&p[E]);console.log(`[auto-webmcp] orphan: field (name="${m.name??""}" id="${m.id}") rawKey="${f}" safeKey="${E}" matched=${y}`),y&&d.push({key:E,el:m})}if(console.log(`[auto-webmcp] orphan: ${d.length}/${l.length} input(s) mapped to schema keys`),d.length===0){console.log(`[auto-webmcp] orphan: skipping group "${u.name}" \u2014 no inputs mapped to schema keys`);continue}let T=u.name,w=async m=>{console.log(`[auto-webmcp] orphan execute: tool="${T}" params=`,m),console.log("[auto-webmcp] orphan execute: inputPairs=",d.map(E=>E.key));for(let{key:E,el:y}of d)m[E]!==void 0?(console.log(`[auto-webmcp] orphan execute: filling key="${E}" value=`,m[E],"element=",y),y.getAttribute("role")==="combobox"&&y.tagName.toLowerCase()==="button"?await Fe(y,m[E]):Ie(y,m[E]),console.log("[auto-webmcp] orphan execute: after fill, element value=",y.value)):console.log(`[auto-webmcp] orphan execute: key="${E}" not in params, skipping`);if(window.dispatchEvent(new CustomEvent("toolactivated",{detail:{toolName:T}})),!(e.autoSubmit||!!c?.hasAttribute("toolautosubmit")||c instanceof HTMLElement&&c.dataset.webmcpAutosubmit!==void 0||i.hasAttribute("toolautosubmit")||i instanceof HTMLElement&&i.dataset.webmcpAutosubmit!==void 0))return console.log("[auto-webmcp] orphan execute: autoSubmit=false, returning without clicking submit"),{content:[{type:"text",text:"Fields filled. Ready to submit."}]};console.log("[auto-webmcp] orphan execute: resolving submit button (up to 2s)...");let f=null;if(c&&document.contains(c)){let E=!c.disabled&&c.getAttribute("aria-disabled")!=="true",y=c.getBoundingClientRect();E&&y.width>0&&y.height>0&&(f=c,console.log(`[auto-webmcp] orphan execute: using captured submit button "${f.textContent?.trim()}"`))}if(!f){let E=Date.now()+2e3;for(;Date.now()<E;){let y=Array.from(i.querySelectorAll(t)).filter(S=>{let ie=S.getBoundingClientRect();return ie.width>0&&ie.height>0}),x=y[y.length-1]??null;if(x){f=x;break}await new Promise(S=>setTimeout(S,100))}}if(!f){let E=Array.from((i!==document.body?i:document).querySelectorAll('button, [role="button"]')).filter(y=>{let x=y.getBoundingClientRect();return x.width>0&&x.height>0&&!y.disabled&&y.getAttribute("aria-disabled")!=="true"&&n.test(y.textContent??"")});f=E[E.length-1]??null,f&&console.log(`[auto-webmcp] orphan execute: using text-matched fallback button "${f.textContent?.trim()}"`)}return f?(console.log(`[auto-webmcp] orphan execute: clicking submit button "${f.textContent?.trim()}"`),f.click(),{content:[{type:"text",text:"Fields filled and form submitted."}]}):(console.warn("[auto-webmcp] orphan execute: submit button still disabled after 2s"),{content:[{type:"text",text:"Fields filled but the submit button is still disabled. The page may require additional input before submitting."}]})};try{if(ne.has(u.name)){console.log(`[auto-webmcp] orphan: "${u.name}" already registered, skipping`);continue}let m={name:u.name,description:u.description,inputSchema:u.inputSchema,execute:w};u.annotations&&Object.keys(u.annotations).length>0&&(m.annotations=u.annotations),await navigator.modelContext.registerTool(m),ne.add(u.name);let g=window.__pendingSubmitBtns??={};g[u.name]=c,e.debug&&console.log(`[auto-webmcp] Orphan tool registered: ${u.name}`,u)}catch{}}}function Ct(e,t){/^form_\d+$|^submit$|^form$/.test(e)&&console.warn(`[auto-webmcp] Tool "${e}" has a generic name. Consider adding a toolname or data-webmcp-name attribute.`),(!t||t==="Submit form")&&console.warn(`[auto-webmcp] Tool "${e}" has no meaningful description.`),/don'?t|do not|never|avoid|not for/i.test(t)&&console.warn(`[auto-webmcp] Tool "${e}" description contains negative instructions. Per spec best practices, prefer positive descriptions.`)}async function Ne(e){document.readyState==="loading"&&await new Promise(t=>document.addEventListener("DOMContentLoaded",()=>t(),{once:!0})),Pe=0,ne.clear(),At(e),St(e),await I(e),await _e(e)}function Be(){F?.disconnect(),F=null}O();async function qe(e){let t=ae(e);return t.debug&&console.debug("[auto-webmcp] Initializing",{webmcpSupported:L(),config:t}),await Ne(t),{destroy:async()=>{Be(),await Y()},getTools:K,isSupported:L()}}typeof window<"u"&&!window.__AUTO_WEBMCP_NO_AUTOINIT&&qe();return Ve(kt);})();
1
+ "use strict";var AutoWebMCP=(()=>{var G=Object.defineProperty;var Ye=Object.getOwnPropertyDescriptor;var Xe=Object.getOwnPropertyNames;var Qe=Object.prototype.hasOwnProperty;var Ze=(e,t)=>{for(var o in t)G(e,o,{get:t[o],enumerable:!0})},et=(e,t,o,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Xe(t))!Qe.call(e,i)&&i!==o&&G(e,i,{get:()=>t[i],enumerable:!(n=Ye(t,i))||n.enumerable});return e};var tt=e=>et(G({},"__esModule",{value:!0}),e);var Jt={};Ze(Jt,{autoWebMCP:()=>Ge});function de(e){let t=e?.paramBinding?.strict??!1,o=t?!1:e?.paramBinding?.enableAliasResolution??!0;return{exclude:e?.exclude??[],autoSubmit:e?.autoSubmit??!1,declarativeMode:e?.declarativeMode??"skip",paramBinding:{strict:t,enableAliasResolution:o},execution:{timeoutMs:Math.max(100,e?.execution?.timeoutMs??15e3)},overrides:e?.overrides??{},debug:e?.debug??!1}}var _=["textbox","combobox","checkbox","radio","switch","spinbutton","searchbox","slider"];function X(e){return e instanceof HTMLInputElement?nt(e):e instanceof HTMLTextAreaElement?{type:"string"}:e instanceof HTMLSelectElement?it(e):null}function nt(e){switch(e.type.toLowerCase()){case"text":case"search":case"tel":return Y(e);case"email":return{...Y(e),format:"email"};case"url":return{...Y(e),format:"uri"};case"number":case"range":{let o={type:"number"};return e.min!==""&&(o.minimum=parseFloat(e.min)),e.max!==""&&(o.maximum=parseFloat(e.max)),o}case"date":return{type:"string",format:"date"};case"datetime-local":return{type:"string",format:"date-time"};case"time":return{type:"string",format:"time"};case"month":return{type:"string",pattern:"^\\d{4}-\\d{2}$"};case"week":return{type:"string",pattern:"^\\d{4}-W\\d{2}$"};case"color":return{type:"string",pattern:"^#[0-9a-fA-F]{6}$"};case"checkbox":return{type:"boolean"};case"radio":return{type:"string"};case"file":case"hidden":case"submit":case"reset":case"button":case"image":return null;case"password":return null;default:return{type:"string"}}}function Y(e){let t={type:"string"};e.minLength>0&&(t.minLength=e.minLength),e.maxLength>0&&e.maxLength!==524288&&(t.maxLength=e.maxLength),e.pattern&&(t.pattern=e.pattern);let o=e.getAttribute("list");if(o){let n=e.ownerDocument.getElementById(o);if(n instanceof HTMLDataListElement){let i=Array.from(n.options).filter(s=>!s.disabled&&s.value.trim()!=="");i.length>0&&(t.enum=i.map(s=>s.value.trim()),t.oneOf=i.map(s=>({const:s.value.trim(),title:s.textContent?.trim()||s.value.trim()})))}}return t}var ot=/^(select|choose|pick)\b|^--+|---/i;function fe(e){return e.disabled?!0:e.value!==""?!1:ot.test(e.text.trim())}function it(e){let t=[],o=[];for(let n of Array.from(e.children))if(n instanceof HTMLOptGroupElement){if(n.disabled)continue;let i=n.label?.trim()??"";for(let s of Array.from(n.children)){if(!(s instanceof HTMLOptionElement)||fe(s))continue;t.push(s.value);let r={const:s.value,title:s.text.trim()||s.value};i&&(r.group=i),o.push(r)}}else if(n instanceof HTMLOptionElement){if(fe(n))continue;t.push(n.value),o.push({const:n.value,title:n.text.trim()||n.value})}return t.length===0?{type:"string"}:e.multiple?{type:"array",items:{type:"string",enum:t}}:{type:"string",enum:t,oneOf:o}}function pe(e,t){return Array.from(e.elements).filter(o=>o instanceof HTMLInputElement&&o.type==="checkbox"&&o.name===t).map(o=>o.value).filter(o=>o!==""&&o!=="on")}function ge(e,t){return Array.from(e.elements).filter(n=>n instanceof HTMLInputElement&&n.type==="radio"&&n.name===t).map(n=>n.value).filter(n=>n!=="")}function be(e,t){return Array.from(e.elements).filter(n=>n instanceof HTMLInputElement&&n.type==="radio"&&n.name===t).filter(n=>n.value!=="").map(n=>{let i=rt(n);return{const:n.value,title:i||n.value}})}function Ee(e,t){switch(t){case"checkbox":case"switch":return{type:"boolean"};case"spinbutton":case"slider":{let o={type:"number"},n=e.getAttribute("aria-valuemin"),i=e.getAttribute("aria-valuemax");return n!==null&&(o.minimum=parseFloat(n)),i!==null&&(o.maximum=parseFloat(i)),o}case"combobox":{let o=e.getAttribute("aria-owns")??e.getAttribute("aria-controls");if(o){let n=document.getElementById(o);if(n){let i=Array.from(n.querySelectorAll('[role="option"]')).filter(s=>s.getAttribute("aria-disabled")!=="true");if(i.length>0){let s=i.map(c=>(c.getAttribute("data-value")??c.textContent??"").trim()).filter(Boolean),r=i.map(c=>({const:(c.getAttribute("data-value")??c.textContent??"").trim(),title:(c.textContent??"").trim()}));return{type:"string",enum:s,oneOf:r}}}}return{type:"string"}}case"textbox":case"searchbox":case"radio":default:return{type:"string"}}}function rt(e){let t=e.closest("label");if(t){let o=t.cloneNode(!0);o.querySelectorAll("input, select, textarea, button").forEach(i=>i.remove());let n=o.textContent?.trim()??"";if(n)return n}if(e.id){let o=document.querySelector(`label[for="${CSS.escape(e.id)}"]`);if(o){let n=o.textContent?.trim()??"";if(n)return n}}return""}var Te=0;function ye(e,t){let o=t?.name??st(e),n=t?.description??lt(e),{schema:i,fieldElements:s}=ft(e),r=ut(e);return{name:o,description:n,inputSchema:i,annotations:r,fieldElements:s}}function st(e){let t=e.getAttribute("toolname");if(t)return h(t);let o=e.dataset.webmcpName;if(o)return h(o);let n=Q(e);if(n)return h(n);let i=Me(e);if(i)return h(i);if(e.id)return h(e.id);if(e.name)return h(e.name);if(e.action){let s=at(e.action);if(s)return h(s)}return`form_${++Te}`}function h(e){return e.toLowerCase().trim().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"").slice(0,64)||"form"}function Q(e){let t=[...Array.from(e.querySelectorAll('button[type="submit"], button:not([type])')),...Array.from(e.querySelectorAll('input[type="submit"]'))];for(let o of t){let n=o instanceof HTMLInputElement?o.value.trim():o.textContent?.trim()??"";if(n&&n.length>0&&n.length<80)return n}return""}function Me(e){let t=e;for(;t;){let o=t.previousElementSibling;for(;o;){if(/^H[1-3]$/i.test(o.tagName)){let n=o.textContent?.trim()??"";if(n)return n}o=o.previousElementSibling}if(t=t.parentElement,!t||t===document.body)break}return""}function at(e){try{let o=new URL(e,window.location.href).pathname.split("/").filter(Boolean);return o[o.length-1]??""}catch{return""}}function lt(e){let t=e.getAttribute("tooldescription");if(t)return t.trim();let o=e.dataset.webmcpDescription;if(o)return o.trim();let n=e.querySelector("legend");if(n?.textContent?.trim())return n.textContent.trim();let i=e.getAttribute("aria-label");if(i?.trim())return i.trim();let s=e.getAttribute("aria-describedby");if(s){let a=document.getElementById(s);if(a?.textContent?.trim())return a.textContent.trim()}let r=Me(e),c=document.title?.trim();return r&&c?`${r}: ${c}`:r||c||"Submit form"}var we=/^(search|find|look|filter|browse|view|show|check|preview|get|fetch|retrieve|load)\b/i,Le=/^(delete|remove|cancel|terminate|destroy|purge|revoke|unsubscribe|deactivate)\b/i,ct=/\/(delete|remove|cancel|destroy)\b/i;function ut(e){let t={};if(e.dataset.webmcpReadonly!==void 0&&(t.readOnlyHint=e.dataset.webmcpReadonly!=="false"),e.dataset.webmcpDestructive!==void 0&&(t.destructiveHint=e.dataset.webmcpDestructive!=="false"),e.dataset.webmcpIdempotent!==void 0&&(t.idempotentHint=e.dataset.webmcpIdempotent!=="false"),e.dataset.webmcpOpenworld!==void 0&&(t.openWorldHint=e.dataset.webmcpOpenworld!=="false"),t.readOnlyHint===void 0){let n=e.method.toLowerCase()==="get",i=Q(e),s=i?we.test(i.trim()):!1;(n||s)&&(t.readOnlyHint=!0)}if(t.destructiveHint===void 0){let n=Q(e),i=n?Le.test(n.trim()):!1,s=e.action?ct.test(e.action):!1;(i||s)&&(t.destructiveHint=!0)}return t.idempotentHint===void 0&&(t.readOnlyHint===!0||e.method.toLowerCase()==="get")&&(t.idempotentHint=!0),t.openWorldHint===void 0&&(t.openWorldHint=t.readOnlyHint!==!0),t.readOnlyHint===!0||t.destructiveHint===!0||t.idempotentHint===!0||t.openWorldHint===!1?t:{}}function mt(e){if(e instanceof HTMLInputElement){let t=e.type.toLowerCase();return t==="checkbox"?e.checked?!0:void 0:t==="radio"?void 0:t==="number"||t==="range"?e.value!==""?parseFloat(e.value):void 0:e.value!==""?e.value:void 0}if(e instanceof HTMLTextAreaElement)return e.value!==""?e.value:void 0;if(e instanceof HTMLSelectElement){if(e.multiple){let t=Array.from(e.options).filter(o=>o.selected).map(o=>o.value);return t.length>0?t:void 0}return e.value!==""?e.value:void 0}}function xe(e,t=new Set){if(t.has(e))return[];t.add(e);let o=[];for(let n of Array.from(e.querySelectorAll("*")))if(n.shadowRoot){let i=Array.from(n.shadowRoot.querySelectorAll("input, textarea, select"));i.length>0&&console.log(`[auto-webmcp] shadow: found ${i.length} control(s) in ${n.tagName.toLowerCase()} shadow root:`,i.map(s=>`${s.tagName.toLowerCase()}[type=${s.type??"?"}][name="${s.name}"][id="${s.id}"]`)),o.push(...i,...xe(n.shadowRoot,t))}return o}function dt(e){let t=Array.from(e.elements).filter(n=>n instanceof HTMLInputElement||n instanceof HTMLTextAreaElement||n instanceof HTMLSelectElement),o=new Set(t);for(let n of xe(e))o.has(n)||(t.push(n),o.add(n));return t}function ft(e){let t={},o=[],n=new Map,i=new Set,s=new Set,r=dt(e);for(let l of r){let u=l.name,d=u||Ae(l);if(!d)continue;if(l instanceof HTMLInputElement&&l.type==="radio"){if(i.has(d))continue;i.add(d)}if(l instanceof HTMLInputElement&&l.type==="checkbox"){if(s.has(d))continue;s.add(d)}let m=X(l);if(!m||!ee(l))continue;m.title=ve(l);let E=Se(l);E&&(m.description=E);let p=mt(l);if(p!==void 0&&(m.default=p),l instanceof HTMLInputElement&&l.type==="radio"){m.enum=ge(e,d);let w=be(e,d);w.length>0&&(m.oneOf=w);let f=Array.from(e.elements).find(g=>g instanceof HTMLInputElement&&g.type==="radio"&&g.name===d&&g.checked);f?.value&&(m.default=f.value)}if(l instanceof HTMLInputElement&&l.type==="checkbox"){let w=pe(e,d);if(w.length>1){let f={type:"array",items:{type:"string",enum:w},title:m.title};m.description&&(f.description=m.description);let g=Array.from(e.elements).filter(T=>T instanceof HTMLInputElement&&T.type==="checkbox"&&T.name===d&&T.checked).map(T=>T.value);g.length>0&&(f.default=g),t[d]=f,l.required&&o.push(d);continue}}t[d]=m,u||n.set(d,l);let y=l.required;if(!y){let w=l;for(;;){let f=w.getRootNode();if(!(f instanceof ShadowRoot))break;let g=f.host;if(g.hasAttribute("required")||g.getAttribute("aria-required")==="true"){y=!0;break}w=g}}y&&o.push(d)}let c=bt(e),a=new Set;for(let{el:l,role:u,key:d,enumValues:m,enumOneOf:E}of c){if(t[d])continue;if(u==="radio"){if(a.has(d))continue;a.add(d)}let p=Ee(l,u);m&&m.length>0&&(p.enum=m,E&&E.length>0&&(p.oneOf=E)),p.title=Et(l);let y=ht(l);y&&(p.description=y),t[d]=p,n.set(d,l),l.getAttribute("aria-required")==="true"&&o.push(d)}return{schema:{$schema:"https://json-schema.org/draft/2020-12/schema",type:"object",properties:t,required:o},fieldElements:n}}var He=/^_r_[0-9a-z]+_$|^:[a-z0-9]+:$/i;function Ae(e){let t=e;if(t.dataset.webmcpName)return h(t.dataset.webmcpName);if(e.id&&!He.test(e.id))return h(e.id);let o=e.getAttribute("aria-label");if(o)return h(o);if((e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement)&&e.placeholder?.trim())return h(e.placeholder.trim());let n=pt(e);return n||(e instanceof HTMLInputElement&&e.type!=="text"?e.type:null)}function pt(e){let t=e;for(;;){let o=t.getRootNode();if(!(o instanceof ShadowRoot))break;let n=o.host,i=n.getAttribute("field-name");if(i)return console.log("[auto-webmcp] shadow host key: field-name=",i),h(i);let s=n.getAttribute("label")||n.getAttribute("aria-label");if(s)return console.log("[auto-webmcp] shadow host key: label=",s),h(s);let r=n.getAttribute("name");if(r)return console.log("[auto-webmcp] shadow host key: name=",r),h(r);t=n}return null}function gt(e){if(e.dataset.webmcpName)return h(e.dataset.webmcpName);if(e.id&&!He.test(e.id))return h(e.id);let t=e.getAttribute("aria-label");if(t)return h(t);let o=e.getAttribute("placeholder");return o?h(o):null}function bt(e){let t=_.map(a=>`[role="${a}"]`).join(", "),o=[];for(let a of Array.from(e.querySelectorAll(t))){if(a instanceof HTMLInputElement||a instanceof HTMLTextAreaElement||a instanceof HTMLSelectElement||a.getAttribute("aria-hidden")==="true"||a.hidden)continue;let l=a.getAttribute("role"),u=he(a);u&&o.push({el:a,role:l,key:u})}let n=o.filter(a=>a.role==="radio"),i=o.filter(a=>a.role!=="radio"),s=new Map,r=[];for(let a of n){let l=a.el.closest('[role="radiogroup"]');l?(s.has(l)||s.set(l,[]),s.get(l).push(a.el)):r.push(a)}let c=[];for(let[a,l]of s){let u=he(a);if(!u)continue;let d=l.map(E=>(E.getAttribute("data-value")??E.getAttribute("aria-label")??E.textContent??"").trim()).filter(Boolean),m=l.map(E=>{let p=(E.getAttribute("data-value")??E.getAttribute("aria-label")??E.textContent??"").trim(),y=(E.getAttribute("aria-label")??E.textContent??"").trim();return{const:p,title:y||p}}).filter(E=>E.const!=="");d.length>0&&c.push({el:a,role:"radio",key:u,enumValues:d,enumOneOf:m})}return[...i,...c,...r]}function he(e){let t=e;if(t.dataset?.webmcpName)return h(t.dataset.webmcpName);if(e.id)return h(e.id);let o=e.getAttribute("aria-label");if(o)return h(o);let n=e.getAttribute("aria-labelledby");if(n){let i=document.getElementById(n)?.textContent?.trim();if(i)return h(i)}return null}function Et(e){let t=e;if(t.dataset?.webmcpTitle)return t.dataset.webmcpTitle;let o=e.getAttribute("aria-label");if(o)return o.trim();let n=e.getAttribute("aria-labelledby");if(n){let i=document.getElementById(n)?.textContent?.trim();if(i)return i}return e.id?Z(e.id):""}function ht(e){let t=e.getAttribute("toolparamdescription");if(t)return t.trim();let o=e;if(o.dataset?.webmcpDescription)return o.dataset.webmcpDescription;let n=e.getAttribute("aria-description");if(n)return n;let i=e.getAttribute("aria-describedby");if(i){let r=document.getElementById(i)?.textContent?.trim();if(r)return r}let s=e.getAttribute("placeholder")??e.dataset?.placeholder;return s?s.trim():""}function ve(e){if("dataset"in e&&e.dataset.webmcpTitle)return e.dataset.webmcpTitle;let t=Tt(e);return t||(e.name?Z(e.name):e.id?Z(e.id):(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement)&&e.placeholder?.trim()?e.placeholder.trim():"")}function Se(e){let t=e.getAttribute("toolparamdescription");if(t)return t.trim();let o=e;if(o.dataset.webmcpDescription)return o.dataset.webmcpDescription;let n=e.getAttribute("aria-description");if(n)return n;let i=e.getAttribute("aria-describedby");if(i){let s=document.getElementById(i);if(s?.textContent?.trim())return s.textContent.trim()}if(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement){let s=e.placeholder?.trim();if(s&&s.length>0)return s}return""}function Tt(e){if(e.id){let i=document.querySelector(`label[for="${CSS.escape(e.id)}"]`);if(i){let s=W(i);if(s)return s}}let t=e.getRootNode();if(t instanceof ShadowRoot){if(e.id){let s=t.querySelector(`label[for="${CSS.escape(e.id)}"]`);if(s){let r=W(s);if(r)return r}}let i=t.querySelector("label");if(i){let s=W(i);if(s)return s}}let o=e.closest("label");if(o){let i=W(o);if(i)return i}let n=e;for(;;){let i=n.getRootNode();if(!(i instanceof ShadowRoot))break;let s=i.host,r=s.getAttribute("label")||s.getAttribute("aria-label");if(r)return r;n=s}return""}function W(e){let t=e.cloneNode(!0);return t.querySelectorAll("input, select, textarea, button").forEach(o=>o.remove()),t.textContent?.trim()??""}function Z(e){return e.replace(/[-_]/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").trim().replace(/\b\w/g,t=>t.toUpperCase())}function ee(e){let t=window.getComputedStyle(e);if(t.display==="none"||t.visibility==="hidden"||e.offsetParent===null&&t.position!=="fixed")return!1;let o=e;for(;o&&o!==document.body;){if(o.getAttribute("aria-hidden")==="true")return!1;o=o.parentElement}return!e.closest("fieldset")?.disabled}function Ce(e,t,o){let n=Mt(e,o),i=wt(e),{schema:s,fieldElements:r}=Lt(t),c=yt(o);return{name:n,description:i,inputSchema:s,annotations:c,fieldElements:r}}function yt(e){let t={},o=e instanceof HTMLInputElement?e.value.trim():e?.textContent?.trim()??"";return we.test(o)&&(t.readOnlyHint=!0,t.idempotentHint=!0),Le.test(o)&&(t.destructiveHint=!0),t.readOnlyHint!==!0&&(t.openWorldHint=!0),t.readOnlyHint===!0||t.destructiveHint===!0||t.idempotentHint===!0||t.openWorldHint===!1?t:{}}function Mt(e,t){if(t){let i=t instanceof HTMLInputElement?t.value.trim():t.textContent?.trim()??"";if(i&&i.length>0&&i.length<80)return h(i)}let o=ke(e);if(o)return h(o);let n=document.title?.trim();return n?h(n):`form_${++Te}`}function wt(e){let t=ke(e),o=document.title?.trim();return t&&o&&t!==o?`${t} on ${o}`:t||o||"Submit form"}function ke(e){let t=e.querySelector("h1, h2, h3");if(t?.textContent?.trim())return t.textContent.trim();let o=e;for(;o;){let n=o.previousElementSibling;for(;n;){if(/^H[1-3]$/i.test(n.tagName)){let i=n.textContent?.trim()??"";if(i)return i}n=n.previousElementSibling}if(o=o.parentElement,!o||o===document.body)break}return""}function Lt(e){let t={},o=[],n=new Map,i=new Set,s=new Set;for(let r of e){if(!(r instanceof HTMLInputElement)&&!(r instanceof HTMLTextAreaElement)&&!(r instanceof HTMLSelectElement)){let d=gt(r);if(!d||!ee(r))continue;let m={type:"string"};m.title=r.getAttribute("aria-label")??d;let E=(r.getAttribute("aria-description")??r.getAttribute("aria-describedby"),null);E&&(m.description=E),t[d]=m,n.set(d,r),o.push(d);continue}let c=r.name,a=(c?h(c):null)||Ae(r);if(!a)continue;if(r instanceof HTMLInputElement&&r.type==="radio"){if(i.has(a))continue;i.add(a)}if(r instanceof HTMLInputElement&&r.type==="checkbox"){if(s.has(a))continue;s.add(a)}let l=X(r);if(!l||!ee(r))continue;l.title=ve(r);let u=Se(r);if(u&&(l.description=u),r instanceof HTMLInputElement&&r.type==="checkbox"){let d=e.filter(m=>m instanceof HTMLInputElement&&m.type==="checkbox"&&m.name===a).map(m=>m.value).filter(m=>m!==""&&m!=="on");if(d.length>1){let m={type:"array",items:{type:"string",enum:d},title:l.title};l.description&&(m.description=l.description),t[a]=m,r.required&&o.push(a);continue}}t[a]=l,c||n.set(a,r),r.required&&o.push(a)}return{schema:{$schema:"https://json-schema.org/draft/2020-12/schema",type:"object",properties:t,required:o},fieldElements:n}}var C=new Map,te=new Map;function k(){return typeof navigator<"u"&&typeof navigator.modelContext<"u"}async function Re(e,t,o){if(!k())return;C.get(e)&&await O(e);let i={name:t.name,description:t.description,inputSchema:t.inputSchema,execute:o};t.annotations&&Object.keys(t.annotations).length>0&&(i.annotations=t.annotations);let s=new AbortController;te.set(e,s);try{await navigator.modelContext.registerTool(i,{signal:s.signal})}catch{try{await navigator.modelContext.unregisterTool?.(t.name),await navigator.modelContext.registerTool(i,{signal:s.signal})}catch{}}C.set(e,t.name)}async function O(e){if(!k())return;let t=C.get(e);if(!t)return;let o=te.get(e);o&&(o.abort(),te.delete(e));try{await navigator.modelContext.unregisterTool?.(t)}catch{}C.delete(e)}function ne(e){return C.get(e)}function J(){return Array.from(C.entries()).map(([e,t])=>({form:e,name:t}))}async function Ie(){let e=Array.from(C.entries());await Promise.all(e.map(([t])=>O(t)))}var A=new WeakMap,$=new WeakMap,R=new WeakMap,H=new WeakMap,x=new WeakMap,I=new WeakMap,xt=Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,"value")?.set,Ht=Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype,"value")?.set,F=Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,"checked")?.set;function $e(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"")}function S(e,t,o){if(!t)return;let n=$e(t);n&&(e.has(n)||e.set(n,new Set),e.get(n).add(o))}function At(e,t){let o=new Map,n=t?.inputSchema?.properties??{};for(let[i,s]of Object.entries(n)){S(o,i,i),S(o,i.replace(/_/g," "),i),S(o,s.title,i);let r=U(e,i),c=t?.fieldElements?.get(i),a=r??c??null;if(!a)continue;let l=a;if(S(o,l.getAttribute("id"),i),S(o,l.getAttribute("name"),i),S(o,l.getAttribute("aria-label"),i),S(o,l.getAttribute("placeholder"),i),a instanceof HTMLInputElement||a instanceof HTMLTextAreaElement||a instanceof HTMLSelectElement)for(let u of Array.from(a.labels??[]))S(o,u.textContent?.trim(),i)}return o}function vt(e,t,o,n){let i={},s=[],r=o?.inputSchema?.properties??{},c=n.paramBinding.enableAliasResolution;for(let[l,u]of Object.entries(t))l in r&&(i[l]=u);if(!c)return{resolved:i,warnings:s};let a=At(e,o);for(let[l,u]of Object.entries(t)){if(l in r)continue;let d=a.get($e(l));if(!d||d.size!==1)continue;let m=Array.from(d)[0];!m||m in i||(i[m]=u,s.push({field:m,type:"alias_resolved",original:l,message:`resolved "${l}" to schema field "${m}"`}))}return{resolved:i,warnings:s}}function St(e){let t=[],o=Array.from(e.elements).filter(n=>n instanceof HTMLInputElement||n instanceof HTMLTextAreaElement||n instanceof HTMLSelectElement);for(let n of o){if(!n.willValidate||n.checkValidity())continue;let i=n.name||n.id||n.getAttribute("aria-label")||"unknown_field";t.push({field:i,type:"blocked_submit",message:n.validationMessage||`field "${i}" failed validation`})}return t}function Be(e,t,o,n){return n?.fieldElements&&R.set(e,n.fieldElements),Fe(e,o),async(i,s)=>{let r=s;if(t.autoSubmit&&n?.annotations?.destructiveHint===!0&&typeof r?.requestUserInteraction=="function"&&!await r.requestUserInteraction(async()=>new Promise(d=>{let m=window.confirm(`Agent requested a destructive action via "${o}". Continue?`);d(m)})))return window.dispatchEvent(new CustomEvent("toolcancel",{detail:{toolName:o}})),{content:[{type:"text",text:`Cancelled "${o}" by user.`}]};x.set(e,[]),H.delete(e);let{resolved:c,warnings:a}=vt(e,i,n,t);a.length>0&&x.set(e,[...x.get(e)??[],...a]),oe(e,c);let l=kt(n,c);return l.length>0&&H.set(e,l),window.dispatchEvent(new CustomEvent("toolactivated",{detail:{toolName:o}})),new Promise((u,d)=>{let m=t.execution.timeoutMs,E=setTimeout(()=>{if(!A.get(e))return;A.delete(e);let y=t.autoSubmit||e.hasAttribute("toolautosubmit")||e.dataset.webmcpAutosubmit!==void 0?"timed_out":"awaiting_user_action",w={field:"__form__",type:"timeout",message:y==="timed_out"?`tool execution timed out after ${m}ms`:`waiting for user submit (timed out after ${m}ms)`},f={status:y,filled_fields:ae(e,$.get(e),R.get(e)),skipped_fields:[],missing_required:H.get(e)??[],warnings:[...x.get(e)??[],w]};H.delete(e),x.delete(e),I.delete(e),u({content:[{type:"text",text:w.message},{type:"text",text:JSON.stringify(f)}]})},m);A.set(e,{resolve:u,reject:d,timeoutId:E}),(t.autoSubmit||e.hasAttribute("toolautosubmit")||e.dataset.webmcpAutosubmit!==void 0)&&Oe(e).then(async()=>{try{oe(e,c);for(let y=0;y<2&&Ct(e,c,R.get(e)).length!==0;y++)oe(e,c),await Oe(e,400,100);let p=e;if(!e.isConnected){let w=document.querySelector('button[type="submit"]:not([disabled]), input[type="submit"]:not([disabled])')?.closest("form");if(w){p=w;let f=A.get(e),g=f?.timeoutId?{resolve:u,reject:d,timeoutId:f.timeoutId}:{resolve:u,reject:d};A.set(p,g),Fe(p,o)}}if(p!==e&&H.has(e)&&(H.set(p,H.get(e)),H.delete(e)),!p.checkValidity()){let y=A.get(p)??A.get(e);if(y){y.timeoutId&&clearTimeout(y.timeoutId),A.delete(p),A.delete(e);let w=[...x.get(p)??x.get(e)??[],...St(p)];x.delete(p),x.delete(e);let f={status:"blocked_invalid",filled_fields:ae(p,$.get(p)??$.get(e),R.get(p)??R.get(e)),skipped_fields:[],missing_required:H.get(p)??H.get(e)??[],warnings:w};H.delete(p),H.delete(e),I.delete(p),I.delete(e),u({content:[{type:"text",text:"Form submission blocked by native validation."},{type:"text",text:JSON.stringify(f)}]})}return}p.requestSubmit()}catch(p){d(p instanceof Error?p:new Error(String(p)))}})})}}function Fe(e,t){e.__awmcp_intercepted||(e.__awmcp_intercepted=!0,e.addEventListener("submit",o=>{let n=A.get(e);if(!n)return;let{resolve:i}=n;n.timeoutId&&clearTimeout(n.timeoutId),A.delete(e);let s=ae(e,$.get(e),R.get(e));I.delete(e);let r=H.get(e)??[];H.delete(e);let c=x.get(e)??[];x.delete(e);let a=c.filter(p=>p.type==="not_filled").map(p=>p.field),l={status:r.length>0||a.length>0?"partial":"success",filled_fields:s,skipped_fields:a,missing_required:r,warnings:[...r.map(p=>({field:p,type:"missing_required",message:`required field "${p}" was not provided`})),...c]},u=[...r.length?[`required fields were not filled: ${r.join(", ")}`]:[],...c.map(p=>p.message)],d=u.length?` Note: ${u.join("; ")}.`:"",E={content:[{type:"text",text:`Form submitted. Fields: ${JSON.stringify(s)}${d}`},{type:"text",text:JSON.stringify(l)}]};o.agentInvoked&&typeof o.respondWith=="function"&&(o.preventDefault(),o.respondWith(Promise.resolve(E))),i(E)}),e.addEventListener("reset",()=>{I.delete(e),window.dispatchEvent(new CustomEvent("toolcancel",{detail:{toolName:t}}))}))}function B(e,t){if(e.focus(),e.select?.(),document.execCommand("insertText",!1,t)&&e.value===t)return;let o=e instanceof HTMLTextAreaElement?Ht:xt;o?o.call(e,t):e.value=t,e.dispatchEvent(new InputEvent("input",{bubbles:!0,cancelable:!0,inputType:"insertText",data:t})),e.dispatchEvent(new Event("change",{bubbles:!0}))}function ie(e,t){F?F.call(e,t):e.checked=t,e.dispatchEvent(new Event("change",{bubbles:!0}))}function j(e,t){for(let o of Array.from(e.querySelectorAll("*"))){let n=o.shadowRoot;if(!n)continue;let i=n.querySelector(t);if(i)return i;let s=j(n,t);if(s)return s}return null}function re(e,t,o){return Array.from(e.elements).filter(n=>n instanceof HTMLInputElement&&n.type===t&&n.name===o)}function U(e,t){let o=e.elements.namedItem(t);if(typeof o=="object"&&o!==null&&(o instanceof HTMLInputElement||o instanceof HTMLTextAreaElement||o instanceof HTMLSelectElement))return o;if(o instanceof RadioNodeList){let r=o[0];if(r instanceof HTMLInputElement||r instanceof HTMLTextAreaElement||r instanceof HTMLSelectElement)return r}let n=CSS.escape(t),i=e.querySelector(`[name="${n}"]`)??e.querySelector(`input#${n}, textarea#${n}, select#${n}`);return i||(j(document,`[name="${n}"]`)??j(document,`input#${n}, textarea#${n}, select#${n}`))}function oe(e,t){$.set(e,t);let o=R.get(e),n={};for(let[i,s]of Object.entries(t)){let r=U(e,i);if(r){r instanceof HTMLInputElement?(_e(r,e,i,s),r.type==="checkbox"?Array.isArray(s)?n[i]=re(e,"checkbox",i).filter(a=>a.checked).map(a=>a.value):n[i]=r.checked:n[i]=r.value):r instanceof HTMLTextAreaElement?(B(r,String(s??"")),n[i]=r.value):r instanceof HTMLSelectElement&&(se(r,s,e,i),n[i]=r.multiple?Array.from(r.options).filter(a=>a.selected).map(a=>a.value):r.value);continue}let c=o?.get(i);if(c){let a=c;if(!c.isConnected){let l=c.id;if(l){let u=document.getElementById(l)??j(document,`#${CSS.escape(l)}`);u&&(a=u)}}a instanceof HTMLInputElement?(_e(a,e,i,s),n[i]=a.type==="checkbox"?a.checked:a.value):a instanceof HTMLTextAreaElement?(B(a,String(s??"")),n[i]=a.value):a instanceof HTMLSelectElement?(se(a,s,e,i),n[i]=a.multiple?Array.from(a.options).filter(l=>l.selected).map(l=>l.value):a.value):(Pe(a,s),n[i]=s)}}I.set(e,n),window.__lastFillWarnings=x.get(e)??[]}function _e(e,t,o,n){let i=e.type.toLowerCase();if(i==="checkbox"){if(Array.isArray(n)){let s=re(t,"checkbox",o);for(let r of s)ie(r,n.map(String).includes(r.value));return}ie(e,!!n);return}if(i==="number"||i==="range"){let s=String(n??""),r=Number(s);if(s===""||isNaN(r)){x.get(t)?.push({field:o,type:"type_mismatch",message:`"${o}" expects a number, got: ${JSON.stringify(n)}`,original:n});return}let c=e.min!==""?parseFloat(e.min):-1/0,a=e.max!==""?parseFloat(e.max):1/0;if(r<c||r>a){let l=Math.min(Math.max(r,c),a);x.get(t)?.push({field:o,type:"clamped",message:`"${o}" value ${r} is outside allowed range [${e.min||"?"}, ${e.max||"?"}], clamped to ${l}`,original:r,actual:l}),e.value=String(l)}else e.value=String(r);e.dispatchEvent(new InputEvent("input",{bubbles:!0,cancelable:!0,inputType:"insertText",data:String(r)})),e.dispatchEvent(new Event("change",{bubbles:!0}));return}if(i==="radio"){let s=re(t,"radio",o);for(let r of s)if(r.value===String(n)){F?F.call(r,!0):r.checked=!0,r.dispatchEvent(new Event("change",{bubbles:!0}));break}return}B(e,String(n??""))}function se(e,t,o,n){if(e.multiple){let s=Array.isArray(t)?t.map(String):[String(t??"")];for(let r of Array.from(e.options))r.selected=s.includes(r.value);e.dispatchEvent(new Event("change",{bubbles:!0}));return}let i=String(t??"");if(e.value=i,e.value!==i){let s=i.toLowerCase(),r=Array.from(e.options).find(c=>c.text.trim().toLowerCase()===s||c.label.trim().toLowerCase()===s);r?e.value=r.value:o&&n&&x.get(o)?.push({field:n,type:"not_filled",message:`"${n}" value "${i}" did not match any option in the select`,original:i})}e.dispatchEvent(new Event("change",{bubbles:!0}))}function Pe(e,t){let o=e.getAttribute("role");if(o==="checkbox"||o==="switch"){e.setAttribute("aria-checked",String(!!t)),e.dispatchEvent(new MouseEvent("click",{bubbles:!0}));return}if(o==="radio"){e.setAttribute("aria-checked","true"),e.dispatchEvent(new MouseEvent("click",{bubbles:!0}));return}if(o==="radiogroup"){let i=Array.from(e.querySelectorAll('[role="radio"]'));for(let s of i)if((s.getAttribute("data-value")??s.getAttribute("aria-label")??s.textContent??"").trim()===String(t)){s.setAttribute("aria-checked","true"),s.dispatchEvent(new MouseEvent("click",{bubbles:!0}));for(let c of i)c!==s&&c.setAttribute("aria-checked","false");break}return}let n=e;if(console.log("[auto-webmcp] fillAriaField",{tag:e.tagName,role:o,isContentEditable:n.isContentEditable,id:e.id,ariaLabel:e.getAttribute("aria-label"),textContentBefore:(n.textContent??"").slice(0,80)}),n.isContentEditable){n.focus();let i=document.createRange();i.selectNodeContents(n);let s=window.getSelection();s?.removeAllRanges(),s?.addRange(i);let r=String(t??"");console.log("[auto-webmcp] fillAriaField: text to insert:",JSON.stringify(r));let c=!1;try{let a=new DataTransfer;a.setData("text/plain",r),n.dispatchEvent(new ClipboardEvent("paste",{bubbles:!0,cancelable:!0,composed:!0,clipboardData:a})),c=(n.textContent??"").trim().length>0,console.log("[auto-webmcp] fillAriaField: S1 paste result:",c,JSON.stringify((n.textContent??"").slice(0,80)))}catch(a){console.log("[auto-webmcp] fillAriaField: S1 paste threw:",a)}if(!c){let a=document.execCommand("insertText",!1,r);c=(n.textContent??"").trim().length>0,console.log("[auto-webmcp] fillAriaField: S2 execCommand result:",a,"inserted:",c,JSON.stringify((n.textContent??"").slice(0,80)))}if(!c)try{n.dispatchEvent(new InputEvent("beforeinput",{bubbles:!0,cancelable:!0,composed:!0,inputType:"insertText",data:r})),c=(n.textContent??"").trim().length>0,console.log("[auto-webmcp] fillAriaField: S3 beforeinput result:",c,JSON.stringify((n.textContent??"").slice(0,80)))}catch(a){console.log("[auto-webmcp] fillAriaField: S3 beforeinput threw:",a)}if(!c){n.textContent=r;let a=document.createRange();a.selectNodeContents(n),a.collapse(!1),s?.removeAllRanges(),s?.addRange(a),console.log("[auto-webmcp] fillAriaField: S4 textContent assignment done, textContent:",JSON.stringify((n.textContent??"").slice(0,80)))}n.dispatchEvent(new InputEvent("input",{bubbles:!0,cancelable:!0,inputType:"insertText",data:r})),console.log("[auto-webmcp] fillAriaField: done, final textContent:",JSON.stringify((n.textContent??"").slice(0,80)))}else console.log("[auto-webmcp] fillAriaField: not contentEditable, dispatching input/change only"),e.dispatchEvent(new Event("input",{bubbles:!0})),e.dispatchEvent(new Event("change",{bubbles:!0}))}function ae(e,t,o){let n={},i=new FormData(e),s=I.get(e);for(let[r,c]of i.entries())if(n[r]!==void 0){let a=n[r];Array.isArray(a)?a.push(c):n[r]=[a,c]}else n[r]=c;if(t)for(let r of Object.keys(t)){if(r in n)continue;if(s&&r in s){n[r]=s[r];continue}let c=U(e,r)??o?.get(r)??null;if(c)if(c instanceof HTMLInputElement&&c.type==="checkbox")n[r]=c.checked;else if(c instanceof HTMLInputElement||c instanceof HTMLTextAreaElement||c instanceof HTMLSelectElement)n[r]=c.value;else{let a=c.getAttribute("role");a==="checkbox"||a==="switch"?n[r]=c.getAttribute("aria-checked")==="true":n[r]=c.textContent?.trim()??""}}return n}function Ne(e,t){if(e instanceof HTMLInputElement){let o=e.type.toLowerCase();o==="checkbox"?ie(e,!!t):o==="radio"?e.value===String(t)&&(F?F.call(e,!0):e.checked=!0,e.dispatchEvent(new Event("change",{bubbles:!0}))):B(e,String(t??""))}else e instanceof HTMLTextAreaElement?B(e,String(t??"")):e instanceof HTMLSelectElement?se(e,t):Pe(e,t)}function Oe(e,t=800,o=150){return new Promise(n=>{let i=!1,s=null,r=()=>{i||(i=!0,c.disconnect(),s!==null&&clearTimeout(s),n())},c=new MutationObserver(()=>{s!==null&&clearTimeout(s),s=setTimeout(r,o)});c.observe(e,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),setTimeout(r,t),s=setTimeout(r,o)})}function Ct(e,t,o){let n=[];for(let[i,s]of Object.entries(t)){let r=U(e,i)??o?.get(i)??null;r&&(r instanceof HTMLInputElement&&r.type==="checkbox"?r.checked!==!!s&&n.push(i):(r instanceof HTMLInputElement||r instanceof HTMLTextAreaElement||r instanceof HTMLSelectElement)&&r.value!==String(s??"")&&n.push(i))}return n}function kt(e,t){return e?.inputSchema?.required?.length?e.inputSchema.required.filter(o=>!(o in t)):[]}async function qe(e,t){let o=String(t??"").trim();console.log("[auto-webmcp] fillComboboxButton: clicking button, value=",JSON.stringify(o)),e.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}));let n=await new Promise(c=>{let a=Date.now()+1e3,l=()=>{let u=document.querySelector('[role="listbox"]')??document.querySelector('[role="option"]')?.closest('[role="listbox"]')??null;if(u){c(u);return}if(Date.now()>=a){c(null);return}setTimeout(l,50)};l()});if(!n){console.warn("[auto-webmcp] fillComboboxButton: listbox did not appear after 1s");return}let i=Array.from(n.querySelectorAll('[role="option"]'));console.log("[auto-webmcp] fillComboboxButton: listbox has",i.length,"options");let s=o.toLowerCase(),r=i.find(c=>{let a=(c.getAttribute("data-value")??"").toLowerCase(),l=(c.getAttribute("aria-label")??"").toLowerCase(),u=(c.textContent??"").trim().toLowerCase();return a===s||l===s||u===s});r?(console.log("[auto-webmcp] fillComboboxButton: clicking option",r.textContent?.trim()),r.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))):console.warn("[auto-webmcp] fillComboboxButton: no option matched",JSON.stringify(o),"available:",i.map(c=>c.textContent?.trim()))}function Je(e,t,o){window.dispatchEvent(new CustomEvent(e,{detail:{form:t,toolName:o}}))}function Rt(e,t){if(e.dataset.noWebmcp!==void 0)return!0;for(let o of t.exclude)try{if(e.matches(o))return!0}catch{}return!1}function De(e,t){let o=`_${t}`;return`${e.slice(0,Math.max(1,64-o.length))}${o}`}function It(e){let t=new Set(z);for(let{form:o,name:n}of J())e&&o===e||t.add(n);return t}function je(e,t){let o=It(t);if(!o.has(e))return e;let n=2,i=De(e,n);for(;o.has(i);)n++,i=De(e,n);return i}function Ft(e){return!!e.getAttribute("toolname")?.trim().length}async function N(e,t){if(Rt(e,t))return;let o=ne(e);if(Ft(e)&&t.declarativeMode!=="force"){if(o&&await O(e),t.debug){let l=t.declarativeMode;console.log(`[auto-webmcp] Skipping imperative registration for native declarative form (mode=${l})`)}return}let n;for(let[l,u]of Object.entries(t.overrides))try{if(e.matches(l)){n=u;break}}catch{}let i=ye(e,n),s=je(i.name,e);s!==i.name&&t.debug&&console.warn(`[auto-webmcp] tool name collision: "${i.name}" renamed to "${s}"`),i.name=s,t.debug&&Wt(i.name,i.description);let r=Be(e,t,i.name,i);await Re(e,i,r),D.add(e),Ue++;let c=e.querySelector('[type="submit"], button[data-variant="primary"], button:not([type])')??null,a=window.__pendingSubmitBtns??={};o&&o!==i.name&&delete a[o],a[i.name]=c,t.debug&&console.log(`[auto-webmcp] Registered: ${i.name}`,i),Je("form:registered",e,i.name)}async function _t(e,t){let o=ne(e);if(!o)return;await O(e),D.delete(e);let n=window.__pendingSubmitBtns;n&&delete n[o],t.debug&&console.log(`[auto-webmcp] Unregistered: ${o}`),Je("form:unregistered",e,o)}var q=null,D=new WeakSet,Ue=0,le=new Map,Ot=300,V=null,$t=500,z=new Set;function We(e){V&&clearTimeout(V),V=setTimeout(()=>{V=null,Ve(e)},$t)}function ce(e){let t=e.tagName.toLowerCase();if(t==="input"||t==="textarea"||t==="select")return!0;let o=e.getAttribute("role");if(o&&_.includes(o)||e.querySelector("input, textarea, select"))return!0;for(let n of _)if(e.querySelector(`[role="${n}"]`))return!0;return!1}function ue(e,t){let o=le.get(e);o&&clearTimeout(o),le.set(e,setTimeout(()=>{le.delete(e),N(e,t)},Ot))}function Bt(e,t){let o=document.getElementById(e);o instanceof HTMLFormElement&&D.has(o)&&ue(o,t)}function Pt(e){let t=e.closest("form");if(t instanceof HTMLFormElement)return t;let o=e.form;if(o instanceof HTMLFormElement)return o;let n=e.getAttribute("form");if(n){let i=document.getElementById(n);if(i instanceof HTMLFormElement)return i}return null}function Nt(e){q||(q=new MutationObserver(t=>{for(let o of t){if(o.type==="attributes"&&o.target instanceof Element){let n=o.target,i=Pt(n);i&&D.has(i)?ue(i,e):n instanceof HTMLFormElement?N(n,e):ce(n)&&!n.closest("form")&&We(e),o.attributeName==="form"&&o.oldValue&&Bt(o.oldValue,e);continue}for(let n of o.addedNodes){if(!(n instanceof Element))continue;if(n instanceof HTMLFormElement){N(n,e);continue}let i=n.closest("form");i instanceof HTMLFormElement&&D.has(i)&&ce(n)&&ue(i,e);for(let s of Array.from(n.querySelectorAll("form")))N(s,e);ce(n)&&!n.closest("form")&&We(e)}for(let n of o.removedNodes){if(!(n instanceof Element))continue;let i=n instanceof HTMLFormElement?[n]:Array.from(n.querySelectorAll("form"));for(let s of i)_t(s,e)}}}),q.observe(document.body,{childList:!0,subtree:!0,attributes:!0,attributeOldValue:!0}))}function qt(e){window.addEventListener("hashchange",()=>P(e));let t={pushState:history.pushState.bind(history),replaceState:history.replaceState.bind(history)};history.pushState=function(...o){t.pushState(...o),P(e)},history.replaceState=function(...o){t.replaceState(...o),P(e)},window.addEventListener("popstate",()=>P(e))}async function P(e){let t=Array.from(document.querySelectorAll("form"));await Promise.allSettled(t.map(o=>N(o,e)))}var Dt=new Set(["password","hidden","file","submit","reset","button","image"]);async function Ve(e){if(!k())return;let t='[type="submit"]:not([disabled]), button[data-variant="primary"]:not([disabled])',o='[type="submit"], button[data-variant="primary"]',n=/subscribe|submit|sign[\s-]?up|send|join|go|search|post|tweet|publish|save/i,i=Array.from(document.querySelectorAll('input:not(form input), textarea:not(form textarea), select:not(form select), [role="textbox"]:not(form [role="textbox"]):not(input):not(textarea), [role="searchbox"]:not(form [role="searchbox"]):not(input):not(textarea), [contenteditable="true"]:not(form [contenteditable="true"]):not(input):not(textarea), button[role="combobox"]:not(form button[role="combobox"])')).filter(r=>{if(r instanceof HTMLInputElement&&Dt.has(r.type.toLowerCase()))return console.log(`[auto-webmcp] orphan: skipping excluded type "${r.type}" (name="${r.name}" id="${r.id}")`),!1;let c=r.getBoundingClientRect();return c.width===0||c.height===0?(console.log(`[auto-webmcp] orphan: skipping invisible input (name="${r.name}" id="${r.id}")`),!1):!0});if(console.log(`[auto-webmcp] orphan: found ${i.length} visible orphan input(s)`),i.length===0)return;let s=new Map;for(let r of i){let c=r.parentElement,a=r.parentElement??document.body;for(;c&&c!==document.body;){if(c.querySelector(o)!==null||Array.from(c.querySelectorAll("button")).some(u=>n.test(u.textContent??""))){a=c;break}c=c.parentElement}console.log(`[auto-webmcp] orphan: input (name="${r.name}" id="${r.id}") grouped into container`,a),s.has(a)||s.set(a,[]),s.get(a).push(r)}console.log(`[auto-webmcp] orphan: ${s.size} group(s) found`);for(let[r,c]of s){let a=Array.from(r.querySelectorAll(t)).filter(f=>{let g=f.getBoundingClientRect();return g.width>0&&g.height>0}),l=a[a.length-1]??null;if(!l){let f=Array.from(r.querySelectorAll(o)).filter(g=>{let T=g.getBoundingClientRect();return T.width>0&&T.height>0&&g.disabled});l=f[f.length-1]??null,l&&console.log(`[auto-webmcp] orphan: using disabled submit button as reference: "${l.textContent?.trim()}"`)}if(!l){let f=Array.from(r.querySelectorAll('button, [role="button"]')).filter(g=>{let T=g.getBoundingClientRect();return T.width>0&&T.height>0&&!g.disabled&&g.getAttribute("aria-disabled")!=="true"&&n.test(g.textContent??"")});l=f[f.length-1]??null,l&&console.log(`[auto-webmcp] orphan: using text-matched button in container: "${l.textContent?.trim()}"`)}if(!l){let f=r.closest('[role="dialog"], [aria-modal="true"]');if(f){let g=Array.from(f.querySelectorAll('button, [role="button"]')).filter(b=>{let v=b.getBoundingClientRect();return v.width>0&&v.height>0&&n.test(b.textContent??"")});console.log("[auto-webmcp] orphan: dialog buttons matching submit text:",g.map(b=>`"${b.textContent?.trim().slice(0,30)}" disabled=${b.disabled} aria-disabled=${b.getAttribute("aria-disabled")}`));let T=g.filter(b=>b.disabled||b.getAttribute("aria-disabled")==="true"),L=g.filter(b=>!b.disabled&&b.getAttribute("aria-disabled")!=="true"),M=T.length>0?T:L;l=M[M.length-1]??null,l&&console.log(`[auto-webmcp] orphan: using text-matched button in dialog: "${l.textContent?.trim().slice(0,40)}" disabled=${l.disabled} aria-disabled=${l.getAttribute("aria-disabled")}`)}}if(!l){let f=Array.from(document.querySelectorAll('button, [role="button"]')).filter(g=>{let T=g.getBoundingClientRect();return T.width>0&&T.height>0&&g.getAttribute("aria-disabled")!=="true"&&n.test(g.textContent??"")});l=f[f.length-1]??null,l&&console.log(`[auto-webmcp] orphan: using page-wide fallback submit button: "${l.textContent?.trim()}"`)}console.log("[auto-webmcp] orphan: submit button for group:",l?`"${l.textContent?.trim()}" disabled=${l.disabled}`:"none");let u=Ce(r,c,l);if(z.has(u.name)){console.log(`[auto-webmcp] orphan: "${u.name}" already registered, skipping`);continue}let d=je(u.name);d!==u.name&&e.debug&&console.warn(`[auto-webmcp] orphan tool name collision: "${u.name}" renamed to "${d}"`),u.name=d,console.log(`[auto-webmcp] orphan: tool="${u.name}" schema keys:`,Object.keys(u.inputSchema.properties));let m=[],E=u.inputSchema.properties,p=/^_r_[0-9a-z]+_$/i;for(let f of c){let g=f.id&&!p.test(f.id)?f.id:null,T=f.name||f.getAttribute("name")||f.dataset.webmcpName||g||f.getAttribute("aria-label")||f.getAttribute("placeholder")||null,L=T?T.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"").slice(0,64):null,M=!!(L&&E[L]);console.log(`[auto-webmcp] orphan: field (name="${f.name??""}" id="${f.id}") rawKey="${T}" safeKey="${L}" matched=${M}`),M&&m.push({key:L,el:f})}if(console.log(`[auto-webmcp] orphan: ${m.length}/${c.length} input(s) mapped to schema keys`),m.length===0){console.log(`[auto-webmcp] orphan: skipping group "${u.name}" \u2014 no inputs mapped to schema keys`);continue}let y=u.name,w=async(f,g)=>{console.log(`[auto-webmcp] orphan execute: tool="${y}" params=`,f),console.log("[auto-webmcp] orphan execute: inputPairs=",m.map(M=>M.key));for(let{key:M,el:b}of m)f[M]!==void 0?(console.log(`[auto-webmcp] orphan execute: filling key="${M}" value=`,f[M],"element=",b),b.getAttribute("role")==="combobox"&&b.tagName.toLowerCase()==="button"?await qe(b,f[M]):Ne(b,f[M]),console.log("[auto-webmcp] orphan execute: after fill, element value=",b.value)):console.log(`[auto-webmcp] orphan execute: key="${M}" not in params, skipping`);if(window.dispatchEvent(new CustomEvent("toolactivated",{detail:{toolName:y}})),!(e.autoSubmit||!!l?.hasAttribute("toolautosubmit")||l instanceof HTMLElement&&l.dataset.webmcpAutosubmit!==void 0||r.hasAttribute("toolautosubmit")||r instanceof HTMLElement&&r.dataset.webmcpAutosubmit!==void 0))return console.log("[auto-webmcp] orphan execute: autoSubmit=false, returning without clicking submit"),{content:[{type:"text",text:"Fields filled. Ready to submit."}]};console.log("[auto-webmcp] orphan execute: resolving submit button (up to 2s)...");let L=null;if(l&&document.contains(l)){let M=!l.disabled&&l.getAttribute("aria-disabled")!=="true",b=l.getBoundingClientRect();M&&b.width>0&&b.height>0&&(L=l,console.log(`[auto-webmcp] orphan execute: using captured submit button "${L.textContent?.trim()}"`))}if(!L){let M=Date.now()+2e3;for(;Date.now()<M;){let b=Array.from(r.querySelectorAll(t)).filter(K=>{let me=K.getBoundingClientRect();return me.width>0&&me.height>0}),v=b[b.length-1]??null;if(v){L=v;break}await new Promise(K=>setTimeout(K,100))}}if(!L){let M=Array.from((r!==document.body?r:document).querySelectorAll('button, [role="button"]')).filter(b=>{let v=b.getBoundingClientRect();return v.width>0&&v.height>0&&!b.disabled&&b.getAttribute("aria-disabled")!=="true"&&n.test(b.textContent??"")});L=M[M.length-1]??null,L&&console.log(`[auto-webmcp] orphan execute: using text-matched fallback button "${L.textContent?.trim()}"`)}return L?(console.log(`[auto-webmcp] orphan execute: clicking submit button "${L.textContent?.trim()}"`),L.click(),{content:[{type:"text",text:"Fields filled and form submitted."}]}):(console.warn("[auto-webmcp] orphan execute: submit button still disabled after 2s"),{content:[{type:"text",text:"Fields filled but the submit button is still disabled. The page may require additional input before submitting."}]})};try{let f={name:u.name,description:u.description,inputSchema:u.inputSchema,execute:w};u.annotations&&Object.keys(u.annotations).length>0&&(f.annotations=u.annotations),await navigator.modelContext.registerTool(f),z.add(u.name);let g=window.__pendingSubmitBtns??={};g[u.name]=l,e.debug&&console.log(`[auto-webmcp] Orphan tool registered: ${u.name}`,u)}catch{}}}function Wt(e,t){/^form_\d+$|^submit$|^form$/.test(e)&&console.warn(`[auto-webmcp] Tool "${e}" has a generic name. Consider adding a toolname or data-webmcp-name attribute.`),(!t||t==="Submit form")&&console.warn(`[auto-webmcp] Tool "${e}" has no meaningful description.`),/don'?t|do not|never|avoid|not for/i.test(t)&&console.warn(`[auto-webmcp] Tool "${e}" description contains negative instructions. Per spec best practices, prefer positive descriptions.`)}async function ze(e){document.readyState==="loading"&&await new Promise(t=>document.addEventListener("DOMContentLoaded",()=>t(),{once:!0})),Ue=0,z.clear(),Nt(e),qt(e),await P(e),await Ve(e)}function Ke(){q?.disconnect(),q=null}async function Ge(e){let t=de(e);return t.debug&&console.debug("[auto-webmcp] Initializing",{webmcpSupported:k(),config:t}),await ze(t),{destroy:async()=>{Ke(),await Ie()},getTools:J,isSupported:k()}}typeof window<"u"&&!window.__AUTO_WEBMCP_NO_AUTOINIT&&Ge();return tt(Jt);})();
2
2
  //# sourceMappingURL=auto-webmcp.iife.js.map