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