auto-webmcp 0.3.23 → 0.3.24

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