@mcp-b/extension-tools 0.2.1 → 0.2.2

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/index.js CHANGED
@@ -1,17 +1,17 @@
1
- import {z}from'zod';var d=class{constructor(e,t={}){this.server=e;this.options=t;}shouldRegisterTool(e){return this.options[e]!==false}formatError(e){return {content:[{type:"text",text:`Error: ${e instanceof Error?e.message:String(e)}`}],isError:true}}formatSuccess(e,t){return {content:[{type:"text",text:t?`${e}
2
- ${JSON.stringify(t,null,2)}`:e}]}}formatJson(e){return {content:[{type:"text",text:JSON.stringify(e,null,2)}]}}register(){let e=this.checkAvailability();if(!e.available){console.warn(`\u2717 ${this.apiName} API not available: ${e.message}`),e.details&&console.warn(` Details: ${e.details}`);return}console.log(`\u2713 ${this.apiName} API available`),this.registerTools();}};var Ae=class extends d{apiName="Alarms";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.alarms?typeof chrome.alarms.getAll!="function"?{available:!1,message:"chrome.alarms.getAll is not available",details:"The alarms API appears to be partially available. Check manifest permissions."}:(chrome.alarms.getAll(e=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"Alarms API is fully available"}):{available:!1,message:"chrome.alarms API is not defined",details:'This extension needs the "alarms" permission in its manifest.json'}}catch(e){return {available:false,message:"Failed to access chrome.alarms API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("createAlarm")&&this.registerCreateAlarm(),this.shouldRegisterTool("getAlarm")&&this.registerGetAlarm(),this.shouldRegisterTool("getAllAlarms")&&this.registerGetAllAlarms(),this.shouldRegisterTool("clearAlarm")&&this.registerClearAlarm(),this.shouldRegisterTool("clearAllAlarms")&&this.registerClearAllAlarms();}registerCreateAlarm(){this.server.registerTool("extension_tool_create_alarm",{description:"Create an alarm that fires at a specific time or periodically",inputSchema:{name:z.string().optional().describe("Optional name to identify this alarm"),delayInMinutes:z.number().min(.5).optional().describe("Time in minutes from now when the alarm should first fire. Minimum is 0.5 minutes (30 seconds)"),periodInMinutes:z.number().min(.5).optional().describe("If set, the alarm will repeat every periodInMinutes minutes after the initial event. Minimum is 0.5 minutes (30 seconds)"),when:z.number().optional().describe("Time at which the alarm should fire, in milliseconds past the epoch (e.g. Date.now() + n)")}},async({name:e,delayInMinutes:t,periodInMinutes:r,when:o})=>{try{if(t===void 0&&o===void 0)return this.formatError("Either delayInMinutes or when must be specified to create an alarm");let i={};t!==void 0&&(i.delayInMinutes=t),r!==void 0&&(i.periodInMinutes=r),o!==void 0&&(i.when=o),await new Promise((n,a)=>{e?chrome.alarms.create(e,i,()=>{chrome.runtime.lastError?a(new Error(chrome.runtime.lastError.message)):n();}):chrome.alarms.create(i,()=>{chrome.runtime.lastError?a(new Error(chrome.runtime.lastError.message)):n();});});let s=await new Promise((n,a)=>{chrome.alarms.get(e||"",c=>{chrome.runtime.lastError?a(new Error(chrome.runtime.lastError.message)):n(c);});});return this.formatSuccess("Alarm created successfully",{name:s?.name||e||"unnamed",scheduledTime:s?.scheduledTime,periodInMinutes:s?.periodInMinutes})}catch(i){return this.formatError(i)}});}registerGetAlarm(){this.server.registerTool("extension_tool_get_alarm",{description:"Get details about a specific alarm",inputSchema:{name:z.string().optional().describe("Name of the alarm to retrieve. If not specified, gets the default unnamed alarm")}},async({name:e})=>{try{let t=await new Promise((r,o)=>{e?chrome.alarms.get(e,i=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r(i);}):chrome.alarms.get(i=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r(i);});});return t?this.formatJson({name:t.name,scheduledTime:t.scheduledTime,scheduledTimeFormatted:new Date(t.scheduledTime).toISOString(),periodInMinutes:t.periodInMinutes}):this.formatSuccess("No alarm found",{name:e||"unnamed"})}catch(t){return this.formatError(t)}});}registerGetAllAlarms(){this.server.registerTool("extension_tool_get_all_alarms",{description:"Get all active alarms",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.alarms.getAll(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({count:e.length,alarms:e.map(t=>({name:t.name,scheduledTime:t.scheduledTime,scheduledTimeFormatted:new Date(t.scheduledTime).toISOString(),periodInMinutes:t.periodInMinutes}))})}catch(e){return this.formatError(e)}});}registerClearAlarm(){this.server.registerTool("extension_tool_clear_alarm",{description:"Clear a specific alarm",inputSchema:{name:z.string().optional().describe("Name of the alarm to clear. If not specified, clears the default unnamed alarm")}},async({name:e})=>{try{return await new Promise((r,o)=>{e?chrome.alarms.clear(e,i=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r(i);}):chrome.alarms.clear(i=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r(i);});})?this.formatSuccess("Alarm cleared successfully",{name:e||"unnamed"}):this.formatSuccess("No alarm found to clear",{name:e||"unnamed"})}catch(t){return this.formatError(t)}});}registerClearAllAlarms(){this.server.registerTool("extension_tool_clear_all_alarms",{description:"Clear all alarms",inputSchema:{}},async()=>{try{let e=await new Promise((r,o)=>{chrome.alarms.getAll(i=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r(i);});});return await new Promise((r,o)=>{chrome.alarms.clearAll(i=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r(i);});})?this.formatSuccess("All alarms cleared successfully",{clearedCount:e.length,clearedAlarms:e.map(r=>r.name)}):this.formatSuccess("No alarms to clear")}catch(e){return this.formatError(e)}});}};var Ie=class extends d{apiName="Audio";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.audio?typeof chrome.audio.getDevices!="function"?{available:!1,message:"chrome.audio.getDevices is not available",details:"The audio API appears to be partially available. Check manifest permissions and ensure you are on ChromeOS."}:(chrome.audio.getDevices({},e=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"Audio API is fully available"}):{available:!1,message:"chrome.audio API is not defined",details:'This extension needs the "audio" permission in its manifest.json and only works on ChromeOS'}}catch(e){return {available:false,message:"Failed to access chrome.audio API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("getDevices")&&this.registerGetDevices(),this.shouldRegisterTool("getMute")&&this.registerGetMute(),this.shouldRegisterTool("setActiveDevices")&&this.registerSetActiveDevices(),this.shouldRegisterTool("setMute")&&this.registerSetMute(),this.shouldRegisterTool("setProperties")&&this.registerSetProperties();}registerGetDevices(){this.server.registerTool("extension_tool_get_audio_devices",{description:"Get a list of audio devices filtered based on criteria",inputSchema:{isActive:z.boolean().optional().describe("If set, only audio devices whose active state matches this value will be returned"),streamTypes:z.array(z.enum(["INPUT","OUTPUT"])).optional().describe("If set, only audio devices whose stream type is included in this list will be returned")}},async({isActive:e,streamTypes:t})=>{try{let r={};e!==void 0&&(r.isActive=e),t!==void 0&&(r.streamTypes=t);let o=await new Promise((i,s)=>{chrome.audio.getDevices(r,n=>{chrome.runtime.lastError?s(new Error(chrome.runtime.lastError.message)):i(n);});});return this.formatJson({count:o.length,devices:o.map(i=>({id:i.id,deviceName:i.deviceName,deviceType:i.deviceType,displayName:i.displayName,isActive:i.isActive,level:i.level,stableDeviceId:i.stableDeviceId,streamType:i.streamType}))})}catch(r){return this.formatError(r)}});}registerGetMute(){this.server.registerTool("extension_tool_get_audio_mute",{description:"Get the system-wide mute state for the specified stream type",inputSchema:{streamType:z.enum(["INPUT","OUTPUT"]).describe("Stream type for which mute state should be fetched")}},async({streamType:e})=>{try{let t=await new Promise((r,o)=>{chrome.audio.getMute(e,i=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r(i);});});return this.formatJson({streamType:e,isMuted:t})}catch(t){return this.formatError(t)}});}registerSetActiveDevices(){this.server.registerTool("extension_tool_set_active_audio_devices",{description:"Set lists of active input and/or output devices",inputSchema:{input:z.array(z.string()).optional().describe("List of input device IDs that should be active. Leave unset to not affect input devices"),output:z.array(z.string()).optional().describe("List of output device IDs that should be active. Leave unset to not affect output devices")}},async({input:e,output:t})=>{try{if(e===void 0&&t===void 0)return this.formatError("At least one of input or output device lists must be specified");let r={};return e!==void 0&&(r.input=e),t!==void 0&&(r.output=t),await new Promise((o,i)=>{chrome.audio.setActiveDevices(r,()=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o();});}),this.formatSuccess("Active audio devices set successfully",{inputDevices:e,outputDevices:t})}catch(r){return this.formatError(r)}});}registerSetMute(){this.server.registerTool("extension_tool_set_audio_mute",{description:"Set mute state for a stream type. The mute state will apply to all audio devices with the specified audio stream type",inputSchema:{streamType:z.enum(["INPUT","OUTPUT"]).describe("Stream type for which mute state should be set"),isMuted:z.boolean().describe("New mute value")}},async({streamType:e,isMuted:t})=>{try{return await new Promise((r,o)=>{chrome.audio.setMute(e,t,()=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r();});}),this.formatSuccess("Audio mute state set successfully",{streamType:e,isMuted:t})}catch(r){return this.formatError(r)}});}registerSetProperties(){this.server.registerTool("extension_tool_set_audio_device_properties",{description:"Set the properties for the input or output device",inputSchema:{id:z.string().describe("ID of the audio device to modify"),level:z.number().min(0).max(100).optional().describe("The audio device's desired sound level. For input devices, represents gain. For output devices, represents volume")}},async({id:e,level:t})=>{try{let r={};return t!==void 0&&(r.level=t),await new Promise((o,i)=>{chrome.audio.setProperties(e,r,()=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o();});}),this.formatSuccess("Audio device properties set successfully",{deviceId:e,level:t})}catch(r){return this.formatError(r)}});}};var Re=class extends d{apiName="Bookmarks";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.bookmarks?typeof chrome.bookmarks.getTree!="function"?{available:!1,message:"chrome.bookmarks.getTree is not available",details:"The bookmarks API appears to be partially available. Check manifest permissions."}:(chrome.bookmarks.getTree(e=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"Bookmarks API is fully available"}):{available:!1,message:"chrome.bookmarks API is not defined",details:'This extension needs the "bookmarks" permission in its manifest.json'}}catch(e){return {available:false,message:"Failed to access chrome.bookmarks API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("create")&&this.registerCreate(),this.shouldRegisterTool("get")&&this.registerGet(),this.shouldRegisterTool("getChildren")&&this.registerGetChildren(),this.shouldRegisterTool("getRecent")&&this.registerGetRecent(),this.shouldRegisterTool("getSubTree")&&this.registerGetSubTree(),this.shouldRegisterTool("getTree")&&this.registerGetTree(),this.shouldRegisterTool("move")&&this.registerMove(),this.shouldRegisterTool("remove")&&this.registerRemove(),this.shouldRegisterTool("removeTree")&&this.registerRemoveTree(),this.shouldRegisterTool("search")&&this.registerSearch(),this.shouldRegisterTool("update")&&this.registerUpdate();}registerCreate(){this.server.registerTool("extension_tool_create_bookmark",{description:"Create a bookmark or folder under the specified parent. If url is not provided, it will be a folder",inputSchema:{parentId:z.string().optional().describe("Parent folder ID. Defaults to the Other Bookmarks folder"),title:z.string().optional().describe("The title of the bookmark or folder"),url:z.string().optional().describe("The URL for the bookmark. Omit for folders"),index:z.number().optional().describe("The position within the parent folder")}},async({parentId:e,title:t,url:r,index:o})=>{try{let i={};e!==void 0&&(i.parentId=e),t!==void 0&&(i.title=t),r!==void 0&&(i.url=r),o!==void 0&&(i.index=o);let s=await new Promise((n,a)=>{chrome.bookmarks.create(i,c=>{chrome.runtime.lastError?a(new Error(chrome.runtime.lastError.message)):n(c);});});return this.formatJson({id:s.id,title:s.title,url:s.url,parentId:s.parentId,index:s.index,dateAdded:s.dateAdded,type:s.url?"bookmark":"folder"})}catch(i){return this.formatError(i)}});}registerGet(){this.server.registerTool("extension_tool_get_bookmark",{description:"Retrieve the specified bookmark(s) by ID",inputSchema:{idOrIdList:z.union([z.string(),z.array(z.string())]).describe("A single bookmark ID or array of bookmark IDs")}},async({idOrIdList:e})=>{try{let t=await new Promise((r,o)=>{chrome.bookmarks.get(e,i=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r(i);});});return this.formatJson({count:t.length,bookmarks:t.map(r=>({id:r.id,title:r.title,url:r.url,parentId:r.parentId,index:r.index,dateAdded:r.dateAdded,dateAddedFormatted:r.dateAdded?new Date(r.dateAdded).toISOString():void 0,type:r.url?"bookmark":"folder"}))})}catch(t){return this.formatError(t)}});}registerGetChildren(){this.server.registerTool("extension_tool_get_bookmark_children",{description:"Retrieve the children of the specified bookmark folder",inputSchema:{id:z.string().describe("The ID of the folder to get children from")}},async({id:e})=>{try{let t=await new Promise((r,o)=>{chrome.bookmarks.getChildren(e,i=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r(i);});});return this.formatJson({parentId:e,count:t.length,children:t.map(r=>({id:r.id,title:r.title,url:r.url,parentId:r.parentId,index:r.index,dateAdded:r.dateAdded,dateAddedFormatted:r.dateAdded?new Date(r.dateAdded).toISOString():void 0,type:r.url?"bookmark":"folder"}))})}catch(t){return this.formatError(t)}});}registerGetRecent(){this.server.registerTool("extension_tool_get_recent_bookmarks",{description:"Retrieve the recently added bookmarks",inputSchema:{numberOfItems:z.number().min(1).describe("The maximum number of items to return")}},async({numberOfItems:e})=>{try{let t=await new Promise((r,o)=>{chrome.bookmarks.getRecent(e,i=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r(i);});});return this.formatJson({count:t.length,recentBookmarks:t.map(r=>({id:r.id,title:r.title,url:r.url,parentId:r.parentId,index:r.index,dateAdded:r.dateAdded,dateAddedFormatted:r.dateAdded?new Date(r.dateAdded).toISOString():void 0}))})}catch(t){return this.formatError(t)}});}registerGetSubTree(){this.server.registerTool("extension_tool_get_bookmark_subtree",{description:"Retrieve part of the bookmarks hierarchy, starting at the specified node",inputSchema:{id:z.string().describe("The ID of the root of the subtree to retrieve")}},async({id:e})=>{try{let t=await new Promise((o,i)=>{chrome.bookmarks.getSubTree(e,s=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o(s);});}),r=o=>({id:o.id,title:o.title,url:o.url,parentId:o.parentId,index:o.index,dateAdded:o.dateAdded,dateAddedFormatted:o.dateAdded?new Date(o.dateAdded).toISOString():void 0,type:o.url?"bookmark":"folder",children:o.children?o.children.map(r):void 0});return this.formatJson({rootId:e,subtree:t.map(r)})}catch(t){return this.formatError(t)}});}registerGetTree(){this.server.registerTool("extension_tool_get_bookmark_tree",{description:"Retrieve the entire bookmarks hierarchy",inputSchema:{}},async()=>{try{let e=await new Promise((r,o)=>{chrome.bookmarks.getTree(i=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r(i);});}),t=r=>({id:r.id,title:r.title,url:r.url,parentId:r.parentId,index:r.index,dateAdded:r.dateAdded,dateAddedFormatted:r.dateAdded?new Date(r.dateAdded).toISOString():void 0,type:r.url?"bookmark":"folder",children:r.children?r.children.map(t):void 0});return this.formatJson({tree:e.map(t)})}catch(e){return this.formatError(e)}});}registerMove(){this.server.registerTool("extension_tool_move_bookmark",{description:"Move the specified bookmark or folder to a new location",inputSchema:{id:z.string().describe("The ID of the bookmark or folder to move"),parentId:z.string().optional().describe("The new parent folder ID"),index:z.number().optional().describe("The new position within the parent folder")}},async({id:e,parentId:t,index:r})=>{try{let o={};t!==void 0&&(o.parentId=t),r!==void 0&&(o.index=r);let i=await new Promise((s,n)=>{chrome.bookmarks.move(e,o,a=>{chrome.runtime.lastError?n(new Error(chrome.runtime.lastError.message)):s(a);});});return this.formatSuccess("Bookmark moved successfully",{id:i.id,title:i.title,url:i.url,parentId:i.parentId,index:i.index,type:i.url?"bookmark":"folder"})}catch(o){return this.formatError(o)}});}registerRemove(){this.server.registerTool("extension_tool_remove_bookmark",{description:"Remove a bookmark or an empty bookmark folder",inputSchema:{id:z.string().describe("The ID of the bookmark or empty folder to remove")}},async({id:e})=>{try{return await new Promise((t,r)=>{chrome.bookmarks.remove(e,()=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t();});}),this.formatSuccess("Bookmark removed successfully",{id:e})}catch(t){return this.formatError(t)}});}registerRemoveTree(){this.server.registerTool("extension_tool_remove_bookmark_tree",{description:"Recursively remove a bookmark folder and all its contents",inputSchema:{id:z.string().describe("The ID of the folder to remove recursively")}},async({id:e})=>{try{return await new Promise((t,r)=>{chrome.bookmarks.removeTree(e,()=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t();});}),this.formatSuccess("Bookmark folder and all contents removed successfully",{id:e})}catch(t){return this.formatError(t)}});}registerSearch(){this.server.registerTool("extension_tool_search_bookmarks",{description:"Search for bookmarks matching the given query",inputSchema:{query:z.union([z.string(),z.object({query:z.string().optional().describe("Words and phrases to match against URLs and titles"),url:z.string().optional().describe("URL to match exactly"),title:z.string().optional().describe("Title to match exactly")})]).describe("Search query string or object with specific search criteria")}},async({query:e})=>{try{let t=await new Promise((r,o)=>{chrome.bookmarks.search(e,i=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r(i);});});return this.formatJson({query:typeof e=="string"?e:JSON.stringify(e),count:t.length,results:t.map(r=>({id:r.id,title:r.title,url:r.url,parentId:r.parentId,index:r.index,dateAdded:r.dateAdded,dateAddedFormatted:r.dateAdded?new Date(r.dateAdded).toISOString():void 0,type:r.url?"bookmark":"folder"}))})}catch(t){return this.formatError(t)}});}registerUpdate(){this.server.registerTool("extension_tool_update_bookmark",{description:"Update the properties of a bookmark or folder. Only title and url can be changed",inputSchema:{id:z.string().describe("The ID of the bookmark or folder to update"),title:z.string().optional().describe("The new title"),url:z.string().optional().describe("The new URL (bookmarks only)")}},async({id:e,title:t,url:r})=>{try{let o={};if(t!==void 0&&(o.title=t),r!==void 0&&(o.url=r),Object.keys(o).length===0)return this.formatError("At least one property (title or url) must be specified to update");let i=await new Promise((s,n)=>{chrome.bookmarks.update(e,o,a=>{chrome.runtime.lastError?n(new Error(chrome.runtime.lastError.message)):s(a);});});return this.formatSuccess("Bookmark updated successfully",{id:i.id,title:i.title,url:i.url,parentId:i.parentId,index:i.index,type:i.url?"bookmark":"folder",changes:o})}catch(o){return this.formatError(o)}});}};var Pe=class extends d{apiName="BrowsingData";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.browsingData?typeof chrome.browsingData.settings!="function"?{available:!1,message:"chrome.browsingData.settings is not available",details:"The browsingData API appears to be partially available. Check manifest permissions."}:(chrome.browsingData.settings(e=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"BrowsingData API is fully available"}):{available:!1,message:"chrome.browsingData API is not defined",details:'This extension needs the "browsingData" permission in its manifest.json'}}catch(e){return {available:false,message:"Failed to access chrome.browsingData API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("remove")&&this.registerRemove(),this.shouldRegisterTool("removeAppcache")&&this.registerRemoveAppcache(),this.shouldRegisterTool("removeCache")&&this.registerRemoveCache(),this.shouldRegisterTool("removeCacheStorage")&&this.registerRemoveCacheStorage(),this.shouldRegisterTool("removeCookies")&&this.registerRemoveCookies(),this.shouldRegisterTool("removeDownloads")&&this.registerRemoveDownloads(),this.shouldRegisterTool("removeFileSystems")&&this.registerRemoveFileSystems(),this.shouldRegisterTool("removeFormData")&&this.registerRemoveFormData(),this.shouldRegisterTool("removeHistory")&&this.registerRemoveHistory(),this.shouldRegisterTool("removeIndexedDB")&&this.registerRemoveIndexedDB(),this.shouldRegisterTool("removeLocalStorage")&&this.registerRemoveLocalStorage(),this.shouldRegisterTool("removePasswords")&&this.registerRemovePasswords(),this.shouldRegisterTool("removeServiceWorkers")&&this.registerRemoveServiceWorkers(),this.shouldRegisterTool("removeWebSQL")&&this.registerRemoveWebSQL(),this.shouldRegisterTool("settings")&&this.registerSettings();}registerRemove(){this.server.registerTool("extension_tool_remove_browsing_data",{description:"Remove various types of browsing data from the user's profile",inputSchema:{since:z.number().optional().describe("Remove data accumulated on or after this date (milliseconds since epoch)"),origins:z.array(z.string()).optional().describe("Only remove data for these origins (cookies, storage, cache only)"),excludeOrigins:z.array(z.string()).optional().describe("Exclude data for these origins from deletion"),originTypes:z.object({unprotectedWeb:z.boolean().optional(),protectedWeb:z.boolean().optional(),extension:z.boolean().optional()}).optional().describe("Types of origins to clear"),appcache:z.boolean().optional().describe("Remove websites' appcaches"),cache:z.boolean().optional().describe("Remove browser cache"),cacheStorage:z.boolean().optional().describe("Remove cache storage"),cookies:z.boolean().optional().describe("Remove cookies"),downloads:z.boolean().optional().describe("Remove download list"),fileSystems:z.boolean().optional().describe("Remove websites' file systems"),formData:z.boolean().optional().describe("Remove stored form data"),history:z.boolean().optional().describe("Remove browser history"),indexedDB:z.boolean().optional().describe("Remove IndexedDB data"),localStorage:z.boolean().optional().describe("Remove local storage data"),passwords:z.boolean().optional().describe("Remove stored passwords"),serviceWorkers:z.boolean().optional().describe("Remove service workers"),webSQL:z.boolean().optional().describe("Remove WebSQL data")}},async({since:e,origins:t,excludeOrigins:r,originTypes:o,appcache:i,cache:s,cacheStorage:n,cookies:a,downloads:c,fileSystems:u,formData:m,history:g,indexedDB:w,localStorage:k,passwords:R,serviceWorkers:D,webSQL:ce})=>{try{let V={};e!==void 0&&(V.since=e),t!==void 0&&(V.origins=t),r!==void 0&&(V.excludeOrigins=r),o!==void 0&&(V.originTypes=o);let L={};return i!==void 0&&(L.appcache=i),s!==void 0&&(L.cache=s),n!==void 0&&(L.cacheStorage=n),a!==void 0&&(L.cookies=a),c!==void 0&&(L.downloads=c),u!==void 0&&(L.fileSystems=u),m!==void 0&&(L.formData=m),g!==void 0&&(L.history=g),w!==void 0&&(L.indexedDB=w),k!==void 0&&(L.localStorage=k),R!==void 0&&(L.passwords=R),D!==void 0&&(L.serviceWorkers=D),ce!==void 0&&(L.webSQL=ce),await new Promise((se,Se)=>{chrome.browsingData.remove(V,L,()=>{chrome.runtime.lastError?Se(new Error(chrome.runtime.lastError.message)):se();});}),this.formatSuccess("Browsing data removed successfully",{options:V,dataTypes:Object.keys(L).filter(se=>L[se])})}catch(V){return this.formatError(V)}});}registerRemoveAppcache(){this.server.registerTool("extension_tool_remove_appcache",{description:"Remove websites' appcache data",inputSchema:{since:z.number().optional().describe("Remove data accumulated on or after this date (milliseconds since epoch)"),origins:z.array(z.string()).optional().describe("Only remove data for these origins"),excludeOrigins:z.array(z.string()).optional().describe("Exclude data for these origins from deletion"),originTypes:z.object({unprotectedWeb:z.boolean().optional(),protectedWeb:z.boolean().optional(),extension:z.boolean().optional()}).optional().describe("Types of origins to clear")}},async({since:e,origins:t,excludeOrigins:r,originTypes:o})=>{try{let i={};return e!==void 0&&(i.since=e),t!==void 0&&(i.origins=t),r!==void 0&&(i.excludeOrigins=r),o!==void 0&&(i.originTypes=o),await new Promise((s,n)=>{chrome.browsingData.removeAppcache(i,()=>{chrome.runtime.lastError?n(new Error(chrome.runtime.lastError.message)):s();});}),this.formatSuccess("Appcache data removed successfully",{options:i})}catch(i){return this.formatError(i)}});}registerRemoveCache(){this.server.registerTool("extension_tool_remove_cache",{description:"Remove browser cache",inputSchema:{since:z.number().optional().describe("Remove data accumulated on or after this date (milliseconds since epoch)"),origins:z.array(z.string()).optional().describe("Only remove data for these origins"),excludeOrigins:z.array(z.string()).optional().describe("Exclude data for these origins from deletion"),originTypes:z.object({unprotectedWeb:z.boolean().optional(),protectedWeb:z.boolean().optional(),extension:z.boolean().optional()}).optional().describe("Types of origins to clear")}},async({since:e,origins:t,excludeOrigins:r,originTypes:o})=>{try{let i={};return e!==void 0&&(i.since=e),t!==void 0&&(i.origins=t),r!==void 0&&(i.excludeOrigins=r),o!==void 0&&(i.originTypes=o),await new Promise((s,n)=>{chrome.browsingData.removeCache(i,()=>{chrome.runtime.lastError?n(new Error(chrome.runtime.lastError.message)):s();});}),this.formatSuccess("Cache removed successfully",{options:i})}catch(i){return this.formatError(i)}});}registerRemoveCacheStorage(){this.server.registerTool("extension_tool_remove_cache_storage",{description:"Remove websites' cache storage data",inputSchema:{since:z.number().optional().describe("Remove data accumulated on or after this date (milliseconds since epoch)"),origins:z.array(z.string()).optional().describe("Only remove data for these origins"),excludeOrigins:z.array(z.string()).optional().describe("Exclude data for these origins from deletion"),originTypes:z.object({unprotectedWeb:z.boolean().optional(),protectedWeb:z.boolean().optional(),extension:z.boolean().optional()}).optional().describe("Types of origins to clear")}},async({since:e,origins:t,excludeOrigins:r,originTypes:o})=>{try{let i={};return e!==void 0&&(i.since=e),t!==void 0&&(i.origins=t),r!==void 0&&(i.excludeOrigins=r),o!==void 0&&(i.originTypes=o),await new Promise((s,n)=>{chrome.browsingData.removeCacheStorage(i,()=>{chrome.runtime.lastError?n(new Error(chrome.runtime.lastError.message)):s();});}),this.formatSuccess("Cache storage removed successfully",{options:i})}catch(i){return this.formatError(i)}});}registerRemoveCookies(){this.server.registerTool("extension_tool_remove_cookies",{description:"Remove browser cookies and server-bound certificates",inputSchema:{since:z.number().optional().describe("Remove data accumulated on or after this date (milliseconds since epoch)"),origins:z.array(z.string()).optional().describe("Only remove data for these origins"),excludeOrigins:z.array(z.string()).optional().describe("Exclude data for these origins from deletion"),originTypes:z.object({unprotectedWeb:z.boolean().optional(),protectedWeb:z.boolean().optional(),extension:z.boolean().optional()}).optional().describe("Types of origins to clear")}},async({since:e,origins:t,excludeOrigins:r,originTypes:o})=>{try{let i={};return e!==void 0&&(i.since=e),t!==void 0&&(i.origins=t),r!==void 0&&(i.excludeOrigins=r),o!==void 0&&(i.originTypes=o),await new Promise((s,n)=>{chrome.browsingData.removeCookies(i,()=>{chrome.runtime.lastError?n(new Error(chrome.runtime.lastError.message)):s();});}),this.formatSuccess("Cookies removed successfully",{options:i})}catch(i){return this.formatError(i)}});}registerRemoveDownloads(){this.server.registerTool("extension_tool_remove_downloads",{description:"Remove browser download list (not the downloaded files themselves)",inputSchema:{since:z.number().optional().describe("Remove data accumulated on or after this date (milliseconds since epoch)"),originTypes:z.object({unprotectedWeb:z.boolean().optional(),protectedWeb:z.boolean().optional(),extension:z.boolean().optional()}).optional().describe("Types of origins to clear")}},async({since:e,originTypes:t})=>{try{let r={};return e!==void 0&&(r.since=e),t!==void 0&&(r.originTypes=t),await new Promise((o,i)=>{chrome.browsingData.removeDownloads(r,()=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o();});}),this.formatSuccess("Download list removed successfully",{options:r})}catch(r){return this.formatError(r)}});}registerRemoveFileSystems(){this.server.registerTool("extension_tool_remove_file_systems",{description:"Remove websites' file system data",inputSchema:{since:z.number().optional().describe("Remove data accumulated on or after this date (milliseconds since epoch)"),origins:z.array(z.string()).optional().describe("Only remove data for these origins"),excludeOrigins:z.array(z.string()).optional().describe("Exclude data for these origins from deletion"),originTypes:z.object({unprotectedWeb:z.boolean().optional(),protectedWeb:z.boolean().optional(),extension:z.boolean().optional()}).optional().describe("Types of origins to clear")}},async({since:e,origins:t,excludeOrigins:r,originTypes:o})=>{try{let i={};return e!==void 0&&(i.since=e),t!==void 0&&(i.origins=t),r!==void 0&&(i.excludeOrigins=r),o!==void 0&&(i.originTypes=o),await new Promise((s,n)=>{chrome.browsingData.removeFileSystems(i,()=>{chrome.runtime.lastError?n(new Error(chrome.runtime.lastError.message)):s();});}),this.formatSuccess("File systems removed successfully",{options:i})}catch(i){return this.formatError(i)}});}registerRemoveFormData(){this.server.registerTool("extension_tool_remove_form_data",{description:"Remove browser stored form data (autofill)",inputSchema:{since:z.number().optional().describe("Remove data accumulated on or after this date (milliseconds since epoch)"),originTypes:z.object({unprotectedWeb:z.boolean().optional(),protectedWeb:z.boolean().optional(),extension:z.boolean().optional()}).optional().describe("Types of origins to clear")}},async({since:e,originTypes:t})=>{try{let r={};return e!==void 0&&(r.since=e),t!==void 0&&(r.originTypes=t),await new Promise((o,i)=>{chrome.browsingData.removeFormData(r,()=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o();});}),this.formatSuccess("Form data removed successfully",{options:r})}catch(r){return this.formatError(r)}});}registerRemoveHistory(){this.server.registerTool("extension_tool_remove_history",{description:"Remove browser history",inputSchema:{since:z.number().optional().describe("Remove data accumulated on or after this date (milliseconds since epoch)"),originTypes:z.object({unprotectedWeb:z.boolean().optional(),protectedWeb:z.boolean().optional(),extension:z.boolean().optional()}).optional().describe("Types of origins to clear")}},async({since:e,originTypes:t})=>{try{let r={};return e!==void 0&&(r.since=e),t!==void 0&&(r.originTypes=t),await new Promise((o,i)=>{chrome.browsingData.removeHistory(r,()=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o();});}),this.formatSuccess("History removed successfully",{options:r})}catch(r){return this.formatError(r)}});}registerRemoveIndexedDB(){this.server.registerTool("extension_tool_remove_indexed_db",{description:"Remove websites' IndexedDB data",inputSchema:{since:z.number().optional().describe("Remove data accumulated on or after this date (milliseconds since epoch)"),origins:z.array(z.string()).optional().describe("Only remove data for these origins"),excludeOrigins:z.array(z.string()).optional().describe("Exclude data for these origins from deletion"),originTypes:z.object({unprotectedWeb:z.boolean().optional(),protectedWeb:z.boolean().optional(),extension:z.boolean().optional()}).optional().describe("Types of origins to clear")}},async({since:e,origins:t,excludeOrigins:r,originTypes:o})=>{try{let i={};return e!==void 0&&(i.since=e),t!==void 0&&(i.origins=t),r!==void 0&&(i.excludeOrigins=r),o!==void 0&&(i.originTypes=o),await new Promise((s,n)=>{chrome.browsingData.removeIndexedDB(i,()=>{chrome.runtime.lastError?n(new Error(chrome.runtime.lastError.message)):s();});}),this.formatSuccess("IndexedDB data removed successfully",{options:i})}catch(i){return this.formatError(i)}});}registerRemoveLocalStorage(){this.server.registerTool("extension_tool_remove_local_storage",{description:"Remove websites' local storage data",inputSchema:{since:z.number().optional().describe("Remove data accumulated on or after this date (milliseconds since epoch)"),origins:z.array(z.string()).optional().describe("Only remove data for these origins"),excludeOrigins:z.array(z.string()).optional().describe("Exclude data for these origins from deletion"),originTypes:z.object({unprotectedWeb:z.boolean().optional(),protectedWeb:z.boolean().optional(),extension:z.boolean().optional()}).optional().describe("Types of origins to clear")}},async({since:e,origins:t,excludeOrigins:r,originTypes:o})=>{try{let i={};return e!==void 0&&(i.since=e),t!==void 0&&(i.origins=t),r!==void 0&&(i.excludeOrigins=r),o!==void 0&&(i.originTypes=o),await new Promise((s,n)=>{chrome.browsingData.removeLocalStorage(i,()=>{chrome.runtime.lastError?n(new Error(chrome.runtime.lastError.message)):s();});}),this.formatSuccess("Local storage removed successfully",{options:i})}catch(i){return this.formatError(i)}});}registerRemovePasswords(){this.server.registerTool("extension_tool_remove_passwords",{description:"Remove browser stored passwords",inputSchema:{since:z.number().optional().describe("Remove data accumulated on or after this date (milliseconds since epoch)"),originTypes:z.object({unprotectedWeb:z.boolean().optional(),protectedWeb:z.boolean().optional(),extension:z.boolean().optional()}).optional().describe("Types of origins to clear")}},async({since:e,originTypes:t})=>{try{let r={};return e!==void 0&&(r.since=e),t!==void 0&&(r.originTypes=t),await new Promise((o,i)=>{chrome.browsingData.removePasswords(r,()=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o();});}),this.formatSuccess("Passwords removed successfully",{options:r})}catch(r){return this.formatError(r)}});}registerRemoveServiceWorkers(){this.server.registerTool("extension_tool_remove_service_workers",{description:"Remove websites' service workers",inputSchema:{since:z.number().optional().describe("Remove data accumulated on or after this date (milliseconds since epoch)"),origins:z.array(z.string()).optional().describe("Only remove data for these origins"),excludeOrigins:z.array(z.string()).optional().describe("Exclude data for these origins from deletion"),originTypes:z.object({unprotectedWeb:z.boolean().optional(),protectedWeb:z.boolean().optional(),extension:z.boolean().optional()}).optional().describe("Types of origins to clear")}},async({since:e,origins:t,excludeOrigins:r,originTypes:o})=>{try{let i={};return e!==void 0&&(i.since=e),t!==void 0&&(i.origins=t),r!==void 0&&(i.excludeOrigins=r),o!==void 0&&(i.originTypes=o),await new Promise((s,n)=>{chrome.browsingData.removeServiceWorkers(i,()=>{chrome.runtime.lastError?n(new Error(chrome.runtime.lastError.message)):s();});}),this.formatSuccess("Service workers removed successfully",{options:i})}catch(i){return this.formatError(i)}});}registerRemoveWebSQL(){this.server.registerTool("extension_tool_remove_web_sql",{description:"Remove websites' WebSQL data",inputSchema:{since:z.number().optional().describe("Remove data accumulated on or after this date (milliseconds since epoch)"),origins:z.array(z.string()).optional().describe("Only remove data for these origins"),excludeOrigins:z.array(z.string()).optional().describe("Exclude data for these origins from deletion"),originTypes:z.object({unprotectedWeb:z.boolean().optional(),protectedWeb:z.boolean().optional(),extension:z.boolean().optional()}).optional().describe("Types of origins to clear")}},async({since:e,origins:t,excludeOrigins:r,originTypes:o})=>{try{let i={};return e!==void 0&&(i.since=e),t!==void 0&&(i.origins=t),r!==void 0&&(i.excludeOrigins=r),o!==void 0&&(i.originTypes=o),await new Promise((s,n)=>{chrome.browsingData.removeWebSQL(i,()=>{chrome.runtime.lastError?n(new Error(chrome.runtime.lastError.message)):s();});}),this.formatSuccess("WebSQL data removed successfully",{options:i})}catch(i){return this.formatError(i)}});}registerSettings(){this.server.registerTool("extension_tool_get_browsing_data_settings",{description:"Get current browsing data settings from the Clear browsing data UI",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.browsingData.settings(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({dataRemovalPermitted:e.dataRemovalPermitted,dataToRemove:e.dataToRemove,options:e.options})}catch(e){return this.formatError(e)}});}};var Ce=class extends d{apiName="CertificateProvider";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.certificateProvider?typeof chrome.certificateProvider.setCertificates!="function"?{available:!1,message:"chrome.certificateProvider.setCertificates is not available",details:"The certificateProvider API appears to be partially available. Check manifest permissions and ensure running on ChromeOS."}:{available:!0,message:"CertificateProvider API is fully available"}:{available:!1,message:"chrome.certificateProvider API is not defined",details:'This extension needs the "certificateProvider" permission in its manifest.json and only works on ChromeOS'}}catch(e){return {available:false,message:"Failed to access chrome.certificateProvider API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("setCertificates")&&this.registerSetCertificates(),this.shouldRegisterTool("reportSignature")&&this.registerReportSignature(),this.shouldRegisterTool("requestPin")&&this.registerRequestPin(),this.shouldRegisterTool("stopPinRequest")&&this.registerStopPinRequest(),this.shouldRegisterTool("onCertificatesUpdateRequested")&&this.registerOnCertificatesUpdateRequested(),this.shouldRegisterTool("onSignatureRequested")&&this.registerOnSignatureRequested();}registerSetCertificates(){this.server.registerTool("extension_tool_set_certificates",{description:"Sets a list of certificates to use in the browser for TLS client authentication",inputSchema:{certificatesRequestId:z.number().optional().describe("Request ID when responding to onCertificatesUpdateRequested event"),clientCertificates:z.array(z.object({certificateChain:z.array(z.string()).describe("Array of base64-encoded DER certificates, with client cert first"),supportedAlgorithms:z.array(z.string()).describe("Supported signature algorithms for this certificate")})).describe("List of client certificates to provide"),error:z.enum(["GENERAL_ERROR"]).optional().describe("Error that occurred while extracting certificates")}},async({certificatesRequestId:e,clientCertificates:t,error:r})=>{try{let o={clientCertificates:t.map(i=>({certificateChain:i.certificateChain.map(s=>{let n=atob(s),a=new Uint8Array(n.length);for(let c=0;c<n.length;c++)a[c]=n.charCodeAt(c);return a.buffer}),supportedAlgorithms:i.supportedAlgorithms}))};return e!==void 0&&(o.certificatesRequestId=e),r!==void 0&&(o.error=r),await new Promise((i,s)=>{chrome.certificateProvider.setCertificates(o,()=>{chrome.runtime.lastError?s(new Error(chrome.runtime.lastError.message)):i();});}),this.formatSuccess("Certificates set successfully",{certificateCount:t.length,requestId:e})}catch(o){return this.formatError(o)}});}registerReportSignature(){this.server.registerTool("extension_tool_report_signature",{description:"Reports the signature for a signing request from the browser",inputSchema:{signRequestId:z.number().describe("Request identifier from onSignatureRequested event"),signature:z.string().optional().describe("Base64-encoded signature data, if successfully generated"),error:z.enum(["GENERAL_ERROR"]).optional().describe("Error that occurred while generating the signature")}},async({signRequestId:e,signature:t,error:r})=>{try{let o={signRequestId:e};if(t!==void 0){let i=atob(t),s=new Uint8Array(i.length);for(let n=0;n<i.length;n++)s[n]=i.charCodeAt(n);o.signature=s.buffer;}return r!==void 0&&(o.error=r),await new Promise((i,s)=>{chrome.certificateProvider.reportSignature(o,()=>{chrome.runtime.lastError?s(new Error(chrome.runtime.lastError.message)):i();});}),this.formatSuccess("Signature reported successfully",{signRequestId:e,hasSignature:t!==void 0,hasError:r!==void 0})}catch(o){return this.formatError(o)}});}registerRequestPin(){this.server.registerTool("extension_tool_request_pin",{description:"Requests PIN or PUK from the user for certificate operations",inputSchema:{signRequestId:z.number().describe("The ID from SignRequest"),requestType:z.enum(["PIN","PUK"]).optional().describe("Type of code being requested (default: PIN)"),errorType:z.enum(["INVALID_PIN","INVALID_PUK","MAX_ATTEMPTS_EXCEEDED","UNKNOWN_ERROR"]).optional().describe("Error from previous request to show to user"),attemptsLeft:z.number().optional().describe("Number of attempts remaining for user information")}},async({signRequestId:e,requestType:t,errorType:r,attemptsLeft:o})=>{try{let i={signRequestId:e};t!==void 0&&(i.requestType=t),r!==void 0&&(i.errorType=r),o!==void 0&&(i.attemptsLeft=o);let s=await new Promise((n,a)=>{chrome.certificateProvider.requestPin(i,c=>{chrome.runtime.lastError?a(new Error(chrome.runtime.lastError.message)):n(c);});});return this.formatJson({signRequestId:e,userInput:s?.userInput||null,success:!!s?.userInput})}catch(i){return this.formatError(i)}});}registerStopPinRequest(){this.server.registerTool("extension_tool_stop_pin_request",{description:"Stops an ongoing PIN request flow",inputSchema:{signRequestId:z.number().describe("The ID from SignRequest"),errorType:z.enum(["INVALID_PIN","INVALID_PUK","MAX_ATTEMPTS_EXCEEDED","UNKNOWN_ERROR"]).optional().describe("Error reason for stopping the flow")}},async({signRequestId:e,errorType:t})=>{try{let r={signRequestId:e};return t!==void 0&&(r.errorType=t),await new Promise((o,i)=>{chrome.certificateProvider.stopPinRequest(r,()=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o();});}),this.formatSuccess("PIN request stopped successfully",{signRequestId:e,errorType:t})}catch(r){return this.formatError(r)}});}registerOnCertificatesUpdateRequested(){this.server.registerTool("extension_tool_listen_certificates_update_requested",{description:"Sets up listener for certificate update requests from the browser",inputSchema:{}},async()=>{try{return chrome.certificateProvider.onCertificatesUpdateRequested.hasListeners()&&chrome.certificateProvider.onCertificatesUpdateRequested.removeListener(this.handleCertificatesUpdateRequested),chrome.certificateProvider.onCertificatesUpdateRequested.addListener(this.handleCertificatesUpdateRequested),this.formatSuccess("Certificate update request listener registered",{event:"onCertificatesUpdateRequested",hasListeners:chrome.certificateProvider.onCertificatesUpdateRequested.hasListeners()})}catch(e){return this.formatError(e)}});}registerOnSignatureRequested(){this.server.registerTool("extension_tool_listen_signature_requested",{description:"Sets up listener for signature requests from the browser",inputSchema:{}},async()=>{try{return chrome.certificateProvider.onSignatureRequested.hasListeners()&&chrome.certificateProvider.onSignatureRequested.removeListener(this.handleSignatureRequested),chrome.certificateProvider.onSignatureRequested.addListener(this.handleSignatureRequested),this.formatSuccess("Signature request listener registered",{event:"onSignatureRequested",hasListeners:chrome.certificateProvider.onSignatureRequested.hasListeners()})}catch(e){return this.formatError(e)}});}handleCertificatesUpdateRequested=e=>{console.log("Certificate update requested:",{certificatesRequestId:e.certificatesRequestId,timestamp:new Date().toISOString()});};handleSignatureRequested=e=>{let t=new Uint8Array(e.certificate),r=new Uint8Array(e.input);console.log("Signature requested:",{signRequestId:e.signRequestId,algorithm:e.algorithm,certificateLength:t.length,inputLength:r.length,timestamp:new Date().toISOString()});}};var ke=class extends d{apiName="Commands";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.commands?typeof chrome.commands.getAll!="function"?{available:!1,message:"chrome.commands.getAll is not available",details:"The commands API appears to be partially available. Check manifest permissions."}:(chrome.commands.getAll(e=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"Commands API is fully available"}):{available:!1,message:"chrome.commands API is not defined",details:'This extension needs the "commands" permission in its manifest.json'}}catch(e){return {available:false,message:"Failed to access chrome.commands API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("getAll")&&this.registerGetAll();}registerGetAll(){this.server.registerTool("extension_tool_get_all_commands",{description:"Get all registered extension commands and their keyboard shortcuts",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.commands.getAll(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({count:e.length,commands:e.map(t=>({name:t.name,description:t.description,shortcut:t.shortcut||"Not assigned",isActive:!!t.shortcut}))})}catch(e){return this.formatError(e)}});}};var De=class extends d{apiName="ContentSettings";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.contentSettings?!chrome.contentSettings.cookies||typeof chrome.contentSettings.cookies.get!="function"?{available:!1,message:"chrome.contentSettings.cookies.get is not available",details:"The contentSettings API appears to be partially available. Check manifest permissions."}:(chrome.contentSettings.cookies.get({primaryUrl:"https://example.com"},e=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"ContentSettings API is fully available"}):{available:!1,message:"chrome.contentSettings API is not defined",details:'This extension needs the "contentSettings" permission in its manifest.json'}}catch(e){return {available:false,message:"Failed to access chrome.contentSettings API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("getCookiesSetting")&&this.registerGetCookiesSetting(),this.shouldRegisterTool("setCookiesSetting")&&this.registerSetCookiesSetting(),this.shouldRegisterTool("clearCookiesSetting")&&this.registerClearCookiesSetting(),this.shouldRegisterTool("getJavascriptSetting")&&this.registerGetJavascriptSetting(),this.shouldRegisterTool("setJavascriptSetting")&&this.registerSetJavascriptSetting(),this.shouldRegisterTool("clearJavascriptSetting")&&this.registerClearJavascriptSetting(),this.shouldRegisterTool("getImagesSetting")&&this.registerGetImagesSetting(),this.shouldRegisterTool("setImagesSetting")&&this.registerSetImagesSetting(),this.shouldRegisterTool("clearImagesSetting")&&this.registerClearImagesSetting(),this.shouldRegisterTool("getLocationSetting")&&this.registerGetLocationSetting(),this.shouldRegisterTool("setLocationSetting")&&this.registerSetLocationSetting(),this.shouldRegisterTool("clearLocationSetting")&&this.registerClearLocationSetting(),this.shouldRegisterTool("getNotificationsSetting")&&this.registerGetNotificationsSetting(),this.shouldRegisterTool("setNotificationsSetting")&&this.registerSetNotificationsSetting(),this.shouldRegisterTool("clearNotificationsSetting")&&this.registerClearNotificationsSetting(),this.shouldRegisterTool("getPopupsSetting")&&this.registerGetPopupsSetting(),this.shouldRegisterTool("setPopupsSetting")&&this.registerSetPopupsSetting(),this.shouldRegisterTool("clearPopupsSetting")&&this.registerClearPopupsSetting(),this.shouldRegisterTool("getCameraSetting")&&this.registerGetCameraSetting(),this.shouldRegisterTool("setCameraSetting")&&this.registerSetCameraSetting(),this.shouldRegisterTool("clearCameraSetting")&&this.registerClearCameraSetting(),this.shouldRegisterTool("getMicrophoneSetting")&&this.registerGetMicrophoneSetting(),this.shouldRegisterTool("setMicrophoneSetting")&&this.registerSetMicrophoneSetting(),this.shouldRegisterTool("clearMicrophoneSetting")&&this.registerClearMicrophoneSetting(),this.shouldRegisterTool("getAutomaticDownloadsSetting")&&this.registerGetAutomaticDownloadsSetting(),this.shouldRegisterTool("setAutomaticDownloadsSetting")&&this.registerSetAutomaticDownloadsSetting(),this.shouldRegisterTool("clearAutomaticDownloadsSetting")&&this.registerClearAutomaticDownloadsSetting(),this.shouldRegisterTool("getClipboardSetting")&&this.registerGetClipboardSetting(),this.shouldRegisterTool("setClipboardSetting")&&this.registerSetClipboardSetting(),this.shouldRegisterTool("clearClipboardSetting")&&this.registerClearClipboardSetting(),this.shouldRegisterTool("getAutoVerifySetting")&&this.registerGetAutoVerifySetting(),this.shouldRegisterTool("setAutoVerifySetting")&&this.registerSetAutoVerifySetting(),this.shouldRegisterTool("clearAutoVerifySetting")&&this.registerClearAutoVerifySetting(),this.shouldRegisterTool("getPluginsResourceIdentifiers")&&this.registerGetPluginsResourceIdentifiers();}registerGetCookiesSetting(){this.server.registerTool("extension_tool_get_cookies_setting",{description:"Get the current cookies content setting for a given pair of URLs",inputSchema:{primaryUrl:z.string().describe("The primary URL for which the content setting should be retrieved"),secondaryUrl:z.string().optional().describe("The secondary URL for which the content setting should be retrieved"),incognito:z.boolean().optional().describe("Whether to check the content settings for an incognito session"),resourceIdentifier:z.object({id:z.string(),description:z.string().optional()}).optional().describe("A more specific identifier of the type of content")}},async({primaryUrl:e,secondaryUrl:t,incognito:r,resourceIdentifier:o})=>{try{let i={primaryUrl:e};t!==void 0&&(i.secondaryUrl=t),r!==void 0&&(i.incognito=r),o!==void 0&&(i.resourceIdentifier=o);let s=await new Promise((n,a)=>{chrome.contentSettings.cookies.get(i,c=>{chrome.runtime.lastError?a(new Error(chrome.runtime.lastError.message)):n(c);});});return this.formatJson({primaryUrl:e,secondaryUrl:t,incognito:r||!1,setting:s.setting})}catch(i){return this.formatError(i)}});}registerSetCookiesSetting(){this.server.registerTool("extension_tool_set_cookies_setting",{description:"Set a new cookies content setting rule",inputSchema:{primaryPattern:z.string().describe("The pattern for the primary URL"),secondaryPattern:z.string().optional().describe("The pattern for the secondary URL"),setting:z.enum(["allow","block","session_only"]).describe("The setting to apply"),scope:z.enum(["regular","incognito_session_only"]).optional().describe("Where to set the setting"),resourceIdentifier:z.object({id:z.string(),description:z.string().optional()}).optional().describe("The resource identifier for the content type")}},async({primaryPattern:e,secondaryPattern:t,setting:r,scope:o,resourceIdentifier:i})=>{try{let s={primaryPattern:e,setting:r};return t!==void 0&&(s.secondaryPattern=t),o!==void 0&&(s.scope=o),i!==void 0&&(s.resourceIdentifier=i),await new Promise((n,a)=>{chrome.contentSettings.cookies.set(s,()=>{chrome.runtime.lastError?a(new Error(chrome.runtime.lastError.message)):n();});}),this.formatSuccess("Cookies content setting rule applied successfully",{primaryPattern:e,secondaryPattern:t,setting:r,scope:o||"regular"})}catch(s){return this.formatError(s)}});}registerClearCookiesSetting(){this.server.registerTool("extension_tool_clear_cookies_setting",{description:"Clear all cookies content setting rules set by this extension",inputSchema:{scope:z.enum(["regular","incognito_session_only"]).optional().describe("Where to clear the setting")}},async({scope:e})=>{try{let t={};return e!==void 0&&(t.scope=e),await new Promise((r,o)=>{chrome.contentSettings.cookies.clear(t,()=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r();});}),this.formatSuccess("All cookies content setting rules cleared successfully",{scope:e||"regular"})}catch(t){return this.formatError(t)}});}registerGetJavascriptSetting(){this.server.registerTool("extension_tool_get_javascript_setting",{description:"Get the current JavaScript content setting for a given pair of URLs",inputSchema:{primaryUrl:z.string().describe("The primary URL for which the content setting should be retrieved"),secondaryUrl:z.string().optional().describe("The secondary URL for which the content setting should be retrieved"),incognito:z.boolean().optional().describe("Whether to check the content settings for an incognito session"),resourceIdentifier:z.object({id:z.string(),description:z.string().optional()}).optional().describe("A more specific identifier of the type of content")}},async({primaryUrl:e,secondaryUrl:t,incognito:r,resourceIdentifier:o})=>{try{let i={primaryUrl:e};t!==void 0&&(i.secondaryUrl=t),r!==void 0&&(i.incognito=r),o!==void 0&&(i.resourceIdentifier=o);let s=await new Promise((n,a)=>{chrome.contentSettings.javascript.get(i,c=>{chrome.runtime.lastError?a(new Error(chrome.runtime.lastError.message)):n(c);});});return this.formatJson({primaryUrl:e,secondaryUrl:t,incognito:r||!1,setting:s.setting})}catch(i){return this.formatError(i)}});}registerSetJavascriptSetting(){this.server.registerTool("extension_tool_set_javascript_setting",{description:"Set a new JavaScript content setting rule",inputSchema:{primaryPattern:z.string().describe("The pattern for the primary URL"),secondaryPattern:z.string().optional().describe("The pattern for the secondary URL"),setting:z.enum(["allow","block"]).describe("The setting to apply"),scope:z.enum(["regular","incognito_session_only"]).optional().describe("Where to set the setting"),resourceIdentifier:z.object({id:z.string(),description:z.string().optional()}).optional().describe("The resource identifier for the content type")}},async({primaryPattern:e,secondaryPattern:t,setting:r,scope:o,resourceIdentifier:i})=>{try{let s={primaryPattern:e,setting:r};return t!==void 0&&(s.secondaryPattern=t),o!==void 0&&(s.scope=o),i!==void 0&&(s.resourceIdentifier=i),await new Promise((n,a)=>{chrome.contentSettings.javascript.set(s,()=>{chrome.runtime.lastError?a(new Error(chrome.runtime.lastError.message)):n();});}),this.formatSuccess("JavaScript content setting rule applied successfully",{primaryPattern:e,secondaryPattern:t,setting:r,scope:o||"regular"})}catch(s){return this.formatError(s)}});}registerClearJavascriptSetting(){this.server.registerTool("extension_tool_clear_javascript_setting",{description:"Clear all JavaScript content setting rules set by this extension",inputSchema:{scope:z.enum(["regular","incognito_session_only"]).optional().describe("Where to clear the setting")}},async({scope:e})=>{try{let t={};return e!==void 0&&(t.scope=e),await new Promise((r,o)=>{chrome.contentSettings.javascript.clear(t,()=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r();});}),this.formatSuccess("All JavaScript content setting rules cleared successfully",{scope:e||"regular"})}catch(t){return this.formatError(t)}});}registerGetImagesSetting(){this.server.registerTool("extension_tool_get_images_setting",{description:"Get the current images content setting for a given pair of URLs",inputSchema:{primaryUrl:z.string().describe("The primary URL for which the content setting should be retrieved"),secondaryUrl:z.string().optional().describe("The secondary URL for which the content setting should be retrieved"),incognito:z.boolean().optional().describe("Whether to check the content settings for an incognito session"),resourceIdentifier:z.object({id:z.string(),description:z.string().optional()}).optional().describe("A more specific identifier of the type of content")}},async({primaryUrl:e,secondaryUrl:t,incognito:r,resourceIdentifier:o})=>{try{let i={primaryUrl:e};t!==void 0&&(i.secondaryUrl=t),r!==void 0&&(i.incognito=r),o!==void 0&&(i.resourceIdentifier=o);let s=await new Promise((n,a)=>{chrome.contentSettings.images.get(i,c=>{chrome.runtime.lastError?a(new Error(chrome.runtime.lastError.message)):n(c);});});return this.formatJson({primaryUrl:e,secondaryUrl:t,incognito:r||!1,setting:s.setting})}catch(i){return this.formatError(i)}});}registerSetImagesSetting(){this.server.registerTool("extension_tool_set_images_setting",{description:"Set a new images content setting rule",inputSchema:{primaryPattern:z.string().describe("The pattern for the primary URL"),secondaryPattern:z.string().optional().describe("The pattern for the secondary URL"),setting:z.enum(["allow","block"]).describe("The setting to apply"),scope:z.enum(["regular","incognito_session_only"]).optional().describe("Where to set the setting"),resourceIdentifier:z.object({id:z.string(),description:z.string().optional()}).optional().describe("The resource identifier for the content type")}},async({primaryPattern:e,secondaryPattern:t,setting:r,scope:o,resourceIdentifier:i})=>{try{let s={primaryPattern:e,setting:r};return t!==void 0&&(s.secondaryPattern=t),o!==void 0&&(s.scope=o),i!==void 0&&(s.resourceIdentifier=i),await new Promise((n,a)=>{chrome.contentSettings.images.set(s,()=>{chrome.runtime.lastError?a(new Error(chrome.runtime.lastError.message)):n();});}),this.formatSuccess("Images content setting rule applied successfully",{primaryPattern:e,secondaryPattern:t,setting:r,scope:o||"regular"})}catch(s){return this.formatError(s)}});}registerClearImagesSetting(){this.server.registerTool("extension_tool_clear_images_setting",{description:"Clear all images content setting rules set by this extension",inputSchema:{scope:z.enum(["regular","incognito_session_only"]).optional().describe("Where to clear the setting")}},async({scope:e})=>{try{let t={};return e!==void 0&&(t.scope=e),await new Promise((r,o)=>{chrome.contentSettings.images.clear(t,()=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r();});}),this.formatSuccess("All images content setting rules cleared successfully",{scope:e||"regular"})}catch(t){return this.formatError(t)}});}registerGetLocationSetting(){this.server.registerTool("extension_tool_get_location_setting",{description:"Get the current location content setting for a given pair of URLs",inputSchema:{primaryUrl:z.string().describe("The primary URL for which the content setting should be retrieved"),secondaryUrl:z.string().optional().describe("The secondary URL for which the content setting should be retrieved"),incognito:z.boolean().optional().describe("Whether to check the content settings for an incognito session"),resourceIdentifier:z.object({id:z.string(),description:z.string().optional()}).optional().describe("A more specific identifier of the type of content")}},async({primaryUrl:e,secondaryUrl:t,incognito:r,resourceIdentifier:o})=>{try{let i={primaryUrl:e};t!==void 0&&(i.secondaryUrl=t),r!==void 0&&(i.incognito=r),o!==void 0&&(i.resourceIdentifier=o);let s=await new Promise((n,a)=>{chrome.contentSettings.location.get(i,c=>{chrome.runtime.lastError?a(new Error(chrome.runtime.lastError.message)):n(c);});});return this.formatJson({primaryUrl:e,secondaryUrl:t,incognito:r||!1,setting:s.setting})}catch(i){return this.formatError(i)}});}registerSetLocationSetting(){this.server.registerTool("extension_tool_set_location_setting",{description:"Set a new location content setting rule",inputSchema:{primaryPattern:z.string().describe("The pattern for the primary URL"),secondaryPattern:z.string().optional().describe("The pattern for the secondary URL"),setting:z.enum(["allow","block","ask"]).describe("The setting to apply"),scope:z.enum(["regular","incognito_session_only"]).optional().describe("Where to set the setting"),resourceIdentifier:z.object({id:z.string(),description:z.string().optional()}).optional().describe("The resource identifier for the content type")}},async({primaryPattern:e,secondaryPattern:t,setting:r,scope:o,resourceIdentifier:i})=>{try{let s={primaryPattern:e,setting:r};return t!==void 0&&(s.secondaryPattern=t),o!==void 0&&(s.scope=o),i!==void 0&&(s.resourceIdentifier=i),await new Promise((n,a)=>{chrome.contentSettings.location.set(s,()=>{chrome.runtime.lastError?a(new Error(chrome.runtime.lastError.message)):n();});}),this.formatSuccess("Location content setting rule applied successfully",{primaryPattern:e,secondaryPattern:t,setting:r,scope:o||"regular"})}catch(s){return this.formatError(s)}});}registerClearLocationSetting(){this.server.registerTool("extension_tool_clear_location_setting",{description:"Clear all location content setting rules set by this extension",inputSchema:{scope:z.enum(["regular","incognito_session_only"]).optional().describe("Where to clear the setting")}},async({scope:e})=>{try{let t={};return e!==void 0&&(t.scope=e),await new Promise((r,o)=>{chrome.contentSettings.location.clear(t,()=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r();});}),this.formatSuccess("All location content setting rules cleared successfully",{scope:e||"regular"})}catch(t){return this.formatError(t)}});}registerGetNotificationsSetting(){this.server.registerTool("extension_tool_get_notifications_setting",{description:"Get the current notifications content setting for a given pair of URLs",inputSchema:{primaryUrl:z.string().describe("The primary URL for which the content setting should be retrieved"),secondaryUrl:z.string().optional().describe("The secondary URL for which the content setting should be retrieved"),incognito:z.boolean().optional().describe("Whether to check the content settings for an incognito session"),resourceIdentifier:z.object({id:z.string(),description:z.string().optional()}).optional().describe("A more specific identifier of the type of content")}},async({primaryUrl:e,secondaryUrl:t,incognito:r,resourceIdentifier:o})=>{try{let i={primaryUrl:e};t!==void 0&&(i.secondaryUrl=t),r!==void 0&&(i.incognito=r),o!==void 0&&(i.resourceIdentifier=o);let s=await new Promise((n,a)=>{chrome.contentSettings.notifications.get(i,c=>{chrome.runtime.lastError?a(new Error(chrome.runtime.lastError.message)):n(c);});});return this.formatJson({primaryUrl:e,secondaryUrl:t,incognito:r||!1,setting:s.setting})}catch(i){return this.formatError(i)}});}registerSetNotificationsSetting(){this.server.registerTool("extension_tool_set_notifications_setting",{description:"Set a new notifications content setting rule",inputSchema:{primaryPattern:z.string().describe("The pattern for the primary URL"),secondaryPattern:z.string().optional().describe("The pattern for the secondary URL"),setting:z.enum(["allow","block","ask"]).describe("The setting to apply"),scope:z.enum(["regular","incognito_session_only"]).optional().describe("Where to set the setting"),resourceIdentifier:z.object({id:z.string(),description:z.string().optional()}).optional().describe("The resource identifier for the content type")}},async({primaryPattern:e,secondaryPattern:t,setting:r,scope:o,resourceIdentifier:i})=>{try{let s={primaryPattern:e,setting:r};return t!==void 0&&(s.secondaryPattern=t),o!==void 0&&(s.scope=o),i!==void 0&&(s.resourceIdentifier=i),await new Promise((n,a)=>{chrome.contentSettings.notifications.set(s,()=>{chrome.runtime.lastError?a(new Error(chrome.runtime.lastError.message)):n();});}),this.formatSuccess("Notifications content setting rule applied successfully",{primaryPattern:e,secondaryPattern:t,setting:r,scope:o||"regular"})}catch(s){return this.formatError(s)}});}registerClearNotificationsSetting(){this.server.registerTool("extension_tool_clear_notifications_setting",{description:"Clear all notifications content setting rules set by this extension",inputSchema:{scope:z.enum(["regular","incognito_session_only"]).optional().describe("Where to clear the setting")}},async({scope:e})=>{try{let t={};return e!==void 0&&(t.scope=e),await new Promise((r,o)=>{chrome.contentSettings.notifications.clear(t,()=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r();});}),this.formatSuccess("All notifications content setting rules cleared successfully",{scope:e||"regular"})}catch(t){return this.formatError(t)}});}registerGetPopupsSetting(){this.server.registerTool("extension_tool_get_popups_setting",{description:"Get the current popups content setting for a given pair of URLs",inputSchema:{primaryUrl:z.string().describe("The primary URL for which the content setting should be retrieved"),secondaryUrl:z.string().optional().describe("The secondary URL for which the content setting should be retrieved"),incognito:z.boolean().optional().describe("Whether to check the content settings for an incognito session"),resourceIdentifier:z.object({id:z.string(),description:z.string().optional()}).optional().describe("A more specific identifier of the type of content")}},async({primaryUrl:e,secondaryUrl:t,incognito:r,resourceIdentifier:o})=>{try{let i={primaryUrl:e};t!==void 0&&(i.secondaryUrl=t),r!==void 0&&(i.incognito=r),o!==void 0&&(i.resourceIdentifier=o);let s=await new Promise((n,a)=>{chrome.contentSettings.popups.get(i,c=>{chrome.runtime.lastError?a(new Error(chrome.runtime.lastError.message)):n(c);});});return this.formatJson({primaryUrl:e,secondaryUrl:t,incognito:r||!1,setting:s.setting})}catch(i){return this.formatError(i)}});}registerSetPopupsSetting(){this.server.registerTool("extension_tool_set_popups_setting",{description:"Set a new popups content setting rule",inputSchema:{primaryPattern:z.string().describe("The pattern for the primary URL"),secondaryPattern:z.string().optional().describe("The pattern for the secondary URL"),setting:z.enum(["allow","block"]).describe("The setting to apply"),scope:z.enum(["regular","incognito_session_only"]).optional().describe("Where to set the setting"),resourceIdentifier:z.object({id:z.string(),description:z.string().optional()}).optional().describe("The resource identifier for the content type")}},async({primaryPattern:e,secondaryPattern:t,setting:r,scope:o,resourceIdentifier:i})=>{try{let s={primaryPattern:e,setting:r};return t!==void 0&&(s.secondaryPattern=t),o!==void 0&&(s.scope=o),i!==void 0&&(s.resourceIdentifier=i),await new Promise((n,a)=>{chrome.contentSettings.popups.set(s,()=>{chrome.runtime.lastError?a(new Error(chrome.runtime.lastError.message)):n();});}),this.formatSuccess("Popups content setting rule applied successfully",{primaryPattern:e,secondaryPattern:t,setting:r,scope:o||"regular"})}catch(s){return this.formatError(s)}});}registerClearPopupsSetting(){this.server.registerTool("extension_tool_clear_popups_setting",{description:"Clear all popups content setting rules set by this extension",inputSchema:{scope:z.enum(["regular","incognito_session_only"]).optional().describe("Where to clear the setting")}},async({scope:e})=>{try{let t={};return e!==void 0&&(t.scope=e),await new Promise((r,o)=>{chrome.contentSettings.popups.clear(t,()=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r();});}),this.formatSuccess("All popups content setting rules cleared successfully",{scope:e||"regular"})}catch(t){return this.formatError(t)}});}registerGetCameraSetting(){this.server.registerTool("extension_tool_get_camera_setting",{description:"Get the current camera content setting for a given pair of URLs",inputSchema:{primaryUrl:z.string().describe("The primary URL for which the content setting should be retrieved"),secondaryUrl:z.string().optional().describe("The secondary URL for which the content setting should be retrieved"),incognito:z.boolean().optional().describe("Whether to check the content settings for an incognito session"),resourceIdentifier:z.object({id:z.string(),description:z.string().optional()}).optional().describe("A more specific identifier of the type of content")}},async({primaryUrl:e,secondaryUrl:t,incognito:r,resourceIdentifier:o})=>{try{let i={primaryUrl:e};t!==void 0&&(i.secondaryUrl=t),r!==void 0&&(i.incognito=r),o!==void 0&&(i.resourceIdentifier=o);let s=await new Promise((n,a)=>{chrome.contentSettings.camera.get(i,c=>{chrome.runtime.lastError?a(new Error(chrome.runtime.lastError.message)):n(c);});});return this.formatJson({primaryUrl:e,secondaryUrl:t,incognito:r||!1,setting:s.setting})}catch(i){return this.formatError(i)}});}registerSetCameraSetting(){this.server.registerTool("extension_tool_set_camera_setting",{description:"Set a new camera content setting rule",inputSchema:{primaryPattern:z.string().describe("The pattern for the primary URL"),secondaryPattern:z.string().optional().describe("The pattern for the secondary URL"),setting:z.enum(["allow","block","ask"]).describe("The setting to apply"),scope:z.enum(["regular","incognito_session_only"]).optional().describe("Where to set the setting"),resourceIdentifier:z.object({id:z.string(),description:z.string().optional()}).optional().describe("The resource identifier for the content type")}},async({primaryPattern:e,secondaryPattern:t,setting:r,scope:o,resourceIdentifier:i})=>{try{let s={primaryPattern:e,setting:r};return t!==void 0&&(s.secondaryPattern=t),o!==void 0&&(s.scope=o),i!==void 0&&(s.resourceIdentifier=i),await new Promise((n,a)=>{chrome.contentSettings.camera.set(s,()=>{chrome.runtime.lastError?a(new Error(chrome.runtime.lastError.message)):n();});}),this.formatSuccess("Camera content setting rule applied successfully",{primaryPattern:e,secondaryPattern:t,setting:r,scope:o||"regular"})}catch(s){return this.formatError(s)}});}registerClearCameraSetting(){this.server.registerTool("extension_tool_clear_camera_setting",{description:"Clear all camera content setting rules set by this extension",inputSchema:{scope:z.enum(["regular","incognito_session_only"]).optional().describe("Where to clear the setting")}},async({scope:e})=>{try{let t={};return e!==void 0&&(t.scope=e),await new Promise((r,o)=>{chrome.contentSettings.camera.clear(t,()=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r();});}),this.formatSuccess("All camera content setting rules cleared successfully",{scope:e||"regular"})}catch(t){return this.formatError(t)}});}registerGetMicrophoneSetting(){this.server.registerTool("extension_tool_get_microphone_setting",{description:"Get the current microphone content setting for a given pair of URLs",inputSchema:{primaryUrl:z.string().describe("The primary URL for which the content setting should be retrieved"),secondaryUrl:z.string().optional().describe("The secondary URL for which the content setting should be retrieved"),incognito:z.boolean().optional().describe("Whether to check the content settings for an incognito session"),resourceIdentifier:z.object({id:z.string(),description:z.string().optional()}).optional().describe("A more specific identifier of the type of content")}},async({primaryUrl:e,secondaryUrl:t,incognito:r,resourceIdentifier:o})=>{try{let i={primaryUrl:e};t!==void 0&&(i.secondaryUrl=t),r!==void 0&&(i.incognito=r),o!==void 0&&(i.resourceIdentifier=o);let s=await new Promise((n,a)=>{chrome.contentSettings.microphone.get(i,c=>{chrome.runtime.lastError?a(new Error(chrome.runtime.lastError.message)):n(c);});});return this.formatJson({primaryUrl:e,secondaryUrl:t,incognito:r||!1,setting:s.setting})}catch(i){return this.formatError(i)}});}registerSetMicrophoneSetting(){this.server.registerTool("extension_tool_set_microphone_setting",{description:"Set a new microphone content setting rule",inputSchema:{primaryPattern:z.string().describe("The pattern for the primary URL"),secondaryPattern:z.string().optional().describe("The pattern for the secondary URL"),setting:z.enum(["allow","block","ask"]).describe("The setting to apply"),scope:z.enum(["regular","incognito_session_only"]).optional().describe("Where to set the setting"),resourceIdentifier:z.object({id:z.string(),description:z.string().optional()}).optional().describe("The resource identifier for the content type")}},async({primaryPattern:e,secondaryPattern:t,setting:r,scope:o,resourceIdentifier:i})=>{try{let s={primaryPattern:e,setting:r};return t!==void 0&&(s.secondaryPattern=t),o!==void 0&&(s.scope=o),i!==void 0&&(s.resourceIdentifier=i),await new Promise((n,a)=>{chrome.contentSettings.microphone.set(s,()=>{chrome.runtime.lastError?a(new Error(chrome.runtime.lastError.message)):n();});}),this.formatSuccess("Microphone content setting rule applied successfully",{primaryPattern:e,secondaryPattern:t,setting:r,scope:o||"regular"})}catch(s){return this.formatError(s)}});}registerClearMicrophoneSetting(){this.server.registerTool("extension_tool_clear_microphone_setting",{description:"Clear all microphone content setting rules set by this extension",inputSchema:{scope:z.enum(["regular","incognito_session_only"]).optional().describe("Where to clear the setting")}},async({scope:e})=>{try{let t={};return e!==void 0&&(t.scope=e),await new Promise((r,o)=>{chrome.contentSettings.microphone.clear(t,()=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r();});}),this.formatSuccess("All microphone content setting rules cleared successfully",{scope:e||"regular"})}catch(t){return this.formatError(t)}});}registerGetAutomaticDownloadsSetting(){this.server.registerTool("extension_tool_get_automatic_downloads_setting",{description:"Get the current automatic downloads content setting for a given pair of URLs",inputSchema:{primaryUrl:z.string().describe("The primary URL for which the content setting should be retrieved"),secondaryUrl:z.string().optional().describe("The secondary URL for which the content setting should be retrieved"),incognito:z.boolean().optional().describe("Whether to check the content settings for an incognito session"),resourceIdentifier:z.object({id:z.string(),description:z.string().optional()}).optional().describe("A more specific identifier of the type of content")}},async({primaryUrl:e,secondaryUrl:t,incognito:r,resourceIdentifier:o})=>{try{let i={primaryUrl:e};t!==void 0&&(i.secondaryUrl=t),r!==void 0&&(i.incognito=r),o!==void 0&&(i.resourceIdentifier=o);let s=await new Promise((n,a)=>{chrome.contentSettings.automaticDownloads.get(i,c=>{chrome.runtime.lastError?a(new Error(chrome.runtime.lastError.message)):n(c);});});return this.formatJson({primaryUrl:e,secondaryUrl:t,incognito:r||!1,setting:s.setting})}catch(i){return this.formatError(i)}});}registerSetAutomaticDownloadsSetting(){this.server.registerTool("extension_tool_set_automatic_downloads_setting",{description:"Set a new automatic downloads content setting rule",inputSchema:{primaryPattern:z.string().describe("The pattern for the primary URL"),secondaryPattern:z.string().optional().describe("The pattern for the secondary URL"),setting:z.enum(["allow","block","ask"]).describe("The setting to apply"),scope:z.enum(["regular","incognito_session_only"]).optional().describe("Where to set the setting"),resourceIdentifier:z.object({id:z.string(),description:z.string().optional()}).optional().describe("The resource identifier for the content type")}},async({primaryPattern:e,secondaryPattern:t,setting:r,scope:o,resourceIdentifier:i})=>{try{let s={primaryPattern:e,setting:r};return t!==void 0&&(s.secondaryPattern=t),o!==void 0&&(s.scope=o),i!==void 0&&(s.resourceIdentifier=i),await new Promise((n,a)=>{chrome.contentSettings.automaticDownloads.set(s,()=>{chrome.runtime.lastError?a(new Error(chrome.runtime.lastError.message)):n();});}),this.formatSuccess("Automatic downloads content setting rule applied successfully",{primaryPattern:e,secondaryPattern:t,setting:r,scope:o||"regular"})}catch(s){return this.formatError(s)}});}registerClearAutomaticDownloadsSetting(){this.server.registerTool("extension_tool_clear_automatic_downloads_setting",{description:"Clear all automatic downloads content setting rules set by this extension",inputSchema:{scope:z.enum(["regular","incognito_session_only"]).optional().describe("Where to clear the setting")}},async({scope:e})=>{try{let t={};return e!==void 0&&(t.scope=e),await new Promise((r,o)=>{chrome.contentSettings.automaticDownloads.clear(t,()=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r();});}),this.formatSuccess("All automatic downloads content setting rules cleared successfully",{scope:e||"regular"})}catch(t){return this.formatError(t)}});}registerGetClipboardSetting(){this.server.registerTool("extension_tool_get_clipboard_setting",{description:"Get the current clipboard content setting for a given pair of URLs",inputSchema:{primaryUrl:z.string().describe("The primary URL for which the content setting should be retrieved"),secondaryUrl:z.string().optional().describe("The secondary URL for which the content setting should be retrieved"),incognito:z.boolean().optional().describe("Whether to check the content settings for an incognito session"),resourceIdentifier:z.object({id:z.string(),description:z.string().optional()}).optional().describe("A more specific identifier of the type of content")}},async({primaryUrl:e,secondaryUrl:t,incognito:r,resourceIdentifier:o})=>{try{let i={primaryUrl:e};t!==void 0&&(i.secondaryUrl=t),r!==void 0&&(i.incognito=r),o!==void 0&&(i.resourceIdentifier=o);let s=await new Promise((n,a)=>{chrome.contentSettings.clipboard.get(i,c=>{chrome.runtime.lastError?a(new Error(chrome.runtime.lastError.message)):n(c);});});return this.formatJson({primaryUrl:e,secondaryUrl:t,incognito:r||!1,setting:s.setting})}catch(i){return this.formatError(i)}});}registerSetClipboardSetting(){this.server.registerTool("extension_tool_set_clipboard_setting",{description:"Set a new clipboard content setting rule",inputSchema:{primaryPattern:z.string().describe("The pattern for the primary URL"),secondaryPattern:z.string().optional().describe("The pattern for the secondary URL"),setting:z.enum(["allow","block","ask"]).describe("The setting to apply"),scope:z.enum(["regular","incognito_session_only"]).optional().describe("Where to set the setting"),resourceIdentifier:z.object({id:z.string(),description:z.string().optional()}).optional().describe("The resource identifier for the content type")}},async({primaryPattern:e,secondaryPattern:t,setting:r,scope:o,resourceIdentifier:i})=>{try{let s={primaryPattern:e,setting:r};return t!==void 0&&(s.secondaryPattern=t),o!==void 0&&(s.scope=o),i!==void 0&&(s.resourceIdentifier=i),await new Promise((n,a)=>{chrome.contentSettings.clipboard.set(s,()=>{chrome.runtime.lastError?a(new Error(chrome.runtime.lastError.message)):n();});}),this.formatSuccess("Clipboard content setting rule applied successfully",{primaryPattern:e,secondaryPattern:t,setting:r,scope:o||"regular"})}catch(s){return this.formatError(s)}});}registerClearClipboardSetting(){this.server.registerTool("extension_tool_clear_clipboard_setting",{description:"Clear all clipboard content setting rules set by this extension",inputSchema:{scope:z.enum(["regular","incognito_session_only"]).optional().describe("Where to clear the setting")}},async({scope:e})=>{try{let t={};return e!==void 0&&(t.scope=e),await new Promise((r,o)=>{chrome.contentSettings.clipboard.clear(t,()=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r();});}),this.formatSuccess("All clipboard content setting rules cleared successfully",{scope:e||"regular"})}catch(t){return this.formatError(t)}});}registerGetAutoVerifySetting(){this.server.registerTool("extension_tool_get_auto_verify_setting",{description:"Get the current auto verify content setting for a given pair of URLs",inputSchema:{primaryUrl:z.string().describe("The primary URL for which the content setting should be retrieved"),secondaryUrl:z.string().optional().describe("The secondary URL for which the content setting should be retrieved"),incognito:z.boolean().optional().describe("Whether to check the content settings for an incognito session"),resourceIdentifier:z.object({id:z.string(),description:z.string().optional()}).optional().describe("A more specific identifier of the type of content")}},async({primaryUrl:e,secondaryUrl:t,incognito:r,resourceIdentifier:o})=>{try{let i={primaryUrl:e};t!==void 0&&(i.secondaryUrl=t),r!==void 0&&(i.incognito=r),o!==void 0&&(i.resourceIdentifier=o);let s=await new Promise((n,a)=>{chrome.contentSettings.autoVerify.get(i,c=>{chrome.runtime.lastError?a(new Error(chrome.runtime.lastError.message)):n(c);});});return this.formatJson({primaryUrl:e,secondaryUrl:t,incognito:r||!1,setting:s.setting})}catch(i){return this.formatError(i)}});}registerSetAutoVerifySetting(){this.server.registerTool("extension_tool_set_auto_verify_setting",{description:"Set a new auto verify content setting rule",inputSchema:{primaryPattern:z.string().describe("The pattern for the primary URL"),secondaryPattern:z.string().optional().describe("The pattern for the secondary URL"),setting:z.enum(["allow","block"]).describe("The setting to apply"),scope:z.enum(["regular","incognito_session_only"]).optional().describe("Where to set the setting"),resourceIdentifier:z.object({id:z.string(),description:z.string().optional()}).optional().describe("The resource identifier for the content type")}},async({primaryPattern:e,secondaryPattern:t,setting:r,scope:o,resourceIdentifier:i})=>{try{let s={primaryPattern:e,setting:r};return t!==void 0&&(s.secondaryPattern=t),o!==void 0&&(s.scope=o),i!==void 0&&(s.resourceIdentifier=i),await new Promise((n,a)=>{chrome.contentSettings.autoVerify.set(s,()=>{chrome.runtime.lastError?a(new Error(chrome.runtime.lastError.message)):n();});}),this.formatSuccess("Auto verify content setting rule applied successfully",{primaryPattern:e,secondaryPattern:t,setting:r,scope:o||"regular"})}catch(s){return this.formatError(s)}});}registerClearAutoVerifySetting(){this.server.registerTool("extension_tool_clear_auto_verify_setting",{description:"Clear all auto verify content setting rules set by this extension",inputSchema:{scope:z.enum(["regular","incognito_session_only"]).optional().describe("Where to clear the setting")}},async({scope:e})=>{try{let t={};return e!==void 0&&(t.scope=e),await new Promise((r,o)=>{chrome.contentSettings.autoVerify.clear(t,()=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r();});}),this.formatSuccess("All auto verify content setting rules cleared successfully",{scope:e||"regular"})}catch(t){return this.formatError(t)}});}registerGetPluginsResourceIdentifiers(){this.server.registerTool("extension_tool_get_plugins_resource_identifiers",{description:"Get a list of resource identifiers for the plugins content type",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.contentSettings.plugins.getResourceIdentifiers(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({count:e?.length||0,resourceIdentifiers:e||[]})}catch(e){return this.formatError(e)}});}};var Oe=class extends d{apiName="ContextMenus";constructor(e,t={}){super(e,t);}checkAvailability(){try{if(!chrome.contextMenus)return {available:!1,message:"chrome.contextMenus API is not defined",details:'This extension needs the "contextMenus" permission in its manifest.json'};if(typeof chrome.contextMenus.create!="function")return {available:!1,message:"chrome.contextMenus.create is not available",details:"The contextMenus API appears to be partially available. Check manifest permissions."};try{chrome.contextMenus.removeAll(()=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)});}catch{}return {available:!0,message:"ContextMenus API is fully available"}}catch(e){return {available:false,message:"Failed to access chrome.contextMenus API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("createContextMenu")&&this.registerCreateContextMenu(),this.shouldRegisterTool("updateContextMenu")&&this.registerUpdateContextMenu(),this.shouldRegisterTool("removeContextMenu")&&this.registerRemoveContextMenu(),this.shouldRegisterTool("removeAllContextMenus")&&this.registerRemoveAllContextMenus();}registerCreateContextMenu(){this.server.registerTool("extension_tool_create_context_menu",{description:"Create a new context menu item that appears when right-clicking on web pages",inputSchema:{id:z.string().optional().describe("Unique ID for this menu item. If not provided, one will be generated"),title:z.string().optional().describe("Text to display in the menu item. Required unless type is separator. Use %s to show selected text"),type:z.enum(["normal","checkbox","radio","separator"]).optional().describe("Type of menu item. Defaults to normal"),contexts:z.array(z.enum(["all","page","frame","selection","link","editable","image","video","audio","launcher","browser_action","page_action","action"])).optional().describe("Contexts where this menu item appears. Defaults to [page]"),checked:z.boolean().optional().describe("Initial state for checkbox or radio items"),enabled:z.boolean().optional().describe("Whether the menu item is enabled. Defaults to true"),visible:z.boolean().optional().describe("Whether the menu item is visible. Defaults to true"),parentId:z.union([z.string(),z.number()]).optional().describe("ID of parent menu item to create a submenu"),documentUrlPatterns:z.array(z.string()).optional().describe("URL patterns where this item should appear"),targetUrlPatterns:z.array(z.string()).optional().describe("URL patterns for link/media targets")}},async({id:e,title:t,type:r,contexts:o,checked:i,enabled:s,visible:n,parentId:a,documentUrlPatterns:c,targetUrlPatterns:u})=>{try{if(r!=="separator"&&!t)return this.formatError("Title is required unless type is separator");let m={};e!==void 0&&(m.id=e),t!==void 0&&(m.title=t),r!==void 0&&(m.type=r),o!==void 0&&(m.contexts=o),i!==void 0&&(m.checked=i),s!==void 0&&(m.enabled=s),n!==void 0&&(m.visible=n),a!==void 0&&(m.parentId=a),c!==void 0&&(m.documentUrlPatterns=c),u!==void 0&&(m.targetUrlPatterns=u);let g=await new Promise((w,k)=>{let R=chrome.contextMenus.create(m,()=>{chrome.runtime.lastError?k(new Error(chrome.runtime.lastError.message)):w(R);});});return this.formatSuccess("Context menu item created successfully",{id:g,title:t||"(separator)",type:r||"normal",contexts:o||["page"],enabled:s!==!1,visible:n!==!1})}catch(m){return this.formatError(m)}});}registerUpdateContextMenu(){this.server.registerTool("extension_tool_update_context_menu",{description:"Update an existing context menu item",inputSchema:{id:z.union([z.string(),z.number()]).describe("ID of the menu item to update"),title:z.string().optional().describe("New title for the menu item"),type:z.enum(["normal","checkbox","radio","separator"]).optional().describe("New type for the menu item"),contexts:z.array(z.enum(["all","page","frame","selection","link","editable","image","video","audio","launcher","browser_action","page_action","action"])).optional().describe("New contexts for the menu item"),checked:z.boolean().optional().describe("New checked state for checkbox or radio items"),enabled:z.boolean().optional().describe("Whether the menu item should be enabled"),visible:z.boolean().optional().describe("Whether the menu item should be visible"),parentId:z.union([z.string(),z.number()]).optional().describe("New parent ID for the menu item"),documentUrlPatterns:z.array(z.string()).optional().describe("New document URL patterns"),targetUrlPatterns:z.array(z.string()).optional().describe("New target URL patterns")}},async({id:e,title:t,type:r,contexts:o,checked:i,enabled:s,visible:n,parentId:a,documentUrlPatterns:c,targetUrlPatterns:u})=>{try{let m={};return t!==void 0&&(m.title=t),r!==void 0&&(m.type=r),o!==void 0&&(m.contexts=o),i!==void 0&&(m.checked=i),s!==void 0&&(m.enabled=s),n!==void 0&&(m.visible=n),a!==void 0&&(m.parentId=a),c!==void 0&&(m.documentUrlPatterns=c),u!==void 0&&(m.targetUrlPatterns=u),await new Promise((g,w)=>{chrome.contextMenus.update(e,m,()=>{chrome.runtime.lastError?w(new Error(chrome.runtime.lastError.message)):g();});}),this.formatSuccess("Context menu item updated successfully",{id:e,updatedProperties:Object.keys(m)})}catch(m){return this.formatError(m)}});}registerRemoveContextMenu(){this.server.registerTool("extension_tool_remove_context_menu",{description:"Remove a specific context menu item",inputSchema:{id:z.union([z.string(),z.number()]).describe("ID of the menu item to remove")}},async({id:e})=>{try{return await new Promise((t,r)=>{chrome.contextMenus.remove(e,()=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t();});}),this.formatSuccess("Context menu item removed successfully",{id:e})}catch(t){return this.formatError(t)}});}registerRemoveAllContextMenus(){this.server.registerTool("extension_tool_remove_all_context_menus",{description:"Remove all context menu items created by this extension",inputSchema:{}},async()=>{try{return await new Promise((e,t)=>{chrome.contextMenus.removeAll(()=>{chrome.runtime.lastError?t(new Error(chrome.runtime.lastError.message)):e();});}),this.formatSuccess("All context menu items removed successfully")}catch(e){return this.formatError(e)}});}};var Le=class extends d{apiName="Cookies";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.cookies?typeof chrome.cookies.getAllCookieStores!="function"?{available:!1,message:"chrome.cookies.getAllCookieStores is not available",details:"The cookies API appears to be partially available. Check manifest permissions."}:(chrome.cookies.getAllCookieStores(e=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"Cookies API is fully available"}):{available:!1,message:"chrome.cookies API is not defined",details:'This extension needs the "cookies" permission and appropriate host permissions in its manifest.json'}}catch(e){return {available:false,message:"Failed to access chrome.cookies API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("getCookie")&&this.registerGetCookie(),this.shouldRegisterTool("getAllCookies")&&this.registerGetAllCookies(),this.shouldRegisterTool("getAllCookieStores")&&this.registerGetAllCookieStores(),this.shouldRegisterTool("getPartitionKey")&&this.registerGetPartitionKey(),this.shouldRegisterTool("setCookie")&&this.registerSetCookie(),this.shouldRegisterTool("removeCookie")&&this.registerRemoveCookie();}registerGetCookie(){this.server.registerTool("extension_tool_get_cookie",{description:"Retrieve information about a single cookie by name and URL",inputSchema:{url:z.string().describe("The URL with which the cookie is associated"),name:z.string().describe("The name of the cookie to retrieve"),storeId:z.string().optional().describe("The ID of the cookie store to search in"),partitionKey:z.object({topLevelSite:z.string().optional(),hasCrossSiteAncestor:z.boolean().optional()}).optional().describe("The partition key for partitioned cookies")}},async({url:e,name:t,storeId:r,partitionKey:o})=>{try{let i={url:e,name:t};r!==void 0&&(i.storeId=r),o!==void 0&&(i.partitionKey=o);let s=await new Promise((n,a)=>{chrome.cookies.get(i,c=>{chrome.runtime.lastError?a(new Error(chrome.runtime.lastError.message)):n(c??void 0);});});return s?this.formatJson({name:s.name,value:s.value,domain:s.domain,path:s.path,secure:s.secure,httpOnly:s.httpOnly,sameSite:s.sameSite,session:s.session,expirationDate:s.expirationDate,hostOnly:s.hostOnly,storeId:s.storeId,partitionKey:s.partitionKey}):this.formatSuccess("No cookie found",{name:t,url:e})}catch(i){return this.formatError(i)}});}registerGetAllCookies(){this.server.registerTool("extension_tool_get_all_cookies",{description:"Retrieve all cookies that match the given criteria",inputSchema:{url:z.string().optional().describe("Restricts cookies to those that would match the given URL"),domain:z.string().optional().describe("Restricts cookies to those whose domains match or are subdomains of this one"),name:z.string().optional().describe("Filters the cookies by name"),path:z.string().optional().describe("Restricts cookies to those whose path exactly matches this string"),secure:z.boolean().optional().describe("Filters cookies by their Secure property"),session:z.boolean().optional().describe("Filters out session vs. persistent cookies"),storeId:z.string().optional().describe("The cookie store to retrieve cookies from"),partitionKey:z.object({topLevelSite:z.string().optional(),hasCrossSiteAncestor:z.boolean().optional()}).optional().describe("The partition key for partitioned cookies")}},async({url:e,domain:t,name:r,path:o,secure:i,session:s,storeId:n,partitionKey:a})=>{try{let c={};e!==void 0&&(c.url=e),t!==void 0&&(c.domain=t),r!==void 0&&(c.name=r),o!==void 0&&(c.path=o),i!==void 0&&(c.secure=i),s!==void 0&&(c.session=s),n!==void 0&&(c.storeId=n),a!==void 0&&(c.partitionKey=a);let u=await new Promise((m,g)=>{chrome.cookies.getAll(c,w=>{chrome.runtime.lastError?g(new Error(chrome.runtime.lastError.message)):m(w);});});return this.formatJson({count:u.length,cookies:u.map(m=>({name:m.name,value:m.value,domain:m.domain,path:m.path,secure:m.secure,httpOnly:m.httpOnly,sameSite:m.sameSite,session:m.session,expirationDate:m.expirationDate,hostOnly:m.hostOnly,storeId:m.storeId,partitionKey:m.partitionKey}))})}catch(c){return this.formatError(c)}});}registerGetAllCookieStores(){this.server.registerTool("extension_tool_get_all_cookie_stores",{description:"List all existing cookie stores",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.cookies.getAllCookieStores(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({count:e.length,cookieStores:e.map(t=>({id:t.id,tabIds:t.tabIds}))})}catch(e){return this.formatError(e)}});}registerGetPartitionKey(){this.server.registerTool("extension_tool_get_partition_key",{description:"Get the partition key for a specific frame",inputSchema:{tabId:z.number().optional().describe("The unique identifier for the tab containing the frame"),frameId:z.number().optional().describe("The unique identifier for the frame within the tab"),documentId:z.string().optional().describe("The unique identifier for the document")}},async({tabId:e,frameId:t,documentId:r})=>{try{let o={};e!==void 0&&(o.tabId=e),t!==void 0&&(o.frameId=t),r!==void 0&&(o.documentId=r);let i=await new Promise((s,n)=>{chrome.cookies.getPartitionKey(o,a=>{chrome.runtime.lastError?n(new Error(chrome.runtime.lastError.message)):s(a);});});return this.formatJson({partitionKey:i.partitionKey})}catch(o){return this.formatError(o)}});}registerSetCookie(){this.server.registerTool("extension_tool_set_cookie",{description:"Set a cookie with the given data; may overwrite equivalent cookies if they exist",inputSchema:{url:z.string().describe("The request-URI to associate with the setting of the cookie"),name:z.string().optional().describe("The name of the cookie. Empty by default if omitted"),value:z.string().optional().describe("The value of the cookie. Empty by default if omitted"),domain:z.string().optional().describe("The domain of the cookie. If omitted, the cookie becomes a host-only cookie"),path:z.string().optional().describe("The path of the cookie. Defaults to the path portion of the url parameter"),secure:z.boolean().optional().describe("Whether the cookie should be marked as Secure. Defaults to false"),httpOnly:z.boolean().optional().describe("Whether the cookie should be marked as HttpOnly. Defaults to false"),sameSite:z.enum(["no_restriction","lax","strict","unspecified"]).optional().describe("The cookie's same-site status"),expirationDate:z.number().optional().describe("The expiration date of the cookie as the number of seconds since the UNIX epoch"),storeId:z.string().optional().describe("The ID of the cookie store in which to set the cookie"),partitionKey:z.object({topLevelSite:z.string().optional(),hasCrossSiteAncestor:z.boolean().optional()}).optional().describe("The partition key for partitioned cookies")}},async({url:e,name:t,value:r,domain:o,path:i,secure:s,httpOnly:n,sameSite:a,expirationDate:c,storeId:u,partitionKey:m})=>{try{let g={url:e};t!==void 0&&(g.name=t),r!==void 0&&(g.value=r),o!==void 0&&(g.domain=o),i!==void 0&&(g.path=i),s!==void 0&&(g.secure=s),n!==void 0&&(g.httpOnly=n),a!==void 0&&(g.sameSite=a),c!==void 0&&(g.expirationDate=c),u!==void 0&&(g.storeId=u),m!==void 0&&(g.partitionKey=m);let w=await new Promise((k,R)=>{chrome.cookies.set(g,D=>{chrome.runtime.lastError?R(new Error(chrome.runtime.lastError.message)):k(D??void 0);});});return w?this.formatSuccess("Cookie set successfully",{name:w.name,value:w.value,domain:w.domain,path:w.path,secure:w.secure,httpOnly:w.httpOnly,sameSite:w.sameSite,session:w.session,expirationDate:w.expirationDate,hostOnly:w.hostOnly,storeId:w.storeId,partitionKey:w.partitionKey}):this.formatError("Failed to set cookie")}catch(g){return this.formatError(g)}});}registerRemoveCookie(){this.server.registerTool("extension_tool_remove_cookie",{description:"Delete a cookie by name",inputSchema:{url:z.string().describe("The URL with which the cookie to remove is associated"),name:z.string().describe("The name of the cookie to remove"),storeId:z.string().optional().describe("The ID of the cookie store to look in"),partitionKey:z.object({topLevelSite:z.string().optional(),hasCrossSiteAncestor:z.boolean().optional()}).optional().describe("The partition key for partitioned cookies")}},async({url:e,name:t,storeId:r,partitionKey:o})=>{try{let i={url:e,name:t};r!==void 0&&(i.storeId=r),o!==void 0&&(i.partitionKey=o);let s=await new Promise((n,a)=>{chrome.cookies.remove(i,c=>{chrome.runtime.lastError?a(new Error(chrome.runtime.lastError.message)):n(c);});});return s?this.formatSuccess("Cookie removed successfully",{name:s.name,url:s.url,storeId:s.storeId,partitionKey:s.partitionKey}):this.formatSuccess("No cookie found to remove",{name:t,url:e})}catch(i){return this.formatError(i)}});}};var Ue=class extends d{apiName="Debugger";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.debugger?typeof chrome.debugger.getTargets!="function"?{available:!1,message:"chrome.debugger.getTargets is not available",details:"The debugger API appears to be partially available. Check manifest permissions."}:(chrome.debugger.getTargets(e=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"Debugger API is fully available"}):{available:!1,message:"chrome.debugger API is not defined",details:'This extension needs the "debugger" permission in its manifest.json'}}catch(e){return {available:false,message:"Failed to access chrome.debugger API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("attach")&&this.registerAttach(),this.shouldRegisterTool("detach")&&this.registerDetach(),this.shouldRegisterTool("sendCommand")&&this.registerSendCommand(),this.shouldRegisterTool("getTargets")&&this.registerGetTargets();}registerAttach(){this.server.registerTool("extension_tool_attach_debugger",{description:"Attach debugger to a target (tab, extension, or target ID)",inputSchema:{tabId:z.number().optional().describe("The ID of the tab to debug"),extensionId:z.string().optional().describe("The ID of the extension to debug"),targetId:z.string().optional().describe("The opaque ID of the debug target"),requiredVersion:z.string().default("1.3").describe("Required debugging protocol version (default: 1.3)")}},async({tabId:e,extensionId:t,targetId:r,requiredVersion:o})=>{try{if(e===void 0&&t===void 0&&r===void 0)return this.formatError("Either tabId, extensionId, or targetId must be specified to attach debugger");let i={};return e!==void 0&&(i.tabId=e),t!==void 0&&(i.extensionId=t),r!==void 0&&(i.targetId=r),await new Promise((s,n)=>{chrome.debugger.attach(i,o,()=>{chrome.runtime.lastError?n(new Error(chrome.runtime.lastError.message)):s();});}),this.formatSuccess("Debugger attached successfully",{target:i,protocolVersion:o})}catch(i){return this.formatError(i)}});}registerDetach(){this.server.registerTool("extension_tool_detach_debugger",{description:"Detach debugger from a target",inputSchema:{tabId:z.number().optional().describe("The ID of the tab to detach from"),extensionId:z.string().optional().describe("The ID of the extension to detach from"),targetId:z.string().optional().describe("The opaque ID of the debug target to detach from")}},async({tabId:e,extensionId:t,targetId:r})=>{try{if(e===void 0&&t===void 0&&r===void 0)return this.formatError("Either tabId, extensionId, or targetId must be specified to detach debugger");let o={};return e!==void 0&&(o.tabId=e),t!==void 0&&(o.extensionId=t),r!==void 0&&(o.targetId=r),await new Promise((i,s)=>{chrome.debugger.detach(o,()=>{chrome.runtime.lastError?s(new Error(chrome.runtime.lastError.message)):i();});}),this.formatSuccess("Debugger detached successfully",{target:o})}catch(o){return this.formatError(o)}});}registerSendCommand(){this.server.registerTool("extension_tool_send_debugger_command",{description:"Send a Chrome DevTools Protocol command to a debugging target",inputSchema:{tabId:z.number().optional().describe("The ID of the tab target"),extensionId:z.string().optional().describe("The ID of the extension target"),targetId:z.string().optional().describe("The opaque ID of the debug target"),sessionId:z.string().optional().describe("The session ID for child protocol sessions"),method:z.string().describe("CDP method name (e.g., Runtime.evaluate, Page.navigate)"),commandParams:z.record(z.any()).optional().describe("Parameters for the CDP command")}},async({tabId:e,extensionId:t,targetId:r,sessionId:o,method:i,commandParams:s})=>{try{if(e===void 0&&t===void 0&&r===void 0)return this.formatError("Either tabId, extensionId, or targetId must be specified to send command");let n={};e!==void 0&&(n.tabId=e),t!==void 0&&(n.extensionId=t),r!==void 0&&(n.targetId=r),o!==void 0&&(n.sessionId=o);let a=await new Promise((c,u)=>{chrome.debugger.sendCommand(n,i,s,m=>{chrome.runtime.lastError?u(new Error(chrome.runtime.lastError.message)):c(m);});});return this.formatJson({method:i,target:n,result:a||null})}catch(n){return this.formatError(n)}});}registerGetTargets(){this.server.registerTool("extension_tool_get_debug_targets",{description:"Get list of available debug targets",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.debugger.getTargets(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({count:e.length,targets:e.map(t=>({id:t.id,type:t.type,title:t.title,url:t.url,attached:t.attached,tabId:t.tabId,extensionId:t.extensionId,faviconUrl:t.faviconUrl}))})}catch(e){return this.formatError(e)}});}};var Me=class extends d{apiName="DeclarativeContent";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.declarativeContent?chrome.declarativeContent.onPageChanged?typeof chrome.declarativeContent.PageStateMatcher!="function"?{available:!1,message:"chrome.declarativeContent.PageStateMatcher constructor is not available",details:"The declarativeContent API constructors are not accessible."}:{available:!0,message:"DeclarativeContent API is fully available"}:{available:!1,message:"chrome.declarativeContent.onPageChanged is not available",details:"The declarativeContent API appears to be partially available. Check manifest permissions."}:{available:!1,message:"chrome.declarativeContent API is not defined",details:'This extension needs the "declarativeContent" permission in its manifest.json'}}catch(e){return {available:false,message:"Failed to access chrome.declarativeContent API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("addRules")&&this.registerAddRules(),this.shouldRegisterTool("removeRules")&&this.registerRemoveRules(),this.shouldRegisterTool("getRules")&&this.registerGetRules();}registerAddRules(){this.server.registerTool("extension_tool_add_declarative_rules",{description:"Add declarative content rules to control when the extension action is enabled",inputSchema:{rules:z.array(z.object({id:z.string().optional().describe("Optional unique identifier for this rule"),conditions:z.array(z.object({pageUrl:z.object({hostContains:z.string().optional().describe("Matches if the host contains this string"),hostEquals:z.string().optional().describe("Matches if the host equals this string"),hostPrefix:z.string().optional().describe("Matches if the host starts with this string"),hostSuffix:z.string().optional().describe("Matches if the host ends with this string"),pathContains:z.string().optional().describe("Matches if the path contains this string"),pathEquals:z.string().optional().describe("Matches if the path equals this string"),pathPrefix:z.string().optional().describe("Matches if the path starts with this string"),pathSuffix:z.string().optional().describe("Matches if the path ends with this string"),queryContains:z.string().optional().describe("Matches if the query contains this string"),queryEquals:z.string().optional().describe("Matches if the query equals this string"),queryPrefix:z.string().optional().describe("Matches if the query starts with this string"),querySuffix:z.string().optional().describe("Matches if the query ends with this string"),urlContains:z.string().optional().describe("Matches if the URL contains this string"),urlEquals:z.string().optional().describe("Matches if the URL equals this string"),urlMatches:z.string().optional().describe("Matches if the URL matches this regular expression"),urlPrefix:z.string().optional().describe("Matches if the URL starts with this string"),urlSuffix:z.string().optional().describe("Matches if the URL ends with this string"),schemes:z.array(z.string()).optional().describe("Matches if the scheme is in this list"),ports:z.array(z.number()).optional().describe("Matches if the port is in this list")}).optional().describe("URL matching criteria"),css:z.array(z.string()).optional().describe("CSS selectors that must match displayed elements"),isBookmarked:z.boolean().optional().describe("Whether the page must be bookmarked (requires bookmarks permission)")})).describe("Conditions that must be met for the rule to trigger"),actions:z.array(z.object({type:z.enum(["ShowAction","SetIcon"]).describe("Type of action to perform"),imageData:z.record(z.string()).optional().describe("Icon image data for SetIcon action")})).describe("Actions to perform when conditions are met")})).describe("Array of declarative content rules to add")}},async({rules:e})=>{try{let t=e.map(r=>{let o={conditions:r.conditions.map(i=>{let s={};return i.pageUrl&&(s.pageUrl=i.pageUrl),i.css&&(s.css=i.css),i.isBookmarked!==void 0&&(s.isBookmarked=i.isBookmarked),new chrome.declarativeContent.PageStateMatcher(s)}),actions:r.actions.map(i=>{if(i.type==="ShowAction")return new chrome.declarativeContent.ShowAction;if(i.type==="SetIcon"){let s={};return i.imageData&&(s.imageData=i.imageData),new chrome.declarativeContent.SetIcon(s)}throw new Error(`Unknown action type: ${i.type}`)})};return r.id&&(o.id=r.id),o});return await new Promise((r,o)=>{chrome.declarativeContent.onPageChanged.addRules(t,()=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r();});}),this.formatSuccess("Declarative content rules added successfully",{rulesAdded:e.length,ruleIds:e.map(r=>r.id).filter(Boolean)})}catch(t){return this.formatError(t)}});}registerRemoveRules(){this.server.registerTool("extension_tool_remove_declarative_rules",{description:"Remove declarative content rules",inputSchema:{ruleIds:z.array(z.string()).optional().describe("Array of rule IDs to remove. If not specified, all rules are removed")}},async({ruleIds:e})=>{try{return await new Promise((t,r)=>{chrome.declarativeContent.onPageChanged.removeRules(e,()=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t();});}),e&&e.length>0?this.formatSuccess("Specified declarative content rules removed successfully",{removedRuleIds:e}):this.formatSuccess("All declarative content rules removed successfully")}catch(t){return this.formatError(t)}});}registerGetRules(){this.server.registerTool("extension_tool_get_declarative_rules",{description:"Get existing declarative content rules",inputSchema:{ruleIds:z.array(z.string()).optional().describe("Array of rule IDs to retrieve. If not specified, all rules are returned")}},async({ruleIds:e})=>{try{let t=await new Promise((r,o)=>{chrome.declarativeContent.onPageChanged.getRules(e,i=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r(i);});});return this.formatJson({count:t.length,rules:t.map(r=>({id:r.id,priority:r.priority,conditions:r.conditions?.length||0,actions:r.actions?.length||0,tags:r.tags}))})}catch(t){return this.formatError(t)}});}};var Ne=class extends d{apiName="DeclarativeNetRequest";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.declarativeNetRequest?typeof chrome.declarativeNetRequest.getDynamicRules!="function"?{available:!1,message:"chrome.declarativeNetRequest.getDynamicRules is not available",details:"The declarativeNetRequest API appears to be partially available. Check manifest permissions."}:(chrome.declarativeNetRequest.getDynamicRules(e=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"DeclarativeNetRequest API is fully available"}):{available:!1,message:"chrome.declarativeNetRequest API is not defined",details:'This extension needs the "declarativeNetRequest" or "declarativeNetRequestWithHostAccess" permission in its manifest.json'}}catch(e){return {available:false,message:"Failed to access chrome.declarativeNetRequest API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("getDynamicRules")&&this.registerGetDynamicRules(),this.shouldRegisterTool("updateDynamicRules")&&this.registerUpdateDynamicRules(),this.shouldRegisterTool("getSessionRules")&&this.registerGetSessionRules(),this.shouldRegisterTool("updateSessionRules")&&this.registerUpdateSessionRules(),this.shouldRegisterTool("getEnabledRulesets")&&this.registerGetEnabledRulesets(),this.shouldRegisterTool("updateEnabledRulesets")&&this.registerUpdateEnabledRulesets(),this.shouldRegisterTool("updateStaticRules")&&this.registerUpdateStaticRules(),this.shouldRegisterTool("getAvailableStaticRuleCount")&&this.registerGetAvailableStaticRuleCount(),this.shouldRegisterTool("getMatchedRules")&&this.registerGetMatchedRules(),this.shouldRegisterTool("isRegexSupported")&&this.registerIsRegexSupported(),this.shouldRegisterTool("testMatchOutcome")&&this.registerTestMatchOutcome(),this.shouldRegisterTool("setExtensionActionOptions")&&this.registerSetExtensionActionOptions();}registerGetDynamicRules(){this.server.registerTool("extension_tool_get_dynamic_rules",{description:"Get the current set of dynamic rules for the extension"},async()=>{try{let e=await new Promise((t,r)=>{chrome.declarativeNetRequest.getDynamicRules(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({count:e.length,rules:e})}catch(e){return this.formatError(e)}});}registerUpdateDynamicRules(){this.server.registerTool("extension_tool_update_dynamic_rules",{description:"Modify the current set of dynamic rules for the extension",inputSchema:{removeRuleIds:z.array(z.number()).optional().describe("IDs of the rules to remove. Any invalid IDs will be ignored"),addRules:z.array(z.any()).optional().describe("Rules to add. Must follow the Rule schema")}},async({removeRuleIds:e,addRules:t})=>{try{let r={};return e!==void 0&&(r.removeRuleIds=e),t!==void 0&&(r.addRules=t),await new Promise((o,i)=>{chrome.declarativeNetRequest.updateDynamicRules(r,()=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o();});}),this.formatSuccess("Dynamic rules updated successfully",{removedCount:e?.length||0,addedCount:t?.length||0})}catch(r){return this.formatError(r)}});}registerGetSessionRules(){this.server.registerTool("extension_tool_get_session_rules",{description:"Get the current set of session scoped rules for the extension"},async()=>{try{let e=await new Promise((t,r)=>{chrome.declarativeNetRequest.getSessionRules(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({count:e.length,rules:e})}catch(e){return this.formatError(e)}});}registerUpdateSessionRules(){this.server.registerTool("extension_tool_update_session_rules",{description:"Modify the current set of session scoped rules for the extension",inputSchema:{removeRuleIds:z.array(z.number()).optional().describe("IDs of the rules to remove. Any invalid IDs will be ignored"),addRules:z.array(z.any()).optional().describe("Rules to add. Must follow the Rule schema")}},async({removeRuleIds:e,addRules:t})=>{try{let r={};return e!==void 0&&(r.removeRuleIds=e),t!==void 0&&(r.addRules=t),await new Promise((o,i)=>{chrome.declarativeNetRequest.updateSessionRules(r,()=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o();});}),this.formatSuccess("Session rules updated successfully",{removedCount:e?.length||0,addedCount:t?.length||0})}catch(r){return this.formatError(r)}});}registerGetEnabledRulesets(){this.server.registerTool("extension_tool_get_enabled_rulesets",{description:"Get the ids for the current set of enabled static rulesets",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.declarativeNetRequest.getEnabledRulesets(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({count:e.length,rulesetIds:e})}catch(e){return this.formatError(e)}});}registerUpdateEnabledRulesets(){this.server.registerTool("extension_tool_update_enabled_rulesets",{description:"Update the set of enabled static rulesets for the extension",inputSchema:{enableRulesetIds:z.array(z.string()).optional().describe("The set of ids corresponding to a static Ruleset that should be enabled"),disableRulesetIds:z.array(z.string()).optional().describe("The set of ids corresponding to a static Ruleset that should be disabled")}},async({enableRulesetIds:e,disableRulesetIds:t})=>{try{let r={};return e!==void 0&&(r.enableRulesetIds=e),t!==void 0&&(r.disableRulesetIds=t),await new Promise((o,i)=>{chrome.declarativeNetRequest.updateEnabledRulesets(r,()=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o();});}),this.formatSuccess("Enabled rulesets updated successfully",{enabledCount:e?.length||0,disabledCount:t?.length||0})}catch(r){return this.formatError(r)}});}registerUpdateStaticRules(){this.server.registerTool("extension_tool_update_static_rules",{description:"Disable and enable individual static rules in a Ruleset",inputSchema:{rulesetId:z.string().describe("The id corresponding to a static Ruleset"),enableRuleIds:z.array(z.number()).optional().describe("Set of ids corresponding to rules in the Ruleset to enable"),disableRuleIds:z.array(z.number()).optional().describe("Set of ids corresponding to rules in the Ruleset to disable")}},async({rulesetId:e,enableRuleIds:t,disableRuleIds:r})=>{try{let o={rulesetId:e};return t!==void 0&&(o.enableRuleIds=t),r!==void 0&&(o.disableRuleIds=r),await new Promise((i,s)=>{chrome.declarativeNetRequest.updateStaticRules(o,()=>{chrome.runtime.lastError?s(new Error(chrome.runtime.lastError.message)):i();});}),this.formatSuccess("Static rules updated successfully",{rulesetId:e,enabledCount:t?.length||0,disabledCount:r?.length||0})}catch(o){return this.formatError(o)}});}registerGetAvailableStaticRuleCount(){this.server.registerTool("extension_tool_get_available_static_rule_count",{description:"Get the number of static rules an extension can enable before the global static rule limit is reached",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.declarativeNetRequest.getAvailableStaticRuleCount(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({availableStaticRuleCount:e})}catch(e){return this.formatError(e)}});}registerGetMatchedRules(){this.server.registerTool("extension_tool_get_matched_rules",{description:'Get all rules matched for the extension. Requires "declarativeNetRequestFeedback" permission',inputSchema:{tabId:z.number().optional().describe("If specified, only matches rules for the given tab. Matches rules not associated with any active tab if set to -1"),minTimeStamp:z.number().optional().describe("If specified, only matches rules after the given timestamp")}},async({tabId:e,minTimeStamp:t})=>{try{let r={};e!==void 0&&(r.tabId=e),t!==void 0&&(r.minTimeStamp=t);let o=await new Promise((i,s)=>{chrome.declarativeNetRequest.getMatchedRules(r,n=>{chrome.runtime.lastError?s(new Error(chrome.runtime.lastError.message)):i(n);});});return this.formatJson({count:o.rulesMatchedInfo.length,rulesMatchedInfo:o.rulesMatchedInfo.map(i=>({rule:i.rule,tabId:i.tabId,timeStamp:i.timeStamp,timeStampFormatted:new Date(i.timeStamp).toISOString()}))})}catch(r){return this.formatError(r)}});}registerIsRegexSupported(){this.server.registerTool("extension_tool_is_regex_supported",{description:"Check if the given regular expression will be supported as a regexFilter rule condition",inputSchema:{regex:z.string().describe("The regular expression to check"),isCaseSensitive:z.boolean().optional().describe("Whether the regex specified is case sensitive. Default is true"),requireCapturing:z.boolean().optional().describe("Whether the regex specified requires capturing. Default is false")}},async({regex:e,isCaseSensitive:t,requireCapturing:r})=>{try{let o={regex:e};t!==void 0&&(o.isCaseSensitive=t),r!==void 0&&(o.requireCapturing=r);let i=await new Promise((s,n)=>{chrome.declarativeNetRequest.isRegexSupported(o,a=>{chrome.runtime.lastError?n(new Error(chrome.runtime.lastError.message)):s(a);});});return this.formatJson({regex:e,isSupported:i.isSupported,reason:i.reason})}catch(o){return this.formatError(o)}});}registerTestMatchOutcome(){this.server.registerTool("extension_tool_test_match_outcome",{description:"Check if any of the extension's declarativeNetRequest rules would match a hypothetical request. Only available for unpacked extensions",inputSchema:{url:z.string().describe("The URL of the hypothetical request"),type:z.string().describe("The resource type of the hypothetical request"),method:z.string().optional().describe('Standard HTTP method of the hypothetical request. Defaults to "get" for HTTP requests'),tabId:z.number().optional().describe("The ID of the tab in which the hypothetical request takes place. Default is -1"),initiator:z.string().optional().describe("The initiator URL (if any) for the hypothetical request"),responseHeaders:z.record(z.array(z.string())).optional().describe("The headers provided by a hypothetical response")}},async({url:e,type:t,method:r,tabId:o,initiator:i,responseHeaders:s})=>{try{let n={url:e,type:t};r!==void 0&&(n.method=r),o!==void 0&&(n.tabId=o),i!==void 0&&(n.initiator=i),s!==void 0&&(n.responseHeaders=s);let a=await new Promise((c,u)=>{chrome.declarativeNetRequest.testMatchOutcome(n,m=>{chrome.runtime.lastError?u(new Error(chrome.runtime.lastError.message)):c(m);});});return this.formatJson({url:e,matchedRulesCount:a.matchedRules.length,matchedRules:a.matchedRules})}catch(n){return this.formatError(n)}});}registerSetExtensionActionOptions(){this.server.registerTool("extension_tool_set_extension_action_options",{description:"Configure if the action count for tabs should be displayed as the extension action's badge text",inputSchema:{displayActionCountAsBadgeText:z.boolean().optional().describe("Whether to automatically display the action count for a page as the extension's badge text"),tabUpdateIncrement:z.number().optional().describe("The amount to increment the tab's action count by. Negative values will decrement the count"),tabUpdateTabId:z.number().optional().describe("The tab for which to update the action count")}},async({displayActionCountAsBadgeText:e,tabUpdateIncrement:t,tabUpdateTabId:r})=>{try{let o={};return e!==void 0&&(o.displayActionCountAsBadgeText=e),t!==void 0&&r!==void 0&&(o.tabUpdate={increment:t,tabId:r}),await new Promise((i,s)=>{chrome.declarativeNetRequest.setExtensionActionOptions(o,()=>{chrome.runtime.lastError?s(new Error(chrome.runtime.lastError.message)):i();});}),this.formatSuccess("Extension action options updated successfully",{displayActionCountAsBadgeText:e,tabUpdate:o.tabUpdate})}catch(o){return this.formatError(o)}});}};var qe=class extends d{apiName="DesktopCapture";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.desktopCapture?typeof chrome.desktopCapture.chooseDesktopMedia!="function"?{available:!1,message:"chrome.desktopCapture.chooseDesktopMedia is not available",details:"The desktopCapture API appears to be partially available. Check manifest permissions."}:{available:!0,message:"DesktopCapture API is fully available"}:{available:!1,message:"chrome.desktopCapture API is not defined",details:'This extension needs the "desktopCapture" permission in its manifest.json'}}catch(e){return {available:false,message:"Failed to access chrome.desktopCapture API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("chooseDesktopMedia")&&this.registerChooseDesktopMedia(),this.shouldRegisterTool("cancelChooseDesktopMedia")&&this.registerCancelChooseDesktopMedia();}registerChooseDesktopMedia(){this.server.registerTool("extension_tool_choose_desktop_media",{description:"Shows desktop media picker UI with the specified set of sources",inputSchema:{sources:z.array(z.enum(["screen","window","tab","audio"])).describe("Set of sources that should be shown to the user. The sources order in the set decides the tab order in the picker"),targetTabId:z.number().describe("Optional tab ID for which the stream is created. If not specified then the resulting stream can be used only by the calling extension")}},async({sources:e,targetTabId:t})=>{try{let r;t!==void 0&&(r=await new Promise((i,s)=>{chrome.tabs.get(t,n=>{chrome.runtime.lastError?s(new Error(chrome.runtime.lastError.message)):i(n);});}));let o=await new Promise((i,s)=>{let n=chrome.desktopCapture.chooseDesktopMedia(e,r,(a,c)=>{chrome.runtime.lastError?s(new Error(chrome.runtime.lastError.message)):i({requestId:n,streamId:a,options:c});});});return o.streamId?this.formatJson({requestId:o.requestId,streamId:o.streamId,canRequestAudioTrack:o.options?.canRequestAudioTrack||!1,sources:e,targetTabId:t}):this.formatSuccess("User canceled the desktop media selection")}catch(r){return this.formatError(r)}});}registerCancelChooseDesktopMedia(){this.server.registerTool("extension_tool_cancel_choose_desktop_media",{description:"Hides desktop media picker dialog shown by chooseDesktopMedia",inputSchema:{desktopMediaRequestId:z.number().describe("Id returned by chooseDesktopMedia()")}},async({desktopMediaRequestId:e})=>{try{return chrome.desktopCapture.cancelChooseDesktopMedia(e),this.formatSuccess("Desktop media picker dialog canceled successfully",{requestId:e})}catch(t){return this.formatError(t)}});}};var Ge=class extends d{apiName="Devtools.inspectedWindow";constructor(e,t={}){super(e,t);}checkAvailability(){try{return !chrome.devtools||!chrome.devtools.inspectedWindow?{available:!1,message:"chrome.devtools.inspectedWindow API is not defined",details:'This extension needs to be running in a devtools context and have the "devtools" permission in its manifest.json'}:typeof chrome.devtools.inspectedWindow.eval!="function"?{available:!1,message:"chrome.devtools.inspectedWindow.eval is not available",details:"The devtools.inspectedWindow API appears to be partially available. Check manifest permissions and devtools context."}:{available:!0,message:"Devtools.inspectedWindow API is fully available"}}catch(e){return {available:false,message:"Failed to access chrome.devtools.inspectedWindow API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("eval")&&this.registerEval(),this.shouldRegisterTool("reload")&&this.registerReload(),this.shouldRegisterTool("getResources")&&this.registerGetResources();}registerEval(){this.server.registerTool("extension_tool_eval_inspected_window",{description:"Evaluate JavaScript expression in the context of the inspected page",inputSchema:{expression:z.string().describe("JavaScript expression to evaluate in the inspected page"),options:z.object({frameURL:z.string().optional().describe("URL of the frame to evaluate in. If omitted, evaluates in the main frame"),contextSecurityOrigin:z.string().optional().describe("Security origin for the evaluation context"),useContentScriptContext:z.boolean().optional().describe("If true, evaluate in the context of a content script")}).optional().describe("Options for the evaluation")}},async({expression:e,options:t})=>{try{let r=await new Promise((s,n)=>{let a={};t?.frameURL!==void 0&&(a.frameURL=t.frameURL),t?.contextSecurityOrigin!==void 0&&(a.contextSecurityOrigin=t.contextSecurityOrigin),t?.useContentScriptContext!==void 0&&(a.useContentScriptContext=t.useContentScriptContext),chrome.devtools.inspectedWindow.eval(e,Object.keys(a).length>0?a:void 0,(c,u)=>{chrome.runtime.lastError?n(new Error(chrome.runtime.lastError.message)):s([c,u]);});}),[o,i]=r;return i?this.formatJson({success:!1,expression:e,exception:{isError:i.isError,code:i.code,description:i.description,details:i.details,isException:i.isException,value:i.value}}):this.formatJson({success:!0,expression:e,result:o})}catch(r){return this.formatError(r)}});}registerReload(){this.server.registerTool("extension_tool_reload_inspected_window",{description:"Reload the inspected page",inputSchema:{reloadOptions:z.object({ignoreCache:z.boolean().optional().describe("If true, reload ignoring cache"),userAgent:z.string().optional().describe("Custom user agent string to use for the reload"),injectedScript:z.string().optional().describe("Script to inject into every frame of the inspected page immediately upon load")}).optional().describe("Options for the reload")}},async({reloadOptions:e})=>{try{let t={};return e?.ignoreCache!==void 0&&(t.ignoreCache=e.ignoreCache),e?.userAgent!==void 0&&(t.userAgent=e.userAgent),e?.injectedScript!==void 0&&(t.injectedScript=e.injectedScript),chrome.devtools.inspectedWindow.reload(Object.keys(t).length>0?t:void 0),this.formatSuccess("Inspected window reload initiated",{options:e||{}})}catch(t){return this.formatError(t)}});}registerGetResources(){this.server.registerTool("extension_tool_get_inspected_window_resources",{description:"Get all resources loaded by the inspected page",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.devtools.inspectedWindow.getResources(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({count:e.length,resources:e.map(t=>({url:t.url}))})}catch(e){return this.formatError(e)}});}};var je=class extends d{apiName="Devtools.network";constructor(e,t={}){super(e,t);}checkAvailability(){try{return !chrome.devtools||!chrome.devtools.network?{available:!1,message:"chrome.devtools.network API is not defined",details:'This extension needs to be running in a devtools context and have the "devtools" permission in its manifest.json'}:typeof chrome.devtools.network.getHAR!="function"?{available:!1,message:"chrome.devtools.network.getHAR is not available",details:"The devtools.network API appears to be partially available. Check manifest permissions and ensure running in devtools context."}:(chrome.devtools.network.getHAR(e=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"Devtools.network API is fully available"})}catch(e){return {available:false,message:"Failed to access chrome.devtools.network API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("getHAR")&&this.registerGetHAR(),this.shouldRegisterTool("onNavigated")&&this.registerOnNavigated(),this.shouldRegisterTool("onRequestFinished")&&this.registerOnRequestFinished();}registerGetHAR(){this.server.registerTool("extension_tool_get_har",{description:"Get the HTTP Archive (HAR) log for the current page, containing all network requests",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.devtools.network.getHAR(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({version:e.version,creator:e.creator,browser:e.browser,pages:e.pages?.map(t=>({startedDateTime:t.startedDateTime,id:t.id,title:t.title,pageTimings:t.pageTimings})),entries:e.entries?.map(t=>({startedDateTime:t.startedDateTime,time:t.time,request:{method:t.request.method,url:t.request.url,httpVersion:t.request.httpVersion,headers:t.request.headers,queryString:t.request.queryString,postData:t.request.postData,headersSize:t.request.headersSize,bodySize:t.request.bodySize},response:{status:t.response.status,statusText:t.response.statusText,httpVersion:t.response.httpVersion,headers:t.response.headers,content:{size:t.response.content.size,mimeType:t.response.content.mimeType,compression:t.response.content.compression},redirectURL:t.response.redirectURL,headersSize:t.response.headersSize,bodySize:t.response.bodySize},cache:t.cache,timings:t.timings,serverIPAddress:t.serverIPAddress,connection:t.connection})),totalEntries:e.entries?.length||0})}catch(e){return this.formatError(e)}});}registerOnNavigated(){this.server.registerTool("extension_tool_on_navigated",{description:"Set up a listener for navigation events in the inspected window",inputSchema:{enable:z.boolean().optional().describe("Whether to enable or disable the navigation listener")}},async({enable:e=true})=>{try{if(e){let t=r=>{console.log("Navigation detected to:",r);};return chrome.devtools.network.onNavigated.addListener(t),this.formatSuccess("Navigation listener enabled",{listening:!0,event:"onNavigated"})}else return chrome.devtools.network.onNavigated.removeListener(()=>{}),this.formatSuccess("Navigation listener disabled",{listening:!1,event:"onNavigated"})}catch(t){return this.formatError(t)}});}registerOnRequestFinished(){this.server.registerTool("extension_tool_on_request_finished",{description:"Set up a listener for network request completion events",inputSchema:{enable:z.boolean().optional().describe("Whether to enable or disable the request finished listener")}},async({enable:e=true})=>{try{if(e){let t=r=>{console.log("Request finished:",{url:r.request.url,method:r.request.method,status:r.response.status,time:r.time});};return chrome.devtools.network.onRequestFinished.addListener(t),this.formatSuccess("Request finished listener enabled",{listening:!0,event:"onRequestFinished"})}else return chrome.devtools.network.onRequestFinished.removeListener(()=>{}),this.formatSuccess("Request finished listener disabled",{listening:!1,event:"onRequestFinished"})}catch(t){return this.formatError(t)}});}};var Be=class extends d{apiName="Devtools.panels";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.devtools?.panels?typeof chrome.devtools.panels.create!="function"?{available:!1,message:"chrome.devtools.panels.create is not available",details:"The devtools.panels API appears to be partially available. Check manifest permissions and context."}:{available:!0,message:"Devtools.panels API is fully available"}:{available:!1,message:"chrome.devtools.panels API is not defined",details:'This extension needs to be running in a devtools context and have the "devtools" permission in its manifest.json'}}catch(e){return {available:false,message:"Failed to access chrome.devtools.panels API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("createPanel")&&this.registerCreatePanel(),this.shouldRegisterTool("createSidebarPane")&&this.registerCreateSidebarPane(),this.shouldRegisterTool("getThemeColor")&&this.registerGetThemeColor(),this.shouldRegisterTool("openResource")&&this.registerOpenResource(),this.shouldRegisterTool("setOpenResourceHandler")&&this.registerSetOpenResourceHandler();}registerCreatePanel(){this.server.registerTool("extension_tool_create_panel",{description:"Create a new devtools panel with specified title and icon",inputSchema:{title:z.string().describe("The title of the panel"),iconPath:z.string().describe("Path to the icon for the panel"),pagePath:z.string().describe("Path to the HTML page that will be displayed in the panel")}},async({title:e,iconPath:t,pagePath:r})=>{try{return await new Promise((o,i)=>{chrome.devtools.panels.create(e,t,r,s=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o(s);});}),this.formatSuccess("Panel created successfully",{title:e,iconPath:t,pagePath:r,panelCreated:!0})}catch(o){return this.formatError(o)}});}registerCreateSidebarPane(){this.server.registerTool("extension_tool_create_sidebar_pane",{description:"Create a sidebar pane in the Elements panel",inputSchema:{title:z.string().describe("The title of the sidebar pane")}},async({title:e})=>{try{return await new Promise((t,r)=>{chrome.devtools.panels.elements.createSidebarPane(e,o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});}),this.formatSuccess("Sidebar pane created successfully",{title:e,sidebarPaneCreated:!0})}catch(t){return this.formatError(t)}});}registerGetThemeColor(){this.server.registerTool("extension_tool_get_theme_color",{description:"Get the current theme color of the devtools",inputSchema:{}},async()=>{try{let e=chrome.devtools.panels.themeName;return this.formatJson({themeName:e,description:e==="dark"?"Dark theme is active":"Light theme is active"})}catch(e){return this.formatError(e)}});}registerOpenResource(){this.server.registerTool("extension_tool_open_resource",{description:"Open a resource in the Sources panel",inputSchema:{url:z.string().describe("URL of the resource to open"),lineNumber:z.number().optional().describe("Line number to navigate to (1-based)")}},async({url:e,lineNumber:t})=>{try{return await new Promise((r,o)=>{t!==void 0?chrome.devtools.panels.openResource(e,t,()=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r();}):chrome.devtools.panels.openResource(e,1,()=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r();});}),this.formatSuccess("Resource opened successfully",{url:e,lineNumber:t||"not specified"})}catch(r){return this.formatError(r)}});}registerSetOpenResourceHandler(){this.server.registerTool("extension_tool_set_open_resource_handler",{description:"Set a handler for when resources are opened in the devtools",inputSchema:{enable:z.boolean().describe("Whether to enable or disable the open resource handler")}},async({enable:e})=>{try{return e?(chrome.devtools.panels.setOpenResourceHandler(t=>(console.log("Resource opened:",t),!0)),this.formatSuccess("Open resource handler enabled",{handlerEnabled:!0})):(chrome.devtools.panels.setOpenResourceHandler(void 0),this.formatSuccess("Open resource handler disabled",{handlerEnabled:!1}))}catch(t){return this.formatError(t)}});}};var We=class extends d{apiName="DocumentScan";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.documentScan?typeof chrome.documentScan.scan!="function"?{available:!1,message:"chrome.documentScan.scan is not available",details:"The documentScan API appears to be partially available. Check manifest permissions and ensure you are running on ChromeOS."}:{available:!0,message:"DocumentScan API is fully available"}:{available:!1,message:"chrome.documentScan API is not defined",details:'This extension needs the "documentScan" permission in its manifest.json and only works on ChromeOS'}}catch(e){return {available:false,message:"Failed to access chrome.documentScan API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("scan")&&this.registerScan(),this.shouldRegisterTool("getScannerList")&&this.registerGetScannerList(),this.shouldRegisterTool("openScanner")&&this.registerOpenScanner(),this.shouldRegisterTool("closeScanner")&&this.registerCloseScanner(),this.shouldRegisterTool("getOptionGroups")&&this.registerGetOptionGroups(),this.shouldRegisterTool("setOptions")&&this.registerSetOptions(),this.shouldRegisterTool("startScan")&&this.registerStartScan(),this.shouldRegisterTool("readScanData")&&this.registerReadScanData(),this.shouldRegisterTool("cancelScan")&&this.registerCancelScan();}registerScan(){this.server.registerTool("extension_tool_document_scan",{description:"Perform a simple document scan using any available scanner",inputSchema:{maxImages:z.number().min(1).optional().describe("The number of scanned images allowed. Default is 1"),mimeTypes:z.array(z.string()).optional().describe('The MIME types that are accepted by the caller (e.g., ["image/jpeg", "image/png"])')}},async({maxImages:e,mimeTypes:t})=>{try{let r={};e!==void 0&&(r.maxImages=e),t!==void 0&&(r.mimeTypes=t);let o=await new Promise((i,s)=>{chrome.documentScan.scan(r,n=>{chrome.runtime.lastError?s(new Error(chrome.runtime.lastError.message)):i(n);});});return this.formatJson({mimeType:o.mimeType,imageCount:o.dataUrls.length,dataUrls:o.dataUrls})}catch(r){return this.formatError(r)}});}registerGetScannerList(){this.server.registerTool("extension_tool_get_scanner_list",{description:"Get the list of available document scanners",inputSchema:{local:z.boolean().optional().describe("Only return scanners that are directly attached to the computer"),secure:z.boolean().optional().describe("Only return scanners that use a secure transport, such as USB or TLS")}},async({local:e,secure:t})=>{try{let r={};e!==void 0&&(r.local=e),t!==void 0&&(r.secure=t);let o=await new Promise((i,s)=>{chrome.documentScan.getScannerList(r,n=>{chrome.runtime.lastError?s(new Error(chrome.runtime.lastError.message)):i(n);});});return this.formatJson({result:o.result,scannerCount:o.scanners.length,scanners:o.scanners.map(i=>({scannerId:i.scannerId,name:i.name,manufacturer:i.manufacturer,model:i.model,deviceUuid:i.deviceUuid,connectionType:i.connectionType,protocolType:i.protocolType,secure:i.secure,imageFormats:i.imageFormats}))})}catch(r){return this.formatError(r)}});}registerOpenScanner(){this.server.registerTool("extension_tool_open_scanner",{description:"Open a scanner for exclusive access and configuration",inputSchema:{scannerId:z.string().describe("The ID of a scanner to be opened (from getScannerList)")}},async({scannerId:e})=>{try{let t=await new Promise((o,i)=>{chrome.documentScan.openScanner(e,s=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o(s);});}),r={result:t.result,scannerId:t.scannerId};return t.scannerHandle&&(r.scannerHandle=t.scannerHandle),t.options&&(r.optionCount=Object.keys(t.options).length,r.availableOptions=Object.keys(t.options)),this.formatJson(r)}catch(t){return this.formatError(t)}});}registerCloseScanner(){this.server.registerTool("extension_tool_close_scanner",{description:"Close a previously opened scanner",inputSchema:{scannerHandle:z.string().describe("The handle of an open scanner from openScanner")}},async({scannerHandle:e})=>{try{let t=await new Promise((r,o)=>{chrome.documentScan.closeScanner(e,i=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r(i);});});return this.formatJson({result:t.result,scannerHandle:t.scannerHandle})}catch(t){return this.formatError(t)}});}registerGetOptionGroups(){this.server.registerTool("extension_tool_get_option_groups",{description:"Get the group names and member options from an open scanner",inputSchema:{scannerHandle:z.string().describe("The handle of an open scanner from openScanner")}},async({scannerHandle:e})=>{try{let t=await new Promise((o,i)=>{chrome.documentScan.getOptionGroups(e,s=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o(s);});}),r={result:t.result,scannerHandle:t.scannerHandle};return t.groups&&(r.groupCount=t.groups.length,r.groups=t.groups.map(o=>({title:o.title,memberCount:o.members.length,members:o.members}))),this.formatJson(r)}catch(t){return this.formatError(t)}});}registerSetOptions(){this.server.registerTool("extension_tool_set_scanner_options",{description:"Set options on a scanner",inputSchema:{scannerHandle:z.string().describe("The handle of an open scanner from openScanner"),options:z.array(z.object({name:z.string().describe("The name of the option to set"),type:z.enum(["UNKNOWN","BOOL","INT","FIXED","STRING","BUTTON","GROUP"]).describe("The data type of the option"),value:z.union([z.string(),z.number(),z.boolean(),z.array(z.number())]).optional().describe("The value to set (leave unset for automatic setting)")})).describe("Array of option settings to apply")}},async({scannerHandle:e,options:t})=>{try{let r=t.map(s=>{let n={name:s.name,type:s.type};return s.value!==void 0&&(n.value=s.value),n}),o=await new Promise((s,n)=>{chrome.documentScan.setOptions(e,r,a=>{chrome.runtime.lastError?n(new Error(chrome.runtime.lastError.message)):s(a);});}),i={scannerHandle:o.scannerHandle,results:o.results.map(s=>({name:s.name,result:s.result}))};return o.options&&(i.updatedOptionCount=Object.keys(o.options).length,i.updatedOptions=Object.keys(o.options)),this.formatJson(i)}catch(r){return this.formatError(r)}});}registerStartScan(){this.server.registerTool("extension_tool_start_scan",{description:"Start a scan on an open scanner",inputSchema:{scannerHandle:z.string().describe("The handle of an open scanner from openScanner"),format:z.string().describe('The MIME type to return scanned data in (e.g., "image/jpeg")'),maxReadSize:z.number().min(32768).optional().describe("Maximum bytes returned in a single readScanData response (minimum 32768)")}},async({scannerHandle:e,format:t,maxReadSize:r})=>{try{let o={format:t};r!==void 0&&(o.maxReadSize=r);let i=await new Promise((n,a)=>{chrome.documentScan.startScan(e,o,c=>{chrome.runtime.lastError?a(new Error(chrome.runtime.lastError.message)):n(c);});}),s={result:i.result,scannerHandle:i.scannerHandle};return i.job&&(s.job=i.job),this.formatJson(s)}catch(o){return this.formatError(o)}});}registerReadScanData(){this.server.registerTool("extension_tool_read_scan_data",{description:"Read the next chunk of scan data from an active scan job",inputSchema:{job:z.string().describe("Active job handle from startScan")}},async({job:e})=>{try{let t=await new Promise((o,i)=>{chrome.documentScan.readScanData(e,s=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o(s);});}),r={job:t.job,result:t.result};return t.data&&(r.dataSize=t.data.byteLength,r.hasData=t.data.byteLength>0),t.estimatedCompletion!==void 0&&(r.estimatedCompletion=t.estimatedCompletion),this.formatJson(r)}catch(t){return this.formatError(t)}});}registerCancelScan(){this.server.registerTool("extension_tool_cancel_scan",{description:"Cancel an active scan job",inputSchema:{job:z.string().describe("The handle of an active scan job from startScan")}},async({job:e})=>{try{let t=await new Promise((r,o)=>{chrome.documentScan.cancelScan(e,i=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r(i);});});return this.formatJson({job:t.job,result:t.result})}catch(t){return this.formatError(t)}});}};var Je=class extends d{apiName="Dom";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.dom?typeof chrome.dom.openOrClosedShadowRoot!="function"?{available:!1,message:"chrome.dom.openOrClosedShadowRoot is not available",details:"The dom API appears to be partially available. Check Chrome version (88+) and context."}:{available:!0,message:"Dom API is fully available"}:{available:!1,message:"chrome.dom API is not defined",details:"This extension needs to be running in a content script context"}}catch(e){return {available:false,message:"Failed to access chrome.dom API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("openOrClosedShadowRoot")&&this.registerOpenOrClosedShadowRoot();}registerOpenOrClosedShadowRoot(){this.server.registerTool("extension_tool_open_or_closed_shadow_root",{description:"Gets the open shadow root or the closed shadow root hosted by the specified element",inputSchema:{elementSelector:z.string().describe("CSS selector to find the element that hosts the shadow root"),elementIndex:z.number().optional().default(0).describe("Index of the element if multiple elements match the selector (default: 0)")}},async({elementSelector:e,elementIndex:t=0})=>{try{let r=document.querySelectorAll(e);if(r.length===0)return this.formatError(`No elements found matching selector: ${e}`);if(t>=r.length)return this.formatError(`Element index ${t} is out of range. Found ${r.length} elements.`);let o=r[t];if(!o)return this.formatError("Selected element is not an HTMLElement");let i=chrome.dom.openOrClosedShadowRoot(o);if(!i)return this.formatSuccess("No shadow root found on the specified element",{elementSelector:e,elementIndex:t,tagName:o.tagName,id:o.id||null,className:o.className||null});let s={mode:i.mode,delegatesFocus:i.delegatesFocus,slotAssignment:i.slotAssignment,childElementCount:i.childElementCount,innerHTML:i.innerHTML,textContent:i.textContent,children:Array.from(i.children).map((n,a)=>({index:a,tagName:n.tagName,id:n.id||null,className:n.className||null,textContent:n.textContent?.substring(0,100)||null}))};return this.formatJson({found:!0,elementSelector:e,elementIndex:t,element:{tagName:o.tagName,id:o.id||null,className:o.className||null},shadowRoot:s})}catch(r){return this.formatError(r)}});}};var ze=class extends d{apiName="Downloads";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.downloads?typeof chrome.downloads.search!="function"?{available:!1,message:"chrome.downloads.search is not available",details:"The downloads API appears to be partially available. Check manifest permissions."}:(chrome.downloads.search({},e=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"Downloads API is fully available"}):{available:!1,message:"chrome.downloads API is not defined",details:'This extension needs the "downloads" permission in its manifest.json'}}catch(e){return {available:false,message:"Failed to access chrome.downloads API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("download")&&this.registerDownload(),this.shouldRegisterTool("search")&&this.registerSearch(),this.shouldRegisterTool("pause")&&this.registerPause(),this.shouldRegisterTool("resume")&&this.registerResume(),this.shouldRegisterTool("cancel")&&this.registerCancel(),this.shouldRegisterTool("getFileIcon")&&this.registerGetFileIcon(),this.shouldRegisterTool("open")&&this.registerOpen(),this.shouldRegisterTool("show")&&this.registerShow(),this.shouldRegisterTool("showDefaultFolder")&&this.registerShowDefaultFolder(),this.shouldRegisterTool("erase")&&this.registerErase(),this.shouldRegisterTool("removeFile")&&this.registerRemoveFile(),this.shouldRegisterTool("acceptDanger")&&this.registerAcceptDanger(),this.shouldRegisterTool("setUiOptions")&&this.registerSetUiOptions();}registerDownload(){this.server.registerTool("extension_tool_download_file",{description:"Download a file from a URL",inputSchema:{url:z.string().url().describe("The URL to download"),filename:z.string().optional().describe("A file path relative to the Downloads directory to contain the downloaded file"),saveAs:z.boolean().optional().describe("Use a file-chooser to allow the user to select a filename"),method:z.enum(["GET","POST"]).optional().describe("The HTTP method to use if the URL uses the HTTP[S] protocol"),headers:z.array(z.object({name:z.string().describe("Name of the HTTP header"),value:z.string().describe("Value of the HTTP header")})).optional().describe("Extra HTTP headers to send with the request"),body:z.string().optional().describe("Post body"),conflictAction:z.enum(["uniquify","overwrite","prompt"]).optional().describe("The action to take if filename already exists")}},async({url:e,filename:t,saveAs:r,method:o,headers:i,body:s,conflictAction:n})=>{try{let a={url:e};t!==void 0&&(a.filename=t),r!==void 0&&(a.saveAs=r),o!==void 0&&(a.method=o),i!==void 0&&(a.headers=i),s!==void 0&&(a.body=s),n!==void 0&&(a.conflictAction=n);let c=await new Promise((u,m)=>{chrome.downloads.download(a,g=>{chrome.runtime.lastError?m(new Error(chrome.runtime.lastError.message)):u(g);});});return this.formatSuccess("Download started successfully",{downloadId:c,url:e,filename:t||"auto-generated"})}catch(a){return this.formatError(a)}});}registerSearch(){this.server.registerTool("extension_tool_search_downloads",{description:"Search for downloads matching specified criteria",inputSchema:{id:z.number().optional().describe("The id of the DownloadItem to query"),url:z.string().optional().describe("The absolute URL that this download initiated from"),urlRegex:z.string().optional().describe("Limits results to DownloadItem whose url matches the given regular expression"),filename:z.string().optional().describe("Absolute local path"),filenameRegex:z.string().optional().describe("Limits results to DownloadItem whose filename matches the given regular expression"),query:z.array(z.string()).optional().describe("Search terms that must be contained in filename or url. Terms beginning with dash are excluded"),state:z.enum(["in_progress","interrupted","complete"]).optional().describe("Indicates whether the download is progressing, interrupted, or complete"),danger:z.enum(["file","url","content","uncommon","host","unwanted","safe","accepted"]).optional().describe("Indication of whether this download is thought to be safe or suspicious"),mime:z.string().optional().describe("The file's MIME type"),startTime:z.string().optional().describe("The time when the download began in ISO 8601 format"),endTime:z.string().optional().describe("The time when the download ended in ISO 8601 format"),startedAfter:z.string().optional().describe("Limits results to DownloadItem that started after the given time in ISO 8601 format"),startedBefore:z.string().optional().describe("Limits results to DownloadItem that started before the given time in ISO 8601 format"),endedAfter:z.string().optional().describe("Limits results to DownloadItem that ended after the given time in ISO 8601 format"),endedBefore:z.string().optional().describe("Limits results to DownloadItem that ended before the given time in ISO 8601 format"),totalBytesGreater:z.number().optional().describe("Limits results to DownloadItem whose totalBytes is greater than the given integer"),totalBytesLess:z.number().optional().describe("Limits results to DownloadItem whose totalBytes is less than the given integer"),exists:z.boolean().optional().describe("Whether the downloaded file exists"),limit:z.number().optional().describe("The maximum number of matching DownloadItem returned. Defaults to 1000"),orderBy:z.array(z.string()).optional().describe("Set elements to DownloadItem properties to sort results. Prefix with hyphen for descending order")}},async e=>{try{let t={};e.id!==void 0&&(t.id=e.id),e.url!==void 0&&(t.url=e.url),e.urlRegex!==void 0&&(t.urlRegex=e.urlRegex),e.filename!==void 0&&(t.filename=e.filename),e.filenameRegex!==void 0&&(t.filenameRegex=e.filenameRegex),e.query!==void 0&&(t.query=e.query),e.state!==void 0&&(t.state=e.state),e.danger!==void 0&&(t.danger=e.danger),e.mime!==void 0&&(t.mime=e.mime),e.startTime!==void 0&&(t.startTime=e.startTime),e.endTime!==void 0&&(t.endTime=e.endTime),e.startedAfter!==void 0&&(t.startedAfter=e.startedAfter),e.startedBefore!==void 0&&(t.startedBefore=e.startedBefore),e.endedAfter!==void 0&&(t.endedAfter=e.endedAfter),e.endedBefore!==void 0&&(t.endedBefore=e.endedBefore),e.totalBytesGreater!==void 0&&(t.totalBytesGreater=e.totalBytesGreater),e.totalBytesLess!==void 0&&(t.totalBytesLess=e.totalBytesLess),e.exists!==void 0&&(t.exists=e.exists),e.limit!==void 0&&(t.limit=e.limit),e.orderBy!==void 0&&(t.orderBy=e.orderBy);let r=await new Promise((o,i)=>{chrome.downloads.search(t,s=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o(s);});});return this.formatJson({count:r.length,downloads:r.map(o=>({id:o.id,url:o.url,finalUrl:o.finalUrl,filename:o.filename,incognito:o.incognito,danger:o.danger,mime:o.mime,startTime:o.startTime,endTime:o.endTime,estimatedEndTime:o.estimatedEndTime,state:o.state,paused:o.paused,canResume:o.canResume,error:o.error,bytesReceived:o.bytesReceived,totalBytes:o.totalBytes,fileSize:o.fileSize,exists:o.exists,byExtensionId:o.byExtensionId,byExtensionName:o.byExtensionName}))})}catch(t){return this.formatError(t)}});}registerPause(){this.server.registerTool("extension_tool_pause_download",{description:"Pause a download",inputSchema:{downloadId:z.number().describe("The id of the download to pause")}},async({downloadId:e})=>{try{return await new Promise((t,r)=>{chrome.downloads.pause(e,()=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t();});}),this.formatSuccess("Download paused successfully",{downloadId:e})}catch(t){return this.formatError(t)}});}registerResume(){this.server.registerTool("extension_tool_resume_download",{description:"Resume a paused download",inputSchema:{downloadId:z.number().describe("The id of the download to resume")}},async({downloadId:e})=>{try{return await new Promise((t,r)=>{chrome.downloads.resume(e,()=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t();});}),this.formatSuccess("Download resumed successfully",{downloadId:e})}catch(t){return this.formatError(t)}});}registerCancel(){this.server.registerTool("extension_tool_cancel_download",{description:"Cancel a download",inputSchema:{downloadId:z.number().describe("The id of the download to cancel")}},async({downloadId:e})=>{try{return await new Promise((t,r)=>{chrome.downloads.cancel(e,()=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t();});}),this.formatSuccess("Download cancelled successfully",{downloadId:e})}catch(t){return this.formatError(t)}});}registerGetFileIcon(){this.server.registerTool("extension_tool_get_file_icon",{description:"Retrieve an icon for the specified download",inputSchema:{downloadId:z.number().describe("The identifier for the download"),size:z.number().optional().describe("The size of the returned icon. Supported sizes are 16 and 32. Default is 32")}},async({downloadId:e,size:t})=>{try{let r={};t!==void 0&&(r.size=t);let o=await new Promise((i,s)=>{chrome.downloads.getFileIcon(e,r,n=>{chrome.runtime.lastError?s(new Error(chrome.runtime.lastError.message)):i(n);});});return this.formatJson({downloadId:e,iconURL:o||null,size:t||32})}catch(r){return this.formatError(r)}});}registerOpen(){this.server.registerTool("extension_tool_open_download",{description:"Open the downloaded file if the download is complete",inputSchema:{downloadId:z.number().describe("The identifier for the downloaded file")}},async({downloadId:e})=>{try{return chrome.downloads.open(e),this.formatSuccess("Download opened successfully",{downloadId:e})}catch(t){return this.formatError(t)}});}registerShow(){this.server.registerTool("extension_tool_show_download",{description:"Show the downloaded file in its folder in a file manager",inputSchema:{downloadId:z.number().describe("The identifier for the downloaded file")}},async({downloadId:e})=>{try{return chrome.downloads.show(e),this.formatSuccess("Download shown in file manager",{downloadId:e})}catch(t){return this.formatError(t)}});}registerShowDefaultFolder(){this.server.registerTool("extension_tool_show_default_folder",{description:"Show the default Downloads folder in a file manager",inputSchema:{}},async()=>{try{return chrome.downloads.showDefaultFolder(),this.formatSuccess("Default Downloads folder shown in file manager")}catch(e){return this.formatError(e)}});}registerErase(){this.server.registerTool("extension_tool_erase_downloads",{description:"Erase matching downloads from history without deleting the downloaded files",inputSchema:{id:z.number().optional().describe("The id of the DownloadItem to erase"),url:z.string().optional().describe("The absolute URL that this download initiated from"),urlRegex:z.string().optional().describe("Limits results to DownloadItem whose url matches the given regular expression"),filename:z.string().optional().describe("Absolute local path"),filenameRegex:z.string().optional().describe("Limits results to DownloadItem whose filename matches the given regular expression"),state:z.enum(["in_progress","interrupted","complete"]).optional().describe("Indicates whether the download is progressing, interrupted, or complete"),danger:z.enum(["file","url","content","uncommon","host","unwanted","safe","accepted"]).optional().describe("Indication of whether this download is thought to be safe or suspicious"),mime:z.string().optional().describe("The file's MIME type"),startedAfter:z.string().optional().describe("Limits results to DownloadItem that started after the given time in ISO 8601 format"),startedBefore:z.string().optional().describe("Limits results to DownloadItem that started before the given time in ISO 8601 format"),endedAfter:z.string().optional().describe("Limits results to DownloadItem that ended after the given time in ISO 8601 format"),endedBefore:z.string().optional().describe("Limits results to DownloadItem that ended before the given time in ISO 8601 format"),limit:z.number().optional().describe("The maximum number of matching DownloadItem to erase")}},async e=>{try{let t={};e.id!==void 0&&(t.id=e.id),e.url!==void 0&&(t.url=e.url),e.urlRegex!==void 0&&(t.urlRegex=e.urlRegex),e.filename!==void 0&&(t.filename=e.filename),e.filenameRegex!==void 0&&(t.filenameRegex=e.filenameRegex),e.state!==void 0&&(t.state=e.state),e.danger!==void 0&&(t.danger=e.danger),e.mime!==void 0&&(t.mime=e.mime),e.startedAfter!==void 0&&(t.startedAfter=e.startedAfter),e.startedBefore!==void 0&&(t.startedBefore=e.startedBefore),e.endedAfter!==void 0&&(t.endedAfter=e.endedAfter),e.endedBefore!==void 0&&(t.endedBefore=e.endedBefore),e.limit!==void 0&&(t.limit=e.limit);let r=await new Promise((o,i)=>{chrome.downloads.erase(t,s=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o(s);});});return this.formatSuccess("Downloads erased from history successfully",{erasedCount:r.length,erasedIds:r})}catch(t){return this.formatError(t)}});}registerRemoveFile(){this.server.registerTool("extension_tool_remove_file",{description:"Remove the downloaded file if it exists and the download is complete",inputSchema:{downloadId:z.number().describe("The identifier for the downloaded file to remove")}},async({downloadId:e})=>{try{return await new Promise((t,r)=>{chrome.downloads.removeFile(e,()=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t();});}),this.formatSuccess("Downloaded file removed successfully",{downloadId:e})}catch(t){return this.formatError(t)}});}registerAcceptDanger(){this.server.registerTool("extension_tool_accept_danger",{description:"Prompt the user to accept a dangerous download",inputSchema:{downloadId:z.number().describe("The identifier for the DownloadItem")}},async({downloadId:e})=>{try{return await new Promise((t,r)=>{chrome.downloads.acceptDanger(e,()=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t();});}),this.formatSuccess("Dangerous download accepted",{downloadId:e})}catch(t){return this.formatError(t)}});}registerSetUiOptions(){this.server.registerTool("extension_tool_set_ui_options",{description:"Change the download UI of every window associated with the current browser profile",inputSchema:{enabled:z.boolean().describe("Enable or disable the download UI")}},async({enabled:e})=>{try{return await new Promise((t,r)=>{chrome.downloads.setUiOptions({enabled:e},()=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t();});}),this.formatSuccess("Download UI options updated successfully",{enabled:e})}catch(t){return this.formatError(t)}});}};var He=class extends d{apiName="Enterprise.deviceAttributes";constructor(e,t={}){super(e,t);}checkAvailability(){try{return !chrome.enterprise||!chrome.enterprise.deviceAttributes?{available:!1,message:"chrome.enterprise.deviceAttributes API is not defined",details:'This extension needs the "enterprise.deviceAttributes" permission in its manifest.json and must run on Chrome OS'}:typeof chrome.enterprise.deviceAttributes.getDirectoryDeviceId!="function"?{available:!1,message:"chrome.enterprise.deviceAttributes.getDirectoryDeviceId is not available",details:"The enterprise device attributes API appears to be partially available. Check manifest permissions and ensure this is running on Chrome OS."}:(chrome.enterprise.deviceAttributes.getDirectoryDeviceId(e=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"Enterprise Device Attributes API is fully available"})}catch(e){return {available:false,message:"Failed to access chrome.enterprise.deviceAttributes API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("getDirectoryDeviceId")&&this.registerGetDirectoryDeviceId(),this.shouldRegisterTool("getDeviceSerialNumber")&&this.registerGetDeviceSerialNumber(),this.shouldRegisterTool("getDeviceAssetId")&&this.registerGetDeviceAssetId(),this.shouldRegisterTool("getDeviceAnnotatedLocation")&&this.registerGetDeviceAnnotatedLocation(),this.shouldRegisterTool("getDeviceHostname")&&this.registerGetDeviceHostname();}registerGetDirectoryDeviceId(){this.server.registerTool("extension_tool_get_directory_device_id",{description:"Get the directory device ID for the Chrome OS device",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.enterprise.deviceAttributes.getDirectoryDeviceId(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({directoryDeviceId:e})}catch(e){return this.formatError(e)}});}registerGetDeviceSerialNumber(){this.server.registerTool("extension_tool_get_device_serial_number",{description:"Get the serial number of the Chrome OS device",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.enterprise.deviceAttributes.getDeviceSerialNumber(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({deviceSerialNumber:e})}catch(e){return this.formatError(e)}});}registerGetDeviceAssetId(){this.server.registerTool("extension_tool_get_device_asset_id",{description:"Get the asset ID of the Chrome OS device",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.enterprise.deviceAttributes.getDeviceAssetId(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({deviceAssetId:e})}catch(e){return this.formatError(e)}});}registerGetDeviceAnnotatedLocation(){this.server.registerTool("extension_tool_get_device_annotated_location",{description:"Get the annotated location of the Chrome OS device",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.enterprise.deviceAttributes.getDeviceAnnotatedLocation(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({deviceAnnotatedLocation:e})}catch(e){return this.formatError(e)}});}registerGetDeviceHostname(){this.server.registerTool("extension_tool_get_device_hostname",{description:"Get the hostname of the Chrome OS device",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.enterprise.deviceAttributes.getDeviceHostname(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({deviceHostname:e})}catch(e){return this.formatError(e)}});}};var Ke=class extends d{apiName="Enterprise.hardwarePlatform";constructor(e,t={}){super(e,t);}checkAvailability(){try{return !chrome.enterprise||!chrome.enterprise.hardwarePlatform?{available:!1,message:"chrome.enterprise.hardwarePlatform API is not defined",details:'This extension needs the "enterprise.hardwarePlatform" permission in its manifest.json'}:typeof chrome.enterprise.hardwarePlatform.getHardwarePlatformInfo!="function"?{available:!1,message:"chrome.enterprise.hardwarePlatform.getHardwarePlatformInfo is not available",details:"The enterprise.hardwarePlatform API appears to be partially available. Check manifest permissions."}:(chrome.enterprise.hardwarePlatform.getHardwarePlatformInfo(e=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"Enterprise.hardwarePlatform API is fully available"})}catch(e){return {available:false,message:"Failed to access chrome.enterprise.hardwarePlatform API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("getHardwarePlatformInfo")&&this.registerGetHardwarePlatformInfo();}registerGetHardwarePlatformInfo(){this.server.registerTool("extension_tool_get_hardware_platform_info",{description:"Get hardware platform information for the device",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.enterprise.hardwarePlatform.getHardwarePlatformInfo(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({manufacturer:e.manufacturer,model:e.model})}catch(e){return this.formatError(e)}});}};var $e=class extends d{apiName="Enterprise.networkingAttributes";constructor(e,t={}){super(e,t);}checkAvailability(){try{return !chrome.enterprise||!chrome.enterprise.networkingAttributes?{available:!1,message:"chrome.enterprise.networkingAttributes API is not defined",details:'This extension needs the "enterprise.networkingAttributes" permission in its manifest.json and must run on ChromeOS'}:typeof chrome.enterprise.networkingAttributes.getNetworkDetails!="function"?{available:!1,message:"chrome.enterprise.networkingAttributes.getNetworkDetails is not available",details:"The enterprise networking attributes API appears to be partially available. Check manifest permissions and platform compatibility."}:{available:!0,message:"Enterprise Networking Attributes API is fully available"}}catch(e){return {available:false,message:"Failed to access chrome.enterprise.networkingAttributes API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("getNetworkDetails")&&this.registerGetNetworkDetails();}registerGetNetworkDetails(){this.server.registerTool("extension_tool_get_network_details",{description:"Get network details for the current network connection including enterprise networking attributes",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.enterprise.networkingAttributes.getNetworkDetails(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({macAddress:e.macAddress,ipv4:e.ipv4,ipv6:e.ipv6})}catch(e){return this.formatError(e)}});}};var Ye=class extends d{apiName="Enterprise.platformKeys";constructor(e,t={}){super(e,t);}checkAvailability(){try{return !chrome.enterprise||!chrome.enterprise.platformKeys?{available:!1,message:"chrome.enterprise.platformKeys API is not defined",details:'This extension needs the "enterprise.platformKeys" permission in its manifest.json and must be running on ChromeOS'}:typeof chrome.enterprise.platformKeys.getTokens!="function"?{available:!1,message:"chrome.enterprise.platformKeys.getTokens is not available",details:"The enterprise.platformKeys API appears to be partially available. Check manifest permissions and ChromeOS platform."}:(chrome.enterprise.platformKeys.getTokens(e=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"Enterprise.platformKeys API is fully available"})}catch(e){return {available:false,message:"Failed to access chrome.enterprise.platformKeys API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("getTokens")&&this.registerGetTokens(),this.shouldRegisterTool("getCertificates")&&this.registerGetCertificates(),this.shouldRegisterTool("importCertificate")&&this.registerImportCertificate(),this.shouldRegisterTool("removeCertificate")&&this.registerRemoveCertificate(),this.shouldRegisterTool("challengeMachineKey")&&this.registerChallengeMachineKey(),this.shouldRegisterTool("challengeUserKey")&&this.registerChallengeUserKey();}registerGetTokens(){this.server.registerTool("extension_tool_get_tokens",{description:"Get the available platform keys tokens",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.enterprise.platformKeys.getTokens(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({count:e.length,tokens:e.map(t=>({id:t.id,subtleCrypto:!!t.subtleCrypto}))})}catch(e){return this.formatError(e)}});}registerGetCertificates(){this.server.registerTool("extension_tool_get_certificates",{description:"Get certificates from a platform keys token",inputSchema:{tokenId:z.string().describe("The ID of the token to get certificates from")}},async({tokenId:e})=>{try{if(!(await new Promise((i,s)=>{chrome.enterprise.platformKeys.getTokens(n=>{chrome.runtime.lastError?s(new Error(chrome.runtime.lastError.message)):i(n);});})).find(i=>i.id===e))return this.formatError(`Token with ID '${e}' not found`);let o=await new Promise((i,s)=>{chrome.enterprise.platformKeys.getCertificates(e,n=>{chrome.runtime.lastError?s(new Error(chrome.runtime.lastError.message)):i(n);});});return this.formatJson({tokenId:e,count:o.length,certificates:o.map((i,s)=>({index:s,size:i.byteLength,type:"ArrayBuffer"}))})}catch(t){return this.formatError(t)}});}registerImportCertificate(){this.server.registerTool("extension_tool_import_certificate",{description:"Import a certificate to a platform keys token",inputSchema:{tokenId:z.string().describe("The ID of the token to import the certificate to"),certificate:z.string().describe("The certificate data as a base64 encoded string")}},async({tokenId:e,certificate:t})=>{try{let r=atob(t),o=new Uint8Array(r.length);for(let s=0;s<r.length;s++)o[s]=r.charCodeAt(s);let i=o.buffer;return await new Promise((s,n)=>{chrome.enterprise.platformKeys.importCertificate(e,i,()=>{chrome.runtime.lastError?n(new Error(chrome.runtime.lastError.message)):s();});}),this.formatSuccess("Certificate imported successfully",{tokenId:e,certificateSize:i.byteLength})}catch(r){return this.formatError(r)}});}registerRemoveCertificate(){this.server.registerTool("extension_tool_remove_certificate",{description:"Remove a certificate from a platform keys token",inputSchema:{tokenId:z.string().describe("The ID of the token to remove the certificate from"),certificate:z.string().describe("The certificate data as a base64 encoded string")}},async({tokenId:e,certificate:t})=>{try{let r=atob(t),o=new Uint8Array(r.length);for(let s=0;s<r.length;s++)o[s]=r.charCodeAt(s);let i=o.buffer;return await new Promise((s,n)=>{chrome.enterprise.platformKeys.removeCertificate(e,i,()=>{chrome.runtime.lastError?n(new Error(chrome.runtime.lastError.message)):s();});}),this.formatSuccess("Certificate removed successfully",{tokenId:e,certificateSize:i.byteLength})}catch(r){return this.formatError(r)}});}registerChallengeMachineKey(){this.server.registerTool("extension_tool_challenge_machine_key",{description:"Challenge the machine key for enterprise attestation",inputSchema:{challenge:z.string().describe("The challenge data as a base64 encoded string"),registerKey:z.boolean().optional().describe("Whether to register the key if it does not exist")}},async({challenge:e,registerKey:t})=>{try{let r=atob(e),o=new Uint8Array(r.length);for(let c=0;c<r.length;c++)o[c]=r.charCodeAt(c);let i=o.buffer,s=await new Promise((c,u)=>{t!==void 0?chrome.enterprise.platformKeys.challengeMachineKey(i,t,m=>{chrome.runtime.lastError?u(new Error(chrome.runtime.lastError.message)):c(m);}):chrome.enterprise.platformKeys.challengeMachineKey(i,m=>{chrome.runtime.lastError?u(new Error(chrome.runtime.lastError.message)):c(m);});}),n=new Uint8Array(s),a=btoa(String.fromCharCode(...n));return this.formatJson({challengeSize:i.byteLength,responseSize:s.byteLength,response:a,registerKey:t||!1})}catch(r){return this.formatError(r)}});}registerChallengeUserKey(){this.server.registerTool("extension_tool_challenge_user_key",{description:"Challenge the user key for enterprise attestation",inputSchema:{challenge:z.string().describe("The challenge data as a base64 encoded string"),registerKey:z.boolean().describe("Whether to register the key if it does not exist")}},async({challenge:e,registerKey:t})=>{try{let r=atob(e),o=new Uint8Array(r.length);for(let c=0;c<r.length;c++)o[c]=r.charCodeAt(c);let i=o.buffer,s=await new Promise((c,u)=>{chrome.enterprise.platformKeys.challengeUserKey(i,t,m=>{chrome.runtime.lastError?u(new Error(chrome.runtime.lastError.message)):c(m);});}),n=new Uint8Array(s),a=btoa(String.fromCharCode(...n));return this.formatJson({challengeSize:i.byteLength,responseSize:s.byteLength,response:a,registerKey:t})}catch(r){return this.formatError(r)}});}};var Qe=class extends d{apiName="Extension";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.extension?typeof chrome.extension.getViews!="function"?{available:!1,message:"chrome.extension.getViews is not available",details:"The extension API appears to be partially available. Check extension context."}:(chrome.extension.getViews(),{available:!0,message:"Extension API is fully available"}):{available:!1,message:"chrome.extension API is not defined",details:"This extension needs to be running in a Chrome extension context"}}catch(e){return {available:false,message:"Failed to access chrome.extension API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("getBackgroundPage")&&this.registerGetBackgroundPage(),this.shouldRegisterTool("getViews")&&this.registerGetViews(),this.shouldRegisterTool("isAllowedFileSchemeAccess")&&this.registerIsAllowedFileSchemeAccess(),this.shouldRegisterTool("isAllowedIncognitoAccess")&&this.registerIsAllowedIncognitoAccess(),this.shouldRegisterTool("setUpdateUrlData")&&this.registerSetUpdateUrlData();}registerGetBackgroundPage(){this.server.registerTool("extension_tool_get_background_page",{description:"Returns the JavaScript window object for the background page running inside the current extension",inputSchema:{}},async()=>{try{let e=chrome.extension.getBackgroundPage();return e?this.formatSuccess("Background page retrieved successfully",{hasBackgroundPage:!0,location:e.location.href,title:e.document.title}):this.formatSuccess("No background page found",{hasBackgroundPage:!1})}catch(e){return this.formatError(e)}});}registerGetViews(){this.server.registerTool("extension_tool_get_views",{description:"Returns an array of the JavaScript window objects for each of the pages running inside the current extension",inputSchema:{tabId:z.number().optional().describe("Find a view according to a tab id. If omitted, returns all views"),type:z.enum(["tab","popup"]).optional().describe("The type of view to get. If omitted, returns all views including background pages and tabs"),windowId:z.number().optional().describe("The window to restrict the search to. If omitted, returns all views")}},async({tabId:e,type:t,windowId:r})=>{try{let o={};e!==void 0&&(o.tabId=e),t!==void 0&&(o.type=t),r!==void 0&&(o.windowId=r);let i=chrome.extension.getViews(Object.keys(o).length>0?o:void 0);return this.formatJson({count:i.length,views:i.map((s,n)=>({index:n,location:s.location.href,title:s.document.title,isBackground:s===chrome.extension.getBackgroundPage()}))})}catch(o){return this.formatError(o)}});}registerIsAllowedFileSchemeAccess(){this.server.registerTool("extension_tool_is_allowed_file_scheme_access",{description:`Retrieves the state of the extension's access to the file:// scheme. This corresponds to the user-controlled per-extension "Allow access to File URLs" setting`,inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.extension.isAllowedFileSchemeAccess(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({isAllowedFileSchemeAccess:e,message:e?"Extension has access to file:// URLs":"Extension does not have access to file:// URLs. This can be enabled in chrome://extensions"})}catch(e){return this.formatError(e)}});}registerIsAllowedIncognitoAccess(){this.server.registerTool("extension_tool_is_allowed_incognito_access",{description:`Retrieves the state of the extension's access to Incognito-mode. This corresponds to the user-controlled per-extension "Allowed in Incognito" setting`,inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.extension.isAllowedIncognitoAccess(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({isAllowedIncognitoAccess:e,inIncognitoContext:chrome.extension.inIncognitoContext,message:e?"Extension has access to Incognito mode":"Extension does not have access to Incognito mode. This can be enabled in chrome://extensions"})}catch(e){return this.formatError(e)}});}registerSetUpdateUrlData(){this.server.registerTool("extension_tool_set_update_url_data",{description:"Sets the value of the ap CGI parameter used in the extension's update URL. This value is ignored for extensions hosted in the Chrome Extension Gallery",inputSchema:{data:z.string().describe("The data to set for the update URL parameter")}},async({data:e})=>{try{return chrome.extension.setUpdateUrlData(e),this.formatSuccess("Update URL data set successfully",{data:e,note:"This value is ignored for extensions hosted in the Chrome Extension Gallery"})}catch(t){return this.formatError(t)}});}};var Xe=class extends d{apiName="FileBrowserHandler";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.fileBrowserHandler?typeof chrome.fileBrowserHandler.onExecute!="object"||typeof chrome.fileBrowserHandler.onExecute.addListener!="function"?{available:!1,message:"chrome.fileBrowserHandler.onExecute is not available",details:"The fileBrowserHandler API appears to be partially available. Check manifest permissions and ensure running on ChromeOS."}:navigator.userAgent.includes("CrOS")?{available:!0,message:"FileBrowserHandler API is fully available"}:{available:!1,message:"FileBrowserHandler API is only available on ChromeOS",details:"This API requires ChromeOS and proper file_browser_handlers configuration in manifest.json"}:{available:!1,message:"chrome.fileBrowserHandler API is not defined",details:'This extension needs the "fileBrowserHandler" permission in its manifest.json and must be running on ChromeOS'}}catch(e){return {available:false,message:"Failed to access chrome.fileBrowserHandler API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("getExecuteEventDetails")&&this.registerGetExecuteEventDetails(),this.shouldRegisterTool("addExecuteListener")&&this.registerAddExecuteListener(),this.shouldRegisterTool("removeExecuteListener")&&this.registerRemoveExecuteListener();}registerGetExecuteEventDetails(){this.server.registerTool("extension_tool_get_execute_event_details",{description:"Get information about the current file browser handler execute event details structure",inputSchema:{}},async()=>{try{return this.formatJson({eventStructure:{id:"string - The id value from the manifest file",details:{entries:"FileSystemFileEntry[] - Array of selected file entries",tab_id:"number (optional) - The ID of the tab that raised this event"}},usage:"Use addExecuteListener to register a handler for file browser execute events",note:"This API only works on ChromeOS and requires file_browser_handlers in manifest.json"})}catch(e){return this.formatError(e)}});}registerAddExecuteListener(){this.server.registerTool("extension_tool_add_execute_listener",{description:"Add a listener for file browser handler execute events. This will log events when users execute file browser actions.",inputSchema:{logEvents:z.boolean().optional().default(true).describe("Whether to log execute events to console")}},async({logEvents:e})=>{try{let t=(r,o)=>{e&&console.log("FileBrowserHandler execute event:",{id:r,entriesCount:o.entries?.length||0,tabId:o.tab_id,timestamp:new Date().toISOString()});};return chrome.fileBrowserHandler.onExecute.addListener(t),this.formatSuccess("Execute event listener added successfully",{listenerAdded:!0,loggingEnabled:e,note:"Events will be triggered when users execute file browser actions"})}catch(t){return this.formatError(t)}});}registerRemoveExecuteListener(){this.server.registerTool("extension_tool_remove_execute_listener",{description:"Remove all execute event listeners for file browser handler",inputSchema:{}},async()=>{try{let e=chrome.fileBrowserHandler.onExecute.hasListeners();return chrome.fileBrowserHandler.onExecute.removeListener,this.formatSuccess("Execute event listeners removed",{hadListeners:e,listenersRemoved:!0,note:"All execute event listeners have been removed"})}catch(e){return this.formatError(e)}});}};var Ze=class extends d{apiName="FileSystemProvider";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.fileSystemProvider?typeof chrome.fileSystemProvider.getAll!="function"?{available:!1,message:"chrome.fileSystemProvider.getAll is not available",details:"The fileSystemProvider API appears to be partially available. Check manifest permissions and ensure running on ChromeOS."}:(chrome.fileSystemProvider.getAll(e=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"FileSystemProvider API is fully available"}):{available:!1,message:"chrome.fileSystemProvider API is not defined",details:'This extension needs the "fileSystemProvider" permission in its manifest.json and is only available on ChromeOS'}}catch(e){return {available:false,message:"Failed to access chrome.fileSystemProvider API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("mount")&&this.registerMount(),this.shouldRegisterTool("unmount")&&this.registerUnmount(),this.shouldRegisterTool("get")&&this.registerGet(),this.shouldRegisterTool("getAll")&&this.registerGetAll(),this.shouldRegisterTool("notify")&&this.registerNotify();}registerMount(){this.server.registerTool("extension_tool_mount_file_system",{description:"Mount a file system with the given fileSystemId and displayName",inputSchema:{fileSystemId:z.string().describe("The string identifier of the file system. Must be unique per each extension"),displayName:z.string().describe("A human-readable name for the file system"),writable:z.boolean().optional().describe("Whether the file system supports operations which may change contents"),openedFilesLimit:z.number().optional().describe("The maximum number of files that can be opened at once. If not specified, or 0, then not limited"),supportsNotifyTag:z.boolean().optional().describe("Whether the file system supports the tag field for observed directories"),persistent:z.boolean().optional().describe("Whether the framework should resume the file system at the next sign-in session. True by default")}},async({fileSystemId:e,displayName:t,writable:r,openedFilesLimit:o,supportsNotifyTag:i,persistent:s})=>{try{let n={fileSystemId:e,displayName:t};return r!==void 0&&(n.writable=r),o!==void 0&&(n.openedFilesLimit=o),i!==void 0&&(n.supportsNotifyTag=i),s!==void 0&&(n.persistent=s),await new Promise((a,c)=>{chrome.fileSystemProvider.mount(n,()=>{chrome.runtime.lastError?c(new Error(chrome.runtime.lastError.message)):a();});}),this.formatSuccess("File system mounted successfully",{fileSystemId:e,displayName:t,writable:n.writable,openedFilesLimit:n.openedFilesLimit,supportsNotifyTag:n.supportsNotifyTag,persistent:n.persistent})}catch(n){return this.formatError(n)}});}registerUnmount(){this.server.registerTool("extension_tool_unmount_file_system",{description:"Unmount a file system with the given fileSystemId",inputSchema:{fileSystemId:z.string().describe("The identifier of the file system to be unmounted")}},async({fileSystemId:e})=>{try{return await new Promise((t,r)=>{chrome.fileSystemProvider.unmount({fileSystemId:e},()=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t();});}),this.formatSuccess("File system unmounted successfully",{fileSystemId:e})}catch(t){return this.formatError(t)}});}registerGet(){this.server.registerTool("extension_tool_get_file_system",{description:"Get information about a file system with the specified fileSystemId",inputSchema:{fileSystemId:z.string().describe("The identifier of the file system to retrieve information about")}},async({fileSystemId:e})=>{try{let t=await new Promise((r,o)=>{chrome.fileSystemProvider.get(e,i=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r(i);});});return this.formatJson({fileSystemId:t.fileSystemId,displayName:t.displayName,writable:t.writable,openedFilesLimit:t.openedFilesLimit,supportsNotifyTag:t.supportsNotifyTag,openedFiles:t.openedFiles.map(r=>({filePath:r.filePath,mode:r.mode,openRequestId:r.openRequestId})),watchers:t.watchers.map(r=>({entryPath:r.entryPath,recursive:r.recursive,lastTag:r.lastTag}))})}catch(t){return this.formatError(t)}});}registerGetAll(){this.server.registerTool("extension_tool_get_all_file_systems",{description:"Get all file systems mounted by the extension",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.fileSystemProvider.getAll(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({count:e.length,fileSystems:e.map(t=>({fileSystemId:t.fileSystemId,displayName:t.displayName,writable:t.writable,openedFilesLimit:t.openedFilesLimit,supportsNotifyTag:t.supportsNotifyTag,openedFilesCount:t.openedFiles.length,watchersCount:t.watchers.length}))})}catch(e){return this.formatError(e)}});}registerNotify(){this.server.registerTool("extension_tool_notify_file_system_changes",{description:"Notify about changes in the watched directory at observedPath in recursive mode",inputSchema:{fileSystemId:z.string().describe("The identifier of the file system related to this change"),observedPath:z.string().describe("The path of the observed entry"),recursive:z.boolean().describe("Mode of the observed entry"),changeType:z.enum(["CHANGED","DELETED"]).describe("The type of the change which happened to the observed entry"),tag:z.string().optional().describe("Tag for the notification. Required if the file system was mounted with the supportsNotifyTag option"),changes:z.array(z.object({entryPath:z.string().describe("The path of the changed entry"),changeType:z.enum(["CHANGED","DELETED"]).describe("The type of the change which happened to the entry")})).optional().describe("List of changes to entries within the observed directory")}},async({fileSystemId:e,observedPath:t,recursive:r,changeType:o,tag:i,changes:s})=>{try{let n={fileSystemId:e,observedPath:t,recursive:r,changeType:o};return i!==void 0&&(n.tag=i),s!==void 0&&(n.changes=s.map(a=>({entryPath:a.entryPath,changeType:a.changeType}))),await new Promise((a,c)=>{chrome.fileSystemProvider.notify(n,()=>{chrome.runtime.lastError?c(new Error(chrome.runtime.lastError.message)):a();});}),this.formatSuccess("File system changes notified successfully",{fileSystemId:e,observedPath:t,recursive:r,changeType:o,tag:i,changesCount:s?.length||0})}catch(n){return this.formatError(n)}});}};var et=class extends d{apiName="FontSettings";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.fontSettings?typeof chrome.fontSettings.getFontList!="function"?{available:!1,message:"chrome.fontSettings.getFontList is not available",details:"The fontSettings API appears to be partially available. Check manifest permissions."}:(chrome.fontSettings.getFontList(e=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"FontSettings API is fully available"}):{available:!1,message:"chrome.fontSettings API is not defined",details:'This extension needs the "fontSettings" permission in its manifest.json'}}catch(e){return {available:false,message:"Failed to access chrome.fontSettings API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("getFont")&&this.registerGetFont(),this.shouldRegisterTool("setFont")&&this.registerSetFont(),this.shouldRegisterTool("clearFont")&&this.registerClearFont(),this.shouldRegisterTool("getFontList")&&this.registerGetFontList(),this.shouldRegisterTool("getDefaultFontSize")&&this.registerGetDefaultFontSize(),this.shouldRegisterTool("setDefaultFontSize")&&this.registerSetDefaultFontSize(),this.shouldRegisterTool("clearDefaultFontSize")&&this.registerClearDefaultFontSize(),this.shouldRegisterTool("getDefaultFixedFontSize")&&this.registerGetDefaultFixedFontSize(),this.shouldRegisterTool("setDefaultFixedFontSize")&&this.registerSetDefaultFixedFontSize(),this.shouldRegisterTool("clearDefaultFixedFontSize")&&this.registerClearDefaultFixedFontSize(),this.shouldRegisterTool("getMinimumFontSize")&&this.registerGetMinimumFontSize(),this.shouldRegisterTool("setMinimumFontSize")&&this.registerSetMinimumFontSize(),this.shouldRegisterTool("clearMinimumFontSize")&&this.registerClearMinimumFontSize();}registerGetFont(){this.server.registerTool("extension_tool_get_font",{description:"Get the font for a given script and generic font family",inputSchema:{genericFamily:z.enum(["standard","sansserif","serif","fixed","cursive","fantasy","math"]).describe("The generic font family for which the font should be retrieved"),script:z.string().optional().describe('The script for which the font should be retrieved. If omitted, the font setting for the global script (script code "Zyyy") is retrieved')}},async({genericFamily:e,script:t})=>{try{let r={genericFamily:e};t!==void 0&&(r.script=t);let o=await new Promise((i,s)=>{chrome.fontSettings.getFont(r,n=>{chrome.runtime.lastError?s(new Error(chrome.runtime.lastError.message)):i(n);});});return this.formatJson({fontId:o.fontId,levelOfControl:o.levelOfControl,genericFamily:e,script:t||"Zyyy"})}catch(r){return this.formatError(r)}});}registerSetFont(){this.server.registerTool("extension_tool_set_font",{description:"Set the font for a given script and generic font family",inputSchema:{fontId:z.string().describe("The font ID. The empty string means to fallback to the global script font setting"),genericFamily:z.enum(["standard","sansserif","serif","fixed","cursive","fantasy","math"]).describe("The generic font family for which the font should be set"),script:z.string().optional().describe('The script code which the font should be set. If omitted, the font setting for the global script (script code "Zyyy") is set')}},async({fontId:e,genericFamily:t,script:r})=>{try{let o={fontId:e,genericFamily:t};return r!==void 0&&(o.script=r),await new Promise((i,s)=>{chrome.fontSettings.setFont(o,()=>{chrome.runtime.lastError?s(new Error(chrome.runtime.lastError.message)):i();});}),this.formatSuccess("Font set successfully",{fontId:e,genericFamily:t,script:r||"Zyyy"})}catch(o){return this.formatError(o)}});}registerClearFont(){this.server.registerTool("extension_tool_clear_font",{description:"Clear the font set by this extension, if any",inputSchema:{genericFamily:z.enum(["standard","sansserif","serif","fixed","cursive","fantasy","math"]).describe("The generic font family for which the font should be cleared"),script:z.string().optional().describe("The script for which the font should be cleared. If omitted, the global script font setting is cleared")}},async({genericFamily:e,script:t})=>{try{let r={genericFamily:e};return t!==void 0&&(r.script=t),await new Promise((o,i)=>{chrome.fontSettings.clearFont(r,()=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o();});}),this.formatSuccess("Font cleared successfully",{genericFamily:e,script:t||"Zyyy"})}catch(r){return this.formatError(r)}});}registerGetFontList(){this.server.registerTool("extension_tool_get_font_list",{description:"Get a list of fonts on the system",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.fontSettings.getFontList(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({count:e.length,fonts:e.map(t=>({fontId:t.fontId,displayName:t.displayName}))})}catch(e){return this.formatError(e)}});}registerGetDefaultFontSize(){this.server.registerTool("extension_tool_get_default_font_size",{description:"Get the default font size",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.fontSettings.getDefaultFontSize({},o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({pixelSize:e.pixelSize,levelOfControl:e.levelOfControl})}catch(e){return this.formatError(e)}});}registerSetDefaultFontSize(){this.server.registerTool("extension_tool_set_default_font_size",{description:"Set the default font size",inputSchema:{pixelSize:z.number().min(6).max(72).describe("The font size in pixels")}},async({pixelSize:e})=>{try{return await new Promise((t,r)=>{chrome.fontSettings.setDefaultFontSize({pixelSize:e},()=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t();});}),this.formatSuccess("Default font size set successfully",{pixelSize:e})}catch(t){return this.formatError(t)}});}registerClearDefaultFontSize(){this.server.registerTool("extension_tool_clear_default_font_size",{description:"Clear the default font size set by this extension, if any",inputSchema:{}},async()=>{try{return await new Promise((e,t)=>{chrome.fontSettings.clearDefaultFontSize({},()=>{chrome.runtime.lastError?t(new Error(chrome.runtime.lastError.message)):e();});}),this.formatSuccess("Default font size cleared successfully")}catch(e){return this.formatError(e)}});}registerGetDefaultFixedFontSize(){this.server.registerTool("extension_tool_get_default_fixed_font_size",{description:"Get the default size for fixed width fonts",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.fontSettings.getDefaultFixedFontSize({},o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({pixelSize:e.pixelSize,levelOfControl:e.levelOfControl})}catch(e){return this.formatError(e)}});}registerSetDefaultFixedFontSize(){this.server.registerTool("extension_tool_set_default_fixed_font_size",{description:"Set the default size for fixed width fonts",inputSchema:{pixelSize:z.number().min(6).max(72).describe("The font size in pixels")}},async({pixelSize:e})=>{try{return await new Promise((t,r)=>{chrome.fontSettings.setDefaultFixedFontSize({pixelSize:e},()=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t();});}),this.formatSuccess("Default fixed font size set successfully",{pixelSize:e})}catch(t){return this.formatError(t)}});}registerClearDefaultFixedFontSize(){this.server.registerTool("extension_tool_clear_default_fixed_font_size",{description:"Clear the default fixed font size set by this extension, if any",inputSchema:{}},async()=>{try{return await new Promise((e,t)=>{chrome.fontSettings.clearDefaultFixedFontSize({},()=>{chrome.runtime.lastError?t(new Error(chrome.runtime.lastError.message)):e();});}),this.formatSuccess("Default fixed font size cleared successfully")}catch(e){return this.formatError(e)}});}registerGetMinimumFontSize(){this.server.registerTool("extension_tool_get_minimum_font_size",{description:"Get the minimum font size",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.fontSettings.getMinimumFontSize({},o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({pixelSize:e.pixelSize,levelOfControl:e.levelOfControl})}catch(e){return this.formatError(e)}});}registerSetMinimumFontSize(){this.server.registerTool("extension_tool_set_minimum_font_size",{description:"Set the minimum font size",inputSchema:{pixelSize:z.number().min(6).max(24).describe("The font size in pixels")}},async({pixelSize:e})=>{try{return await new Promise((t,r)=>{chrome.fontSettings.setMinimumFontSize({pixelSize:e},()=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t();});}),this.formatSuccess("Minimum font size set successfully",{pixelSize:e})}catch(t){return this.formatError(t)}});}registerClearMinimumFontSize(){this.server.registerTool("extension_tool_clear_minimum_font_size",{description:"Clear the minimum font size set by this extension, if any",inputSchema:{}},async()=>{try{return await new Promise((e,t)=>{chrome.fontSettings.clearMinimumFontSize({},()=>{chrome.runtime.lastError?t(new Error(chrome.runtime.lastError.message)):e();});}),this.formatSuccess("Minimum font size cleared successfully")}catch(e){return this.formatError(e)}});}};var tt=class extends d{apiName="Gcm";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.gcm?typeof chrome.gcm.register!="function"?{available:!1,message:"chrome.gcm.register is not available",details:"The gcm API appears to be partially available. Check manifest permissions."}:{available:!0,message:"GCM API is fully available"}:{available:!1,message:"chrome.gcm API is not defined",details:'This extension needs the "gcm" permission in its manifest.json'}}catch(e){return {available:false,message:"Failed to access chrome.gcm API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("register")&&this.registerRegister(),this.shouldRegisterTool("send")&&this.registerSend(),this.shouldRegisterTool("unregister")&&this.registerUnregister();}registerRegister(){this.server.registerTool("extension_tool_gcm_register",{description:"Register the application with Firebase Cloud Messaging (FCM) to receive messages",inputSchema:{senderIds:z.array(z.string()).min(1).max(100).describe("A list of server IDs that are allowed to send messages to the application. Must contain at least one and no more than 100 sender IDs")}},async({senderIds:e})=>{try{let t=await new Promise((r,o)=>{chrome.gcm.register(e,i=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r(i);});});return this.formatSuccess("Successfully registered with FCM",{registrationId:t,senderIds:e})}catch(t){return this.formatError(t)}});}registerSend(){this.server.registerTool("extension_tool_gcm_send",{description:"Send a message through Firebase Cloud Messaging (FCM)",inputSchema:{destinationId:z.string().describe("The ID of the server to send the message to as assigned by Google API Console"),messageId:z.string().describe("The ID of the message. Must be unique for each message in scope of the application"),data:z.record(z.string()).describe("Message data to send to the server. Case-insensitive goog. and google, as well as case-sensitive collapse_key are disallowed as key prefixes"),timeToLive:z.number().min(0).max(2419200).optional().describe("Time-to-live of the message in seconds. 0 means send immediately or fail. Default is 86,400 seconds (1 day), maximum is 2,419,200 seconds (28 days)")}},async({destinationId:e,messageId:t,data:r,timeToLive:o})=>{try{let i=JSON.stringify(r).length;if(i>4096)return this.formatError("Message data exceeds maximum size of 4096 bytes");for(let a of Object.keys(r)){let c=a.toLowerCase();if(c.startsWith("goog.")||c.startsWith("google")||a==="collapse_key")return this.formatError(`Invalid key prefix: ${a}. Keys cannot start with 'goog.', 'google', or be 'collapse_key'`)}let s={destinationId:e,messageId:t,data:r};o!==void 0&&(s.timeToLive=o);let n=await new Promise((a,c)=>{chrome.gcm.send(s,u=>{chrome.runtime.lastError?c(new Error(chrome.runtime.lastError.message)):a(u);});});return this.formatSuccess("Message sent successfully",{messageId:n,destinationId:e,dataSize:i,timeToLive:o||86400})}catch(i){return this.formatError(i)}});}registerUnregister(){this.server.registerTool("extension_tool_gcm_unregister",{description:"Unregister the application from Firebase Cloud Messaging (FCM)",inputSchema:{}},async()=>{try{return await new Promise((e,t)=>{chrome.gcm.unregister(()=>{chrome.runtime.lastError?t(new Error(chrome.runtime.lastError.message)):e();});}),this.formatSuccess("Successfully unregistered from FCM")}catch(e){return this.formatError(e)}});}};var rt=class extends d{apiName="History";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.history?typeof chrome.history.search!="function"?{available:!1,message:"chrome.history.search is not available",details:"The history API appears to be partially available. Check manifest permissions."}:(chrome.history.search({text:"",maxResults:1},e=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"History API is fully available"}):{available:!1,message:"chrome.history API is not defined",details:'This extension needs the "history" permission in its manifest.json'}}catch(e){return {available:false,message:"Failed to access chrome.history API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("addUrl")&&this.registerAddUrl(),this.shouldRegisterTool("deleteAll")&&this.registerDeleteAll(),this.shouldRegisterTool("deleteRange")&&this.registerDeleteRange(),this.shouldRegisterTool("deleteUrl")&&this.registerDeleteUrl(),this.shouldRegisterTool("getVisits")&&this.registerGetVisits(),this.shouldRegisterTool("search")&&this.registerSearch();}registerAddUrl(){this.server.registerTool("extension_tool_add_url",{description:'Add a URL to the history at the current time with a transition type of "link"',inputSchema:{url:z.string().url().describe("The URL to add to history. Must be a valid URL format")}},async({url:e})=>{try{return await new Promise((t,r)=>{chrome.history.addUrl({url:e},()=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t();});}),this.formatSuccess("URL added to history successfully",{url:e})}catch(t){return this.formatError(t)}});}registerDeleteAll(){this.server.registerTool("extension_tool_delete_all_history",{description:"Delete all items from the browser history",inputSchema:{}},async()=>{try{return await new Promise((e,t)=>{chrome.history.deleteAll(()=>{chrome.runtime.lastError?t(new Error(chrome.runtime.lastError.message)):e();});}),this.formatSuccess("All history deleted successfully")}catch(e){return this.formatError(e)}});}registerDeleteRange(){this.server.registerTool("extension_tool_delete_history_range",{description:"Remove all items within the specified date range from history. Pages will not be removed unless all visits fall within the range",inputSchema:{startTime:z.number().describe("Items added to history after this date, represented in milliseconds since the epoch"),endTime:z.number().describe("Items added to history before this date, represented in milliseconds since the epoch")}},async({startTime:e,endTime:t})=>{try{return e>=t?this.formatError("startTime must be less than endTime"):(await new Promise((r,o)=>{chrome.history.deleteRange({startTime:e,endTime:t},()=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r();});}),this.formatSuccess("History range deleted successfully",{startTime:e,endTime:t,startTimeFormatted:new Date(e).toISOString(),endTimeFormatted:new Date(t).toISOString()}))}catch(r){return this.formatError(r)}});}registerDeleteUrl(){this.server.registerTool("extension_tool_delete_url",{description:"Remove all occurrences of the given URL from history",inputSchema:{url:z.string().url().describe("The URL to remove from history. Must be in the format as returned from a call to history.search()")}},async({url:e})=>{try{return await new Promise((t,r)=>{chrome.history.deleteUrl({url:e},()=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t();});}),this.formatSuccess("URL deleted from history successfully",{url:e})}catch(t){return this.formatError(t)}});}registerGetVisits(){this.server.registerTool("extension_tool_get_visits",{description:"Retrieve information about visits to a specific URL",inputSchema:{url:z.string().url().describe("The URL to get visit information for. Must be in the format as returned from a call to history.search()")}},async({url:e})=>{try{let t=await new Promise((r,o)=>{chrome.history.getVisits({url:e},i=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r(i);});});return this.formatJson({url:e,visitCount:t.length,visits:t.map(r=>({id:r.id,visitId:r.visitId,visitTime:r.visitTime,visitTimeFormatted:r.visitTime?new Date(r.visitTime).toISOString():void 0,referringVisitId:r.referringVisitId,transition:r.transition}))})}catch(t){return this.formatError(t)}});}registerSearch(){this.server.registerTool("extension_tool_search_history",{description:"Search the history for the last visit time of each page matching the query",inputSchema:{text:z.string().describe("A free-text query to the history service. Leave empty to retrieve all pages"),startTime:z.number().optional().describe("Limit results to those visited after this date, represented in milliseconds since the epoch. Defaults to 24 hours ago if not specified"),endTime:z.number().optional().describe("Limit results to those visited before this date, represented in milliseconds since the epoch"),maxResults:z.number().min(1).max(1e3).optional().describe("The maximum number of results to retrieve. Defaults to 100")}},async({text:e,startTime:t,endTime:r,maxResults:o})=>{try{let i={text:e};t!==void 0&&(i.startTime=t),r!==void 0&&(i.endTime=r),o!==void 0&&(i.maxResults=o);let s=await new Promise((n,a)=>{chrome.history.search(i,c=>{chrome.runtime.lastError?a(new Error(chrome.runtime.lastError.message)):n(c);});});return this.formatJson({query:{text:e,startTime:t,endTime:r,maxResults:o},resultCount:s.length,results:s.map(n=>({id:n.id,url:n.url,title:n.title,lastVisitTime:n.lastVisitTime,lastVisitTimeFormatted:n.lastVisitTime?new Date(n.lastVisitTime).toISOString():void 0,visitCount:n.visitCount,typedCount:n.typedCount}))})}catch(i){return this.formatError(i)}});}};var ot=class extends d{apiName="I18n";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.i18n?typeof chrome.i18n.getMessage!="function"?{available:!1,message:"chrome.i18n.getMessage is not available",details:"The i18n API appears to be partially available. This is unexpected."}:chrome.i18n.getMessage("@@ui_locale")?{available:!0,message:"I18n API is fully available"}:{available:!1,message:"Failed to get UI locale from chrome.i18n",details:"The i18n API is not functioning properly"}:{available:!1,message:"chrome.i18n API is not defined",details:"The i18n API should be available by default in Chrome extensions"}}catch(e){return {available:false,message:"Failed to access chrome.i18n API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("getMessage")&&this.registerGetMessage(),this.shouldRegisterTool("getUILanguage")&&this.registerGetUILanguage(),this.shouldRegisterTool("getAcceptLanguages")&&this.registerGetAcceptLanguages(),this.shouldRegisterTool("detectLanguage")&&this.registerDetectLanguage();}registerGetMessage(){this.server.registerTool("extension_tool_get_message",{description:"Get a localized string for the specified message. Returns empty string if message is missing.",inputSchema:{messageName:z.string().describe("The name of the message, as specified in the messages.json file"),substitutions:z.array(z.string()).max(9).optional().describe("Up to 9 substitution strings, if the message requires any"),escapeLt:z.boolean().optional().describe("Escape < in translation to &lt;. Useful when translation is used in HTML context")}},async({messageName:e,substitutions:t,escapeLt:r})=>{try{let o={};r!==void 0&&(o.escapeLt=r);let i;return t&&t.length>0?(Object.keys(o).length>0,i=chrome.i18n.getMessage(e,t)):Object.keys(o).length>0?i=chrome.i18n.getMessage(e,void 0):i=chrome.i18n.getMessage(e),i===void 0?this.formatError("Invalid getMessage() call format"):this.formatJson({messageName:e,message:i,isEmpty:i==="",substitutions:t||[],options:o})}catch(o){return this.formatError(o)}});}registerGetUILanguage(){this.server.registerTool("extension_tool_get_ui_language",{description:"Get the browser UI language. This is different from accept languages which returns preferred user languages.",inputSchema:{}},async()=>{try{let e=chrome.i18n.getUILanguage();return this.formatJson({uiLanguage:e,description:"The browser UI language code such as en-US or fr-FR"})}catch(e){return this.formatError(e)}});}registerGetAcceptLanguages(){this.server.registerTool("extension_tool_get_accept_languages",{description:"Get the accept-languages of the browser. This is different from the locale used by the browser.",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.i18n.getAcceptLanguages(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({count:e.length,languages:e,description:"Array of language codes representing user's preferred languages"})}catch(e){return this.formatError(e)}});}registerDetectLanguage(){this.server.registerTool("extension_tool_detect_language",{description:"Detect the language of provided text using CLD (Compact Language Detector). Returns up to 3 detected languages.",inputSchema:{text:z.string().min(1).describe("User input string to be analyzed for language detection")}},async({text:e})=>{try{let t=await new Promise((r,o)=>{chrome.i18n.detectLanguage(e,i=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r(i);});});return this.formatJson({inputText:e,isReliable:t.isReliable,detectedLanguages:t.languages.map(r=>({language:r.language,percentage:r.percentage,description:r.language==="und"?"Unknown language":`ISO language code: ${r.language}`})),summary:{primaryLanguage:t.languages[0]?.language||"unknown",primaryPercentage:t.languages[0]?.percentage||0,totalLanguagesDetected:t.languages.length}})}catch(t){return this.formatError(t)}});}};var it=class extends d{apiName="Identity";constructor(e,t={}){super(e,t);}checkAvailability(){try{if(!chrome.identity)return {available:!1,message:"chrome.identity API is not defined",details:'This extension needs the "identity" permission in its manifest.json'};if(typeof chrome.identity.getRedirectURL!="function")return {available:!1,message:"chrome.identity.getRedirectURL is not available",details:"The identity API appears to be partially available. Check manifest permissions."};if(!chrome.identity.getRedirectURL())throw new Error("Failed to generate redirect URL");return {available:!0,message:"Identity API is fully available"}}catch(e){return {available:false,message:"Failed to access chrome.identity API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("getAuthToken")&&this.registerGetAuthToken(),this.shouldRegisterTool("getProfileUserInfo")&&this.registerGetProfileUserInfo(),this.shouldRegisterTool("getAccounts")&&this.registerGetAccounts(),this.shouldRegisterTool("getRedirectURL")&&this.registerGetRedirectURL(),this.shouldRegisterTool("launchWebAuthFlow")&&this.registerLaunchWebAuthFlow(),this.shouldRegisterTool("removeCachedAuthToken")&&this.registerRemoveCachedAuthToken(),this.shouldRegisterTool("clearAllCachedAuthTokens")&&this.registerClearAllCachedAuthTokens();}registerGetAuthToken(){this.server.registerTool("extension_tool_get_auth_token",{description:"Gets an OAuth2 access token using the client ID and scopes specified in manifest.json",inputSchema:{interactive:z.boolean().optional().describe("Whether to prompt the user for authorization if required"),scopes:z.array(z.string()).optional().describe("List of OAuth2 scopes to request (overrides manifest.json scopes)"),accountId:z.string().optional().describe("Account ID whose token should be returned"),enableGranularPermissions:z.boolean().optional().describe("Enable granular permissions consent screen")}},async({interactive:e,scopes:t,accountId:r,enableGranularPermissions:o})=>{try{let i={};e!==void 0&&(i.interactive=e),t!==void 0&&(i.scopes=t),r!==void 0&&(i.account={id:r}),o!==void 0&&(i.enableGranularPermissions=o);let s=await new Promise((n,a)=>{chrome.identity.getAuthToken(i,c=>{chrome.runtime.lastError?a(new Error(chrome.runtime.lastError.message)):n(c);});});return this.formatJson({token:s.token,grantedScopes:s.grantedScopes})}catch(i){return this.formatError(i)}});}registerGetProfileUserInfo(){this.server.registerTool("extension_tool_get_profile_user_info",{description:"Retrieves email address and obfuscated gaia id of the user signed into a profile",inputSchema:{accountStatus:z.enum(["SYNC","ANY"]).optional().describe("Status of the primary account (SYNC or ANY)")}},async({accountStatus:e})=>{try{let t={};e!==void 0&&(t.accountStatus=e);let r=await new Promise((o,i)=>{chrome.identity.getProfileUserInfo(t,s=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o(s);});});return this.formatJson({id:r.id,email:r.email})}catch(t){return this.formatError(t)}});}registerGetAccounts(){this.server.registerTool("extension_tool_get_accounts",{description:"Retrieves a list of AccountInfo objects describing the accounts present on the profile",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.identity.getAccounts(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({count:e.length,accounts:e.map(t=>({id:t.id}))})}catch(e){return this.formatError(e)}});}registerGetRedirectURL(){this.server.registerTool("extension_tool_get_redirect_url",{description:"Generates a redirect URL to be used in launchWebAuthFlow",inputSchema:{path:z.string().optional().describe("The path appended to the end of the generated URL")}},async({path:e})=>{try{let t=chrome.identity.getRedirectURL(e);return this.formatJson({redirectUrl:t})}catch(t){return this.formatError(t)}});}registerLaunchWebAuthFlow(){this.server.registerTool("extension_tool_launch_web_auth_flow",{description:"Starts an auth flow at the specified URL with non-Google identity providers",inputSchema:{url:z.string().describe("The URL that initiates the auth flow"),interactive:z.boolean().optional().describe("Whether to launch auth flow in interactive mode"),abortOnLoadForNonInteractive:z.boolean().optional().describe("Whether to terminate flow for non-interactive requests after page loads"),timeoutMsForNonInteractive:z.number().optional().describe("Maximum time in milliseconds for non-interactive mode")}},async({url:e,interactive:t,abortOnLoadForNonInteractive:r,timeoutMsForNonInteractive:o})=>{try{let i={url:e};t!==void 0&&(i.interactive=t),r!==void 0&&(i.abortOnLoadForNonInteractive=r),o!==void 0&&(i.timeoutMsForNonInteractive=o);let s=await new Promise((n,a)=>{chrome.identity.launchWebAuthFlow(i,c=>{chrome.runtime.lastError?a(new Error(chrome.runtime.lastError.message)):n(c);});});return this.formatJson({responseUrl:s})}catch(i){return this.formatError(i)}});}registerRemoveCachedAuthToken(){this.server.registerTool("extension_tool_remove_cached_auth_token",{description:"Removes an OAuth2 access token from the Identity API token cache",inputSchema:{token:z.string().describe("The specific token that should be removed from the cache")}},async({token:e})=>{try{let t={token:e};return await new Promise((r,o)=>{chrome.identity.removeCachedAuthToken(t,()=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r();});}),this.formatSuccess("Token removed from cache successfully",{token:e})}catch(t){return this.formatError(t)}});}registerClearAllCachedAuthTokens(){this.server.registerTool("extension_tool_clear_all_cached_auth_tokens",{description:"Resets the state of the Identity API by removing all OAuth2 tokens and user preferences",inputSchema:{}},async()=>{try{return await new Promise((e,t)=>{chrome.identity.clearAllCachedAuthTokens(()=>{chrome.runtime.lastError?t(new Error(chrome.runtime.lastError.message)):e();});}),this.formatSuccess("All cached auth tokens cleared successfully")}catch(e){return this.formatError(e)}});}};var nt=class extends d{apiName="Idle";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.idle?typeof chrome.idle.queryState!="function"?{available:!1,message:"chrome.idle.queryState is not available",details:"The idle API appears to be partially available. Check manifest permissions."}:(chrome.idle.queryState(60,e=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"Idle API is fully available"}):{available:!1,message:"chrome.idle API is not defined",details:'This extension needs the "idle" permission in its manifest.json'}}catch(e){return {available:false,message:"Failed to access chrome.idle API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("queryState")&&this.registerQueryState(),this.shouldRegisterTool("setDetectionInterval")&&this.registerSetDetectionInterval(),this.shouldRegisterTool("getAutoLockDelay")&&this.registerGetAutoLockDelay();}registerQueryState(){this.server.registerTool("extension_tool_query_idle_state",{description:'Query the current idle state of the system. Returns "locked" if the system is locked, "idle" if the user has not generated input for the specified time, or "active" otherwise.',inputSchema:{detectionIntervalInSeconds:z.number().min(15).default(60).describe("The system is considered idle if this many seconds have elapsed since the last user input detected. Minimum is 15 seconds.")}},async({detectionIntervalInSeconds:e})=>{try{let t=await new Promise((r,o)=>{chrome.idle.queryState(e,i=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r(i);});});return this.formatJson({state:t,detectionIntervalInSeconds:e,timestamp:Date.now(),timestampFormatted:new Date().toISOString()})}catch(t){return this.formatError(t)}});}registerSetDetectionInterval(){this.server.registerTool("extension_tool_set_idle_detection_interval",{description:"Set the interval used to determine when the system is in an idle state for onStateChanged events. The default interval is 60 seconds.",inputSchema:{intervalInSeconds:z.number().min(15).describe("Threshold, in seconds, used to determine when the system is in an idle state. Minimum is 15 seconds.")}},async({intervalInSeconds:e})=>{try{return chrome.idle.setDetectionInterval(e),this.formatSuccess("Idle detection interval set successfully",{intervalInSeconds:e})}catch(t){return this.formatError(t)}});}registerGetAutoLockDelay(){this.server.registerTool("extension_tool_get_auto_lock_delay",{description:"Get the time, in seconds, it takes until the screen is locked automatically while idle. Returns zero if the screen is never locked automatically. Currently supported on Chrome OS only.",inputSchema:{}},async()=>{try{if(typeof chrome.idle.getAutoLockDelay!="function")return this.formatError("getAutoLockDelay is not available. This method requires Chrome 73+ and is currently supported on Chrome OS only.");let e=await new Promise((t,r)=>{chrome.idle.getAutoLockDelay(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({autoLockDelaySeconds:e,autoLockEnabled:e>0,autoLockDelayFormatted:e>0?`${e} seconds`:"Never locks automatically"})}catch(e){return this.formatError(e)}});}};var at=class extends d{apiName="Input.ime";constructor(e,t={}){super(e,t);}checkAvailability(){try{return !chrome.input||!chrome.input.ime?{available:!1,message:"chrome.input.ime API is not defined",details:'This extension needs the "input" permission in its manifest.json and must run on ChromeOS'}:typeof chrome.input.ime.commitText!="function"?{available:!1,message:"chrome.input.ime.commitText is not available",details:"The input.ime API appears to be partially available. Check manifest permissions and platform support."}:{available:!0,message:"Input.ime API is fully available"}}catch(e){return {available:false,message:"Failed to access chrome.input.ime API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("setComposition")&&this.registerSetComposition(),this.shouldRegisterTool("clearComposition")&&this.registerClearComposition(),this.shouldRegisterTool("commitText")&&this.registerCommitText(),this.shouldRegisterTool("sendKeyEvents")&&this.registerSendKeyEvents(),this.shouldRegisterTool("hideInputView")&&this.registerHideInputView(),this.shouldRegisterTool("setCandidateWindowProperties")&&this.registerSetCandidateWindowProperties(),this.shouldRegisterTool("setCandidates")&&this.registerSetCandidates(),this.shouldRegisterTool("setCursorPosition")&&this.registerSetCursorPosition(),this.shouldRegisterTool("setMenuItems")&&this.registerSetMenuItems(),this.shouldRegisterTool("updateMenuItems")&&this.registerUpdateMenuItems(),this.shouldRegisterTool("deleteSurroundingText")&&this.registerDeleteSurroundingText();}registerSetComposition(){this.server.registerTool("extension_tool_set_composition",{description:"Set the current composition text and cursor position",inputSchema:{contextID:z.number().describe("ID of the context where the composition text will be set"),text:z.string().describe("Text to set as the current composition"),selectionStart:z.number().optional().describe("Position to start the selection"),selectionEnd:z.number().optional().describe("Position to end the selection"),cursor:z.number().describe("Position to set the cursor"),segments:z.array(z.object({start:z.number().describe("Start position of the segment"),end:z.number().describe("End position of the segment"),style:z.enum(["underline","doubleUnderline","noUnderline"]).describe("Style of the segment")})).optional().describe("Array of segments with styling information")}},async({contextID:e,text:t,selectionStart:r,selectionEnd:o,cursor:i,segments:s})=>{try{let n={contextID:e,text:t,cursor:i};r!==void 0&&(n.selectionStart=r),o!==void 0&&(n.selectionEnd=o),s!==void 0&&(n.segments=s);let a=await new Promise((c,u)=>{chrome.input.ime.setComposition(n,m=>{chrome.runtime.lastError?u(new Error(chrome.runtime.lastError.message)):c(m);});});return this.formatSuccess("Composition set successfully",{contextID:e,text:t,cursor:i,success:a})}catch(n){return this.formatError(n)}});}registerClearComposition(){this.server.registerTool("extension_tool_clear_composition",{description:"Clear the current composition text",inputSchema:{contextID:z.number().describe("ID of the context where the composition will be cleared")}},async({contextID:e})=>{try{let t=await new Promise((r,o)=>{chrome.input.ime.clearComposition({contextID:e},i=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r(i);});});return this.formatSuccess("Composition cleared successfully",{contextID:e,success:t})}catch(t){return this.formatError(t)}});}registerCommitText(){this.server.registerTool("extension_tool_commit_text",{description:"Commit the provided text to the current input",inputSchema:{contextID:z.number().describe("ID of the context where the text will be committed"),text:z.string().describe("The text to commit")}},async({contextID:e,text:t})=>{try{let r=await new Promise((o,i)=>{chrome.input.ime.commitText({contextID:e,text:t},s=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o(s);});});return this.formatSuccess("Text committed successfully",{contextID:e,text:t,success:r})}catch(r){return this.formatError(r)}});}registerSendKeyEvents(){this.server.registerTool("extension_tool_send_key_events",{description:"Send key events to the system",inputSchema:{contextID:z.number().describe("ID of the context where the key events will be sent"),keyData:z.array(z.object({type:z.enum(["keyup","keydown"]).describe("Type of key event"),requestId:z.string().optional().describe("Request ID for the key event"),key:z.string().describe("The key value"),code:z.string().describe("The key code"),keyCode:z.number().optional().describe("The key code number"),altKey:z.boolean().optional().describe("Whether Alt key is pressed"),ctrlKey:z.boolean().optional().describe("Whether Ctrl key is pressed"),shiftKey:z.boolean().optional().describe("Whether Shift key is pressed"),capsLock:z.boolean().optional().describe("Whether Caps Lock is on")})).describe("Array of key events to send")}},async({contextID:e,keyData:t})=>{try{return await new Promise((r,o)=>{chrome.input.ime.sendKeyEvents({contextID:e,keyData:t},()=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r();});}),this.formatSuccess("Key events sent successfully",{contextID:e,eventCount:t.length})}catch(r){return this.formatError(r)}});}registerHideInputView(){this.server.registerTool("extension_tool_hide_input_view",{description:"Hide the input view window",inputSchema:{}},async()=>{try{return chrome.input.ime.hideInputView(),this.formatSuccess("Input view hidden successfully")}catch(e){return this.formatError(e)}});}registerSetCandidateWindowProperties(){this.server.registerTool("extension_tool_set_candidate_window_properties",{description:"Set the properties of the candidate window",inputSchema:{engineID:z.string().describe("ID of the engine to set candidate window properties"),properties:z.object({visible:z.boolean().optional().describe("Whether the candidate window is visible"),cursorVisible:z.boolean().optional().describe("Whether the cursor is visible"),vertical:z.boolean().optional().describe("Whether the candidate window is vertical"),pageSize:z.number().optional().describe("Number of candidates to display per page"),auxiliaryText:z.string().optional().describe("Auxiliary text to show"),auxiliaryTextVisible:z.boolean().optional().describe("Whether auxiliary text is visible"),windowPosition:z.enum(["cursor","composition"]).optional().describe("Where to display the candidate window")}).describe("Properties to set for the candidate window")}},async({engineID:e,properties:t})=>{try{let r=await new Promise((o,i)=>{chrome.input.ime.setCandidateWindowProperties({engineID:e,properties:t},s=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o(s);});});return this.formatSuccess("Candidate window properties set successfully",{engineID:e,properties:t,success:r})}catch(r){return this.formatError(r)}});}registerSetCandidates(){this.server.registerTool("extension_tool_set_candidates",{description:"Set the current candidates",inputSchema:{contextID:z.number().describe("ID of the context to set candidates for"),candidates:z.array(z.object({candidate:z.string().describe("The candidate text"),id:z.number().describe("The candidate ID"),parentId:z.number().optional().describe("The parent candidate ID"),label:z.string().optional().describe("The candidate label"),annotation:z.string().optional().describe("The candidate annotation"),usage:z.object({title:z.string().describe("Usage title"),body:z.string().describe("Usage body")}).optional().describe("Usage information for the candidate")})).describe("Array of candidates to set")}},async({contextID:e,candidates:t})=>{try{let r=await new Promise((o,i)=>{chrome.input.ime.setCandidates({contextID:e,candidates:t},s=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o(s);});});return this.formatSuccess("Candidates set successfully",{contextID:e,candidateCount:t.length,success:r})}catch(r){return this.formatError(r)}});}registerSetCursorPosition(){this.server.registerTool("extension_tool_set_cursor_position",{description:"Set the position of the cursor in the candidate window",inputSchema:{contextID:z.number().describe("ID of the context to set cursor position for"),candidateID:z.number().describe("ID of the candidate to position cursor on")}},async({contextID:e,candidateID:t})=>{try{let r=await new Promise((o,i)=>{chrome.input.ime.setCursorPosition({contextID:e,candidateID:t},s=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o(s);});});return this.formatSuccess("Cursor position set successfully",{contextID:e,candidateID:t,success:r})}catch(r){return this.formatError(r)}});}registerSetMenuItems(){this.server.registerTool("extension_tool_set_menu_items",{description:"Set the current menu items",inputSchema:{engineID:z.string().describe("ID of the engine to set menu items for"),items:z.array(z.object({id:z.string().describe("Menu item ID"),label:z.string().optional().describe("Menu item label"),style:z.enum(["check","radio","separator"]).optional().describe("Menu item style"),visible:z.boolean().optional().describe("Whether the menu item is visible"),checked:z.boolean().optional().describe("Whether the menu item is checked"),enabled:z.boolean().optional().describe("Whether the menu item is enabled")})).describe("Array of menu items to set")}},async({engineID:e,items:t})=>{try{return await new Promise((r,o)=>{chrome.input.ime.setMenuItems({engineID:e,items:t},()=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r();});}),this.formatSuccess("Menu items set successfully",{engineID:e,itemCount:t.length})}catch(r){return this.formatError(r)}});}registerUpdateMenuItems(){this.server.registerTool("extension_tool_update_menu_items",{description:"Update the current menu items",inputSchema:{engineId:z.string().describe("ID of the engine to update menu items for"),items:z.array(z.object({id:z.string().describe("Menu item ID"),label:z.string().optional().describe("Menu item label"),style:z.enum(["check","radio","separator"]).optional().describe("Menu item style"),visible:z.boolean().optional().describe("Whether the menu item is visible"),checked:z.boolean().optional().describe("Whether the menu item is checked"),enabled:z.boolean().optional().describe("Whether the menu item is enabled")})).describe("Array of menu items to update")}},async({engineId:e,items:t})=>{try{return await new Promise((r,o)=>{chrome.input.ime.updateMenuItems({engineId:e,items:t},()=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r();});}),this.formatSuccess("Menu items updated successfully",{engineId:e,itemCount:t.length})}catch(r){return this.formatError(r)}});}registerDeleteSurroundingText(){this.server.registerTool("extension_tool_delete_surrounding_text",{description:"Delete the text around the cursor",inputSchema:{contextID:z.number().describe("ID of the context to delete surrounding text from"),offset:z.number().describe("Offset from the cursor position"),length:z.number().describe("Number of characters to delete"),engineID:z.string().describe("ID of the engine requesting the deletion")}},async({contextID:e,offset:t,length:r,engineID:o})=>{try{return await new Promise((i,s)=>{chrome.input.ime.deleteSurroundingText({contextID:e,offset:t,length:r,engineID:o},()=>{chrome.runtime.lastError?s(new Error(chrome.runtime.lastError.message)):i();});}),this.formatSuccess("Surrounding text deleted successfully",{contextID:e,offset:t,length:r,engineID:o})}catch(i){return this.formatError(i)}});}};var ct=class extends d{apiName="InstanceID";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.instanceID?typeof chrome.instanceID.getID!="function"?{available:!1,message:"chrome.instanceID.getID is not available",details:"The instanceID API appears to be partially available. Check manifest permissions."}:(chrome.instanceID.getID(e=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"InstanceID API is fully available"}):{available:!1,message:"chrome.instanceID API is not defined",details:'This extension needs the "gcm" permission in its manifest.json'}}catch(e){return {available:false,message:"Failed to access chrome.instanceID API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("getID")&&this.registerGetID(),this.shouldRegisterTool("getCreationTime")&&this.registerGetCreationTime(),this.shouldRegisterTool("getToken")&&this.registerGetToken(),this.shouldRegisterTool("deleteToken")&&this.registerDeleteToken(),this.shouldRegisterTool("deleteID")&&this.registerDeleteID();}registerGetID(){this.server.registerTool("extension_tool_get_instance_id",{description:"Retrieve an identifier for the app instance. The same ID will be returned as long as the application identity has not been revoked or expired",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.instanceID.getID(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({instanceID:e})}catch(e){return this.formatError(e)}});}registerGetCreationTime(){this.server.registerTool("extension_tool_get_creation_time",{description:"Retrieve the time when the InstanceID has been generated, represented in milliseconds since the epoch",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.instanceID.getCreationTime(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({creationTime:e,creationTimeFormatted:new Date(e).toISOString()})}catch(e){return this.formatError(e)}});}registerGetToken(){this.server.registerTool("extension_tool_get_token",{description:"Return a token that allows the authorized entity to access the service defined by scope",inputSchema:{authorizedEntity:z.string().describe("Identifies the entity that is authorized to access resources associated with this Instance ID. It can be a project ID from Google developer console"),scope:z.string().describe("Identifies authorized actions that the authorized entity can take. E.g. for sending GCM messages, GCM scope should be used"),options:z.record(z.string()).optional().describe("Optional key/value pairs that will be associated with the token (deprecated since Chrome 89)")}},async({authorizedEntity:e,scope:t,options:r})=>{try{let o={authorizedEntity:e,scope:t};r!==void 0&&(o.options=r);let i=await new Promise((s,n)=>{chrome.instanceID.getToken(o,a=>{chrome.runtime.lastError?n(new Error(chrome.runtime.lastError.message)):s(a);});});return this.formatJson({token:i,authorizedEntity:e,scope:t})}catch(o){return this.formatError(o)}});}registerDeleteToken(){this.server.registerTool("extension_tool_delete_token",{description:"Revoke a granted token",inputSchema:{authorizedEntity:z.string().describe("The authorized entity that is used to obtain the token"),scope:z.string().describe("The scope that is used to obtain the token")}},async({authorizedEntity:e,scope:t})=>{try{let r={authorizedEntity:e,scope:t};return await new Promise((o,i)=>{chrome.instanceID.deleteToken(r,()=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o();});}),this.formatSuccess("Token deleted successfully",{authorizedEntity:e,scope:t})}catch(r){return this.formatError(r)}});}registerDeleteID(){this.server.registerTool("extension_tool_delete_instance_id",{description:"Reset the app instance identifier and revoke all tokens associated with it",inputSchema:{}},async()=>{try{return await new Promise((e,t)=>{chrome.instanceID.deleteID(()=>{chrome.runtime.lastError?t(new Error(chrome.runtime.lastError.message)):e();});}),this.formatSuccess("Instance ID deleted successfully and all associated tokens revoked")}catch(e){return this.formatError(e)}});}};var lt=class extends d{apiName="LoginState";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.loginState?typeof chrome.loginState.getProfileType!="function"?{available:!1,message:"chrome.loginState.getProfileType is not available",details:"The loginState API appears to be partially available. Check manifest permissions and ensure this is running on ChromeOS."}:(chrome.loginState.getProfileType(e=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"LoginState API is fully available"}):{available:!1,message:"chrome.loginState API is not defined",details:'This extension needs the "loginState" permission in its manifest.json and only works on ChromeOS'}}catch(e){return {available:false,message:"Failed to access chrome.loginState API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("getProfileType")&&this.registerGetProfileType(),this.shouldRegisterTool("getSessionState")&&this.registerGetSessionState();}registerGetProfileType(){this.server.registerTool("extension_tool_get_profile_type",{description:"Get the type of the profile the extension is in (signin profile or user profile)",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.loginState.getProfileType(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({profileType:e,description:e==="SIGNIN_PROFILE"?"Extension is in the signin profile":"Extension is in the user profile"})}catch(e){return this.formatError(e)}});}registerGetSessionState(){this.server.registerTool("extension_tool_get_session_state",{description:"Get the current session state (unknown, OOBE screen, login screen, in session, lock screen, or RMA screen)",inputSchema:{}},async()=>{try{let e=await new Promise((r,o)=>{chrome.loginState.getSessionState(i=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r(i);});}),t=r=>{switch(r){case "UNKNOWN":return "Session state is unknown";case "IN_OOBE_SCREEN":return "User is in the out-of-box-experience screen";case "IN_LOGIN_SCREEN":return "User is in the login screen";case "IN_SESSION":return "User is in the session";case "IN_LOCK_SCREEN":return "User is in the lock screen";default:return "Unknown session state"}};return this.formatJson({sessionState:e,description:t(e)})}catch(e){return this.formatError(e)}});}};var dt=class extends d{apiName="Management";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.management?typeof chrome.management.getSelf!="function"?{available:!1,message:"chrome.management.getSelf is not available",details:"The management API appears to be partially available. Check manifest permissions."}:(chrome.management.getSelf(e=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"Management API is fully available"}):{available:!1,message:"chrome.management API is not defined",details:'This extension needs the "management" permission in its manifest.json'}}catch(e){return {available:false,message:"Failed to access chrome.management API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("get")&&this.registerGet(),this.shouldRegisterTool("getAll")&&this.registerGetAll(),this.shouldRegisterTool("getSelf")&&this.registerGetSelf(),this.shouldRegisterTool("setEnabled")&&this.registerSetEnabled(),this.shouldRegisterTool("uninstall")&&this.registerUninstall(),this.shouldRegisterTool("uninstallSelf")&&this.registerUninstallSelf(),this.shouldRegisterTool("launchApp")&&this.registerLaunchApp(),this.shouldRegisterTool("createAppShortcut")&&this.registerCreateAppShortcut(),this.shouldRegisterTool("generateAppForLink")&&this.registerGenerateAppForLink(),this.shouldRegisterTool("setLaunchType")&&this.registerSetLaunchType(),this.shouldRegisterTool("getPermissionWarningsById")&&this.registerGetPermissionWarningsById(),this.shouldRegisterTool("getPermissionWarningsByManifest")&&this.registerGetPermissionWarningsByManifest();}registerGet(){this.server.registerTool("extension_tool_get_extension",{description:"Get information about an installed extension, app, or theme by ID",inputSchema:{id:z.string().describe("The ID of the extension, app, or theme")}},async({id:e})=>{try{let t=await new Promise((r,o)=>{chrome.management.get(e,i=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r(i);});});return this.formatJson({id:t.id,name:t.name,shortName:t.shortName,description:t.description,version:t.version,type:t.type,enabled:t.enabled,mayDisable:t.mayDisable,installType:t.installType,isApp:t.isApp,appLaunchUrl:t.appLaunchUrl,homepageUrl:t.homepageUrl,updateUrl:t.updateUrl,offlineEnabled:t.offlineEnabled,optionsUrl:t.optionsUrl,permissions:t.permissions,hostPermissions:t.hostPermissions,disabledReason:t.disabledReason,launchType:t.launchType,availableLaunchTypes:t.availableLaunchTypes,icons:t.icons})}catch(t){return this.formatError(t)}});}registerGetAll(){this.server.registerTool("extension_tool_get_all_extensions",{description:"Get information about all installed extensions, apps, and themes",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.management.getAll(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({count:e.length,extensions:e.map(t=>({id:t.id,name:t.name,shortName:t.shortName,description:t.description,version:t.version,type:t.type,enabled:t.enabled,mayDisable:t.mayDisable,installType:t.installType,isApp:t.isApp,appLaunchUrl:t.appLaunchUrl,homepageUrl:t.homepageUrl,updateUrl:t.updateUrl,offlineEnabled:t.offlineEnabled,optionsUrl:t.optionsUrl,permissions:t.permissions,hostPermissions:t.hostPermissions,disabledReason:t.disabledReason,launchType:t.launchType,availableLaunchTypes:t.availableLaunchTypes,icons:t.icons}))})}catch(e){return this.formatError(e)}});}registerGetSelf(){this.server.registerTool("extension_tool_get_self",{description:"Get information about the calling extension, app, or theme",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.management.getSelf(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({id:e.id,name:e.name,shortName:e.shortName,description:e.description,version:e.version,type:e.type,enabled:e.enabled,mayDisable:e.mayDisable,installType:e.installType,isApp:e.isApp,appLaunchUrl:e.appLaunchUrl,homepageUrl:e.homepageUrl,updateUrl:e.updateUrl,offlineEnabled:e.offlineEnabled,optionsUrl:e.optionsUrl,permissions:e.permissions,hostPermissions:e.hostPermissions,disabledReason:e.disabledReason,launchType:e.launchType,availableLaunchTypes:e.availableLaunchTypes,icons:e.icons})}catch(e){return this.formatError(e)}});}registerSetEnabled(){this.server.registerTool("extension_tool_set_extension_enabled",{description:"Enable or disable an extension, app, or theme",inputSchema:{id:z.string().describe("The ID of the extension, app, or theme"),enabled:z.boolean().describe("Whether the extension should be enabled or disabled")}},async({id:e,enabled:t})=>{try{return await new Promise((r,o)=>{chrome.management.setEnabled(e,t,()=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r();});}),this.formatSuccess(`Extension ${t?"enabled":"disabled"} successfully`,{id:e,enabled:t})}catch(r){return this.formatError(r)}});}registerUninstall(){this.server.registerTool("extension_tool_uninstall_extension",{description:"Uninstall an extension, app, or theme",inputSchema:{id:z.string().describe("The ID of the extension, app, or theme to uninstall"),showConfirmDialog:z.boolean().optional().describe("Whether to show a confirmation dialog. Defaults to false")}},async({id:e,showConfirmDialog:t})=>{try{let r={};return t!==void 0&&(r.showConfirmDialog=t),await new Promise((o,i)=>{chrome.management.uninstall(e,r,()=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o();});}),this.formatSuccess("Extension uninstalled successfully",{id:e})}catch(r){return this.formatError(r)}});}registerUninstallSelf(){this.server.registerTool("extension_tool_uninstall_self",{description:"Uninstall the calling extension",inputSchema:{showConfirmDialog:z.boolean().optional().describe("Whether to show a confirmation dialog. Defaults to false")}},async({showConfirmDialog:e})=>{try{let t={};return e!==void 0&&(t.showConfirmDialog=e),await new Promise((r,o)=>{chrome.management.uninstallSelf(t,()=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r();});}),this.formatSuccess("Extension uninstalled successfully")}catch(t){return this.formatError(t)}});}registerLaunchApp(){this.server.registerTool("extension_tool_launch_app",{description:"Launch an application",inputSchema:{id:z.string().describe("The extension ID of the application to launch")}},async({id:e})=>{try{return await new Promise((t,r)=>{chrome.management.launchApp(e,()=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t();});}),this.formatSuccess("Application launched successfully",{id:e})}catch(t){return this.formatError(t)}});}registerCreateAppShortcut(){this.server.registerTool("extension_tool_create_app_shortcut",{description:"Create a shortcut for an app",inputSchema:{id:z.string().describe("The ID of the app to create a shortcut for")}},async({id:e})=>{try{return await new Promise((t,r)=>{chrome.management.createAppShortcut(e,()=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t();});}),this.formatSuccess("App shortcut created successfully",{id:e})}catch(t){return this.formatError(t)}});}registerGenerateAppForLink(){this.server.registerTool("extension_tool_generate_app_for_link",{description:"Generate a bookmark app for a URL",inputSchema:{url:z.string().url().describe("The URL of the web page. Must use http or https scheme"),title:z.string().describe("The title of the generated app")}},async({url:e,title:t})=>{try{let r=await new Promise((o,i)=>{chrome.management.generateAppForLink(e,t,s=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o(s);});});return this.formatJson({message:"Bookmark app generated successfully",app:{id:r.id,name:r.name,shortName:r.shortName,description:r.description,version:r.version,type:r.type,enabled:r.enabled,appLaunchUrl:r.appLaunchUrl}})}catch(r){return this.formatError(r)}});}registerSetLaunchType(){this.server.registerTool("extension_tool_set_app_launch_type",{description:"Set the launch type of an app",inputSchema:{id:z.string().describe("The ID of the app"),launchType:z.enum(["OPEN_AS_REGULAR_TAB","OPEN_AS_PINNED_TAB","OPEN_AS_WINDOW","OPEN_FULL_SCREEN"]).describe("The launch type for the app")}},async({id:e,launchType:t})=>{try{return await new Promise((r,o)=>{chrome.management.setLaunchType(e,t,()=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r();});}),this.formatSuccess("App launch type set successfully",{id:e,launchType:t})}catch(r){return this.formatError(r)}});}registerGetPermissionWarningsById(){this.server.registerTool("extension_tool_get_permission_warnings_by_id",{description:"Get permission warnings for an installed extension by ID",inputSchema:{id:z.string().describe("The ID of the installed extension")}},async({id:e})=>{try{let t=await new Promise((r,o)=>{chrome.management.getPermissionWarningsById(e,i=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r(i);});});return this.formatJson({id:e,warningCount:t.length,warnings:t})}catch(t){return this.formatError(t)}});}registerGetPermissionWarningsByManifest(){this.server.registerTool("extension_tool_get_permission_warnings_by_manifest",{description:"Get permission warnings for an extension manifest",inputSchema:{manifestStr:z.string().describe("Extension manifest JSON string")}},async({manifestStr:e})=>{try{let t=await new Promise((r,o)=>{chrome.management.getPermissionWarningsByManifest(e,i=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r(i);});});return this.formatJson({warningCount:t.length,warnings:t})}catch(t){return this.formatError(t)}});}};var mt=class extends d{apiName="Notifications";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.notifications?typeof chrome.notifications.getPermissionLevel!="function"?{available:!1,message:"chrome.notifications.getPermissionLevel is not available",details:"The notifications API appears to be partially available. Check manifest permissions."}:(chrome.notifications.getPermissionLevel(e=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"Notifications API is fully available"}):{available:!1,message:"chrome.notifications API is not defined",details:'This extension needs the "notifications" permission in its manifest.json'}}catch(e){return {available:false,message:"Failed to access chrome.notifications API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("createNotification")&&this.registerCreateNotification(),this.shouldRegisterTool("updateNotification")&&this.registerUpdateNotification(),this.shouldRegisterTool("clearNotification")&&this.registerClearNotification(),this.shouldRegisterTool("getAllNotifications")&&this.registerGetAllNotifications(),this.shouldRegisterTool("getPermissionLevel")&&this.registerGetPermissionLevel();}registerCreateNotification(){this.server.registerTool("extension_tool_create_notification",{description:"Create and display a notification",inputSchema:{notificationId:z.string().optional().describe("Identifier of the notification. If not set, an ID will be auto-generated. Max 500 characters"),type:z.enum(["basic","image","list","progress"]).describe("Type of notification template to use"),iconUrl:z.string().describe("URL to the notification icon"),title:z.string().describe("Title of the notification"),message:z.string().describe("Main notification content"),contextMessage:z.string().optional().describe("Alternate notification content with lower-weight font"),priority:z.number().min(-2).max(2).optional().describe("Priority from -2 (lowest) to 2 (highest). Default is 0"),eventTime:z.number().optional().describe("Timestamp in milliseconds past epoch (e.g. Date.now() + n)"),buttons:z.array(z.object({title:z.string().describe("Button text"),iconUrl:z.string().optional().describe("Button icon URL (deprecated on Mac)")})).max(2).optional().describe("Up to two notification action buttons"),imageUrl:z.string().optional().describe("URL to image thumbnail for image-type notifications (deprecated on Mac)"),items:z.array(z.object({title:z.string().describe("Item title"),message:z.string().describe("Item details")})).optional().describe("Items for list-type notifications (only first item visible on Mac)"),progress:z.number().min(0).max(100).optional().describe("Progress value from 0 to 100 for progress-type notifications"),isClickable:z.boolean().optional().describe("Whether notification is clickable (deprecated since Chrome 67)"),requireInteraction:z.boolean().optional().describe("Whether notification should remain visible until user interaction"),silent:z.boolean().optional().describe("Whether to suppress sounds and vibrations")}},async({notificationId:e,type:t,iconUrl:r,title:o,message:i,contextMessage:s,priority:n,eventTime:a,buttons:c,imageUrl:u,items:m,progress:g,isClickable:w,requireInteraction:k,silent:R})=>{try{let D={type:t,iconUrl:r,title:o,message:i};s!==void 0&&(D.contextMessage=s),n!==void 0&&(D.priority=n),a!==void 0&&(D.eventTime=a),c!==void 0&&(D.buttons=c),u!==void 0&&(D.imageUrl=u),m!==void 0&&(D.items=m),g!==void 0&&(D.progress=g),w!==void 0&&(D.isClickable=w),k!==void 0&&(D.requireInteraction=k),R!==void 0&&(D.silent=R);let ce=await new Promise((V,L)=>{e?chrome.notifications.create(e,D,se=>{chrome.runtime.lastError?L(new Error(chrome.runtime.lastError.message)):V(se);}):chrome.notifications.create(D,se=>{chrome.runtime.lastError?L(new Error(chrome.runtime.lastError.message)):V(se);});});return this.formatSuccess("Notification created successfully",{notificationId:ce,type:t,title:o,message:i})}catch(D){return this.formatError(D)}});}registerUpdateNotification(){this.server.registerTool("extension_tool_update_notification",{description:"Update an existing notification",inputSchema:{notificationId:z.string().describe("ID of the notification to update"),type:z.enum(["basic","image","list","progress"]).optional().describe("Type of notification template to use"),iconUrl:z.string().optional().describe("URL to the notification icon"),title:z.string().optional().describe("Title of the notification"),message:z.string().optional().describe("Main notification content"),contextMessage:z.string().optional().describe("Alternate notification content with lower-weight font"),priority:z.number().min(-2).max(2).optional().describe("Priority from -2 (lowest) to 2 (highest)"),eventTime:z.number().optional().describe("Timestamp in milliseconds past epoch"),buttons:z.array(z.object({title:z.string().describe("Button text"),iconUrl:z.string().optional().describe("Button icon URL")})).max(2).optional().describe("Up to two notification action buttons"),imageUrl:z.string().optional().describe("URL to image thumbnail"),items:z.array(z.object({title:z.string().describe("Item title"),message:z.string().describe("Item details")})).optional().describe("Items for list-type notifications"),progress:z.number().min(0).max(100).optional().describe("Progress value from 0 to 100"),requireInteraction:z.boolean().optional().describe("Whether notification should remain visible until user interaction"),silent:z.boolean().optional().describe("Whether to suppress sounds and vibrations")}},async({notificationId:e,type:t,iconUrl:r,title:o,message:i,contextMessage:s,priority:n,eventTime:a,buttons:c,imageUrl:u,items:m,progress:g,requireInteraction:w,silent:k})=>{try{let R={};return t!==void 0&&(R.type=t),r!==void 0&&(R.iconUrl=r),o!==void 0&&(R.title=o),i!==void 0&&(R.message=i),s!==void 0&&(R.contextMessage=s),n!==void 0&&(R.priority=n),a!==void 0&&(R.eventTime=a),c!==void 0&&(R.buttons=c),u!==void 0&&(R.imageUrl=u),m!==void 0&&(R.items=m),g!==void 0&&(R.progress=g),w!==void 0&&(R.requireInteraction=w),k!==void 0&&(R.silent=k),await new Promise((ce,V)=>{chrome.notifications.update(e,R,L=>{chrome.runtime.lastError?V(new Error(chrome.runtime.lastError.message)):ce(L);});})?this.formatSuccess("Notification updated successfully",{notificationId:e,updatedFields:Object.keys(R)}):this.formatSuccess("Notification not found or could not be updated",{notificationId:e})}catch(R){return this.formatError(R)}});}registerClearNotification(){this.server.registerTool("extension_tool_clear_notification",{description:"Clear a specific notification",inputSchema:{notificationId:z.string().describe("ID of the notification to clear")}},async({notificationId:e})=>{try{return await new Promise((r,o)=>{chrome.notifications.clear(e,i=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r(i);});})?this.formatSuccess("Notification cleared successfully",{notificationId:e}):this.formatSuccess("Notification not found or already cleared",{notificationId:e})}catch(t){return this.formatError(t)}});}registerGetAllNotifications(){this.server.registerTool("extension_tool_get_all_notifications",{description:"Get all active notifications for this extension",inputSchema:{}},async()=>{try{let e=await new Promise((r,o)=>{chrome.notifications.getAll(i=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r(i);});}),t=Object.keys(e);return this.formatJson({count:t.length,notificationIds:t,notifications:e})}catch(e){return this.formatError(e)}});}registerGetPermissionLevel(){this.server.registerTool("extension_tool_get_permission_level",{description:"Get the current notification permission level for this extension",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.notifications.getPermissionLevel(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({permissionLevel:e,canShowNotifications:e==="granted",description:e==="granted"?"User has granted permission to show notifications":"User has denied permission to show notifications"})}catch(e){return this.formatError(e)}});}};var ht=class extends d{apiName="Offscreen";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.offscreen?typeof chrome.offscreen.createDocument!="function"?{available:!1,message:"chrome.offscreen.createDocument is not available",details:"The offscreen API appears to be partially available. Check manifest permissions."}:{available:!0,message:"Offscreen API is fully available"}:{available:!1,message:"chrome.offscreen API is not defined",details:'This extension needs the "offscreen" permission in its manifest.json'}}catch(e){return {available:false,message:"Failed to access chrome.offscreen API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("createDocument")&&this.registerCreateDocument(),this.shouldRegisterTool("closeDocument")&&this.registerCloseDocument(),this.shouldRegisterTool("hasOffscreenDocument")&&this.registerHasOffscreenDocument();}registerCreateDocument(){this.server.registerTool("extension_tool_create_offscreen_document",{description:"Create a new offscreen document for the extension",inputSchema:{url:z.string().describe("The (relative) URL to load in the document"),reasons:z.array(z.enum(["TESTING","AUDIO_PLAYBACK","IFRAME_SCRIPTING","DOM_SCRAPING","BLOBS","DOM_PARSER","USER_MEDIA","DISPLAY_MEDIA","WEB_RTC","CLIPBOARD","LOCAL_STORAGE","WORKERS","BATTERY_STATUS","MATCH_MEDIA","GEOLOCATION"])).describe("The reason(s) the extension is creating the offscreen document"),justification:z.string().describe("A developer-provided string that explains, in more detail, the need for the background context")}},async({url:e,reasons:t,justification:r})=>{try{let o={url:e,reasons:t,justification:r};return await new Promise((i,s)=>{chrome.offscreen.createDocument(o,()=>{chrome.runtime.lastError?s(new Error(chrome.runtime.lastError.message)):i();});}),this.formatSuccess("Offscreen document created successfully",{url:e,reasons:t,justification:r})}catch(o){return this.formatError(o)}});}registerCloseDocument(){this.server.registerTool("extension_tool_close_offscreen_document",{description:"Close the currently-open offscreen document for the extension",inputSchema:{}},async()=>{try{return await new Promise((e,t)=>{chrome.offscreen.closeDocument(()=>{chrome.runtime.lastError?t(new Error(chrome.runtime.lastError.message)):e();});}),this.formatSuccess("Offscreen document closed successfully")}catch(e){return this.formatError(e)}});}registerHasOffscreenDocument(){this.server.registerTool("extension_tool_has_offscreen_document",{description:"Check if an offscreen document exists for the extension",inputSchema:{documentUrl:z.string().optional().describe("Optional specific document URL to check for")}},async({documentUrl:e})=>{try{let t=!1,r=null;if("getContexts"in chrome.runtime){let o={contextTypes:["OFFSCREEN_DOCUMENT"]};e&&(o.documentUrls=[chrome.runtime.getURL(e)]);let i=await new Promise((s,n)=>{chrome.runtime.getContexts(o,a=>{chrome.runtime.lastError?n(new Error(chrome.runtime.lastError.message)):s(a);});});t=i.length>0,t&&(r={count:i.length,contexts:i.map(s=>({contextType:s.contextType,documentUrl:s.documentUrl,frameId:s.frameId,tabId:s.tabId}))});}else try{t=(await self.clients.matchAll()).some(i=>{let s=i.url.includes(chrome.runtime.id);return e?s&&i.url.includes(e):s}),t&&(r={method:"clients.matchAll (legacy)",note:"Limited information available in Chrome versions before 116"});}catch{return this.formatSuccess("Cannot determine offscreen document status - clients API not available")}return this.formatJson({hasOffscreenDocument:t,documentInfo:r,checkedUrl:e||"any"})}catch(t){return this.formatError(t)}});}};var pt=class extends d{apiName="Omnibox";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.omnibox?typeof chrome.omnibox.setDefaultSuggestion!="function"?{available:!1,message:"chrome.omnibox.setDefaultSuggestion is not available",details:"The omnibox API appears to be partially available. Check manifest permissions."}:(chrome.omnibox.setDefaultSuggestion({description:"Test"}),{available:!0,message:"Omnibox API is fully available"}):{available:!1,message:"chrome.omnibox API is not defined",details:'This extension needs the "omnibox" field in its manifest.json with a keyword specified'}}catch(e){return {available:false,message:"Failed to access chrome.omnibox API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("setDefaultSuggestion")&&this.registerSetDefaultSuggestion(),this.shouldRegisterTool("onInputStarted")&&this.registerOnInputStarted(),this.shouldRegisterTool("onInputChanged")&&this.registerOnInputChanged(),this.shouldRegisterTool("onInputEntered")&&this.registerOnInputEntered(),this.shouldRegisterTool("onInputCancelled")&&this.registerOnInputCancelled(),this.shouldRegisterTool("onDeleteSuggestion")&&this.registerOnDeleteSuggestion();}registerSetDefaultSuggestion(){this.server.registerTool("extension_tool_set_default_suggestion",{description:"Set the description and styling for the default suggestion in the omnibox",inputSchema:{description:z.string().describe("The text displayed in the URL dropdown. Can contain XML-style markup for styling with tags: url, match, dim")}},async({description:e})=>{try{return chrome.omnibox.setDefaultSuggestion({description:e}),this.formatSuccess("Default suggestion set successfully",{description:e})}catch(t){return this.formatError(t)}});}registerOnInputStarted(){this.server.registerTool("extension_tool_add_input_started_listener",{description:"Add a listener for when user starts a keyword input session by typing the extension keyword",inputSchema:{}},async()=>{try{return chrome.omnibox.onInputStarted.addListener(()=>{console.log("Omnibox input session started");}),this.formatSuccess("Input started listener added successfully")}catch(e){return this.formatError(e)}});}registerOnInputChanged(){this.server.registerTool("extension_tool_add_input_changed_listener",{description:"Add a listener for when user changes what is typed into the omnibox",inputSchema:{enableSuggestions:z.boolean().optional().default(true).describe("Whether to provide example suggestions when input changes")}},async({enableSuggestions:e})=>{try{return chrome.omnibox.onInputChanged.addListener((t,r)=>{if(console.log("Omnibox input changed:",t),e){let o=[{content:`search_${t}`,description:`Search for <match>${t}</match>`},{content:`navigate_${t}`,description:`Navigate to <url>${t}</url>`}];r(o);}}),this.formatSuccess("Input changed listener added successfully",{enableSuggestions:e})}catch(t){return this.formatError(t)}});}registerOnInputEntered(){this.server.registerTool("extension_tool_add_input_entered_listener",{description:"Add a listener for when user accepts what is typed into the omnibox",inputSchema:{}},async()=>{try{return chrome.omnibox.onInputEntered.addListener((e,t)=>{switch(console.log("Omnibox input entered:",e,"disposition:",t),t){case "currentTab":console.log("Navigate in current tab");break;case "newForegroundTab":console.log("Navigate in new foreground tab");break;case "newBackgroundTab":console.log("Navigate in new background tab");break}}),this.formatSuccess("Input entered listener added successfully")}catch(e){return this.formatError(e)}});}registerOnInputCancelled(){this.server.registerTool("extension_tool_add_input_cancelled_listener",{description:"Add a listener for when user ends the keyword input session without accepting input",inputSchema:{}},async()=>{try{return chrome.omnibox.onInputCancelled.addListener(()=>{console.log("Omnibox input session cancelled");}),this.formatSuccess("Input cancelled listener added successfully")}catch(e){return this.formatError(e)}});}registerOnDeleteSuggestion(){this.server.registerTool("extension_tool_add_delete_suggestion_listener",{description:"Add a listener for when user deletes a suggested result",inputSchema:{}},async()=>{try{return chrome.omnibox.onDeleteSuggestion.addListener(e=>{console.log("Omnibox suggestion deleted:",e);}),this.formatSuccess("Delete suggestion listener added successfully")}catch(e){return this.formatError(e)}});}};var ft=class extends d{apiName="PageCapture";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.pageCapture?typeof chrome.pageCapture.saveAsMHTML!="function"?{available:!1,message:"chrome.pageCapture.saveAsMHTML is not available",details:"The pageCapture API appears to be partially available. Check manifest permissions."}:{available:!0,message:"PageCapture API is fully available"}:{available:!1,message:"chrome.pageCapture API is not defined",details:'This extension needs the "pageCapture" permission in its manifest.json'}}catch(e){return {available:false,message:"Failed to access chrome.pageCapture API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("saveAsMHTML")&&this.registerSaveAsMHTML();}registerSaveAsMHTML(){this.server.registerTool("extension_tool_save_as_mhtml",{description:"Save the content of a tab as MHTML format",inputSchema:{tabId:z.number().describe("The ID of the tab to save as MHTML")}},async({tabId:e})=>{try{let t=await new Promise((r,o)=>{chrome.pageCapture.saveAsMHTML({tabId:e},i=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r(i);});});return t?this.formatSuccess("Page captured as MHTML successfully",{tabId:e,size:t.size,type:t.type,sizeFormatted:`${(t.size/1024).toFixed(2)} KB`}):this.formatError("Failed to capture page as MHTML - no data returned")}catch(t){return this.formatError(t)}});}};var gt=class extends d{apiName="Permissions";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.permissions?typeof chrome.permissions.getAll!="function"?{available:!1,message:"chrome.permissions.getAll is not available",details:"The permissions API appears to be partially available. Check manifest permissions."}:(chrome.permissions.getAll(e=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"Permissions API is fully available"}):{available:!1,message:"chrome.permissions API is not defined",details:'This extension needs the "permissions" permission in its manifest.json'}}catch(e){return {available:false,message:"Failed to access chrome.permissions API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("request")&&this.registerRequest(),this.shouldRegisterTool("contains")&&this.registerContains(),this.shouldRegisterTool("getAll")&&this.registerGetAll(),this.shouldRegisterTool("remove")&&this.registerRemove(),this.shouldRegisterTool("addHostAccessRequest")&&this.registerAddHostAccessRequest(),this.shouldRegisterTool("removeHostAccessRequest")&&this.registerRemoveHostAccessRequest();}registerRequest(){this.server.registerTool("extension_tool_request_permissions",{description:"Request access to specified permissions, displaying a prompt to the user if necessary",inputSchema:{permissions:z.array(z.string()).optional().describe("List of named permissions to request"),origins:z.array(z.string()).optional().describe('List of host permissions to request (e.g., ["https://www.google.com/"])')}},async({permissions:e,origins:t})=>{try{if(!e&&!t)return this.formatError("Either permissions or origins must be specified to request permissions");let r={};return e&&e.length>0&&(r.permissions=e),t&&t.length>0&&(r.origins=t),await new Promise((i,s)=>{chrome.permissions.request(r,n=>{chrome.runtime.lastError?s(new Error(chrome.runtime.lastError.message)):i(n);});})?this.formatSuccess("Permissions granted successfully",{permissions:e||[],origins:t||[]}):this.formatSuccess("Permissions request denied by user",{permissions:e||[],origins:t||[]})}catch(r){return this.formatError(r)}});}registerContains(){this.server.registerTool("extension_tool_contains_permissions",{description:"Check if the extension has the specified permissions",inputSchema:{permissions:z.array(z.string()).optional().describe("List of named permissions to check"),origins:z.array(z.string()).optional().describe('List of host permissions to check (e.g., ["https://www.google.com/"])')}},async({permissions:e,origins:t})=>{try{if(!e&&!t)return this.formatError("Either permissions or origins must be specified to check permissions");let r={};e&&e.length>0&&(r.permissions=e),t&&t.length>0&&(r.origins=t);let o=await new Promise((i,s)=>{chrome.permissions.contains(r,n=>{chrome.runtime.lastError?s(new Error(chrome.runtime.lastError.message)):i(n);});});return this.formatJson({hasPermissions:o,checkedPermissions:e||[],checkedOrigins:t||[]})}catch(r){return this.formatError(r)}});}registerGetAll(){this.server.registerTool("extension_tool_get_all_permissions",{description:"Get the extension's current set of permissions",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.permissions.getAll(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({permissions:e.permissions||[],origins:e.origins||[],permissionsCount:(e.permissions||[]).length,originsCount:(e.origins||[]).length})}catch(e){return this.formatError(e)}});}registerRemove(){this.server.registerTool("extension_tool_remove_permissions",{description:"Remove access to the specified permissions",inputSchema:{permissions:z.array(z.string()).optional().describe("List of named permissions to remove"),origins:z.array(z.string()).optional().describe('List of host permissions to remove (e.g., ["https://www.google.com/"])')}},async({permissions:e,origins:t})=>{try{if(!e&&!t)return this.formatError("Either permissions or origins must be specified to remove permissions");let r={};return e&&e.length>0&&(r.permissions=e),t&&t.length>0&&(r.origins=t),await new Promise((i,s)=>{chrome.permissions.remove(r,n=>{chrome.runtime.lastError?s(new Error(chrome.runtime.lastError.message)):i(n);});})?this.formatSuccess("Permissions removed successfully",{permissions:e||[],origins:t||[]}):this.formatSuccess("Permissions could not be removed (may be required permissions)",{permissions:e||[],origins:t||[]})}catch(r){return this.formatError(r)}});}registerAddHostAccessRequest(){this.server.registerTool("extension_tool_add_host_access_request",{description:"Add a host access request that will be shown to the user",inputSchema:{tabId:z.number().optional().describe("The id of the tab where host access requests can be shown"),documentId:z.string().optional().describe("The id of a document where host access requests can be shown"),pattern:z.string().optional().describe("The URL pattern where host access requests can be shown")}},async({tabId:e,documentId:t,pattern:r})=>{try{if(e===void 0&&t===void 0)return this.formatError("Either tabId or documentId must be specified to add host access request");let o={};return e!==void 0&&(o.tabId=e),t!==void 0&&(o.documentId=t),r!==void 0&&(o.pattern=r),await new Promise((i,s)=>{chrome.permissions.addHostAccessRequest(o,()=>{chrome.runtime.lastError?s(new Error(chrome.runtime.lastError.message)):i();});}),this.formatSuccess("Host access request added successfully",{tabId:e,documentId:t,pattern:r})}catch(o){return this.formatError(o)}});}registerRemoveHostAccessRequest(){this.server.registerTool("extension_tool_remove_host_access_request",{description:"Remove a host access request",inputSchema:{tabId:z.number().optional().describe("The id of the tab where host access request will be removed"),documentId:z.string().optional().describe("The id of a document where host access request will be removed"),pattern:z.string().optional().describe("The URL pattern where host access request will be removed")}},async({tabId:e,documentId:t,pattern:r})=>{try{if(e===void 0&&t===void 0)return this.formatError("Either tabId or documentId must be specified to remove host access request");let o={};return e!==void 0&&(o.tabId=e),t!==void 0&&(o.documentId=t),r!==void 0&&(o.pattern=r),await new Promise((i,s)=>{chrome.permissions.removeHostAccessRequest(o,()=>{chrome.runtime.lastError?s(new Error(chrome.runtime.lastError.message)):i();});}),this.formatSuccess("Host access request removed successfully",{tabId:e,documentId:t,pattern:r})}catch(o){return this.formatError(o)}});}};var bt=class extends d{apiName="PlatformKeys";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.platformKeys?typeof chrome.platformKeys.selectClientCertificates!="function"?{available:!1,message:"chrome.platformKeys.selectClientCertificates is not available",details:"The platformKeys API appears to be partially available. Check manifest permissions and ensure running on ChromeOS."}:typeof chrome.platformKeys.subtleCrypto!="function"?{available:!1,message:"chrome.platformKeys.subtleCrypto is not available",details:"The platformKeys API appears to be partially available. Check manifest permissions."}:{available:!0,message:"PlatformKeys API is fully available"}:{available:!1,message:"chrome.platformKeys API is not defined",details:'This extension needs the "platformKeys" permission in its manifest.json and must run on ChromeOS'}}catch(e){return {available:false,message:"Failed to access chrome.platformKeys API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("selectClientCertificates")&&this.registerSelectClientCertificates(),this.shouldRegisterTool("getKeyPair")&&this.registerGetKeyPair(),this.shouldRegisterTool("getKeyPairBySpki")&&this.registerGetKeyPairBySpki(),this.shouldRegisterTool("verifyTLSServerCertificate")&&this.registerVerifyTLSServerCertificate(),this.shouldRegisterTool("getSubtleCrypto")&&this.registerGetSubtleCrypto();}registerSelectClientCertificates(){this.server.registerTool("extension_tool_select_client_certificates",{description:"Filter and select client certificates that match the request and are available to the extension",inputSchema:{request:z.object({certificateTypes:z.array(z.enum(["rsaSign","ecdsaSign"])).describe("List of certificate types requested, sorted by server preference"),certificateAuthorities:z.array(z.string()).optional().describe("List of distinguished names of certificate authorities (base64-encoded DER)")}).describe("Certificate request parameters"),interactive:z.boolean().describe("If true, present filtered list to user for manual selection"),clientCerts:z.array(z.string()).optional().describe("Optional list of certificates to operate on (base64-encoded DER)")}},async({request:e,interactive:t,clientCerts:r})=>{try{let o=e.certificateAuthorities?.map(a=>{let c=atob(a),u=new Uint8Array(c.length);for(let m=0;m<c.length;m++)u[m]=c.charCodeAt(m);return u.buffer}),i=r?.map(a=>{let c=atob(a),u=new Uint8Array(c.length);for(let m=0;m<c.length;m++)u[m]=c.charCodeAt(m);return u.buffer}),s={request:{certificateTypes:e.certificateTypes,certificateAuthorities:o||[]},interactive:t};i&&(s.clientCerts=i);let n=await new Promise((a,c)=>{chrome.platformKeys.selectClientCertificates(s,u=>{chrome.runtime.lastError?c(new Error(chrome.runtime.lastError.message)):a(u);});});return this.formatJson({count:n.length,certificates:n.map(a=>({certificate:btoa(String.fromCharCode(...new Uint8Array(a.certificate))),keyAlgorithm:a.keyAlgorithm}))})}catch(o){return this.formatError(o)}});}registerGetKeyPair(){this.server.registerTool("extension_tool_get_key_pair",{description:"Get the key pair for a certificate for usage with platformKeys.subtleCrypto",inputSchema:{certificate:z.string().describe("Base64-encoded DER certificate from selectClientCertificates"),parameters:z.object({name:z.string().describe("Algorithm name (RSASSA-PKCS1-v1_5 or ECDSA)"),hash:z.object({name:z.string().describe("Hash algorithm name (none, SHA-1, SHA-256, SHA-384, SHA-512)")}).optional().describe("Hash parameters for RSASSA-PKCS1-v1_5")}).describe("Algorithm parameters")}},async({certificate:e,parameters:t})=>{try{let r=atob(e),o=new Uint8Array(r.length);for(let n=0;n<r.length;n++)o[n]=r.charCodeAt(n);let i=o.buffer,s=await new Promise((n,a)=>{chrome.platformKeys.getKeyPair(i,t,(c,u)=>{chrome.runtime.lastError?a(new Error(chrome.runtime.lastError.message)):n({publicKey:c,privateKey:u});});});return this.formatSuccess("Key pair retrieved successfully",{hasPublicKey:!!s.publicKey,hasPrivateKey:!!s.privateKey,algorithm:s.publicKey.algorithm})}catch(r){return this.formatError(r)}});}registerGetKeyPairBySpki(){this.server.registerTool("extension_tool_get_key_pair_by_spki",{description:"Get the key pair identified by a SubjectPublicKeyInfo for usage with platformKeys.subtleCrypto",inputSchema:{publicKeySpkiDer:z.string().describe("Base64-encoded DER X.509 SubjectPublicKeyInfo"),parameters:z.object({name:z.string().describe("Algorithm name (ECDSA or RSASSA-PKCS1-v1_5)"),hash:z.object({name:z.string().describe("Hash algorithm name (none, SHA-1, SHA-256, SHA-384, SHA-512)")}).optional().describe("Hash parameters for RSASSA-PKCS1-v1_5")}).describe("Algorithm parameters")}},async({publicKeySpkiDer:e,parameters:t})=>{try{let r=atob(e),o=new Uint8Array(r.length);for(let n=0;n<r.length;n++)o[n]=r.charCodeAt(n);let i=o.buffer,s=await new Promise((n,a)=>{chrome.platformKeys.getKeyPairBySpki(i,t,(c,u)=>{chrome.runtime.lastError?a(new Error(chrome.runtime.lastError.message)):n({publicKey:c,privateKey:u});});});return this.formatSuccess("Key pair retrieved successfully by SPKI",{hasPublicKey:!!s.publicKey,hasPrivateKey:!!s.privateKey,algorithm:s.publicKey.algorithm})}catch(r){return this.formatError(r)}});}registerVerifyTLSServerCertificate(){this.server.registerTool("extension_tool_verify_tls_server_certificate",{description:"Verify if a server certificate chain can be trusted for a hostname according to platform trust settings",inputSchema:{hostname:z.string().describe("Hostname of the server to verify the certificate for"),serverCertificateChain:z.array(z.string()).describe("Array of base64-encoded DER X.509 certificates, first entry must be server certificate")}},async({hostname:e,serverCertificateChain:t})=>{try{let r=t.map(s=>{let n=atob(s),a=new Uint8Array(n.length);for(let c=0;c<n.length;c++)a[c]=n.charCodeAt(c);return a.buffer}),o={hostname:e,serverCertificateChain:r},i=await new Promise((s,n)=>{chrome.platformKeys.verifyTLSServerCertificate(o,a=>{chrome.runtime.lastError?n(new Error(chrome.runtime.lastError.message)):s(a);});});return this.formatJson({hostname:e,trusted:i.trusted,debugErrors:i.debug_errors||[],certificateCount:t.length})}catch(r){return this.formatError(r)}});}registerGetSubtleCrypto(){this.server.registerTool("extension_tool_get_subtle_crypto",{description:"Get information about the SubtleCrypto implementation for platform keys",inputSchema:{}},async()=>{try{return chrome.platformKeys.subtleCrypto()?this.formatSuccess("SubtleCrypto implementation is available",{available:!0,methods:["encrypt","decrypt","sign","verify","digest","generateKey","deriveKey","deriveBits","importKey","exportKey","wrapKey","unwrapKey"]}):this.formatError("SubtleCrypto implementation is not available")}catch(e){return this.formatError(e)}});}};var vt=class extends d{apiName="Power";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.power?typeof chrome.power.requestKeepAwake!="function"?{available:!1,message:"chrome.power.requestKeepAwake is not available",details:"The power API appears to be partially available. Check manifest permissions."}:(chrome.power.requestKeepAwake("system"),chrome.power.releaseKeepAwake(),{available:!0,message:"Power API is fully available"}):{available:!1,message:"chrome.power API is not defined",details:'This extension needs the "power" permission in its manifest.json'}}catch(e){return {available:false,message:"Failed to access chrome.power API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("requestKeepAwake")&&this.registerRequestKeepAwake(),this.shouldRegisterTool("releaseKeepAwake")&&this.registerReleaseKeepAwake(),this.shouldRegisterTool("reportActivity")&&this.registerReportActivity();}registerRequestKeepAwake(){this.server.registerTool("extension_tool_request_keep_awake",{description:"Request that power management be temporarily disabled to keep the system or display awake",inputSchema:{level:z.enum(["system","display"]).describe('Level of power management to disable. "system" prevents system sleep but allows screen dimming. "display" prevents both system sleep and screen dimming/turning off')}},async({level:e})=>{try{return chrome.power.requestKeepAwake(e),this.formatSuccess("Power management request activated",{level:e,description:e==="system"?"System will stay awake but screen may dim or turn off":"Both system and display will stay awake"})}catch(t){return this.formatError(t)}});}registerReleaseKeepAwake(){this.server.registerTool("extension_tool_release_keep_awake",{description:"Release a previously made power management request, allowing normal power management to resume",inputSchema:{}},async()=>{try{return chrome.power.releaseKeepAwake(),this.formatSuccess("Power management request released",{description:"Normal power management behavior has been restored"})}catch(e){return this.formatError(e)}});}registerReportActivity(){this.server.registerTool("extension_tool_report_activity",{description:"Report user activity to wake the screen from dimmed/off state or exit screensaver (ChromeOS only)",inputSchema:{}},async()=>{try{return typeof chrome.power.reportActivity!="function"?this.formatError("reportActivity is not available. This method requires Chrome 113+ on ChromeOS"):(await new Promise((e,t)=>{chrome.power.reportActivity(()=>{chrome.runtime.lastError?t(new Error(chrome.runtime.lastError.message)):e();});}),this.formatSuccess("User activity reported",{description:"Screen should wake from dimmed/off state and exit screensaver if active"}))}catch(e){return this.formatError(e)}});}};var yt=class extends d{apiName="Printing";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.printing?typeof chrome.printing.getPrinters!="function"?{available:!1,message:"chrome.printing.getPrinters is not available",details:"The printing API appears to be partially available. Check manifest permissions and ensure this is running on ChromeOS."}:(chrome.printing.getPrinters(e=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"Printing API is fully available"}):{available:!1,message:"chrome.printing API is not defined",details:'This extension needs the "printing" permission in its manifest.json and only works on ChromeOS'}}catch(e){return {available:false,message:"Failed to access chrome.printing API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("getPrinters")&&this.registerGetPrinters(),this.shouldRegisterTool("getPrinterInfo")&&this.registerGetPrinterInfo(),this.shouldRegisterTool("submitJob")&&this.registerSubmitJob(),this.shouldRegisterTool("cancelJob")&&this.registerCancelJob(),this.shouldRegisterTool("getJobStatus")&&this.registerGetJobStatus();}registerGetPrinters(){this.server.registerTool("extension_tool_get_printers",{description:"Get the list of available printers on the device. This includes manually added, enterprise and discovered printers.",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.printing.getPrinters(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({count:e.length,printers:e.map(t=>({id:t.id,name:t.name,description:t.description,isDefault:t.isDefault,source:t.source,uri:t.uri,recentlyUsedRank:t.recentlyUsedRank}))})}catch(e){return this.formatError(e)}});}registerGetPrinterInfo(){this.server.registerTool("extension_tool_get_printer_info",{description:"Get the status and capabilities of a specific printer in CDD format",inputSchema:{printerId:z.string().describe("The ID of the printer to get information for")}},async({printerId:e})=>{try{let t=await new Promise((r,o)=>{chrome.printing.getPrinterInfo(e,i=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r(i);});});return this.formatJson({printerId:e,status:t.status,capabilities:t.capabilities})}catch(t){return this.formatError(t)}});}registerSubmitJob(){this.server.registerTool("extension_tool_submit_job",{description:'Submit a print job to a printer. Supported content types are "application/pdf" and "image/png". User confirmation may be required unless extension is allowlisted.',inputSchema:{printerId:z.string().describe("The ID of the printer to use"),title:z.string().describe("The title of the print job"),contentType:z.enum(["application/pdf","image/png"]).describe("The content type of the document to print"),documentData:z.string().describe("Base64 encoded document data to print"),ticket:z.object({version:z.string().optional().describe('Ticket version (e.g., "1.0")'),print:z.object({color:z.object({type:z.string().optional().describe('Color type (e.g., "STANDARD_MONOCHROME", "STANDARD_COLOR")')}).optional(),duplex:z.object({type:z.string().optional().describe('Duplex type (e.g., "NO_DUPLEX", "LONG_EDGE", "SHORT_EDGE")')}).optional(),page_orientation:z.object({type:z.string().optional().describe('Page orientation (e.g., "PORTRAIT", "LANDSCAPE")')}).optional(),copies:z.object({copies:z.number().optional().describe("Number of copies to print")}).optional(),dpi:z.object({horizontal_dpi:z.number().optional().describe("Horizontal DPI"),vertical_dpi:z.number().optional().describe("Vertical DPI")}).optional(),media_size:z.object({width_microns:z.number().optional().describe("Paper width in microns"),height_microns:z.number().optional().describe("Paper height in microns")}).optional(),collate:z.object({collate:z.boolean().optional().describe("Whether to collate pages")}).optional(),vendor_ticket_item:z.array(z.object({id:z.string().describe("Vendor capability ID"),value:z.any().describe("Vendor capability value")})).optional().describe("Vendor-specific ticket items")}).optional()}).optional().describe("Print ticket specifying printer capabilities to use")}},async({printerId:e,title:t,contentType:r,documentData:o,ticket:i})=>{try{let s=atob(o),n=new Uint8Array(s.length);for(let m=0;m<s.length;m++)n[m]=s.charCodeAt(m);let a=new Blob([n],{type:r}),c={job:{printerId:e,title:t,ticket:i||{},contentType:r,document:a}},u=await new Promise((m,g)=>{chrome.printing.submitJob(c,w=>{chrome.runtime.lastError?g(new Error(chrome.runtime.lastError.message)):m(w);});});return this.formatJson({status:u.status,jobId:u.jobId,message:u.status==="OK"?"Print job submitted successfully":"Print job was rejected"})}catch(s){return this.formatError(s)}});}registerCancelJob(){this.server.registerTool("extension_tool_cancel_job",{description:"Cancel a previously submitted print job",inputSchema:{jobId:z.string().describe("The ID of the print job to cancel")}},async({jobId:e})=>{try{return await new Promise((t,r)=>{chrome.printing.cancelJob(e,()=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t();});}),this.formatSuccess("Print job cancelled successfully",{jobId:e})}catch(t){return this.formatError(t)}});}registerGetJobStatus(){this.server.registerTool("extension_tool_get_job_status",{description:"Get the status of a print job",inputSchema:{jobId:z.string().describe("The ID of the print job to get status for")}},async({jobId:e})=>{try{let t=await new Promise((r,o)=>{chrome.printing.getJobStatus(e,i=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r(i);});});return this.formatJson({jobId:e,status:t,statusDescription:this.getJobStatusDescription(t)})}catch(t){return this.formatError(t)}});}getJobStatusDescription(e){switch(e){case "PENDING":return "Print job is received on Chrome side but was not processed yet";case "IN_PROGRESS":return "Print job is sent for printing";case "FAILED":return "Print job was interrupted due to some error";case "CANCELED":return "Print job was canceled by the user or via API";case "PRINTED":return "Print job was printed without any errors";default:return "Unknown status"}}};var wt=class extends d{apiName="PrintingMetrics";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.printingMetrics?typeof chrome.printingMetrics.getPrintJobs!="function"?{available:!1,message:"chrome.printingMetrics.getPrintJobs is not available",details:"The printingMetrics API appears to be partially available. Check manifest permissions and ensure this is running on ChromeOS."}:(chrome.printingMetrics.getPrintJobs(e=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"PrintingMetrics API is fully available"}):{available:!1,message:"chrome.printingMetrics API is not defined",details:'This extension needs the "printingMetrics" permission in its manifest.json and only works on ChromeOS'}}catch(e){return {available:false,message:"Failed to access chrome.printingMetrics API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("getPrintJobs")&&this.registerGetPrintJobs();}registerGetPrintJobs(){this.server.registerTool("extension_tool_get_print_jobs",{description:"Get the list of finished print jobs with details about printers, settings, and status",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.printingMetrics.getPrintJobs(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({count:e.length,jobs:e.map(t=>({id:t.id,title:t.title,status:t.status,source:t.source,sourceId:t.sourceId,numberOfPages:t.numberOfPages,creationTime:t.creationTime,creationTimeFormatted:new Date(t.creationTime).toISOString(),completionTime:t.completionTime,completionTimeFormatted:new Date(t.completionTime).toISOString(),printer:{name:t.printer.name,source:t.printer.source,uri:t.printer.uri},printerStatus:t.printer_status,settings:{color:t.settings.color,copies:t.settings.copies,duplex:t.settings.duplex,mediaSize:{width:t.settings.mediaSize.width,height:t.settings.mediaSize.height,vendorId:t.settings.mediaSize.vendorId}}}))})}catch(e){return this.formatError(e)}});}};var St=class extends d{apiName="Proxy";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.proxy?!chrome.proxy.settings||typeof chrome.proxy.settings.get!="function"?{available:!1,message:"chrome.proxy.settings.get is not available",details:"The proxy API appears to be partially available. Check manifest permissions."}:(chrome.proxy.settings.get({incognito:!1},e=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"Proxy API is fully available"}):{available:!1,message:"chrome.proxy API is not defined",details:'This extension needs the "proxy" permission in its manifest.json'}}catch(e){return {available:false,message:"Failed to access chrome.proxy API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("getProxySettings")&&this.registerGetProxySettings(),this.shouldRegisterTool("setProxySettings")&&this.registerSetProxySettings(),this.shouldRegisterTool("clearProxySettings")&&this.registerClearProxySettings();}registerGetProxySettings(){this.server.registerTool("extension_tool_get_proxy_settings",{description:"Get the current proxy configuration settings",inputSchema:{incognito:z.boolean().optional().default(false).describe("Whether to get proxy settings for incognito mode")}},async({incognito:e})=>{try{let t=await new Promise((r,o)=>{chrome.proxy.settings.get({incognito:e},i=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r(i);});});return this.formatJson({levelOfControl:t.levelOfControl,value:t.value,incognitoSpecific:t.incognitoSpecific})}catch(t){return this.formatError(t)}});}registerSetProxySettings(){this.server.registerTool("extension_tool_set_proxy_settings",{description:"Set proxy configuration settings",inputSchema:{mode:z.enum(["direct","auto_detect","pac_script","fixed_servers","system"]).describe("Proxy mode to use"),scope:z.enum(["regular","regular_only","incognito_persistent","incognito_session_only"]).optional().default("regular").describe("Scope of the setting"),pacScriptUrl:z.string().optional().describe("URL of the PAC file (for pac_script mode)"),pacScriptData:z.string().optional().describe("PAC script content (for pac_script mode)"),pacScriptMandatory:z.boolean().optional().describe("Whether PAC script is mandatory"),singleProxyHost:z.string().optional().describe("Host for single proxy (for fixed_servers mode)"),singleProxyPort:z.number().optional().describe("Port for single proxy (for fixed_servers mode)"),singleProxyScheme:z.enum(["http","https","quic","socks4","socks5"]).optional().describe("Scheme for single proxy (for fixed_servers mode)"),httpProxyHost:z.string().optional().describe("Host for HTTP proxy (for fixed_servers mode)"),httpProxyPort:z.number().optional().describe("Port for HTTP proxy (for fixed_servers mode)"),httpProxyScheme:z.enum(["http","https","quic","socks4","socks5"]).optional().describe("Scheme for HTTP proxy (for fixed_servers mode)"),httpsProxyHost:z.string().optional().describe("Host for HTTPS proxy (for fixed_servers mode)"),httpsProxyPort:z.number().optional().describe("Port for HTTPS proxy (for fixed_servers mode)"),httpsProxyScheme:z.enum(["http","https","quic","socks4","socks5"]).optional().describe("Scheme for HTTPS proxy (for fixed_servers mode)"),ftpProxyHost:z.string().optional().describe("Host for FTP proxy (for fixed_servers mode)"),ftpProxyPort:z.number().optional().describe("Port for FTP proxy (for fixed_servers mode)"),ftpProxyScheme:z.enum(["http","https","quic","socks4","socks5"]).optional().describe("Scheme for FTP proxy (for fixed_servers mode)"),fallbackProxyHost:z.string().optional().describe("Host for fallback proxy (for fixed_servers mode)"),fallbackProxyPort:z.number().optional().describe("Port for fallback proxy (for fixed_servers mode)"),fallbackProxyScheme:z.enum(["http","https","quic","socks4","socks5"]).optional().describe("Scheme for fallback proxy (for fixed_servers mode)"),bypassList:z.array(z.string()).optional().describe("List of servers to bypass proxy (for fixed_servers mode)")}},async({mode:e,scope:t,pacScriptUrl:r,pacScriptData:o,pacScriptMandatory:i,singleProxyHost:s,singleProxyPort:n,singleProxyScheme:a,httpProxyHost:c,httpProxyPort:u,httpProxyScheme:m,httpsProxyHost:g,httpsProxyPort:w,httpsProxyScheme:k,ftpProxyHost:R,ftpProxyPort:D,ftpProxyScheme:ce,fallbackProxyHost:V,fallbackProxyPort:L,fallbackProxyScheme:se,bypassList:Se})=>{try{let fe={mode:e};if(e==="pac_script"){let J={};if(r!==void 0&&(J.url=r),o!==void 0&&(J.data=o),i!==void 0&&(J.mandatory=i),Object.keys(J).length===0)return this.formatError("PAC script URL or data must be provided for pac_script mode");fe.pacScript=J;}else if(e==="fixed_servers"){let J={};if(s){let N={host:s};n!==void 0&&(N.port=n),a!==void 0&&(N.scheme=a),J.singleProxy=N;}else {if(c){let N={host:c};u!==void 0&&(N.port=u),m!==void 0&&(N.scheme=m),J.proxyForHttp=N;}if(g){let N={host:g};w!==void 0&&(N.port=w),k!==void 0&&(N.scheme=k),J.proxyForHttps=N;}if(R){let N={host:R};D!==void 0&&(N.port=D),ce!==void 0&&(N.scheme=ce),J.proxyForFtp=N;}if(V){let N={host:V};L!==void 0&&(N.port=L),se!==void 0&&(N.scheme=se),J.fallbackProxy=N;}}if(Se!==void 0&&(J.bypassList=Se),Object.keys(J).length===0)return this.formatError("At least one proxy server must be specified for fixed_servers mode");fe.rules=J;}return await new Promise((J,N)=>{chrome.proxy.settings.set({value:fe,scope:t},()=>{chrome.runtime.lastError?N(new Error(chrome.runtime.lastError.message)):J();});}),this.formatSuccess("Proxy settings updated successfully",{mode:e,scope:t,config:fe})}catch(fe){return this.formatError(fe)}});}registerClearProxySettings(){this.server.registerTool("extension_tool_clear_proxy_settings",{description:"Clear proxy settings and revert to default",inputSchema:{scope:z.enum(["regular","regular_only","incognito_persistent","incognito_session_only"]).optional().default("regular").describe("Scope of the setting to clear")}},async({scope:e})=>{try{return await new Promise((t,r)=>{chrome.proxy.settings.clear({scope:e},()=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t();});}),this.formatSuccess("Proxy settings cleared successfully",{scope:e})}catch(t){return this.formatError(t)}});}};var Tt=class extends d{apiName="ReadingList";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.readingList?typeof chrome.readingList.query!="function"?{available:!1,message:"chrome.readingList.query is not available",details:"The readingList API appears to be partially available. Check manifest permissions."}:(chrome.readingList.query({},e=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"ReadingList API is fully available"}):{available:!1,message:"chrome.readingList API is not defined",details:'This extension needs the "readingList" permission in its manifest.json'}}catch(e){return {available:false,message:"Failed to access chrome.readingList API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("addEntry")&&this.registerAddEntry(),this.shouldRegisterTool("query")&&this.registerQuery(),this.shouldRegisterTool("removeEntry")&&this.registerRemoveEntry(),this.shouldRegisterTool("updateEntry")&&this.registerUpdateEntry();}registerAddEntry(){this.server.registerTool("extension_tool_add_reading_list_entry",{description:"Add an entry to the reading list if it does not exist",inputSchema:{title:z.string().describe("The title of the entry"),url:z.string().url().describe("The URL of the entry"),hasBeenRead:z.boolean().describe("Whether the entry has been read")}},async({title:e,url:t,hasBeenRead:r})=>{try{return await new Promise((o,i)=>{chrome.readingList.addEntry({title:e,url:t,hasBeenRead:r},()=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o();});}),this.formatSuccess("Reading list entry added successfully",{title:e,url:t,hasBeenRead:r})}catch(o){return this.formatError(o)}});}registerQuery(){this.server.registerTool("extension_tool_query_reading_list",{description:"Retrieve all entries that match the query criteria. Properties that are not provided will not be matched",inputSchema:{hasBeenRead:z.boolean().optional().describe("Indicates whether to search for read (true) or unread (false) items"),title:z.string().optional().describe("A title to search for"),url:z.string().optional().describe("A URL to search for")}},async({hasBeenRead:e,title:t,url:r})=>{try{let o={};e!==void 0&&(o.hasBeenRead=e),t!==void 0&&(o.title=t),r!==void 0&&(o.url=r);let i=await new Promise((s,n)=>{chrome.readingList.query(o,a=>{chrome.runtime.lastError?n(new Error(chrome.runtime.lastError.message)):s(a);});});return this.formatJson({count:i.length,entries:i.map(s=>({title:s.title,url:s.url,hasBeenRead:s.hasBeenRead,creationTime:s.creationTime,creationTimeFormatted:new Date(s.creationTime).toISOString(),lastUpdateTime:s.lastUpdateTime,lastUpdateTimeFormatted:new Date(s.lastUpdateTime).toISOString()}))})}catch(o){return this.formatError(o)}});}registerRemoveEntry(){this.server.registerTool("extension_tool_remove_reading_list_entry",{description:"Remove an entry from the reading list if it exists",inputSchema:{url:z.string().url().describe("The URL to remove")}},async({url:e})=>{try{return await new Promise((t,r)=>{chrome.readingList.removeEntry({url:e},()=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t();});}),this.formatSuccess("Reading list entry removed successfully",{url:e})}catch(t){return this.formatError(t)}});}registerUpdateEntry(){this.server.registerTool("extension_tool_update_reading_list_entry",{description:"Update a reading list entry if it exists",inputSchema:{url:z.string().url().describe("The URL that will be updated"),title:z.string().optional().describe("The new title. The existing title remains if a value is not provided"),hasBeenRead:z.boolean().optional().describe("The updated read status. The existing status remains if a value is not provided")}},async({url:e,title:t,hasBeenRead:r})=>{try{let o={url:e};return t!==void 0&&(o.title=t),r!==void 0&&(o.hasBeenRead=r),await new Promise((i,s)=>{chrome.readingList.updateEntry(o,()=>{chrome.runtime.lastError?s(new Error(chrome.runtime.lastError.message)):i();});}),this.formatSuccess("Reading list entry updated successfully",{url:e,title:t,hasBeenRead:r})}catch(o){return this.formatError(o)}});}};var Et=class extends d{apiName="Runtime";constructor(e,t={}){super(e,t);}checkAvailability(){try{if(!chrome.runtime)return {available:!1,message:"chrome.runtime API is not defined",details:"The runtime API should be available in all extension contexts"};if(typeof chrome.runtime.getManifest!="function")return {available:!1,message:"chrome.runtime.getManifest is not available",details:"The runtime API appears to be partially available."};if(!chrome.runtime.getManifest())throw new Error("Failed to get manifest");return {available:!0,message:"Runtime API is fully available"}}catch(e){return {available:false,message:"Failed to access chrome.runtime API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("connect")&&this.registerConnect(),this.shouldRegisterTool("connectNative")&&this.registerConnectNative(),this.shouldRegisterTool("getContexts")&&this.registerGetContexts(),this.shouldRegisterTool("getManifest")&&this.registerGetManifest(),this.shouldRegisterTool("getPackageDirectoryEntry")&&this.registerGetPackageDirectoryEntry(),this.shouldRegisterTool("getPlatformInfo")&&this.registerGetPlatformInfo(),this.shouldRegisterTool("getURL")&&this.registerGetURL(),this.shouldRegisterTool("openOptionsPage")&&this.registerOpenOptionsPage(),this.shouldRegisterTool("reload")&&this.registerReload(),this.shouldRegisterTool("requestUpdateCheck")&&this.registerRequestUpdateCheck(),this.shouldRegisterTool("restart")&&this.registerRestart(),this.shouldRegisterTool("restartAfterDelay")&&this.registerRestartAfterDelay(),this.shouldRegisterTool("sendMessage")&&this.registerSendMessage(),this.shouldRegisterTool("sendNativeMessage")&&this.registerSendNativeMessage(),this.shouldRegisterTool("setUninstallURL")&&this.registerSetUninstallURL();}registerConnect(){this.server.registerTool("extension_tool_runtime_connect",{description:"Connect to listeners within an extension or other extensions/apps",inputSchema:{extensionId:z.string().optional().describe("The ID of the extension to connect to. If omitted, connects to your own extension"),name:z.string().optional().describe("Will be passed into onConnect for processes listening for the connection event"),includeTlsChannelId:z.boolean().optional().describe("Whether the TLS channel ID will be passed into onConnectExternal")}},async({extensionId:e,name:t,includeTlsChannelId:r})=>{try{let o={};t!==void 0&&(o.name=t),r!==void 0&&(o.includeTlsChannelId=r);let i;return e?i=chrome.runtime.connect(e,o):i=chrome.runtime.connect(o),this.formatSuccess("Connection established successfully",{portName:i.name,extensionId:e||"own extension",sender:i.sender?{id:i.sender.id,url:i.sender.url,tab:i.sender.tab?{id:i.sender.tab.id,url:i.sender.tab.url}:void 0}:void 0})}catch(o){return this.formatError(o)}});}registerConnectNative(){this.server.registerTool("extension_tool_runtime_connect_native",{description:'Connect to a native application in the host machine. Requires "nativeMessaging" permission',inputSchema:{application:z.string().describe("The name of the registered application to connect to")}},async({application:e})=>{try{let t=chrome.runtime.connectNative(e);return this.formatSuccess("Native connection established successfully",{portName:t.name,application:e})}catch(t){return this.formatError(t)}});}registerGetContexts(){this.server.registerTool("extension_tool_runtime_get_contexts",{description:"Fetch information about active contexts associated with this extension",inputSchema:{contextTypes:z.array(z.enum(["TAB","POPUP","BACKGROUND","OFFSCREEN_DOCUMENT","SIDE_PANEL","DEVELOPER_TOOLS"])).optional().describe("Filter by context types"),contextIds:z.array(z.string()).optional().describe("Filter by specific context IDs"),tabIds:z.array(z.number()).optional().describe("Filter by tab IDs"),windowIds:z.array(z.number()).optional().describe("Filter by window IDs"),frameIds:z.array(z.number()).optional().describe("Filter by frame IDs"),documentIds:z.array(z.string()).optional().describe("Filter by document IDs"),documentUrls:z.array(z.string()).optional().describe("Filter by document URLs"),documentOrigins:z.array(z.string()).optional().describe("Filter by document origins"),incognito:z.boolean().optional().describe("Filter by incognito status")}},async({contextTypes:e,contextIds:t,tabIds:r,windowIds:o,frameIds:i,documentIds:s,documentUrls:n,documentOrigins:a,incognito:c})=>{try{let u={};e!==void 0&&(u.contextTypes=e),t!==void 0&&(u.contextIds=t),r!==void 0&&(u.tabIds=r),o!==void 0&&(u.windowIds=o),i!==void 0&&(u.frameIds=i),s!==void 0&&(u.documentIds=s),n!==void 0&&(u.documentUrls=n),a!==void 0&&(u.documentOrigins=a),c!==void 0&&(u.incognito=c);let m=await new Promise((g,w)=>{chrome.runtime.getContexts(u,k=>{chrome.runtime.lastError?w(new Error(chrome.runtime.lastError.message)):g(k);});});return this.formatJson({count:m.length,contexts:m.map(g=>({contextId:g.contextId,contextType:g.contextType,documentId:g.documentId,documentOrigin:g.documentOrigin,documentUrl:g.documentUrl,frameId:g.frameId,incognito:g.incognito,tabId:g.tabId,windowId:g.windowId}))})}catch(u){return this.formatError(u)}});}registerGetManifest(){this.server.registerTool("extension_tool_runtime_get_manifest",{description:"Get details about the app or extension from the manifest",inputSchema:{}},async()=>{try{let e=chrome.runtime.getManifest();return this.formatJson({manifest:e,name:e.name,version:e.version,manifestVersion:e.manifest_version,description:e.description,permissions:e.permissions||[],hostPermissions:e.host_permissions||[]})}catch(e){return this.formatError(e)}});}registerGetPackageDirectoryEntry(){this.server.registerTool("extension_tool_runtime_get_package_directory_entry",{description:"Get a DirectoryEntry for the package directory",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.runtime.getPackageDirectoryEntry(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({name:e.name,fullPath:e.fullPath,isDirectory:e.isDirectory,isFile:e.isFile})}catch(e){return this.formatError(e)}});}registerGetPlatformInfo(){this.server.registerTool("extension_tool_runtime_get_platform_info",{description:"Get information about the current platform",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.runtime.getPlatformInfo(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({os:e.os,arch:e.arch,nacl_arch:e.nacl_arch})}catch(e){return this.formatError(e)}});}registerGetURL(){this.server.registerTool("extension_tool_runtime_get_url",{description:"Convert a relative path within an app/extension install directory to a fully-qualified URL",inputSchema:{path:z.string().describe("A path to a resource within an app/extension expressed relative to its install directory")}},async({path:e})=>{try{let t=chrome.runtime.getURL(e);return this.formatJson({relativePath:e,fullUrl:t})}catch(t){return this.formatError(t)}});}registerOpenOptionsPage(){this.server.registerTool("extension_tool_runtime_open_options_page",{description:"Open the extension's options page",inputSchema:{}},async()=>{try{return await new Promise((e,t)=>{chrome.runtime.openOptionsPage(()=>{chrome.runtime.lastError?t(new Error(chrome.runtime.lastError.message)):e();});}),this.formatSuccess("Options page opened successfully")}catch(e){return this.formatError(e)}});}registerReload(){this.server.registerTool("extension_tool_runtime_reload",{description:"Reload the app or extension",inputSchema:{}},async()=>{try{return chrome.runtime.reload(),this.formatSuccess("Extension reload initiated")}catch(e){return this.formatError(e)}});}registerRequestUpdateCheck(){this.server.registerTool("extension_tool_runtime_request_update_check",{description:"Request an immediate update check for this app/extension",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.runtime.requestUpdateCheck(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({status:e.status,version:e.version})}catch(e){return this.formatError(e)}});}registerRestart(){this.server.registerTool("extension_tool_runtime_restart",{description:"Restart the ChromeOS device when the app runs in kiosk mode",inputSchema:{}},async()=>{try{return chrome.runtime.restart(),this.formatSuccess("Device restart initiated (kiosk mode only)")}catch(e){return this.formatError(e)}});}registerRestartAfterDelay(){this.server.registerTool("extension_tool_runtime_restart_after_delay",{description:"Restart the ChromeOS device after a delay when the app runs in kiosk mode",inputSchema:{seconds:z.number().describe("Time to wait in seconds before rebooting the device, or -1 to cancel a scheduled reboot")}},async({seconds:e})=>{try{return await new Promise((t,r)=>{chrome.runtime.restartAfterDelay(e,()=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t();});}),e===-1?this.formatSuccess("Scheduled restart cancelled"):this.formatSuccess("Device restart scheduled",{delaySeconds:e})}catch(t){return this.formatError(t)}});}registerSendMessage(){this.server.registerTool("extension_tool_runtime_send_message",{description:"Send a single message to event listeners within your extension or a different extension/app",inputSchema:{message:z.any().describe("The message to send. This message should be a JSON-ifiable object"),extensionId:z.string().optional().describe("The ID of the extension to send the message to. If omitted, sends to your own extension"),includeTlsChannelId:z.boolean().optional().describe("Whether the TLS channel ID will be passed into onMessageExternal")}},async({message:e,extensionId:t,includeTlsChannelId:r})=>{try{let o={};r!==void 0&&(o.includeTlsChannelId=r);let i=await new Promise((s,n)=>{t?chrome.runtime.sendMessage(t,e,o,a=>{chrome.runtime.lastError?n(new Error(chrome.runtime.lastError.message)):s(a);}):chrome.runtime.sendMessage(e,o,a=>{chrome.runtime.lastError?n(new Error(chrome.runtime.lastError.message)):s(a);});});return this.formatJson({messageSent:e,response:i,extensionId:t||"own extension"})}catch(o){return this.formatError(o)}});}registerSendNativeMessage(){this.server.registerTool("extension_tool_runtime_send_native_message",{description:'Send a single message to a native application. Requires "nativeMessaging" permission',inputSchema:{application:z.string().describe("The name of the native messaging host"),message:z.any().describe("The message that will be passed to the native messaging host")}},async({application:e,message:t})=>{try{let r=await new Promise((o,i)=>{chrome.runtime.sendNativeMessage(e,t,s=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o(s);});});return this.formatJson({application:e,messageSent:t,response:r})}catch(r){return this.formatError(r)}});}registerSetUninstallURL(){this.server.registerTool("extension_tool_runtime_set_uninstall_url",{description:"Set the URL to be visited upon uninstallation. Maximum 1023 characters",inputSchema:{url:z.string().max(1023).describe("URL to be opened after the extension is uninstalled. Must have http: or https: scheme. Set empty string to not open a new tab")}},async({url:e})=>{try{return await new Promise((t,r)=>{chrome.runtime.setUninstallURL(e,()=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t();});}),this.formatSuccess("Uninstall URL set successfully",{url:e})}catch(t){return this.formatError(t)}});}};var _t=class extends d{apiName="Scripting";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.scripting?typeof chrome.scripting.executeScript!="function"?{available:!1,message:"chrome.scripting.executeScript is not available",details:'The scripting API appears to be partially available. Ensure you have Chrome 88+ and the "scripting" permission.'}:{available:!0,message:"Scripting API is available"}:{available:!1,message:"chrome.scripting API is not defined",details:'This extension needs the "scripting" permission in its manifest.json. This API is available in Chrome 88+.'}}catch(e){return {available:false,message:"Failed to access chrome.scripting API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("executeScript")&&this.registerExecuteScript(),this.shouldRegisterTool("executeUserScript")&&this.checkAndRegisterUserScripts(),this.shouldRegisterTool("insertCSS")&&this.registerInsertCSS(),this.shouldRegisterTool("removeCSS")&&this.registerRemoveCSS();}checkAndRegisterUserScripts(){if(!chrome.userScripts){console.warn("UserScripts API not available - Chrome 120+ required");return}try{chrome.userScripts.getScripts(),this.getChromeVersion()>=135?(console.log("UserScripts execute() method available (Chrome 135+)"),this.registerUserScriptExecute()):(console.log("UserScripts API available (legacy mode)"),this.registerUserScriptLegacy());}catch{console.warn('UserScripts API not enabled. Users need to enable developer mode and "User Scripts" toggle in chrome://extensions');}}getChromeVersion(){let e=navigator.userAgent.match(/(Chrome|Chromium)\/([0-9]+)/);return e?Number(e[2]):0}registerExecuteScript(){this.server.registerTool("extension_tool_execute_script",{description:"Execute JavaScript code in a specific tab using chrome.scripting API. Limited by CSP restrictions. If no tabId is specified, operates on the currently active tab",inputSchema:{tabId:z.number().optional().describe("Tab ID to execute script in (defaults to active tab)"),code:z.string().describe("JavaScript code to execute"),allFrames:z.boolean().optional().describe("Execute in all frames (default: false)"),world:z.enum(["MAIN","ISOLATED"]).optional().default("MAIN").describe("Execution world - MAIN runs in page context, ISOLATED runs in extension context")}},async({tabId:e,code:t,allFrames:r=false,world:o="MAIN"})=>{try{if(e===void 0){let[n]=await chrome.tabs.query({active:!0,currentWindow:!0});if(!n||!n.id)return this.formatError(new Error("No active tab found"));e=n.id;}let i=n=>{try{let a=document.createElement("script");a.textContent=`
1
+ import {z}from'zod';import ir,{zodToJsonSchema}from'zod-to-json-schema';var m=class{constructor(e,t={}){this.server=e;this.options=t;}shouldRegisterTool(e){return this.options[e]!==false}formatError(e){return {content:[{type:"text",text:`Error: ${e instanceof Error?e.message:String(e)}`}],isError:true}}formatSuccess(e,t){return {content:[{type:"text",text:t?`${e}
2
+ ${JSON.stringify(t,null,2)}`:e}]}}formatJson(e){return {content:[{type:"text",text:JSON.stringify(e,null,2)}]}}register(){let e=this.checkAvailability();if(!e.available){console.warn(`\u2717 ${this.apiName} API not available: ${e.message}`),e.details&&console.warn(` Details: ${e.details}`);return}console.log(`\u2713 ${this.apiName} API available`),this.registerTools();}};var xe=class extends m{apiName="Alarms";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.alarms?typeof chrome.alarms.getAll!="function"?{available:!1,message:"chrome.alarms.getAll is not available",details:"The alarms API appears to be partially available. Check manifest permissions."}:(chrome.alarms.getAll(e=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"Alarms API is fully available"}):{available:!1,message:"chrome.alarms API is not defined",details:'This extension needs the "alarms" permission in its manifest.json'}}catch(e){return {available:false,message:"Failed to access chrome.alarms API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("createAlarm")&&this.registerCreateAlarm(),this.shouldRegisterTool("getAlarm")&&this.registerGetAlarm(),this.shouldRegisterTool("getAllAlarms")&&this.registerGetAllAlarms(),this.shouldRegisterTool("clearAlarm")&&this.registerClearAlarm(),this.shouldRegisterTool("clearAllAlarms")&&this.registerClearAllAlarms();}registerCreateAlarm(){this.server.registerTool("extension_tool_create_alarm",{description:"Create an alarm that fires at a specific time or periodically",inputSchema:{name:z.string().optional().describe("Optional name to identify this alarm"),delayInMinutes:z.number().min(.5).optional().describe("Time in minutes from now when the alarm should first fire. Minimum is 0.5 minutes (30 seconds)"),periodInMinutes:z.number().min(.5).optional().describe("If set, the alarm will repeat every periodInMinutes minutes after the initial event. Minimum is 0.5 minutes (30 seconds)"),when:z.number().optional().describe("Time at which the alarm should fire, in milliseconds past the epoch (e.g. Date.now() + n)")}},async({name:e,delayInMinutes:t,periodInMinutes:r,when:o})=>{try{if(t===void 0&&o===void 0)return this.formatError("Either delayInMinutes or when must be specified to create an alarm");let i={};t!==void 0&&(i.delayInMinutes=t),r!==void 0&&(i.periodInMinutes=r),o!==void 0&&(i.when=o),await new Promise((n,a)=>{e?chrome.alarms.create(e,i,()=>{chrome.runtime.lastError?a(new Error(chrome.runtime.lastError.message)):n();}):chrome.alarms.create(i,()=>{chrome.runtime.lastError?a(new Error(chrome.runtime.lastError.message)):n();});});let s=await new Promise((n,a)=>{chrome.alarms.get(e||"",c=>{chrome.runtime.lastError?a(new Error(chrome.runtime.lastError.message)):n(c);});});return this.formatSuccess("Alarm created successfully",{name:s?.name||e||"unnamed",scheduledTime:s?.scheduledTime,periodInMinutes:s?.periodInMinutes})}catch(i){return this.formatError(i)}});}registerGetAlarm(){this.server.registerTool("extension_tool_get_alarm",{description:"Get details about a specific alarm",inputSchema:{name:z.string().optional().describe("Name of the alarm to retrieve. If not specified, gets the default unnamed alarm")}},async({name:e})=>{try{let t=await new Promise((r,o)=>{e?chrome.alarms.get(e,i=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r(i);}):chrome.alarms.get(i=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r(i);});});return t?this.formatJson({name:t.name,scheduledTime:t.scheduledTime,scheduledTimeFormatted:new Date(t.scheduledTime).toISOString(),periodInMinutes:t.periodInMinutes}):this.formatSuccess("No alarm found",{name:e||"unnamed"})}catch(t){return this.formatError(t)}});}registerGetAllAlarms(){this.server.registerTool("extension_tool_get_all_alarms",{description:"Get all active alarms",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.alarms.getAll(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({count:e.length,alarms:e.map(t=>({name:t.name,scheduledTime:t.scheduledTime,scheduledTimeFormatted:new Date(t.scheduledTime).toISOString(),periodInMinutes:t.periodInMinutes}))})}catch(e){return this.formatError(e)}});}registerClearAlarm(){this.server.registerTool("extension_tool_clear_alarm",{description:"Clear a specific alarm",inputSchema:{name:z.string().optional().describe("Name of the alarm to clear. If not specified, clears the default unnamed alarm")}},async({name:e})=>{try{return await new Promise((r,o)=>{e?chrome.alarms.clear(e,i=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r(i);}):chrome.alarms.clear(i=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r(i);});})?this.formatSuccess("Alarm cleared successfully",{name:e||"unnamed"}):this.formatSuccess("No alarm found to clear",{name:e||"unnamed"})}catch(t){return this.formatError(t)}});}registerClearAllAlarms(){this.server.registerTool("extension_tool_clear_all_alarms",{description:"Clear all alarms",inputSchema:{}},async()=>{try{let e=await new Promise((r,o)=>{chrome.alarms.getAll(i=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r(i);});});return await new Promise((r,o)=>{chrome.alarms.clearAll(i=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r(i);});})?this.formatSuccess("All alarms cleared successfully",{clearedCount:e.length,clearedAlarms:e.map(r=>r.name)}):this.formatSuccess("No alarms to clear")}catch(e){return this.formatError(e)}});}};var Ie=class extends m{apiName="Audio";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.audio?typeof chrome.audio.getDevices!="function"?{available:!1,message:"chrome.audio.getDevices is not available",details:"The audio API appears to be partially available. Check manifest permissions and ensure you are on ChromeOS."}:(chrome.audio.getDevices({},e=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"Audio API is fully available"}):{available:!1,message:"chrome.audio API is not defined",details:'This extension needs the "audio" permission in its manifest.json and only works on ChromeOS'}}catch(e){return {available:false,message:"Failed to access chrome.audio API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("getDevices")&&this.registerGetDevices(),this.shouldRegisterTool("getMute")&&this.registerGetMute(),this.shouldRegisterTool("setActiveDevices")&&this.registerSetActiveDevices(),this.shouldRegisterTool("setMute")&&this.registerSetMute(),this.shouldRegisterTool("setProperties")&&this.registerSetProperties();}registerGetDevices(){this.server.registerTool("extension_tool_get_audio_devices",{description:"Get a list of audio devices filtered based on criteria",inputSchema:{isActive:z.boolean().optional().describe("If set, only audio devices whose active state matches this value will be returned"),streamTypes:z.array(z.enum(["INPUT","OUTPUT"])).optional().describe("If set, only audio devices whose stream type is included in this list will be returned")}},async({isActive:e,streamTypes:t})=>{try{let r={};e!==void 0&&(r.isActive=e),t!==void 0&&(r.streamTypes=t);let o=await new Promise((i,s)=>{chrome.audio.getDevices(r,n=>{chrome.runtime.lastError?s(new Error(chrome.runtime.lastError.message)):i(n);});});return this.formatJson({count:o.length,devices:o.map(i=>({id:i.id,deviceName:i.deviceName,deviceType:i.deviceType,displayName:i.displayName,isActive:i.isActive,level:i.level,stableDeviceId:i.stableDeviceId,streamType:i.streamType}))})}catch(r){return this.formatError(r)}});}registerGetMute(){this.server.registerTool("extension_tool_get_audio_mute",{description:"Get the system-wide mute state for the specified stream type",inputSchema:{streamType:z.enum(["INPUT","OUTPUT"]).describe("Stream type for which mute state should be fetched")}},async({streamType:e})=>{try{let t=await new Promise((r,o)=>{chrome.audio.getMute(e,i=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r(i);});});return this.formatJson({streamType:e,isMuted:t})}catch(t){return this.formatError(t)}});}registerSetActiveDevices(){this.server.registerTool("extension_tool_set_active_audio_devices",{description:"Set lists of active input and/or output devices",inputSchema:{input:z.array(z.string()).optional().describe("List of input device IDs that should be active. Leave unset to not affect input devices"),output:z.array(z.string()).optional().describe("List of output device IDs that should be active. Leave unset to not affect output devices")}},async({input:e,output:t})=>{try{if(e===void 0&&t===void 0)return this.formatError("At least one of input or output device lists must be specified");let r={};return e!==void 0&&(r.input=e),t!==void 0&&(r.output=t),await new Promise((o,i)=>{chrome.audio.setActiveDevices(r,()=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o();});}),this.formatSuccess("Active audio devices set successfully",{inputDevices:e,outputDevices:t})}catch(r){return this.formatError(r)}});}registerSetMute(){this.server.registerTool("extension_tool_set_audio_mute",{description:"Set mute state for a stream type. The mute state will apply to all audio devices with the specified audio stream type",inputSchema:{streamType:z.enum(["INPUT","OUTPUT"]).describe("Stream type for which mute state should be set"),isMuted:z.boolean().describe("New mute value")}},async({streamType:e,isMuted:t})=>{try{return await new Promise((r,o)=>{chrome.audio.setMute(e,t,()=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r();});}),this.formatSuccess("Audio mute state set successfully",{streamType:e,isMuted:t})}catch(r){return this.formatError(r)}});}registerSetProperties(){this.server.registerTool("extension_tool_set_audio_device_properties",{description:"Set the properties for the input or output device",inputSchema:{id:z.string().describe("ID of the audio device to modify"),level:z.number().min(0).max(100).optional().describe("The audio device's desired sound level. For input devices, represents gain. For output devices, represents volume")}},async({id:e,level:t})=>{try{let r={};return t!==void 0&&(r.level=t),await new Promise((o,i)=>{chrome.audio.setProperties(e,r,()=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o();});}),this.formatSuccess("Audio device properties set successfully",{deviceId:e,level:t})}catch(r){return this.formatError(r)}});}};var rr=["create","get","getChildren","getRecent","getSubTree","getTree","move","remove","removeTree","search","update"],Re=z.enum(rr),Pe=class extends m{apiName="Bookmarks";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.bookmarks?typeof chrome.bookmarks.getTree!="function"?{available:!1,message:"chrome.bookmarks.getTree is not available",details:"The bookmarks API appears to be partially available. Check manifest permissions."}:(chrome.bookmarks.getTree(e=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"Bookmarks API is fully available"}):{available:!1,message:"chrome.bookmarks API is not defined",details:'This extension needs the "bookmarks" permission in its manifest.json'}}catch(e){return {available:false,message:"Failed to access chrome.bookmarks API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.server.registerTool("extension_tool_bookmark_operations",{description:"Perform bookmark operations. Choose an action and supply the corresponding parameters.",inputSchema:{action:Re,params:z.record(z.any()).optional().describe("Parameters for the chosen action")}},async({action:e,params:t={}})=>{try{if(!this.isActionEnabled(e))return this.formatError(`Action '${e}' is disabled by configuration`);switch(e){case "create":return await this.handleCreate(t);case "get":return await this.handleGet(t);case "getChildren":return await this.handleGetChildren(t);case "getRecent":return await this.handleGetRecent(t);case "getSubTree":return await this.handleGetSubTree(t);case "getTree":return await this.handleGetTree();case "move":return await this.handleMove(t);case "remove":return await this.handleRemove(t);case "removeTree":return await this.handleRemoveTree(t);case "search":return await this.handleSearch(t);case "update":return await this.handleUpdate(t);default:return this.formatError(`Unknown action: ${String(e)}`)}}catch(r){return this.formatError(r)}}),this.server.registerTool("extension_tool_bookmark_parameters_description",{description:"Get the parameters for extension_tool_bookmark_operations tool and the description for the associated action, this tool should be used first before extension_tool_bookmark_operations",inputSchema:{action:Re}},async({action:e})=>{try{if(!this.isActionEnabled(e))return this.formatError(`Action '${e}' is disabled by configuration`);let t=(o,i)=>zodToJsonSchema(o,{name:i,$refStrategy:"none"}),r={tool:"extension_tool_bookmark_operations",action:e,note:"Use the description to double check if the correct action is chosen. Use this JSON Schema for the params field when calling the tool. The top-level tool input is { action, params }."};switch(e){case "create":{let o=t(this.createSchema,"BookmarksCreateParams"),i={title:"My Site",url:"https://example.com",parentId:"1"},s={params:o,description:"Create a bookmark or folder under the specified parent. A folder must have a title and no url"};return this.formatJson({...r,...s,example:i})}case "get":{let o=t(this.getSchema,"BookmarksGetParams"),i={idOrIdList:"123"},s={params:o,description:"Retrieve the specified bookmark(s) by ID"};return this.formatJson({...r,...s,example:i})}case "getChildren":{let o=t(this.getChildrenSchema,"BookmarksGetChildrenParams"),i={id:"1"},s={params:o,description:"Retrieve the children of the specified bookmark folder"};return this.formatJson({...r,...s,example:i})}case "getRecent":{let o=t(this.getRecentSchema,"BookmarksGetRecentParams"),i={numberOfItems:10},s={params:o,description:"Retrieve the recently added bookmarks"};return this.formatJson({...r,...s,example:i})}case "getSubTree":{let o=t(this.getSubTreeSchema,"BookmarksGetSubTreeParams"),i={id:"1"},s={params:o,description:"Retrieve part of the bookmarks hierarchy, starting at the specified node"};return this.formatJson({...r,...s,example:i})}case "getTree":{let o={type:"object",properties:{},additionalProperties:!1},i={},s={params:o,description:"Retrieve the entire bookmarks hierarchy"};return this.formatJson({...r,...s,example:i})}case "move":{let o=t(this.moveSchema,"BookmarksMoveParams"),i={id:"123",parentId:"1",index:0},s={params:o,description:"Move the specified bookmark or folder to a new location"};return this.formatJson({...r,...s,example:i})}case "remove":{let o=t(this.removeSchema,"BookmarksRemoveParams"),i={id:"123"},s={params:o,description:"Remove the specified bookmark or empty folder"};return this.formatJson({...r,...s,example:i})}case "removeTree":{let o=t(this.removeTreeSchema,"BookmarksRemoveTreeParams"),i={id:"1"},s={params:o,description:"Recursively remove a bookmark folder and all its contents"};return this.formatJson({...r,...s,example:i})}case "search":{let o=t(this.searchSchema,"BookmarksSearchParams"),i={query:"recipes"},s={params:o,description:"Search for bookmarks matching the given query"};return this.formatJson({...r,...s,example:i})}case "update":{let o=t(this.updateSchema,"BookmarksUpdateParams"),i={id:"123",title:"New title"},s={params:o,description:"Update the properties of a bookmark or folder. Only title and url can be changed"};return this.formatJson({...r,...s,example:i})}default:return this.formatError(`Unknown action: ${String(e)}`)}}catch(t){return this.formatError(t)}});}createSchema=z.object({parentId:z.string().optional().describe("Parent folder ID. Defaults to the Other Bookmarks folder"),title:z.string().optional().describe("The title of the bookmark or folder"),url:z.string().optional().describe("The URL for the bookmark. Omit for folders"),index:z.number().optional().describe("The position within the parent folder")});getSchema=z.object({idOrIdList:z.union([z.string(),z.array(z.string())]).describe("A single bookmark ID or array of bookmark IDs")});getChildrenSchema=z.object({id:z.string().describe("The ID of the folder to get children from")});getRecentSchema=z.object({numberOfItems:z.number().min(1).describe("The maximum number of items to return")});getSubTreeSchema=z.object({id:z.string().describe("The ID of the root of the subtree to retrieve")});moveSchema=z.object({id:z.string().describe("The ID of the bookmark or folder to move"),parentId:z.string().optional().describe("The new parent folder ID"),index:z.number().optional().describe("The new position within the parent folder")});removeSchema=z.object({id:z.string().describe("The ID of the bookmark or empty folder to remove")});removeTreeSchema=z.object({id:z.string().describe("The ID of the folder to remove recursively")});searchSchema=z.object({query:z.union([z.string(),z.object({query:z.string().optional().describe("Words and phrases to match against URLs and titles"),url:z.string().optional().describe("URL to match exactly"),title:z.string().optional().describe("Title to match exactly")})])});updateSchema=z.object({id:z.string().describe("The ID of the bookmark or folder to update"),title:z.string().optional().describe("The new title"),url:z.string().optional().describe("The new URL (bookmarks only)")});async handleCreate(e){let{parentId:t,title:r,url:o,index:i}=this.createSchema.parse(e);if(r===void 0&&o===void 0)throw new Error("Either title or url must be provided");if(r?.length===0&&o?.length===0)throw new Error("Either title or url must be provided");let s={};t!==void 0&&(s.parentId=t),r!==void 0&&(s.title=r),o!==void 0&&(s.url=o),i!==void 0&&(s.index=i);let n=await new Promise((a,c)=>{chrome.bookmarks.create(s,u=>{chrome.runtime.lastError?c(new Error(chrome.runtime.lastError.message)):a(u);});});return this.formatJson({id:n.id,title:n.title,url:n.url,parentId:n.parentId,index:n.index,dateAdded:n.dateAdded,type:n.url?"bookmark":"folder"})}async handleGet(e){let{idOrIdList:t}=this.getSchema.parse(e),r=await new Promise((o,i)=>{chrome.bookmarks.get(t,s=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o(s);});});return this.formatJson({count:r.length,bookmarks:r.map(o=>({id:o.id,title:o.title,url:o.url,parentId:o.parentId,index:o.index,dateAdded:o.dateAdded,dateAddedFormatted:o.dateAdded?new Date(o.dateAdded).toISOString():void 0,type:o.url?"bookmark":"folder"}))})}async handleGetChildren(e){let{id:t}=this.getChildrenSchema.parse(e),r=await new Promise((o,i)=>{chrome.bookmarks.getChildren(t,s=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o(s);});});return this.formatJson({parentId:t,count:r.length,children:r.map(o=>({id:o.id,title:o.title,url:o.url,parentId:o.parentId,index:o.index,dateAdded:o.dateAdded,dateAddedFormatted:o.dateAdded?new Date(o.dateAdded).toISOString():void 0,type:o.url?"bookmark":"folder"}))})}async handleGetRecent(e){let{numberOfItems:t}=this.getRecentSchema.parse(e),r=await new Promise((o,i)=>{chrome.bookmarks.getRecent(t,s=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o(s);});});return this.formatJson({count:r.length,recentBookmarks:r.map(o=>({id:o.id,title:o.title,url:o.url,parentId:o.parentId,index:o.index,dateAdded:o.dateAdded,dateAddedFormatted:o.dateAdded?new Date(o.dateAdded).toISOString():void 0}))})}async handleGetSubTree(e){let{id:t}=this.getSubTreeSchema.parse(e),r=await new Promise((i,s)=>{chrome.bookmarks.getSubTree(t,n=>{chrome.runtime.lastError?s(new Error(chrome.runtime.lastError.message)):i(n);});}),o=i=>({id:i.id,title:i.title,url:i.url,parentId:i.parentId,index:i.index,dateAdded:i.dateAdded,dateAddedFormatted:i.dateAdded?new Date(i.dateAdded).toISOString():void 0,type:i.url?"bookmark":"folder",children:i.children?i.children.map(o):void 0});return this.formatJson({rootId:t,subtree:r.map(o)})}async handleGetTree(){let e=await new Promise((r,o)=>{chrome.bookmarks.getTree(i=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r(i);});}),t=r=>({id:r.id,title:r.title,url:r.url,parentId:r.parentId,index:r.index,dateAdded:r.dateAdded,dateAddedFormatted:r.dateAdded?new Date(r.dateAdded).toISOString():void 0,type:r.url?"bookmark":"folder",children:r.children?r.children.map(t):void 0});return this.formatJson({tree:e.map(t)})}async handleMove(e){let{id:t,parentId:r,index:o}=this.moveSchema.parse(e),i={};r!==void 0&&(i.parentId=r),o!==void 0&&(i.index=o);let s=await new Promise((n,a)=>{chrome.bookmarks.move(t,i,c=>{chrome.runtime.lastError?a(new Error(chrome.runtime.lastError.message)):n(c);});});return this.formatSuccess("Bookmark moved successfully",{id:s.id,title:s.title,url:s.url,parentId:s.parentId,index:s.index,type:s.url?"bookmark":"folder"})}async handleRemove(e){let{id:t}=this.removeSchema.parse(e);return await new Promise((r,o)=>{chrome.bookmarks.remove(t,()=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r();});}),this.formatSuccess("Bookmark removed successfully",{id:t})}async handleRemoveTree(e){let{id:t}=this.removeTreeSchema.parse(e);return await new Promise((r,o)=>{chrome.bookmarks.removeTree(t,()=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r();});}),this.formatSuccess("Bookmark folder and all contents removed successfully",{id:t})}async handleSearch(e){let{query:t}=this.searchSchema.parse(e),r=await new Promise((o,i)=>{chrome.bookmarks.search(t,s=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o(s);});});return this.formatJson({query:typeof t=="string"?t:JSON.stringify(t),count:r.length,results:r.map(o=>({id:o.id,title:o.title,url:o.url,parentId:o.parentId,index:o.index,dateAdded:o.dateAdded,dateAddedFormatted:o.dateAdded?new Date(o.dateAdded).toISOString():void 0,type:o.url?"bookmark":"folder"}))})}async handleUpdate(e){let{id:t,title:r,url:o}=this.updateSchema.parse(e),i={};if(r!==void 0&&(i.title=r),o!==void 0&&(i.url=o),Object.keys(i).length===0)return this.formatError("At least one property (title or url) must be specified to update");let s=await new Promise((n,a)=>{chrome.bookmarks.update(t,i,c=>{chrome.runtime.lastError?a(new Error(chrome.runtime.lastError.message)):n(c);});});return this.formatSuccess("Bookmark updated successfully",{id:s.id,title:s.title,url:s.url,parentId:s.parentId,index:s.index,type:s.url?"bookmark":"folder",changes:i})}isActionEnabled(e){let r={create:"create",get:"get",getChildren:"getChildren",getRecent:"getRecent",getSubTree:"getSubTree",getTree:"getTree",move:"move",remove:"remove",removeTree:"removeTree",search:"search",update:"update"}[e];return this.options[r]!==false}};var ke=class extends m{apiName="BrowsingData";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.browsingData?typeof chrome.browsingData.settings!="function"?{available:!1,message:"chrome.browsingData.settings is not available",details:"The browsingData API appears to be partially available. Check manifest permissions."}:(chrome.browsingData.settings(e=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"BrowsingData API is fully available"}):{available:!1,message:"chrome.browsingData API is not defined",details:'This extension needs the "browsingData" permission in its manifest.json'}}catch(e){return {available:false,message:"Failed to access chrome.browsingData API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("remove")&&this.registerRemove(),this.shouldRegisterTool("removeAppcache")&&this.registerRemoveAppcache(),this.shouldRegisterTool("removeCache")&&this.registerRemoveCache(),this.shouldRegisterTool("removeCacheStorage")&&this.registerRemoveCacheStorage(),this.shouldRegisterTool("removeCookies")&&this.registerRemoveCookies(),this.shouldRegisterTool("removeDownloads")&&this.registerRemoveDownloads(),this.shouldRegisterTool("removeFileSystems")&&this.registerRemoveFileSystems(),this.shouldRegisterTool("removeFormData")&&this.registerRemoveFormData(),this.shouldRegisterTool("removeHistory")&&this.registerRemoveHistory(),this.shouldRegisterTool("removeIndexedDB")&&this.registerRemoveIndexedDB(),this.shouldRegisterTool("removeLocalStorage")&&this.registerRemoveLocalStorage(),this.shouldRegisterTool("removePasswords")&&this.registerRemovePasswords(),this.shouldRegisterTool("removeServiceWorkers")&&this.registerRemoveServiceWorkers(),this.shouldRegisterTool("removeWebSQL")&&this.registerRemoveWebSQL(),this.shouldRegisterTool("settings")&&this.registerSettings();}registerRemove(){this.server.registerTool("extension_tool_remove_browsing_data",{description:"Remove various types of browsing data from the user's profile",inputSchema:{since:z.number().optional().describe("Remove data accumulated on or after this date (milliseconds since epoch)"),origins:z.array(z.string()).optional().describe("Only remove data for these origins (cookies, storage, cache only)"),excludeOrigins:z.array(z.string()).optional().describe("Exclude data for these origins from deletion"),originTypes:z.object({unprotectedWeb:z.boolean().optional(),protectedWeb:z.boolean().optional(),extension:z.boolean().optional()}).optional().describe("Types of origins to clear"),appcache:z.boolean().optional().describe("Remove websites' appcaches"),cache:z.boolean().optional().describe("Remove browser cache"),cacheStorage:z.boolean().optional().describe("Remove cache storage"),cookies:z.boolean().optional().describe("Remove cookies"),downloads:z.boolean().optional().describe("Remove download list"),fileSystems:z.boolean().optional().describe("Remove websites' file systems"),formData:z.boolean().optional().describe("Remove stored form data"),history:z.boolean().optional().describe("Remove browser history"),indexedDB:z.boolean().optional().describe("Remove IndexedDB data"),localStorage:z.boolean().optional().describe("Remove local storage data"),passwords:z.boolean().optional().describe("Remove stored passwords"),serviceWorkers:z.boolean().optional().describe("Remove service workers"),webSQL:z.boolean().optional().describe("Remove WebSQL data")}},async({since:e,origins:t,excludeOrigins:r,originTypes:o,appcache:i,cache:s,cacheStorage:n,cookies:a,downloads:c,fileSystems:u,formData:d,history:v,indexedDB:S,localStorage:P,passwords:I,serviceWorkers:O,webSQL:ne})=>{try{let H={};e!==void 0&&(H.since=e),t!==void 0&&(H.origins=t),r!==void 0&&(H.excludeOrigins=r),o!==void 0&&(H.originTypes=o);let U={};return i!==void 0&&(U.appcache=i),s!==void 0&&(U.cache=s),n!==void 0&&(U.cacheStorage=n),a!==void 0&&(U.cookies=a),c!==void 0&&(U.downloads=c),u!==void 0&&(U.fileSystems=u),d!==void 0&&(U.formData=d),v!==void 0&&(U.history=v),S!==void 0&&(U.indexedDB=S),P!==void 0&&(U.localStorage=P),I!==void 0&&(U.passwords=I),O!==void 0&&(U.serviceWorkers=O),ne!==void 0&&(U.webSQL=ne),await new Promise((ae,Se)=>{chrome.browsingData.remove(H,U,()=>{chrome.runtime.lastError?Se(new Error(chrome.runtime.lastError.message)):ae();});}),this.formatSuccess("Browsing data removed successfully",{options:H,dataTypes:Object.keys(U).filter(ae=>U[ae])})}catch(H){return this.formatError(H)}});}registerRemoveAppcache(){this.server.registerTool("extension_tool_remove_appcache",{description:"Remove websites' appcache data",inputSchema:{since:z.number().optional().describe("Remove data accumulated on or after this date (milliseconds since epoch)"),origins:z.array(z.string()).optional().describe("Only remove data for these origins"),excludeOrigins:z.array(z.string()).optional().describe("Exclude data for these origins from deletion"),originTypes:z.object({unprotectedWeb:z.boolean().optional(),protectedWeb:z.boolean().optional(),extension:z.boolean().optional()}).optional().describe("Types of origins to clear")}},async({since:e,origins:t,excludeOrigins:r,originTypes:o})=>{try{let i={};return e!==void 0&&(i.since=e),t!==void 0&&(i.origins=t),r!==void 0&&(i.excludeOrigins=r),o!==void 0&&(i.originTypes=o),await new Promise((s,n)=>{chrome.browsingData.removeAppcache(i,()=>{chrome.runtime.lastError?n(new Error(chrome.runtime.lastError.message)):s();});}),this.formatSuccess("Appcache data removed successfully",{options:i})}catch(i){return this.formatError(i)}});}registerRemoveCache(){this.server.registerTool("extension_tool_remove_cache",{description:"Remove browser cache",inputSchema:{since:z.number().optional().describe("Remove data accumulated on or after this date (milliseconds since epoch)"),origins:z.array(z.string()).optional().describe("Only remove data for these origins"),excludeOrigins:z.array(z.string()).optional().describe("Exclude data for these origins from deletion"),originTypes:z.object({unprotectedWeb:z.boolean().optional(),protectedWeb:z.boolean().optional(),extension:z.boolean().optional()}).optional().describe("Types of origins to clear")}},async({since:e,origins:t,excludeOrigins:r,originTypes:o})=>{try{let i={};return e!==void 0&&(i.since=e),t!==void 0&&(i.origins=t),r!==void 0&&(i.excludeOrigins=r),o!==void 0&&(i.originTypes=o),await new Promise((s,n)=>{chrome.browsingData.removeCache(i,()=>{chrome.runtime.lastError?n(new Error(chrome.runtime.lastError.message)):s();});}),this.formatSuccess("Cache removed successfully",{options:i})}catch(i){return this.formatError(i)}});}registerRemoveCacheStorage(){this.server.registerTool("extension_tool_remove_cache_storage",{description:"Remove websites' cache storage data",inputSchema:{since:z.number().optional().describe("Remove data accumulated on or after this date (milliseconds since epoch)"),origins:z.array(z.string()).optional().describe("Only remove data for these origins"),excludeOrigins:z.array(z.string()).optional().describe("Exclude data for these origins from deletion"),originTypes:z.object({unprotectedWeb:z.boolean().optional(),protectedWeb:z.boolean().optional(),extension:z.boolean().optional()}).optional().describe("Types of origins to clear")}},async({since:e,origins:t,excludeOrigins:r,originTypes:o})=>{try{let i={};return e!==void 0&&(i.since=e),t!==void 0&&(i.origins=t),r!==void 0&&(i.excludeOrigins=r),o!==void 0&&(i.originTypes=o),await new Promise((s,n)=>{chrome.browsingData.removeCacheStorage(i,()=>{chrome.runtime.lastError?n(new Error(chrome.runtime.lastError.message)):s();});}),this.formatSuccess("Cache storage removed successfully",{options:i})}catch(i){return this.formatError(i)}});}registerRemoveCookies(){this.server.registerTool("extension_tool_remove_cookies",{description:"Remove browser cookies and server-bound certificates",inputSchema:{since:z.number().optional().describe("Remove data accumulated on or after this date (milliseconds since epoch)"),origins:z.array(z.string()).optional().describe("Only remove data for these origins"),excludeOrigins:z.array(z.string()).optional().describe("Exclude data for these origins from deletion"),originTypes:z.object({unprotectedWeb:z.boolean().optional(),protectedWeb:z.boolean().optional(),extension:z.boolean().optional()}).optional().describe("Types of origins to clear")}},async({since:e,origins:t,excludeOrigins:r,originTypes:o})=>{try{let i={};return e!==void 0&&(i.since=e),t!==void 0&&(i.origins=t),r!==void 0&&(i.excludeOrigins=r),o!==void 0&&(i.originTypes=o),await new Promise((s,n)=>{chrome.browsingData.removeCookies(i,()=>{chrome.runtime.lastError?n(new Error(chrome.runtime.lastError.message)):s();});}),this.formatSuccess("Cookies removed successfully",{options:i})}catch(i){return this.formatError(i)}});}registerRemoveDownloads(){this.server.registerTool("extension_tool_remove_downloads",{description:"Remove browser download list (not the downloaded files themselves)",inputSchema:{since:z.number().optional().describe("Remove data accumulated on or after this date (milliseconds since epoch)"),originTypes:z.object({unprotectedWeb:z.boolean().optional(),protectedWeb:z.boolean().optional(),extension:z.boolean().optional()}).optional().describe("Types of origins to clear")}},async({since:e,originTypes:t})=>{try{let r={};return e!==void 0&&(r.since=e),t!==void 0&&(r.originTypes=t),await new Promise((o,i)=>{chrome.browsingData.removeDownloads(r,()=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o();});}),this.formatSuccess("Download list removed successfully",{options:r})}catch(r){return this.formatError(r)}});}registerRemoveFileSystems(){this.server.registerTool("extension_tool_remove_file_systems",{description:"Remove websites' file system data",inputSchema:{since:z.number().optional().describe("Remove data accumulated on or after this date (milliseconds since epoch)"),origins:z.array(z.string()).optional().describe("Only remove data for these origins"),excludeOrigins:z.array(z.string()).optional().describe("Exclude data for these origins from deletion"),originTypes:z.object({unprotectedWeb:z.boolean().optional(),protectedWeb:z.boolean().optional(),extension:z.boolean().optional()}).optional().describe("Types of origins to clear")}},async({since:e,origins:t,excludeOrigins:r,originTypes:o})=>{try{let i={};return e!==void 0&&(i.since=e),t!==void 0&&(i.origins=t),r!==void 0&&(i.excludeOrigins=r),o!==void 0&&(i.originTypes=o),await new Promise((s,n)=>{chrome.browsingData.removeFileSystems(i,()=>{chrome.runtime.lastError?n(new Error(chrome.runtime.lastError.message)):s();});}),this.formatSuccess("File systems removed successfully",{options:i})}catch(i){return this.formatError(i)}});}registerRemoveFormData(){this.server.registerTool("extension_tool_remove_form_data",{description:"Remove browser stored form data (autofill)",inputSchema:{since:z.number().optional().describe("Remove data accumulated on or after this date (milliseconds since epoch)"),originTypes:z.object({unprotectedWeb:z.boolean().optional(),protectedWeb:z.boolean().optional(),extension:z.boolean().optional()}).optional().describe("Types of origins to clear")}},async({since:e,originTypes:t})=>{try{let r={};return e!==void 0&&(r.since=e),t!==void 0&&(r.originTypes=t),await new Promise((o,i)=>{chrome.browsingData.removeFormData(r,()=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o();});}),this.formatSuccess("Form data removed successfully",{options:r})}catch(r){return this.formatError(r)}});}registerRemoveHistory(){this.server.registerTool("extension_tool_remove_history",{description:"Remove browser history",inputSchema:{since:z.number().optional().describe("Remove data accumulated on or after this date (milliseconds since epoch)"),originTypes:z.object({unprotectedWeb:z.boolean().optional(),protectedWeb:z.boolean().optional(),extension:z.boolean().optional()}).optional().describe("Types of origins to clear")}},async({since:e,originTypes:t})=>{try{let r={};return e!==void 0&&(r.since=e),t!==void 0&&(r.originTypes=t),await new Promise((o,i)=>{chrome.browsingData.removeHistory(r,()=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o();});}),this.formatSuccess("History removed successfully",{options:r})}catch(r){return this.formatError(r)}});}registerRemoveIndexedDB(){this.server.registerTool("extension_tool_remove_indexed_db",{description:"Remove websites' IndexedDB data",inputSchema:{since:z.number().optional().describe("Remove data accumulated on or after this date (milliseconds since epoch)"),origins:z.array(z.string()).optional().describe("Only remove data for these origins"),excludeOrigins:z.array(z.string()).optional().describe("Exclude data for these origins from deletion"),originTypes:z.object({unprotectedWeb:z.boolean().optional(),protectedWeb:z.boolean().optional(),extension:z.boolean().optional()}).optional().describe("Types of origins to clear")}},async({since:e,origins:t,excludeOrigins:r,originTypes:o})=>{try{let i={};return e!==void 0&&(i.since=e),t!==void 0&&(i.origins=t),r!==void 0&&(i.excludeOrigins=r),o!==void 0&&(i.originTypes=o),await new Promise((s,n)=>{chrome.browsingData.removeIndexedDB(i,()=>{chrome.runtime.lastError?n(new Error(chrome.runtime.lastError.message)):s();});}),this.formatSuccess("IndexedDB data removed successfully",{options:i})}catch(i){return this.formatError(i)}});}registerRemoveLocalStorage(){this.server.registerTool("extension_tool_remove_local_storage",{description:"Remove websites' local storage data",inputSchema:{since:z.number().optional().describe("Remove data accumulated on or after this date (milliseconds since epoch)"),origins:z.array(z.string()).optional().describe("Only remove data for these origins"),excludeOrigins:z.array(z.string()).optional().describe("Exclude data for these origins from deletion"),originTypes:z.object({unprotectedWeb:z.boolean().optional(),protectedWeb:z.boolean().optional(),extension:z.boolean().optional()}).optional().describe("Types of origins to clear")}},async({since:e,origins:t,excludeOrigins:r,originTypes:o})=>{try{let i={};return e!==void 0&&(i.since=e),t!==void 0&&(i.origins=t),r!==void 0&&(i.excludeOrigins=r),o!==void 0&&(i.originTypes=o),await new Promise((s,n)=>{chrome.browsingData.removeLocalStorage(i,()=>{chrome.runtime.lastError?n(new Error(chrome.runtime.lastError.message)):s();});}),this.formatSuccess("Local storage removed successfully",{options:i})}catch(i){return this.formatError(i)}});}registerRemovePasswords(){this.server.registerTool("extension_tool_remove_passwords",{description:"Remove browser stored passwords",inputSchema:{since:z.number().optional().describe("Remove data accumulated on or after this date (milliseconds since epoch)"),originTypes:z.object({unprotectedWeb:z.boolean().optional(),protectedWeb:z.boolean().optional(),extension:z.boolean().optional()}).optional().describe("Types of origins to clear")}},async({since:e,originTypes:t})=>{try{let r={};return e!==void 0&&(r.since=e),t!==void 0&&(r.originTypes=t),await new Promise((o,i)=>{chrome.browsingData.removePasswords(r,()=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o();});}),this.formatSuccess("Passwords removed successfully",{options:r})}catch(r){return this.formatError(r)}});}registerRemoveServiceWorkers(){this.server.registerTool("extension_tool_remove_service_workers",{description:"Remove websites' service workers",inputSchema:{since:z.number().optional().describe("Remove data accumulated on or after this date (milliseconds since epoch)"),origins:z.array(z.string()).optional().describe("Only remove data for these origins"),excludeOrigins:z.array(z.string()).optional().describe("Exclude data for these origins from deletion"),originTypes:z.object({unprotectedWeb:z.boolean().optional(),protectedWeb:z.boolean().optional(),extension:z.boolean().optional()}).optional().describe("Types of origins to clear")}},async({since:e,origins:t,excludeOrigins:r,originTypes:o})=>{try{let i={};return e!==void 0&&(i.since=e),t!==void 0&&(i.origins=t),r!==void 0&&(i.excludeOrigins=r),o!==void 0&&(i.originTypes=o),await new Promise((s,n)=>{chrome.browsingData.removeServiceWorkers(i,()=>{chrome.runtime.lastError?n(new Error(chrome.runtime.lastError.message)):s();});}),this.formatSuccess("Service workers removed successfully",{options:i})}catch(i){return this.formatError(i)}});}registerRemoveWebSQL(){this.server.registerTool("extension_tool_remove_web_sql",{description:"Remove websites' WebSQL data",inputSchema:{since:z.number().optional().describe("Remove data accumulated on or after this date (milliseconds since epoch)"),origins:z.array(z.string()).optional().describe("Only remove data for these origins"),excludeOrigins:z.array(z.string()).optional().describe("Exclude data for these origins from deletion"),originTypes:z.object({unprotectedWeb:z.boolean().optional(),protectedWeb:z.boolean().optional(),extension:z.boolean().optional()}).optional().describe("Types of origins to clear")}},async({since:e,origins:t,excludeOrigins:r,originTypes:o})=>{try{let i={};return e!==void 0&&(i.since=e),t!==void 0&&(i.origins=t),r!==void 0&&(i.excludeOrigins=r),o!==void 0&&(i.originTypes=o),await new Promise((s,n)=>{chrome.browsingData.removeWebSQL(i,()=>{chrome.runtime.lastError?n(new Error(chrome.runtime.lastError.message)):s();});}),this.formatSuccess("WebSQL data removed successfully",{options:i})}catch(i){return this.formatError(i)}});}registerSettings(){this.server.registerTool("extension_tool_get_browsing_data_settings",{description:"Get current browsing data settings from the Clear browsing data UI",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.browsingData.settings(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({dataRemovalPermitted:e.dataRemovalPermitted,dataToRemove:e.dataToRemove,options:e.options})}catch(e){return this.formatError(e)}});}};var Ce=class extends m{apiName="CertificateProvider";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.certificateProvider?typeof chrome.certificateProvider.setCertificates!="function"?{available:!1,message:"chrome.certificateProvider.setCertificates is not available",details:"The certificateProvider API appears to be partially available. Check manifest permissions and ensure running on ChromeOS."}:{available:!0,message:"CertificateProvider API is fully available"}:{available:!1,message:"chrome.certificateProvider API is not defined",details:'This extension needs the "certificateProvider" permission in its manifest.json and only works on ChromeOS'}}catch(e){return {available:false,message:"Failed to access chrome.certificateProvider API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("setCertificates")&&this.registerSetCertificates(),this.shouldRegisterTool("reportSignature")&&this.registerReportSignature(),this.shouldRegisterTool("requestPin")&&this.registerRequestPin(),this.shouldRegisterTool("stopPinRequest")&&this.registerStopPinRequest(),this.shouldRegisterTool("onCertificatesUpdateRequested")&&this.registerOnCertificatesUpdateRequested(),this.shouldRegisterTool("onSignatureRequested")&&this.registerOnSignatureRequested();}registerSetCertificates(){this.server.registerTool("extension_tool_set_certificates",{description:"Sets a list of certificates to use in the browser for TLS client authentication",inputSchema:{certificatesRequestId:z.number().optional().describe("Request ID when responding to onCertificatesUpdateRequested event"),clientCertificates:z.array(z.object({certificateChain:z.array(z.string()).describe("Array of base64-encoded DER certificates, with client cert first"),supportedAlgorithms:z.array(z.string()).describe("Supported signature algorithms for this certificate")})).describe("List of client certificates to provide"),error:z.enum(["GENERAL_ERROR"]).optional().describe("Error that occurred while extracting certificates")}},async({certificatesRequestId:e,clientCertificates:t,error:r})=>{try{let o={clientCertificates:t.map(i=>({certificateChain:i.certificateChain.map(s=>{let n=atob(s),a=new Uint8Array(n.length);for(let c=0;c<n.length;c++)a[c]=n.charCodeAt(c);return a.buffer}),supportedAlgorithms:i.supportedAlgorithms}))};return e!==void 0&&(o.certificatesRequestId=e),r!==void 0&&(o.error=r),await new Promise((i,s)=>{chrome.certificateProvider.setCertificates(o,()=>{chrome.runtime.lastError?s(new Error(chrome.runtime.lastError.message)):i();});}),this.formatSuccess("Certificates set successfully",{certificateCount:t.length,requestId:e})}catch(o){return this.formatError(o)}});}registerReportSignature(){this.server.registerTool("extension_tool_report_signature",{description:"Reports the signature for a signing request from the browser",inputSchema:{signRequestId:z.number().describe("Request identifier from onSignatureRequested event"),signature:z.string().optional().describe("Base64-encoded signature data, if successfully generated"),error:z.enum(["GENERAL_ERROR"]).optional().describe("Error that occurred while generating the signature")}},async({signRequestId:e,signature:t,error:r})=>{try{let o={signRequestId:e};if(t!==void 0){let i=atob(t),s=new Uint8Array(i.length);for(let n=0;n<i.length;n++)s[n]=i.charCodeAt(n);o.signature=s.buffer;}return r!==void 0&&(o.error=r),await new Promise((i,s)=>{chrome.certificateProvider.reportSignature(o,()=>{chrome.runtime.lastError?s(new Error(chrome.runtime.lastError.message)):i();});}),this.formatSuccess("Signature reported successfully",{signRequestId:e,hasSignature:t!==void 0,hasError:r!==void 0})}catch(o){return this.formatError(o)}});}registerRequestPin(){this.server.registerTool("extension_tool_request_pin",{description:"Requests PIN or PUK from the user for certificate operations",inputSchema:{signRequestId:z.number().describe("The ID from SignRequest"),requestType:z.enum(["PIN","PUK"]).optional().describe("Type of code being requested (default: PIN)"),errorType:z.enum(["INVALID_PIN","INVALID_PUK","MAX_ATTEMPTS_EXCEEDED","UNKNOWN_ERROR"]).optional().describe("Error from previous request to show to user"),attemptsLeft:z.number().optional().describe("Number of attempts remaining for user information")}},async({signRequestId:e,requestType:t,errorType:r,attemptsLeft:o})=>{try{let i={signRequestId:e};t!==void 0&&(i.requestType=t),r!==void 0&&(i.errorType=r),o!==void 0&&(i.attemptsLeft=o);let s=await new Promise((n,a)=>{chrome.certificateProvider.requestPin(i,c=>{chrome.runtime.lastError?a(new Error(chrome.runtime.lastError.message)):n(c);});});return this.formatJson({signRequestId:e,userInput:s?.userInput||null,success:!!s?.userInput})}catch(i){return this.formatError(i)}});}registerStopPinRequest(){this.server.registerTool("extension_tool_stop_pin_request",{description:"Stops an ongoing PIN request flow",inputSchema:{signRequestId:z.number().describe("The ID from SignRequest"),errorType:z.enum(["INVALID_PIN","INVALID_PUK","MAX_ATTEMPTS_EXCEEDED","UNKNOWN_ERROR"]).optional().describe("Error reason for stopping the flow")}},async({signRequestId:e,errorType:t})=>{try{let r={signRequestId:e};return t!==void 0&&(r.errorType=t),await new Promise((o,i)=>{chrome.certificateProvider.stopPinRequest(r,()=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o();});}),this.formatSuccess("PIN request stopped successfully",{signRequestId:e,errorType:t})}catch(r){return this.formatError(r)}});}registerOnCertificatesUpdateRequested(){this.server.registerTool("extension_tool_listen_certificates_update_requested",{description:"Sets up listener for certificate update requests from the browser",inputSchema:{}},async()=>{try{return chrome.certificateProvider.onCertificatesUpdateRequested.hasListeners()&&chrome.certificateProvider.onCertificatesUpdateRequested.removeListener(this.handleCertificatesUpdateRequested),chrome.certificateProvider.onCertificatesUpdateRequested.addListener(this.handleCertificatesUpdateRequested),this.formatSuccess("Certificate update request listener registered",{event:"onCertificatesUpdateRequested",hasListeners:chrome.certificateProvider.onCertificatesUpdateRequested.hasListeners()})}catch(e){return this.formatError(e)}});}registerOnSignatureRequested(){this.server.registerTool("extension_tool_listen_signature_requested",{description:"Sets up listener for signature requests from the browser",inputSchema:{}},async()=>{try{return chrome.certificateProvider.onSignatureRequested.hasListeners()&&chrome.certificateProvider.onSignatureRequested.removeListener(this.handleSignatureRequested),chrome.certificateProvider.onSignatureRequested.addListener(this.handleSignatureRequested),this.formatSuccess("Signature request listener registered",{event:"onSignatureRequested",hasListeners:chrome.certificateProvider.onSignatureRequested.hasListeners()})}catch(e){return this.formatError(e)}});}handleCertificatesUpdateRequested=e=>{console.log("Certificate update requested:",{certificatesRequestId:e.certificatesRequestId,timestamp:new Date().toISOString()});};handleSignatureRequested=e=>{let t=new Uint8Array(e.certificate),r=new Uint8Array(e.input);console.log("Signature requested:",{signRequestId:e.signRequestId,algorithm:e.algorithm,certificateLength:t.length,inputLength:r.length,timestamp:new Date().toISOString()});}};var De=class extends m{apiName="Commands";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.commands?typeof chrome.commands.getAll!="function"?{available:!1,message:"chrome.commands.getAll is not available",details:"The commands API appears to be partially available. Check manifest permissions."}:(chrome.commands.getAll(e=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"Commands API is fully available"}):{available:!1,message:"chrome.commands API is not defined",details:'This extension needs the "commands" permission in its manifest.json'}}catch(e){return {available:false,message:"Failed to access chrome.commands API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("getAll")&&this.registerGetAll();}registerGetAll(){this.server.registerTool("extension_tool_get_all_commands",{description:"Get all registered extension commands and their keyboard shortcuts",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.commands.getAll(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({count:e.length,commands:e.map(t=>({name:t.name,description:t.description,shortcut:t.shortcut||"Not assigned",isActive:!!t.shortcut}))})}catch(e){return this.formatError(e)}});}};var Oe=class extends m{apiName="ContentSettings";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.contentSettings?!chrome.contentSettings.cookies||typeof chrome.contentSettings.cookies.get!="function"?{available:!1,message:"chrome.contentSettings.cookies.get is not available",details:"The contentSettings API appears to be partially available. Check manifest permissions."}:(chrome.contentSettings.cookies.get({primaryUrl:"https://example.com"},e=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"ContentSettings API is fully available"}):{available:!1,message:"chrome.contentSettings API is not defined",details:'This extension needs the "contentSettings" permission in its manifest.json'}}catch(e){return {available:false,message:"Failed to access chrome.contentSettings API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("getCookiesSetting")&&this.registerGetCookiesSetting(),this.shouldRegisterTool("setCookiesSetting")&&this.registerSetCookiesSetting(),this.shouldRegisterTool("clearCookiesSetting")&&this.registerClearCookiesSetting(),this.shouldRegisterTool("getJavascriptSetting")&&this.registerGetJavascriptSetting(),this.shouldRegisterTool("setJavascriptSetting")&&this.registerSetJavascriptSetting(),this.shouldRegisterTool("clearJavascriptSetting")&&this.registerClearJavascriptSetting(),this.shouldRegisterTool("getImagesSetting")&&this.registerGetImagesSetting(),this.shouldRegisterTool("setImagesSetting")&&this.registerSetImagesSetting(),this.shouldRegisterTool("clearImagesSetting")&&this.registerClearImagesSetting(),this.shouldRegisterTool("getLocationSetting")&&this.registerGetLocationSetting(),this.shouldRegisterTool("setLocationSetting")&&this.registerSetLocationSetting(),this.shouldRegisterTool("clearLocationSetting")&&this.registerClearLocationSetting(),this.shouldRegisterTool("getNotificationsSetting")&&this.registerGetNotificationsSetting(),this.shouldRegisterTool("setNotificationsSetting")&&this.registerSetNotificationsSetting(),this.shouldRegisterTool("clearNotificationsSetting")&&this.registerClearNotificationsSetting(),this.shouldRegisterTool("getPopupsSetting")&&this.registerGetPopupsSetting(),this.shouldRegisterTool("setPopupsSetting")&&this.registerSetPopupsSetting(),this.shouldRegisterTool("clearPopupsSetting")&&this.registerClearPopupsSetting(),this.shouldRegisterTool("getCameraSetting")&&this.registerGetCameraSetting(),this.shouldRegisterTool("setCameraSetting")&&this.registerSetCameraSetting(),this.shouldRegisterTool("clearCameraSetting")&&this.registerClearCameraSetting(),this.shouldRegisterTool("getMicrophoneSetting")&&this.registerGetMicrophoneSetting(),this.shouldRegisterTool("setMicrophoneSetting")&&this.registerSetMicrophoneSetting(),this.shouldRegisterTool("clearMicrophoneSetting")&&this.registerClearMicrophoneSetting(),this.shouldRegisterTool("getAutomaticDownloadsSetting")&&this.registerGetAutomaticDownloadsSetting(),this.shouldRegisterTool("setAutomaticDownloadsSetting")&&this.registerSetAutomaticDownloadsSetting(),this.shouldRegisterTool("clearAutomaticDownloadsSetting")&&this.registerClearAutomaticDownloadsSetting(),this.shouldRegisterTool("getClipboardSetting")&&this.registerGetClipboardSetting(),this.shouldRegisterTool("setClipboardSetting")&&this.registerSetClipboardSetting(),this.shouldRegisterTool("clearClipboardSetting")&&this.registerClearClipboardSetting(),this.shouldRegisterTool("getAutoVerifySetting")&&this.registerGetAutoVerifySetting(),this.shouldRegisterTool("setAutoVerifySetting")&&this.registerSetAutoVerifySetting(),this.shouldRegisterTool("clearAutoVerifySetting")&&this.registerClearAutoVerifySetting(),this.shouldRegisterTool("getPluginsResourceIdentifiers")&&this.registerGetPluginsResourceIdentifiers();}registerGetCookiesSetting(){this.server.registerTool("extension_tool_get_cookies_setting",{description:"Get the current cookies content setting for a given pair of URLs",inputSchema:{primaryUrl:z.string().describe("The primary URL for which the content setting should be retrieved"),secondaryUrl:z.string().optional().describe("The secondary URL for which the content setting should be retrieved"),incognito:z.boolean().optional().describe("Whether to check the content settings for an incognito session"),resourceIdentifier:z.object({id:z.string(),description:z.string().optional()}).optional().describe("A more specific identifier of the type of content")}},async({primaryUrl:e,secondaryUrl:t,incognito:r,resourceIdentifier:o})=>{try{let i={primaryUrl:e};t!==void 0&&(i.secondaryUrl=t),r!==void 0&&(i.incognito=r),o!==void 0&&(i.resourceIdentifier=o);let s=await new Promise((n,a)=>{chrome.contentSettings.cookies.get(i,c=>{chrome.runtime.lastError?a(new Error(chrome.runtime.lastError.message)):n(c);});});return this.formatJson({primaryUrl:e,secondaryUrl:t,incognito:r||!1,setting:s.setting})}catch(i){return this.formatError(i)}});}registerSetCookiesSetting(){this.server.registerTool("extension_tool_set_cookies_setting",{description:"Set a new cookies content setting rule",inputSchema:{primaryPattern:z.string().describe("The pattern for the primary URL"),secondaryPattern:z.string().optional().describe("The pattern for the secondary URL"),setting:z.enum(["allow","block","session_only"]).describe("The setting to apply"),scope:z.enum(["regular","incognito_session_only"]).optional().describe("Where to set the setting"),resourceIdentifier:z.object({id:z.string(),description:z.string().optional()}).optional().describe("The resource identifier for the content type")}},async({primaryPattern:e,secondaryPattern:t,setting:r,scope:o,resourceIdentifier:i})=>{try{let s={primaryPattern:e,setting:r};return t!==void 0&&(s.secondaryPattern=t),o!==void 0&&(s.scope=o),i!==void 0&&(s.resourceIdentifier=i),await new Promise((n,a)=>{chrome.contentSettings.cookies.set(s,()=>{chrome.runtime.lastError?a(new Error(chrome.runtime.lastError.message)):n();});}),this.formatSuccess("Cookies content setting rule applied successfully",{primaryPattern:e,secondaryPattern:t,setting:r,scope:o||"regular"})}catch(s){return this.formatError(s)}});}registerClearCookiesSetting(){this.server.registerTool("extension_tool_clear_cookies_setting",{description:"Clear all cookies content setting rules set by this extension",inputSchema:{scope:z.enum(["regular","incognito_session_only"]).optional().describe("Where to clear the setting")}},async({scope:e})=>{try{let t={};return e!==void 0&&(t.scope=e),await new Promise((r,o)=>{chrome.contentSettings.cookies.clear(t,()=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r();});}),this.formatSuccess("All cookies content setting rules cleared successfully",{scope:e||"regular"})}catch(t){return this.formatError(t)}});}registerGetJavascriptSetting(){this.server.registerTool("extension_tool_get_javascript_setting",{description:"Get the current JavaScript content setting for a given pair of URLs",inputSchema:{primaryUrl:z.string().describe("The primary URL for which the content setting should be retrieved"),secondaryUrl:z.string().optional().describe("The secondary URL for which the content setting should be retrieved"),incognito:z.boolean().optional().describe("Whether to check the content settings for an incognito session"),resourceIdentifier:z.object({id:z.string(),description:z.string().optional()}).optional().describe("A more specific identifier of the type of content")}},async({primaryUrl:e,secondaryUrl:t,incognito:r,resourceIdentifier:o})=>{try{let i={primaryUrl:e};t!==void 0&&(i.secondaryUrl=t),r!==void 0&&(i.incognito=r),o!==void 0&&(i.resourceIdentifier=o);let s=await new Promise((n,a)=>{chrome.contentSettings.javascript.get(i,c=>{chrome.runtime.lastError?a(new Error(chrome.runtime.lastError.message)):n(c);});});return this.formatJson({primaryUrl:e,secondaryUrl:t,incognito:r||!1,setting:s.setting})}catch(i){return this.formatError(i)}});}registerSetJavascriptSetting(){this.server.registerTool("extension_tool_set_javascript_setting",{description:"Set a new JavaScript content setting rule",inputSchema:{primaryPattern:z.string().describe("The pattern for the primary URL"),secondaryPattern:z.string().optional().describe("The pattern for the secondary URL"),setting:z.enum(["allow","block"]).describe("The setting to apply"),scope:z.enum(["regular","incognito_session_only"]).optional().describe("Where to set the setting"),resourceIdentifier:z.object({id:z.string(),description:z.string().optional()}).optional().describe("The resource identifier for the content type")}},async({primaryPattern:e,secondaryPattern:t,setting:r,scope:o,resourceIdentifier:i})=>{try{let s={primaryPattern:e,setting:r};return t!==void 0&&(s.secondaryPattern=t),o!==void 0&&(s.scope=o),i!==void 0&&(s.resourceIdentifier=i),await new Promise((n,a)=>{chrome.contentSettings.javascript.set(s,()=>{chrome.runtime.lastError?a(new Error(chrome.runtime.lastError.message)):n();});}),this.formatSuccess("JavaScript content setting rule applied successfully",{primaryPattern:e,secondaryPattern:t,setting:r,scope:o||"regular"})}catch(s){return this.formatError(s)}});}registerClearJavascriptSetting(){this.server.registerTool("extension_tool_clear_javascript_setting",{description:"Clear all JavaScript content setting rules set by this extension",inputSchema:{scope:z.enum(["regular","incognito_session_only"]).optional().describe("Where to clear the setting")}},async({scope:e})=>{try{let t={};return e!==void 0&&(t.scope=e),await new Promise((r,o)=>{chrome.contentSettings.javascript.clear(t,()=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r();});}),this.formatSuccess("All JavaScript content setting rules cleared successfully",{scope:e||"regular"})}catch(t){return this.formatError(t)}});}registerGetImagesSetting(){this.server.registerTool("extension_tool_get_images_setting",{description:"Get the current images content setting for a given pair of URLs",inputSchema:{primaryUrl:z.string().describe("The primary URL for which the content setting should be retrieved"),secondaryUrl:z.string().optional().describe("The secondary URL for which the content setting should be retrieved"),incognito:z.boolean().optional().describe("Whether to check the content settings for an incognito session"),resourceIdentifier:z.object({id:z.string(),description:z.string().optional()}).optional().describe("A more specific identifier of the type of content")}},async({primaryUrl:e,secondaryUrl:t,incognito:r,resourceIdentifier:o})=>{try{let i={primaryUrl:e};t!==void 0&&(i.secondaryUrl=t),r!==void 0&&(i.incognito=r),o!==void 0&&(i.resourceIdentifier=o);let s=await new Promise((n,a)=>{chrome.contentSettings.images.get(i,c=>{chrome.runtime.lastError?a(new Error(chrome.runtime.lastError.message)):n(c);});});return this.formatJson({primaryUrl:e,secondaryUrl:t,incognito:r||!1,setting:s.setting})}catch(i){return this.formatError(i)}});}registerSetImagesSetting(){this.server.registerTool("extension_tool_set_images_setting",{description:"Set a new images content setting rule",inputSchema:{primaryPattern:z.string().describe("The pattern for the primary URL"),secondaryPattern:z.string().optional().describe("The pattern for the secondary URL"),setting:z.enum(["allow","block"]).describe("The setting to apply"),scope:z.enum(["regular","incognito_session_only"]).optional().describe("Where to set the setting"),resourceIdentifier:z.object({id:z.string(),description:z.string().optional()}).optional().describe("The resource identifier for the content type")}},async({primaryPattern:e,secondaryPattern:t,setting:r,scope:o,resourceIdentifier:i})=>{try{let s={primaryPattern:e,setting:r};return t!==void 0&&(s.secondaryPattern=t),o!==void 0&&(s.scope=o),i!==void 0&&(s.resourceIdentifier=i),await new Promise((n,a)=>{chrome.contentSettings.images.set(s,()=>{chrome.runtime.lastError?a(new Error(chrome.runtime.lastError.message)):n();});}),this.formatSuccess("Images content setting rule applied successfully",{primaryPattern:e,secondaryPattern:t,setting:r,scope:o||"regular"})}catch(s){return this.formatError(s)}});}registerClearImagesSetting(){this.server.registerTool("extension_tool_clear_images_setting",{description:"Clear all images content setting rules set by this extension",inputSchema:{scope:z.enum(["regular","incognito_session_only"]).optional().describe("Where to clear the setting")}},async({scope:e})=>{try{let t={};return e!==void 0&&(t.scope=e),await new Promise((r,o)=>{chrome.contentSettings.images.clear(t,()=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r();});}),this.formatSuccess("All images content setting rules cleared successfully",{scope:e||"regular"})}catch(t){return this.formatError(t)}});}registerGetLocationSetting(){this.server.registerTool("extension_tool_get_location_setting",{description:"Get the current location content setting for a given pair of URLs",inputSchema:{primaryUrl:z.string().describe("The primary URL for which the content setting should be retrieved"),secondaryUrl:z.string().optional().describe("The secondary URL for which the content setting should be retrieved"),incognito:z.boolean().optional().describe("Whether to check the content settings for an incognito session"),resourceIdentifier:z.object({id:z.string(),description:z.string().optional()}).optional().describe("A more specific identifier of the type of content")}},async({primaryUrl:e,secondaryUrl:t,incognito:r,resourceIdentifier:o})=>{try{let i={primaryUrl:e};t!==void 0&&(i.secondaryUrl=t),r!==void 0&&(i.incognito=r),o!==void 0&&(i.resourceIdentifier=o);let s=await new Promise((n,a)=>{chrome.contentSettings.location.get(i,c=>{chrome.runtime.lastError?a(new Error(chrome.runtime.lastError.message)):n(c);});});return this.formatJson({primaryUrl:e,secondaryUrl:t,incognito:r||!1,setting:s.setting})}catch(i){return this.formatError(i)}});}registerSetLocationSetting(){this.server.registerTool("extension_tool_set_location_setting",{description:"Set a new location content setting rule",inputSchema:{primaryPattern:z.string().describe("The pattern for the primary URL"),secondaryPattern:z.string().optional().describe("The pattern for the secondary URL"),setting:z.enum(["allow","block","ask"]).describe("The setting to apply"),scope:z.enum(["regular","incognito_session_only"]).optional().describe("Where to set the setting"),resourceIdentifier:z.object({id:z.string(),description:z.string().optional()}).optional().describe("The resource identifier for the content type")}},async({primaryPattern:e,secondaryPattern:t,setting:r,scope:o,resourceIdentifier:i})=>{try{let s={primaryPattern:e,setting:r};return t!==void 0&&(s.secondaryPattern=t),o!==void 0&&(s.scope=o),i!==void 0&&(s.resourceIdentifier=i),await new Promise((n,a)=>{chrome.contentSettings.location.set(s,()=>{chrome.runtime.lastError?a(new Error(chrome.runtime.lastError.message)):n();});}),this.formatSuccess("Location content setting rule applied successfully",{primaryPattern:e,secondaryPattern:t,setting:r,scope:o||"regular"})}catch(s){return this.formatError(s)}});}registerClearLocationSetting(){this.server.registerTool("extension_tool_clear_location_setting",{description:"Clear all location content setting rules set by this extension",inputSchema:{scope:z.enum(["regular","incognito_session_only"]).optional().describe("Where to clear the setting")}},async({scope:e})=>{try{let t={};return e!==void 0&&(t.scope=e),await new Promise((r,o)=>{chrome.contentSettings.location.clear(t,()=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r();});}),this.formatSuccess("All location content setting rules cleared successfully",{scope:e||"regular"})}catch(t){return this.formatError(t)}});}registerGetNotificationsSetting(){this.server.registerTool("extension_tool_get_notifications_setting",{description:"Get the current notifications content setting for a given pair of URLs",inputSchema:{primaryUrl:z.string().describe("The primary URL for which the content setting should be retrieved"),secondaryUrl:z.string().optional().describe("The secondary URL for which the content setting should be retrieved"),incognito:z.boolean().optional().describe("Whether to check the content settings for an incognito session"),resourceIdentifier:z.object({id:z.string(),description:z.string().optional()}).optional().describe("A more specific identifier of the type of content")}},async({primaryUrl:e,secondaryUrl:t,incognito:r,resourceIdentifier:o})=>{try{let i={primaryUrl:e};t!==void 0&&(i.secondaryUrl=t),r!==void 0&&(i.incognito=r),o!==void 0&&(i.resourceIdentifier=o);let s=await new Promise((n,a)=>{chrome.contentSettings.notifications.get(i,c=>{chrome.runtime.lastError?a(new Error(chrome.runtime.lastError.message)):n(c);});});return this.formatJson({primaryUrl:e,secondaryUrl:t,incognito:r||!1,setting:s.setting})}catch(i){return this.formatError(i)}});}registerSetNotificationsSetting(){this.server.registerTool("extension_tool_set_notifications_setting",{description:"Set a new notifications content setting rule",inputSchema:{primaryPattern:z.string().describe("The pattern for the primary URL"),secondaryPattern:z.string().optional().describe("The pattern for the secondary URL"),setting:z.enum(["allow","block","ask"]).describe("The setting to apply"),scope:z.enum(["regular","incognito_session_only"]).optional().describe("Where to set the setting"),resourceIdentifier:z.object({id:z.string(),description:z.string().optional()}).optional().describe("The resource identifier for the content type")}},async({primaryPattern:e,secondaryPattern:t,setting:r,scope:o,resourceIdentifier:i})=>{try{let s={primaryPattern:e,setting:r};return t!==void 0&&(s.secondaryPattern=t),o!==void 0&&(s.scope=o),i!==void 0&&(s.resourceIdentifier=i),await new Promise((n,a)=>{chrome.contentSettings.notifications.set(s,()=>{chrome.runtime.lastError?a(new Error(chrome.runtime.lastError.message)):n();});}),this.formatSuccess("Notifications content setting rule applied successfully",{primaryPattern:e,secondaryPattern:t,setting:r,scope:o||"regular"})}catch(s){return this.formatError(s)}});}registerClearNotificationsSetting(){this.server.registerTool("extension_tool_clear_notifications_setting",{description:"Clear all notifications content setting rules set by this extension",inputSchema:{scope:z.enum(["regular","incognito_session_only"]).optional().describe("Where to clear the setting")}},async({scope:e})=>{try{let t={};return e!==void 0&&(t.scope=e),await new Promise((r,o)=>{chrome.contentSettings.notifications.clear(t,()=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r();});}),this.formatSuccess("All notifications content setting rules cleared successfully",{scope:e||"regular"})}catch(t){return this.formatError(t)}});}registerGetPopupsSetting(){this.server.registerTool("extension_tool_get_popups_setting",{description:"Get the current popups content setting for a given pair of URLs",inputSchema:{primaryUrl:z.string().describe("The primary URL for which the content setting should be retrieved"),secondaryUrl:z.string().optional().describe("The secondary URL for which the content setting should be retrieved"),incognito:z.boolean().optional().describe("Whether to check the content settings for an incognito session"),resourceIdentifier:z.object({id:z.string(),description:z.string().optional()}).optional().describe("A more specific identifier of the type of content")}},async({primaryUrl:e,secondaryUrl:t,incognito:r,resourceIdentifier:o})=>{try{let i={primaryUrl:e};t!==void 0&&(i.secondaryUrl=t),r!==void 0&&(i.incognito=r),o!==void 0&&(i.resourceIdentifier=o);let s=await new Promise((n,a)=>{chrome.contentSettings.popups.get(i,c=>{chrome.runtime.lastError?a(new Error(chrome.runtime.lastError.message)):n(c);});});return this.formatJson({primaryUrl:e,secondaryUrl:t,incognito:r||!1,setting:s.setting})}catch(i){return this.formatError(i)}});}registerSetPopupsSetting(){this.server.registerTool("extension_tool_set_popups_setting",{description:"Set a new popups content setting rule",inputSchema:{primaryPattern:z.string().describe("The pattern for the primary URL"),secondaryPattern:z.string().optional().describe("The pattern for the secondary URL"),setting:z.enum(["allow","block"]).describe("The setting to apply"),scope:z.enum(["regular","incognito_session_only"]).optional().describe("Where to set the setting"),resourceIdentifier:z.object({id:z.string(),description:z.string().optional()}).optional().describe("The resource identifier for the content type")}},async({primaryPattern:e,secondaryPattern:t,setting:r,scope:o,resourceIdentifier:i})=>{try{let s={primaryPattern:e,setting:r};return t!==void 0&&(s.secondaryPattern=t),o!==void 0&&(s.scope=o),i!==void 0&&(s.resourceIdentifier=i),await new Promise((n,a)=>{chrome.contentSettings.popups.set(s,()=>{chrome.runtime.lastError?a(new Error(chrome.runtime.lastError.message)):n();});}),this.formatSuccess("Popups content setting rule applied successfully",{primaryPattern:e,secondaryPattern:t,setting:r,scope:o||"regular"})}catch(s){return this.formatError(s)}});}registerClearPopupsSetting(){this.server.registerTool("extension_tool_clear_popups_setting",{description:"Clear all popups content setting rules set by this extension",inputSchema:{scope:z.enum(["regular","incognito_session_only"]).optional().describe("Where to clear the setting")}},async({scope:e})=>{try{let t={};return e!==void 0&&(t.scope=e),await new Promise((r,o)=>{chrome.contentSettings.popups.clear(t,()=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r();});}),this.formatSuccess("All popups content setting rules cleared successfully",{scope:e||"regular"})}catch(t){return this.formatError(t)}});}registerGetCameraSetting(){this.server.registerTool("extension_tool_get_camera_setting",{description:"Get the current camera content setting for a given pair of URLs",inputSchema:{primaryUrl:z.string().describe("The primary URL for which the content setting should be retrieved"),secondaryUrl:z.string().optional().describe("The secondary URL for which the content setting should be retrieved"),incognito:z.boolean().optional().describe("Whether to check the content settings for an incognito session"),resourceIdentifier:z.object({id:z.string(),description:z.string().optional()}).optional().describe("A more specific identifier of the type of content")}},async({primaryUrl:e,secondaryUrl:t,incognito:r,resourceIdentifier:o})=>{try{let i={primaryUrl:e};t!==void 0&&(i.secondaryUrl=t),r!==void 0&&(i.incognito=r),o!==void 0&&(i.resourceIdentifier=o);let s=await new Promise((n,a)=>{chrome.contentSettings.camera.get(i,c=>{chrome.runtime.lastError?a(new Error(chrome.runtime.lastError.message)):n(c);});});return this.formatJson({primaryUrl:e,secondaryUrl:t,incognito:r||!1,setting:s.setting})}catch(i){return this.formatError(i)}});}registerSetCameraSetting(){this.server.registerTool("extension_tool_set_camera_setting",{description:"Set a new camera content setting rule",inputSchema:{primaryPattern:z.string().describe("The pattern for the primary URL"),secondaryPattern:z.string().optional().describe("The pattern for the secondary URL"),setting:z.enum(["allow","block","ask"]).describe("The setting to apply"),scope:z.enum(["regular","incognito_session_only"]).optional().describe("Where to set the setting"),resourceIdentifier:z.object({id:z.string(),description:z.string().optional()}).optional().describe("The resource identifier for the content type")}},async({primaryPattern:e,secondaryPattern:t,setting:r,scope:o,resourceIdentifier:i})=>{try{let s={primaryPattern:e,setting:r};return t!==void 0&&(s.secondaryPattern=t),o!==void 0&&(s.scope=o),i!==void 0&&(s.resourceIdentifier=i),await new Promise((n,a)=>{chrome.contentSettings.camera.set(s,()=>{chrome.runtime.lastError?a(new Error(chrome.runtime.lastError.message)):n();});}),this.formatSuccess("Camera content setting rule applied successfully",{primaryPattern:e,secondaryPattern:t,setting:r,scope:o||"regular"})}catch(s){return this.formatError(s)}});}registerClearCameraSetting(){this.server.registerTool("extension_tool_clear_camera_setting",{description:"Clear all camera content setting rules set by this extension",inputSchema:{scope:z.enum(["regular","incognito_session_only"]).optional().describe("Where to clear the setting")}},async({scope:e})=>{try{let t={};return e!==void 0&&(t.scope=e),await new Promise((r,o)=>{chrome.contentSettings.camera.clear(t,()=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r();});}),this.formatSuccess("All camera content setting rules cleared successfully",{scope:e||"regular"})}catch(t){return this.formatError(t)}});}registerGetMicrophoneSetting(){this.server.registerTool("extension_tool_get_microphone_setting",{description:"Get the current microphone content setting for a given pair of URLs",inputSchema:{primaryUrl:z.string().describe("The primary URL for which the content setting should be retrieved"),secondaryUrl:z.string().optional().describe("The secondary URL for which the content setting should be retrieved"),incognito:z.boolean().optional().describe("Whether to check the content settings for an incognito session"),resourceIdentifier:z.object({id:z.string(),description:z.string().optional()}).optional().describe("A more specific identifier of the type of content")}},async({primaryUrl:e,secondaryUrl:t,incognito:r,resourceIdentifier:o})=>{try{let i={primaryUrl:e};t!==void 0&&(i.secondaryUrl=t),r!==void 0&&(i.incognito=r),o!==void 0&&(i.resourceIdentifier=o);let s=await new Promise((n,a)=>{chrome.contentSettings.microphone.get(i,c=>{chrome.runtime.lastError?a(new Error(chrome.runtime.lastError.message)):n(c);});});return this.formatJson({primaryUrl:e,secondaryUrl:t,incognito:r||!1,setting:s.setting})}catch(i){return this.formatError(i)}});}registerSetMicrophoneSetting(){this.server.registerTool("extension_tool_set_microphone_setting",{description:"Set a new microphone content setting rule",inputSchema:{primaryPattern:z.string().describe("The pattern for the primary URL"),secondaryPattern:z.string().optional().describe("The pattern for the secondary URL"),setting:z.enum(["allow","block","ask"]).describe("The setting to apply"),scope:z.enum(["regular","incognito_session_only"]).optional().describe("Where to set the setting"),resourceIdentifier:z.object({id:z.string(),description:z.string().optional()}).optional().describe("The resource identifier for the content type")}},async({primaryPattern:e,secondaryPattern:t,setting:r,scope:o,resourceIdentifier:i})=>{try{let s={primaryPattern:e,setting:r};return t!==void 0&&(s.secondaryPattern=t),o!==void 0&&(s.scope=o),i!==void 0&&(s.resourceIdentifier=i),await new Promise((n,a)=>{chrome.contentSettings.microphone.set(s,()=>{chrome.runtime.lastError?a(new Error(chrome.runtime.lastError.message)):n();});}),this.formatSuccess("Microphone content setting rule applied successfully",{primaryPattern:e,secondaryPattern:t,setting:r,scope:o||"regular"})}catch(s){return this.formatError(s)}});}registerClearMicrophoneSetting(){this.server.registerTool("extension_tool_clear_microphone_setting",{description:"Clear all microphone content setting rules set by this extension",inputSchema:{scope:z.enum(["regular","incognito_session_only"]).optional().describe("Where to clear the setting")}},async({scope:e})=>{try{let t={};return e!==void 0&&(t.scope=e),await new Promise((r,o)=>{chrome.contentSettings.microphone.clear(t,()=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r();});}),this.formatSuccess("All microphone content setting rules cleared successfully",{scope:e||"regular"})}catch(t){return this.formatError(t)}});}registerGetAutomaticDownloadsSetting(){this.server.registerTool("extension_tool_get_automatic_downloads_setting",{description:"Get the current automatic downloads content setting for a given pair of URLs",inputSchema:{primaryUrl:z.string().describe("The primary URL for which the content setting should be retrieved"),secondaryUrl:z.string().optional().describe("The secondary URL for which the content setting should be retrieved"),incognito:z.boolean().optional().describe("Whether to check the content settings for an incognito session"),resourceIdentifier:z.object({id:z.string(),description:z.string().optional()}).optional().describe("A more specific identifier of the type of content")}},async({primaryUrl:e,secondaryUrl:t,incognito:r,resourceIdentifier:o})=>{try{let i={primaryUrl:e};t!==void 0&&(i.secondaryUrl=t),r!==void 0&&(i.incognito=r),o!==void 0&&(i.resourceIdentifier=o);let s=await new Promise((n,a)=>{chrome.contentSettings.automaticDownloads.get(i,c=>{chrome.runtime.lastError?a(new Error(chrome.runtime.lastError.message)):n(c);});});return this.formatJson({primaryUrl:e,secondaryUrl:t,incognito:r||!1,setting:s.setting})}catch(i){return this.formatError(i)}});}registerSetAutomaticDownloadsSetting(){this.server.registerTool("extension_tool_set_automatic_downloads_setting",{description:"Set a new automatic downloads content setting rule",inputSchema:{primaryPattern:z.string().describe("The pattern for the primary URL"),secondaryPattern:z.string().optional().describe("The pattern for the secondary URL"),setting:z.enum(["allow","block","ask"]).describe("The setting to apply"),scope:z.enum(["regular","incognito_session_only"]).optional().describe("Where to set the setting"),resourceIdentifier:z.object({id:z.string(),description:z.string().optional()}).optional().describe("The resource identifier for the content type")}},async({primaryPattern:e,secondaryPattern:t,setting:r,scope:o,resourceIdentifier:i})=>{try{let s={primaryPattern:e,setting:r};return t!==void 0&&(s.secondaryPattern=t),o!==void 0&&(s.scope=o),i!==void 0&&(s.resourceIdentifier=i),await new Promise((n,a)=>{chrome.contentSettings.automaticDownloads.set(s,()=>{chrome.runtime.lastError?a(new Error(chrome.runtime.lastError.message)):n();});}),this.formatSuccess("Automatic downloads content setting rule applied successfully",{primaryPattern:e,secondaryPattern:t,setting:r,scope:o||"regular"})}catch(s){return this.formatError(s)}});}registerClearAutomaticDownloadsSetting(){this.server.registerTool("extension_tool_clear_automatic_downloads_setting",{description:"Clear all automatic downloads content setting rules set by this extension",inputSchema:{scope:z.enum(["regular","incognito_session_only"]).optional().describe("Where to clear the setting")}},async({scope:e})=>{try{let t={};return e!==void 0&&(t.scope=e),await new Promise((r,o)=>{chrome.contentSettings.automaticDownloads.clear(t,()=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r();});}),this.formatSuccess("All automatic downloads content setting rules cleared successfully",{scope:e||"regular"})}catch(t){return this.formatError(t)}});}registerGetClipboardSetting(){this.server.registerTool("extension_tool_get_clipboard_setting",{description:"Get the current clipboard content setting for a given pair of URLs",inputSchema:{primaryUrl:z.string().describe("The primary URL for which the content setting should be retrieved"),secondaryUrl:z.string().optional().describe("The secondary URL for which the content setting should be retrieved"),incognito:z.boolean().optional().describe("Whether to check the content settings for an incognito session"),resourceIdentifier:z.object({id:z.string(),description:z.string().optional()}).optional().describe("A more specific identifier of the type of content")}},async({primaryUrl:e,secondaryUrl:t,incognito:r,resourceIdentifier:o})=>{try{let i={primaryUrl:e};t!==void 0&&(i.secondaryUrl=t),r!==void 0&&(i.incognito=r),o!==void 0&&(i.resourceIdentifier=o);let s=await new Promise((n,a)=>{chrome.contentSettings.clipboard.get(i,c=>{chrome.runtime.lastError?a(new Error(chrome.runtime.lastError.message)):n(c);});});return this.formatJson({primaryUrl:e,secondaryUrl:t,incognito:r||!1,setting:s.setting})}catch(i){return this.formatError(i)}});}registerSetClipboardSetting(){this.server.registerTool("extension_tool_set_clipboard_setting",{description:"Set a new clipboard content setting rule",inputSchema:{primaryPattern:z.string().describe("The pattern for the primary URL"),secondaryPattern:z.string().optional().describe("The pattern for the secondary URL"),setting:z.enum(["allow","block","ask"]).describe("The setting to apply"),scope:z.enum(["regular","incognito_session_only"]).optional().describe("Where to set the setting"),resourceIdentifier:z.object({id:z.string(),description:z.string().optional()}).optional().describe("The resource identifier for the content type")}},async({primaryPattern:e,secondaryPattern:t,setting:r,scope:o,resourceIdentifier:i})=>{try{let s={primaryPattern:e,setting:r};return t!==void 0&&(s.secondaryPattern=t),o!==void 0&&(s.scope=o),i!==void 0&&(s.resourceIdentifier=i),await new Promise((n,a)=>{chrome.contentSettings.clipboard.set(s,()=>{chrome.runtime.lastError?a(new Error(chrome.runtime.lastError.message)):n();});}),this.formatSuccess("Clipboard content setting rule applied successfully",{primaryPattern:e,secondaryPattern:t,setting:r,scope:o||"regular"})}catch(s){return this.formatError(s)}});}registerClearClipboardSetting(){this.server.registerTool("extension_tool_clear_clipboard_setting",{description:"Clear all clipboard content setting rules set by this extension",inputSchema:{scope:z.enum(["regular","incognito_session_only"]).optional().describe("Where to clear the setting")}},async({scope:e})=>{try{let t={};return e!==void 0&&(t.scope=e),await new Promise((r,o)=>{chrome.contentSettings.clipboard.clear(t,()=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r();});}),this.formatSuccess("All clipboard content setting rules cleared successfully",{scope:e||"regular"})}catch(t){return this.formatError(t)}});}registerGetAutoVerifySetting(){this.server.registerTool("extension_tool_get_auto_verify_setting",{description:"Get the current auto verify content setting for a given pair of URLs",inputSchema:{primaryUrl:z.string().describe("The primary URL for which the content setting should be retrieved"),secondaryUrl:z.string().optional().describe("The secondary URL for which the content setting should be retrieved"),incognito:z.boolean().optional().describe("Whether to check the content settings for an incognito session"),resourceIdentifier:z.object({id:z.string(),description:z.string().optional()}).optional().describe("A more specific identifier of the type of content")}},async({primaryUrl:e,secondaryUrl:t,incognito:r,resourceIdentifier:o})=>{try{let i={primaryUrl:e};t!==void 0&&(i.secondaryUrl=t),r!==void 0&&(i.incognito=r),o!==void 0&&(i.resourceIdentifier=o);let s=await new Promise((n,a)=>{chrome.contentSettings.autoVerify.get(i,c=>{chrome.runtime.lastError?a(new Error(chrome.runtime.lastError.message)):n(c);});});return this.formatJson({primaryUrl:e,secondaryUrl:t,incognito:r||!1,setting:s.setting})}catch(i){return this.formatError(i)}});}registerSetAutoVerifySetting(){this.server.registerTool("extension_tool_set_auto_verify_setting",{description:"Set a new auto verify content setting rule",inputSchema:{primaryPattern:z.string().describe("The pattern for the primary URL"),secondaryPattern:z.string().optional().describe("The pattern for the secondary URL"),setting:z.enum(["allow","block"]).describe("The setting to apply"),scope:z.enum(["regular","incognito_session_only"]).optional().describe("Where to set the setting"),resourceIdentifier:z.object({id:z.string(),description:z.string().optional()}).optional().describe("The resource identifier for the content type")}},async({primaryPattern:e,secondaryPattern:t,setting:r,scope:o,resourceIdentifier:i})=>{try{let s={primaryPattern:e,setting:r};return t!==void 0&&(s.secondaryPattern=t),o!==void 0&&(s.scope=o),i!==void 0&&(s.resourceIdentifier=i),await new Promise((n,a)=>{chrome.contentSettings.autoVerify.set(s,()=>{chrome.runtime.lastError?a(new Error(chrome.runtime.lastError.message)):n();});}),this.formatSuccess("Auto verify content setting rule applied successfully",{primaryPattern:e,secondaryPattern:t,setting:r,scope:o||"regular"})}catch(s){return this.formatError(s)}});}registerClearAutoVerifySetting(){this.server.registerTool("extension_tool_clear_auto_verify_setting",{description:"Clear all auto verify content setting rules set by this extension",inputSchema:{scope:z.enum(["regular","incognito_session_only"]).optional().describe("Where to clear the setting")}},async({scope:e})=>{try{let t={};return e!==void 0&&(t.scope=e),await new Promise((r,o)=>{chrome.contentSettings.autoVerify.clear(t,()=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r();});}),this.formatSuccess("All auto verify content setting rules cleared successfully",{scope:e||"regular"})}catch(t){return this.formatError(t)}});}registerGetPluginsResourceIdentifiers(){this.server.registerTool("extension_tool_get_plugins_resource_identifiers",{description:"Get a list of resource identifiers for the plugins content type",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.contentSettings.plugins.getResourceIdentifiers(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({count:e?.length||0,resourceIdentifiers:e||[]})}catch(e){return this.formatError(e)}});}};var Ue=class extends m{apiName="ContextMenus";constructor(e,t={}){super(e,t);}checkAvailability(){try{if(!chrome.contextMenus)return {available:!1,message:"chrome.contextMenus API is not defined",details:'This extension needs the "contextMenus" permission in its manifest.json'};if(typeof chrome.contextMenus.create!="function")return {available:!1,message:"chrome.contextMenus.create is not available",details:"The contextMenus API appears to be partially available. Check manifest permissions."};try{chrome.contextMenus.removeAll(()=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)});}catch{}return {available:!0,message:"ContextMenus API is fully available"}}catch(e){return {available:false,message:"Failed to access chrome.contextMenus API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("createContextMenu")&&this.registerCreateContextMenu(),this.shouldRegisterTool("updateContextMenu")&&this.registerUpdateContextMenu(),this.shouldRegisterTool("removeContextMenu")&&this.registerRemoveContextMenu(),this.shouldRegisterTool("removeAllContextMenus")&&this.registerRemoveAllContextMenus();}registerCreateContextMenu(){this.server.registerTool("extension_tool_create_context_menu",{description:"Create a new context menu item that appears when right-clicking on web pages",inputSchema:{id:z.string().optional().describe("Unique ID for this menu item. If not provided, one will be generated"),title:z.string().optional().describe("Text to display in the menu item. Required unless type is separator. Use %s to show selected text"),type:z.enum(["normal","checkbox","radio","separator"]).optional().describe("Type of menu item. Defaults to normal"),contexts:z.array(z.enum(["all","page","frame","selection","link","editable","image","video","audio","launcher","browser_action","page_action","action"])).optional().describe("Contexts where this menu item appears. Defaults to [page]"),checked:z.boolean().optional().describe("Initial state for checkbox or radio items"),enabled:z.boolean().optional().describe("Whether the menu item is enabled. Defaults to true"),visible:z.boolean().optional().describe("Whether the menu item is visible. Defaults to true"),parentId:z.union([z.string(),z.number()]).optional().describe("ID of parent menu item to create a submenu"),documentUrlPatterns:z.array(z.string()).optional().describe("URL patterns where this item should appear"),targetUrlPatterns:z.array(z.string()).optional().describe("URL patterns for link/media targets")}},async({id:e,title:t,type:r,contexts:o,checked:i,enabled:s,visible:n,parentId:a,documentUrlPatterns:c,targetUrlPatterns:u})=>{try{if(r!=="separator"&&!t)return this.formatError("Title is required unless type is separator");let d={};e!==void 0&&(d.id=e),t!==void 0&&(d.title=t),r!==void 0&&(d.type=r),o!==void 0&&(d.contexts=o),i!==void 0&&(d.checked=i),s!==void 0&&(d.enabled=s),n!==void 0&&(d.visible=n),a!==void 0&&(d.parentId=a),c!==void 0&&(d.documentUrlPatterns=c),u!==void 0&&(d.targetUrlPatterns=u);let v=await new Promise((S,P)=>{let I=chrome.contextMenus.create(d,()=>{chrome.runtime.lastError?P(new Error(chrome.runtime.lastError.message)):S(I);});});return this.formatSuccess("Context menu item created successfully",{id:v,title:t||"(separator)",type:r||"normal",contexts:o||["page"],enabled:s!==!1,visible:n!==!1})}catch(d){return this.formatError(d)}});}registerUpdateContextMenu(){this.server.registerTool("extension_tool_update_context_menu",{description:"Update an existing context menu item",inputSchema:{id:z.union([z.string(),z.number()]).describe("ID of the menu item to update"),title:z.string().optional().describe("New title for the menu item"),type:z.enum(["normal","checkbox","radio","separator"]).optional().describe("New type for the menu item"),contexts:z.array(z.enum(["all","page","frame","selection","link","editable","image","video","audio","launcher","browser_action","page_action","action"])).optional().describe("New contexts for the menu item"),checked:z.boolean().optional().describe("New checked state for checkbox or radio items"),enabled:z.boolean().optional().describe("Whether the menu item should be enabled"),visible:z.boolean().optional().describe("Whether the menu item should be visible"),parentId:z.union([z.string(),z.number()]).optional().describe("New parent ID for the menu item"),documentUrlPatterns:z.array(z.string()).optional().describe("New document URL patterns"),targetUrlPatterns:z.array(z.string()).optional().describe("New target URL patterns")}},async({id:e,title:t,type:r,contexts:o,checked:i,enabled:s,visible:n,parentId:a,documentUrlPatterns:c,targetUrlPatterns:u})=>{try{let d={};return t!==void 0&&(d.title=t),r!==void 0&&(d.type=r),o!==void 0&&(d.contexts=o),i!==void 0&&(d.checked=i),s!==void 0&&(d.enabled=s),n!==void 0&&(d.visible=n),a!==void 0&&(d.parentId=a),c!==void 0&&(d.documentUrlPatterns=c),u!==void 0&&(d.targetUrlPatterns=u),await new Promise((v,S)=>{chrome.contextMenus.update(e,d,()=>{chrome.runtime.lastError?S(new Error(chrome.runtime.lastError.message)):v();});}),this.formatSuccess("Context menu item updated successfully",{id:e,updatedProperties:Object.keys(d)})}catch(d){return this.formatError(d)}});}registerRemoveContextMenu(){this.server.registerTool("extension_tool_remove_context_menu",{description:"Remove a specific context menu item",inputSchema:{id:z.union([z.string(),z.number()]).describe("ID of the menu item to remove")}},async({id:e})=>{try{return await new Promise((t,r)=>{chrome.contextMenus.remove(e,()=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t();});}),this.formatSuccess("Context menu item removed successfully",{id:e})}catch(t){return this.formatError(t)}});}registerRemoveAllContextMenus(){this.server.registerTool("extension_tool_remove_all_context_menus",{description:"Remove all context menu items created by this extension",inputSchema:{}},async()=>{try{return await new Promise((e,t)=>{chrome.contextMenus.removeAll(()=>{chrome.runtime.lastError?t(new Error(chrome.runtime.lastError.message)):e();});}),this.formatSuccess("All context menu items removed successfully")}catch(e){return this.formatError(e)}});}};var Le=class extends m{apiName="Cookies";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.cookies?typeof chrome.cookies.getAllCookieStores!="function"?{available:!1,message:"chrome.cookies.getAllCookieStores is not available",details:"The cookies API appears to be partially available. Check manifest permissions."}:(chrome.cookies.getAllCookieStores(e=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"Cookies API is fully available"}):{available:!1,message:"chrome.cookies API is not defined",details:'This extension needs the "cookies" permission and appropriate host permissions in its manifest.json'}}catch(e){return {available:false,message:"Failed to access chrome.cookies API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("getCookie")&&this.registerGetCookie(),this.shouldRegisterTool("getAllCookies")&&this.registerGetAllCookies(),this.shouldRegisterTool("getAllCookieStores")&&this.registerGetAllCookieStores(),this.shouldRegisterTool("getPartitionKey")&&this.registerGetPartitionKey(),this.shouldRegisterTool("setCookie")&&this.registerSetCookie(),this.shouldRegisterTool("removeCookie")&&this.registerRemoveCookie();}registerGetCookie(){this.server.registerTool("extension_tool_get_cookie",{description:"Retrieve information about a single cookie by name and URL",inputSchema:{url:z.string().describe("The URL with which the cookie is associated"),name:z.string().describe("The name of the cookie to retrieve"),storeId:z.string().optional().describe("The ID of the cookie store to search in"),partitionKey:z.object({topLevelSite:z.string().optional(),hasCrossSiteAncestor:z.boolean().optional()}).optional().describe("The partition key for partitioned cookies")}},async({url:e,name:t,storeId:r,partitionKey:o})=>{try{let i={url:e,name:t};r!==void 0&&(i.storeId=r),o!==void 0&&(i.partitionKey=o);let s=await new Promise((n,a)=>{chrome.cookies.get(i,c=>{chrome.runtime.lastError?a(new Error(chrome.runtime.lastError.message)):n(c??void 0);});});return s?this.formatJson({name:s.name,value:s.value,domain:s.domain,path:s.path,secure:s.secure,httpOnly:s.httpOnly,sameSite:s.sameSite,session:s.session,expirationDate:s.expirationDate,hostOnly:s.hostOnly,storeId:s.storeId,partitionKey:s.partitionKey}):this.formatSuccess("No cookie found",{name:t,url:e})}catch(i){return this.formatError(i)}});}registerGetAllCookies(){this.server.registerTool("extension_tool_get_all_cookies",{description:"Retrieve all cookies that match the given criteria",inputSchema:{url:z.string().optional().describe("Restricts cookies to those that would match the given URL"),domain:z.string().optional().describe("Restricts cookies to those whose domains match or are subdomains of this one"),name:z.string().optional().describe("Filters the cookies by name"),path:z.string().optional().describe("Restricts cookies to those whose path exactly matches this string"),secure:z.boolean().optional().describe("Filters cookies by their Secure property"),session:z.boolean().optional().describe("Filters out session vs. persistent cookies"),storeId:z.string().optional().describe("The cookie store to retrieve cookies from"),partitionKey:z.object({topLevelSite:z.string().optional(),hasCrossSiteAncestor:z.boolean().optional()}).optional().describe("The partition key for partitioned cookies")}},async({url:e,domain:t,name:r,path:o,secure:i,session:s,storeId:n,partitionKey:a})=>{try{let c={};e!==void 0&&(c.url=e),t!==void 0&&(c.domain=t),r!==void 0&&(c.name=r),o!==void 0&&(c.path=o),i!==void 0&&(c.secure=i),s!==void 0&&(c.session=s),n!==void 0&&(c.storeId=n),a!==void 0&&(c.partitionKey=a);let u=await new Promise((d,v)=>{chrome.cookies.getAll(c,S=>{chrome.runtime.lastError?v(new Error(chrome.runtime.lastError.message)):d(S);});});return this.formatJson({count:u.length,cookies:u.map(d=>({name:d.name,value:d.value,domain:d.domain,path:d.path,secure:d.secure,httpOnly:d.httpOnly,sameSite:d.sameSite,session:d.session,expirationDate:d.expirationDate,hostOnly:d.hostOnly,storeId:d.storeId,partitionKey:d.partitionKey}))})}catch(c){return this.formatError(c)}});}registerGetAllCookieStores(){this.server.registerTool("extension_tool_get_all_cookie_stores",{description:"List all existing cookie stores",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.cookies.getAllCookieStores(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({count:e.length,cookieStores:e.map(t=>({id:t.id,tabIds:t.tabIds}))})}catch(e){return this.formatError(e)}});}registerGetPartitionKey(){this.server.registerTool("extension_tool_get_partition_key",{description:"Get the partition key for a specific frame",inputSchema:{tabId:z.number().optional().describe("The unique identifier for the tab containing the frame"),frameId:z.number().optional().describe("The unique identifier for the frame within the tab"),documentId:z.string().optional().describe("The unique identifier for the document")}},async({tabId:e,frameId:t,documentId:r})=>{try{let o={};e!==void 0&&(o.tabId=e),t!==void 0&&(o.frameId=t),r!==void 0&&(o.documentId=r);let i=await new Promise((s,n)=>{chrome.cookies.getPartitionKey(o,a=>{chrome.runtime.lastError?n(new Error(chrome.runtime.lastError.message)):s(a);});});return this.formatJson({partitionKey:i.partitionKey})}catch(o){return this.formatError(o)}});}registerSetCookie(){this.server.registerTool("extension_tool_set_cookie",{description:"Set a cookie with the given data; may overwrite equivalent cookies if they exist",inputSchema:{url:z.string().describe("The request-URI to associate with the setting of the cookie"),name:z.string().optional().describe("The name of the cookie. Empty by default if omitted"),value:z.string().optional().describe("The value of the cookie. Empty by default if omitted"),domain:z.string().optional().describe("The domain of the cookie. If omitted, the cookie becomes a host-only cookie"),path:z.string().optional().describe("The path of the cookie. Defaults to the path portion of the url parameter"),secure:z.boolean().optional().describe("Whether the cookie should be marked as Secure. Defaults to false"),httpOnly:z.boolean().optional().describe("Whether the cookie should be marked as HttpOnly. Defaults to false"),sameSite:z.enum(["no_restriction","lax","strict","unspecified"]).optional().describe("The cookie's same-site status"),expirationDate:z.number().optional().describe("The expiration date of the cookie as the number of seconds since the UNIX epoch"),storeId:z.string().optional().describe("The ID of the cookie store in which to set the cookie"),partitionKey:z.object({topLevelSite:z.string().optional(),hasCrossSiteAncestor:z.boolean().optional()}).optional().describe("The partition key for partitioned cookies")}},async({url:e,name:t,value:r,domain:o,path:i,secure:s,httpOnly:n,sameSite:a,expirationDate:c,storeId:u,partitionKey:d})=>{try{let v={url:e};t!==void 0&&(v.name=t),r!==void 0&&(v.value=r),o!==void 0&&(v.domain=o),i!==void 0&&(v.path=i),s!==void 0&&(v.secure=s),n!==void 0&&(v.httpOnly=n),a!==void 0&&(v.sameSite=a),c!==void 0&&(v.expirationDate=c),u!==void 0&&(v.storeId=u),d!==void 0&&(v.partitionKey=d);let S=await new Promise((P,I)=>{chrome.cookies.set(v,O=>{chrome.runtime.lastError?I(new Error(chrome.runtime.lastError.message)):P(O??void 0);});});return S?this.formatSuccess("Cookie set successfully",{name:S.name,value:S.value,domain:S.domain,path:S.path,secure:S.secure,httpOnly:S.httpOnly,sameSite:S.sameSite,session:S.session,expirationDate:S.expirationDate,hostOnly:S.hostOnly,storeId:S.storeId,partitionKey:S.partitionKey}):this.formatError("Failed to set cookie")}catch(v){return this.formatError(v)}});}registerRemoveCookie(){this.server.registerTool("extension_tool_remove_cookie",{description:"Delete a cookie by name",inputSchema:{url:z.string().describe("The URL with which the cookie to remove is associated"),name:z.string().describe("The name of the cookie to remove"),storeId:z.string().optional().describe("The ID of the cookie store to look in"),partitionKey:z.object({topLevelSite:z.string().optional(),hasCrossSiteAncestor:z.boolean().optional()}).optional().describe("The partition key for partitioned cookies")}},async({url:e,name:t,storeId:r,partitionKey:o})=>{try{let i={url:e,name:t};r!==void 0&&(i.storeId=r),o!==void 0&&(i.partitionKey=o);let s=await new Promise((n,a)=>{chrome.cookies.remove(i,c=>{chrome.runtime.lastError?a(new Error(chrome.runtime.lastError.message)):n(c);});});return s?this.formatSuccess("Cookie removed successfully",{name:s.name,url:s.url,storeId:s.storeId,partitionKey:s.partitionKey}):this.formatSuccess("No cookie found to remove",{name:t,url:e})}catch(i){return this.formatError(i)}});}};var Me=class extends m{apiName="Debugger";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.debugger?typeof chrome.debugger.getTargets!="function"?{available:!1,message:"chrome.debugger.getTargets is not available",details:"The debugger API appears to be partially available. Check manifest permissions."}:(chrome.debugger.getTargets(e=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"Debugger API is fully available"}):{available:!1,message:"chrome.debugger API is not defined",details:'This extension needs the "debugger" permission in its manifest.json'}}catch(e){return {available:false,message:"Failed to access chrome.debugger API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("attach")&&this.registerAttach(),this.shouldRegisterTool("detach")&&this.registerDetach(),this.shouldRegisterTool("sendCommand")&&this.registerSendCommand(),this.shouldRegisterTool("getTargets")&&this.registerGetTargets();}registerAttach(){this.server.registerTool("extension_tool_attach_debugger",{description:"Attach debugger to a target (tab, extension, or target ID)",inputSchema:{tabId:z.number().optional().describe("The ID of the tab to debug"),extensionId:z.string().optional().describe("The ID of the extension to debug"),targetId:z.string().optional().describe("The opaque ID of the debug target"),requiredVersion:z.string().default("1.3").describe("Required debugging protocol version (default: 1.3)")}},async({tabId:e,extensionId:t,targetId:r,requiredVersion:o})=>{try{if(e===void 0&&t===void 0&&r===void 0)return this.formatError("Either tabId, extensionId, or targetId must be specified to attach debugger");let i={};return e!==void 0&&(i.tabId=e),t!==void 0&&(i.extensionId=t),r!==void 0&&(i.targetId=r),await new Promise((s,n)=>{chrome.debugger.attach(i,o,()=>{chrome.runtime.lastError?n(new Error(chrome.runtime.lastError.message)):s();});}),this.formatSuccess("Debugger attached successfully",{target:i,protocolVersion:o})}catch(i){return this.formatError(i)}});}registerDetach(){this.server.registerTool("extension_tool_detach_debugger",{description:"Detach debugger from a target",inputSchema:{tabId:z.number().optional().describe("The ID of the tab to detach from"),extensionId:z.string().optional().describe("The ID of the extension to detach from"),targetId:z.string().optional().describe("The opaque ID of the debug target to detach from")}},async({tabId:e,extensionId:t,targetId:r})=>{try{if(e===void 0&&t===void 0&&r===void 0)return this.formatError("Either tabId, extensionId, or targetId must be specified to detach debugger");let o={};return e!==void 0&&(o.tabId=e),t!==void 0&&(o.extensionId=t),r!==void 0&&(o.targetId=r),await new Promise((i,s)=>{chrome.debugger.detach(o,()=>{chrome.runtime.lastError?s(new Error(chrome.runtime.lastError.message)):i();});}),this.formatSuccess("Debugger detached successfully",{target:o})}catch(o){return this.formatError(o)}});}registerSendCommand(){this.server.registerTool("extension_tool_send_debugger_command",{description:"Send a Chrome DevTools Protocol command to a debugging target",inputSchema:{tabId:z.number().optional().describe("The ID of the tab target"),extensionId:z.string().optional().describe("The ID of the extension target"),targetId:z.string().optional().describe("The opaque ID of the debug target"),sessionId:z.string().optional().describe("The session ID for child protocol sessions"),method:z.string().describe("CDP method name (e.g., Runtime.evaluate, Page.navigate)"),commandParams:z.record(z.any()).optional().describe("Parameters for the CDP command")}},async({tabId:e,extensionId:t,targetId:r,sessionId:o,method:i,commandParams:s})=>{try{if(e===void 0&&t===void 0&&r===void 0)return this.formatError("Either tabId, extensionId, or targetId must be specified to send command");let n={};e!==void 0&&(n.tabId=e),t!==void 0&&(n.extensionId=t),r!==void 0&&(n.targetId=r),o!==void 0&&(n.sessionId=o);let a=await new Promise((c,u)=>{chrome.debugger.sendCommand(n,i,s,d=>{chrome.runtime.lastError?u(new Error(chrome.runtime.lastError.message)):c(d);});});return this.formatJson({method:i,target:n,result:a||null})}catch(n){return this.formatError(n)}});}registerGetTargets(){this.server.registerTool("extension_tool_get_debug_targets",{description:"Get list of available debug targets",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.debugger.getTargets(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({count:e.length,targets:e.map(t=>({id:t.id,type:t.type,title:t.title,url:t.url,attached:t.attached,tabId:t.tabId,extensionId:t.extensionId,faviconUrl:t.faviconUrl}))})}catch(e){return this.formatError(e)}});}};var Ne=class extends m{apiName="DeclarativeContent";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.declarativeContent?chrome.declarativeContent.onPageChanged?typeof chrome.declarativeContent.PageStateMatcher!="function"?{available:!1,message:"chrome.declarativeContent.PageStateMatcher constructor is not available",details:"The declarativeContent API constructors are not accessible."}:{available:!0,message:"DeclarativeContent API is fully available"}:{available:!1,message:"chrome.declarativeContent.onPageChanged is not available",details:"The declarativeContent API appears to be partially available. Check manifest permissions."}:{available:!1,message:"chrome.declarativeContent API is not defined",details:'This extension needs the "declarativeContent" permission in its manifest.json'}}catch(e){return {available:false,message:"Failed to access chrome.declarativeContent API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("addRules")&&this.registerAddRules(),this.shouldRegisterTool("removeRules")&&this.registerRemoveRules(),this.shouldRegisterTool("getRules")&&this.registerGetRules();}registerAddRules(){this.server.registerTool("extension_tool_add_declarative_rules",{description:"Add declarative content rules to control when the extension action is enabled",inputSchema:{rules:z.array(z.object({id:z.string().optional().describe("Optional unique identifier for this rule"),conditions:z.array(z.object({pageUrl:z.object({hostContains:z.string().optional().describe("Matches if the host contains this string"),hostEquals:z.string().optional().describe("Matches if the host equals this string"),hostPrefix:z.string().optional().describe("Matches if the host starts with this string"),hostSuffix:z.string().optional().describe("Matches if the host ends with this string"),pathContains:z.string().optional().describe("Matches if the path contains this string"),pathEquals:z.string().optional().describe("Matches if the path equals this string"),pathPrefix:z.string().optional().describe("Matches if the path starts with this string"),pathSuffix:z.string().optional().describe("Matches if the path ends with this string"),queryContains:z.string().optional().describe("Matches if the query contains this string"),queryEquals:z.string().optional().describe("Matches if the query equals this string"),queryPrefix:z.string().optional().describe("Matches if the query starts with this string"),querySuffix:z.string().optional().describe("Matches if the query ends with this string"),urlContains:z.string().optional().describe("Matches if the URL contains this string"),urlEquals:z.string().optional().describe("Matches if the URL equals this string"),urlMatches:z.string().optional().describe("Matches if the URL matches this regular expression"),urlPrefix:z.string().optional().describe("Matches if the URL starts with this string"),urlSuffix:z.string().optional().describe("Matches if the URL ends with this string"),schemes:z.array(z.string()).optional().describe("Matches if the scheme is in this list"),ports:z.array(z.number()).optional().describe("Matches if the port is in this list")}).optional().describe("URL matching criteria"),css:z.array(z.string()).optional().describe("CSS selectors that must match displayed elements"),isBookmarked:z.boolean().optional().describe("Whether the page must be bookmarked (requires bookmarks permission)")})).describe("Conditions that must be met for the rule to trigger"),actions:z.array(z.object({type:z.enum(["ShowAction","SetIcon"]).describe("Type of action to perform"),imageData:z.record(z.string()).optional().describe("Icon image data for SetIcon action")})).describe("Actions to perform when conditions are met")})).describe("Array of declarative content rules to add")}},async({rules:e})=>{try{let t=e.map(r=>{let o={conditions:r.conditions.map(i=>{let s={};return i.pageUrl&&(s.pageUrl=i.pageUrl),i.css&&(s.css=i.css),i.isBookmarked!==void 0&&(s.isBookmarked=i.isBookmarked),new chrome.declarativeContent.PageStateMatcher(s)}),actions:r.actions.map(i=>{if(i.type==="ShowAction")return new chrome.declarativeContent.ShowAction;if(i.type==="SetIcon"){let s={};return i.imageData&&(s.imageData=i.imageData),new chrome.declarativeContent.SetIcon(s)}throw new Error(`Unknown action type: ${i.type}`)})};return r.id&&(o.id=r.id),o});return await new Promise((r,o)=>{chrome.declarativeContent.onPageChanged.addRules(t,()=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r();});}),this.formatSuccess("Declarative content rules added successfully",{rulesAdded:e.length,ruleIds:e.map(r=>r.id).filter(Boolean)})}catch(t){return this.formatError(t)}});}registerRemoveRules(){this.server.registerTool("extension_tool_remove_declarative_rules",{description:"Remove declarative content rules",inputSchema:{ruleIds:z.array(z.string()).optional().describe("Array of rule IDs to remove. If not specified, all rules are removed")}},async({ruleIds:e})=>{try{return await new Promise((t,r)=>{chrome.declarativeContent.onPageChanged.removeRules(e,()=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t();});}),e&&e.length>0?this.formatSuccess("Specified declarative content rules removed successfully",{removedRuleIds:e}):this.formatSuccess("All declarative content rules removed successfully")}catch(t){return this.formatError(t)}});}registerGetRules(){this.server.registerTool("extension_tool_get_declarative_rules",{description:"Get existing declarative content rules",inputSchema:{ruleIds:z.array(z.string()).optional().describe("Array of rule IDs to retrieve. If not specified, all rules are returned")}},async({ruleIds:e})=>{try{let t=await new Promise((r,o)=>{chrome.declarativeContent.onPageChanged.getRules(e,i=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r(i);});});return this.formatJson({count:t.length,rules:t.map(r=>({id:r.id,priority:r.priority,conditions:r.conditions?.length||0,actions:r.actions?.length||0,tags:r.tags}))})}catch(t){return this.formatError(t)}});}};var qe=class extends m{apiName="DeclarativeNetRequest";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.declarativeNetRequest?typeof chrome.declarativeNetRequest.getDynamicRules!="function"?{available:!1,message:"chrome.declarativeNetRequest.getDynamicRules is not available",details:"The declarativeNetRequest API appears to be partially available. Check manifest permissions."}:(chrome.declarativeNetRequest.getDynamicRules(e=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"DeclarativeNetRequest API is fully available"}):{available:!1,message:"chrome.declarativeNetRequest API is not defined",details:'This extension needs the "declarativeNetRequest" or "declarativeNetRequestWithHostAccess" permission in its manifest.json'}}catch(e){return {available:false,message:"Failed to access chrome.declarativeNetRequest API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("getDynamicRules")&&this.registerGetDynamicRules(),this.shouldRegisterTool("updateDynamicRules")&&this.registerUpdateDynamicRules(),this.shouldRegisterTool("getSessionRules")&&this.registerGetSessionRules(),this.shouldRegisterTool("updateSessionRules")&&this.registerUpdateSessionRules(),this.shouldRegisterTool("getEnabledRulesets")&&this.registerGetEnabledRulesets(),this.shouldRegisterTool("updateEnabledRulesets")&&this.registerUpdateEnabledRulesets(),this.shouldRegisterTool("updateStaticRules")&&this.registerUpdateStaticRules(),this.shouldRegisterTool("getAvailableStaticRuleCount")&&this.registerGetAvailableStaticRuleCount(),this.shouldRegisterTool("getMatchedRules")&&this.registerGetMatchedRules(),this.shouldRegisterTool("isRegexSupported")&&this.registerIsRegexSupported(),this.shouldRegisterTool("testMatchOutcome")&&this.registerTestMatchOutcome(),this.shouldRegisterTool("setExtensionActionOptions")&&this.registerSetExtensionActionOptions();}registerGetDynamicRules(){this.server.registerTool("extension_tool_get_dynamic_rules",{description:"Get the current set of dynamic rules for the extension"},async()=>{try{let e=await new Promise((t,r)=>{chrome.declarativeNetRequest.getDynamicRules(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({count:e.length,rules:e})}catch(e){return this.formatError(e)}});}registerUpdateDynamicRules(){this.server.registerTool("extension_tool_update_dynamic_rules",{description:"Modify the current set of dynamic rules for the extension",inputSchema:{removeRuleIds:z.array(z.number()).optional().describe("IDs of the rules to remove. Any invalid IDs will be ignored"),addRules:z.array(z.any()).optional().describe("Rules to add. Must follow the Rule schema")}},async({removeRuleIds:e,addRules:t})=>{try{let r={};return e!==void 0&&(r.removeRuleIds=e),t!==void 0&&(r.addRules=t),await new Promise((o,i)=>{chrome.declarativeNetRequest.updateDynamicRules(r,()=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o();});}),this.formatSuccess("Dynamic rules updated successfully",{removedCount:e?.length||0,addedCount:t?.length||0})}catch(r){return this.formatError(r)}});}registerGetSessionRules(){this.server.registerTool("extension_tool_get_session_rules",{description:"Get the current set of session scoped rules for the extension"},async()=>{try{let e=await new Promise((t,r)=>{chrome.declarativeNetRequest.getSessionRules(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({count:e.length,rules:e})}catch(e){return this.formatError(e)}});}registerUpdateSessionRules(){this.server.registerTool("extension_tool_update_session_rules",{description:"Modify the current set of session scoped rules for the extension",inputSchema:{removeRuleIds:z.array(z.number()).optional().describe("IDs of the rules to remove. Any invalid IDs will be ignored"),addRules:z.array(z.any()).optional().describe("Rules to add. Must follow the Rule schema")}},async({removeRuleIds:e,addRules:t})=>{try{let r={};return e!==void 0&&(r.removeRuleIds=e),t!==void 0&&(r.addRules=t),await new Promise((o,i)=>{chrome.declarativeNetRequest.updateSessionRules(r,()=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o();});}),this.formatSuccess("Session rules updated successfully",{removedCount:e?.length||0,addedCount:t?.length||0})}catch(r){return this.formatError(r)}});}registerGetEnabledRulesets(){this.server.registerTool("extension_tool_get_enabled_rulesets",{description:"Get the ids for the current set of enabled static rulesets",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.declarativeNetRequest.getEnabledRulesets(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({count:e.length,rulesetIds:e})}catch(e){return this.formatError(e)}});}registerUpdateEnabledRulesets(){this.server.registerTool("extension_tool_update_enabled_rulesets",{description:"Update the set of enabled static rulesets for the extension",inputSchema:{enableRulesetIds:z.array(z.string()).optional().describe("The set of ids corresponding to a static Ruleset that should be enabled"),disableRulesetIds:z.array(z.string()).optional().describe("The set of ids corresponding to a static Ruleset that should be disabled")}},async({enableRulesetIds:e,disableRulesetIds:t})=>{try{let r={};return e!==void 0&&(r.enableRulesetIds=e),t!==void 0&&(r.disableRulesetIds=t),await new Promise((o,i)=>{chrome.declarativeNetRequest.updateEnabledRulesets(r,()=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o();});}),this.formatSuccess("Enabled rulesets updated successfully",{enabledCount:e?.length||0,disabledCount:t?.length||0})}catch(r){return this.formatError(r)}});}registerUpdateStaticRules(){this.server.registerTool("extension_tool_update_static_rules",{description:"Disable and enable individual static rules in a Ruleset",inputSchema:{rulesetId:z.string().describe("The id corresponding to a static Ruleset"),enableRuleIds:z.array(z.number()).optional().describe("Set of ids corresponding to rules in the Ruleset to enable"),disableRuleIds:z.array(z.number()).optional().describe("Set of ids corresponding to rules in the Ruleset to disable")}},async({rulesetId:e,enableRuleIds:t,disableRuleIds:r})=>{try{let o={rulesetId:e};return t!==void 0&&(o.enableRuleIds=t),r!==void 0&&(o.disableRuleIds=r),await new Promise((i,s)=>{chrome.declarativeNetRequest.updateStaticRules(o,()=>{chrome.runtime.lastError?s(new Error(chrome.runtime.lastError.message)):i();});}),this.formatSuccess("Static rules updated successfully",{rulesetId:e,enabledCount:t?.length||0,disabledCount:r?.length||0})}catch(o){return this.formatError(o)}});}registerGetAvailableStaticRuleCount(){this.server.registerTool("extension_tool_get_available_static_rule_count",{description:"Get the number of static rules an extension can enable before the global static rule limit is reached",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.declarativeNetRequest.getAvailableStaticRuleCount(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({availableStaticRuleCount:e})}catch(e){return this.formatError(e)}});}registerGetMatchedRules(){this.server.registerTool("extension_tool_get_matched_rules",{description:'Get all rules matched for the extension. Requires "declarativeNetRequestFeedback" permission',inputSchema:{tabId:z.number().optional().describe("If specified, only matches rules for the given tab. Matches rules not associated with any active tab if set to -1"),minTimeStamp:z.number().optional().describe("If specified, only matches rules after the given timestamp")}},async({tabId:e,minTimeStamp:t})=>{try{let r={};e!==void 0&&(r.tabId=e),t!==void 0&&(r.minTimeStamp=t);let o=await new Promise((i,s)=>{chrome.declarativeNetRequest.getMatchedRules(r,n=>{chrome.runtime.lastError?s(new Error(chrome.runtime.lastError.message)):i(n);});});return this.formatJson({count:o.rulesMatchedInfo.length,rulesMatchedInfo:o.rulesMatchedInfo.map(i=>({rule:i.rule,tabId:i.tabId,timeStamp:i.timeStamp,timeStampFormatted:new Date(i.timeStamp).toISOString()}))})}catch(r){return this.formatError(r)}});}registerIsRegexSupported(){this.server.registerTool("extension_tool_is_regex_supported",{description:"Check if the given regular expression will be supported as a regexFilter rule condition",inputSchema:{regex:z.string().describe("The regular expression to check"),isCaseSensitive:z.boolean().optional().describe("Whether the regex specified is case sensitive. Default is true"),requireCapturing:z.boolean().optional().describe("Whether the regex specified requires capturing. Default is false")}},async({regex:e,isCaseSensitive:t,requireCapturing:r})=>{try{let o={regex:e};t!==void 0&&(o.isCaseSensitive=t),r!==void 0&&(o.requireCapturing=r);let i=await new Promise((s,n)=>{chrome.declarativeNetRequest.isRegexSupported(o,a=>{chrome.runtime.lastError?n(new Error(chrome.runtime.lastError.message)):s(a);});});return this.formatJson({regex:e,isSupported:i.isSupported,reason:i.reason})}catch(o){return this.formatError(o)}});}registerTestMatchOutcome(){this.server.registerTool("extension_tool_test_match_outcome",{description:"Check if any of the extension's declarativeNetRequest rules would match a hypothetical request. Only available for unpacked extensions",inputSchema:{url:z.string().describe("The URL of the hypothetical request"),type:z.string().describe("The resource type of the hypothetical request"),method:z.string().optional().describe('Standard HTTP method of the hypothetical request. Defaults to "get" for HTTP requests'),tabId:z.number().optional().describe("The ID of the tab in which the hypothetical request takes place. Default is -1"),initiator:z.string().optional().describe("The initiator URL (if any) for the hypothetical request"),responseHeaders:z.record(z.array(z.string())).optional().describe("The headers provided by a hypothetical response")}},async({url:e,type:t,method:r,tabId:o,initiator:i,responseHeaders:s})=>{try{let n={url:e,type:t};r!==void 0&&(n.method=r),o!==void 0&&(n.tabId=o),i!==void 0&&(n.initiator=i),s!==void 0&&(n.responseHeaders=s);let a=await new Promise((c,u)=>{chrome.declarativeNetRequest.testMatchOutcome(n,d=>{chrome.runtime.lastError?u(new Error(chrome.runtime.lastError.message)):c(d);});});return this.formatJson({url:e,matchedRulesCount:a.matchedRules.length,matchedRules:a.matchedRules})}catch(n){return this.formatError(n)}});}registerSetExtensionActionOptions(){this.server.registerTool("extension_tool_set_extension_action_options",{description:"Configure if the action count for tabs should be displayed as the extension action's badge text",inputSchema:{displayActionCountAsBadgeText:z.boolean().optional().describe("Whether to automatically display the action count for a page as the extension's badge text"),tabUpdateIncrement:z.number().optional().describe("The amount to increment the tab's action count by. Negative values will decrement the count"),tabUpdateTabId:z.number().optional().describe("The tab for which to update the action count")}},async({displayActionCountAsBadgeText:e,tabUpdateIncrement:t,tabUpdateTabId:r})=>{try{let o={};return e!==void 0&&(o.displayActionCountAsBadgeText=e),t!==void 0&&r!==void 0&&(o.tabUpdate={increment:t,tabId:r}),await new Promise((i,s)=>{chrome.declarativeNetRequest.setExtensionActionOptions(o,()=>{chrome.runtime.lastError?s(new Error(chrome.runtime.lastError.message)):i();});}),this.formatSuccess("Extension action options updated successfully",{displayActionCountAsBadgeText:e,tabUpdate:o.tabUpdate})}catch(o){return this.formatError(o)}});}};var Ge=class extends m{apiName="DesktopCapture";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.desktopCapture?typeof chrome.desktopCapture.chooseDesktopMedia!="function"?{available:!1,message:"chrome.desktopCapture.chooseDesktopMedia is not available",details:"The desktopCapture API appears to be partially available. Check manifest permissions."}:{available:!0,message:"DesktopCapture API is fully available"}:{available:!1,message:"chrome.desktopCapture API is not defined",details:'This extension needs the "desktopCapture" permission in its manifest.json'}}catch(e){return {available:false,message:"Failed to access chrome.desktopCapture API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("chooseDesktopMedia")&&this.registerChooseDesktopMedia(),this.shouldRegisterTool("cancelChooseDesktopMedia")&&this.registerCancelChooseDesktopMedia();}registerChooseDesktopMedia(){this.server.registerTool("extension_tool_choose_desktop_media",{description:"Shows desktop media picker UI with the specified set of sources",inputSchema:{sources:z.array(z.enum(["screen","window","tab","audio"])).describe("Set of sources that should be shown to the user. The sources order in the set decides the tab order in the picker"),targetTabId:z.number().describe("Optional tab ID for which the stream is created. If not specified then the resulting stream can be used only by the calling extension")}},async({sources:e,targetTabId:t})=>{try{let r;t!==void 0&&(r=await new Promise((i,s)=>{chrome.tabs.get(t,n=>{chrome.runtime.lastError?s(new Error(chrome.runtime.lastError.message)):i(n);});}));let o=await new Promise((i,s)=>{let n=chrome.desktopCapture.chooseDesktopMedia(e,r,(a,c)=>{chrome.runtime.lastError?s(new Error(chrome.runtime.lastError.message)):i({requestId:n,streamId:a,options:c});});});return o.streamId?this.formatJson({requestId:o.requestId,streamId:o.streamId,canRequestAudioTrack:o.options?.canRequestAudioTrack||!1,sources:e,targetTabId:t}):this.formatSuccess("User canceled the desktop media selection")}catch(r){return this.formatError(r)}});}registerCancelChooseDesktopMedia(){this.server.registerTool("extension_tool_cancel_choose_desktop_media",{description:"Hides desktop media picker dialog shown by chooseDesktopMedia",inputSchema:{desktopMediaRequestId:z.number().describe("Id returned by chooseDesktopMedia()")}},async({desktopMediaRequestId:e})=>{try{return chrome.desktopCapture.cancelChooseDesktopMedia(e),this.formatSuccess("Desktop media picker dialog canceled successfully",{requestId:e})}catch(t){return this.formatError(t)}});}};var Fe=class extends m{apiName="Devtools.inspectedWindow";constructor(e,t={}){super(e,t);}checkAvailability(){try{return !chrome.devtools||!chrome.devtools.inspectedWindow?{available:!1,message:"chrome.devtools.inspectedWindow API is not defined",details:'This extension needs to be running in a devtools context and have the "devtools" permission in its manifest.json'}:typeof chrome.devtools.inspectedWindow.eval!="function"?{available:!1,message:"chrome.devtools.inspectedWindow.eval is not available",details:"The devtools.inspectedWindow API appears to be partially available. Check manifest permissions and devtools context."}:{available:!0,message:"Devtools.inspectedWindow API is fully available"}}catch(e){return {available:false,message:"Failed to access chrome.devtools.inspectedWindow API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("eval")&&this.registerEval(),this.shouldRegisterTool("reload")&&this.registerReload(),this.shouldRegisterTool("getResources")&&this.registerGetResources();}registerEval(){this.server.registerTool("extension_tool_eval_inspected_window",{description:"Evaluate JavaScript expression in the context of the inspected page",inputSchema:{expression:z.string().describe("JavaScript expression to evaluate in the inspected page"),options:z.object({frameURL:z.string().optional().describe("URL of the frame to evaluate in. If omitted, evaluates in the main frame"),contextSecurityOrigin:z.string().optional().describe("Security origin for the evaluation context"),useContentScriptContext:z.boolean().optional().describe("If true, evaluate in the context of a content script")}).optional().describe("Options for the evaluation")}},async({expression:e,options:t})=>{try{let r=await new Promise((s,n)=>{let a={};t?.frameURL!==void 0&&(a.frameURL=t.frameURL),t?.contextSecurityOrigin!==void 0&&(a.contextSecurityOrigin=t.contextSecurityOrigin),t?.useContentScriptContext!==void 0&&(a.useContentScriptContext=t.useContentScriptContext),chrome.devtools.inspectedWindow.eval(e,Object.keys(a).length>0?a:void 0,(c,u)=>{chrome.runtime.lastError?n(new Error(chrome.runtime.lastError.message)):s([c,u]);});}),[o,i]=r;return i?this.formatJson({success:!1,expression:e,exception:{isError:i.isError,code:i.code,description:i.description,details:i.details,isException:i.isException,value:i.value}}):this.formatJson({success:!0,expression:e,result:o})}catch(r){return this.formatError(r)}});}registerReload(){this.server.registerTool("extension_tool_reload_inspected_window",{description:"Reload the inspected page",inputSchema:{reloadOptions:z.object({ignoreCache:z.boolean().optional().describe("If true, reload ignoring cache"),userAgent:z.string().optional().describe("Custom user agent string to use for the reload"),injectedScript:z.string().optional().describe("Script to inject into every frame of the inspected page immediately upon load")}).optional().describe("Options for the reload")}},async({reloadOptions:e})=>{try{let t={};return e?.ignoreCache!==void 0&&(t.ignoreCache=e.ignoreCache),e?.userAgent!==void 0&&(t.userAgent=e.userAgent),e?.injectedScript!==void 0&&(t.injectedScript=e.injectedScript),chrome.devtools.inspectedWindow.reload(Object.keys(t).length>0?t:void 0),this.formatSuccess("Inspected window reload initiated",{options:e||{}})}catch(t){return this.formatError(t)}});}registerGetResources(){this.server.registerTool("extension_tool_get_inspected_window_resources",{description:"Get all resources loaded by the inspected page",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.devtools.inspectedWindow.getResources(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({count:e.length,resources:e.map(t=>({url:t.url}))})}catch(e){return this.formatError(e)}});}};var Be=class extends m{apiName="Devtools.network";constructor(e,t={}){super(e,t);}checkAvailability(){try{return !chrome.devtools||!chrome.devtools.network?{available:!1,message:"chrome.devtools.network API is not defined",details:'This extension needs to be running in a devtools context and have the "devtools" permission in its manifest.json'}:typeof chrome.devtools.network.getHAR!="function"?{available:!1,message:"chrome.devtools.network.getHAR is not available",details:"The devtools.network API appears to be partially available. Check manifest permissions and ensure running in devtools context."}:(chrome.devtools.network.getHAR(e=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"Devtools.network API is fully available"})}catch(e){return {available:false,message:"Failed to access chrome.devtools.network API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("getHAR")&&this.registerGetHAR(),this.shouldRegisterTool("onNavigated")&&this.registerOnNavigated(),this.shouldRegisterTool("onRequestFinished")&&this.registerOnRequestFinished();}registerGetHAR(){this.server.registerTool("extension_tool_get_har",{description:"Get the HTTP Archive (HAR) log for the current page, containing all network requests",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.devtools.network.getHAR(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({version:e.version,creator:e.creator,browser:e.browser,pages:e.pages?.map(t=>({startedDateTime:t.startedDateTime,id:t.id,title:t.title,pageTimings:t.pageTimings})),entries:e.entries?.map(t=>({startedDateTime:t.startedDateTime,time:t.time,request:{method:t.request.method,url:t.request.url,httpVersion:t.request.httpVersion,headers:t.request.headers,queryString:t.request.queryString,postData:t.request.postData,headersSize:t.request.headersSize,bodySize:t.request.bodySize},response:{status:t.response.status,statusText:t.response.statusText,httpVersion:t.response.httpVersion,headers:t.response.headers,content:{size:t.response.content.size,mimeType:t.response.content.mimeType,compression:t.response.content.compression},redirectURL:t.response.redirectURL,headersSize:t.response.headersSize,bodySize:t.response.bodySize},cache:t.cache,timings:t.timings,serverIPAddress:t.serverIPAddress,connection:t.connection})),totalEntries:e.entries?.length||0})}catch(e){return this.formatError(e)}});}registerOnNavigated(){this.server.registerTool("extension_tool_on_navigated",{description:"Set up a listener for navigation events in the inspected window",inputSchema:{enable:z.boolean().optional().describe("Whether to enable or disable the navigation listener")}},async({enable:e=true})=>{try{if(e){let t=r=>{console.log("Navigation detected to:",r);};return chrome.devtools.network.onNavigated.addListener(t),this.formatSuccess("Navigation listener enabled",{listening:!0,event:"onNavigated"})}return chrome.devtools.network.onNavigated.removeListener(()=>{}),this.formatSuccess("Navigation listener disabled",{listening:!1,event:"onNavigated"})}catch(t){return this.formatError(t)}});}registerOnRequestFinished(){this.server.registerTool("extension_tool_on_request_finished",{description:"Set up a listener for network request completion events",inputSchema:{enable:z.boolean().optional().describe("Whether to enable or disable the request finished listener")}},async({enable:e=true})=>{try{if(e){let t=r=>{console.log("Request finished:",{url:r.request.url,method:r.request.method,status:r.response.status,time:r.time});};return chrome.devtools.network.onRequestFinished.addListener(t),this.formatSuccess("Request finished listener enabled",{listening:!0,event:"onRequestFinished"})}return chrome.devtools.network.onRequestFinished.removeListener(()=>{}),this.formatSuccess("Request finished listener disabled",{listening:!1,event:"onRequestFinished"})}catch(t){return this.formatError(t)}});}};var We=class extends m{apiName="Devtools.panels";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.devtools?.panels?typeof chrome.devtools.panels.create!="function"?{available:!1,message:"chrome.devtools.panels.create is not available",details:"The devtools.panels API appears to be partially available. Check manifest permissions and context."}:{available:!0,message:"Devtools.panels API is fully available"}:{available:!1,message:"chrome.devtools.panels API is not defined",details:'This extension needs to be running in a devtools context and have the "devtools" permission in its manifest.json'}}catch(e){return {available:false,message:"Failed to access chrome.devtools.panels API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("createPanel")&&this.registerCreatePanel(),this.shouldRegisterTool("createSidebarPane")&&this.registerCreateSidebarPane(),this.shouldRegisterTool("getThemeColor")&&this.registerGetThemeColor(),this.shouldRegisterTool("openResource")&&this.registerOpenResource(),this.shouldRegisterTool("setOpenResourceHandler")&&this.registerSetOpenResourceHandler();}registerCreatePanel(){this.server.registerTool("extension_tool_create_panel",{description:"Create a new devtools panel with specified title and icon",inputSchema:{title:z.string().describe("The title of the panel"),iconPath:z.string().describe("Path to the icon for the panel"),pagePath:z.string().describe("Path to the HTML page that will be displayed in the panel")}},async({title:e,iconPath:t,pagePath:r})=>{try{return await new Promise((o,i)=>{chrome.devtools.panels.create(e,t,r,s=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o(s);});}),this.formatSuccess("Panel created successfully",{title:e,iconPath:t,pagePath:r,panelCreated:!0})}catch(o){return this.formatError(o)}});}registerCreateSidebarPane(){this.server.registerTool("extension_tool_create_sidebar_pane",{description:"Create a sidebar pane in the Elements panel",inputSchema:{title:z.string().describe("The title of the sidebar pane")}},async({title:e})=>{try{return await new Promise((t,r)=>{chrome.devtools.panels.elements.createSidebarPane(e,o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});}),this.formatSuccess("Sidebar pane created successfully",{title:e,sidebarPaneCreated:!0})}catch(t){return this.formatError(t)}});}registerGetThemeColor(){this.server.registerTool("extension_tool_get_theme_color",{description:"Get the current theme color of the devtools",inputSchema:{}},async()=>{try{let e=chrome.devtools.panels.themeName;return this.formatJson({themeName:e,description:e==="dark"?"Dark theme is active":"Light theme is active"})}catch(e){return this.formatError(e)}});}registerOpenResource(){this.server.registerTool("extension_tool_open_resource",{description:"Open a resource in the Sources panel",inputSchema:{url:z.string().describe("URL of the resource to open"),lineNumber:z.number().optional().describe("Line number to navigate to (1-based)")}},async({url:e,lineNumber:t})=>{try{return await new Promise((r,o)=>{t!==void 0?chrome.devtools.panels.openResource(e,t,()=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r();}):chrome.devtools.panels.openResource(e,1,()=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r();});}),this.formatSuccess("Resource opened successfully",{url:e,lineNumber:t||"not specified"})}catch(r){return this.formatError(r)}});}registerSetOpenResourceHandler(){this.server.registerTool("extension_tool_set_open_resource_handler",{description:"Set a handler for when resources are opened in the devtools",inputSchema:{enable:z.boolean().describe("Whether to enable or disable the open resource handler")}},async({enable:e})=>{try{return e?(chrome.devtools.panels.setOpenResourceHandler(t=>(console.log("Resource opened:",t),!0)),this.formatSuccess("Open resource handler enabled",{handlerEnabled:!0})):(chrome.devtools.panels.setOpenResourceHandler(void 0),this.formatSuccess("Open resource handler disabled",{handlerEnabled:!1}))}catch(t){return this.formatError(t)}});}};var Je=class extends m{apiName="DocumentScan";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.documentScan?typeof chrome.documentScan.scan!="function"?{available:!1,message:"chrome.documentScan.scan is not available",details:"The documentScan API appears to be partially available. Check manifest permissions and ensure you are running on ChromeOS."}:{available:!0,message:"DocumentScan API is fully available"}:{available:!1,message:"chrome.documentScan API is not defined",details:'This extension needs the "documentScan" permission in its manifest.json and only works on ChromeOS'}}catch(e){return {available:false,message:"Failed to access chrome.documentScan API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("scan")&&this.registerScan(),this.shouldRegisterTool("getScannerList")&&this.registerGetScannerList(),this.shouldRegisterTool("openScanner")&&this.registerOpenScanner(),this.shouldRegisterTool("closeScanner")&&this.registerCloseScanner(),this.shouldRegisterTool("getOptionGroups")&&this.registerGetOptionGroups(),this.shouldRegisterTool("setOptions")&&this.registerSetOptions(),this.shouldRegisterTool("startScan")&&this.registerStartScan(),this.shouldRegisterTool("readScanData")&&this.registerReadScanData(),this.shouldRegisterTool("cancelScan")&&this.registerCancelScan();}registerScan(){this.server.registerTool("extension_tool_document_scan",{description:"Perform a simple document scan using any available scanner",inputSchema:{maxImages:z.number().min(1).optional().describe("The number of scanned images allowed. Default is 1"),mimeTypes:z.array(z.string()).optional().describe('The MIME types that are accepted by the caller (e.g., ["image/jpeg", "image/png"])')}},async({maxImages:e,mimeTypes:t})=>{try{let r={};e!==void 0&&(r.maxImages=e),t!==void 0&&(r.mimeTypes=t);let o=await new Promise((i,s)=>{chrome.documentScan.scan(r,n=>{chrome.runtime.lastError?s(new Error(chrome.runtime.lastError.message)):i(n);});});return this.formatJson({mimeType:o.mimeType,imageCount:o.dataUrls.length,dataUrls:o.dataUrls})}catch(r){return this.formatError(r)}});}registerGetScannerList(){this.server.registerTool("extension_tool_get_scanner_list",{description:"Get the list of available document scanners",inputSchema:{local:z.boolean().optional().describe("Only return scanners that are directly attached to the computer"),secure:z.boolean().optional().describe("Only return scanners that use a secure transport, such as USB or TLS")}},async({local:e,secure:t})=>{try{let r={};e!==void 0&&(r.local=e),t!==void 0&&(r.secure=t);let o=await new Promise((i,s)=>{chrome.documentScan.getScannerList(r,n=>{chrome.runtime.lastError?s(new Error(chrome.runtime.lastError.message)):i(n);});});return this.formatJson({result:o.result,scannerCount:o.scanners.length,scanners:o.scanners.map(i=>({scannerId:i.scannerId,name:i.name,manufacturer:i.manufacturer,model:i.model,deviceUuid:i.deviceUuid,connectionType:i.connectionType,protocolType:i.protocolType,secure:i.secure,imageFormats:i.imageFormats}))})}catch(r){return this.formatError(r)}});}registerOpenScanner(){this.server.registerTool("extension_tool_open_scanner",{description:"Open a scanner for exclusive access and configuration",inputSchema:{scannerId:z.string().describe("The ID of a scanner to be opened (from getScannerList)")}},async({scannerId:e})=>{try{let t=await new Promise((o,i)=>{chrome.documentScan.openScanner(e,s=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o(s);});}),r={result:t.result,scannerId:t.scannerId};return t.scannerHandle&&(r.scannerHandle=t.scannerHandle),t.options&&(r.optionCount=Object.keys(t.options).length,r.availableOptions=Object.keys(t.options)),this.formatJson(r)}catch(t){return this.formatError(t)}});}registerCloseScanner(){this.server.registerTool("extension_tool_close_scanner",{description:"Close a previously opened scanner",inputSchema:{scannerHandle:z.string().describe("The handle of an open scanner from openScanner")}},async({scannerHandle:e})=>{try{let t=await new Promise((r,o)=>{chrome.documentScan.closeScanner(e,i=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r(i);});});return this.formatJson({result:t.result,scannerHandle:t.scannerHandle})}catch(t){return this.formatError(t)}});}registerGetOptionGroups(){this.server.registerTool("extension_tool_get_option_groups",{description:"Get the group names and member options from an open scanner",inputSchema:{scannerHandle:z.string().describe("The handle of an open scanner from openScanner")}},async({scannerHandle:e})=>{try{let t=await new Promise((o,i)=>{chrome.documentScan.getOptionGroups(e,s=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o(s);});}),r={result:t.result,scannerHandle:t.scannerHandle};return t.groups&&(r.groupCount=t.groups.length,r.groups=t.groups.map(o=>({title:o.title,memberCount:o.members.length,members:o.members}))),this.formatJson(r)}catch(t){return this.formatError(t)}});}registerSetOptions(){this.server.registerTool("extension_tool_set_scanner_options",{description:"Set options on a scanner",inputSchema:{scannerHandle:z.string().describe("The handle of an open scanner from openScanner"),options:z.array(z.object({name:z.string().describe("The name of the option to set"),type:z.enum(["UNKNOWN","BOOL","INT","FIXED","STRING","BUTTON","GROUP"]).describe("The data type of the option"),value:z.union([z.string(),z.number(),z.boolean(),z.array(z.number())]).optional().describe("The value to set (leave unset for automatic setting)")})).describe("Array of option settings to apply")}},async({scannerHandle:e,options:t})=>{try{let r=t.map(s=>{let n={name:s.name,type:s.type};return s.value!==void 0&&(n.value=s.value),n}),o=await new Promise((s,n)=>{chrome.documentScan.setOptions(e,r,a=>{chrome.runtime.lastError?n(new Error(chrome.runtime.lastError.message)):s(a);});}),i={scannerHandle:o.scannerHandle,results:o.results.map(s=>({name:s.name,result:s.result}))};return o.options&&(i.updatedOptionCount=Object.keys(o.options).length,i.updatedOptions=Object.keys(o.options)),this.formatJson(i)}catch(r){return this.formatError(r)}});}registerStartScan(){this.server.registerTool("extension_tool_start_scan",{description:"Start a scan on an open scanner",inputSchema:{scannerHandle:z.string().describe("The handle of an open scanner from openScanner"),format:z.string().describe('The MIME type to return scanned data in (e.g., "image/jpeg")'),maxReadSize:z.number().min(32768).optional().describe("Maximum bytes returned in a single readScanData response (minimum 32768)")}},async({scannerHandle:e,format:t,maxReadSize:r})=>{try{let o={format:t};r!==void 0&&(o.maxReadSize=r);let i=await new Promise((n,a)=>{chrome.documentScan.startScan(e,o,c=>{chrome.runtime.lastError?a(new Error(chrome.runtime.lastError.message)):n(c);});}),s={result:i.result,scannerHandle:i.scannerHandle};return i.job&&(s.job=i.job),this.formatJson(s)}catch(o){return this.formatError(o)}});}registerReadScanData(){this.server.registerTool("extension_tool_read_scan_data",{description:"Read the next chunk of scan data from an active scan job",inputSchema:{job:z.string().describe("Active job handle from startScan")}},async({job:e})=>{try{let t=await new Promise((o,i)=>{chrome.documentScan.readScanData(e,s=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o(s);});}),r={job:t.job,result:t.result};return t.data&&(r.dataSize=t.data.byteLength,r.hasData=t.data.byteLength>0),t.estimatedCompletion!==void 0&&(r.estimatedCompletion=t.estimatedCompletion),this.formatJson(r)}catch(t){return this.formatError(t)}});}registerCancelScan(){this.server.registerTool("extension_tool_cancel_scan",{description:"Cancel an active scan job",inputSchema:{job:z.string().describe("The handle of an active scan job from startScan")}},async({job:e})=>{try{let t=await new Promise((r,o)=>{chrome.documentScan.cancelScan(e,i=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r(i);});});return this.formatJson({job:t.job,result:t.result})}catch(t){return this.formatError(t)}});}};var ze=class extends m{apiName="Dom";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.dom?typeof chrome.dom.openOrClosedShadowRoot!="function"?{available:!1,message:"chrome.dom.openOrClosedShadowRoot is not available",details:"The dom API appears to be partially available. Check Chrome version (88+) and context."}:{available:!0,message:"Dom API is fully available"}:{available:!1,message:"chrome.dom API is not defined",details:"This extension needs to be running in a content script context"}}catch(e){return {available:false,message:"Failed to access chrome.dom API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("openOrClosedShadowRoot")&&this.registerOpenOrClosedShadowRoot();}registerOpenOrClosedShadowRoot(){this.server.registerTool("extension_tool_open_or_closed_shadow_root",{description:"Gets the open shadow root or the closed shadow root hosted by the specified element",inputSchema:{elementSelector:z.string().describe("CSS selector to find the element that hosts the shadow root"),elementIndex:z.number().optional().default(0).describe("Index of the element if multiple elements match the selector (default: 0)")}},async({elementSelector:e,elementIndex:t=0})=>{try{let r=document.querySelectorAll(e);if(r.length===0)return this.formatError(`No elements found matching selector: ${e}`);if(t>=r.length)return this.formatError(`Element index ${t} is out of range. Found ${r.length} elements.`);let o=r[t];if(!o)return this.formatError("Selected element is not an HTMLElement");let i=chrome.dom.openOrClosedShadowRoot(o);if(!i)return this.formatSuccess("No shadow root found on the specified element",{elementSelector:e,elementIndex:t,tagName:o.tagName,id:o.id||null,className:o.className||null});let s={mode:i.mode,delegatesFocus:i.delegatesFocus,slotAssignment:i.slotAssignment,childElementCount:i.childElementCount,innerHTML:i.innerHTML,textContent:i.textContent,children:Array.from(i.children).map((n,a)=>({index:a,tagName:n.tagName,id:n.id||null,className:n.className||null,textContent:n.textContent?.substring(0,100)||null}))};return this.formatJson({found:!0,elementSelector:e,elementIndex:t,element:{tagName:o.tagName,id:o.id||null,className:o.className||null},shadowRoot:s})}catch(r){return this.formatError(r)}});}};var He=class extends m{apiName="Downloads";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.downloads?typeof chrome.downloads.search!="function"?{available:!1,message:"chrome.downloads.search is not available",details:"The downloads API appears to be partially available. Check manifest permissions."}:(chrome.downloads.search({},e=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"Downloads API is fully available"}):{available:!1,message:"chrome.downloads API is not defined",details:'This extension needs the "downloads" permission in its manifest.json'}}catch(e){return {available:false,message:"Failed to access chrome.downloads API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("download")&&this.registerDownload(),this.shouldRegisterTool("search")&&this.registerSearch(),this.shouldRegisterTool("pause")&&this.registerPause(),this.shouldRegisterTool("resume")&&this.registerResume(),this.shouldRegisterTool("cancel")&&this.registerCancel(),this.shouldRegisterTool("getFileIcon")&&this.registerGetFileIcon(),this.shouldRegisterTool("open")&&this.registerOpen(),this.shouldRegisterTool("show")&&this.registerShow(),this.shouldRegisterTool("showDefaultFolder")&&this.registerShowDefaultFolder(),this.shouldRegisterTool("erase")&&this.registerErase(),this.shouldRegisterTool("removeFile")&&this.registerRemoveFile(),this.shouldRegisterTool("acceptDanger")&&this.registerAcceptDanger(),this.shouldRegisterTool("setUiOptions")&&this.registerSetUiOptions();}registerDownload(){this.server.registerTool("extension_tool_download_file",{description:"Download a file from a URL",inputSchema:{url:z.string().url().describe("The URL to download"),filename:z.string().optional().describe("A file path relative to the Downloads directory to contain the downloaded file"),saveAs:z.boolean().optional().describe("Use a file-chooser to allow the user to select a filename"),method:z.enum(["GET","POST"]).optional().describe("The HTTP method to use if the URL uses the HTTP[S] protocol"),headers:z.array(z.object({name:z.string().describe("Name of the HTTP header"),value:z.string().describe("Value of the HTTP header")})).optional().describe("Extra HTTP headers to send with the request"),body:z.string().optional().describe("Post body"),conflictAction:z.enum(["uniquify","overwrite","prompt"]).optional().describe("The action to take if filename already exists")}},async({url:e,filename:t,saveAs:r,method:o,headers:i,body:s,conflictAction:n})=>{try{let a={url:e};t!==void 0&&(a.filename=t),r!==void 0&&(a.saveAs=r),o!==void 0&&(a.method=o),i!==void 0&&(a.headers=i),s!==void 0&&(a.body=s),n!==void 0&&(a.conflictAction=n);let c=await new Promise((u,d)=>{chrome.downloads.download(a,v=>{chrome.runtime.lastError?d(new Error(chrome.runtime.lastError.message)):u(v);});});return this.formatSuccess("Download started successfully",{downloadId:c,url:e,filename:t||"auto-generated"})}catch(a){return this.formatError(a)}});}registerSearch(){this.server.registerTool("extension_tool_search_downloads",{description:"Search for downloads matching specified criteria",inputSchema:{id:z.number().optional().describe("The id of the DownloadItem to query"),url:z.string().optional().describe("The absolute URL that this download initiated from"),urlRegex:z.string().optional().describe("Limits results to DownloadItem whose url matches the given regular expression"),filename:z.string().optional().describe("Absolute local path"),filenameRegex:z.string().optional().describe("Limits results to DownloadItem whose filename matches the given regular expression"),query:z.array(z.string()).optional().describe("Search terms that must be contained in filename or url. Terms beginning with dash are excluded"),state:z.enum(["in_progress","interrupted","complete"]).optional().describe("Indicates whether the download is progressing, interrupted, or complete"),danger:z.enum(["file","url","content","uncommon","host","unwanted","safe","accepted"]).optional().describe("Indication of whether this download is thought to be safe or suspicious"),mime:z.string().optional().describe("The file's MIME type"),startTime:z.string().optional().describe("The time when the download began in ISO 8601 format"),endTime:z.string().optional().describe("The time when the download ended in ISO 8601 format"),startedAfter:z.string().optional().describe("Limits results to DownloadItem that started after the given time in ISO 8601 format"),startedBefore:z.string().optional().describe("Limits results to DownloadItem that started before the given time in ISO 8601 format"),endedAfter:z.string().optional().describe("Limits results to DownloadItem that ended after the given time in ISO 8601 format"),endedBefore:z.string().optional().describe("Limits results to DownloadItem that ended before the given time in ISO 8601 format"),totalBytesGreater:z.number().optional().describe("Limits results to DownloadItem whose totalBytes is greater than the given integer"),totalBytesLess:z.number().optional().describe("Limits results to DownloadItem whose totalBytes is less than the given integer"),exists:z.boolean().optional().describe("Whether the downloaded file exists"),limit:z.number().optional().describe("The maximum number of matching DownloadItem returned. Defaults to 1000"),orderBy:z.array(z.string()).optional().describe("Set elements to DownloadItem properties to sort results. Prefix with hyphen for descending order")}},async e=>{try{let t={};e.id!==void 0&&(t.id=e.id),e.url!==void 0&&(t.url=e.url),e.urlRegex!==void 0&&(t.urlRegex=e.urlRegex),e.filename!==void 0&&(t.filename=e.filename),e.filenameRegex!==void 0&&(t.filenameRegex=e.filenameRegex),e.query!==void 0&&(t.query=e.query),e.state!==void 0&&(t.state=e.state),e.danger!==void 0&&(t.danger=e.danger),e.mime!==void 0&&(t.mime=e.mime),e.startTime!==void 0&&(t.startTime=e.startTime),e.endTime!==void 0&&(t.endTime=e.endTime),e.startedAfter!==void 0&&(t.startedAfter=e.startedAfter),e.startedBefore!==void 0&&(t.startedBefore=e.startedBefore),e.endedAfter!==void 0&&(t.endedAfter=e.endedAfter),e.endedBefore!==void 0&&(t.endedBefore=e.endedBefore),e.totalBytesGreater!==void 0&&(t.totalBytesGreater=e.totalBytesGreater),e.totalBytesLess!==void 0&&(t.totalBytesLess=e.totalBytesLess),e.exists!==void 0&&(t.exists=e.exists),e.limit!==void 0&&(t.limit=e.limit),e.orderBy!==void 0&&(t.orderBy=e.orderBy);let r=await new Promise((o,i)=>{chrome.downloads.search(t,s=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o(s);});});return this.formatJson({count:r.length,downloads:r.map(o=>({id:o.id,url:o.url,finalUrl:o.finalUrl,filename:o.filename,incognito:o.incognito,danger:o.danger,mime:o.mime,startTime:o.startTime,endTime:o.endTime,estimatedEndTime:o.estimatedEndTime,state:o.state,paused:o.paused,canResume:o.canResume,error:o.error,bytesReceived:o.bytesReceived,totalBytes:o.totalBytes,fileSize:o.fileSize,exists:o.exists,byExtensionId:o.byExtensionId,byExtensionName:o.byExtensionName}))})}catch(t){return this.formatError(t)}});}registerPause(){this.server.registerTool("extension_tool_pause_download",{description:"Pause a download",inputSchema:{downloadId:z.number().describe("The id of the download to pause")}},async({downloadId:e})=>{try{return await new Promise((t,r)=>{chrome.downloads.pause(e,()=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t();});}),this.formatSuccess("Download paused successfully",{downloadId:e})}catch(t){return this.formatError(t)}});}registerResume(){this.server.registerTool("extension_tool_resume_download",{description:"Resume a paused download",inputSchema:{downloadId:z.number().describe("The id of the download to resume")}},async({downloadId:e})=>{try{return await new Promise((t,r)=>{chrome.downloads.resume(e,()=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t();});}),this.formatSuccess("Download resumed successfully",{downloadId:e})}catch(t){return this.formatError(t)}});}registerCancel(){this.server.registerTool("extension_tool_cancel_download",{description:"Cancel a download",inputSchema:{downloadId:z.number().describe("The id of the download to cancel")}},async({downloadId:e})=>{try{return await new Promise((t,r)=>{chrome.downloads.cancel(e,()=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t();});}),this.formatSuccess("Download cancelled successfully",{downloadId:e})}catch(t){return this.formatError(t)}});}registerGetFileIcon(){this.server.registerTool("extension_tool_get_file_icon",{description:"Retrieve an icon for the specified download",inputSchema:{downloadId:z.number().describe("The identifier for the download"),size:z.number().optional().describe("The size of the returned icon. Supported sizes are 16 and 32. Default is 32")}},async({downloadId:e,size:t})=>{try{let r={};t!==void 0&&(r.size=t);let o=await new Promise((i,s)=>{chrome.downloads.getFileIcon(e,r,n=>{chrome.runtime.lastError?s(new Error(chrome.runtime.lastError.message)):i(n);});});return this.formatJson({downloadId:e,iconURL:o||null,size:t||32})}catch(r){return this.formatError(r)}});}registerOpen(){this.server.registerTool("extension_tool_open_download",{description:"Open the downloaded file if the download is complete",inputSchema:{downloadId:z.number().describe("The identifier for the downloaded file")}},async({downloadId:e})=>{try{return chrome.downloads.open(e),this.formatSuccess("Download opened successfully",{downloadId:e})}catch(t){return this.formatError(t)}});}registerShow(){this.server.registerTool("extension_tool_show_download",{description:"Show the downloaded file in its folder in a file manager",inputSchema:{downloadId:z.number().describe("The identifier for the downloaded file")}},async({downloadId:e})=>{try{return chrome.downloads.show(e),this.formatSuccess("Download shown in file manager",{downloadId:e})}catch(t){return this.formatError(t)}});}registerShowDefaultFolder(){this.server.registerTool("extension_tool_show_default_folder",{description:"Show the default Downloads folder in a file manager",inputSchema:{}},async()=>{try{return chrome.downloads.showDefaultFolder(),this.formatSuccess("Default Downloads folder shown in file manager")}catch(e){return this.formatError(e)}});}registerErase(){this.server.registerTool("extension_tool_erase_downloads",{description:"Erase matching downloads from history without deleting the downloaded files",inputSchema:{id:z.number().optional().describe("The id of the DownloadItem to erase"),url:z.string().optional().describe("The absolute URL that this download initiated from"),urlRegex:z.string().optional().describe("Limits results to DownloadItem whose url matches the given regular expression"),filename:z.string().optional().describe("Absolute local path"),filenameRegex:z.string().optional().describe("Limits results to DownloadItem whose filename matches the given regular expression"),state:z.enum(["in_progress","interrupted","complete"]).optional().describe("Indicates whether the download is progressing, interrupted, or complete"),danger:z.enum(["file","url","content","uncommon","host","unwanted","safe","accepted"]).optional().describe("Indication of whether this download is thought to be safe or suspicious"),mime:z.string().optional().describe("The file's MIME type"),startedAfter:z.string().optional().describe("Limits results to DownloadItem that started after the given time in ISO 8601 format"),startedBefore:z.string().optional().describe("Limits results to DownloadItem that started before the given time in ISO 8601 format"),endedAfter:z.string().optional().describe("Limits results to DownloadItem that ended after the given time in ISO 8601 format"),endedBefore:z.string().optional().describe("Limits results to DownloadItem that ended before the given time in ISO 8601 format"),limit:z.number().optional().describe("The maximum number of matching DownloadItem to erase")}},async e=>{try{let t={};e.id!==void 0&&(t.id=e.id),e.url!==void 0&&(t.url=e.url),e.urlRegex!==void 0&&(t.urlRegex=e.urlRegex),e.filename!==void 0&&(t.filename=e.filename),e.filenameRegex!==void 0&&(t.filenameRegex=e.filenameRegex),e.state!==void 0&&(t.state=e.state),e.danger!==void 0&&(t.danger=e.danger),e.mime!==void 0&&(t.mime=e.mime),e.startedAfter!==void 0&&(t.startedAfter=e.startedAfter),e.startedBefore!==void 0&&(t.startedBefore=e.startedBefore),e.endedAfter!==void 0&&(t.endedAfter=e.endedAfter),e.endedBefore!==void 0&&(t.endedBefore=e.endedBefore),e.limit!==void 0&&(t.limit=e.limit);let r=await new Promise((o,i)=>{chrome.downloads.erase(t,s=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o(s);});});return this.formatSuccess("Downloads erased from history successfully",{erasedCount:r.length,erasedIds:r})}catch(t){return this.formatError(t)}});}registerRemoveFile(){this.server.registerTool("extension_tool_remove_file",{description:"Remove the downloaded file if it exists and the download is complete",inputSchema:{downloadId:z.number().describe("The identifier for the downloaded file to remove")}},async({downloadId:e})=>{try{return await new Promise((t,r)=>{chrome.downloads.removeFile(e,()=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t();});}),this.formatSuccess("Downloaded file removed successfully",{downloadId:e})}catch(t){return this.formatError(t)}});}registerAcceptDanger(){this.server.registerTool("extension_tool_accept_danger",{description:"Prompt the user to accept a dangerous download",inputSchema:{downloadId:z.number().describe("The identifier for the DownloadItem")}},async({downloadId:e})=>{try{return await new Promise((t,r)=>{chrome.downloads.acceptDanger(e,()=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t();});}),this.formatSuccess("Dangerous download accepted",{downloadId:e})}catch(t){return this.formatError(t)}});}registerSetUiOptions(){this.server.registerTool("extension_tool_set_ui_options",{description:"Change the download UI of every window associated with the current browser profile",inputSchema:{enabled:z.boolean().describe("Enable or disable the download UI")}},async({enabled:e})=>{try{return await new Promise((t,r)=>{chrome.downloads.setUiOptions({enabled:e},()=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t();});}),this.formatSuccess("Download UI options updated successfully",{enabled:e})}catch(t){return this.formatError(t)}});}};var Ke=class extends m{apiName="Enterprise.deviceAttributes";constructor(e,t={}){super(e,t);}checkAvailability(){try{return !chrome.enterprise||!chrome.enterprise.deviceAttributes?{available:!1,message:"chrome.enterprise.deviceAttributes API is not defined",details:'This extension needs the "enterprise.deviceAttributes" permission in its manifest.json and must run on Chrome OS'}:typeof chrome.enterprise.deviceAttributes.getDirectoryDeviceId!="function"?{available:!1,message:"chrome.enterprise.deviceAttributes.getDirectoryDeviceId is not available",details:"The enterprise device attributes API appears to be partially available. Check manifest permissions and ensure this is running on Chrome OS."}:(chrome.enterprise.deviceAttributes.getDirectoryDeviceId(e=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"Enterprise Device Attributes API is fully available"})}catch(e){return {available:false,message:"Failed to access chrome.enterprise.deviceAttributes API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("getDirectoryDeviceId")&&this.registerGetDirectoryDeviceId(),this.shouldRegisterTool("getDeviceSerialNumber")&&this.registerGetDeviceSerialNumber(),this.shouldRegisterTool("getDeviceAssetId")&&this.registerGetDeviceAssetId(),this.shouldRegisterTool("getDeviceAnnotatedLocation")&&this.registerGetDeviceAnnotatedLocation(),this.shouldRegisterTool("getDeviceHostname")&&this.registerGetDeviceHostname();}registerGetDirectoryDeviceId(){this.server.registerTool("extension_tool_get_directory_device_id",{description:"Get the directory device ID for the Chrome OS device",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.enterprise.deviceAttributes.getDirectoryDeviceId(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({directoryDeviceId:e})}catch(e){return this.formatError(e)}});}registerGetDeviceSerialNumber(){this.server.registerTool("extension_tool_get_device_serial_number",{description:"Get the serial number of the Chrome OS device",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.enterprise.deviceAttributes.getDeviceSerialNumber(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({deviceSerialNumber:e})}catch(e){return this.formatError(e)}});}registerGetDeviceAssetId(){this.server.registerTool("extension_tool_get_device_asset_id",{description:"Get the asset ID of the Chrome OS device",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.enterprise.deviceAttributes.getDeviceAssetId(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({deviceAssetId:e})}catch(e){return this.formatError(e)}});}registerGetDeviceAnnotatedLocation(){this.server.registerTool("extension_tool_get_device_annotated_location",{description:"Get the annotated location of the Chrome OS device",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.enterprise.deviceAttributes.getDeviceAnnotatedLocation(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({deviceAnnotatedLocation:e})}catch(e){return this.formatError(e)}});}registerGetDeviceHostname(){this.server.registerTool("extension_tool_get_device_hostname",{description:"Get the hostname of the Chrome OS device",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.enterprise.deviceAttributes.getDeviceHostname(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({deviceHostname:e})}catch(e){return this.formatError(e)}});}};var $e=class extends m{apiName="Enterprise.hardwarePlatform";constructor(e,t={}){super(e,t);}checkAvailability(){try{return !chrome.enterprise||!chrome.enterprise.hardwarePlatform?{available:!1,message:"chrome.enterprise.hardwarePlatform API is not defined",details:'This extension needs the "enterprise.hardwarePlatform" permission in its manifest.json'}:typeof chrome.enterprise.hardwarePlatform.getHardwarePlatformInfo!="function"?{available:!1,message:"chrome.enterprise.hardwarePlatform.getHardwarePlatformInfo is not available",details:"The enterprise.hardwarePlatform API appears to be partially available. Check manifest permissions."}:(chrome.enterprise.hardwarePlatform.getHardwarePlatformInfo(e=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"Enterprise.hardwarePlatform API is fully available"})}catch(e){return {available:false,message:"Failed to access chrome.enterprise.hardwarePlatform API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("getHardwarePlatformInfo")&&this.registerGetHardwarePlatformInfo();}registerGetHardwarePlatformInfo(){this.server.registerTool("extension_tool_get_hardware_platform_info",{description:"Get hardware platform information for the device",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.enterprise.hardwarePlatform.getHardwarePlatformInfo(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({manufacturer:e.manufacturer,model:e.model})}catch(e){return this.formatError(e)}});}};var Ze=class extends m{apiName="Enterprise.networkingAttributes";constructor(e,t={}){super(e,t);}checkAvailability(){try{return !chrome.enterprise||!chrome.enterprise.networkingAttributes?{available:!1,message:"chrome.enterprise.networkingAttributes API is not defined",details:'This extension needs the "enterprise.networkingAttributes" permission in its manifest.json and must run on ChromeOS'}:typeof chrome.enterprise.networkingAttributes.getNetworkDetails!="function"?{available:!1,message:"chrome.enterprise.networkingAttributes.getNetworkDetails is not available",details:"The enterprise networking attributes API appears to be partially available. Check manifest permissions and platform compatibility."}:{available:!0,message:"Enterprise Networking Attributes API is fully available"}}catch(e){return {available:false,message:"Failed to access chrome.enterprise.networkingAttributes API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("getNetworkDetails")&&this.registerGetNetworkDetails();}registerGetNetworkDetails(){this.server.registerTool("extension_tool_get_network_details",{description:"Get network details for the current network connection including enterprise networking attributes",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.enterprise.networkingAttributes.getNetworkDetails(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({macAddress:e.macAddress,ipv4:e.ipv4,ipv6:e.ipv6})}catch(e){return this.formatError(e)}});}};var Ye=class extends m{apiName="Enterprise.platformKeys";constructor(e,t={}){super(e,t);}checkAvailability(){try{return !chrome.enterprise||!chrome.enterprise.platformKeys?{available:!1,message:"chrome.enterprise.platformKeys API is not defined",details:'This extension needs the "enterprise.platformKeys" permission in its manifest.json and must be running on ChromeOS'}:typeof chrome.enterprise.platformKeys.getTokens!="function"?{available:!1,message:"chrome.enterprise.platformKeys.getTokens is not available",details:"The enterprise.platformKeys API appears to be partially available. Check manifest permissions and ChromeOS platform."}:(chrome.enterprise.platformKeys.getTokens(e=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"Enterprise.platformKeys API is fully available"})}catch(e){return {available:false,message:"Failed to access chrome.enterprise.platformKeys API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("getTokens")&&this.registerGetTokens(),this.shouldRegisterTool("getCertificates")&&this.registerGetCertificates(),this.shouldRegisterTool("importCertificate")&&this.registerImportCertificate(),this.shouldRegisterTool("removeCertificate")&&this.registerRemoveCertificate(),this.shouldRegisterTool("challengeMachineKey")&&this.registerChallengeMachineKey(),this.shouldRegisterTool("challengeUserKey")&&this.registerChallengeUserKey();}registerGetTokens(){this.server.registerTool("extension_tool_get_tokens",{description:"Get the available platform keys tokens",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.enterprise.platformKeys.getTokens(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({count:e.length,tokens:e.map(t=>({id:t.id,subtleCrypto:!!t.subtleCrypto}))})}catch(e){return this.formatError(e)}});}registerGetCertificates(){this.server.registerTool("extension_tool_get_certificates",{description:"Get certificates from a platform keys token",inputSchema:{tokenId:z.string().describe("The ID of the token to get certificates from")}},async({tokenId:e})=>{try{if(!(await new Promise((i,s)=>{chrome.enterprise.platformKeys.getTokens(n=>{chrome.runtime.lastError?s(new Error(chrome.runtime.lastError.message)):i(n);});})).find(i=>i.id===e))return this.formatError(`Token with ID '${e}' not found`);let o=await new Promise((i,s)=>{chrome.enterprise.platformKeys.getCertificates(e,n=>{chrome.runtime.lastError?s(new Error(chrome.runtime.lastError.message)):i(n);});});return this.formatJson({tokenId:e,count:o.length,certificates:o.map((i,s)=>({index:s,size:i.byteLength,type:"ArrayBuffer"}))})}catch(t){return this.formatError(t)}});}registerImportCertificate(){this.server.registerTool("extension_tool_import_certificate",{description:"Import a certificate to a platform keys token",inputSchema:{tokenId:z.string().describe("The ID of the token to import the certificate to"),certificate:z.string().describe("The certificate data as a base64 encoded string")}},async({tokenId:e,certificate:t})=>{try{let r=atob(t),o=new Uint8Array(r.length);for(let s=0;s<r.length;s++)o[s]=r.charCodeAt(s);let i=o.buffer;return await new Promise((s,n)=>{chrome.enterprise.platformKeys.importCertificate(e,i,()=>{chrome.runtime.lastError?n(new Error(chrome.runtime.lastError.message)):s();});}),this.formatSuccess("Certificate imported successfully",{tokenId:e,certificateSize:i.byteLength})}catch(r){return this.formatError(r)}});}registerRemoveCertificate(){this.server.registerTool("extension_tool_remove_certificate",{description:"Remove a certificate from a platform keys token",inputSchema:{tokenId:z.string().describe("The ID of the token to remove the certificate from"),certificate:z.string().describe("The certificate data as a base64 encoded string")}},async({tokenId:e,certificate:t})=>{try{let r=atob(t),o=new Uint8Array(r.length);for(let s=0;s<r.length;s++)o[s]=r.charCodeAt(s);let i=o.buffer;return await new Promise((s,n)=>{chrome.enterprise.platformKeys.removeCertificate(e,i,()=>{chrome.runtime.lastError?n(new Error(chrome.runtime.lastError.message)):s();});}),this.formatSuccess("Certificate removed successfully",{tokenId:e,certificateSize:i.byteLength})}catch(r){return this.formatError(r)}});}registerChallengeMachineKey(){this.server.registerTool("extension_tool_challenge_machine_key",{description:"Challenge the machine key for enterprise attestation",inputSchema:{challenge:z.string().describe("The challenge data as a base64 encoded string"),registerKey:z.boolean().optional().describe("Whether to register the key if it does not exist")}},async({challenge:e,registerKey:t})=>{try{let r=atob(e),o=new Uint8Array(r.length);for(let c=0;c<r.length;c++)o[c]=r.charCodeAt(c);let i=o.buffer,s=await new Promise((c,u)=>{t!==void 0?chrome.enterprise.platformKeys.challengeMachineKey(i,t,d=>{chrome.runtime.lastError?u(new Error(chrome.runtime.lastError.message)):c(d);}):chrome.enterprise.platformKeys.challengeMachineKey(i,d=>{chrome.runtime.lastError?u(new Error(chrome.runtime.lastError.message)):c(d);});}),n=new Uint8Array(s),a=btoa(String.fromCharCode(...n));return this.formatJson({challengeSize:i.byteLength,responseSize:s.byteLength,response:a,registerKey:t||!1})}catch(r){return this.formatError(r)}});}registerChallengeUserKey(){this.server.registerTool("extension_tool_challenge_user_key",{description:"Challenge the user key for enterprise attestation",inputSchema:{challenge:z.string().describe("The challenge data as a base64 encoded string"),registerKey:z.boolean().describe("Whether to register the key if it does not exist")}},async({challenge:e,registerKey:t})=>{try{let r=atob(e),o=new Uint8Array(r.length);for(let c=0;c<r.length;c++)o[c]=r.charCodeAt(c);let i=o.buffer,s=await new Promise((c,u)=>{chrome.enterprise.platformKeys.challengeUserKey(i,t,d=>{chrome.runtime.lastError?u(new Error(chrome.runtime.lastError.message)):c(d);});}),n=new Uint8Array(s),a=btoa(String.fromCharCode(...n));return this.formatJson({challengeSize:i.byteLength,responseSize:s.byteLength,response:a,registerKey:t})}catch(r){return this.formatError(r)}});}};var Qe=class extends m{apiName="Extension";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.extension?typeof chrome.extension.getViews!="function"?{available:!1,message:"chrome.extension.getViews is not available",details:"The extension API appears to be partially available. Check extension context."}:(chrome.extension.getViews(),{available:!0,message:"Extension API is fully available"}):{available:!1,message:"chrome.extension API is not defined",details:"This extension needs to be running in a Chrome extension context"}}catch(e){return {available:false,message:"Failed to access chrome.extension API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("getBackgroundPage")&&this.registerGetBackgroundPage(),this.shouldRegisterTool("getViews")&&this.registerGetViews(),this.shouldRegisterTool("isAllowedFileSchemeAccess")&&this.registerIsAllowedFileSchemeAccess(),this.shouldRegisterTool("isAllowedIncognitoAccess")&&this.registerIsAllowedIncognitoAccess(),this.shouldRegisterTool("setUpdateUrlData")&&this.registerSetUpdateUrlData();}registerGetBackgroundPage(){this.server.registerTool("extension_tool_get_background_page",{description:"Returns the JavaScript window object for the background page running inside the current extension",inputSchema:{}},async()=>{try{let e=chrome.extension.getBackgroundPage();return e?this.formatSuccess("Background page retrieved successfully",{hasBackgroundPage:!0,location:e.location.href,title:e.document.title}):this.formatSuccess("No background page found",{hasBackgroundPage:!1})}catch(e){return this.formatError(e)}});}registerGetViews(){this.server.registerTool("extension_tool_get_views",{description:"Returns an array of the JavaScript window objects for each of the pages running inside the current extension",inputSchema:{tabId:z.number().optional().describe("Find a view according to a tab id. If omitted, returns all views"),type:z.enum(["tab","popup"]).optional().describe("The type of view to get. If omitted, returns all views including background pages and tabs"),windowId:z.number().optional().describe("The window to restrict the search to. If omitted, returns all views")}},async({tabId:e,type:t,windowId:r})=>{try{let o={};e!==void 0&&(o.tabId=e),t!==void 0&&(o.type=t),r!==void 0&&(o.windowId=r);let i=chrome.extension.getViews(Object.keys(o).length>0?o:void 0);return this.formatJson({count:i.length,views:i.map((s,n)=>({index:n,location:s.location.href,title:s.document.title,isBackground:s===chrome.extension.getBackgroundPage()}))})}catch(o){return this.formatError(o)}});}registerIsAllowedFileSchemeAccess(){this.server.registerTool("extension_tool_is_allowed_file_scheme_access",{description:`Retrieves the state of the extension's access to the file:// scheme. This corresponds to the user-controlled per-extension "Allow access to File URLs" setting`,inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.extension.isAllowedFileSchemeAccess(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({isAllowedFileSchemeAccess:e,message:e?"Extension has access to file:// URLs":"Extension does not have access to file:// URLs. This can be enabled in chrome://extensions"})}catch(e){return this.formatError(e)}});}registerIsAllowedIncognitoAccess(){this.server.registerTool("extension_tool_is_allowed_incognito_access",{description:`Retrieves the state of the extension's access to Incognito-mode. This corresponds to the user-controlled per-extension "Allowed in Incognito" setting`,inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.extension.isAllowedIncognitoAccess(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({isAllowedIncognitoAccess:e,inIncognitoContext:chrome.extension.inIncognitoContext,message:e?"Extension has access to Incognito mode":"Extension does not have access to Incognito mode. This can be enabled in chrome://extensions"})}catch(e){return this.formatError(e)}});}registerSetUpdateUrlData(){this.server.registerTool("extension_tool_set_update_url_data",{description:"Sets the value of the ap CGI parameter used in the extension's update URL. This value is ignored for extensions hosted in the Chrome Extension Gallery",inputSchema:{data:z.string().describe("The data to set for the update URL parameter")}},async({data:e})=>{try{return chrome.extension.setUpdateUrlData(e),this.formatSuccess("Update URL data set successfully",{data:e,note:"This value is ignored for extensions hosted in the Chrome Extension Gallery"})}catch(t){return this.formatError(t)}});}};var Xe=class extends m{apiName="FileBrowserHandler";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.fileBrowserHandler?typeof chrome.fileBrowserHandler.onExecute!="object"||typeof chrome.fileBrowserHandler.onExecute.addListener!="function"?{available:!1,message:"chrome.fileBrowserHandler.onExecute is not available",details:"The fileBrowserHandler API appears to be partially available. Check manifest permissions and ensure running on ChromeOS."}:navigator.userAgent.includes("CrOS")?{available:!0,message:"FileBrowserHandler API is fully available"}:{available:!1,message:"FileBrowserHandler API is only available on ChromeOS",details:"This API requires ChromeOS and proper file_browser_handlers configuration in manifest.json"}:{available:!1,message:"chrome.fileBrowserHandler API is not defined",details:'This extension needs the "fileBrowserHandler" permission in its manifest.json and must be running on ChromeOS'}}catch(e){return {available:false,message:"Failed to access chrome.fileBrowserHandler API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("getExecuteEventDetails")&&this.registerGetExecuteEventDetails(),this.shouldRegisterTool("addExecuteListener")&&this.registerAddExecuteListener(),this.shouldRegisterTool("removeExecuteListener")&&this.registerRemoveExecuteListener();}registerGetExecuteEventDetails(){this.server.registerTool("extension_tool_get_execute_event_details",{description:"Get information about the current file browser handler execute event details structure",inputSchema:{}},async()=>{try{return this.formatJson({eventStructure:{id:"string - The id value from the manifest file",details:{entries:"FileSystemFileEntry[] - Array of selected file entries",tab_id:"number (optional) - The ID of the tab that raised this event"}},usage:"Use addExecuteListener to register a handler for file browser execute events",note:"This API only works on ChromeOS and requires file_browser_handlers in manifest.json"})}catch(e){return this.formatError(e)}});}registerAddExecuteListener(){this.server.registerTool("extension_tool_add_execute_listener",{description:"Add a listener for file browser handler execute events. This will log events when users execute file browser actions.",inputSchema:{logEvents:z.boolean().optional().default(true).describe("Whether to log execute events to console")}},async({logEvents:e})=>{try{let t=(r,o)=>{e&&console.log("FileBrowserHandler execute event:",{id:r,entriesCount:o.entries?.length||0,tabId:o.tab_id,timestamp:new Date().toISOString()});};return chrome.fileBrowserHandler.onExecute.addListener(t),this.formatSuccess("Execute event listener added successfully",{listenerAdded:!0,loggingEnabled:e,note:"Events will be triggered when users execute file browser actions"})}catch(t){return this.formatError(t)}});}registerRemoveExecuteListener(){this.server.registerTool("extension_tool_remove_execute_listener",{description:"Remove all execute event listeners for file browser handler",inputSchema:{}},async()=>{try{let e=chrome.fileBrowserHandler.onExecute.hasListeners();return chrome.fileBrowserHandler.onExecute.removeListener,this.formatSuccess("Execute event listeners removed",{hadListeners:e,listenersRemoved:!0,note:"All execute event listeners have been removed"})}catch(e){return this.formatError(e)}});}};var et=class extends m{apiName="FileSystemProvider";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.fileSystemProvider?typeof chrome.fileSystemProvider.getAll!="function"?{available:!1,message:"chrome.fileSystemProvider.getAll is not available",details:"The fileSystemProvider API appears to be partially available. Check manifest permissions and ensure running on ChromeOS."}:(chrome.fileSystemProvider.getAll(e=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"FileSystemProvider API is fully available"}):{available:!1,message:"chrome.fileSystemProvider API is not defined",details:'This extension needs the "fileSystemProvider" permission in its manifest.json and is only available on ChromeOS'}}catch(e){return {available:false,message:"Failed to access chrome.fileSystemProvider API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("mount")&&this.registerMount(),this.shouldRegisterTool("unmount")&&this.registerUnmount(),this.shouldRegisterTool("get")&&this.registerGet(),this.shouldRegisterTool("getAll")&&this.registerGetAll(),this.shouldRegisterTool("notify")&&this.registerNotify();}registerMount(){this.server.registerTool("extension_tool_mount_file_system",{description:"Mount a file system with the given fileSystemId and displayName",inputSchema:{fileSystemId:z.string().describe("The string identifier of the file system. Must be unique per each extension"),displayName:z.string().describe("A human-readable name for the file system"),writable:z.boolean().optional().describe("Whether the file system supports operations which may change contents"),openedFilesLimit:z.number().optional().describe("The maximum number of files that can be opened at once. If not specified, or 0, then not limited"),supportsNotifyTag:z.boolean().optional().describe("Whether the file system supports the tag field for observed directories"),persistent:z.boolean().optional().describe("Whether the framework should resume the file system at the next sign-in session. True by default")}},async({fileSystemId:e,displayName:t,writable:r,openedFilesLimit:o,supportsNotifyTag:i,persistent:s})=>{try{let n={fileSystemId:e,displayName:t};return r!==void 0&&(n.writable=r),o!==void 0&&(n.openedFilesLimit=o),i!==void 0&&(n.supportsNotifyTag=i),s!==void 0&&(n.persistent=s),await new Promise((a,c)=>{chrome.fileSystemProvider.mount(n,()=>{chrome.runtime.lastError?c(new Error(chrome.runtime.lastError.message)):a();});}),this.formatSuccess("File system mounted successfully",{fileSystemId:e,displayName:t,writable:n.writable,openedFilesLimit:n.openedFilesLimit,supportsNotifyTag:n.supportsNotifyTag,persistent:n.persistent})}catch(n){return this.formatError(n)}});}registerUnmount(){this.server.registerTool("extension_tool_unmount_file_system",{description:"Unmount a file system with the given fileSystemId",inputSchema:{fileSystemId:z.string().describe("The identifier of the file system to be unmounted")}},async({fileSystemId:e})=>{try{return await new Promise((t,r)=>{chrome.fileSystemProvider.unmount({fileSystemId:e},()=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t();});}),this.formatSuccess("File system unmounted successfully",{fileSystemId:e})}catch(t){return this.formatError(t)}});}registerGet(){this.server.registerTool("extension_tool_get_file_system",{description:"Get information about a file system with the specified fileSystemId",inputSchema:{fileSystemId:z.string().describe("The identifier of the file system to retrieve information about")}},async({fileSystemId:e})=>{try{let t=await new Promise((r,o)=>{chrome.fileSystemProvider.get(e,i=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r(i);});});return this.formatJson({fileSystemId:t.fileSystemId,displayName:t.displayName,writable:t.writable,openedFilesLimit:t.openedFilesLimit,supportsNotifyTag:t.supportsNotifyTag,openedFiles:t.openedFiles.map(r=>({filePath:r.filePath,mode:r.mode,openRequestId:r.openRequestId})),watchers:t.watchers.map(r=>({entryPath:r.entryPath,recursive:r.recursive,lastTag:r.lastTag}))})}catch(t){return this.formatError(t)}});}registerGetAll(){this.server.registerTool("extension_tool_get_all_file_systems",{description:"Get all file systems mounted by the extension",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.fileSystemProvider.getAll(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({count:e.length,fileSystems:e.map(t=>({fileSystemId:t.fileSystemId,displayName:t.displayName,writable:t.writable,openedFilesLimit:t.openedFilesLimit,supportsNotifyTag:t.supportsNotifyTag,openedFilesCount:t.openedFiles.length,watchersCount:t.watchers.length}))})}catch(e){return this.formatError(e)}});}registerNotify(){this.server.registerTool("extension_tool_notify_file_system_changes",{description:"Notify about changes in the watched directory at observedPath in recursive mode",inputSchema:{fileSystemId:z.string().describe("The identifier of the file system related to this change"),observedPath:z.string().describe("The path of the observed entry"),recursive:z.boolean().describe("Mode of the observed entry"),changeType:z.enum(["CHANGED","DELETED"]).describe("The type of the change which happened to the observed entry"),tag:z.string().optional().describe("Tag for the notification. Required if the file system was mounted with the supportsNotifyTag option"),changes:z.array(z.object({entryPath:z.string().describe("The path of the changed entry"),changeType:z.enum(["CHANGED","DELETED"]).describe("The type of the change which happened to the entry")})).optional().describe("List of changes to entries within the observed directory")}},async({fileSystemId:e,observedPath:t,recursive:r,changeType:o,tag:i,changes:s})=>{try{let n={fileSystemId:e,observedPath:t,recursive:r,changeType:o};return i!==void 0&&(n.tag=i),s!==void 0&&(n.changes=s.map(a=>({entryPath:a.entryPath,changeType:a.changeType}))),await new Promise((a,c)=>{chrome.fileSystemProvider.notify(n,()=>{chrome.runtime.lastError?c(new Error(chrome.runtime.lastError.message)):a();});}),this.formatSuccess("File system changes notified successfully",{fileSystemId:e,observedPath:t,recursive:r,changeType:o,tag:i,changesCount:s?.length||0})}catch(n){return this.formatError(n)}});}};var tt=class extends m{apiName="FontSettings";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.fontSettings?typeof chrome.fontSettings.getFontList!="function"?{available:!1,message:"chrome.fontSettings.getFontList is not available",details:"The fontSettings API appears to be partially available. Check manifest permissions."}:(chrome.fontSettings.getFontList(e=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"FontSettings API is fully available"}):{available:!1,message:"chrome.fontSettings API is not defined",details:'This extension needs the "fontSettings" permission in its manifest.json'}}catch(e){return {available:false,message:"Failed to access chrome.fontSettings API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("getFont")&&this.registerGetFont(),this.shouldRegisterTool("setFont")&&this.registerSetFont(),this.shouldRegisterTool("clearFont")&&this.registerClearFont(),this.shouldRegisterTool("getFontList")&&this.registerGetFontList(),this.shouldRegisterTool("getDefaultFontSize")&&this.registerGetDefaultFontSize(),this.shouldRegisterTool("setDefaultFontSize")&&this.registerSetDefaultFontSize(),this.shouldRegisterTool("clearDefaultFontSize")&&this.registerClearDefaultFontSize(),this.shouldRegisterTool("getDefaultFixedFontSize")&&this.registerGetDefaultFixedFontSize(),this.shouldRegisterTool("setDefaultFixedFontSize")&&this.registerSetDefaultFixedFontSize(),this.shouldRegisterTool("clearDefaultFixedFontSize")&&this.registerClearDefaultFixedFontSize(),this.shouldRegisterTool("getMinimumFontSize")&&this.registerGetMinimumFontSize(),this.shouldRegisterTool("setMinimumFontSize")&&this.registerSetMinimumFontSize(),this.shouldRegisterTool("clearMinimumFontSize")&&this.registerClearMinimumFontSize();}registerGetFont(){this.server.registerTool("extension_tool_get_font",{description:"Get the font for a given script and generic font family",inputSchema:{genericFamily:z.enum(["standard","sansserif","serif","fixed","cursive","fantasy","math"]).describe("The generic font family for which the font should be retrieved"),script:z.string().optional().describe('The script for which the font should be retrieved. If omitted, the font setting for the global script (script code "Zyyy") is retrieved')}},async({genericFamily:e,script:t})=>{try{let r={genericFamily:e};t!==void 0&&(r.script=t);let o=await new Promise((i,s)=>{chrome.fontSettings.getFont(r,n=>{chrome.runtime.lastError?s(new Error(chrome.runtime.lastError.message)):i(n);});});return this.formatJson({fontId:o.fontId,levelOfControl:o.levelOfControl,genericFamily:e,script:t||"Zyyy"})}catch(r){return this.formatError(r)}});}registerSetFont(){this.server.registerTool("extension_tool_set_font",{description:"Set the font for a given script and generic font family",inputSchema:{fontId:z.string().describe("The font ID. The empty string means to fallback to the global script font setting"),genericFamily:z.enum(["standard","sansserif","serif","fixed","cursive","fantasy","math"]).describe("The generic font family for which the font should be set"),script:z.string().optional().describe('The script code which the font should be set. If omitted, the font setting for the global script (script code "Zyyy") is set')}},async({fontId:e,genericFamily:t,script:r})=>{try{let o={fontId:e,genericFamily:t};return r!==void 0&&(o.script=r),await new Promise((i,s)=>{chrome.fontSettings.setFont(o,()=>{chrome.runtime.lastError?s(new Error(chrome.runtime.lastError.message)):i();});}),this.formatSuccess("Font set successfully",{fontId:e,genericFamily:t,script:r||"Zyyy"})}catch(o){return this.formatError(o)}});}registerClearFont(){this.server.registerTool("extension_tool_clear_font",{description:"Clear the font set by this extension, if any",inputSchema:{genericFamily:z.enum(["standard","sansserif","serif","fixed","cursive","fantasy","math"]).describe("The generic font family for which the font should be cleared"),script:z.string().optional().describe("The script for which the font should be cleared. If omitted, the global script font setting is cleared")}},async({genericFamily:e,script:t})=>{try{let r={genericFamily:e};return t!==void 0&&(r.script=t),await new Promise((o,i)=>{chrome.fontSettings.clearFont(r,()=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o();});}),this.formatSuccess("Font cleared successfully",{genericFamily:e,script:t||"Zyyy"})}catch(r){return this.formatError(r)}});}registerGetFontList(){this.server.registerTool("extension_tool_get_font_list",{description:"Get a list of fonts on the system",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.fontSettings.getFontList(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({count:e.length,fonts:e.map(t=>({fontId:t.fontId,displayName:t.displayName}))})}catch(e){return this.formatError(e)}});}registerGetDefaultFontSize(){this.server.registerTool("extension_tool_get_default_font_size",{description:"Get the default font size",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.fontSettings.getDefaultFontSize({},o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({pixelSize:e.pixelSize,levelOfControl:e.levelOfControl})}catch(e){return this.formatError(e)}});}registerSetDefaultFontSize(){this.server.registerTool("extension_tool_set_default_font_size",{description:"Set the default font size",inputSchema:{pixelSize:z.number().min(6).max(72).describe("The font size in pixels")}},async({pixelSize:e})=>{try{return await new Promise((t,r)=>{chrome.fontSettings.setDefaultFontSize({pixelSize:e},()=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t();});}),this.formatSuccess("Default font size set successfully",{pixelSize:e})}catch(t){return this.formatError(t)}});}registerClearDefaultFontSize(){this.server.registerTool("extension_tool_clear_default_font_size",{description:"Clear the default font size set by this extension, if any",inputSchema:{}},async()=>{try{return await new Promise((e,t)=>{chrome.fontSettings.clearDefaultFontSize({},()=>{chrome.runtime.lastError?t(new Error(chrome.runtime.lastError.message)):e();});}),this.formatSuccess("Default font size cleared successfully")}catch(e){return this.formatError(e)}});}registerGetDefaultFixedFontSize(){this.server.registerTool("extension_tool_get_default_fixed_font_size",{description:"Get the default size for fixed width fonts",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.fontSettings.getDefaultFixedFontSize({},o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({pixelSize:e.pixelSize,levelOfControl:e.levelOfControl})}catch(e){return this.formatError(e)}});}registerSetDefaultFixedFontSize(){this.server.registerTool("extension_tool_set_default_fixed_font_size",{description:"Set the default size for fixed width fonts",inputSchema:{pixelSize:z.number().min(6).max(72).describe("The font size in pixels")}},async({pixelSize:e})=>{try{return await new Promise((t,r)=>{chrome.fontSettings.setDefaultFixedFontSize({pixelSize:e},()=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t();});}),this.formatSuccess("Default fixed font size set successfully",{pixelSize:e})}catch(t){return this.formatError(t)}});}registerClearDefaultFixedFontSize(){this.server.registerTool("extension_tool_clear_default_fixed_font_size",{description:"Clear the default fixed font size set by this extension, if any",inputSchema:{}},async()=>{try{return await new Promise((e,t)=>{chrome.fontSettings.clearDefaultFixedFontSize({},()=>{chrome.runtime.lastError?t(new Error(chrome.runtime.lastError.message)):e();});}),this.formatSuccess("Default fixed font size cleared successfully")}catch(e){return this.formatError(e)}});}registerGetMinimumFontSize(){this.server.registerTool("extension_tool_get_minimum_font_size",{description:"Get the minimum font size",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.fontSettings.getMinimumFontSize({},o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({pixelSize:e.pixelSize,levelOfControl:e.levelOfControl})}catch(e){return this.formatError(e)}});}registerSetMinimumFontSize(){this.server.registerTool("extension_tool_set_minimum_font_size",{description:"Set the minimum font size",inputSchema:{pixelSize:z.number().min(6).max(24).describe("The font size in pixels")}},async({pixelSize:e})=>{try{return await new Promise((t,r)=>{chrome.fontSettings.setMinimumFontSize({pixelSize:e},()=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t();});}),this.formatSuccess("Minimum font size set successfully",{pixelSize:e})}catch(t){return this.formatError(t)}});}registerClearMinimumFontSize(){this.server.registerTool("extension_tool_clear_minimum_font_size",{description:"Clear the minimum font size set by this extension, if any",inputSchema:{}},async()=>{try{return await new Promise((e,t)=>{chrome.fontSettings.clearMinimumFontSize({},()=>{chrome.runtime.lastError?t(new Error(chrome.runtime.lastError.message)):e();});}),this.formatSuccess("Minimum font size cleared successfully")}catch(e){return this.formatError(e)}});}};var rt=class extends m{apiName="Gcm";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.gcm?typeof chrome.gcm.register!="function"?{available:!1,message:"chrome.gcm.register is not available",details:"The gcm API appears to be partially available. Check manifest permissions."}:{available:!0,message:"GCM API is fully available"}:{available:!1,message:"chrome.gcm API is not defined",details:'This extension needs the "gcm" permission in its manifest.json'}}catch(e){return {available:false,message:"Failed to access chrome.gcm API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("register")&&this.registerRegister(),this.shouldRegisterTool("send")&&this.registerSend(),this.shouldRegisterTool("unregister")&&this.registerUnregister();}registerRegister(){this.server.registerTool("extension_tool_gcm_register",{description:"Register the application with Firebase Cloud Messaging (FCM) to receive messages",inputSchema:{senderIds:z.array(z.string()).min(1).max(100).describe("A list of server IDs that are allowed to send messages to the application. Must contain at least one and no more than 100 sender IDs")}},async({senderIds:e})=>{try{let t=await new Promise((r,o)=>{chrome.gcm.register(e,i=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r(i);});});return this.formatSuccess("Successfully registered with FCM",{registrationId:t,senderIds:e})}catch(t){return this.formatError(t)}});}registerSend(){this.server.registerTool("extension_tool_gcm_send",{description:"Send a message through Firebase Cloud Messaging (FCM)",inputSchema:{destinationId:z.string().describe("The ID of the server to send the message to as assigned by Google API Console"),messageId:z.string().describe("The ID of the message. Must be unique for each message in scope of the application"),data:z.record(z.string()).describe("Message data to send to the server. Case-insensitive goog. and google, as well as case-sensitive collapse_key are disallowed as key prefixes"),timeToLive:z.number().min(0).max(2419200).optional().describe("Time-to-live of the message in seconds. 0 means send immediately or fail. Default is 86,400 seconds (1 day), maximum is 2,419,200 seconds (28 days)")}},async({destinationId:e,messageId:t,data:r,timeToLive:o})=>{try{let i=JSON.stringify(r).length;if(i>4096)return this.formatError("Message data exceeds maximum size of 4096 bytes");for(let a of Object.keys(r)){let c=a.toLowerCase();if(c.startsWith("goog.")||c.startsWith("google")||a==="collapse_key")return this.formatError(`Invalid key prefix: ${a}. Keys cannot start with 'goog.', 'google', or be 'collapse_key'`)}let s={destinationId:e,messageId:t,data:r};o!==void 0&&(s.timeToLive=o);let n=await new Promise((a,c)=>{chrome.gcm.send(s,u=>{chrome.runtime.lastError?c(new Error(chrome.runtime.lastError.message)):a(u);});});return this.formatSuccess("Message sent successfully",{messageId:n,destinationId:e,dataSize:i,timeToLive:o||86400})}catch(i){return this.formatError(i)}});}registerUnregister(){this.server.registerTool("extension_tool_gcm_unregister",{description:"Unregister the application from Firebase Cloud Messaging (FCM)",inputSchema:{}},async()=>{try{return await new Promise((e,t)=>{chrome.gcm.unregister(()=>{chrome.runtime.lastError?t(new Error(chrome.runtime.lastError.message)):e();});}),this.formatSuccess("Successfully unregistered from FCM")}catch(e){return this.formatError(e)}});}};var sr=["addUrl","deleteAll","deleteRange","deleteUrl","getVisits","search"],ot=z.enum(sr),it=class extends m{apiName="History";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.history?typeof chrome.history.search!="function"?{available:!1,message:"chrome.history.search is not available",details:"The history API appears to be partially available. Check manifest permissions."}:(chrome.history.search({text:"",maxResults:1},e=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"History API is fully available"}):{available:!1,message:"chrome.history API is not defined",details:'This extension needs the "history" permission in its manifest.json'}}catch(e){return {available:false,message:"Failed to access chrome.history API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.server.registerTool("extension_tool_history_operations",{description:"Perform operations on the Chrome History API",inputSchema:{action:ot,params:z.record(z.any()).optional().describe("Parameters for the chosen action")}},async({action:e,params:t={}})=>{try{if(!this.shouldRegisterTool(e))return this.formatError(new Error(`Action "${e}" is not supported`));switch(e){case "addUrl":return await this.handleAddUrl(t);case "deleteAll":return await this.handleDeleteAll();case "deleteRange":return await this.handleDeleteRange(t);case "deleteUrl":return await this.handleDeleteUrl(t);case "getVisits":return await this.handleGetVisits(t);case "search":return await this.handleSearch(t);default:return this.formatError(`Unknown action: ${String(e)}`)}}catch(r){return this.formatError(r)}}),this.server.registerTool("extension_tool_history_parameters_description",{description:"Get the parameters for extension_tool_history_operations tool and the description for the associated action, this tool should be used first before extension_tool_history_operations",inputSchema:{action:ot}},async({action:e})=>{try{if(!this.shouldRegisterTool(e))return this.formatError(new Error(`Action "${e}" is not supported`));let t=(o,i)=>ir(o,{name:i,$refStrategy:"none"}),r={tool:"extension_tool_history_operations",action:e,note:"Use the description to double check if the correct action is chosen. Use this JSON Schema for the params field when calling the tool. The top-level tool input is { action, params }."};switch(e){case "addUrl":{let o={params:t(this.addUrlSchema,"AddUrlParams"),description:'Add a URL to the history at the current time with a transition type of "link"'};return this.formatJson({...r,...o})}case "deleteAll":{let o={params:t(this.deleteAllSchema,"DeleteAllParams"),description:"Delete all items from the browser history"};return this.formatJson({...r,...o})}case "deleteRange":{let o={params:t(this.deleteRangeSchema,"DeleteRangeParams"),description:"Remove all items within the specified date range from history. Pages will not be removed unless all visits fall within the range"};return this.formatJson({...r,...o})}case "deleteUrl":{let o={params:t(this.deleteUrlSchema,"DeleteUrlParams"),description:"Remove all occurrences of the given URL from history"};return this.formatJson({...r,...o})}case "getVisits":{let o={params:t(this.getVisitsSchema,"GetVisitsParams"),description:"Retrieve information about visits to a specific URL"};return this.formatJson({...r,...o})}case "search":{let o={params:t(this.searchSchema,"SearchParams"),description:"Search the history for the last visit time of each page matching the query"};return this.formatJson({...r,...o})}default:return this.formatError(`Unknown action: ${String(e)}`)}}catch(t){return this.formatError(t)}});}async handleAddUrl(e){let{url:t}=this.addUrlSchema.parse(e);return await chrome.history.addUrl({url:t}),await new Promise((r,o)=>{chrome.history.addUrl({url:t},()=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r();});}),this.formatSuccess("URL added to history successfully",{url:t})}async handleDeleteAll(){return await new Promise((e,t)=>{chrome.history.deleteAll(()=>{chrome.runtime.lastError?t(new Error(chrome.runtime.lastError.message)):e();});}),this.formatSuccess("All history deleted successfully")}async handleDeleteRange(e){let{startTime:t,endTime:r}=this.deleteRangeSchema.parse(e);return t>=r?this.formatError("startTime must be less than endTime"):(await new Promise((o,i)=>{chrome.history.deleteRange({startTime:t,endTime:r},()=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o();});}),this.formatSuccess("History range deleted successfully",{startTime:t,endTime:r,startTimeFormatted:new Date(t).toISOString(),endTimeFormatted:new Date(r).toISOString()}))}async handleDeleteUrl(e){let{url:t}=this.deleteUrlSchema.parse(e);return await new Promise((r,o)=>{chrome.history.deleteUrl({url:t},()=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r();});}),this.formatSuccess("URL deleted from history successfully",{url:t})}async handleGetVisits(e){let{url:t}=this.getVisitsSchema.parse(e),r=await new Promise((o,i)=>{chrome.history.getVisits({url:t},s=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o(s);});});return this.formatJson({url:t,visitCount:r.length,visits:r.map(o=>({id:o.id,visitId:o.visitId,visitTime:o.visitTime,visitTimeFormatted:o.visitTime?new Date(o.visitTime).toISOString():void 0,referringVisitId:o.referringVisitId,transition:o.transition}))})}async handleSearch(e){let{text:t,startTime:r,endTime:o,maxResults:i}=this.searchSchema.parse(e),s={text:t};r!==void 0&&(s.startTime=r),o!==void 0&&(s.endTime=o),i!==void 0&&(s.maxResults=i);let n=await new Promise((a,c)=>{chrome.history.search(s,u=>{chrome.runtime.lastError?c(new Error(chrome.runtime.lastError.message)):a(u);});});return this.formatJson({query:{text:t,startTime:r,endTime:o,maxResults:i},resultCount:n.length,results:n.map(a=>({id:a.id,url:a.url,title:a.title,lastVisitTime:a.lastVisitTime,lastVisitTimeFormatted:a.lastVisitTime?new Date(a.lastVisitTime).toISOString():void 0,visitCount:a.visitCount,typedCount:a.typedCount}))})}addUrlSchema=z.object({url:z.string().url().describe("The URL to add to history. Must be a valid URL format")});deleteAllSchema=z.object({});deleteRangeSchema=z.object({startTime:z.number().describe("Items added to history after this date, represented in milliseconds since the epoch"),endTime:z.number().describe("Items added to history before this date, represented in milliseconds since the epoch")});deleteUrlSchema=z.object({url:z.string().url().describe("The URL to remove from history. Must be in the format as returned from a call to history.search()")});getVisitsSchema=z.object({url:z.string().url().describe("The URL to get visit information for. Must be in the format as returned from a call to history.search()")});searchSchema=z.object({text:z.string().describe("A free-text query to the history service. Leave empty to retrieve all pages"),startTime:z.number().optional().describe("Limit results to those visited after this date, represented in milliseconds since the epoch. Defaults to 24 hours ago if not specified"),endTime:z.number().optional().describe("Limit results to those visited before this date, represented in milliseconds since the epoch"),maxResults:z.number().min(1).max(1e3).optional().describe("The maximum number of results to retrieve. Defaults to 100")})};var st=class extends m{apiName="I18n";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.i18n?typeof chrome.i18n.getMessage!="function"?{available:!1,message:"chrome.i18n.getMessage is not available",details:"The i18n API appears to be partially available. This is unexpected."}:chrome.i18n.getMessage("@@ui_locale")?{available:!0,message:"I18n API is fully available"}:{available:!1,message:"Failed to get UI locale from chrome.i18n",details:"The i18n API is not functioning properly"}:{available:!1,message:"chrome.i18n API is not defined",details:"The i18n API should be available by default in Chrome extensions"}}catch(e){return {available:false,message:"Failed to access chrome.i18n API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("getMessage")&&this.registerGetMessage(),this.shouldRegisterTool("getUILanguage")&&this.registerGetUILanguage(),this.shouldRegisterTool("getAcceptLanguages")&&this.registerGetAcceptLanguages(),this.shouldRegisterTool("detectLanguage")&&this.registerDetectLanguage();}registerGetMessage(){this.server.registerTool("extension_tool_get_message",{description:"Get a localized string for the specified message. Returns empty string if message is missing.",inputSchema:{messageName:z.string().describe("The name of the message, as specified in the messages.json file"),substitutions:z.array(z.string()).max(9).optional().describe("Up to 9 substitution strings, if the message requires any"),escapeLt:z.boolean().optional().describe("Escape < in translation to &lt;. Useful when translation is used in HTML context")}},async({messageName:e,substitutions:t,escapeLt:r})=>{try{let o={};r!==void 0&&(o.escapeLt=r);let i;return t&&t.length>0?(Object.keys(o).length>0,i=chrome.i18n.getMessage(e,t)):Object.keys(o).length>0?i=chrome.i18n.getMessage(e,void 0):i=chrome.i18n.getMessage(e),i===void 0?this.formatError("Invalid getMessage() call format"):this.formatJson({messageName:e,message:i,isEmpty:i==="",substitutions:t||[],options:o})}catch(o){return this.formatError(o)}});}registerGetUILanguage(){this.server.registerTool("extension_tool_get_ui_language",{description:"Get the browser UI language. This is different from accept languages which returns preferred user languages.",inputSchema:{}},async()=>{try{let e=chrome.i18n.getUILanguage();return this.formatJson({uiLanguage:e,description:"The browser UI language code such as en-US or fr-FR"})}catch(e){return this.formatError(e)}});}registerGetAcceptLanguages(){this.server.registerTool("extension_tool_get_accept_languages",{description:"Get the accept-languages of the browser. This is different from the locale used by the browser.",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.i18n.getAcceptLanguages(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({count:e.length,languages:e,description:"Array of language codes representing user's preferred languages"})}catch(e){return this.formatError(e)}});}registerDetectLanguage(){this.server.registerTool("extension_tool_detect_language",{description:"Detect the language of provided text using CLD (Compact Language Detector). Returns up to 3 detected languages.",inputSchema:{text:z.string().min(1).describe("User input string to be analyzed for language detection")}},async({text:e})=>{try{let t=await new Promise((r,o)=>{chrome.i18n.detectLanguage(e,i=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r(i);});});return this.formatJson({inputText:e,isReliable:t.isReliable,detectedLanguages:t.languages.map(r=>({language:r.language,percentage:r.percentage,description:r.language==="und"?"Unknown language":`ISO language code: ${r.language}`})),summary:{primaryLanguage:t.languages[0]?.language||"unknown",primaryPercentage:t.languages[0]?.percentage||0,totalLanguagesDetected:t.languages.length}})}catch(t){return this.formatError(t)}});}};var nt=class extends m{apiName="Identity";constructor(e,t={}){super(e,t);}checkAvailability(){try{if(!chrome.identity)return {available:!1,message:"chrome.identity API is not defined",details:'This extension needs the "identity" permission in its manifest.json'};if(typeof chrome.identity.getRedirectURL!="function")return {available:!1,message:"chrome.identity.getRedirectURL is not available",details:"The identity API appears to be partially available. Check manifest permissions."};if(!chrome.identity.getRedirectURL())throw new Error("Failed to generate redirect URL");return {available:!0,message:"Identity API is fully available"}}catch(e){return {available:false,message:"Failed to access chrome.identity API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("getAuthToken")&&this.registerGetAuthToken(),this.shouldRegisterTool("getProfileUserInfo")&&this.registerGetProfileUserInfo(),this.shouldRegisterTool("getAccounts")&&this.registerGetAccounts(),this.shouldRegisterTool("getRedirectURL")&&this.registerGetRedirectURL(),this.shouldRegisterTool("launchWebAuthFlow")&&this.registerLaunchWebAuthFlow(),this.shouldRegisterTool("removeCachedAuthToken")&&this.registerRemoveCachedAuthToken(),this.shouldRegisterTool("clearAllCachedAuthTokens")&&this.registerClearAllCachedAuthTokens();}registerGetAuthToken(){this.server.registerTool("extension_tool_get_auth_token",{description:"Gets an OAuth2 access token using the client ID and scopes specified in manifest.json",inputSchema:{interactive:z.boolean().optional().describe("Whether to prompt the user for authorization if required"),scopes:z.array(z.string()).optional().describe("List of OAuth2 scopes to request (overrides manifest.json scopes)"),accountId:z.string().optional().describe("Account ID whose token should be returned"),enableGranularPermissions:z.boolean().optional().describe("Enable granular permissions consent screen")}},async({interactive:e,scopes:t,accountId:r,enableGranularPermissions:o})=>{try{let i={};e!==void 0&&(i.interactive=e),t!==void 0&&(i.scopes=t),r!==void 0&&(i.account={id:r}),o!==void 0&&(i.enableGranularPermissions=o);let s=await new Promise((n,a)=>{chrome.identity.getAuthToken(i,c=>{chrome.runtime.lastError?a(new Error(chrome.runtime.lastError.message)):n(c);});});return this.formatJson({token:s.token,grantedScopes:s.grantedScopes})}catch(i){return this.formatError(i)}});}registerGetProfileUserInfo(){this.server.registerTool("extension_tool_get_profile_user_info",{description:"Retrieves email address and obfuscated gaia id of the user signed into a profile",inputSchema:{accountStatus:z.enum(["SYNC","ANY"]).optional().describe("Status of the primary account (SYNC or ANY)")}},async({accountStatus:e})=>{try{let t={};e!==void 0&&(t.accountStatus=e);let r=await new Promise((o,i)=>{chrome.identity.getProfileUserInfo(t,s=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o(s);});});return this.formatJson({id:r.id,email:r.email})}catch(t){return this.formatError(t)}});}registerGetAccounts(){this.server.registerTool("extension_tool_get_accounts",{description:"Retrieves a list of AccountInfo objects describing the accounts present on the profile",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.identity.getAccounts(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({count:e.length,accounts:e.map(t=>({id:t.id}))})}catch(e){return this.formatError(e)}});}registerGetRedirectURL(){this.server.registerTool("extension_tool_get_redirect_url",{description:"Generates a redirect URL to be used in launchWebAuthFlow",inputSchema:{path:z.string().optional().describe("The path appended to the end of the generated URL")}},async({path:e})=>{try{let t=chrome.identity.getRedirectURL(e);return this.formatJson({redirectUrl:t})}catch(t){return this.formatError(t)}});}registerLaunchWebAuthFlow(){this.server.registerTool("extension_tool_launch_web_auth_flow",{description:"Starts an auth flow at the specified URL with non-Google identity providers",inputSchema:{url:z.string().describe("The URL that initiates the auth flow"),interactive:z.boolean().optional().describe("Whether to launch auth flow in interactive mode"),abortOnLoadForNonInteractive:z.boolean().optional().describe("Whether to terminate flow for non-interactive requests after page loads"),timeoutMsForNonInteractive:z.number().optional().describe("Maximum time in milliseconds for non-interactive mode")}},async({url:e,interactive:t,abortOnLoadForNonInteractive:r,timeoutMsForNonInteractive:o})=>{try{let i={url:e};t!==void 0&&(i.interactive=t),r!==void 0&&(i.abortOnLoadForNonInteractive=r),o!==void 0&&(i.timeoutMsForNonInteractive=o);let s=await new Promise((n,a)=>{chrome.identity.launchWebAuthFlow(i,c=>{chrome.runtime.lastError?a(new Error(chrome.runtime.lastError.message)):n(c);});});return this.formatJson({responseUrl:s})}catch(i){return this.formatError(i)}});}registerRemoveCachedAuthToken(){this.server.registerTool("extension_tool_remove_cached_auth_token",{description:"Removes an OAuth2 access token from the Identity API token cache",inputSchema:{token:z.string().describe("The specific token that should be removed from the cache")}},async({token:e})=>{try{let t={token:e};return await new Promise((r,o)=>{chrome.identity.removeCachedAuthToken(t,()=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r();});}),this.formatSuccess("Token removed from cache successfully",{token:e})}catch(t){return this.formatError(t)}});}registerClearAllCachedAuthTokens(){this.server.registerTool("extension_tool_clear_all_cached_auth_tokens",{description:"Resets the state of the Identity API by removing all OAuth2 tokens and user preferences",inputSchema:{}},async()=>{try{return await new Promise((e,t)=>{chrome.identity.clearAllCachedAuthTokens(()=>{chrome.runtime.lastError?t(new Error(chrome.runtime.lastError.message)):e();});}),this.formatSuccess("All cached auth tokens cleared successfully")}catch(e){return this.formatError(e)}});}};var ct=class extends m{apiName="Idle";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.idle?typeof chrome.idle.queryState!="function"?{available:!1,message:"chrome.idle.queryState is not available",details:"The idle API appears to be partially available. Check manifest permissions."}:(chrome.idle.queryState(60,e=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"Idle API is fully available"}):{available:!1,message:"chrome.idle API is not defined",details:'This extension needs the "idle" permission in its manifest.json'}}catch(e){return {available:false,message:"Failed to access chrome.idle API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("queryState")&&this.registerQueryState(),this.shouldRegisterTool("setDetectionInterval")&&this.registerSetDetectionInterval(),this.shouldRegisterTool("getAutoLockDelay")&&this.registerGetAutoLockDelay();}registerQueryState(){this.server.registerTool("extension_tool_query_idle_state",{description:'Query the current idle state of the system. Returns "locked" if the system is locked, "idle" if the user has not generated input for the specified time, or "active" otherwise.',inputSchema:{detectionIntervalInSeconds:z.number().min(15).default(60).describe("The system is considered idle if this many seconds have elapsed since the last user input detected. Minimum is 15 seconds.")}},async({detectionIntervalInSeconds:e})=>{try{let t=await new Promise((r,o)=>{chrome.idle.queryState(e,i=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r(i);});});return this.formatJson({state:t,detectionIntervalInSeconds:e,timestamp:Date.now(),timestampFormatted:new Date().toISOString()})}catch(t){return this.formatError(t)}});}registerSetDetectionInterval(){this.server.registerTool("extension_tool_set_idle_detection_interval",{description:"Set the interval used to determine when the system is in an idle state for onStateChanged events. The default interval is 60 seconds.",inputSchema:{intervalInSeconds:z.number().min(15).describe("Threshold, in seconds, used to determine when the system is in an idle state. Minimum is 15 seconds.")}},async({intervalInSeconds:e})=>{try{return chrome.idle.setDetectionInterval(e),this.formatSuccess("Idle detection interval set successfully",{intervalInSeconds:e})}catch(t){return this.formatError(t)}});}registerGetAutoLockDelay(){this.server.registerTool("extension_tool_get_auto_lock_delay",{description:"Get the time, in seconds, it takes until the screen is locked automatically while idle. Returns zero if the screen is never locked automatically. Currently supported on Chrome OS only.",inputSchema:{}},async()=>{try{if(typeof chrome.idle.getAutoLockDelay!="function")return this.formatError("getAutoLockDelay is not available. This method requires Chrome 73+ and is currently supported on Chrome OS only.");let e=await new Promise((t,r)=>{chrome.idle.getAutoLockDelay(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({autoLockDelaySeconds:e,autoLockEnabled:e>0,autoLockDelayFormatted:e>0?`${e} seconds`:"Never locks automatically"})}catch(e){return this.formatError(e)}});}};var lt=class extends m{apiName="Input.ime";constructor(e,t={}){super(e,t);}checkAvailability(){try{return !chrome.input||!chrome.input.ime?{available:!1,message:"chrome.input.ime API is not defined",details:'This extension needs the "input" permission in its manifest.json and must run on ChromeOS'}:typeof chrome.input.ime.commitText!="function"?{available:!1,message:"chrome.input.ime.commitText is not available",details:"The input.ime API appears to be partially available. Check manifest permissions and platform support."}:{available:!0,message:"Input.ime API is fully available"}}catch(e){return {available:false,message:"Failed to access chrome.input.ime API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("setComposition")&&this.registerSetComposition(),this.shouldRegisterTool("clearComposition")&&this.registerClearComposition(),this.shouldRegisterTool("commitText")&&this.registerCommitText(),this.shouldRegisterTool("sendKeyEvents")&&this.registerSendKeyEvents(),this.shouldRegisterTool("hideInputView")&&this.registerHideInputView(),this.shouldRegisterTool("setCandidateWindowProperties")&&this.registerSetCandidateWindowProperties(),this.shouldRegisterTool("setCandidates")&&this.registerSetCandidates(),this.shouldRegisterTool("setCursorPosition")&&this.registerSetCursorPosition(),this.shouldRegisterTool("setMenuItems")&&this.registerSetMenuItems(),this.shouldRegisterTool("updateMenuItems")&&this.registerUpdateMenuItems(),this.shouldRegisterTool("deleteSurroundingText")&&this.registerDeleteSurroundingText();}registerSetComposition(){this.server.registerTool("extension_tool_set_composition",{description:"Set the current composition text and cursor position",inputSchema:{contextID:z.number().describe("ID of the context where the composition text will be set"),text:z.string().describe("Text to set as the current composition"),selectionStart:z.number().optional().describe("Position to start the selection"),selectionEnd:z.number().optional().describe("Position to end the selection"),cursor:z.number().describe("Position to set the cursor"),segments:z.array(z.object({start:z.number().describe("Start position of the segment"),end:z.number().describe("End position of the segment"),style:z.enum(["underline","doubleUnderline","noUnderline"]).describe("Style of the segment")})).optional().describe("Array of segments with styling information")}},async({contextID:e,text:t,selectionStart:r,selectionEnd:o,cursor:i,segments:s})=>{try{let n={contextID:e,text:t,cursor:i};r!==void 0&&(n.selectionStart=r),o!==void 0&&(n.selectionEnd=o),s!==void 0&&(n.segments=s);let a=await new Promise((c,u)=>{chrome.input.ime.setComposition(n,d=>{chrome.runtime.lastError?u(new Error(chrome.runtime.lastError.message)):c(d);});});return this.formatSuccess("Composition set successfully",{contextID:e,text:t,cursor:i,success:a})}catch(n){return this.formatError(n)}});}registerClearComposition(){this.server.registerTool("extension_tool_clear_composition",{description:"Clear the current composition text",inputSchema:{contextID:z.number().describe("ID of the context where the composition will be cleared")}},async({contextID:e})=>{try{let t=await new Promise((r,o)=>{chrome.input.ime.clearComposition({contextID:e},i=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r(i);});});return this.formatSuccess("Composition cleared successfully",{contextID:e,success:t})}catch(t){return this.formatError(t)}});}registerCommitText(){this.server.registerTool("extension_tool_commit_text",{description:"Commit the provided text to the current input",inputSchema:{contextID:z.number().describe("ID of the context where the text will be committed"),text:z.string().describe("The text to commit")}},async({contextID:e,text:t})=>{try{let r=await new Promise((o,i)=>{chrome.input.ime.commitText({contextID:e,text:t},s=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o(s);});});return this.formatSuccess("Text committed successfully",{contextID:e,text:t,success:r})}catch(r){return this.formatError(r)}});}registerSendKeyEvents(){this.server.registerTool("extension_tool_send_key_events",{description:"Send key events to the system",inputSchema:{contextID:z.number().describe("ID of the context where the key events will be sent"),keyData:z.array(z.object({type:z.enum(["keyup","keydown"]).describe("Type of key event"),requestId:z.string().optional().describe("Request ID for the key event"),key:z.string().describe("The key value"),code:z.string().describe("The key code"),keyCode:z.number().optional().describe("The key code number"),altKey:z.boolean().optional().describe("Whether Alt key is pressed"),ctrlKey:z.boolean().optional().describe("Whether Ctrl key is pressed"),shiftKey:z.boolean().optional().describe("Whether Shift key is pressed"),capsLock:z.boolean().optional().describe("Whether Caps Lock is on")})).describe("Array of key events to send")}},async({contextID:e,keyData:t})=>{try{return await new Promise((r,o)=>{chrome.input.ime.sendKeyEvents({contextID:e,keyData:t},()=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r();});}),this.formatSuccess("Key events sent successfully",{contextID:e,eventCount:t.length})}catch(r){return this.formatError(r)}});}registerHideInputView(){this.server.registerTool("extension_tool_hide_input_view",{description:"Hide the input view window",inputSchema:{}},async()=>{try{return chrome.input.ime.hideInputView(),this.formatSuccess("Input view hidden successfully")}catch(e){return this.formatError(e)}});}registerSetCandidateWindowProperties(){this.server.registerTool("extension_tool_set_candidate_window_properties",{description:"Set the properties of the candidate window",inputSchema:{engineID:z.string().describe("ID of the engine to set candidate window properties"),properties:z.object({visible:z.boolean().optional().describe("Whether the candidate window is visible"),cursorVisible:z.boolean().optional().describe("Whether the cursor is visible"),vertical:z.boolean().optional().describe("Whether the candidate window is vertical"),pageSize:z.number().optional().describe("Number of candidates to display per page"),auxiliaryText:z.string().optional().describe("Auxiliary text to show"),auxiliaryTextVisible:z.boolean().optional().describe("Whether auxiliary text is visible"),windowPosition:z.enum(["cursor","composition"]).optional().describe("Where to display the candidate window")}).describe("Properties to set for the candidate window")}},async({engineID:e,properties:t})=>{try{let r=await new Promise((o,i)=>{chrome.input.ime.setCandidateWindowProperties({engineID:e,properties:t},s=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o(s);});});return this.formatSuccess("Candidate window properties set successfully",{engineID:e,properties:t,success:r})}catch(r){return this.formatError(r)}});}registerSetCandidates(){this.server.registerTool("extension_tool_set_candidates",{description:"Set the current candidates",inputSchema:{contextID:z.number().describe("ID of the context to set candidates for"),candidates:z.array(z.object({candidate:z.string().describe("The candidate text"),id:z.number().describe("The candidate ID"),parentId:z.number().optional().describe("The parent candidate ID"),label:z.string().optional().describe("The candidate label"),annotation:z.string().optional().describe("The candidate annotation"),usage:z.object({title:z.string().describe("Usage title"),body:z.string().describe("Usage body")}).optional().describe("Usage information for the candidate")})).describe("Array of candidates to set")}},async({contextID:e,candidates:t})=>{try{let r=await new Promise((o,i)=>{chrome.input.ime.setCandidates({contextID:e,candidates:t},s=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o(s);});});return this.formatSuccess("Candidates set successfully",{contextID:e,candidateCount:t.length,success:r})}catch(r){return this.formatError(r)}});}registerSetCursorPosition(){this.server.registerTool("extension_tool_set_cursor_position",{description:"Set the position of the cursor in the candidate window",inputSchema:{contextID:z.number().describe("ID of the context to set cursor position for"),candidateID:z.number().describe("ID of the candidate to position cursor on")}},async({contextID:e,candidateID:t})=>{try{let r=await new Promise((o,i)=>{chrome.input.ime.setCursorPosition({contextID:e,candidateID:t},s=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o(s);});});return this.formatSuccess("Cursor position set successfully",{contextID:e,candidateID:t,success:r})}catch(r){return this.formatError(r)}});}registerSetMenuItems(){this.server.registerTool("extension_tool_set_menu_items",{description:"Set the current menu items",inputSchema:{engineID:z.string().describe("ID of the engine to set menu items for"),items:z.array(z.object({id:z.string().describe("Menu item ID"),label:z.string().optional().describe("Menu item label"),style:z.enum(["check","radio","separator"]).optional().describe("Menu item style"),visible:z.boolean().optional().describe("Whether the menu item is visible"),checked:z.boolean().optional().describe("Whether the menu item is checked"),enabled:z.boolean().optional().describe("Whether the menu item is enabled")})).describe("Array of menu items to set")}},async({engineID:e,items:t})=>{try{return await new Promise((r,o)=>{chrome.input.ime.setMenuItems({engineID:e,items:t},()=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r();});}),this.formatSuccess("Menu items set successfully",{engineID:e,itemCount:t.length})}catch(r){return this.formatError(r)}});}registerUpdateMenuItems(){this.server.registerTool("extension_tool_update_menu_items",{description:"Update the current menu items",inputSchema:{engineId:z.string().describe("ID of the engine to update menu items for"),items:z.array(z.object({id:z.string().describe("Menu item ID"),label:z.string().optional().describe("Menu item label"),style:z.enum(["check","radio","separator"]).optional().describe("Menu item style"),visible:z.boolean().optional().describe("Whether the menu item is visible"),checked:z.boolean().optional().describe("Whether the menu item is checked"),enabled:z.boolean().optional().describe("Whether the menu item is enabled")})).describe("Array of menu items to update")}},async({engineId:e,items:t})=>{try{return await new Promise((r,o)=>{chrome.input.ime.updateMenuItems({engineId:e,items:t},()=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r();});}),this.formatSuccess("Menu items updated successfully",{engineId:e,itemCount:t.length})}catch(r){return this.formatError(r)}});}registerDeleteSurroundingText(){this.server.registerTool("extension_tool_delete_surrounding_text",{description:"Delete the text around the cursor",inputSchema:{contextID:z.number().describe("ID of the context to delete surrounding text from"),offset:z.number().describe("Offset from the cursor position"),length:z.number().describe("Number of characters to delete"),engineID:z.string().describe("ID of the engine requesting the deletion")}},async({contextID:e,offset:t,length:r,engineID:o})=>{try{return await new Promise((i,s)=>{chrome.input.ime.deleteSurroundingText({contextID:e,offset:t,length:r,engineID:o},()=>{chrome.runtime.lastError?s(new Error(chrome.runtime.lastError.message)):i();});}),this.formatSuccess("Surrounding text deleted successfully",{contextID:e,offset:t,length:r,engineID:o})}catch(i){return this.formatError(i)}});}};var dt=class extends m{apiName="InstanceID";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.instanceID?typeof chrome.instanceID.getID!="function"?{available:!1,message:"chrome.instanceID.getID is not available",details:"The instanceID API appears to be partially available. Check manifest permissions."}:(chrome.instanceID.getID(e=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"InstanceID API is fully available"}):{available:!1,message:"chrome.instanceID API is not defined",details:'This extension needs the "gcm" permission in its manifest.json'}}catch(e){return {available:false,message:"Failed to access chrome.instanceID API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("getID")&&this.registerGetID(),this.shouldRegisterTool("getCreationTime")&&this.registerGetCreationTime(),this.shouldRegisterTool("getToken")&&this.registerGetToken(),this.shouldRegisterTool("deleteToken")&&this.registerDeleteToken(),this.shouldRegisterTool("deleteID")&&this.registerDeleteID();}registerGetID(){this.server.registerTool("extension_tool_get_instance_id",{description:"Retrieve an identifier for the app instance. The same ID will be returned as long as the application identity has not been revoked or expired",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.instanceID.getID(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({instanceID:e})}catch(e){return this.formatError(e)}});}registerGetCreationTime(){this.server.registerTool("extension_tool_get_creation_time",{description:"Retrieve the time when the InstanceID has been generated, represented in milliseconds since the epoch",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.instanceID.getCreationTime(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({creationTime:e,creationTimeFormatted:new Date(e).toISOString()})}catch(e){return this.formatError(e)}});}registerGetToken(){this.server.registerTool("extension_tool_get_token",{description:"Return a token that allows the authorized entity to access the service defined by scope",inputSchema:{authorizedEntity:z.string().describe("Identifies the entity that is authorized to access resources associated with this Instance ID. It can be a project ID from Google developer console"),scope:z.string().describe("Identifies authorized actions that the authorized entity can take. E.g. for sending GCM messages, GCM scope should be used"),options:z.record(z.string()).optional().describe("Optional key/value pairs that will be associated with the token (deprecated since Chrome 89)")}},async({authorizedEntity:e,scope:t,options:r})=>{try{let o={authorizedEntity:e,scope:t};r!==void 0&&(o.options=r);let i=await new Promise((s,n)=>{chrome.instanceID.getToken(o,a=>{chrome.runtime.lastError?n(new Error(chrome.runtime.lastError.message)):s(a);});});return this.formatJson({token:i,authorizedEntity:e,scope:t})}catch(o){return this.formatError(o)}});}registerDeleteToken(){this.server.registerTool("extension_tool_delete_token",{description:"Revoke a granted token",inputSchema:{authorizedEntity:z.string().describe("The authorized entity that is used to obtain the token"),scope:z.string().describe("The scope that is used to obtain the token")}},async({authorizedEntity:e,scope:t})=>{try{let r={authorizedEntity:e,scope:t};return await new Promise((o,i)=>{chrome.instanceID.deleteToken(r,()=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o();});}),this.formatSuccess("Token deleted successfully",{authorizedEntity:e,scope:t})}catch(r){return this.formatError(r)}});}registerDeleteID(){this.server.registerTool("extension_tool_delete_instance_id",{description:"Reset the app instance identifier and revoke all tokens associated with it",inputSchema:{}},async()=>{try{return await new Promise((e,t)=>{chrome.instanceID.deleteID(()=>{chrome.runtime.lastError?t(new Error(chrome.runtime.lastError.message)):e();});}),this.formatSuccess("Instance ID deleted successfully and all associated tokens revoked")}catch(e){return this.formatError(e)}});}};var mt=class extends m{apiName="LoginState";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.loginState?typeof chrome.loginState.getProfileType!="function"?{available:!1,message:"chrome.loginState.getProfileType is not available",details:"The loginState API appears to be partially available. Check manifest permissions and ensure this is running on ChromeOS."}:(chrome.loginState.getProfileType(e=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"LoginState API is fully available"}):{available:!1,message:"chrome.loginState API is not defined",details:'This extension needs the "loginState" permission in its manifest.json and only works on ChromeOS'}}catch(e){return {available:false,message:"Failed to access chrome.loginState API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("getProfileType")&&this.registerGetProfileType(),this.shouldRegisterTool("getSessionState")&&this.registerGetSessionState();}registerGetProfileType(){this.server.registerTool("extension_tool_get_profile_type",{description:"Get the type of the profile the extension is in (signin profile or user profile)",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.loginState.getProfileType(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({profileType:e,description:e==="SIGNIN_PROFILE"?"Extension is in the signin profile":"Extension is in the user profile"})}catch(e){return this.formatError(e)}});}registerGetSessionState(){this.server.registerTool("extension_tool_get_session_state",{description:"Get the current session state (unknown, OOBE screen, login screen, in session, lock screen, or RMA screen)",inputSchema:{}},async()=>{try{let e=await new Promise((r,o)=>{chrome.loginState.getSessionState(i=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r(i);});}),t=r=>{switch(r){case "UNKNOWN":return "Session state is unknown";case "IN_OOBE_SCREEN":return "User is in the out-of-box-experience screen";case "IN_LOGIN_SCREEN":return "User is in the login screen";case "IN_SESSION":return "User is in the session";case "IN_LOCK_SCREEN":return "User is in the lock screen";default:return "Unknown session state"}};return this.formatJson({sessionState:e,description:t(e)})}catch(e){return this.formatError(e)}});}};var ht=class extends m{apiName="Management";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.management?typeof chrome.management.getSelf!="function"?{available:!1,message:"chrome.management.getSelf is not available",details:"The management API appears to be partially available. Check manifest permissions."}:(chrome.management.getSelf(e=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"Management API is fully available"}):{available:!1,message:"chrome.management API is not defined",details:'This extension needs the "management" permission in its manifest.json'}}catch(e){return {available:false,message:"Failed to access chrome.management API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("get")&&this.registerGet(),this.shouldRegisterTool("getAll")&&this.registerGetAll(),this.shouldRegisterTool("getSelf")&&this.registerGetSelf(),this.shouldRegisterTool("setEnabled")&&this.registerSetEnabled(),this.shouldRegisterTool("uninstall")&&this.registerUninstall(),this.shouldRegisterTool("uninstallSelf")&&this.registerUninstallSelf(),this.shouldRegisterTool("launchApp")&&this.registerLaunchApp(),this.shouldRegisterTool("createAppShortcut")&&this.registerCreateAppShortcut(),this.shouldRegisterTool("generateAppForLink")&&this.registerGenerateAppForLink(),this.shouldRegisterTool("setLaunchType")&&this.registerSetLaunchType(),this.shouldRegisterTool("getPermissionWarningsById")&&this.registerGetPermissionWarningsById(),this.shouldRegisterTool("getPermissionWarningsByManifest")&&this.registerGetPermissionWarningsByManifest();}registerGet(){this.server.registerTool("extension_tool_get_extension",{description:"Get information about an installed extension, app, or theme by ID",inputSchema:{id:z.string().describe("The ID of the extension, app, or theme")}},async({id:e})=>{try{let t=await new Promise((r,o)=>{chrome.management.get(e,i=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r(i);});});return this.formatJson({id:t.id,name:t.name,shortName:t.shortName,description:t.description,version:t.version,type:t.type,enabled:t.enabled,mayDisable:t.mayDisable,installType:t.installType,isApp:t.isApp,appLaunchUrl:t.appLaunchUrl,homepageUrl:t.homepageUrl,updateUrl:t.updateUrl,offlineEnabled:t.offlineEnabled,optionsUrl:t.optionsUrl,permissions:t.permissions,hostPermissions:t.hostPermissions,disabledReason:t.disabledReason,launchType:t.launchType,availableLaunchTypes:t.availableLaunchTypes,icons:t.icons})}catch(t){return this.formatError(t)}});}registerGetAll(){this.server.registerTool("extension_tool_get_all_extensions",{description:"Get information about all installed extensions, apps, and themes",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.management.getAll(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({count:e.length,extensions:e.map(t=>({id:t.id,name:t.name,shortName:t.shortName,description:t.description,version:t.version,type:t.type,enabled:t.enabled,mayDisable:t.mayDisable,installType:t.installType,isApp:t.isApp,appLaunchUrl:t.appLaunchUrl,homepageUrl:t.homepageUrl,updateUrl:t.updateUrl,offlineEnabled:t.offlineEnabled,optionsUrl:t.optionsUrl,permissions:t.permissions,hostPermissions:t.hostPermissions,disabledReason:t.disabledReason,launchType:t.launchType,availableLaunchTypes:t.availableLaunchTypes,icons:t.icons}))})}catch(e){return this.formatError(e)}});}registerGetSelf(){this.server.registerTool("extension_tool_get_self",{description:"Get information about the calling extension, app, or theme",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.management.getSelf(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({id:e.id,name:e.name,shortName:e.shortName,description:e.description,version:e.version,type:e.type,enabled:e.enabled,mayDisable:e.mayDisable,installType:e.installType,isApp:e.isApp,appLaunchUrl:e.appLaunchUrl,homepageUrl:e.homepageUrl,updateUrl:e.updateUrl,offlineEnabled:e.offlineEnabled,optionsUrl:e.optionsUrl,permissions:e.permissions,hostPermissions:e.hostPermissions,disabledReason:e.disabledReason,launchType:e.launchType,availableLaunchTypes:e.availableLaunchTypes,icons:e.icons})}catch(e){return this.formatError(e)}});}registerSetEnabled(){this.server.registerTool("extension_tool_set_extension_enabled",{description:"Enable or disable an extension, app, or theme",inputSchema:{id:z.string().describe("The ID of the extension, app, or theme"),enabled:z.boolean().describe("Whether the extension should be enabled or disabled")}},async({id:e,enabled:t})=>{try{return await new Promise((r,o)=>{chrome.management.setEnabled(e,t,()=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r();});}),this.formatSuccess(`Extension ${t?"enabled":"disabled"} successfully`,{id:e,enabled:t})}catch(r){return this.formatError(r)}});}registerUninstall(){this.server.registerTool("extension_tool_uninstall_extension",{description:"Uninstall an extension, app, or theme",inputSchema:{id:z.string().describe("The ID of the extension, app, or theme to uninstall"),showConfirmDialog:z.boolean().optional().describe("Whether to show a confirmation dialog. Defaults to false")}},async({id:e,showConfirmDialog:t})=>{try{let r={};return t!==void 0&&(r.showConfirmDialog=t),await new Promise((o,i)=>{chrome.management.uninstall(e,r,()=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o();});}),this.formatSuccess("Extension uninstalled successfully",{id:e})}catch(r){return this.formatError(r)}});}registerUninstallSelf(){this.server.registerTool("extension_tool_uninstall_self",{description:"Uninstall the calling extension",inputSchema:{showConfirmDialog:z.boolean().optional().describe("Whether to show a confirmation dialog. Defaults to false")}},async({showConfirmDialog:e})=>{try{let t={};return e!==void 0&&(t.showConfirmDialog=e),await new Promise((r,o)=>{chrome.management.uninstallSelf(t,()=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r();});}),this.formatSuccess("Extension uninstalled successfully")}catch(t){return this.formatError(t)}});}registerLaunchApp(){this.server.registerTool("extension_tool_launch_app",{description:"Launch an application",inputSchema:{id:z.string().describe("The extension ID of the application to launch")}},async({id:e})=>{try{return await new Promise((t,r)=>{chrome.management.launchApp(e,()=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t();});}),this.formatSuccess("Application launched successfully",{id:e})}catch(t){return this.formatError(t)}});}registerCreateAppShortcut(){this.server.registerTool("extension_tool_create_app_shortcut",{description:"Create a shortcut for an app",inputSchema:{id:z.string().describe("The ID of the app to create a shortcut for")}},async({id:e})=>{try{return await new Promise((t,r)=>{chrome.management.createAppShortcut(e,()=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t();});}),this.formatSuccess("App shortcut created successfully",{id:e})}catch(t){return this.formatError(t)}});}registerGenerateAppForLink(){this.server.registerTool("extension_tool_generate_app_for_link",{description:"Generate a bookmark app for a URL",inputSchema:{url:z.string().url().describe("The URL of the web page. Must use http or https scheme"),title:z.string().describe("The title of the generated app")}},async({url:e,title:t})=>{try{let r=await new Promise((o,i)=>{chrome.management.generateAppForLink(e,t,s=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o(s);});});return this.formatJson({message:"Bookmark app generated successfully",app:{id:r.id,name:r.name,shortName:r.shortName,description:r.description,version:r.version,type:r.type,enabled:r.enabled,appLaunchUrl:r.appLaunchUrl}})}catch(r){return this.formatError(r)}});}registerSetLaunchType(){this.server.registerTool("extension_tool_set_app_launch_type",{description:"Set the launch type of an app",inputSchema:{id:z.string().describe("The ID of the app"),launchType:z.enum(["OPEN_AS_REGULAR_TAB","OPEN_AS_PINNED_TAB","OPEN_AS_WINDOW","OPEN_FULL_SCREEN"]).describe("The launch type for the app")}},async({id:e,launchType:t})=>{try{return await new Promise((r,o)=>{chrome.management.setLaunchType(e,t,()=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r();});}),this.formatSuccess("App launch type set successfully",{id:e,launchType:t})}catch(r){return this.formatError(r)}});}registerGetPermissionWarningsById(){this.server.registerTool("extension_tool_get_permission_warnings_by_id",{description:"Get permission warnings for an installed extension by ID",inputSchema:{id:z.string().describe("The ID of the installed extension")}},async({id:e})=>{try{let t=await new Promise((r,o)=>{chrome.management.getPermissionWarningsById(e,i=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r(i);});});return this.formatJson({id:e,warningCount:t.length,warnings:t})}catch(t){return this.formatError(t)}});}registerGetPermissionWarningsByManifest(){this.server.registerTool("extension_tool_get_permission_warnings_by_manifest",{description:"Get permission warnings for an extension manifest",inputSchema:{manifestStr:z.string().describe("Extension manifest JSON string")}},async({manifestStr:e})=>{try{let t=await new Promise((r,o)=>{chrome.management.getPermissionWarningsByManifest(e,i=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r(i);});});return this.formatJson({warningCount:t.length,warnings:t})}catch(t){return this.formatError(t)}});}};var ut=class extends m{apiName="Notifications";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.notifications?typeof chrome.notifications.getPermissionLevel!="function"?{available:!1,message:"chrome.notifications.getPermissionLevel is not available",details:"The notifications API appears to be partially available. Check manifest permissions."}:(chrome.notifications.getPermissionLevel(e=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"Notifications API is fully available"}):{available:!1,message:"chrome.notifications API is not defined",details:'This extension needs the "notifications" permission in its manifest.json'}}catch(e){return {available:false,message:"Failed to access chrome.notifications API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("createNotification")&&this.registerCreateNotification(),this.shouldRegisterTool("updateNotification")&&this.registerUpdateNotification(),this.shouldRegisterTool("clearNotification")&&this.registerClearNotification(),this.shouldRegisterTool("getAllNotifications")&&this.registerGetAllNotifications(),this.shouldRegisterTool("getPermissionLevel")&&this.registerGetPermissionLevel();}registerCreateNotification(){this.server.registerTool("extension_tool_create_notification",{description:"Create and display a notification",inputSchema:{notificationId:z.string().optional().describe("Identifier of the notification. If not set, an ID will be auto-generated. Max 500 characters"),type:z.enum(["basic","image","list","progress"]).describe("Type of notification template to use"),iconUrl:z.string().describe("URL to the notification icon"),title:z.string().describe("Title of the notification"),message:z.string().describe("Main notification content"),contextMessage:z.string().optional().describe("Alternate notification content with lower-weight font"),priority:z.number().min(-2).max(2).optional().describe("Priority from -2 (lowest) to 2 (highest). Default is 0"),eventTime:z.number().optional().describe("Timestamp in milliseconds past epoch (e.g. Date.now() + n)"),buttons:z.array(z.object({title:z.string().describe("Button text"),iconUrl:z.string().optional().describe("Button icon URL (deprecated on Mac)")})).max(2).optional().describe("Up to two notification action buttons"),imageUrl:z.string().optional().describe("URL to image thumbnail for image-type notifications (deprecated on Mac)"),items:z.array(z.object({title:z.string().describe("Item title"),message:z.string().describe("Item details")})).optional().describe("Items for list-type notifications (only first item visible on Mac)"),progress:z.number().min(0).max(100).optional().describe("Progress value from 0 to 100 for progress-type notifications"),isClickable:z.boolean().optional().describe("Whether notification is clickable (deprecated since Chrome 67)"),requireInteraction:z.boolean().optional().describe("Whether notification should remain visible until user interaction"),silent:z.boolean().optional().describe("Whether to suppress sounds and vibrations")}},async({notificationId:e,type:t,iconUrl:r,title:o,message:i,contextMessage:s,priority:n,eventTime:a,buttons:c,imageUrl:u,items:d,progress:v,isClickable:S,requireInteraction:P,silent:I})=>{try{let O={type:t,iconUrl:r,title:o,message:i};s!==void 0&&(O.contextMessage=s),n!==void 0&&(O.priority=n),a!==void 0&&(O.eventTime=a),c!==void 0&&(O.buttons=c),u!==void 0&&(O.imageUrl=u),d!==void 0&&(O.items=d),v!==void 0&&(O.progress=v),S!==void 0&&(O.isClickable=S),P!==void 0&&(O.requireInteraction=P),I!==void 0&&(O.silent=I);let ne=await new Promise((H,U)=>{e?chrome.notifications.create(e,O,ae=>{chrome.runtime.lastError?U(new Error(chrome.runtime.lastError.message)):H(ae);}):chrome.notifications.create(O,ae=>{chrome.runtime.lastError?U(new Error(chrome.runtime.lastError.message)):H(ae);});});return this.formatSuccess("Notification created successfully",{notificationId:ne,type:t,title:o,message:i})}catch(O){return this.formatError(O)}});}registerUpdateNotification(){this.server.registerTool("extension_tool_update_notification",{description:"Update an existing notification",inputSchema:{notificationId:z.string().describe("ID of the notification to update"),type:z.enum(["basic","image","list","progress"]).optional().describe("Type of notification template to use"),iconUrl:z.string().optional().describe("URL to the notification icon"),title:z.string().optional().describe("Title of the notification"),message:z.string().optional().describe("Main notification content"),contextMessage:z.string().optional().describe("Alternate notification content with lower-weight font"),priority:z.number().min(-2).max(2).optional().describe("Priority from -2 (lowest) to 2 (highest)"),eventTime:z.number().optional().describe("Timestamp in milliseconds past epoch"),buttons:z.array(z.object({title:z.string().describe("Button text"),iconUrl:z.string().optional().describe("Button icon URL")})).max(2).optional().describe("Up to two notification action buttons"),imageUrl:z.string().optional().describe("URL to image thumbnail"),items:z.array(z.object({title:z.string().describe("Item title"),message:z.string().describe("Item details")})).optional().describe("Items for list-type notifications"),progress:z.number().min(0).max(100).optional().describe("Progress value from 0 to 100"),requireInteraction:z.boolean().optional().describe("Whether notification should remain visible until user interaction"),silent:z.boolean().optional().describe("Whether to suppress sounds and vibrations")}},async({notificationId:e,type:t,iconUrl:r,title:o,message:i,contextMessage:s,priority:n,eventTime:a,buttons:c,imageUrl:u,items:d,progress:v,requireInteraction:S,silent:P})=>{try{let I={};return t!==void 0&&(I.type=t),r!==void 0&&(I.iconUrl=r),o!==void 0&&(I.title=o),i!==void 0&&(I.message=i),s!==void 0&&(I.contextMessage=s),n!==void 0&&(I.priority=n),a!==void 0&&(I.eventTime=a),c!==void 0&&(I.buttons=c),u!==void 0&&(I.imageUrl=u),d!==void 0&&(I.items=d),v!==void 0&&(I.progress=v),S!==void 0&&(I.requireInteraction=S),P!==void 0&&(I.silent=P),await new Promise((ne,H)=>{chrome.notifications.update(e,I,U=>{chrome.runtime.lastError?H(new Error(chrome.runtime.lastError.message)):ne(U);});})?this.formatSuccess("Notification updated successfully",{notificationId:e,updatedFields:Object.keys(I)}):this.formatSuccess("Notification not found or could not be updated",{notificationId:e})}catch(I){return this.formatError(I)}});}registerClearNotification(){this.server.registerTool("extension_tool_clear_notification",{description:"Clear a specific notification",inputSchema:{notificationId:z.string().describe("ID of the notification to clear")}},async({notificationId:e})=>{try{return await new Promise((r,o)=>{chrome.notifications.clear(e,i=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r(i);});})?this.formatSuccess("Notification cleared successfully",{notificationId:e}):this.formatSuccess("Notification not found or already cleared",{notificationId:e})}catch(t){return this.formatError(t)}});}registerGetAllNotifications(){this.server.registerTool("extension_tool_get_all_notifications",{description:"Get all active notifications for this extension",inputSchema:{}},async()=>{try{let e=await new Promise((r,o)=>{chrome.notifications.getAll(i=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r(i);});}),t=Object.keys(e);return this.formatJson({count:t.length,notificationIds:t,notifications:e})}catch(e){return this.formatError(e)}});}registerGetPermissionLevel(){this.server.registerTool("extension_tool_get_permission_level",{description:"Get the current notification permission level for this extension",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.notifications.getPermissionLevel(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({permissionLevel:e,canShowNotifications:e==="granted",description:e==="granted"?"User has granted permission to show notifications":"User has denied permission to show notifications"})}catch(e){return this.formatError(e)}});}};var pt=class extends m{apiName="Offscreen";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.offscreen?typeof chrome.offscreen.createDocument!="function"?{available:!1,message:"chrome.offscreen.createDocument is not available",details:"The offscreen API appears to be partially available. Check manifest permissions."}:{available:!0,message:"Offscreen API is fully available"}:{available:!1,message:"chrome.offscreen API is not defined",details:'This extension needs the "offscreen" permission in its manifest.json'}}catch(e){return {available:false,message:"Failed to access chrome.offscreen API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("createDocument")&&this.registerCreateDocument(),this.shouldRegisterTool("closeDocument")&&this.registerCloseDocument(),this.shouldRegisterTool("hasOffscreenDocument")&&this.registerHasOffscreenDocument();}registerCreateDocument(){this.server.registerTool("extension_tool_create_offscreen_document",{description:"Create a new offscreen document for the extension",inputSchema:{url:z.string().describe("The (relative) URL to load in the document"),reasons:z.array(z.enum(["TESTING","AUDIO_PLAYBACK","IFRAME_SCRIPTING","DOM_SCRAPING","BLOBS","DOM_PARSER","USER_MEDIA","DISPLAY_MEDIA","WEB_RTC","CLIPBOARD","LOCAL_STORAGE","WORKERS","BATTERY_STATUS","MATCH_MEDIA","GEOLOCATION"])).describe("The reason(s) the extension is creating the offscreen document"),justification:z.string().describe("A developer-provided string that explains, in more detail, the need for the background context")}},async({url:e,reasons:t,justification:r})=>{try{let o={url:e,reasons:t,justification:r};return await new Promise((i,s)=>{chrome.offscreen.createDocument(o,()=>{chrome.runtime.lastError?s(new Error(chrome.runtime.lastError.message)):i();});}),this.formatSuccess("Offscreen document created successfully",{url:e,reasons:t,justification:r})}catch(o){return this.formatError(o)}});}registerCloseDocument(){this.server.registerTool("extension_tool_close_offscreen_document",{description:"Close the currently-open offscreen document for the extension",inputSchema:{}},async()=>{try{return await new Promise((e,t)=>{chrome.offscreen.closeDocument(()=>{chrome.runtime.lastError?t(new Error(chrome.runtime.lastError.message)):e();});}),this.formatSuccess("Offscreen document closed successfully")}catch(e){return this.formatError(e)}});}registerHasOffscreenDocument(){this.server.registerTool("extension_tool_has_offscreen_document",{description:"Check if an offscreen document exists for the extension",inputSchema:{documentUrl:z.string().optional().describe("Optional specific document URL to check for")}},async({documentUrl:e})=>{try{let t=!1,r=null;if("getContexts"in chrome.runtime){let o={contextTypes:["OFFSCREEN_DOCUMENT"]};e&&(o.documentUrls=[chrome.runtime.getURL(e)]);let i=await new Promise((s,n)=>{chrome.runtime.getContexts(o,a=>{chrome.runtime.lastError?n(new Error(chrome.runtime.lastError.message)):s(a);});});t=i.length>0,t&&(r={count:i.length,contexts:i.map(s=>({contextType:s.contextType,documentUrl:s.documentUrl,frameId:s.frameId,tabId:s.tabId}))});}else try{t=(await self.clients.matchAll()).some(i=>{let s=i.url.includes(chrome.runtime.id);return e?s&&i.url.includes(e):s}),t&&(r={method:"clients.matchAll (legacy)",note:"Limited information available in Chrome versions before 116"});}catch{return this.formatSuccess("Cannot determine offscreen document status - clients API not available")}return this.formatJson({hasOffscreenDocument:t,documentInfo:r,checkedUrl:e||"any"})}catch(t){return this.formatError(t)}});}};var gt=class extends m{apiName="Omnibox";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.omnibox?typeof chrome.omnibox.setDefaultSuggestion!="function"?{available:!1,message:"chrome.omnibox.setDefaultSuggestion is not available",details:"The omnibox API appears to be partially available. Check manifest permissions."}:(chrome.omnibox.setDefaultSuggestion({description:"Test"}),{available:!0,message:"Omnibox API is fully available"}):{available:!1,message:"chrome.omnibox API is not defined",details:'This extension needs the "omnibox" field in its manifest.json with a keyword specified'}}catch(e){return {available:false,message:"Failed to access chrome.omnibox API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("setDefaultSuggestion")&&this.registerSetDefaultSuggestion(),this.shouldRegisterTool("onInputStarted")&&this.registerOnInputStarted(),this.shouldRegisterTool("onInputChanged")&&this.registerOnInputChanged(),this.shouldRegisterTool("onInputEntered")&&this.registerOnInputEntered(),this.shouldRegisterTool("onInputCancelled")&&this.registerOnInputCancelled(),this.shouldRegisterTool("onDeleteSuggestion")&&this.registerOnDeleteSuggestion();}registerSetDefaultSuggestion(){this.server.registerTool("extension_tool_set_default_suggestion",{description:"Set the description and styling for the default suggestion in the omnibox",inputSchema:{description:z.string().describe("The text displayed in the URL dropdown. Can contain XML-style markup for styling with tags: url, match, dim")}},async({description:e})=>{try{return chrome.omnibox.setDefaultSuggestion({description:e}),this.formatSuccess("Default suggestion set successfully",{description:e})}catch(t){return this.formatError(t)}});}registerOnInputStarted(){this.server.registerTool("extension_tool_add_input_started_listener",{description:"Add a listener for when user starts a keyword input session by typing the extension keyword",inputSchema:{}},async()=>{try{return chrome.omnibox.onInputStarted.addListener(()=>{console.log("Omnibox input session started");}),this.formatSuccess("Input started listener added successfully")}catch(e){return this.formatError(e)}});}registerOnInputChanged(){this.server.registerTool("extension_tool_add_input_changed_listener",{description:"Add a listener for when user changes what is typed into the omnibox",inputSchema:{enableSuggestions:z.boolean().optional().default(true).describe("Whether to provide example suggestions when input changes")}},async({enableSuggestions:e})=>{try{return chrome.omnibox.onInputChanged.addListener((t,r)=>{if(console.log("Omnibox input changed:",t),e){let o=[{content:`search_${t}`,description:`Search for <match>${t}</match>`},{content:`navigate_${t}`,description:`Navigate to <url>${t}</url>`}];r(o);}}),this.formatSuccess("Input changed listener added successfully",{enableSuggestions:e})}catch(t){return this.formatError(t)}});}registerOnInputEntered(){this.server.registerTool("extension_tool_add_input_entered_listener",{description:"Add a listener for when user accepts what is typed into the omnibox",inputSchema:{}},async()=>{try{return chrome.omnibox.onInputEntered.addListener((e,t)=>{switch(console.log("Omnibox input entered:",e,"disposition:",t),t){case "currentTab":console.log("Navigate in current tab");break;case "newForegroundTab":console.log("Navigate in new foreground tab");break;case "newBackgroundTab":console.log("Navigate in new background tab");break}}),this.formatSuccess("Input entered listener added successfully")}catch(e){return this.formatError(e)}});}registerOnInputCancelled(){this.server.registerTool("extension_tool_add_input_cancelled_listener",{description:"Add a listener for when user ends the keyword input session without accepting input",inputSchema:{}},async()=>{try{return chrome.omnibox.onInputCancelled.addListener(()=>{console.log("Omnibox input session cancelled");}),this.formatSuccess("Input cancelled listener added successfully")}catch(e){return this.formatError(e)}});}registerOnDeleteSuggestion(){this.server.registerTool("extension_tool_add_delete_suggestion_listener",{description:"Add a listener for when user deletes a suggested result",inputSchema:{}},async()=>{try{return chrome.omnibox.onDeleteSuggestion.addListener(e=>{console.log("Omnibox suggestion deleted:",e);}),this.formatSuccess("Delete suggestion listener added successfully")}catch(e){return this.formatError(e)}});}};var bt=class extends m{apiName="PageCapture";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.pageCapture?typeof chrome.pageCapture.saveAsMHTML!="function"?{available:!1,message:"chrome.pageCapture.saveAsMHTML is not available",details:"The pageCapture API appears to be partially available. Check manifest permissions."}:{available:!0,message:"PageCapture API is fully available"}:{available:!1,message:"chrome.pageCapture API is not defined",details:'This extension needs the "pageCapture" permission in its manifest.json'}}catch(e){return {available:false,message:"Failed to access chrome.pageCapture API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("saveAsMHTML")&&this.registerSaveAsMHTML();}registerSaveAsMHTML(){this.server.registerTool("extension_tool_save_as_mhtml",{description:"Save the content of a tab as MHTML format",inputSchema:{tabId:z.number().describe("The ID of the tab to save as MHTML")}},async({tabId:e})=>{try{let t=await new Promise((r,o)=>{chrome.pageCapture.saveAsMHTML({tabId:e},i=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r(i);});});return t?this.formatSuccess("Page captured as MHTML successfully",{tabId:e,size:t.size,type:t.type,sizeFormatted:`${(t.size/1024).toFixed(2)} KB`}):this.formatError("Failed to capture page as MHTML - no data returned")}catch(t){return this.formatError(t)}});}};var vt=class extends m{apiName="Permissions";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.permissions?typeof chrome.permissions.getAll!="function"?{available:!1,message:"chrome.permissions.getAll is not available",details:"The permissions API appears to be partially available. Check manifest permissions."}:(chrome.permissions.getAll(e=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"Permissions API is fully available"}):{available:!1,message:"chrome.permissions API is not defined",details:'This extension needs the "permissions" permission in its manifest.json'}}catch(e){return {available:false,message:"Failed to access chrome.permissions API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("request")&&this.registerRequest(),this.shouldRegisterTool("contains")&&this.registerContains(),this.shouldRegisterTool("getAll")&&this.registerGetAll(),this.shouldRegisterTool("remove")&&this.registerRemove(),this.shouldRegisterTool("addHostAccessRequest")&&this.registerAddHostAccessRequest(),this.shouldRegisterTool("removeHostAccessRequest")&&this.registerRemoveHostAccessRequest();}registerRequest(){this.server.registerTool("extension_tool_request_permissions",{description:"Request access to specified permissions, displaying a prompt to the user if necessary",inputSchema:{permissions:z.array(z.string()).optional().describe("List of named permissions to request"),origins:z.array(z.string()).optional().describe('List of host permissions to request (e.g., ["https://www.google.com/"])')}},async({permissions:e,origins:t})=>{try{if(!e&&!t)return this.formatError("Either permissions or origins must be specified to request permissions");let r={};return e&&e.length>0&&(r.permissions=e),t&&t.length>0&&(r.origins=t),await new Promise((i,s)=>{chrome.permissions.request(r,n=>{chrome.runtime.lastError?s(new Error(chrome.runtime.lastError.message)):i(n);});})?this.formatSuccess("Permissions granted successfully",{permissions:e||[],origins:t||[]}):this.formatSuccess("Permissions request denied by user",{permissions:e||[],origins:t||[]})}catch(r){return this.formatError(r)}});}registerContains(){this.server.registerTool("extension_tool_contains_permissions",{description:"Check if the extension has the specified permissions",inputSchema:{permissions:z.array(z.string()).optional().describe("List of named permissions to check"),origins:z.array(z.string()).optional().describe('List of host permissions to check (e.g., ["https://www.google.com/"])')}},async({permissions:e,origins:t})=>{try{if(!e&&!t)return this.formatError("Either permissions or origins must be specified to check permissions");let r={};e&&e.length>0&&(r.permissions=e),t&&t.length>0&&(r.origins=t);let o=await new Promise((i,s)=>{chrome.permissions.contains(r,n=>{chrome.runtime.lastError?s(new Error(chrome.runtime.lastError.message)):i(n);});});return this.formatJson({hasPermissions:o,checkedPermissions:e||[],checkedOrigins:t||[]})}catch(r){return this.formatError(r)}});}registerGetAll(){this.server.registerTool("extension_tool_get_all_permissions",{description:"Get the extension's current set of permissions",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.permissions.getAll(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({permissions:e.permissions||[],origins:e.origins||[],permissionsCount:(e.permissions||[]).length,originsCount:(e.origins||[]).length})}catch(e){return this.formatError(e)}});}registerRemove(){this.server.registerTool("extension_tool_remove_permissions",{description:"Remove access to the specified permissions",inputSchema:{permissions:z.array(z.string()).optional().describe("List of named permissions to remove"),origins:z.array(z.string()).optional().describe('List of host permissions to remove (e.g., ["https://www.google.com/"])')}},async({permissions:e,origins:t})=>{try{if(!e&&!t)return this.formatError("Either permissions or origins must be specified to remove permissions");let r={};return e&&e.length>0&&(r.permissions=e),t&&t.length>0&&(r.origins=t),await new Promise((i,s)=>{chrome.permissions.remove(r,n=>{chrome.runtime.lastError?s(new Error(chrome.runtime.lastError.message)):i(n);});})?this.formatSuccess("Permissions removed successfully",{permissions:e||[],origins:t||[]}):this.formatSuccess("Permissions could not be removed (may be required permissions)",{permissions:e||[],origins:t||[]})}catch(r){return this.formatError(r)}});}registerAddHostAccessRequest(){this.server.registerTool("extension_tool_add_host_access_request",{description:"Add a host access request that will be shown to the user",inputSchema:{tabId:z.number().optional().describe("The id of the tab where host access requests can be shown"),documentId:z.string().optional().describe("The id of a document where host access requests can be shown"),pattern:z.string().optional().describe("The URL pattern where host access requests can be shown")}},async({tabId:e,documentId:t,pattern:r})=>{try{if(e===void 0&&t===void 0)return this.formatError("Either tabId or documentId must be specified to add host access request");let o={};return e!==void 0&&(o.tabId=e),t!==void 0&&(o.documentId=t),r!==void 0&&(o.pattern=r),await new Promise((i,s)=>{chrome.permissions.addHostAccessRequest(o,()=>{chrome.runtime.lastError?s(new Error(chrome.runtime.lastError.message)):i();});}),this.formatSuccess("Host access request added successfully",{tabId:e,documentId:t,pattern:r})}catch(o){return this.formatError(o)}});}registerRemoveHostAccessRequest(){this.server.registerTool("extension_tool_remove_host_access_request",{description:"Remove a host access request",inputSchema:{tabId:z.number().optional().describe("The id of the tab where host access request will be removed"),documentId:z.string().optional().describe("The id of a document where host access request will be removed"),pattern:z.string().optional().describe("The URL pattern where host access request will be removed")}},async({tabId:e,documentId:t,pattern:r})=>{try{if(e===void 0&&t===void 0)return this.formatError("Either tabId or documentId must be specified to remove host access request");let o={};return e!==void 0&&(o.tabId=e),t!==void 0&&(o.documentId=t),r!==void 0&&(o.pattern=r),await new Promise((i,s)=>{chrome.permissions.removeHostAccessRequest(o,()=>{chrome.runtime.lastError?s(new Error(chrome.runtime.lastError.message)):i();});}),this.formatSuccess("Host access request removed successfully",{tabId:e,documentId:t,pattern:r})}catch(o){return this.formatError(o)}});}};var yt=class extends m{apiName="PlatformKeys";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.platformKeys?typeof chrome.platformKeys.selectClientCertificates!="function"?{available:!1,message:"chrome.platformKeys.selectClientCertificates is not available",details:"The platformKeys API appears to be partially available. Check manifest permissions and ensure running on ChromeOS."}:typeof chrome.platformKeys.subtleCrypto!="function"?{available:!1,message:"chrome.platformKeys.subtleCrypto is not available",details:"The platformKeys API appears to be partially available. Check manifest permissions."}:{available:!0,message:"PlatformKeys API is fully available"}:{available:!1,message:"chrome.platformKeys API is not defined",details:'This extension needs the "platformKeys" permission in its manifest.json and must run on ChromeOS'}}catch(e){return {available:false,message:"Failed to access chrome.platformKeys API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("selectClientCertificates")&&this.registerSelectClientCertificates(),this.shouldRegisterTool("getKeyPair")&&this.registerGetKeyPair(),this.shouldRegisterTool("getKeyPairBySpki")&&this.registerGetKeyPairBySpki(),this.shouldRegisterTool("verifyTLSServerCertificate")&&this.registerVerifyTLSServerCertificate(),this.shouldRegisterTool("getSubtleCrypto")&&this.registerGetSubtleCrypto();}registerSelectClientCertificates(){this.server.registerTool("extension_tool_select_client_certificates",{description:"Filter and select client certificates that match the request and are available to the extension",inputSchema:{request:z.object({certificateTypes:z.array(z.enum(["rsaSign","ecdsaSign"])).describe("List of certificate types requested, sorted by server preference"),certificateAuthorities:z.array(z.string()).optional().describe("List of distinguished names of certificate authorities (base64-encoded DER)")}).describe("Certificate request parameters"),interactive:z.boolean().describe("If true, present filtered list to user for manual selection"),clientCerts:z.array(z.string()).optional().describe("Optional list of certificates to operate on (base64-encoded DER)")}},async({request:e,interactive:t,clientCerts:r})=>{try{let o=e.certificateAuthorities?.map(a=>{let c=atob(a),u=new Uint8Array(c.length);for(let d=0;d<c.length;d++)u[d]=c.charCodeAt(d);return u.buffer}),i=r?.map(a=>{let c=atob(a),u=new Uint8Array(c.length);for(let d=0;d<c.length;d++)u[d]=c.charCodeAt(d);return u.buffer}),s={request:{certificateTypes:e.certificateTypes,certificateAuthorities:o||[]},interactive:t};i&&(s.clientCerts=i);let n=await new Promise((a,c)=>{chrome.platformKeys.selectClientCertificates(s,u=>{chrome.runtime.lastError?c(new Error(chrome.runtime.lastError.message)):a(u);});});return this.formatJson({count:n.length,certificates:n.map(a=>({certificate:btoa(String.fromCharCode(...new Uint8Array(a.certificate))),keyAlgorithm:a.keyAlgorithm}))})}catch(o){return this.formatError(o)}});}registerGetKeyPair(){this.server.registerTool("extension_tool_get_key_pair",{description:"Get the key pair for a certificate for usage with platformKeys.subtleCrypto",inputSchema:{certificate:z.string().describe("Base64-encoded DER certificate from selectClientCertificates"),parameters:z.object({name:z.string().describe("Algorithm name (RSASSA-PKCS1-v1_5 or ECDSA)"),hash:z.object({name:z.string().describe("Hash algorithm name (none, SHA-1, SHA-256, SHA-384, SHA-512)")}).optional().describe("Hash parameters for RSASSA-PKCS1-v1_5")}).describe("Algorithm parameters")}},async({certificate:e,parameters:t})=>{try{let r=atob(e),o=new Uint8Array(r.length);for(let n=0;n<r.length;n++)o[n]=r.charCodeAt(n);let i=o.buffer,s=await new Promise((n,a)=>{chrome.platformKeys.getKeyPair(i,t,(c,u)=>{chrome.runtime.lastError?a(new Error(chrome.runtime.lastError.message)):n({publicKey:c,privateKey:u});});});return this.formatSuccess("Key pair retrieved successfully",{hasPublicKey:!!s.publicKey,hasPrivateKey:!!s.privateKey,algorithm:s.publicKey.algorithm})}catch(r){return this.formatError(r)}});}registerGetKeyPairBySpki(){this.server.registerTool("extension_tool_get_key_pair_by_spki",{description:"Get the key pair identified by a SubjectPublicKeyInfo for usage with platformKeys.subtleCrypto",inputSchema:{publicKeySpkiDer:z.string().describe("Base64-encoded DER X.509 SubjectPublicKeyInfo"),parameters:z.object({name:z.string().describe("Algorithm name (ECDSA or RSASSA-PKCS1-v1_5)"),hash:z.object({name:z.string().describe("Hash algorithm name (none, SHA-1, SHA-256, SHA-384, SHA-512)")}).optional().describe("Hash parameters for RSASSA-PKCS1-v1_5")}).describe("Algorithm parameters")}},async({publicKeySpkiDer:e,parameters:t})=>{try{let r=atob(e),o=new Uint8Array(r.length);for(let n=0;n<r.length;n++)o[n]=r.charCodeAt(n);let i=o.buffer,s=await new Promise((n,a)=>{chrome.platformKeys.getKeyPairBySpki(i,t,(c,u)=>{chrome.runtime.lastError?a(new Error(chrome.runtime.lastError.message)):n({publicKey:c,privateKey:u});});});return this.formatSuccess("Key pair retrieved successfully by SPKI",{hasPublicKey:!!s.publicKey,hasPrivateKey:!!s.privateKey,algorithm:s.publicKey.algorithm})}catch(r){return this.formatError(r)}});}registerVerifyTLSServerCertificate(){this.server.registerTool("extension_tool_verify_tls_server_certificate",{description:"Verify if a server certificate chain can be trusted for a hostname according to platform trust settings",inputSchema:{hostname:z.string().describe("Hostname of the server to verify the certificate for"),serverCertificateChain:z.array(z.string()).describe("Array of base64-encoded DER X.509 certificates, first entry must be server certificate")}},async({hostname:e,serverCertificateChain:t})=>{try{let r=t.map(s=>{let n=atob(s),a=new Uint8Array(n.length);for(let c=0;c<n.length;c++)a[c]=n.charCodeAt(c);return a.buffer}),o={hostname:e,serverCertificateChain:r},i=await new Promise((s,n)=>{chrome.platformKeys.verifyTLSServerCertificate(o,a=>{chrome.runtime.lastError?n(new Error(chrome.runtime.lastError.message)):s(a);});});return this.formatJson({hostname:e,trusted:i.trusted,debugErrors:i.debug_errors||[],certificateCount:t.length})}catch(r){return this.formatError(r)}});}registerGetSubtleCrypto(){this.server.registerTool("extension_tool_get_subtle_crypto",{description:"Get information about the SubtleCrypto implementation for platform keys",inputSchema:{}},async()=>{try{return chrome.platformKeys.subtleCrypto()?this.formatSuccess("SubtleCrypto implementation is available",{available:!0,methods:["encrypt","decrypt","sign","verify","digest","generateKey","deriveKey","deriveBits","importKey","exportKey","wrapKey","unwrapKey"]}):this.formatError("SubtleCrypto implementation is not available")}catch(e){return this.formatError(e)}});}};var wt=class extends m{apiName="Power";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.power?typeof chrome.power.requestKeepAwake!="function"?{available:!1,message:"chrome.power.requestKeepAwake is not available",details:"The power API appears to be partially available. Check manifest permissions."}:(chrome.power.requestKeepAwake("system"),chrome.power.releaseKeepAwake(),{available:!0,message:"Power API is fully available"}):{available:!1,message:"chrome.power API is not defined",details:'This extension needs the "power" permission in its manifest.json'}}catch(e){return {available:false,message:"Failed to access chrome.power API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("requestKeepAwake")&&this.registerRequestKeepAwake(),this.shouldRegisterTool("releaseKeepAwake")&&this.registerReleaseKeepAwake(),this.shouldRegisterTool("reportActivity")&&this.registerReportActivity();}registerRequestKeepAwake(){this.server.registerTool("extension_tool_request_keep_awake",{description:"Request that power management be temporarily disabled to keep the system or display awake",inputSchema:{level:z.enum(["system","display"]).describe('Level of power management to disable. "system" prevents system sleep but allows screen dimming. "display" prevents both system sleep and screen dimming/turning off')}},async({level:e})=>{try{return chrome.power.requestKeepAwake(e),this.formatSuccess("Power management request activated",{level:e,description:e==="system"?"System will stay awake but screen may dim or turn off":"Both system and display will stay awake"})}catch(t){return this.formatError(t)}});}registerReleaseKeepAwake(){this.server.registerTool("extension_tool_release_keep_awake",{description:"Release a previously made power management request, allowing normal power management to resume",inputSchema:{}},async()=>{try{return chrome.power.releaseKeepAwake(),this.formatSuccess("Power management request released",{description:"Normal power management behavior has been restored"})}catch(e){return this.formatError(e)}});}registerReportActivity(){this.server.registerTool("extension_tool_report_activity",{description:"Report user activity to wake the screen from dimmed/off state or exit screensaver (ChromeOS only)",inputSchema:{}},async()=>{try{return typeof chrome.power.reportActivity!="function"?this.formatError("reportActivity is not available. This method requires Chrome 113+ on ChromeOS"):(await new Promise((e,t)=>{chrome.power.reportActivity(()=>{chrome.runtime.lastError?t(new Error(chrome.runtime.lastError.message)):e();});}),this.formatSuccess("User activity reported",{description:"Screen should wake from dimmed/off state and exit screensaver if active"}))}catch(e){return this.formatError(e)}});}};var St=class extends m{apiName="Printing";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.printing?typeof chrome.printing.getPrinters!="function"?{available:!1,message:"chrome.printing.getPrinters is not available",details:"The printing API appears to be partially available. Check manifest permissions and ensure this is running on ChromeOS."}:(chrome.printing.getPrinters(e=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"Printing API is fully available"}):{available:!1,message:"chrome.printing API is not defined",details:'This extension needs the "printing" permission in its manifest.json and only works on ChromeOS'}}catch(e){return {available:false,message:"Failed to access chrome.printing API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("getPrinters")&&this.registerGetPrinters(),this.shouldRegisterTool("getPrinterInfo")&&this.registerGetPrinterInfo(),this.shouldRegisterTool("submitJob")&&this.registerSubmitJob(),this.shouldRegisterTool("cancelJob")&&this.registerCancelJob(),this.shouldRegisterTool("getJobStatus")&&this.registerGetJobStatus();}registerGetPrinters(){this.server.registerTool("extension_tool_get_printers",{description:"Get the list of available printers on the device. This includes manually added, enterprise and discovered printers.",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.printing.getPrinters(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({count:e.length,printers:e.map(t=>({id:t.id,name:t.name,description:t.description,isDefault:t.isDefault,source:t.source,uri:t.uri,recentlyUsedRank:t.recentlyUsedRank}))})}catch(e){return this.formatError(e)}});}registerGetPrinterInfo(){this.server.registerTool("extension_tool_get_printer_info",{description:"Get the status and capabilities of a specific printer in CDD format",inputSchema:{printerId:z.string().describe("The ID of the printer to get information for")}},async({printerId:e})=>{try{let t=await new Promise((r,o)=>{chrome.printing.getPrinterInfo(e,i=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r(i);});});return this.formatJson({printerId:e,status:t.status,capabilities:t.capabilities})}catch(t){return this.formatError(t)}});}registerSubmitJob(){this.server.registerTool("extension_tool_submit_job",{description:'Submit a print job to a printer. Supported content types are "application/pdf" and "image/png". User confirmation may be required unless extension is allowlisted.',inputSchema:{printerId:z.string().describe("The ID of the printer to use"),title:z.string().describe("The title of the print job"),contentType:z.enum(["application/pdf","image/png"]).describe("The content type of the document to print"),documentData:z.string().describe("Base64 encoded document data to print"),ticket:z.object({version:z.string().optional().describe('Ticket version (e.g., "1.0")'),print:z.object({color:z.object({type:z.string().optional().describe('Color type (e.g., "STANDARD_MONOCHROME", "STANDARD_COLOR")')}).optional(),duplex:z.object({type:z.string().optional().describe('Duplex type (e.g., "NO_DUPLEX", "LONG_EDGE", "SHORT_EDGE")')}).optional(),page_orientation:z.object({type:z.string().optional().describe('Page orientation (e.g., "PORTRAIT", "LANDSCAPE")')}).optional(),copies:z.object({copies:z.number().optional().describe("Number of copies to print")}).optional(),dpi:z.object({horizontal_dpi:z.number().optional().describe("Horizontal DPI"),vertical_dpi:z.number().optional().describe("Vertical DPI")}).optional(),media_size:z.object({width_microns:z.number().optional().describe("Paper width in microns"),height_microns:z.number().optional().describe("Paper height in microns")}).optional(),collate:z.object({collate:z.boolean().optional().describe("Whether to collate pages")}).optional(),vendor_ticket_item:z.array(z.object({id:z.string().describe("Vendor capability ID"),value:z.any().describe("Vendor capability value")})).optional().describe("Vendor-specific ticket items")}).optional()}).optional().describe("Print ticket specifying printer capabilities to use")}},async({printerId:e,title:t,contentType:r,documentData:o,ticket:i})=>{try{let s=atob(o),n=new Uint8Array(s.length);for(let d=0;d<s.length;d++)n[d]=s.charCodeAt(d);let a=new Blob([n],{type:r}),c={job:{printerId:e,title:t,ticket:i||{},contentType:r,document:a}},u=await new Promise((d,v)=>{chrome.printing.submitJob(c,S=>{chrome.runtime.lastError?v(new Error(chrome.runtime.lastError.message)):d(S);});});return this.formatJson({status:u.status,jobId:u.jobId,message:u.status==="OK"?"Print job submitted successfully":"Print job was rejected"})}catch(s){return this.formatError(s)}});}registerCancelJob(){this.server.registerTool("extension_tool_cancel_job",{description:"Cancel a previously submitted print job",inputSchema:{jobId:z.string().describe("The ID of the print job to cancel")}},async({jobId:e})=>{try{return await new Promise((t,r)=>{chrome.printing.cancelJob(e,()=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t();});}),this.formatSuccess("Print job cancelled successfully",{jobId:e})}catch(t){return this.formatError(t)}});}registerGetJobStatus(){this.server.registerTool("extension_tool_get_job_status",{description:"Get the status of a print job",inputSchema:{jobId:z.string().describe("The ID of the print job to get status for")}},async({jobId:e})=>{try{let t=await new Promise((r,o)=>{chrome.printing.getJobStatus(e,i=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r(i);});});return this.formatJson({jobId:e,status:t,statusDescription:this.getJobStatusDescription(t)})}catch(t){return this.formatError(t)}});}getJobStatusDescription(e){switch(e){case "PENDING":return "Print job is received on Chrome side but was not processed yet";case "IN_PROGRESS":return "Print job is sent for printing";case "FAILED":return "Print job was interrupted due to some error";case "CANCELED":return "Print job was canceled by the user or via API";case "PRINTED":return "Print job was printed without any errors";default:return "Unknown status"}}};var Tt=class extends m{apiName="PrintingMetrics";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.printingMetrics?typeof chrome.printingMetrics.getPrintJobs!="function"?{available:!1,message:"chrome.printingMetrics.getPrintJobs is not available",details:"The printingMetrics API appears to be partially available. Check manifest permissions and ensure this is running on ChromeOS."}:(chrome.printingMetrics.getPrintJobs(e=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"PrintingMetrics API is fully available"}):{available:!1,message:"chrome.printingMetrics API is not defined",details:'This extension needs the "printingMetrics" permission in its manifest.json and only works on ChromeOS'}}catch(e){return {available:false,message:"Failed to access chrome.printingMetrics API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("getPrintJobs")&&this.registerGetPrintJobs();}registerGetPrintJobs(){this.server.registerTool("extension_tool_get_print_jobs",{description:"Get the list of finished print jobs with details about printers, settings, and status",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.printingMetrics.getPrintJobs(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({count:e.length,jobs:e.map(t=>({id:t.id,title:t.title,status:t.status,source:t.source,sourceId:t.sourceId,numberOfPages:t.numberOfPages,creationTime:t.creationTime,creationTimeFormatted:new Date(t.creationTime).toISOString(),completionTime:t.completionTime,completionTimeFormatted:new Date(t.completionTime).toISOString(),printer:{name:t.printer.name,source:t.printer.source,uri:t.printer.uri},printerStatus:t.printer_status,settings:{color:t.settings.color,copies:t.settings.copies,duplex:t.settings.duplex,mediaSize:{width:t.settings.mediaSize.width,height:t.settings.mediaSize.height,vendorId:t.settings.mediaSize.vendorId}}}))})}catch(e){return this.formatError(e)}});}};var Et=class extends m{apiName="Proxy";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.proxy?!chrome.proxy.settings||typeof chrome.proxy.settings.get!="function"?{available:!1,message:"chrome.proxy.settings.get is not available",details:"The proxy API appears to be partially available. Check manifest permissions."}:(chrome.proxy.settings.get({incognito:!1},e=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"Proxy API is fully available"}):{available:!1,message:"chrome.proxy API is not defined",details:'This extension needs the "proxy" permission in its manifest.json'}}catch(e){return {available:false,message:"Failed to access chrome.proxy API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("getProxySettings")&&this.registerGetProxySettings(),this.shouldRegisterTool("setProxySettings")&&this.registerSetProxySettings(),this.shouldRegisterTool("clearProxySettings")&&this.registerClearProxySettings();}registerGetProxySettings(){this.server.registerTool("extension_tool_get_proxy_settings",{description:"Get the current proxy configuration settings",inputSchema:{incognito:z.boolean().optional().default(false).describe("Whether to get proxy settings for incognito mode")}},async({incognito:e})=>{try{let t=await new Promise((r,o)=>{chrome.proxy.settings.get({incognito:e},i=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r(i);});});return this.formatJson({levelOfControl:t.levelOfControl,value:t.value,incognitoSpecific:t.incognitoSpecific})}catch(t){return this.formatError(t)}});}registerSetProxySettings(){this.server.registerTool("extension_tool_set_proxy_settings",{description:"Set proxy configuration settings",inputSchema:{mode:z.enum(["direct","auto_detect","pac_script","fixed_servers","system"]).describe("Proxy mode to use"),scope:z.enum(["regular","regular_only","incognito_persistent","incognito_session_only"]).optional().default("regular").describe("Scope of the setting"),pacScriptUrl:z.string().optional().describe("URL of the PAC file (for pac_script mode)"),pacScriptData:z.string().optional().describe("PAC script content (for pac_script mode)"),pacScriptMandatory:z.boolean().optional().describe("Whether PAC script is mandatory"),singleProxyHost:z.string().optional().describe("Host for single proxy (for fixed_servers mode)"),singleProxyPort:z.number().optional().describe("Port for single proxy (for fixed_servers mode)"),singleProxyScheme:z.enum(["http","https","quic","socks4","socks5"]).optional().describe("Scheme for single proxy (for fixed_servers mode)"),httpProxyHost:z.string().optional().describe("Host for HTTP proxy (for fixed_servers mode)"),httpProxyPort:z.number().optional().describe("Port for HTTP proxy (for fixed_servers mode)"),httpProxyScheme:z.enum(["http","https","quic","socks4","socks5"]).optional().describe("Scheme for HTTP proxy (for fixed_servers mode)"),httpsProxyHost:z.string().optional().describe("Host for HTTPS proxy (for fixed_servers mode)"),httpsProxyPort:z.number().optional().describe("Port for HTTPS proxy (for fixed_servers mode)"),httpsProxyScheme:z.enum(["http","https","quic","socks4","socks5"]).optional().describe("Scheme for HTTPS proxy (for fixed_servers mode)"),ftpProxyHost:z.string().optional().describe("Host for FTP proxy (for fixed_servers mode)"),ftpProxyPort:z.number().optional().describe("Port for FTP proxy (for fixed_servers mode)"),ftpProxyScheme:z.enum(["http","https","quic","socks4","socks5"]).optional().describe("Scheme for FTP proxy (for fixed_servers mode)"),fallbackProxyHost:z.string().optional().describe("Host for fallback proxy (for fixed_servers mode)"),fallbackProxyPort:z.number().optional().describe("Port for fallback proxy (for fixed_servers mode)"),fallbackProxyScheme:z.enum(["http","https","quic","socks4","socks5"]).optional().describe("Scheme for fallback proxy (for fixed_servers mode)"),bypassList:z.array(z.string()).optional().describe("List of servers to bypass proxy (for fixed_servers mode)")}},async({mode:e,scope:t,pacScriptUrl:r,pacScriptData:o,pacScriptMandatory:i,singleProxyHost:s,singleProxyPort:n,singleProxyScheme:a,httpProxyHost:c,httpProxyPort:u,httpProxyScheme:d,httpsProxyHost:v,httpsProxyPort:S,httpsProxyScheme:P,ftpProxyHost:I,ftpProxyPort:O,ftpProxyScheme:ne,fallbackProxyHost:H,fallbackProxyPort:U,fallbackProxyScheme:ae,bypassList:Se})=>{try{let fe={mode:e};if(e==="pac_script"){let K={};if(r!==void 0&&(K.url=r),o!==void 0&&(K.data=o),i!==void 0&&(K.mandatory=i),Object.keys(K).length===0)return this.formatError("PAC script URL or data must be provided for pac_script mode");fe.pacScript=K;}else if(e==="fixed_servers"){let K={};if(s){let q={host:s};n!==void 0&&(q.port=n),a!==void 0&&(q.scheme=a),K.singleProxy=q;}else {if(c){let q={host:c};u!==void 0&&(q.port=u),d!==void 0&&(q.scheme=d),K.proxyForHttp=q;}if(v){let q={host:v};S!==void 0&&(q.port=S),P!==void 0&&(q.scheme=P),K.proxyForHttps=q;}if(I){let q={host:I};O!==void 0&&(q.port=O),ne!==void 0&&(q.scheme=ne),K.proxyForFtp=q;}if(H){let q={host:H};U!==void 0&&(q.port=U),ae!==void 0&&(q.scheme=ae),K.fallbackProxy=q;}}if(Se!==void 0&&(K.bypassList=Se),Object.keys(K).length===0)return this.formatError("At least one proxy server must be specified for fixed_servers mode");fe.rules=K;}return await new Promise((K,q)=>{chrome.proxy.settings.set({value:fe,scope:t},()=>{chrome.runtime.lastError?q(new Error(chrome.runtime.lastError.message)):K();});}),this.formatSuccess("Proxy settings updated successfully",{mode:e,scope:t,config:fe})}catch(fe){return this.formatError(fe)}});}registerClearProxySettings(){this.server.registerTool("extension_tool_clear_proxy_settings",{description:"Clear proxy settings and revert to default",inputSchema:{scope:z.enum(["regular","regular_only","incognito_persistent","incognito_session_only"]).optional().default("regular").describe("Scope of the setting to clear")}},async({scope:e})=>{try{return await new Promise((t,r)=>{chrome.proxy.settings.clear({scope:e},()=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t();});}),this.formatSuccess("Proxy settings cleared successfully",{scope:e})}catch(t){return this.formatError(t)}});}};var _t=class extends m{apiName="ReadingList";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.readingList?typeof chrome.readingList.query!="function"?{available:!1,message:"chrome.readingList.query is not available",details:"The readingList API appears to be partially available. Check manifest permissions."}:(chrome.readingList.query({},e=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"ReadingList API is fully available"}):{available:!1,message:"chrome.readingList API is not defined",details:'This extension needs the "readingList" permission in its manifest.json'}}catch(e){return {available:false,message:"Failed to access chrome.readingList API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("addEntry")&&this.registerAddEntry(),this.shouldRegisterTool("query")&&this.registerQuery(),this.shouldRegisterTool("removeEntry")&&this.registerRemoveEntry(),this.shouldRegisterTool("updateEntry")&&this.registerUpdateEntry();}registerAddEntry(){this.server.registerTool("extension_tool_add_reading_list_entry",{description:"Add an entry to the reading list if it does not exist",inputSchema:{title:z.string().describe("The title of the entry"),url:z.string().url().describe("The URL of the entry"),hasBeenRead:z.boolean().describe("Whether the entry has been read")}},async({title:e,url:t,hasBeenRead:r})=>{try{return await new Promise((o,i)=>{chrome.readingList.addEntry({title:e,url:t,hasBeenRead:r},()=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o();});}),this.formatSuccess("Reading list entry added successfully",{title:e,url:t,hasBeenRead:r})}catch(o){return this.formatError(o)}});}registerQuery(){this.server.registerTool("extension_tool_query_reading_list",{description:"Retrieve all entries that match the query criteria. Properties that are not provided will not be matched",inputSchema:{hasBeenRead:z.boolean().optional().describe("Indicates whether to search for read (true) or unread (false) items"),title:z.string().optional().describe("A title to search for"),url:z.string().optional().describe("A URL to search for")}},async({hasBeenRead:e,title:t,url:r})=>{try{let o={};e!==void 0&&(o.hasBeenRead=e),t!==void 0&&(o.title=t),r!==void 0&&(o.url=r);let i=await new Promise((s,n)=>{chrome.readingList.query(o,a=>{chrome.runtime.lastError?n(new Error(chrome.runtime.lastError.message)):s(a);});});return this.formatJson({count:i.length,entries:i.map(s=>({title:s.title,url:s.url,hasBeenRead:s.hasBeenRead,creationTime:s.creationTime,creationTimeFormatted:new Date(s.creationTime).toISOString(),lastUpdateTime:s.lastUpdateTime,lastUpdateTimeFormatted:new Date(s.lastUpdateTime).toISOString()}))})}catch(o){return this.formatError(o)}});}registerRemoveEntry(){this.server.registerTool("extension_tool_remove_reading_list_entry",{description:"Remove an entry from the reading list if it exists",inputSchema:{url:z.string().url().describe("The URL to remove")}},async({url:e})=>{try{return await new Promise((t,r)=>{chrome.readingList.removeEntry({url:e},()=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t();});}),this.formatSuccess("Reading list entry removed successfully",{url:e})}catch(t){return this.formatError(t)}});}registerUpdateEntry(){this.server.registerTool("extension_tool_update_reading_list_entry",{description:"Update a reading list entry if it exists",inputSchema:{url:z.string().url().describe("The URL that will be updated"),title:z.string().optional().describe("The new title. The existing title remains if a value is not provided"),hasBeenRead:z.boolean().optional().describe("The updated read status. The existing status remains if a value is not provided")}},async({url:e,title:t,hasBeenRead:r})=>{try{let o={url:e};return t!==void 0&&(o.title=t),r!==void 0&&(o.hasBeenRead=r),await new Promise((i,s)=>{chrome.readingList.updateEntry(o,()=>{chrome.runtime.lastError?s(new Error(chrome.runtime.lastError.message)):i();});}),this.formatSuccess("Reading list entry updated successfully",{url:e,title:t,hasBeenRead:r})}catch(o){return this.formatError(o)}});}};var At=class extends m{apiName="Runtime";constructor(e,t={}){super(e,t);}checkAvailability(){try{if(!chrome.runtime)return {available:!1,message:"chrome.runtime API is not defined",details:"The runtime API should be available in all extension contexts"};if(typeof chrome.runtime.getManifest!="function")return {available:!1,message:"chrome.runtime.getManifest is not available",details:"The runtime API appears to be partially available."};if(!chrome.runtime.getManifest())throw new Error("Failed to get manifest");return {available:!0,message:"Runtime API is fully available"}}catch(e){return {available:false,message:"Failed to access chrome.runtime API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("connect")&&this.registerConnect(),this.shouldRegisterTool("connectNative")&&this.registerConnectNative(),this.shouldRegisterTool("getContexts")&&this.registerGetContexts(),this.shouldRegisterTool("getManifest")&&this.registerGetManifest(),this.shouldRegisterTool("getPackageDirectoryEntry")&&this.registerGetPackageDirectoryEntry(),this.shouldRegisterTool("getPlatformInfo")&&this.registerGetPlatformInfo(),this.shouldRegisterTool("getURL")&&this.registerGetURL(),this.shouldRegisterTool("openOptionsPage")&&this.registerOpenOptionsPage(),this.shouldRegisterTool("reload")&&this.registerReload(),this.shouldRegisterTool("requestUpdateCheck")&&this.registerRequestUpdateCheck(),this.shouldRegisterTool("restart")&&this.registerRestart(),this.shouldRegisterTool("restartAfterDelay")&&this.registerRestartAfterDelay(),this.shouldRegisterTool("sendMessage")&&this.registerSendMessage(),this.shouldRegisterTool("sendNativeMessage")&&this.registerSendNativeMessage(),this.shouldRegisterTool("setUninstallURL")&&this.registerSetUninstallURL();}registerConnect(){this.server.registerTool("extension_tool_runtime_connect",{description:"Connect to listeners within an extension or other extensions/apps",inputSchema:{extensionId:z.string().optional().describe("The ID of the extension to connect to. If omitted, connects to your own extension"),name:z.string().optional().describe("Will be passed into onConnect for processes listening for the connection event"),includeTlsChannelId:z.boolean().optional().describe("Whether the TLS channel ID will be passed into onConnectExternal")}},async({extensionId:e,name:t,includeTlsChannelId:r})=>{try{let o={};t!==void 0&&(o.name=t),r!==void 0&&(o.includeTlsChannelId=r);let i;return e?i=chrome.runtime.connect(e,o):i=chrome.runtime.connect(o),this.formatSuccess("Connection established successfully",{portName:i.name,extensionId:e||"own extension",sender:i.sender?{id:i.sender.id,url:i.sender.url,tab:i.sender.tab?{id:i.sender.tab.id,url:i.sender.tab.url}:void 0}:void 0})}catch(o){return this.formatError(o)}});}registerConnectNative(){this.server.registerTool("extension_tool_runtime_connect_native",{description:'Connect to a native application in the host machine. Requires "nativeMessaging" permission',inputSchema:{application:z.string().describe("The name of the registered application to connect to")}},async({application:e})=>{try{let t=chrome.runtime.connectNative(e);return this.formatSuccess("Native connection established successfully",{portName:t.name,application:e})}catch(t){return this.formatError(t)}});}registerGetContexts(){this.server.registerTool("extension_tool_runtime_get_contexts",{description:"Fetch information about active contexts associated with this extension",inputSchema:{contextTypes:z.array(z.enum(["TAB","POPUP","BACKGROUND","OFFSCREEN_DOCUMENT","SIDE_PANEL","DEVELOPER_TOOLS"])).optional().describe("Filter by context types"),contextIds:z.array(z.string()).optional().describe("Filter by specific context IDs"),tabIds:z.array(z.number()).optional().describe("Filter by tab IDs"),windowIds:z.array(z.number()).optional().describe("Filter by window IDs"),frameIds:z.array(z.number()).optional().describe("Filter by frame IDs"),documentIds:z.array(z.string()).optional().describe("Filter by document IDs"),documentUrls:z.array(z.string()).optional().describe("Filter by document URLs"),documentOrigins:z.array(z.string()).optional().describe("Filter by document origins"),incognito:z.boolean().optional().describe("Filter by incognito status")}},async({contextTypes:e,contextIds:t,tabIds:r,windowIds:o,frameIds:i,documentIds:s,documentUrls:n,documentOrigins:a,incognito:c})=>{try{let u={};e!==void 0&&(u.contextTypes=e),t!==void 0&&(u.contextIds=t),r!==void 0&&(u.tabIds=r),o!==void 0&&(u.windowIds=o),i!==void 0&&(u.frameIds=i),s!==void 0&&(u.documentIds=s),n!==void 0&&(u.documentUrls=n),a!==void 0&&(u.documentOrigins=a),c!==void 0&&(u.incognito=c);let d=await new Promise((v,S)=>{chrome.runtime.getContexts(u,P=>{chrome.runtime.lastError?S(new Error(chrome.runtime.lastError.message)):v(P);});});return this.formatJson({count:d.length,contexts:d.map(v=>({contextId:v.contextId,contextType:v.contextType,documentId:v.documentId,documentOrigin:v.documentOrigin,documentUrl:v.documentUrl,frameId:v.frameId,incognito:v.incognito,tabId:v.tabId,windowId:v.windowId}))})}catch(u){return this.formatError(u)}});}registerGetManifest(){this.server.registerTool("extension_tool_runtime_get_manifest",{description:"Get details about the app or extension from the manifest",inputSchema:{}},async()=>{try{let e=chrome.runtime.getManifest();return this.formatJson({manifest:e,name:e.name,version:e.version,manifestVersion:e.manifest_version,description:e.description,permissions:e.permissions||[],hostPermissions:e.host_permissions||[]})}catch(e){return this.formatError(e)}});}registerGetPackageDirectoryEntry(){this.server.registerTool("extension_tool_runtime_get_package_directory_entry",{description:"Get a DirectoryEntry for the package directory",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.runtime.getPackageDirectoryEntry(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({name:e.name,fullPath:e.fullPath,isDirectory:e.isDirectory,isFile:e.isFile})}catch(e){return this.formatError(e)}});}registerGetPlatformInfo(){this.server.registerTool("extension_tool_runtime_get_platform_info",{description:"Get information about the current platform",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.runtime.getPlatformInfo(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({os:e.os,arch:e.arch,nacl_arch:e.nacl_arch})}catch(e){return this.formatError(e)}});}registerGetURL(){this.server.registerTool("extension_tool_runtime_get_url",{description:"Convert a relative path within an app/extension install directory to a fully-qualified URL",inputSchema:{path:z.string().describe("A path to a resource within an app/extension expressed relative to its install directory")}},async({path:e})=>{try{let t=chrome.runtime.getURL(e);return this.formatJson({relativePath:e,fullUrl:t})}catch(t){return this.formatError(t)}});}registerOpenOptionsPage(){this.server.registerTool("extension_tool_runtime_open_options_page",{description:"Open the extension's options page",inputSchema:{}},async()=>{try{return await new Promise((e,t)=>{chrome.runtime.openOptionsPage(()=>{chrome.runtime.lastError?t(new Error(chrome.runtime.lastError.message)):e();});}),this.formatSuccess("Options page opened successfully")}catch(e){return this.formatError(e)}});}registerReload(){this.server.registerTool("extension_tool_runtime_reload",{description:"Reload the app or extension",inputSchema:{}},async()=>{try{return chrome.runtime.reload(),this.formatSuccess("Extension reload initiated")}catch(e){return this.formatError(e)}});}registerRequestUpdateCheck(){this.server.registerTool("extension_tool_runtime_request_update_check",{description:"Request an immediate update check for this app/extension",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.runtime.requestUpdateCheck(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({status:e.status,version:e.version})}catch(e){return this.formatError(e)}});}registerRestart(){this.server.registerTool("extension_tool_runtime_restart",{description:"Restart the ChromeOS device when the app runs in kiosk mode",inputSchema:{}},async()=>{try{return chrome.runtime.restart(),this.formatSuccess("Device restart initiated (kiosk mode only)")}catch(e){return this.formatError(e)}});}registerRestartAfterDelay(){this.server.registerTool("extension_tool_runtime_restart_after_delay",{description:"Restart the ChromeOS device after a delay when the app runs in kiosk mode",inputSchema:{seconds:z.number().describe("Time to wait in seconds before rebooting the device, or -1 to cancel a scheduled reboot")}},async({seconds:e})=>{try{return await new Promise((t,r)=>{chrome.runtime.restartAfterDelay(e,()=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t();});}),e===-1?this.formatSuccess("Scheduled restart cancelled"):this.formatSuccess("Device restart scheduled",{delaySeconds:e})}catch(t){return this.formatError(t)}});}registerSendMessage(){this.server.registerTool("extension_tool_runtime_send_message",{description:"Send a single message to event listeners within your extension or a different extension/app",inputSchema:{message:z.any().describe("The message to send. This message should be a JSON-ifiable object"),extensionId:z.string().optional().describe("The ID of the extension to send the message to. If omitted, sends to your own extension"),includeTlsChannelId:z.boolean().optional().describe("Whether the TLS channel ID will be passed into onMessageExternal")}},async({message:e,extensionId:t,includeTlsChannelId:r})=>{try{let o={};r!==void 0&&(o.includeTlsChannelId=r);let i=await new Promise((s,n)=>{t?chrome.runtime.sendMessage(t,e,o,a=>{chrome.runtime.lastError?n(new Error(chrome.runtime.lastError.message)):s(a);}):chrome.runtime.sendMessage(e,o,a=>{chrome.runtime.lastError?n(new Error(chrome.runtime.lastError.message)):s(a);});});return this.formatJson({messageSent:e,response:i,extensionId:t||"own extension"})}catch(o){return this.formatError(o)}});}registerSendNativeMessage(){this.server.registerTool("extension_tool_runtime_send_native_message",{description:'Send a single message to a native application. Requires "nativeMessaging" permission',inputSchema:{application:z.string().describe("The name of the native messaging host"),message:z.any().describe("The message that will be passed to the native messaging host")}},async({application:e,message:t})=>{try{let r=await new Promise((o,i)=>{chrome.runtime.sendNativeMessage(e,t,s=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o(s);});});return this.formatJson({application:e,messageSent:t,response:r})}catch(r){return this.formatError(r)}});}registerSetUninstallURL(){this.server.registerTool("extension_tool_runtime_set_uninstall_url",{description:"Set the URL to be visited upon uninstallation. Maximum 1023 characters",inputSchema:{url:z.string().max(1023).describe("URL to be opened after the extension is uninstalled. Must have http: or https: scheme. Set empty string to not open a new tab")}},async({url:e})=>{try{return await new Promise((t,r)=>{chrome.runtime.setUninstallURL(e,()=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t();});}),this.formatSuccess("Uninstall URL set successfully",{url:e})}catch(t){return this.formatError(t)}});}};var xt=class extends m{apiName="Scripting";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.scripting?typeof chrome.scripting.executeScript!="function"?{available:!1,message:"chrome.scripting.executeScript is not available",details:'The scripting API appears to be partially available. Ensure you have Chrome 88+ and the "scripting" permission.'}:{available:!0,message:"Scripting API is available"}:{available:!1,message:"chrome.scripting API is not defined",details:'This extension needs the "scripting" permission in its manifest.json. This API is available in Chrome 88+.'}}catch(e){return {available:false,message:"Failed to access chrome.scripting API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("executeScript")&&this.registerExecuteScript(),this.shouldRegisterTool("executeUserScript")&&this.checkAndRegisterUserScripts(),this.shouldRegisterTool("insertCSS")&&this.registerInsertCSS(),this.shouldRegisterTool("removeCSS")&&this.registerRemoveCSS();}checkAndRegisterUserScripts(){if(!chrome.userScripts){console.warn("UserScripts API not available - Chrome 120+ required");return}try{chrome.userScripts.getScripts(),this.getChromeVersion()>=135?(console.log("UserScripts execute() method available (Chrome 135+)"),this.registerUserScriptExecute()):(console.log("UserScripts API available (legacy mode)"),this.registerUserScriptLegacy());}catch{console.warn('UserScripts API not enabled. Users need to enable developer mode and "User Scripts" toggle in chrome://extensions');}}getChromeVersion(){let e=navigator.userAgent.match(/(Chrome|Chromium)\/([0-9]+)/);return e?Number(e[2]):0}registerExecuteScript(){this.server.registerTool("extension_tool_execute_script",{description:"Execute JavaScript code in a specific tab using chrome.scripting API. Limited by CSP restrictions. If no tabId is specified, operates on the currently active tab",inputSchema:{tabId:z.number().optional().describe("Tab ID to execute script in (defaults to active tab)"),code:z.string().describe("JavaScript code to execute"),allFrames:z.boolean().optional().describe("Execute in all frames (default: false)"),world:z.enum(["MAIN","ISOLATED"]).optional().default("MAIN").describe("Execution world - MAIN runs in page context, ISOLATED runs in extension context")}},async({tabId:e,code:t,allFrames:r=false,world:o="MAIN"})=>{try{if(e===void 0){let[n]=await chrome.tabs.query({active:!0,currentWindow:!0});if(!n||!n.id)return this.formatError(new Error("No active tab found"));e=n.id;}let i=n=>{try{let a=document.createElement("script");a.textContent=`
3
3
  (function() {
4
4
  try {
5
5
  const __result = (function() { ${n} })();
6
6
  window.__extensionScriptResult = { success: true, result: __result };
7
7
  } catch (error) {
8
- window.__extensionScriptResult = {
9
- success: false,
10
- error: error.message || String(error)
8
+ window.__extensionScriptResult = {
9
+ success: false,
10
+ error: error.message || String(error)
11
11
  };
12
12
  }
13
13
  })();
14
- `,document.documentElement.appendChild(a),a.remove();let c=window.__extensionScriptResult;return delete window.__extensionScriptResult,c||{success:!1,error:"No result returned"}}catch(a){return {success:!1,error:a instanceof Error?a.message:String(a)}}},s=await chrome.scripting.executeScript({target:{tabId:e,allFrames:r},func:i,args:[t],world:o});return this.formatJson(s)}catch(i){return this.formatError(i)}});}registerUserScriptExecute(){this.server.registerTool("extension_tool_execute_user_script",{description:"Execute JavaScript using User Scripts API with no CSP restrictions (Chrome 135+). Requires user to enable developer mode. If no tabId is specified, operates on the currently active tab",inputSchema:{tabId:z.number().optional().describe("Tab ID to execute script in (defaults to active tab)"),code:z.string().describe("JavaScript code to execute"),allFrames:z.boolean().optional().describe("Execute in all frames (default: false)"),world:z.enum(["USER_SCRIPT","MAIN"]).optional().default("USER_SCRIPT").describe("Execution world (default: USER_SCRIPT for no CSP restrictions)")}},async({tabId:e,code:t,allFrames:r=false,world:o="USER_SCRIPT"})=>{try{if(e===void 0){let[s]=await chrome.tabs.query({active:!0,currentWindow:!0});if(!s||!s.id)return this.formatError(new Error("No active tab found"));e=s.id;}chrome.userScripts.configureWorld({messaging:!0,csp:"script-src 'self' 'unsafe-eval'; object-src 'self';"});let i=await chrome.userScripts.execute({target:{tabId:e,allFrames:r},world:o,js:[{code:t}],injectImmediately:!0});return this.formatJson(i)}catch(i){return i instanceof Error&&i.message.includes("User Scripts")?this.formatError(new Error('User Scripts API is not enabled. Enable developer mode and the "User Scripts" toggle in chrome://extensions/?id='+chrome.runtime.id)):this.formatError(i)}});}registerUserScriptLegacy(){this.server.registerTool("extension_tool_execute_user_script_legacy",{description:"Execute JavaScript using User Scripts API (legacy method for Chrome < 135). No CSP restrictions. If no tabId is specified, operates on the currently active tab",inputSchema:{tabId:z.number().optional().describe("Tab ID to execute script in (defaults to active tab)"),code:z.string().describe("JavaScript code to execute"),allFrames:z.boolean().optional().describe("Execute in all frames (default: false)")}},async({tabId:e,code:t,allFrames:r=false})=>{try{if(e===void 0){let[a]=await chrome.tabs.query({active:!0,currentWindow:!0});if(!a||!a.id)return this.formatError(new Error("No active tab found"));e=a.id;}let o=await chrome.tabs.get(e);if(!o.url)return this.formatError(new Error("Tab URL not available"));let i=`temp_${Date.now()}`;await chrome.userScripts.configureWorld({messaging:!0});let s=new Promise(a=>{let c=(u,m)=>{u.type==="SCRIPT_RESULT"&&u.scriptId===i&&(chrome.runtime.onUserScriptMessage.removeListener(c),a(u));};chrome.runtime.onUserScriptMessage.addListener(c);});await chrome.userScripts.register([{id:i,matches:[new URL(o.url).origin+"/*"],js:[{code:`
14
+ `,document.documentElement.appendChild(a),a.remove();let c=window.__extensionScriptResult;return delete window.__extensionScriptResult,c||{success:!1,error:"No result returned"}}catch(a){return {success:!1,error:a instanceof Error?a.message:String(a)}}},s=await chrome.scripting.executeScript({target:{tabId:e,allFrames:r},func:i,args:[t],world:o});return this.formatJson(s)}catch(i){return this.formatError(i)}});}registerUserScriptExecute(){this.server.registerTool("extension_tool_execute_user_script",{description:"Execute JavaScript using User Scripts API with no CSP restrictions (Chrome 135+). Requires user to enable developer mode. If no tabId is specified, operates on the currently active tab",inputSchema:{tabId:z.number().optional().describe("Tab ID to execute script in (defaults to active tab)"),code:z.string().describe("JavaScript code to execute"),allFrames:z.boolean().optional().describe("Execute in all frames (default: false)"),world:z.enum(["USER_SCRIPT","MAIN"]).optional().default("USER_SCRIPT").describe("Execution world (default: USER_SCRIPT for no CSP restrictions)")}},async({tabId:e,code:t,allFrames:r=false,world:o="USER_SCRIPT"})=>{try{if(e===void 0){let[s]=await chrome.tabs.query({active:!0,currentWindow:!0});if(!s||!s.id)return this.formatError(new Error("No active tab found"));e=s.id;}chrome.userScripts.configureWorld({messaging:!0,csp:"script-src 'self' 'unsafe-eval'; object-src 'self';"});let i=await chrome.userScripts.execute({target:{tabId:e,allFrames:r},world:o,js:[{code:t}],injectImmediately:!0});return this.formatJson(i)}catch(i){return i instanceof Error&&i.message.includes("User Scripts")?this.formatError(new Error('User Scripts API is not enabled. Enable developer mode and the "User Scripts" toggle in chrome://extensions/?id='+chrome.runtime.id)):this.formatError(i)}});}registerUserScriptLegacy(){this.server.registerTool("extension_tool_execute_user_script_legacy",{description:"Execute JavaScript using User Scripts API (legacy method for Chrome < 135). No CSP restrictions. If no tabId is specified, operates on the currently active tab",inputSchema:{tabId:z.number().optional().describe("Tab ID to execute script in (defaults to active tab)"),code:z.string().describe("JavaScript code to execute"),allFrames:z.boolean().optional().describe("Execute in all frames (default: false)")}},async({tabId:e,code:t,allFrames:r=false})=>{try{if(e===void 0){let[a]=await chrome.tabs.query({active:!0,currentWindow:!0});if(!a||!a.id)return this.formatError(new Error("No active tab found"));e=a.id;}let o=await chrome.tabs.get(e);if(!o.url)return this.formatError(new Error("Tab URL not available"));let i=`temp_${Date.now()}`;await chrome.userScripts.configureWorld({messaging:!0});let s=new Promise(a=>{let c=(u,d)=>{u.type==="SCRIPT_RESULT"&&u.scriptId===i&&(chrome.runtime.onUserScriptMessage.removeListener(c),a(u));};chrome.runtime.onUserScriptMessage.addListener(c);});await chrome.userScripts.register([{id:i,matches:[new URL(o.url).origin+"/*"],js:[{code:`
15
15
  (async () => {
16
16
  try {
17
17
  const result = await (async () => { ${t} })();
@@ -30,6 +30,6 @@ ${JSON.stringify(t,null,2)}`:e}]}}formatJson(e){return {content:[{type:"text",te
30
30
  });
31
31
  }
32
32
  })();
33
- `}],runAt:"document_idle",world:"USER_SCRIPT",allFrames:r}]),await chrome.tabs.reload(e);let n=await Promise.race([s,new Promise(a=>setTimeout(()=>a({timeout:!0}),5e3))]);return await chrome.userScripts.unregister({ids:[i]}),n.timeout?this.formatError(new Error("Script execution timed out")):this.formatJson(n)}catch(o){return this.formatError(o)}});}registerInsertCSS(){this.server.registerTool("extension_tool_insert_css",{description:"Insert CSS into a tab. If no tabId is specified, operates on the currently active tab",inputSchema:{tabId:z.number().optional().describe("Tab ID to insert CSS into (defaults to active tab)"),css:z.string().describe("CSS code to inject"),allFrames:z.boolean().optional().describe("Inject in all frames (default: false)")}},async({tabId:e,css:t,allFrames:r=false})=>{try{if(e===void 0){let[o]=await chrome.tabs.query({active:!0,currentWindow:!0});if(!o||!o.id)return this.formatError(new Error("No active tab found"));e=o.id;}return await chrome.scripting.insertCSS({target:{tabId:e,allFrames:r},css:t}),this.formatSuccess(`CSS injected into tab ${e}`)}catch(o){return this.formatError(o)}});}registerRemoveCSS(){if(typeof chrome.scripting.removeCSS!="function"){console.warn(" \u2717 removeCSS not available - Chrome 90+ required");return}this.server.registerTool("extension_tool_remove_css",{description:"Remove previously injected CSS from a tab. If no tabId is specified, operates on the currently active tab",inputSchema:{tabId:z.number().optional().describe("Tab ID to remove CSS from (defaults to active tab)"),css:z.string().describe("CSS code to remove (must match exactly)"),allFrames:z.boolean().optional().describe("Remove from all frames (default: false)")}},async({tabId:e,css:t,allFrames:r=false})=>{try{if(e===void 0){let[o]=await chrome.tabs.query({active:!0,currentWindow:!0});if(!o||!o.id)return this.formatError(new Error("No active tab found"));e=o.id;}return await chrome.scripting.removeCSS({target:{tabId:e,allFrames:r},css:t}),this.formatSuccess(`CSS removed from tab ${e}`)}catch(o){return this.formatError(o)}});}};var xt=class extends d{apiName="Search";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.search?typeof chrome.search.query!="function"?{available:!1,message:"chrome.search.query is not available",details:"The search API appears to be partially available. Check manifest permissions."}:{available:!0,message:"Search API is fully available"}:{available:!1,message:"chrome.search API is not defined",details:'This extension needs the "search" permission in its manifest.json'}}catch(e){return {available:false,message:"Failed to access chrome.search API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("query")&&this.registerQuery();}registerQuery(){this.server.registerTool("extension_tool_search_query",{description:"Search using the default search provider",inputSchema:{text:z.string().describe("String to query with the default search provider"),disposition:z.enum(["CURRENT_TAB","NEW_TAB","NEW_WINDOW"]).optional().describe("Location where search results should be displayed. CURRENT_TAB is the default"),tabId:z.number().optional().describe("Tab ID where search results should be displayed. Cannot be used with disposition")}},async({text:e,disposition:t,tabId:r})=>{try{if(t!==void 0&&r!==void 0)return this.formatError("Cannot specify both disposition and tabId. Use one or the other");let o={text:e};return t!==void 0&&(o.disposition=t),r!==void 0&&(o.tabId=r),await new Promise((i,s)=>{chrome.search.query(o,()=>{chrome.runtime.lastError?s(new Error(chrome.runtime.lastError.message)):i();});}),this.formatSuccess("Search query executed successfully",{text:e,disposition:t||"CURRENT_TAB",tabId:r})}catch(o){return this.formatError(o)}});}};var At=class extends d{apiName="Sessions";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.sessions?typeof chrome.sessions.getRecentlyClosed!="function"?{available:!1,message:"chrome.sessions.getRecentlyClosed is not available",details:"The sessions API appears to be partially available. Check manifest permissions."}:(chrome.sessions.getRecentlyClosed(e=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"Sessions API is fully available"}):{available:!1,message:"chrome.sessions API is not defined",details:'This extension needs the "sessions" permission in its manifest.json'}}catch(e){return {available:false,message:"Failed to access chrome.sessions API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("getDevices")&&this.registerGetDevices(),this.shouldRegisterTool("getRecentlyClosed")&&this.registerGetRecentlyClosed(),this.shouldRegisterTool("restore")&&this.registerRestore();}registerGetDevices(){this.server.registerTool("extension_tool_get_devices",{description:"Retrieve all devices with synced sessions",inputSchema:{maxResults:z.number().min(1).max(25).optional().describe("The maximum number of entries to be fetched. Omit to fetch the maximum number of entries (25)")}},async({maxResults:e})=>{try{let t={};e!==void 0&&(t.maxResults=e);let r=await new Promise((o,i)=>{chrome.sessions.getDevices(t,s=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o(s);});});return this.formatJson({count:r.length,devices:r.map(o=>({deviceName:o.deviceName,sessionCount:o.sessions.length,sessions:o.sessions.map(i=>({lastModified:i.lastModified,lastModifiedFormatted:new Date(i.lastModified*1e3).toISOString(),tab:i.tab?{id:i.tab.id,url:i.tab.url,title:i.tab.title,sessionId:i.tab.sessionId}:void 0,window:i.window?{id:i.window.id,sessionId:i.window.sessionId,tabCount:i.window.tabs?.length||0}:void 0}))}))})}catch(t){return this.formatError(t)}});}registerGetRecentlyClosed(){this.server.registerTool("extension_tool_get_recently_closed",{description:"Get the list of recently closed tabs and/or windows",inputSchema:{maxResults:z.number().min(1).max(25).optional().describe("The maximum number of entries to be fetched. Omit to fetch the maximum number of entries (25)")}},async({maxResults:e})=>{try{let t={};e!==void 0&&(t.maxResults=e);let r=await new Promise((o,i)=>{chrome.sessions.getRecentlyClosed(t,s=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o(s);});});return this.formatJson({count:r.length,sessions:r.map(o=>({lastModified:o.lastModified,lastModifiedFormatted:new Date(o.lastModified*1e3).toISOString(),tab:o.tab?{id:o.tab.id,url:o.tab.url,title:o.tab.title,sessionId:o.tab.sessionId,favIconUrl:o.tab.favIconUrl}:void 0,window:o.window?{id:o.window.id,sessionId:o.window.sessionId,tabCount:o.window.tabs?.length||0,incognito:o.window.incognito,type:o.window.type}:void 0}))})}catch(t){return this.formatError(t)}});}registerRestore(){this.server.registerTool("extension_tool_restore_session",{description:"Reopen a recently closed window or tab",inputSchema:{sessionId:z.string().optional().describe("The sessionId of the window or tab to restore. If not specified, the most recently closed session is restored")}},async({sessionId:e})=>{try{let t=await new Promise((r,o)=>{e?chrome.sessions.restore(e,i=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r(i);}):chrome.sessions.restore(i=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r(i);});});return this.formatSuccess("Session restored successfully",{lastModified:t.lastModified,lastModifiedFormatted:new Date(t.lastModified*1e3).toISOString(),tab:t.tab?{id:t.tab.id,url:t.tab.url,title:t.tab.title,sessionId:t.tab.sessionId}:void 0,window:t.window?{id:t.window.id,sessionId:t.window.sessionId,tabCount:t.window.tabs?.length||0,incognito:t.window.incognito,type:t.window.type}:void 0})}catch(t){return this.formatError(t)}});}};var It=class extends d{apiName="SidePanel";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.sidePanel?typeof chrome.sidePanel.getOptions!="function"?{available:!1,message:"chrome.sidePanel.getOptions is not available",details:"The sidePanel API appears to be partially available. Check manifest permissions."}:(chrome.sidePanel.getOptions({},e=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"SidePanel API is fully available"}):{available:!1,message:"chrome.sidePanel API is not defined",details:'This extension needs the "sidePanel" permission in its manifest.json'}}catch(e){return {available:false,message:"Failed to access chrome.sidePanel API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("getOptions")&&this.registerGetOptions(),this.shouldRegisterTool("setOptions")&&this.registerSetOptions(),this.shouldRegisterTool("getPanelBehavior")&&this.registerGetPanelBehavior(),this.shouldRegisterTool("setPanelBehavior")&&this.registerSetPanelBehavior(),this.shouldRegisterTool("open")&&this.registerOpen();}registerGetOptions(){this.server.registerTool("extension_tool_get_side_panel_options",{description:"Get the active side panel configuration for a specific tab or default settings",inputSchema:{tabId:z.number().optional().describe("If specified, the side panel options for the given tab will be returned. Otherwise, returns the default side panel options")}},async({tabId:e})=>{try{let t=await new Promise((r,o)=>{let i={};e!==void 0&&(i.tabId=e),chrome.sidePanel.getOptions(i,s=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r(s);});});return this.formatJson({tabId:e||"default",enabled:t.enabled,path:t.path})}catch(t){return this.formatError(t)}});}registerSetOptions(){this.server.registerTool("extension_tool_set_side_panel_options",{description:"Configure the side panel settings for a specific tab or default behavior",inputSchema:{enabled:z.boolean().optional().describe("Whether the side panel should be enabled. Defaults to true"),path:z.string().optional().describe("The path to the side panel HTML file to use. Must be a local resource within the extension package"),tabId:z.number().optional().describe("If specified, the side panel options will only apply to the tab with this id. If omitted, these options set the default behavior")}},async({enabled:e,path:t,tabId:r})=>{try{let o={};return e!==void 0&&(o.enabled=e),t!==void 0&&(o.path=t),r!==void 0&&(o.tabId=r),await new Promise((i,s)=>{chrome.sidePanel.setOptions(o,()=>{chrome.runtime.lastError?s(new Error(chrome.runtime.lastError.message)):i();});}),this.formatSuccess("Side panel options configured successfully",{tabId:r||"default",enabled:e,path:t})}catch(o){return this.formatError(o)}});}registerGetPanelBehavior(){this.server.registerTool("extension_tool_get_side_panel_behavior",{description:"Get the current side panel behavior configuration",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.sidePanel.getPanelBehavior(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({openPanelOnActionClick:e.openPanelOnActionClick})}catch(e){return this.formatError(e)}});}registerSetPanelBehavior(){this.server.registerTool("extension_tool_set_side_panel_behavior",{description:"Configure the side panel behavior, such as opening when the action icon is clicked",inputSchema:{openPanelOnActionClick:z.boolean().optional().describe("Whether clicking the extension action icon will toggle showing the extension entry in the side panel. Defaults to false")}},async({openPanelOnActionClick:e})=>{try{let t={};return e!==void 0&&(t.openPanelOnActionClick=e),await new Promise((r,o)=>{chrome.sidePanel.setPanelBehavior(t,()=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r();});}),this.formatSuccess("Side panel behavior configured successfully",{openPanelOnActionClick:e})}catch(t){return this.formatError(t)}});}registerOpen(){this.server.registerTool("extension_tool_open_side_panel",{description:"Open the side panel for the extension. This may only be called in response to a user action",inputSchema:{tabId:z.number().optional().describe("The tab in which to open the side panel. If there is a tab-specific panel, it will only open for that tab. At least one of tabId or windowId must be provided"),windowId:z.number().optional().describe("The window in which to open the side panel. This is only applicable if the extension has a global side panel or tabId is also specified. At least one of tabId or windowId must be provided")}},async({tabId:e,windowId:t})=>{try{if(e===void 0&&t===void 0)return this.formatError("Either tabId or windowId must be specified to open the side panel");let r={};return e!==void 0&&(r.tabId=e),t!==void 0&&(r.windowId=t),await new Promise((o,i)=>{chrome.sidePanel.open(r,()=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o();});}),this.formatSuccess("Side panel opened successfully",{tabId:e,windowId:t})}catch(r){return this.formatError(r)}});}};var Rt=class extends d{apiName="Storage";constructor(e,t={}){super(e,t);}checkAvailability(){try{if(!chrome.storage)return {available:!1,message:"chrome.storage API is not defined",details:'This extension needs the "storage" permission in its manifest.json to access storage'};let e=[];return chrome.storage.local&&e.push("local"),chrome.storage.sync&&e.push("sync"),chrome.storage.session&&e.push("session"),chrome.storage.managed&&e.push("managed"),e.length===0?{available:!1,message:"No storage areas are available",details:"The storage API is present but no storage areas can be accessed"}:(chrome.storage.local.get(null,()=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:`Storage API is available with areas: ${e.join(", ")}`})}catch(e){return {available:false,message:"Failed to access chrome.storage API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("getStorage")&&this.registerGetStorage(),this.shouldRegisterTool("setStorage")&&this.registerSetStorage(),this.shouldRegisterTool("removeStorage")&&this.registerRemoveStorage(),this.shouldRegisterTool("clearStorage")&&this.registerClearStorage(),this.shouldRegisterTool("getBytesInUse")&&this.registerGetBytesInUse();}getAvailableAreas(){let e=[];return chrome.storage.sync&&e.push("sync"),chrome.storage.local&&e.push("local"),chrome.storage.session&&e.push("session"),e}registerGetStorage(){let e=this.getAvailableAreas();this.server.registerTool("extension_tool_get_storage",{description:"Get data from extension storage",inputSchema:{keys:z.array(z.string()).optional().describe("Specific keys to retrieve (omit for all)"),area:z.enum(e).optional().describe(`Storage area to use. Available: ${e.join(", ")} (default: local)`)}},async({keys:t,area:r="local"})=>{try{let o=chrome.storage[r];if(!o||typeof o.get!="function")return this.formatError(new Error(`Storage area '${r}' is not available`));let i=await o.get(t||null),s={area:r,data:i,keyCount:Object.keys(i).length};return this.formatJson(s)}catch(o){return this.formatError(o)}});}registerSetStorage(){let e=this.getAvailableAreas();this.server.registerTool("extension_tool_set_storage",{description:"Set data in extension storage",inputSchema:{data:z.record(z.any()).describe("Key-value pairs to store"),area:z.enum(e).optional().describe(`Storage area to use. Available: ${e.join(", ")} (default: local)`)}},async({data:t,area:r="local"})=>{try{let o=chrome.storage[r];return !o||typeof o.set!="function"?this.formatError(new Error(`Storage area '${r}' is not available`)):(await o.set(t),this.formatSuccess(`Stored ${Object.keys(t).length} key(s) in ${r} storage`,{keys:Object.keys(t)}))}catch(o){return this.formatError(o)}});}registerRemoveStorage(){let e=this.getAvailableAreas();this.server.registerTool("extension_tool_remove_storage",{description:"Remove specific keys from extension storage",inputSchema:{keys:z.array(z.string()).describe("Keys to remove from storage"),area:z.enum(e).optional().describe(`Storage area to use. Available: ${e.join(", ")} (default: local)`)}},async({keys:t,area:r="local"})=>{try{let o=chrome.storage[r];return !o||typeof o.remove!="function"?this.formatError(new Error(`Storage area '${r}' is not available`)):(await o.remove(t),this.formatSuccess(`Removed ${t.length} key(s) from ${r} storage`,{keys:t}))}catch(o){return this.formatError(o)}});}registerClearStorage(){let e=this.getAvailableAreas();this.server.registerTool("extension_tool_clear_storage",{description:"Clear all data from a storage area",inputSchema:{area:z.enum(e).describe(`Storage area to clear. Available: ${e.join(", ")}`),confirm:z.boolean().describe("Confirmation flag - must be true to clear storage")}},async({area:t,confirm:r})=>{try{if(!r)return this.formatError(new Error("Clear operation requires confirm=true to prevent accidental data loss"));let o=chrome.storage[t];return !o||typeof o.clear!="function"?this.formatError(new Error(`Storage area '${t}' is not available`)):(await o.clear(),this.formatSuccess(`Cleared all data from ${t} storage`))}catch(o){return this.formatError(o)}});}registerGetBytesInUse(){let e=this.getAvailableAreas();this.server.registerTool("extension_tool_get_storage_bytes_in_use",{description:"Get the amount of storage space used",inputSchema:{keys:z.array(z.string()).optional().describe("Specific keys to check (omit for total)"),area:z.enum(e).optional().describe(`Storage area to check. Available: ${e.join(", ")} (default: local)`)}},async({keys:t,area:r="local"})=>{try{let o=chrome.storage[r];if(!o)return this.formatError(new Error(`Storage area '${r}' is not available`));if(typeof o.getBytesInUse!="function")return this.formatError(new Error(`getBytesInUse is not supported for ${r} storage area`));let i=await o.getBytesInUse(t||null),s=null;return r==="sync"&&chrome.storage.sync.QUOTA_BYTES?s={quotaBytes:chrome.storage.sync.QUOTA_BYTES,quotaBytesPerItem:chrome.storage.sync.QUOTA_BYTES_PER_ITEM,maxItems:chrome.storage.sync.MAX_ITEMS,maxWriteOperationsPerHour:chrome.storage.sync.MAX_WRITE_OPERATIONS_PER_HOUR,maxWriteOperationsPerMinute:chrome.storage.sync.MAX_WRITE_OPERATIONS_PER_MINUTE}:r==="local"&&chrome.storage.local.QUOTA_BYTES&&(s={quotaBytes:chrome.storage.local.QUOTA_BYTES}),this.formatJson({area:r,bytesInUse:i,humanReadable:this.formatBytes(i),quota:s,percentageUsed:s?.quotaBytes?(i/s.quotaBytes*100).toFixed(2)+"%":null})}catch(o){return this.formatError(o)}});}formatBytes(e){if(e===0)return "0 Bytes";let t=1024,r=["Bytes","KB","MB","GB"],o=Math.floor(Math.log(e)/Math.log(t));return parseFloat((e/t**o).toFixed(2))+" "+r[o]}};var Pt=class extends d{apiName="System.cpu";constructor(e,t={}){super(e,t);}checkAvailability(){try{return !chrome.system||!chrome.system.cpu?{available:!1,message:"chrome.system.cpu API is not defined",details:'This extension needs the "system.cpu" permission in its manifest.json'}:typeof chrome.system.cpu.getInfo!="function"?{available:!1,message:"chrome.system.cpu.getInfo is not available",details:"The system.cpu API appears to be partially available. Check manifest permissions."}:(chrome.system.cpu.getInfo(e=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"System.cpu API is fully available"})}catch(e){return {available:false,message:"Failed to access chrome.system.cpu API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("getInfo")&&this.registerGetInfo();}registerGetInfo(){this.server.registerTool("extension_tool_get_cpu_info",{description:"Get information about the CPU including number of processors, architecture, model, and features",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.system.cpu.getInfo(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({numOfProcessors:e.numOfProcessors,archName:e.archName,modelName:e.modelName,features:e.features,processors:e.processors.map(t=>({usage:{kernel:t.usage.kernel,user:t.usage.user,idle:t.usage.idle,total:t.usage.total}}))})}catch(e){return this.formatError(e)}});}};var Ct=class extends d{apiName="SystemLog";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.systemLog?typeof chrome.systemLog.add!="function"?{available:!1,message:"chrome.systemLog.add is not available",details:"The systemLog API appears to be partially available. Check manifest permissions and ensure running on ChromeOS."}:{available:!0,message:"SystemLog API is fully available"}:{available:!1,message:"chrome.systemLog API is not defined",details:'This extension needs the "systemLog" permission in its manifest.json and must run on ChromeOS'}}catch(e){return {available:false,message:"Failed to access chrome.systemLog API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("addLog")&&this.registerAddLog();}registerAddLog(){this.server.registerTool("extension_tool_add_log",{description:"Add a new log record to the Chrome system logs",inputSchema:{message:z.string().describe("The log message to record in the system logs")}},async({message:e})=>{try{let t={message:e};return await new Promise((r,o)=>{chrome.systemLog.add(t,()=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r();});}),this.formatSuccess("Log record added successfully",{message:e,timestamp:new Date().toISOString()})}catch(t){return this.formatError(t)}});}};var kt=class extends d{apiName="System.memory";constructor(e,t={}){super(e,t);}checkAvailability(){try{return !chrome.system||!chrome.system.memory?{available:!1,message:"chrome.system.memory API is not defined",details:'This extension needs the "system.memory" permission in its manifest.json'}:typeof chrome.system.memory.getInfo!="function"?{available:!1,message:"chrome.system.memory.getInfo is not available",details:"The system.memory API appears to be partially available. Check manifest permissions."}:(chrome.system.memory.getInfo(e=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"System.memory API is fully available"})}catch(e){return {available:false,message:"Failed to access chrome.system.memory API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("getInfo")&&this.registerGetInfo();}registerGetInfo(){this.server.registerTool("extension_tool_get_memory_info",{description:"Get information about the system memory",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.system.memory.getInfo(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({capacity:e.capacity,capacityGB:Math.round(e.capacity/(1024*1024*1024)*100)/100,availableCapacity:e.availableCapacity,availableCapacityGB:Math.round(e.availableCapacity/(1024*1024*1024)*100)/100,usedCapacity:e.capacity-e.availableCapacity,usedCapacityGB:Math.round((e.capacity-e.availableCapacity)/(1024*1024*1024)*100)/100,usagePercentage:Math.round((e.capacity-e.availableCapacity)/e.capacity*1e4)/100})}catch(e){return this.formatError(e)}});}};var Ot=class extends d{apiName="System.storage";constructor(e,t={}){super(e,t);}checkAvailability(){try{return !chrome.system||!chrome.system.storage?{available:!1,message:"chrome.system.storage API is not defined",details:'This extension needs the "system.storage" permission in its manifest.json'}:typeof chrome.system.storage.getInfo!="function"?{available:!1,message:"chrome.system.storage.getInfo is not available",details:"The system.storage API appears to be partially available. Check manifest permissions."}:(chrome.system.storage.getInfo(e=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"System.storage API is fully available"})}catch(e){return {available:false,message:"Failed to access chrome.system.storage API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("getInfo")&&this.registerGetInfo(),this.shouldRegisterTool("ejectDevice")&&this.registerEjectDevice(),this.shouldRegisterTool("getAvailableCapacity")&&this.registerGetAvailableCapacity();}registerGetInfo(){this.server.registerTool("extension_tool_get_storage_info",{description:"Get information about all attached storage devices",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.system.storage.getInfo(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({count:e.length,devices:e.map(t=>({id:t.id,name:t.name,type:t.type,capacity:t.capacity,capacityFormatted:this.formatBytes(t.capacity)}))})}catch(e){return this.formatError(e)}});}registerEjectDevice(){this.server.registerTool("extension_tool_eject_storage_device",{description:"Eject a removable storage device",inputSchema:{id:z.string().describe("The transient device ID from getInfo")}},async({id:e})=>{try{let t=await new Promise((i,s)=>{chrome.system.storage.ejectDevice(e,n=>{chrome.runtime.lastError?s(new Error(chrome.runtime.lastError.message)):i(n);});}),r=t==="success",o=this.getEjectResultMessage(t);return r?this.formatSuccess("Device ejected successfully",{deviceId:e,result:t,message:o}):this.formatError(`Failed to eject device: ${o}`)}catch(t){return this.formatError(t)}});}registerGetAvailableCapacity(){this.server.registerTool("extension_tool_get_available_capacity",{description:"Get the available capacity of a specified storage device",inputSchema:{id:z.string().describe("The transient device ID from getInfo")}},async({id:e})=>{try{let t=await new Promise((r,o)=>{chrome.system.storage.getAvailableCapacity(e,i=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r(i);});});return this.formatJson({deviceId:e,availableCapacity:t.availableCapacity,availableCapacityFormatted:this.formatBytes(t.availableCapacity)})}catch(t){return this.formatError(t)}});}getEjectResultMessage(e){switch(e){case "success":return "Device ejected successfully";case "in_use":return "Device is currently in use and cannot be ejected";case "no_such_device":return "No such device found";case "failure":return "Failed to eject device due to unknown error";default:return `Unknown result: ${e}`}}formatBytes(e){if(e===0)return "0 Bytes";let t=1024,r=["Bytes","KB","MB","GB","TB","PB"],o=Math.floor(Math.log(e)/Math.log(t));return parseFloat((e/t**o).toFixed(2))+" "+r[o]}};var Lt=class extends d{apiName="TabCapture";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.tabCapture?typeof chrome.tabCapture.getCapturedTabs!="function"?{available:!1,message:"chrome.tabCapture.getCapturedTabs is not available",details:"The tabCapture API appears to be partially available. Check manifest permissions."}:(chrome.tabCapture.getCapturedTabs(e=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"TabCapture API is fully available"}):{available:!1,message:"chrome.tabCapture API is not defined",details:'This extension needs the "tabCapture" permission in its manifest.json'}}catch(e){return {available:false,message:"Failed to access chrome.tabCapture API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("capture")&&this.registerCapture(),this.shouldRegisterTool("getCapturedTabs")&&this.registerGetCapturedTabs(),this.shouldRegisterTool("getMediaStreamId")&&this.registerGetMediaStreamId();}registerCapture(){this.server.registerTool("extension_tool_capture_tab",{description:"Captures the visible area of the currently active tab. Can only be started on the currently active tab after the extension has been invoked.",inputSchema:{audio:z.boolean().optional().describe("Whether to capture audio from the tab"),video:z.boolean().optional().describe("Whether to capture video from the tab"),audioConstraints:z.object({mandatory:z.record(z.any()).optional(),optional:z.record(z.any()).optional()}).optional().describe("Audio constraints for the media stream"),videoConstraints:z.object({mandatory:z.record(z.any()).optional(),optional:z.record(z.any()).optional()}).optional().describe("Video constraints for the media stream")}},async({audio:e,video:t,audioConstraints:r,videoConstraints:o})=>{try{let i={};e!==void 0&&(i.audio=e),t!==void 0&&(i.video=t),r!==void 0&&(i.audioConstraints=r),o!==void 0&&(i.videoConstraints=o);let s=await new Promise((c,u)=>{chrome.tabCapture.capture(i,m=>{chrome.runtime.lastError?u(new Error(chrome.runtime.lastError.message)):m?c(m):u(new Error("Failed to capture tab - no stream returned"));});}),n=s.getAudioTracks(),a=s.getVideoTracks();return this.formatSuccess("Tab capture started successfully",{streamId:s.id,audioTracks:n.length,videoTracks:a.length,audioTrackLabels:n.map(c=>c.label),videoTrackLabels:a.map(c=>c.label)})}catch(i){return this.formatError(i)}});}registerGetCapturedTabs(){this.server.registerTool("extension_tool_get_captured_tabs",{description:"Returns a list of tabs that have requested capture or are being captured",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.tabCapture.getCapturedTabs(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({count:e.length,capturedTabs:e.map(t=>({tabId:t.tabId,status:t.status,fullscreen:t.fullscreen}))})}catch(e){return this.formatError(e)}});}registerGetMediaStreamId(){this.server.registerTool("extension_tool_get_media_stream_id",{description:"Creates a stream ID to capture the target tab. Returns a media stream ID instead of a media stream.",inputSchema:{targetTabId:z.number().optional().describe("Optional tab id of the tab which will be captured. If not specified then the current active tab will be selected."),consumerTabId:z.number().optional().describe("Optional tab id of the tab which will later invoke getUserMedia() to consume the stream. If not specified then the resulting stream can be used only by the calling extension.")}},async({targetTabId:e,consumerTabId:t})=>{try{let r={};e!==void 0&&(r.targetTabId=e),t!==void 0&&(r.consumerTabId=t);let o=await new Promise((i,s)=>{chrome.tabCapture.getMediaStreamId(r,n=>{chrome.runtime.lastError?s(new Error(chrome.runtime.lastError.message)):n?i(n):s(new Error("Failed to get media stream ID"));});});return this.formatSuccess("Media stream ID created successfully",{streamId:o,targetTabId:e||"current active tab",consumerTabId:t||"calling extension only",usage:'Use this ID with navigator.mediaDevices.getUserMedia() with chromeMediaSource: "tab" and chromeMediaSourceId: streamId'})}catch(r){return this.formatError(r)}});}};var Ut=class extends d{apiName="TabGroups";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.tabGroups?typeof chrome.tabGroups.query!="function"?{available:!1,message:"chrome.tabGroups.query is not available",details:"The tabGroups API appears to be partially available. Check manifest permissions."}:(chrome.tabGroups.query({},()=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"TabGroups API is fully available"}):{available:!1,message:"chrome.tabGroups API is not defined",details:'This extension needs the "tabGroups" permission in its manifest.json and requires Chrome 89+ with Manifest V3'}}catch(e){return {available:false,message:"Failed to access chrome.tabGroups API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("get")&&this.registerGet(),this.shouldRegisterTool("query")&&this.registerQuery(),this.shouldRegisterTool("update")&&this.registerUpdate(),this.shouldRegisterTool("move")&&this.registerMove();}registerGet(){this.server.registerTool("extension_tool_get_tab_group",{description:"Get details about a specific tab group",inputSchema:{groupId:z.number().describe("The ID of the tab group to retrieve")}},async({groupId:e})=>{try{let t=await new Promise((r,o)=>{chrome.tabGroups.get(e,i=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r(i);});});return this.formatJson({id:t.id,title:t.title,color:t.color,collapsed:t.collapsed,shared:t.shared,windowId:t.windowId})}catch(t){return this.formatError(t)}});}registerQuery(){this.server.registerTool("extension_tool_query_tab_groups",{description:"Search for tab groups that match specified criteria",inputSchema:{collapsed:z.boolean().optional().describe("Whether the groups are collapsed"),color:z.enum(["grey","blue","red","yellow","green","pink","purple","cyan","orange"]).optional().describe("The color of the groups"),shared:z.boolean().optional().describe("Whether the group is shared (Chrome 137+)"),title:z.string().optional().describe("Pattern to match group titles against"),windowId:z.number().optional().describe("The ID of the parent window, or use -2 for the current window")}},async({collapsed:e,color:t,shared:r,title:o,windowId:i})=>{try{let s={};e!==void 0&&(s.collapsed=e),t!==void 0&&(s.color=t),r!==void 0&&(s.shared=r),o!==void 0&&(s.title=o),i!==void 0&&(s.windowId=i===-2?chrome.windows.WINDOW_ID_CURRENT:i);let n=await new Promise((a,c)=>{chrome.tabGroups.query(s,u=>{chrome.runtime.lastError?c(new Error(chrome.runtime.lastError.message)):a(u);});});return this.formatJson({count:n.length,groups:n.map(a=>({id:a.id,title:a.title,color:a.color,collapsed:a.collapsed,shared:a.shared,windowId:a.windowId}))})}catch(s){return this.formatError(s)}});}registerUpdate(){this.server.registerTool("extension_tool_update_tab_group",{description:"Modify properties of a tab group",inputSchema:{groupId:z.number().describe("The ID of the group to modify"),collapsed:z.boolean().optional().describe("Whether the group should be collapsed"),color:z.enum(["grey","blue","red","yellow","green","pink","purple","cyan","orange"]).optional().describe("The color of the group"),title:z.string().optional().describe("The title of the group")}},async({groupId:e,collapsed:t,color:r,title:o})=>{try{let i={};t!==void 0&&(i.collapsed=t),r!==void 0&&(i.color=r),o!==void 0&&(i.title=o);let s=await new Promise((n,a)=>{chrome.tabGroups.update(e,i,c=>{chrome.runtime.lastError?a(new Error(chrome.runtime.lastError.message)):n(c);});});return s?this.formatSuccess("Tab group updated successfully",{id:s.id,title:s.title,color:s.color,collapsed:s.collapsed,shared:s.shared,windowId:s.windowId}):this.formatError("Failed to update tab group")}catch(i){return this.formatError(i)}});}registerMove(){this.server.registerTool("extension_tool_move_tab_group",{description:"Move a tab group within its window or to a new window",inputSchema:{groupId:z.number().describe("The ID of the group to move"),index:z.number().describe("The position to move the group to. Use -1 to place at the end"),windowId:z.number().optional().describe("The window to move the group to. Defaults to current window")}},async({groupId:e,index:t,windowId:r})=>{try{let o={index:t};r!==void 0&&(o.windowId=r);let i=await new Promise((s,n)=>{chrome.tabGroups.move(e,o,a=>{chrome.runtime.lastError?n(new Error(chrome.runtime.lastError.message)):s(a);});});return i?this.formatSuccess("Tab group moved successfully",{id:i.id,title:i.title,color:i.color,collapsed:i.collapsed,shared:i.shared,windowId:i.windowId,newIndex:t}):this.formatError("Failed to move tab group")}catch(o){return this.formatError(o)}});}};var Mt=class extends d{apiName="Tabs";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.tabs?typeof chrome.tabs.query!="function"?{available:!1,message:"chrome.tabs.query is not available",details:"The tabs API appears to be partially available. Check manifest permissions."}:{available:!0,message:"Tabs API is fully available"}:{available:!1,message:"chrome.tabs API is not defined",details:'This extension may not have the "tabs" permission in its manifest'}}catch(e){return {available:false,message:"Failed to access chrome.tabs API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("listActiveTabs")&&this.registerListActiveTabs(),this.shouldRegisterTool("createTab")&&this.registerCreateTab(),this.shouldRegisterTool("updateTab")&&this.registerUpdateTab(),this.shouldRegisterTool("closeTabs")&&this.registerCloseTabs(),this.shouldRegisterTool("getAllTabs")&&this.registerGetAllTabs(),this.shouldRegisterTool("navigateHistory")&&this.checkAndRegisterNavigationTools(),this.shouldRegisterTool("reloadTab")&&this.registerReloadTab(),this.shouldRegisterTool("captureVisibleTab")&&this.checkAndRegisterScreenshotTool(),this.shouldRegisterTool("detectLanguage")&&this.registerDetectLanguage(),this.shouldRegisterTool("discardTab")&&this.registerDiscardTab(),this.shouldRegisterTool("duplicateTab")&&this.registerDuplicateTab(),this.shouldRegisterTool("getTab")&&this.registerGetTab(),this.shouldRegisterTool("getZoom")&&(this.registerGetZoom(),this.registerGetZoomSettings()),this.shouldRegisterTool("setZoom")&&(this.registerSetZoom(),this.registerSetZoomSettings()),this.shouldRegisterTool("groupTabs")&&this.registerGroupTabs(),this.shouldRegisterTool("ungroupTabs")&&this.registerUngroupTabs(),this.shouldRegisterTool("highlightTabs")&&this.registerHighlightTabs(),this.shouldRegisterTool("moveTabs")&&this.registerMoveTabs(),this.shouldRegisterTool("sendMessage")&&this.registerSendMessage();}checkAndRegisterNavigationTools(){try{typeof chrome.tabs.goBack=="function"&&typeof chrome.tabs.goForward=="function"?(this.registerNavigateHistory(),console.log(" \u2713 Navigation methods (goBack/goForward) available")):console.warn(" \u2717 Navigation methods not available - Chrome 72+ required");}catch{console.warn(" \u2717 Failed to check navigation methods availability");}}checkAndRegisterScreenshotTool(){try{typeof chrome.tabs.captureVisibleTab=="function"?(this.registerCaptureVisibleTab(),console.log(" \u2713 Screenshot capture available")):console.warn(' \u2717 Screenshot capture not available - requires "activeTab" or "<all_urls>" permission');}catch{console.warn(" \u2717 Failed to check screenshot capture availability");}}registerListActiveTabs(){this.server.registerTool("extension_tool_list_active_tabs",{description:"Lists all tabs grouped by domain",inputSchema:{}},async()=>{let r=(await chrome.tabs.query({})).map(o=>{let i="unknown";if(o.url)try{i=new URL(o.url).hostname;}catch{}return {tabId:o.id,domain:i,url:o.url,title:o.title,isActive:o.active,windowId:o.windowId,index:o.index,pinned:o.pinned,audible:o.audible,mutedInfo:o.mutedInfo,status:o.status}}).reduce((o,i)=>{let s=i.domain||"unknown";return o[s]||(o[s]=[]),o[s].push(i),o},{});for(let o of Object.values(r))o.sort((i,s)=>i.windowId!==s.windowId?(i.windowId||0)-(s.windowId||0):(i.index||0)-(s.index||0));return this.formatJson(r)});}registerCreateTab(){this.server.registerTool("extension_tool_create_tab",{description:"Create a new browser tab",inputSchema:{url:z.string().optional().describe("URL to open in the new tab. Fully-qualified URLs must include a scheme (i.e., 'http://www.google.com', not 'www.google.com'). Relative URLs are relative to the current page within the extension. Defaults to the New Tab Page."),active:z.boolean().optional().describe("Whether the tab should be active"),pinned:z.boolean().optional().describe("Whether the tab should be pinned")}},async({url:e,active:t,pinned:r})=>{try{let o=await chrome.tabs.create({url:e,active:t,pinned:r});return this.formatSuccess(`Created tab ${o.id} with URL: ${o.url||"about:blank"}`)}catch(o){return this.formatError(o)}});}registerUpdateTab(){this.server.registerTool("extension_tool_update_tab",{description:"Update properties of an existing tab. If no tabId is specified, operates on the currently active tab",inputSchema:{tabId:z.number().optional().describe("ID of the tab to update (defaults to active tab)"),url:z.string().optional().describe("New URL for the tab"),active:z.boolean().optional().describe("Whether to make the tab active"),pinned:z.boolean().optional().describe("Whether to pin/unpin the tab"),muted:z.boolean().optional().describe("Whether to mute/unmute the tab")}},async({tabId:e,url:t,active:r,pinned:o,muted:i})=>{try{if(e===void 0){let[a]=await chrome.tabs.query({active:!0,currentWindow:!0});if(!a||!a.id)return this.formatError(new Error("No active tab found"));e=a.id;}let s={};t!==void 0&&(s.url=t),r!==void 0&&(s.active=r),o!==void 0&&(s.pinned=o),i!==void 0&&(s.muted=i);let n=await chrome.tabs.update(e,s);return n?this.formatSuccess(`Updated tab ${n.id}`,s):this.formatError(new Error("Tab does not exist"))}catch(s){return this.formatError(s)}});}registerCloseTabs(){this.server.registerTool("extension_tool_close_tabs",{description:"Close one or more tabs",inputSchema:{tabIds:z.array(z.number()).describe("Array of tab IDs to close")}},async({tabIds:e})=>{try{return await chrome.tabs.remove(e),this.formatSuccess(`Closed ${e.length} tab(s): ${e.join(", ")}`)}catch(t){return this.formatError(t)}});}registerGetAllTabs(){this.server.registerTool("extension_tool_get_all_tabs",{description:"Get information about all open tabs",inputSchema:{currentWindow:z.boolean().optional().describe("Only get tabs from current window")}},async({currentWindow:e})=>{try{let r=(await chrome.tabs.query(e?{currentWindow:!0}:{})).map(o=>({id:o.id,title:o.title,url:o.url,active:o.active,pinned:o.pinned,windowId:o.windowId,index:o.index}));return this.formatJson(r)}catch(t){return this.formatError(t)}});}registerNavigateHistory(){this.server.registerTool("extension_tool_navigate_tab_history",{description:"Navigate forward or backward in a tab's history. If no tabId is specified, operates on the currently active tab",inputSchema:{tabId:z.number().optional().describe("Tab ID to navigate (defaults to active tab)"),direction:z.enum(["back","forward"]).describe("Navigation direction")}},async({tabId:e,direction:t})=>{try{if(e===void 0){let[r]=await chrome.tabs.query({active:!0,currentWindow:!0});if(!r||!r.id)return this.formatError(new Error("No active tab found"));e=r.id;}return t==="back"?await chrome.tabs.goBack(e):await chrome.tabs.goForward(e),this.formatSuccess(`Navigated ${t} in tab ${e}`)}catch(r){return this.formatError(r)}});}registerReloadTab(){this.server.registerTool("extension_tool_reload_tab",{description:"Reload a tab. If no tabId is specified, operates on the currently active tab",inputSchema:{tabId:z.number().optional().describe("Tab ID to reload (defaults to active tab)"),bypassCache:z.boolean().optional().describe("Bypass the cache when reloading")}},async({tabId:e,bypassCache:t})=>{try{if(e===void 0){let[r]=await chrome.tabs.query({active:!0,currentWindow:!0});if(!r||!r.id)return this.formatError(new Error("No active tab found"));e=r.id;}return await chrome.tabs.reload(e,{bypassCache:t}),this.formatSuccess(`Reloaded tab ${e}${t?" (bypassed cache)":""}`)}catch(r){return this.formatError(r)}});}registerCaptureVisibleTab(){this.server.registerTool("extension_tool_capture_visible_tab",{description:"Take a screenshot of the visible area of the currently active tab in a window. Once the screenshot is captured",inputSchema:{windowId:z.number().optional().describe("Window ID (defaults to current window)")}},async({windowId:e})=>{try{let t=e?await chrome.tabs.captureVisibleTab(e,{}):await chrome.tabs.captureVisibleTab();return chrome.tabs.create({url:t}),this.formatSuccess(`Screenshot captured (data URL length: ${t.length} characters)`)}catch(t){return this.formatError(t)}});}registerDetectLanguage(){this.server.registerTool("extension_tool_detect_tab_language",{description:"Detects the primary language of the content in a tab",inputSchema:{tabId:z.number().optional().describe("Tab ID (defaults to active tab)")}},async({tabId:e})=>{try{let t=await chrome.tabs.detectLanguage(e);return this.formatSuccess(`Tab language detected: ${t}`,{language:t})}catch(t){return this.formatError(t)}});}registerDiscardTab(){this.server.registerTool("extension_tool_discard_tab",{description:"Discards a tab from memory. Discarded tabs are still visible but need to reload when activated",inputSchema:{tabId:z.number().optional().describe("Tab ID to discard (if omitted, browser picks least important tab)")}},async({tabId:e})=>{try{let t=await chrome.tabs.discard(e);return t?this.formatSuccess(`Discarded tab ${t.id}`,{tab:t}):this.formatError(new Error("Failed to discard tab"))}catch(t){return this.formatError(t)}});}registerDuplicateTab(){this.server.registerTool("extension_tool_duplicate_tab",{description:"Duplicates a tab",inputSchema:{tabId:z.number().describe("ID of the tab to duplicate")}},async({tabId:e})=>{try{let t=await chrome.tabs.duplicate(e);return t?this.formatSuccess(`Duplicated tab ${e} to new tab ${t.id}`,{tab:t}):this.formatError(new Error("Failed to duplicate tab"))}catch(t){return this.formatError(t)}});}registerGetTab(){this.server.registerTool("extension_tool_get_tab",{description:"Retrieves details about a specific tab",inputSchema:{tabId:z.number().describe("Tab ID")}},async({tabId:e})=>{try{let t=await chrome.tabs.get(e);return this.formatJson(t)}catch(t){return this.formatError(t)}});}registerGetZoom(){this.server.registerTool("extension_tool_get_tab_zoom",{description:"Gets the current zoom factor of a tab",inputSchema:{tabId:z.number().optional().describe("Tab ID (defaults to active tab)")}},async({tabId:e})=>{try{let t=await chrome.tabs.getZoom(e);return this.formatSuccess(`Zoom factor: ${t}`,{zoomFactor:t})}catch(t){return this.formatError(t)}});}registerSetZoom(){this.server.registerTool("extension_tool_set_tab_zoom",{description:"Sets the zoom factor for a tab",inputSchema:{tabId:z.number().optional().describe("Tab ID (defaults to active tab)"),zoomFactor:z.number().describe("New zoom factor (0 resets to default, >0 sets specific zoom)")}},async({tabId:e,zoomFactor:t})=>{try{return await chrome.tabs.setZoom(e,t),this.formatSuccess(`Set zoom factor to ${t===0?"default":t}`)}catch(r){return this.formatError(r)}});}registerGetZoomSettings(){this.server.registerTool("extension_tool_get_tab_zoom_settings",{description:"Gets the current zoom settings of a tab",inputSchema:{tabId:z.number().optional().describe("Tab ID (defaults to active tab)")}},async({tabId:e})=>{try{let t=await chrome.tabs.getZoomSettings(e);return this.formatJson(t)}catch(t){return this.formatError(t)}});}registerSetZoomSettings(){this.server.registerTool("extension_tool_set_tab_zoom_settings",{description:"Sets zoom settings for a tab (how zoom changes are handled)",inputSchema:{tabId:z.number().optional().describe("Tab ID (defaults to active tab)"),mode:z.enum(["automatic","manual","disabled"]).optional().describe("How zoom changes are handled"),scope:z.enum(["per-origin","per-tab"]).optional().describe("Whether zoom persists across pages")}},async({tabId:e,mode:t,scope:r})=>{try{let o={};return t&&(o.mode=t),r&&(o.scope=r),await chrome.tabs.setZoomSettings(e,o),this.formatSuccess("Updated zoom settings",o)}catch(o){return this.formatError(o)}});}registerGroupTabs(){this.server.registerTool("extension_tool_group_tabs",{description:"Groups one or more tabs together",inputSchema:{tabIds:z.array(z.number()).min(1).describe("Tab IDs to group"),groupId:z.number().optional().describe("Existing group ID to add tabs to"),createProperties:z.object({windowId:z.number().optional().describe("Window ID for new group")}).optional().describe("Properties for creating a new group")}},async({tabIds:e,groupId:t,createProperties:r})=>{try{let o={tabIds:e.length===1?e[0]:e};t!==void 0?o.groupId=t:r&&(o.createProperties=r);let i=await chrome.tabs.group(o);return this.formatSuccess(`Grouped ${e.length} tabs into group ${i}`,{groupId:i})}catch(o){return this.formatError(o)}});}registerUngroupTabs(){this.server.registerTool("extension_tool_ungroup_tabs",{description:"Removes tabs from their groups",inputSchema:{tabIds:z.array(z.number()).min(1).describe("Tab IDs to ungroup")}},async({tabIds:e})=>{try{return await chrome.tabs.ungroup(e.length===1?e[0]:e),this.formatSuccess(`Ungrouped ${e.length} tab(s)`)}catch(t){return this.formatError(t)}});}registerHighlightTabs(){this.server.registerTool("extension_tool_highlight_tabs",{description:"Highlights the given tabs and focuses on the first one",inputSchema:{tabs:z.array(z.number()).min(1).describe("Tab indices to highlight"),windowId:z.number().optional().describe("Window ID containing the tabs")}},async({tabs:e,windowId:t})=>{try{let r={tabs:e.length===1?e[0]:e};t!==void 0&&(r.windowId=t);let o=await chrome.tabs.highlight(r);return this.formatSuccess(`Highlighted ${e.length} tab(s)`,{window:o})}catch(r){return this.formatError(r)}});}registerMoveTabs(){this.server.registerTool("extension_tool_move_tabs",{description:"Moves tabs to a new position within their window or to another window",inputSchema:{tabIds:z.array(z.number()).min(1).describe("Tab IDs to move"),index:z.number().describe("Position to move tabs to (-1 for end)"),windowId:z.number().optional().describe("Target window ID")}},async({tabIds:e,index:t,windowId:r})=>{try{let o={index:t};r!==void 0&&(o.windowId=r);let i=chrome.tabs.move(e.length===1?e[0]:e,o);return this.formatSuccess(`Moved ${e.length} tab(s) to index ${t}`,{tabs:i})}catch(o){return this.formatError(o)}});}registerSendMessage(){this.server.registerTool("extension_tool_send_message_to_tab",{description:"Sends a message to content scripts in a specific tab",inputSchema:{tabId:z.number().describe("Tab ID to send message to"),message:z.any().describe("Message to send (must be JSON-serializable)"),frameId:z.number().optional().describe("Specific frame ID to target"),documentId:z.string().optional().describe("Specific document ID to target")}},async({tabId:e,message:t,frameId:r,documentId:o})=>{try{let i={};r!==void 0&&(i.frameId=r),o!==void 0&&(i.documentId=o);let s=await chrome.tabs.sendMessage(e,t,i);return this.formatSuccess("Message sent successfully",{response:s})}catch(i){return this.formatError(i)}});}};var Nt=class extends d{apiName="TopSites";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.topSites?typeof chrome.topSites.get!="function"?{available:!1,message:"chrome.topSites.get is not available",details:"The topSites API appears to be partially available. Check manifest permissions."}:(chrome.topSites.get(e=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"TopSites API is fully available"}):{available:!1,message:"chrome.topSites API is not defined",details:'This extension needs the "topSites" permission in its manifest.json'}}catch(e){return {available:false,message:"Failed to access chrome.topSites API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("getTopSites")&&this.registerGetTopSites();}registerGetTopSites(){this.server.registerTool("extension_tool_get_top_sites",{description:"Get a list of top sites (most visited sites) that are displayed on the new tab page",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.topSites.get(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({count:e.length,topSites:e.map(t=>({title:t.title,url:t.url}))})}catch(e){return this.formatError(e)}});}};var qt=class extends d{apiName="Tts";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.tts?typeof chrome.tts.getVoices!="function"?{available:!1,message:"chrome.tts.getVoices is not available",details:"The tts API appears to be partially available. Check manifest permissions."}:(chrome.tts.getVoices(e=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"TTS API is fully available"}):{available:!1,message:"chrome.tts API is not defined",details:'This extension needs the "tts" permission in its manifest.json'}}catch(e){return {available:false,message:"Failed to access chrome.tts API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("speak")&&this.registerSpeak(),this.shouldRegisterTool("stop")&&this.registerStop(),this.shouldRegisterTool("pause")&&this.registerPause(),this.shouldRegisterTool("resume")&&this.registerResume(),this.shouldRegisterTool("isSpeaking")&&this.registerIsSpeaking(),this.shouldRegisterTool("getVoices")&&this.registerGetVoices();}registerSpeak(){this.server.registerTool("extension_tool_speak_text",{description:"Speaks text using text-to-speech synthesis",inputSchema:{utterance:z.string().max(32768).describe("The text to speak, either plain text or a complete SSML document. Maximum length is 32,768 characters"),lang:z.string().optional().describe('The language to be used for synthesis, in the form language-region. Examples: "en", "en-US", "en-GB", "zh-CN"'),voiceName:z.string().optional().describe("The name of the voice to use for synthesis. If empty, uses any available voice"),rate:z.number().min(.1).max(10).optional().describe("Speaking rate relative to the default rate. 1.0 is default, 2.0 is twice as fast, 0.5 is half as fast"),pitch:z.number().min(0).max(2).optional().describe("Speaking pitch between 0 and 2 inclusive, with 0 being lowest and 2 being highest. 1.0 is default"),volume:z.number().min(0).max(1).optional().describe("Speaking volume between 0 and 1 inclusive, with 0 being lowest and 1 being highest. Default is 1.0"),enqueue:z.boolean().optional().describe("If true, enqueues this utterance if TTS is already in progress. If false (default), interrupts current speech"),extensionId:z.string().optional().describe("The extension ID of the speech engine to use, if known"),requiredEventTypes:z.array(z.string()).optional().describe("The TTS event types the voice must support"),desiredEventTypes:z.array(z.string()).optional().describe("The TTS event types that you are interested in listening to")}},async({utterance:e,lang:t,voiceName:r,rate:o,pitch:i,volume:s,enqueue:n,extensionId:a,requiredEventTypes:c,desiredEventTypes:u})=>{try{let m={};t!==void 0&&(m.lang=t),r!==void 0&&(m.voiceName=r),o!==void 0&&(m.rate=o),i!==void 0&&(m.pitch=i),s!==void 0&&(m.volume=s),n!==void 0&&(m.enqueue=n),a!==void 0&&(m.extensionId=a),c!==void 0&&(m.requiredEventTypes=c),u!==void 0&&(m.desiredEventTypes=u);let g=[];return m.onEvent=w=>{g.push(w);},await new Promise((w,k)=>{chrome.tts.speak(e,m,()=>{chrome.runtime.lastError?k(new Error(chrome.runtime.lastError.message)):w();});}),this.formatSuccess("Text-to-speech started successfully",{utterance:e.substring(0,100)+(e.length>100?"...":""),options:{lang:m.lang,voiceName:m.voiceName,rate:m.rate,pitch:m.pitch,volume:m.volume,enqueue:m.enqueue}})}catch(m){return this.formatError(m)}});}registerStop(){this.server.registerTool("extension_tool_stop_speech",{description:"Stops any current speech and flushes the queue of pending utterances",inputSchema:{}},async()=>{try{return chrome.tts.stop(),this.formatSuccess("Speech stopped and queue cleared")}catch(e){return this.formatError(e)}});}registerPause(){this.server.registerTool("extension_tool_pause_speech",{description:"Pauses speech synthesis, potentially in the middle of an utterance",inputSchema:{}},async()=>{try{return chrome.tts.pause(),this.formatSuccess("Speech paused")}catch(e){return this.formatError(e)}});}registerResume(){this.server.registerTool("extension_tool_resume_speech",{description:"If speech was paused, resumes speaking where it left off",inputSchema:{}},async()=>{try{return chrome.tts.resume(),this.formatSuccess("Speech resumed")}catch(e){return this.formatError(e)}});}registerIsSpeaking(){this.server.registerTool("extension_tool_is_speaking",{description:"Checks whether the engine is currently speaking",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.tts.isSpeaking(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({speaking:e,status:e?"TTS engine is currently speaking":"TTS engine is not speaking"})}catch(e){return this.formatError(e)}});}registerGetVoices(){this.server.registerTool("extension_tool_get_voices",{description:"Gets an array of all available voices for speech synthesis",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.tts.getVoices(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({count:e.length,voices:e.map(t=>({voiceName:t.voiceName,lang:t.lang,extensionId:t.extensionId,eventTypes:t.eventTypes,remote:t.remote}))})}catch(e){return this.formatError(e)}});}};var Gt=class extends d{apiName="TtsEngine";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.ttsEngine?typeof chrome.ttsEngine.updateVoices!="function"?{available:!1,message:"chrome.ttsEngine.updateVoices is not available",details:"The ttsEngine API appears to be partially available. Check manifest permissions."}:!chrome.ttsEngine.onSpeak||!chrome.ttsEngine.onStop?{available:!1,message:"chrome.ttsEngine events are not available",details:"The ttsEngine API requires event listeners to be available."}:{available:!0,message:"TtsEngine API is fully available"}:{available:!1,message:"chrome.ttsEngine API is not defined",details:'This extension needs the "ttsEngine" permission in its manifest.json'}}catch(e){return {available:false,message:"Failed to access chrome.ttsEngine API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("updateVoices")&&this.registerUpdateVoices(),this.shouldRegisterTool("updateLanguage")&&this.registerUpdateLanguage(),this.shouldRegisterTool("onSpeak")&&this.registerOnSpeak(),this.shouldRegisterTool("onStop")&&this.registerOnStop(),this.shouldRegisterTool("onPause")&&this.registerOnPause(),this.shouldRegisterTool("onResume")&&this.registerOnResume(),this.shouldRegisterTool("onSpeakWithAudioStream")&&this.registerOnSpeakWithAudioStream(),this.shouldRegisterTool("onInstallLanguageRequest")&&this.registerOnInstallLanguageRequest(),this.shouldRegisterTool("onLanguageStatusRequest")&&this.registerOnLanguageStatusRequest(),this.shouldRegisterTool("onUninstallLanguageRequest")&&this.registerOnUninstallLanguageRequest();}registerUpdateVoices(){this.server.registerTool("extension_tool_update_voices",{description:"Update the list of voices available for speech synthesis",inputSchema:{voices:z.array(z.object({voiceName:z.string().describe("The name of the voice"),lang:z.string().optional().describe("Language code (e.g., en-US)"),gender:z.enum(["male","female"]).optional().describe("Voice gender (deprecated)"),remote:z.boolean().optional().describe("Whether the voice is remote"),extensionId:z.string().optional().describe("Extension ID providing the voice"),eventTypes:z.array(z.string()).optional().describe("Supported event types")})).describe("Array of voice objects to register")}},async({voices:e})=>{try{return chrome.ttsEngine.updateVoices(e),this.formatSuccess("Voices updated successfully",{voiceCount:e.length,voices:e.map(t=>({name:t.voiceName,lang:t.lang,eventTypes:t.eventTypes}))})}catch(t){return this.formatError(t)}});}registerUpdateLanguage(){this.server.registerTool("extension_tool_update_language",{description:"Update the installation status of a language",inputSchema:{lang:z.string().describe("Language code (e.g., en-US)"),installStatus:z.enum(["notInstalled","installing","installed","failed"]).describe("Installation status"),error:z.string().optional().describe("Error message if installation failed")}},async({lang:e,installStatus:t,error:r})=>{try{let o={lang:e,installStatus:t};return r!==void 0&&(o.error=r),chrome.ttsEngine.updateLanguage(o),this.formatSuccess("Language status updated successfully",{lang:e,installStatus:t,error:r})}catch(o){return this.formatError(o)}});}registerOnSpeak(){this.server.registerTool("extension_tool_register_speak_listener",{description:"Register a listener for speak events from the TTS engine",inputSchema:{}},async()=>{try{let e=(t,r,o)=>{o({type:"start",charIndex:0}),setTimeout(()=>{o({type:"end",charIndex:t.length});},1e3);};return chrome.ttsEngine.onSpeak.addListener(e),this.formatSuccess("Speak listener registered successfully")}catch(e){return this.formatError(e)}});}registerOnStop(){this.server.registerTool("extension_tool_register_stop_listener",{description:"Register a listener for stop events from the TTS engine",inputSchema:{}},async()=>{try{let e=()=>{};return chrome.ttsEngine.onStop.addListener(e),this.formatSuccess("Stop listener registered successfully")}catch(e){return this.formatError(e)}});}registerOnPause(){this.server.registerTool("extension_tool_register_pause_listener",{description:"Register a listener for pause events from the TTS engine",inputSchema:{}},async()=>{try{let e=()=>{};return chrome.ttsEngine.onPause.addListener(e),this.formatSuccess("Pause listener registered successfully")}catch(e){return this.formatError(e)}});}registerOnResume(){this.server.registerTool("extension_tool_register_resume_listener",{description:"Register a listener for resume events from the TTS engine",inputSchema:{}},async()=>{try{let e=()=>{};return chrome.ttsEngine.onResume.addListener(e),this.formatSuccess("Resume listener registered successfully")}catch(e){return this.formatError(e)}});}registerOnSpeakWithAudioStream(){this.server.registerTool("extension_tool_register_speak_audio_stream_listener",{description:"Register a listener for speak events with audio stream support",inputSchema:{}},async()=>{try{let e=(t,r,o,i,s)=>{try{let n=o.bufferSize,a=new ArrayBuffer(n*4);i({audioBuffer:a,charIndex:0,isLastBuffer:!0});}catch(n){s(n instanceof Error?n.message:"Unknown error");}};return chrome.ttsEngine.onSpeakWithAudioStream.addListener(e),this.formatSuccess("Speak with audio stream listener registered successfully")}catch(e){return this.formatError(e)}});}registerOnInstallLanguageRequest(){this.server.registerTool("extension_tool_register_install_language_listener",{description:"Register a listener for language installation requests",inputSchema:{}},async()=>{try{let e=(t,r)=>{chrome.ttsEngine.updateLanguage({lang:r,installStatus:"installing"});};return chrome.ttsEngine.onInstallLanguageRequest.addListener(e),this.formatSuccess("Install language listener registered successfully")}catch(e){return this.formatError(e)}});}registerOnLanguageStatusRequest(){this.server.registerTool("extension_tool_register_language_status_listener",{description:"Register a listener for language status requests",inputSchema:{}},async()=>{try{let e=(t,r)=>{chrome.ttsEngine.updateLanguage({lang:r,installStatus:"installed"});};return chrome.ttsEngine.onLanguageStatusRequest.addListener(e),this.formatSuccess("Language status listener registered successfully")}catch(e){return this.formatError(e)}});}registerOnUninstallLanguageRequest(){this.server.registerTool("extension_tool_register_uninstall_language_listener",{description:"Register a listener for language uninstallation requests",inputSchema:{}},async()=>{try{let e=(t,r,o)=>{o.uninstallImmediately&&chrome.ttsEngine.updateLanguage({lang:r,installStatus:"notInstalled"});};return chrome.ttsEngine.onUninstallLanguageRequest.addListener(e),this.formatSuccess("Uninstall language listener registered successfully")}catch(e){return this.formatError(e)}});}};var Ft=class extends d{apiName="UserScripts";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.userScripts?typeof chrome.userScripts.getScripts!="function"?{available:!1,message:"chrome.userScripts.getScripts is not available",details:"The userScripts API appears to be partially available. Check manifest permissions and user toggle settings."}:(chrome.userScripts.getScripts({},()=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"UserScripts API is fully available"}):{available:!1,message:"chrome.userScripts API is not defined",details:'This extension needs the "userScripts" permission in its manifest.json and users must enable the appropriate toggle (Developer mode for Chrome <138 or Allow User Scripts for Chrome 138+)'}}catch(e){return {available:false,message:"Failed to access chrome.userScripts API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("register")&&this.registerRegister(),this.shouldRegisterTool("getScripts")&&this.registerGetScripts(),this.shouldRegisterTool("update")&&this.registerUpdate(),this.shouldRegisterTool("unregister")&&this.registerUnregister(),this.shouldRegisterTool("configureWorld")&&this.registerConfigureWorld(),this.shouldRegisterTool("getWorldConfigurations")&&this.registerGetWorldConfigurations(),this.shouldRegisterTool("resetWorldConfiguration")&&this.registerResetWorldConfiguration(),this.shouldRegisterTool("execute")&&this.registerExecute();}registerRegister(){this.server.registerTool("extension_tool_register_user_scripts",{description:"Register one or more user scripts for this extension",inputSchema:{scripts:z.array(z.object({id:z.string().describe("The ID of the user script. Must not start with underscore"),matches:z.array(z.string()).describe("Match patterns for pages this script will be injected into"),js:z.array(z.object({code:z.string().optional().describe("JavaScript code to inject"),file:z.string().optional().describe("Path to JavaScript file relative to extension root")})).optional().describe("List of script sources to inject"),allFrames:z.boolean().optional().describe("Whether to inject into all frames (default: false)"),excludeMatches:z.array(z.string()).optional().describe("Pages to exclude from injection"),includeGlobs:z.array(z.string()).optional().describe("Wildcard patterns for pages to include"),excludeGlobs:z.array(z.string()).optional().describe("Wildcard patterns for pages to exclude"),runAt:z.enum(["document_start","document_end","document_idle"]).optional().describe("When to inject the script (default: document_idle)"),world:z.enum(["MAIN","USER_SCRIPT"]).optional().describe("JavaScript execution environment (default: USER_SCRIPT)"),worldId:z.string().optional().describe("User script world ID to execute in")})).describe("Array of user scripts to register")}},async({scripts:e})=>{try{for(let t of e){if(t.id.startsWith("_"))return this.formatError("Script ID cannot start with underscore: "+t.id);if(t.js)for(let r of t.js){let o=r.code!==void 0,i=r.file!==void 0;if(o===i)return this.formatError("Exactly one of code or file must be specified for each script source")}}return await new Promise((t,r)=>{chrome.userScripts.register(e,()=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t();});}),this.formatSuccess("User scripts registered successfully",{registeredCount:e.length,scriptIds:e.map(t=>t.id)})}catch(t){return this.formatError(t)}});}registerGetScripts(){this.server.registerTool("extension_tool_get_user_scripts",{description:"Get all dynamically-registered user scripts for this extension",inputSchema:{ids:z.array(z.string()).optional().describe("Filter to only return scripts with these IDs")}},async({ids:e})=>{try{let t={};e!==void 0&&(t.ids=e);let r=await new Promise((o,i)=>{chrome.userScripts.getScripts(t,s=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o(s);});});return this.formatJson({count:r.length,scripts:r.map(o=>({id:o.id,matches:o.matches,allFrames:o.allFrames,excludeMatches:o.excludeMatches,includeGlobs:o.includeGlobs,excludeGlobs:o.excludeGlobs,runAt:o.runAt,world:o.world,worldId:o.worldId,jsSourcesCount:o.js?.length||0}))})}catch(t){return this.formatError(t)}});}registerUpdate(){this.server.registerTool("extension_tool_update_user_scripts",{description:"Update one or more user scripts for this extension",inputSchema:{scripts:z.array(z.object({id:z.string().describe("The ID of the user script to update"),matches:z.array(z.string()).optional().describe("Match patterns for pages this script will be injected into"),js:z.array(z.object({code:z.string().optional().describe("JavaScript code to inject"),file:z.string().optional().describe("Path to JavaScript file relative to extension root")})).optional().describe("List of script sources to inject"),allFrames:z.boolean().optional().describe("Whether to inject into all frames"),excludeMatches:z.array(z.string()).optional().describe("Pages to exclude from injection"),includeGlobs:z.array(z.string()).optional().describe("Wildcard patterns for pages to include"),excludeGlobs:z.array(z.string()).optional().describe("Wildcard patterns for pages to exclude"),runAt:z.enum(["document_start","document_end","document_idle"]).optional().describe("When to inject the script"),world:z.enum(["MAIN","USER_SCRIPT"]).optional().describe("JavaScript execution environment"),worldId:z.string().optional().describe("User script world ID to execute in")})).describe("Array of user scripts to update")}},async({scripts:e})=>{try{for(let t of e)if(t.js)for(let r of t.js){let o=r.code!==void 0,i=r.file!==void 0;if(o===i)return this.formatError("Exactly one of code or file must be specified for each script source")}return await new Promise((t,r)=>{chrome.userScripts.update(e,()=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t();});}),this.formatSuccess("User scripts updated successfully",{updatedCount:e.length,scriptIds:e.map(t=>t.id)})}catch(t){return this.formatError(t)}});}registerUnregister(){this.server.registerTool("extension_tool_unregister_user_scripts",{description:"Unregister dynamically-registered user scripts for this extension",inputSchema:{ids:z.array(z.string()).optional().describe("Filter to only unregister scripts with these IDs. If not specified, all scripts are unregistered")}},async({ids:e})=>{try{let t={};e!==void 0&&(t.ids=e);let r=await new Promise((o,i)=>{chrome.userScripts.getScripts(t,s=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o(s);});});return await new Promise((o,i)=>{chrome.userScripts.unregister(t,()=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o();});}),this.formatSuccess("User scripts unregistered successfully",{unregisteredCount:r.length,unregisteredScriptIds:r.map(o=>o.id)})}catch(t){return this.formatError(t)}});}registerConfigureWorld(){this.server.registerTool("extension_tool_configure_user_script_world",{description:"Configure the USER_SCRIPT execution environment",inputSchema:{csp:z.string().optional().describe("Content Security Policy for the world"),messaging:z.boolean().optional().describe("Whether messaging APIs are exposed (default: false)"),worldId:z.string().optional().describe("ID of the specific user script world to update")}},async({csp:e,messaging:t,worldId:r})=>{try{let o={};return e!==void 0&&(o.csp=e),t!==void 0&&(o.messaging=t),r!==void 0&&(o.worldId=r),await new Promise((i,s)=>{chrome.userScripts.configureWorld(o,()=>{chrome.runtime.lastError?s(new Error(chrome.runtime.lastError.message)):i();});}),this.formatSuccess("User script world configured successfully",{worldId:r||"default",csp:e,messaging:t})}catch(o){return this.formatError(o)}});}registerGetWorldConfigurations(){this.server.registerTool("extension_tool_get_world_configurations",{description:"Retrieve all registered world configurations",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.userScripts.getWorldConfigurations(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({count:e.length,worlds:e.map(t=>({worldId:t.worldId,csp:t.csp,messaging:t.messaging}))})}catch(e){return this.formatError(e)}});}registerResetWorldConfiguration(){this.server.registerTool("extension_tool_reset_world_configuration",{description:"Reset the configuration for a user script world to defaults",inputSchema:{worldId:z.string().optional().describe("ID of the user script world to reset. If omitted, resets the default world")}},async({worldId:e="default"})=>{try{return await new Promise((t,r)=>{chrome.userScripts.resetWorldConfiguration(e,()=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t();});}),this.formatSuccess("World configuration reset successfully",{worldId:e||"default"})}catch(t){return this.formatError(t)}});}registerExecute(){this.server.registerTool("extension_tool_execute_user_script",{description:"Inject a script into a target context",inputSchema:{target:z.object({tabId:z.number().describe("The ID of the tab to inject into"),frameIds:z.array(z.number()).optional().describe("IDs of specific frames to inject into"),documentIds:z.array(z.string()).optional().describe("IDs of specific documents to inject into"),allFrames:z.boolean().optional().describe("Whether to inject into all frames (default: false)")}).describe("Target specification for injection"),js:z.array(z.object({code:z.string().optional().describe("JavaScript code to inject"),file:z.string().optional().describe("Path to JavaScript file relative to extension root")})).describe("List of script sources to inject"),world:z.enum(["MAIN","USER_SCRIPT"]).optional().describe("JavaScript execution environment (default: USER_SCRIPT)"),worldId:z.string().optional().describe("User script world ID to execute in"),injectImmediately:z.boolean().optional().describe("Whether to inject immediately without waiting (default: false)")}},async({target:e,js:t,world:r,worldId:o,injectImmediately:i})=>{try{for(let a of t){let c=a.code!==void 0,u=a.file!==void 0;if(c===u)return this.formatError("Exactly one of code or file must be specified for each script source")}let s={target:e,js:t};r!==void 0&&(s.world=r),o!==void 0&&(s.worldId=o),i!==void 0&&(s.injectImmediately=i);let n=await new Promise((a,c)=>{chrome.userScripts.execute(s,u=>{chrome.runtime.lastError?c(new Error(chrome.runtime.lastError.message)):a(u);});});return this.formatJson({injectionCount:n.length,results:n.map(a=>({frameId:a.frameId,documentId:a.documentId,error:a.error,hasResult:a.result!==void 0}))})}catch(s){return this.formatError(s)}});}};var jt=class extends d{apiName="VpnProvider";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.vpnProvider?typeof chrome.vpnProvider.createConfig!="function"?{available:!1,message:"chrome.vpnProvider.createConfig is not available",details:"The vpnProvider API appears to be partially available. Check manifest permissions and ensure this is running on ChromeOS."}:{available:!0,message:"VpnProvider API is fully available"}:{available:!1,message:"chrome.vpnProvider API is not defined",details:'This extension needs the "vpnProvider" permission in its manifest.json and only works on ChromeOS'}}catch(e){return {available:false,message:"Failed to access chrome.vpnProvider API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("createConfig")&&this.registerCreateConfig(),this.shouldRegisterTool("destroyConfig")&&this.registerDestroyConfig(),this.shouldRegisterTool("setParameters")&&this.registerSetParameters(),this.shouldRegisterTool("notifyConnectionStateChanged")&&this.registerNotifyConnectionStateChanged(),this.shouldRegisterTool("sendPacket")&&this.registerSendPacket();}registerCreateConfig(){this.server.registerTool("extension_tool_create_vpn_config",{description:"Create a new VPN configuration that persists across multiple login sessions",inputSchema:{name:z.string().describe("The name of the VPN configuration")}},async({name:e})=>{try{let t=await new Promise((r,o)=>{chrome.vpnProvider.createConfig(e,i=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):i?r(i):o(new Error("Failed to create VPN configuration"));});});return this.formatSuccess("VPN configuration created successfully",{id:t,name:e})}catch(t){return this.formatError(t)}});}registerDestroyConfig(){this.server.registerTool("extension_tool_destroy_vpn_config",{description:"Destroy a VPN configuration created by the extension",inputSchema:{id:z.string().describe("ID of the VPN configuration to destroy")}},async({id:e})=>{try{return await new Promise((t,r)=>{chrome.vpnProvider.destroyConfig(e,()=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t();});}),this.formatSuccess("VPN configuration destroyed successfully",{id:e})}catch(t){return this.formatError(t)}});}registerSetParameters(){this.server.registerTool("extension_tool_set_vpn_parameters",{description:'Set the parameters for the VPN session. Should be called immediately after "connected" is received',inputSchema:{address:z.string().describe("IP address for the VPN interface in CIDR notation. IPv4 is currently the only supported mode"),dnsServer:z.array(z.string()).describe("A list of IPs for the DNS servers"),inclusionList:z.array(z.string()).describe("Include network traffic to the list of IP blocks in CIDR notation to the tunnel"),exclusionList:z.array(z.string()).describe("Exclude network traffic to the list of IP blocks in CIDR notation from the tunnel"),broadcastAddress:z.string().optional().describe("Broadcast address for the VPN interface (default: deduced from IP address and mask)"),domainSearch:z.array(z.string()).optional().describe("A list of search domains (default: no search domain)"),mtu:z.string().optional().describe("MTU setting for the VPN interface (default: 1500 bytes)")}},async({address:e,dnsServer:t,inclusionList:r,exclusionList:o,broadcastAddress:i,domainSearch:s,mtu:n})=>{try{let a={address:e,dnsServer:t,inclusionList:r,exclusionList:o};return i!==void 0&&(a.broadcastAddress=i),s!==void 0&&(a.domainSearch=s),n!==void 0&&(a.mtu=n),await new Promise((c,u)=>{chrome.vpnProvider.setParameters(a,()=>{chrome.runtime.lastError?u(new Error(chrome.runtime.lastError.message)):c();});}),this.formatSuccess("VPN parameters set successfully",{parameters:a})}catch(a){return this.formatError(a)}});}registerNotifyConnectionStateChanged(){this.server.registerTool("extension_tool_notify_vpn_connection_state",{description:"Notify the VPN session state to the platform. This will succeed only when the VPN session is owned by the extension",inputSchema:{state:z.enum(["connected","failure"]).describe("The VPN session state of the VPN client")}},async({state:e})=>{try{return await new Promise((t,r)=>{chrome.vpnProvider.notifyConnectionStateChanged(e,()=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t();});}),this.formatSuccess("VPN connection state notified successfully",{state:e})}catch(t){return this.formatError(t)}});}registerSendPacket(){this.server.registerTool("extension_tool_send_vpn_packet",{description:"Send an IP packet through the tunnel created for the VPN session. This will succeed only when the VPN session is owned by the extension",inputSchema:{data:z.string().describe("The IP packet data as a base64 encoded string")}},async({data:e})=>{try{let t=atob(e),r=new Uint8Array(t.length);for(let i=0;i<t.length;i++)r[i]=t.charCodeAt(i);let o=r.buffer;return await new Promise((i,s)=>{chrome.vpnProvider.sendPacket(o,()=>{chrome.runtime.lastError?s(new Error(chrome.runtime.lastError.message)):i();});}),this.formatSuccess("VPN packet sent successfully",{packetSize:o.byteLength})}catch(t){return this.formatError(t)}});}};var Bt=class extends d{apiName="Wallpaper";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.wallpaper?typeof chrome.wallpaper.setWallpaper!="function"?{available:!1,message:"chrome.wallpaper.setWallpaper is not available",details:"The wallpaper API appears to be partially available. Check manifest permissions and ensure you are running on ChromeOS."}:{available:!0,message:"Wallpaper API is fully available"}:{available:!1,message:"chrome.wallpaper API is not defined",details:'This extension needs the "wallpaper" permission in its manifest.json and only works on ChromeOS'}}catch(e){return {available:false,message:"Failed to access chrome.wallpaper API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("setWallpaper")&&this.registerSetWallpaper();}registerSetWallpaper(){this.server.registerTool("extension_tool_set_wallpaper",{description:"Set the ChromeOS wallpaper to an image from a URL or data",inputSchema:{filename:z.string().describe("The file name of the saved wallpaper"),layout:z.enum(["STRETCH","CENTER","CENTER_CROPPED"]).describe("The wallpaper layout"),url:z.string().optional().describe("The URL of the wallpaper to be set (can be relative)"),data:z.string().optional().describe("Base64 encoded jpeg or png wallpaper image data"),thumbnail:z.boolean().optional().describe("True if a 128x60 thumbnail should be generated")}},async({filename:e,layout:t,url:r,data:o,thumbnail:i})=>{try{if(!r&&!o)return this.formatError("Either url or data must be specified to set wallpaper");if(r&&o)return this.formatError("Cannot specify both url and data. Choose one method to set wallpaper");let s={filename:e,layout:t};if(r&&(s.url=r),o)try{let c=atob(o),u=new Uint8Array(c.length);for(let m=0;m<c.length;m++)u[m]=c.charCodeAt(m);s.data=u.buffer;}catch{return this.formatError("Invalid base64 data provided")}i!==void 0&&(s.thumbnail=i);let n=await new Promise((c,u)=>{chrome.wallpaper.setWallpaper(s,m=>{chrome.runtime.lastError?u(new Error(chrome.runtime.lastError.message)):c(m);});}),a={filename:e,layout:t,success:!0};if(r&&(a.url=r),n){let c=new Uint8Array(n),u="";for(let m=0;m<c.byteLength;m++)u+=String.fromCharCode(c[m]);a.thumbnail=btoa(u),a.thumbnailSize=n.byteLength;}return this.formatSuccess("Wallpaper set successfully",a)}catch(s){return this.formatError(s)}});}};var Wt=class extends d{apiName="WebAuthenticationProxy";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.webAuthenticationProxy?typeof chrome.webAuthenticationProxy.attach!="function"?{available:!1,message:"chrome.webAuthenticationProxy.attach is not available",details:"The webAuthenticationProxy API appears to be partially available. Check manifest permissions."}:{available:!0,message:"WebAuthenticationProxy API is fully available"}:{available:!1,message:"chrome.webAuthenticationProxy API is not defined",details:'This extension needs the "webAuthenticationProxy" permission in its manifest.json'}}catch(e){return {available:false,message:"Failed to access chrome.webAuthenticationProxy API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("attach")&&this.registerAttach(),this.shouldRegisterTool("detach")&&this.registerDetach(),this.shouldRegisterTool("completeCreateRequest")&&this.registerCompleteCreateRequest(),this.shouldRegisterTool("completeGetRequest")&&this.registerCompleteGetRequest(),this.shouldRegisterTool("completeIsUvpaaRequest")&&this.registerCompleteIsUvpaaRequest(),this.shouldRegisterTool("onCreateRequest")&&this.registerOnCreateRequest(),this.shouldRegisterTool("onGetRequest")&&this.registerOnGetRequest(),this.shouldRegisterTool("onIsUvpaaRequest")&&this.registerOnIsUvpaaRequest(),this.shouldRegisterTool("onRemoteSessionStateChange")&&this.registerOnRemoteSessionStateChange(),this.shouldRegisterTool("onRequestCanceled")&&this.registerOnRequestCanceled();}registerAttach(){this.server.registerTool("extension_tool_attach_web_authentication_proxy",{description:"Makes this extension the active Web Authentication API request proxy",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.webAuthenticationProxy.attach(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return e?this.formatError(e):this.formatSuccess("Successfully attached as Web Authentication API request proxy")}catch(e){return this.formatError(e)}});}registerDetach(){this.server.registerTool("extension_tool_detach_web_authentication_proxy",{description:"Removes this extension from being the active Web Authentication API request proxy",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.webAuthenticationProxy.detach(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return e?this.formatError(e):this.formatSuccess("Successfully detached from Web Authentication API request proxy")}catch(e){return this.formatError(e)}});}registerCompleteCreateRequest(){this.server.registerTool("extension_tool_complete_create_request",{description:"Reports the result of a navigator.credentials.create() call",inputSchema:{requestId:z.number().describe("The requestId of the CreateRequest"),responseJson:z.string().optional().describe("The PublicKeyCredential serialized as JSON"),error:z.object({name:z.string().describe("The DOMException name"),message:z.string().describe("The DOMException message")}).optional().describe("The DOMException yielded by the remote request, if any")}},async({requestId:e,responseJson:t,error:r})=>{try{let o={requestId:e};return t!==void 0&&(o.responseJson=t),r!==void 0&&(o.error=r),await new Promise((i,s)=>{chrome.webAuthenticationProxy.completeCreateRequest(o,()=>{chrome.runtime.lastError?s(new Error(chrome.runtime.lastError.message)):i();});}),this.formatSuccess("Create request completed successfully",{requestId:e})}catch(o){return this.formatError(o)}});}registerCompleteGetRequest(){this.server.registerTool("extension_tool_complete_get_request",{description:"Reports the result of a navigator.credentials.get() call",inputSchema:{requestId:z.number().describe("The requestId of the GetRequest"),responseJson:z.string().optional().describe("The PublicKeyCredential serialized as JSON"),error:z.object({name:z.string().describe("The DOMException name"),message:z.string().describe("The DOMException message")}).optional().describe("The DOMException yielded by the remote request, if any")}},async({requestId:e,responseJson:t,error:r})=>{try{let o={requestId:e};return t!==void 0&&(o.responseJson=t),r!==void 0&&(o.error=r),await new Promise((i,s)=>{chrome.webAuthenticationProxy.completeGetRequest(o,()=>{chrome.runtime.lastError?s(new Error(chrome.runtime.lastError.message)):i();});}),this.formatSuccess("Get request completed successfully",{requestId:e})}catch(o){return this.formatError(o)}});}registerCompleteIsUvpaaRequest(){this.server.registerTool("extension_tool_complete_is_uvpaa_request",{description:"Reports the result of a PublicKeyCredential.isUserVerifyingPlatformAuthenticator() call",inputSchema:{requestId:z.number().describe("The requestId of the IsUvpaaRequest"),isUvpaa:z.boolean().describe("Whether user verifying platform authenticator is available")}},async({requestId:e,isUvpaa:t})=>{try{let r={requestId:e,isUvpaa:t};return await new Promise((o,i)=>{chrome.webAuthenticationProxy.completeIsUvpaaRequest(r,()=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o();});}),this.formatSuccess("IsUvpaa request completed successfully",{requestId:e,isUvpaa:t})}catch(r){return this.formatError(r)}});}registerOnCreateRequest(){this.server.registerTool("extension_tool_listen_create_requests",{description:"Start listening for WebAuthn navigator.credentials.create() calls",inputSchema:{}},async()=>{try{let e=t=>{console.log("WebAuthn create request received:",{requestId:t.requestId,requestDetailsJson:t.requestDetailsJson});};return chrome.webAuthenticationProxy.onCreateRequest.addListener(e),this.formatSuccess("Started listening for WebAuthn create requests")}catch(e){return this.formatError(e)}});}registerOnGetRequest(){this.server.registerTool("extension_tool_listen_get_requests",{description:"Start listening for WebAuthn navigator.credentials.get() calls",inputSchema:{}},async()=>{try{let e=t=>{console.log("WebAuthn get request received:",{requestId:t.requestId,requestDetailsJson:t.requestDetailsJson});};return chrome.webAuthenticationProxy.onGetRequest.addListener(e),this.formatSuccess("Started listening for WebAuthn get requests")}catch(e){return this.formatError(e)}});}registerOnIsUvpaaRequest(){this.server.registerTool("extension_tool_listen_is_uvpaa_requests",{description:"Start listening for PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable() calls",inputSchema:{}},async()=>{try{let e=t=>{console.log("WebAuthn isUvpaa request received:",{requestId:t.requestId});};return chrome.webAuthenticationProxy.onIsUvpaaRequest.addListener(e),this.formatSuccess("Started listening for WebAuthn isUvpaa requests")}catch(e){return this.formatError(e)}});}registerOnRemoteSessionStateChange(){this.server.registerTool("extension_tool_listen_remote_session_state_changes",{description:"Start listening for remote session state changes",inputSchema:{}},async()=>{try{let e=()=>{console.log("Remote session state change detected");};return chrome.webAuthenticationProxy.onRemoteSessionStateChange.addListener(e),this.formatSuccess("Started listening for remote session state changes")}catch(e){return this.formatError(e)}});}registerOnRequestCanceled(){this.server.registerTool("extension_tool_listen_request_canceled",{description:"Start listening for canceled WebAuthn requests",inputSchema:{}},async()=>{try{let e=t=>{console.log("WebAuthn request canceled:",{requestId:t});};return chrome.webAuthenticationProxy.onRequestCanceled.addListener(e),this.formatSuccess("Started listening for canceled WebAuthn requests")}catch(e){return this.formatError(e)}});}};var Vt=class extends d{apiName="WebNavigation";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.webNavigation?typeof chrome.webNavigation.getAllFrames!="function"?{available:!1,message:"chrome.webNavigation.getAllFrames is not available",details:"The webNavigation API appears to be partially available. Check manifest permissions."}:{available:!0,message:"WebNavigation API is fully available"}:{available:!1,message:"chrome.webNavigation API is not defined",details:'This extension needs the "webNavigation" permission in its manifest.json'}}catch(e){return {available:false,message:"Failed to access chrome.webNavigation API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("getAllFrames")&&this.registerGetAllFrames(),this.shouldRegisterTool("getFrame")&&this.registerGetFrame(),this.shouldRegisterTool("onBeforeNavigate")&&this.registerOnBeforeNavigate(),this.shouldRegisterTool("onCommitted")&&this.registerOnCommitted(),this.shouldRegisterTool("onCompleted")&&this.registerOnCompleted(),this.shouldRegisterTool("onCreatedNavigationTarget")&&this.registerOnCreatedNavigationTarget(),this.shouldRegisterTool("onDOMContentLoaded")&&this.registerOnDOMContentLoaded(),this.shouldRegisterTool("onErrorOccurred")&&this.registerOnErrorOccurred(),this.shouldRegisterTool("onHistoryStateUpdated")&&this.registerOnHistoryStateUpdated(),this.shouldRegisterTool("onReferenceFragmentUpdated")&&this.registerOnReferenceFragmentUpdated(),this.shouldRegisterTool("onTabReplaced")&&this.registerOnTabReplaced();}registerGetAllFrames(){this.server.registerTool("extension_tool_get_all_frames",{description:"Retrieves information about all frames of a given tab",inputSchema:{tabId:z.number().describe("The ID of the tab to retrieve all frames from")}},async({tabId:e})=>{try{let t=await new Promise((r,o)=>{chrome.webNavigation.getAllFrames({tabId:e},i=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r(i??void 0);});});return t?this.formatJson({tabId:e,frameCount:t.length,frames:t.map(r=>({frameId:r.frameId,parentFrameId:r.parentFrameId,processId:r.processId,url:r.url,errorOccurred:r.errorOccurred,documentId:r.documentId,documentLifecycle:r.documentLifecycle,frameType:r.frameType,parentDocumentId:r.parentDocumentId}))}):this.formatError("Invalid tab ID or no frames found")}catch(t){return this.formatError(t)}});}registerGetFrame(){this.server.registerTool("extension_tool_get_frame",{description:"Retrieves information about the given frame. A frame refers to an iframe or frame of a web page",inputSchema:{tabId:z.number().optional().describe("The ID of the tab in which the frame is"),frameId:z.number().optional().describe("The ID of the frame in the given tab")}},async({tabId:e,frameId:t})=>{try{let r={};e!==void 0&&(r.tabId=e),t!==void 0&&(r.frameId=t);let o=await new Promise((i,s)=>{chrome.webNavigation.getFrame(r,n=>{chrome.runtime.lastError?s(new Error(chrome.runtime.lastError.message)):i(n??void 0);});});return o?this.formatJson({parentFrameId:o.parentFrameId,url:o.url,errorOccurred:o.errorOccurred,documentId:o.documentId,documentLifecycle:o.documentLifecycle,frameType:o.frameType,parentDocumentId:o.parentDocumentId}):this.formatSuccess("No frame found with the specified parameters")}catch(r){return this.formatError(r)}});}registerOnBeforeNavigate(){this.server.registerTool("extension_tool_on_before_navigate",{description:"Sets up a listener for navigation events that are about to occur. Returns immediately after setting up the listener",inputSchema:{urlFilters:z.array(z.string()).optional().describe("URL patterns to filter navigation events. If not provided, listens to all navigations")}},async({urlFilters:e})=>{try{let t=e?{url:e.map(r=>({urlMatches:r}))}:void 0;return chrome.webNavigation.onBeforeNavigate.addListener(r=>{console.log("Navigation about to occur:",{tabId:r.tabId,frameId:r.frameId,parentFrameId:r.parentFrameId,url:r.url,timeStamp:r.timeStamp,processId:r.processId,documentLifecycle:r.documentLifecycle,frameType:r.frameType,parentDocumentId:r.parentDocumentId});},t),this.formatSuccess("onBeforeNavigate listener registered successfully",{hasFilters:!!t,filterCount:e?.length||0})}catch(t){return this.formatError(t)}});}registerOnCommitted(){this.server.registerTool("extension_tool_on_committed",{description:"Sets up a listener for navigation committed events. Fired when a navigation is committed",inputSchema:{urlFilters:z.array(z.string()).optional().describe("URL patterns to filter navigation events. If not provided, listens to all navigations")}},async({urlFilters:e})=>{try{let t=e?{url:e.map(r=>({urlMatches:r}))}:void 0;return chrome.webNavigation.onCommitted.addListener(r=>{console.log("Navigation committed:",{tabId:r.tabId,frameId:r.frameId,url:r.url,timeStamp:r.timeStamp,processId:r.processId,transitionType:r.transitionType,transitionQualifiers:r.transitionQualifiers,documentId:r.documentId,documentLifecycle:r.documentLifecycle,frameType:r.frameType,parentDocumentId:r.parentDocumentId});},t),this.formatSuccess("onCommitted listener registered successfully",{hasFilters:!!t,filterCount:e?.length||0})}catch(t){return this.formatError(t)}});}registerOnCompleted(){this.server.registerTool("extension_tool_on_completed",{description:"Sets up a listener for navigation completed events. Fired when a document and its resources are completely loaded",inputSchema:{urlFilters:z.array(z.string()).optional().describe("URL patterns to filter navigation events. If not provided, listens to all navigations")}},async({urlFilters:e})=>{try{let t=e?{url:e.map(r=>({urlMatches:r}))}:void 0;return chrome.webNavigation.onCompleted.addListener(r=>{console.log("Navigation completed:",{tabId:r.tabId,frameId:r.frameId,url:r.url,timeStamp:r.timeStamp,processId:r.processId,documentId:r.documentId,documentLifecycle:r.documentLifecycle,frameType:r.frameType,parentDocumentId:r.parentDocumentId});},t),this.formatSuccess("onCompleted listener registered successfully",{hasFilters:!!t,filterCount:e?.length||0})}catch(t){return this.formatError(t)}});}registerOnCreatedNavigationTarget(){this.server.registerTool("extension_tool_on_created_navigation_target",{description:"Sets up a listener for new navigation target creation events. Fired when a new window or tab is created to host a navigation",inputSchema:{urlFilters:z.array(z.string()).optional().describe("URL patterns to filter navigation events. If not provided, listens to all navigations")}},async({urlFilters:e})=>{try{let t=e?{url:e.map(r=>({urlMatches:r}))}:void 0;return chrome.webNavigation.onCreatedNavigationTarget.addListener(r=>{console.log("Navigation target created:",{sourceTabId:r.sourceTabId,sourceFrameId:r.sourceFrameId,sourceProcessId:r.sourceProcessId,tabId:r.tabId,url:r.url,timeStamp:r.timeStamp});},t),this.formatSuccess("onCreatedNavigationTarget listener registered successfully",{hasFilters:!!t,filterCount:e?.length||0})}catch(t){return this.formatError(t)}});}registerOnDOMContentLoaded(){this.server.registerTool("extension_tool_on_dom_content_loaded",{description:"Sets up a listener for DOM content loaded events. Fired when the page DOM is fully constructed",inputSchema:{urlFilters:z.array(z.string()).optional().describe("URL patterns to filter navigation events. If not provided, listens to all navigations")}},async({urlFilters:e})=>{try{let t=e?{url:e.map(r=>({urlMatches:r}))}:void 0;return chrome.webNavigation.onDOMContentLoaded.addListener(r=>{console.log("DOM content loaded:",{tabId:r.tabId,frameId:r.frameId,url:r.url,timeStamp:r.timeStamp,processId:r.processId,documentId:r.documentId,documentLifecycle:r.documentLifecycle,frameType:r.frameType,parentDocumentId:r.parentDocumentId});},t),this.formatSuccess("onDOMContentLoaded listener registered successfully",{hasFilters:!!t,filterCount:e?.length||0})}catch(t){return this.formatError(t)}});}registerOnErrorOccurred(){this.server.registerTool("extension_tool_on_error_occurred",{description:"Sets up a listener for navigation error events. Fired when an error occurs and navigation is aborted",inputSchema:{urlFilters:z.array(z.string()).optional().describe("URL patterns to filter navigation events. If not provided, listens to all navigations")}},async({urlFilters:e})=>{try{let t=e?{url:e.map(r=>({urlMatches:r}))}:void 0;return chrome.webNavigation.onErrorOccurred.addListener(r=>{console.log("Navigation error occurred:",{tabId:r.tabId,frameId:r.frameId,url:r.url,error:r.error,timeStamp:r.timeStamp,processId:r.processId,documentId:r.documentId,documentLifecycle:r.documentLifecycle,frameType:r.frameType,parentDocumentId:r.parentDocumentId});},t),this.formatSuccess("onErrorOccurred listener registered successfully",{hasFilters:!!t,filterCount:e?.length||0})}catch(t){return this.formatError(t)}});}registerOnHistoryStateUpdated(){this.server.registerTool("extension_tool_on_history_state_updated",{description:"Sets up a listener for history state update events. Fired when the frame history was updated to a new URL",inputSchema:{urlFilters:z.array(z.string()).optional().describe("URL patterns to filter navigation events. If not provided, listens to all navigations")}},async({urlFilters:e})=>{try{let t=e?{url:e.map(r=>({urlMatches:r}))}:void 0;return chrome.webNavigation.onHistoryStateUpdated.addListener(r=>{console.log("History state updated:",{tabId:r.tabId,frameId:r.frameId,url:r.url,timeStamp:r.timeStamp,processId:r.processId,transitionType:r.transitionType,transitionQualifiers:r.transitionQualifiers,documentId:r.documentId,documentLifecycle:r.documentLifecycle,frameType:r.frameType,parentDocumentId:r.parentDocumentId});},t),this.formatSuccess("onHistoryStateUpdated listener registered successfully",{hasFilters:!!t,filterCount:e?.length||0})}catch(t){return this.formatError(t)}});}registerOnReferenceFragmentUpdated(){this.server.registerTool("extension_tool_on_reference_fragment_updated",{description:"Sets up a listener for reference fragment update events. Fired when the reference fragment of a frame was updated",inputSchema:{urlFilters:z.array(z.string()).optional().describe("URL patterns to filter navigation events. If not provided, listens to all navigations")}},async({urlFilters:e})=>{try{let t=e?{url:e.map(r=>({urlMatches:r}))}:void 0;return chrome.webNavigation.onReferenceFragmentUpdated.addListener(r=>{console.log("Reference fragment updated:",{tabId:r.tabId,frameId:r.frameId,url:r.url,timeStamp:r.timeStamp,processId:r.processId,transitionType:r.transitionType,transitionQualifiers:r.transitionQualifiers,documentId:r.documentId,documentLifecycle:r.documentLifecycle,frameType:r.frameType,parentDocumentId:r.parentDocumentId});},t),this.formatSuccess("onReferenceFragmentUpdated listener registered successfully",{hasFilters:!!t,filterCount:e?.length||0})}catch(t){return this.formatError(t)}});}registerOnTabReplaced(){this.server.registerTool("extension_tool_on_tab_replaced",{description:"Sets up a listener for tab replacement events. Fired when the contents of a tab is replaced by a different tab",inputSchema:{}},async()=>{try{return chrome.webNavigation.onTabReplaced.addListener(e=>{console.log("Tab replaced:",{replacedTabId:e.replacedTabId,tabId:e.tabId,timeStamp:e.timeStamp});}),this.formatSuccess("onTabReplaced listener registered successfully")}catch(e){return this.formatError(e)}});}};var Jt=class extends d{apiName="WebRequest";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.webRequest?typeof chrome.webRequest.handlerBehaviorChanged!="function"?{available:!1,message:"chrome.webRequest.handlerBehaviorChanged is not available",details:"The webRequest API appears to be partially available. Check manifest permissions."}:chrome.webRequest.onBeforeRequest?{available:!0,message:"WebRequest API is fully available"}:{available:!1,message:"chrome.webRequest events are not available",details:"WebRequest events are required for this API to function properly."}:{available:!1,message:"chrome.webRequest API is not defined",details:'This extension needs the "webRequest" permission in its manifest.json'}}catch(e){return {available:false,message:"Failed to access chrome.webRequest API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("addListener")&&this.registerAddListener(),this.shouldRegisterTool("removeListener")&&this.registerRemoveListener(),this.shouldRegisterTool("hasListener")&&this.registerHasListener(),this.shouldRegisterTool("handlerBehaviorChanged")&&this.registerHandlerBehaviorChanged(),this.shouldRegisterTool("getActiveListeners")&&this.registerGetActiveListeners();}registerAddListener(){this.server.registerTool("extension_tool_add_webrequest_listener",{description:"Add a listener to a webRequest event to monitor or modify network requests",inputSchema:{event:z.enum(["onBeforeRequest","onBeforeSendHeaders","onSendHeaders","onHeadersReceived","onAuthRequired","onBeforeRedirect","onResponseStarted","onCompleted","onErrorOccurred"]).describe("The webRequest event to listen to"),urls:z.array(z.string()).describe('Array of URL patterns to match (e.g., ["<all_urls>", "*://example.com/*"])'),types:z.array(z.enum(["main_frame","sub_frame","stylesheet","script","image","font","object","xmlhttprequest","ping","csp_report","media","websocket","webbundle","other"])).optional().describe("Array of resource types to filter"),tabId:z.number().optional().describe("Specific tab ID to monitor"),windowId:z.number().optional().describe("Specific window ID to monitor"),extraInfoSpec:z.array(z.enum(["blocking","requestHeaders","responseHeaders","requestBody","extraHeaders","asyncBlocking"])).optional().describe("Additional information to include in the event"),blocking:z.boolean().optional().describe("Whether to block requests for modification (requires webRequestBlocking permission)")}},async({event:e,urls:t,types:r,tabId:o,windowId:i,extraInfoSpec:s,blocking:n})=>{try{let a={urls:t};r&&(a.types=r),o!==void 0&&(a.tabId=o),i!==void 0&&(a.windowId=i);let c=s||[];n&&!c.includes("blocking")&&c.push("blocking");let u=g=>(console.log(`WebRequest ${e}:`,{requestId:g.requestId,url:g.url,method:g.method,type:g.type,tabId:g.tabId,timeStamp:g.timeStamp}),n?{}:g),m=chrome.webRequest[e];return m&&typeof m.addListener=="function"?(c.length>0?m.addListener(u,a,c):m.addListener(u,a),this.formatSuccess("WebRequest listener added successfully",{event:e,filter:a,extraInfoSpec:c,blocking:n||!1})):this.formatError(`Invalid webRequest event: ${e}`)}catch(a){return this.formatError(a)}});}registerRemoveListener(){this.server.registerTool("extension_tool_remove_webrequest_listener",{description:"Remove a webRequest event listener",inputSchema:{event:z.enum(["onBeforeRequest","onBeforeSendHeaders","onSendHeaders","onHeadersReceived","onAuthRequired","onBeforeRedirect","onResponseStarted","onCompleted","onErrorOccurred"]).describe("The webRequest event to remove listener from")}},async({event:e})=>{try{let t=chrome.webRequest[e];return t&&typeof t.removeListener=="function"?this.formatSuccess("WebRequest listener removal attempted",{event:e,note:"All listeners for this event type have been targeted for removal"}):this.formatError(`Invalid webRequest event: ${e}`)}catch(t){return this.formatError(t)}});}registerHasListener(){this.server.registerTool("extension_tool_has_webrequest_listener",{description:"Check if a webRequest event has any listeners",inputSchema:{event:z.enum(["onBeforeRequest","onBeforeSendHeaders","onSendHeaders","onHeadersReceived","onAuthRequired","onBeforeRedirect","onResponseStarted","onCompleted","onErrorOccurred"]).describe("The webRequest event to check")}},async({event:e})=>{try{let t=chrome.webRequest[e];if(t&&typeof t.hasListener=="function"){let r=t.hasListener();return this.formatJson({event:e,hasListener:r})}else return this.formatError(`Invalid webRequest event: ${e}`)}catch(t){return this.formatError(t)}});}registerHandlerBehaviorChanged(){this.server.registerTool("extension_tool_handler_behavior_changed",{description:"Notify that webRequest handler behavior has changed to prevent incorrect caching",inputSchema:{}},async()=>{try{return await new Promise((e,t)=>{chrome.webRequest.handlerBehaviorChanged(()=>{chrome.runtime.lastError?t(new Error(chrome.runtime.lastError.message)):e();});}),this.formatSuccess("Handler behavior change notification sent",{note:"This flushes the in-memory cache to ensure behavior changes take effect",warning:"This is an expensive operation and should not be called frequently"})}catch(e){return this.formatError(e)}});}registerGetActiveListeners(){this.server.registerTool("extension_tool_get_active_webrequest_listeners",{description:"Get information about currently active webRequest listeners",inputSchema:{}},async()=>{try{let e=["onBeforeRequest","onBeforeSendHeaders","onSendHeaders","onHeadersReceived","onAuthRequired","onBeforeRedirect","onResponseStarted","onCompleted","onErrorOccurred"],t=e.map(o=>{let i=chrome.webRequest[o],s=i&&typeof i.hasListener=="function"?i.hasListener():!1;return {event:o,hasListener:s}}),r=t.filter(o=>o.hasListener).length;return this.formatJson({totalEvents:e.length,activeListeners:r,listeners:t,maxHandlerCalls:chrome.webRequest.MAX_HANDLER_BEHAVIOR_CHANGED_CALLS_PER_10_MINUTES||20})}catch(e){return this.formatError(e)}});}};var zt=class extends d{apiName="Windows";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.windows?typeof chrome.windows.getAll!="function"?{available:!1,message:"chrome.windows.getAll is not available",details:"The windows API appears to be partially available. Check manifest permissions."}:(chrome.windows.getAll(e=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"Windows API is fully available"}):{available:!1,message:"chrome.windows API is not defined",details:'This extension needs the "windows" permission in its manifest.json'}}catch(e){return {available:false,message:"Failed to access chrome.windows API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("create")&&this.registerCreate(),this.shouldRegisterTool("get")&&this.registerGet(),this.shouldRegisterTool("getAll")&&this.registerGetAll(),this.shouldRegisterTool("getCurrent")&&this.registerGetCurrent(),this.shouldRegisterTool("getLastFocused")&&this.registerGetLastFocused(),this.shouldRegisterTool("remove")&&this.registerRemove(),this.shouldRegisterTool("update")&&this.registerUpdate();}registerCreate(){this.server.registerTool("extension_tool_create_window",{description:"Create a new browser window with optional sizing, position, or default URL",inputSchema:{url:z.union([z.string(),z.array(z.string())]).optional().describe("A URL or array of URLs to open as tabs in the window"),focused:z.boolean().optional().describe("If true, opens an active window. If false, opens an inactive window"),height:z.number().optional().describe("The height in pixels of the new window, including the frame"),incognito:z.boolean().optional().describe("Whether the new window should be an incognito window"),left:z.number().optional().describe("The number of pixels to position the new window from the left edge of the screen"),setSelfAsOpener:z.boolean().optional().describe("If true, the newly-created window's 'window.opener' is set to the caller"),state:z.enum(["normal","minimized","maximized","fullscreen","locked-fullscreen"]).optional().describe("The initial state of the window"),tabId:z.number().optional().describe("The ID of the tab to add to the new window"),top:z.number().optional().describe("The number of pixels to position the new window from the top edge of the screen"),type:z.enum(["normal","popup","panel"]).optional().describe("Specifies what type of browser window to create"),width:z.number().optional().describe("The width in pixels of the new window, including the frame")}},async({url:e,focused:t,height:r,incognito:o,left:i,setSelfAsOpener:s,state:n,tabId:a,top:c,type:u,width:m})=>{try{let g={};e!==void 0&&(g.url=e),t!==void 0&&(g.focused=t),r!==void 0&&(g.height=r),o!==void 0&&(g.incognito=o),i!==void 0&&(g.left=i),s!==void 0&&(g.setSelfAsOpener=s),n!==void 0&&(g.state=n),a!==void 0&&(g.tabId=a),c!==void 0&&(g.top=c),u!==void 0&&(g.type=u),m!==void 0&&(g.width=m);let w=await new Promise((k,R)=>{chrome.windows.create(g,D=>{chrome.runtime.lastError?R(new Error(chrome.runtime.lastError.message)):k(D);});});return this.formatJson({id:w.id,focused:w.focused,incognito:w.incognito,alwaysOnTop:w.alwaysOnTop,state:w.state,type:w.type,left:w.left,top:w.top,width:w.width,height:w.height,tabs:w.tabs?.map(k=>({id:k.id,url:k.url,title:k.title,active:k.active}))})}catch(g){return this.formatError(g)}});}registerGet(){this.server.registerTool("extension_tool_get_window",{description:"Get details about a specific window",inputSchema:{windowId:z.number().describe("The ID of the window to get"),populate:z.boolean().optional().describe("If true, the window object will include a tabs property with tab details"),windowTypes:z.array(z.enum(["normal","popup","panel","app","devtools"])).optional().describe("Filter the window based on its type")}},async({windowId:e,populate:t,windowTypes:r})=>{try{let o={};t!==void 0&&(o.populate=t),r!==void 0&&(o.windowTypes=r);let i=await new Promise((s,n)=>{chrome.windows.get(e,o,a=>{chrome.runtime.lastError?n(new Error(chrome.runtime.lastError.message)):s(a);});});return this.formatJson({id:i.id,focused:i.focused,incognito:i.incognito,alwaysOnTop:i.alwaysOnTop,state:i.state,type:i.type,left:i.left,top:i.top,width:i.width,height:i.height,sessionId:i.sessionId,tabs:i.tabs?.map(s=>({id:s.id,url:s.url,title:s.title,active:s.active,index:s.index}))})}catch(o){return this.formatError(o)}});}registerGetAll(){this.server.registerTool("extension_tool_get_all_windows",{description:"Get all browser windows",inputSchema:{populate:z.boolean().optional().describe("If true, each window object will include a tabs property with tab details"),windowTypes:z.array(z.enum(["normal","popup","panel","app","devtools"])).optional().describe("Filter windows based on their type")}},async({populate:e,windowTypes:t})=>{try{let r={};e!==void 0&&(r.populate=e),t!==void 0&&(r.windowTypes=t);let o=await new Promise((i,s)=>{chrome.windows.getAll(r,n=>{chrome.runtime.lastError?s(new Error(chrome.runtime.lastError.message)):i(n);});});return this.formatJson({count:o.length,windows:o.map(i=>({id:i.id,focused:i.focused,incognito:i.incognito,alwaysOnTop:i.alwaysOnTop,state:i.state,type:i.type,left:i.left,top:i.top,width:i.width,height:i.height,sessionId:i.sessionId,tabs:i.tabs?.map(s=>({id:s.id,url:s.url,title:s.title,active:s.active,index:s.index}))}))})}catch(r){return this.formatError(r)}});}registerGetCurrent(){this.server.registerTool("extension_tool_get_current_window",{description:"Get the current window",inputSchema:{populate:z.boolean().optional().describe("If true, the window object will include a tabs property with tab details"),windowTypes:z.array(z.enum(["normal","popup","panel","app","devtools"])).optional().describe("Filter the window based on its type")}},async({populate:e,windowTypes:t})=>{try{let r={};e!==void 0&&(r.populate=e),t!==void 0&&(r.windowTypes=t);let o=await new Promise((i,s)=>{chrome.windows.getCurrent(r,n=>{chrome.runtime.lastError?s(new Error(chrome.runtime.lastError.message)):i(n);});});return this.formatJson({id:o.id,focused:o.focused,incognito:o.incognito,alwaysOnTop:o.alwaysOnTop,state:o.state,type:o.type,left:o.left,top:o.top,width:o.width,height:o.height,sessionId:o.sessionId,tabs:o.tabs?.map(i=>({id:i.id,url:i.url,title:i.title,active:i.active,index:i.index}))})}catch(r){return this.formatError(r)}});}registerGetLastFocused(){this.server.registerTool("extension_tool_get_last_focused_window",{description:"Get the window that was most recently focused",inputSchema:{populate:z.boolean().optional().describe("If true, the window object will include a tabs property with tab details"),windowTypes:z.array(z.enum(["normal","popup","panel","app","devtools"])).optional().describe("Filter the window based on its type")}},async({populate:e,windowTypes:t})=>{try{let r={};e!==void 0&&(r.populate=e),t!==void 0&&(r.windowTypes=t);let o=await new Promise((i,s)=>{chrome.windows.getLastFocused(r,n=>{chrome.runtime.lastError?s(new Error(chrome.runtime.lastError.message)):i(n);});});return this.formatJson({id:o.id,focused:o.focused,incognito:o.incognito,alwaysOnTop:o.alwaysOnTop,state:o.state,type:o.type,left:o.left,top:o.top,width:o.width,height:o.height,sessionId:o.sessionId,tabs:o.tabs?.map(i=>({id:i.id,url:i.url,title:i.title,active:i.active,index:i.index}))})}catch(r){return this.formatError(r)}});}registerRemove(){this.server.registerTool("extension_tool_remove_window",{description:"Remove (close) a window and all the tabs inside it",inputSchema:{windowId:z.number().describe("The ID of the window to remove")}},async({windowId:e})=>{try{return await new Promise((t,r)=>{chrome.windows.remove(e,()=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t();});}),this.formatSuccess("Window removed successfully",{windowId:e})}catch(t){return this.formatError(t)}});}registerUpdate(){this.server.registerTool("extension_tool_update_window",{description:"Update the properties of a window",inputSchema:{windowId:z.number().describe("The ID of the window to update"),drawAttention:z.boolean().optional().describe("If true, causes the window to be displayed in a manner that draws the user's attention"),focused:z.boolean().optional().describe("If true, brings the window to the front"),height:z.number().optional().describe("The height to resize the window to in pixels"),left:z.number().optional().describe("The offset from the left edge of the screen to move the window to in pixels"),state:z.enum(["normal","minimized","maximized","fullscreen","locked-fullscreen"]).optional().describe("The new state of the window"),top:z.number().optional().describe("The offset from the top edge of the screen to move the window to in pixels"),width:z.number().optional().describe("The width to resize the window to in pixels")}},async({windowId:e,drawAttention:t,focused:r,height:o,left:i,state:s,top:n,width:a})=>{try{let c={};t!==void 0&&(c.drawAttention=t),r!==void 0&&(c.focused=r),o!==void 0&&(c.height=o),i!==void 0&&(c.left=i),s!==void 0&&(c.state=s),n!==void 0&&(c.top=n),a!==void 0&&(c.width=a);let u=await new Promise((m,g)=>{chrome.windows.update(e,c,w=>{chrome.runtime.lastError?g(new Error(chrome.runtime.lastError.message)):m(w);});});return this.formatJson({id:u.id,focused:u.focused,incognito:u.incognito,alwaysOnTop:u.alwaysOnTop,state:u.state,type:u.type,left:u.left,top:u.top,width:u.width,height:u.height,sessionId:u.sessionId})}catch(c){return this.formatError(c)}});}};var Ht=(p=>(p.ACCESSIBILITY_FEATURES="accessibilityFeatures",p.ACTION="action",p.ALARMS="alarms",p.AUDIO="audio",p.BOOKMARKS="bookmarks",p.BROWSING_DATA="browsingData",p.CERTIFICATE_PROVIDER="certificateProvider",p.COMMANDS="commands",p.CONTENT_SETTINGS="contentSettings",p.CONTEXT_MENUS="contextMenus",p.COOKIES="cookies",p.DEBUGGER="debugger",p.DECLARATIVE_CONTENT="declarativeContent",p.DECLARATIVE_NET_REQUEST="declarativeNetRequest",p.DESKTOP_CAPTURE="desktopCapture",p.DEVTOOLS_INSPECTED_WINDOW="devtools.inspectedWindow",p.DEVTOOLS_NETWORK="devtools.network",p.DEVTOOLS_PANELS="devtools.panels",p.DEVTOOLS_PERFORMANCE="devtools.performance",p.DEVTOOLS_RECORDER="devtools.recorder",p.DNS="dns",p.DOCUMENT_SCAN="documentScan",p.DOM="dom",p.DOWNLOADS="downloads",p.ENTERPRISE_DEVICE_ATTRIBUTES="enterprise.deviceAttributes",p.ENTERPRISE_HARDWARE_PLATFORM="enterprise.hardwarePlatform",p.ENTERPRISE_NETWORKING_ATTRIBUTES="enterprise.networkingAttributes",p.ENTERPRISE_PLATFORM_KEYS="enterprise.platformKeys",p.EVENTS="events",p.EXTENSION="extension",p.EXTENSION_TYPES="extensionTypes",p.FILE_BROWSER_HANDLER="fileBrowserHandler",p.FILE_SYSTEM_PROVIDER="fileSystemProvider",p.FONT_SETTINGS="fontSettings",p.GCM="gcm",p.HISTORY="history",p.I18N="i18n",p.IDENTITY="identity",p.IDLE="idle",p.INPUT_IME="input.ime",p.INSTANCE_ID="instanceID",p.LOGIN_STATE="loginState",p.MANAGEMENT="management",p.NOTIFICATIONS="notifications",p.OFFSCREEN="offscreen",p.OMNIBOX="omnibox",p.PAGE_CAPTURE="pageCapture",p.PERMISSIONS="permissions",p.PLATFORM_KEYS="platformKeys",p.POWER="power",p.PRINTER_PROVIDER="printerProvider",p.PRINTING="printing",p.PRINTING_METRICS="printingMetrics",p.PRIVACY="privacy",p.PROCESSES="processes",p.PROXY="proxy",p.READING_LIST="readingList",p.RUNTIME="runtime",p.SCRIPTING="scripting",p.SEARCH="search",p.SESSIONS="sessions",p.SIDE_PANEL="sidePanel",p.STORAGE="storage",p.SYSTEM_CPU="system.cpu",p.SYSTEM_DISPLAY="system.display",p.SYSTEM_MEMORY="system.memory",p.SYSTEM_STORAGE="system.storage",p.SYSTEM_LOG="systemLog",p.TAB_CAPTURE="tabCapture",p.TAB_GROUPS="tabGroups",p.TABS="tabs",p.TOP_SITES="topSites",p.TTS="tts",p.TTS_ENGINE="ttsEngine",p.TYPES="types",p.USER_SCRIPTS="userScripts",p.VPN_PROVIDER="vpnProvider",p.WALLPAPER="wallpaper",p.WEB_AUTHENTICATION_PROXY="webAuthenticationProxy",p.WEB_NAVIGATION="webNavigation",p.WEB_REQUEST="webRequest",p.WINDOWS="windows",p))(Ht||{}),Zt=z.enum(["all","chromeos"]),er=z.enum(["stable","dev"]),tr=z.enum(["background","content","devtools","all"]),la=z.object({minChromeVersion:z.number().optional(),platform:Zt,channel:er,manifestVersions:z.array(z.literal(2).or(z.literal(3))),requiresPolicy:z.boolean(),foregroundOnly:z.boolean(),contexts:z.array(tr),namespace:z.string()}),Kt={accessibilityFeatures:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"accessibilityFeatures"},action:{minChromeVersion:88,platform:"all",channel:"stable",manifestVersions:[3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"action"},alarms:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"alarms"},audio:{minChromeVersion:59,platform:"chromeos",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"audio"},bookmarks:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background","content"],namespace:"bookmarks"},browsingData:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"browsingData"},certificateProvider:{minChromeVersion:46,platform:"chromeos",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"certificateProvider"},commands:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"commands"},contentSettings:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"contentSettings"},contextMenus:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"contextMenus"},cookies:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background","content"],namespace:"cookies"},debugger:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"debugger"},declarativeContent:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"declarativeContent"},declarativeNetRequest:{minChromeVersion:84,platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"declarativeNetRequest"},desktopCapture:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"desktopCapture"},"devtools.inspectedWindow":{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["devtools"],namespace:"devtools.inspectedWindow"},"devtools.network":{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["devtools"],namespace:"devtools.network"},"devtools.panels":{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["devtools"],namespace:"devtools.panels"},"devtools.performance":{minChromeVersion:129,platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["devtools"],namespace:"devtools.performance"},"devtools.recorder":{minChromeVersion:105,platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["devtools"],namespace:"devtools.recorder"},dns:{platform:"all",channel:"dev",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"dns"},documentScan:{minChromeVersion:44,platform:"chromeos",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"documentScan"},dom:{minChromeVersion:88,platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["content"],namespace:"dom"},downloads:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"downloads"},"enterprise.deviceAttributes":{minChromeVersion:46,platform:"chromeos",channel:"stable",manifestVersions:[2,3],requiresPolicy:true,foregroundOnly:false,contexts:["background"],namespace:"enterprise.deviceAttributes"},"enterprise.hardwarePlatform":{minChromeVersion:71,platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:true,foregroundOnly:false,contexts:["background"],namespace:"enterprise.hardwarePlatform"},"enterprise.networkingAttributes":{minChromeVersion:85,platform:"chromeos",channel:"stable",manifestVersions:[2,3],requiresPolicy:true,foregroundOnly:false,contexts:["background"],namespace:"enterprise.networkingAttributes"},"enterprise.platformKeys":{platform:"chromeos",channel:"stable",manifestVersions:[2,3],requiresPolicy:true,foregroundOnly:false,contexts:["background"],namespace:"enterprise.platformKeys"},events:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["all"],namespace:"events"},extension:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["all"],namespace:"extension"},extensionTypes:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["all"],namespace:"extensionTypes"},fileBrowserHandler:{platform:"chromeos",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:true,contexts:["background"],namespace:"fileBrowserHandler"},fileSystemProvider:{platform:"chromeos",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"fileSystemProvider"},fontSettings:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"fontSettings"},gcm:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"gcm"},history:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background","content"],namespace:"history"},i18n:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["all"],namespace:"i18n"},identity:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"identity"},idle:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"idle"},"input.ime":{platform:"chromeos",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"input.ime"},instanceID:{minChromeVersion:44,platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"instanceID"},loginState:{minChromeVersion:78,platform:"chromeos",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"loginState"},management:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"management"},notifications:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"notifications"},offscreen:{minChromeVersion:109,platform:"all",channel:"stable",manifestVersions:[3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"offscreen"},omnibox:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"omnibox"},pageCapture:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"pageCapture"},permissions:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background","content"],namespace:"permissions"},platformKeys:{minChromeVersion:45,platform:"chromeos",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"platformKeys"},power:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"power"},printerProvider:{minChromeVersion:44,platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"printerProvider"},printing:{minChromeVersion:81,platform:"chromeos",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"printing"},printingMetrics:{minChromeVersion:79,platform:"chromeos",channel:"stable",manifestVersions:[2,3],requiresPolicy:true,foregroundOnly:false,contexts:["background"],namespace:"printingMetrics"},privacy:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"privacy"},processes:{platform:"all",channel:"dev",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"processes"},proxy:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"proxy"},readingList:{minChromeVersion:120,platform:"all",channel:"stable",manifestVersions:[3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"readingList"},runtime:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["all"],namespace:"runtime"},scripting:{minChromeVersion:88,platform:"all",channel:"stable",manifestVersions:[3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"scripting"},search:{minChromeVersion:87,platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"search"},sessions:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"sessions"},sidePanel:{minChromeVersion:114,platform:"all",channel:"stable",manifestVersions:[3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"sidePanel"},storage:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["all"],namespace:"storage"},"system.cpu":{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"system.cpu"},"system.display":{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"system.display"},"system.memory":{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"system.memory"},"system.storage":{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"system.storage"},systemLog:{minChromeVersion:125,platform:"chromeos",channel:"stable",manifestVersions:[2,3],requiresPolicy:true,foregroundOnly:false,contexts:["background"],namespace:"systemLog"},tabCapture:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"tabCapture"},tabGroups:{minChromeVersion:89,platform:"all",channel:"stable",manifestVersions:[3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"tabGroups"},tabs:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background","content"],namespace:"tabs"},topSites:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"topSites"},tts:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"tts"},ttsEngine:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"ttsEngine"},types:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["all"],namespace:"types"},userScripts:{minChromeVersion:120,platform:"all",channel:"stable",manifestVersions:[3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"userScripts"},vpnProvider:{minChromeVersion:43,platform:"chromeos",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"vpnProvider"},wallpaper:{minChromeVersion:43,platform:"chromeos",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"wallpaper"},webAuthenticationProxy:{minChromeVersion:115,platform:"all",channel:"stable",manifestVersions:[3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"webAuthenticationProxy"},webNavigation:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"webNavigation"},webRequest:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"webRequest"},windows:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"windows"}};function rr(f,e,t,r="all",o){let i=Kt[f];return !(!i.contexts.includes(e)&&!i.contexts.includes("all")||!i.manifestVersions.includes(t)||i.platform!=="all"&&i.platform!==r||i.minChromeVersion&&o&&o<i.minChromeVersion)}function da(f){let t=Kt[f].namespace.split("."),r=chrome;for(let o of t)if(r=r?.[o],!r)return;return r}function ma(f,e,t="all",r){return Object.values(Ht).filter(o=>rr(o,f,e,t,r))}
34
- export{Ae as AlarmsApiTools,Ie as AudioApiTools,d as BaseApiTools,Re as BookmarksApiTools,Pe as BrowsingDataApiTools,Kt as CHROME_API_REGISTRY,Ce as CertificateProviderApiTools,Ht as ChromeApi,la as ChromeApiMetadataSchema,er as ChromeChannelSchema,tr as ChromeContextSchema,Zt as ChromePlatformSchema,ke as CommandsApiTools,De as ContentSettingsApiTools,Oe as ContextMenusApiTools,Le as CookiesApiTools,Ue as DebuggerApiTools,Me as DeclarativeContentApiTools,Ne as DeclarativeNetRequestApiTools,qe as DesktopCaptureApiTools,Ge as DevtoolsInspectedWindowApiTools,je as DevtoolsNetworkApiTools,Be as DevtoolsPanelsApiTools,We as DocumentScanApiTools,Je as DomApiTools,ze as DownloadsApiTools,He as EnterpriseDeviceAttributesApiTools,Ke as EnterpriseHardwarePlatformApiTools,$e as EnterpriseNetworkingAttributesApiTools,Ye as EnterprisePlatformKeysApiTools,Qe as ExtensionApiTools,Xe as FileBrowserHandlerApiTools,Ze as FileSystemProviderApiTools,et as FontSettingsApiTools,tt as GcmApiTools,rt as HistoryApiTools,ot as I18nApiTools,it as IdentityApiTools,nt as IdleApiTools,at as InputImeApiTools,ct as InstanceIDApiTools,lt as LoginStateApiTools,dt as ManagementApiTools,mt as NotificationsApiTools,ht as OffscreenApiTools,pt as OmniboxApiTools,ft as PageCaptureApiTools,gt as PermissionsApiTools,bt as PlatformKeysApiTools,vt as PowerApiTools,yt as PrintingApiTools,wt as PrintingMetricsApiTools,St as ProxyApiTools,Tt as ReadingListApiTools,Et as RuntimeApiTools,_t as ScriptingApiTools,xt as SearchApiTools,At as SessionsApiTools,It as SidePanelApiTools,Rt as StorageApiTools,Pt as SystemCpuApiTools,Ct as SystemLogApiTools,kt as SystemMemoryApiTools,Ot as SystemStorageApiTools,Lt as TabCaptureApiTools,Ut as TabGroupsApiTools,Mt as TabsApiTools,Nt as TopSitesApiTools,qt as TtsApiTools,Gt as TtsEngineApiTools,Ft as UserScriptsApiTools,jt as VpnProviderApiTools,Bt as WallpaperApiTools,Wt as WebAuthenticationProxyApiTools,Vt as WebNavigationApiTools,Jt as WebRequestApiTools,zt as WindowsApiTools,ma as getAvailableApis,da as getChromeApiReference,rr as isApiAvailable};//# sourceMappingURL=index.js.map
33
+ `}],runAt:"document_idle",world:"USER_SCRIPT",allFrames:r}]),await chrome.tabs.reload(e);let n=await Promise.race([s,new Promise(a=>setTimeout(()=>a({timeout:!0}),5e3))]);return await chrome.userScripts.unregister({ids:[i]}),n.timeout?this.formatError(new Error("Script execution timed out")):this.formatJson(n)}catch(o){return this.formatError(o)}});}registerInsertCSS(){this.server.registerTool("extension_tool_insert_css",{description:"Insert CSS into a tab. If no tabId is specified, operates on the currently active tab",inputSchema:{tabId:z.number().optional().describe("Tab ID to insert CSS into (defaults to active tab)"),css:z.string().describe("CSS code to inject"),allFrames:z.boolean().optional().describe("Inject in all frames (default: false)")}},async({tabId:e,css:t,allFrames:r=false})=>{try{if(e===void 0){let[o]=await chrome.tabs.query({active:!0,currentWindow:!0});if(!o||!o.id)return this.formatError(new Error("No active tab found"));e=o.id;}return await chrome.scripting.insertCSS({target:{tabId:e,allFrames:r},css:t}),this.formatSuccess(`CSS injected into tab ${e}`)}catch(o){return this.formatError(o)}});}registerRemoveCSS(){if(typeof chrome.scripting.removeCSS!="function"){console.warn(" \u2717 removeCSS not available - Chrome 90+ required");return}this.server.registerTool("extension_tool_remove_css",{description:"Remove previously injected CSS from a tab. If no tabId is specified, operates on the currently active tab",inputSchema:{tabId:z.number().optional().describe("Tab ID to remove CSS from (defaults to active tab)"),css:z.string().describe("CSS code to remove (must match exactly)"),allFrames:z.boolean().optional().describe("Remove from all frames (default: false)")}},async({tabId:e,css:t,allFrames:r=false})=>{try{if(e===void 0){let[o]=await chrome.tabs.query({active:!0,currentWindow:!0});if(!o||!o.id)return this.formatError(new Error("No active tab found"));e=o.id;}return await chrome.scripting.removeCSS({target:{tabId:e,allFrames:r},css:t}),this.formatSuccess(`CSS removed from tab ${e}`)}catch(o){return this.formatError(o)}});}};var It=class extends m{apiName="Search";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.search?typeof chrome.search.query!="function"?{available:!1,message:"chrome.search.query is not available",details:"The search API appears to be partially available. Check manifest permissions."}:{available:!0,message:"Search API is fully available"}:{available:!1,message:"chrome.search API is not defined",details:'This extension needs the "search" permission in its manifest.json'}}catch(e){return {available:false,message:"Failed to access chrome.search API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("query")&&this.registerQuery();}registerQuery(){this.server.registerTool("extension_tool_search_query",{description:"Search using the default search provider",inputSchema:{text:z.string().describe("String to query with the default search provider"),disposition:z.enum(["CURRENT_TAB","NEW_TAB","NEW_WINDOW"]).optional().describe("Location where search results should be displayed. CURRENT_TAB is the default"),tabId:z.number().optional().describe("Tab ID where search results should be displayed. Cannot be used with disposition")}},async({text:e,disposition:t,tabId:r})=>{try{if(t!==void 0&&r!==void 0)return this.formatError("Cannot specify both disposition and tabId. Use one or the other");let o={text:e};return t!==void 0&&(o.disposition=t),r!==void 0&&(o.tabId=r),await new Promise((i,s)=>{chrome.search.query(o,()=>{chrome.runtime.lastError?s(new Error(chrome.runtime.lastError.message)):i();});}),this.formatSuccess("Search query executed successfully",{text:e,disposition:t||"CURRENT_TAB",tabId:r})}catch(o){return this.formatError(o)}});}};var Rt=class extends m{apiName="Sessions";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.sessions?typeof chrome.sessions.getRecentlyClosed!="function"?{available:!1,message:"chrome.sessions.getRecentlyClosed is not available",details:"The sessions API appears to be partially available. Check manifest permissions."}:(chrome.sessions.getRecentlyClosed(e=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"Sessions API is fully available"}):{available:!1,message:"chrome.sessions API is not defined",details:'This extension needs the "sessions" permission in its manifest.json'}}catch(e){return {available:false,message:"Failed to access chrome.sessions API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("getDevices")&&this.registerGetDevices(),this.shouldRegisterTool("getRecentlyClosed")&&this.registerGetRecentlyClosed(),this.shouldRegisterTool("restore")&&this.registerRestore();}registerGetDevices(){this.server.registerTool("extension_tool_get_devices",{description:"Retrieve all devices with synced sessions",inputSchema:{maxResults:z.number().min(1).max(25).optional().describe("The maximum number of entries to be fetched. Omit to fetch the maximum number of entries (25)")}},async({maxResults:e})=>{try{let t={};e!==void 0&&(t.maxResults=e);let r=await new Promise((o,i)=>{chrome.sessions.getDevices(t,s=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o(s);});});return this.formatJson({count:r.length,devices:r.map(o=>({deviceName:o.deviceName,sessionCount:o.sessions.length,sessions:o.sessions.map(i=>({lastModified:i.lastModified,lastModifiedFormatted:new Date(i.lastModified*1e3).toISOString(),tab:i.tab?{id:i.tab.id,url:i.tab.url,title:i.tab.title,sessionId:i.tab.sessionId}:void 0,window:i.window?{id:i.window.id,sessionId:i.window.sessionId,tabCount:i.window.tabs?.length||0}:void 0}))}))})}catch(t){return this.formatError(t)}});}registerGetRecentlyClosed(){this.server.registerTool("extension_tool_get_recently_closed",{description:"Get the list of recently closed tabs and/or windows",inputSchema:{maxResults:z.number().min(1).max(25).optional().describe("The maximum number of entries to be fetched. Omit to fetch the maximum number of entries (25)")}},async({maxResults:e})=>{try{let t={};e!==void 0&&(t.maxResults=e);let r=await new Promise((o,i)=>{chrome.sessions.getRecentlyClosed(t,s=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o(s);});});return this.formatJson({count:r.length,sessions:r.map(o=>({lastModified:o.lastModified,lastModifiedFormatted:new Date(o.lastModified*1e3).toISOString(),tab:o.tab?{id:o.tab.id,url:o.tab.url,title:o.tab.title,sessionId:o.tab.sessionId,favIconUrl:o.tab.favIconUrl}:void 0,window:o.window?{id:o.window.id,sessionId:o.window.sessionId,tabCount:o.window.tabs?.length||0,incognito:o.window.incognito,type:o.window.type}:void 0}))})}catch(t){return this.formatError(t)}});}registerRestore(){this.server.registerTool("extension_tool_restore_session",{description:"Reopen a recently closed window or tab",inputSchema:{sessionId:z.string().optional().describe("The sessionId of the window or tab to restore. If not specified, the most recently closed session is restored")}},async({sessionId:e})=>{try{let t=await new Promise((r,o)=>{e?chrome.sessions.restore(e,i=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r(i);}):chrome.sessions.restore(i=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r(i);});});return this.formatSuccess("Session restored successfully",{lastModified:t.lastModified,lastModifiedFormatted:new Date(t.lastModified*1e3).toISOString(),tab:t.tab?{id:t.tab.id,url:t.tab.url,title:t.tab.title,sessionId:t.tab.sessionId}:void 0,window:t.window?{id:t.window.id,sessionId:t.window.sessionId,tabCount:t.window.tabs?.length||0,incognito:t.window.incognito,type:t.window.type}:void 0})}catch(t){return this.formatError(t)}});}};var Pt=class extends m{apiName="SidePanel";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.sidePanel?typeof chrome.sidePanel.getOptions!="function"?{available:!1,message:"chrome.sidePanel.getOptions is not available",details:"The sidePanel API appears to be partially available. Check manifest permissions."}:(chrome.sidePanel.getOptions({},e=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"SidePanel API is fully available"}):{available:!1,message:"chrome.sidePanel API is not defined",details:'This extension needs the "sidePanel" permission in its manifest.json'}}catch(e){return {available:false,message:"Failed to access chrome.sidePanel API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("getOptions")&&this.registerGetOptions(),this.shouldRegisterTool("setOptions")&&this.registerSetOptions(),this.shouldRegisterTool("getPanelBehavior")&&this.registerGetPanelBehavior(),this.shouldRegisterTool("setPanelBehavior")&&this.registerSetPanelBehavior(),this.shouldRegisterTool("open")&&this.registerOpen();}registerGetOptions(){this.server.registerTool("extension_tool_get_side_panel_options",{description:"Get the active side panel configuration for a specific tab or default settings",inputSchema:{tabId:z.number().optional().describe("If specified, the side panel options for the given tab will be returned. Otherwise, returns the default side panel options")}},async({tabId:e})=>{try{let t=await new Promise((r,o)=>{let i={};e!==void 0&&(i.tabId=e),chrome.sidePanel.getOptions(i,s=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r(s);});});return this.formatJson({tabId:e||"default",enabled:t.enabled,path:t.path})}catch(t){return this.formatError(t)}});}registerSetOptions(){this.server.registerTool("extension_tool_set_side_panel_options",{description:"Configure the side panel settings for a specific tab or default behavior",inputSchema:{enabled:z.boolean().optional().describe("Whether the side panel should be enabled. Defaults to true"),path:z.string().optional().describe("The path to the side panel HTML file to use. Must be a local resource within the extension package"),tabId:z.number().optional().describe("If specified, the side panel options will only apply to the tab with this id. If omitted, these options set the default behavior")}},async({enabled:e,path:t,tabId:r})=>{try{let o={};return e!==void 0&&(o.enabled=e),t!==void 0&&(o.path=t),r!==void 0&&(o.tabId=r),await new Promise((i,s)=>{chrome.sidePanel.setOptions(o,()=>{chrome.runtime.lastError?s(new Error(chrome.runtime.lastError.message)):i();});}),this.formatSuccess("Side panel options configured successfully",{tabId:r||"default",enabled:e,path:t})}catch(o){return this.formatError(o)}});}registerGetPanelBehavior(){this.server.registerTool("extension_tool_get_side_panel_behavior",{description:"Get the current side panel behavior configuration",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.sidePanel.getPanelBehavior(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({openPanelOnActionClick:e.openPanelOnActionClick})}catch(e){return this.formatError(e)}});}registerSetPanelBehavior(){this.server.registerTool("extension_tool_set_side_panel_behavior",{description:"Configure the side panel behavior, such as opening when the action icon is clicked",inputSchema:{openPanelOnActionClick:z.boolean().optional().describe("Whether clicking the extension action icon will toggle showing the extension entry in the side panel. Defaults to false")}},async({openPanelOnActionClick:e})=>{try{let t={};return e!==void 0&&(t.openPanelOnActionClick=e),await new Promise((r,o)=>{chrome.sidePanel.setPanelBehavior(t,()=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r();});}),this.formatSuccess("Side panel behavior configured successfully",{openPanelOnActionClick:e})}catch(t){return this.formatError(t)}});}registerOpen(){this.server.registerTool("extension_tool_open_side_panel",{description:"Open the side panel for the extension. This may only be called in response to a user action",inputSchema:{tabId:z.number().optional().describe("The tab in which to open the side panel. If there is a tab-specific panel, it will only open for that tab. At least one of tabId or windowId must be provided"),windowId:z.number().optional().describe("The window in which to open the side panel. This is only applicable if the extension has a global side panel or tabId is also specified. At least one of tabId or windowId must be provided")}},async({tabId:e,windowId:t})=>{try{if(e===void 0&&t===void 0)return this.formatError("Either tabId or windowId must be specified to open the side panel");let r={};return e!==void 0&&(r.tabId=e),t!==void 0&&(r.windowId=t),await new Promise((o,i)=>{chrome.sidePanel.open(r,()=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o();});}),this.formatSuccess("Side panel opened successfully",{tabId:e,windowId:t})}catch(r){return this.formatError(r)}});}};var lr=["getStorage","setStorage","removeStorage","clearStorage","getBytesInUse"],kt=z.enum(lr),Ct=class extends m{apiName="Storage";constructor(e,t={}){super(e,t);}checkAvailability(){try{if(!chrome.storage)return {available:!1,message:"chrome.storage API is not defined",details:'This extension needs the "storage" permission in its manifest.json to access storage'};let e=[];return chrome.storage.local&&e.push("local"),chrome.storage.sync&&e.push("sync"),chrome.storage.session&&e.push("session"),chrome.storage.managed&&e.push("managed"),e.length===0?{available:!1,message:"No storage areas are available",details:"The storage API is present but no storage areas can be accessed"}:(chrome.storage.local.get(null,()=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:`Storage API is available with areas: ${e.join(", ")}`})}catch(e){return {available:false,message:"Failed to access chrome.storage API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.server.registerTool("extension_tool_storage_operations",{description:"Perform operations on Chrome storage API",inputSchema:{action:kt,params:z.record(z.any()).optional().describe("Parameters for the chosen action")}},async({action:e,params:t={}})=>{try{if(!this.shouldRegisterTool(e))return this.formatError(new Error(`Action "${e}" is not supported`));switch(e){case "getStorage":return await this.handleGetStorage(t);case "setStorage":return await this.handleSetStorage(t);case "removeStorage":return await this.handleRemoveStorage(t);case "clearStorage":return await this.handleClearStorage(t);case "getBytesInUse":return await this.handleGetBytesInUse(t);default:return this.formatError(new Error(`Action "${e}" is not supported`))}}catch(r){return this.formatError(r)}}),this.server.registerTool("extension_tool_storage_parameters_description",{description:"Get the parameters for extension_tool_storage_operations tool and the description for the associated action, this tool should be used first before extension_tool_storage_operations",inputSchema:{action:kt}},async({action:e})=>{try{if(!this.shouldRegisterTool(e))return this.formatError(new Error(`Action "${e}" is not supported`));let t=(o,i)=>ir(o,{name:i,$refStrategy:"none"}),r={tool:"extension_tool_storage_operations",action:e,note:"Use the description to double check if the correct action is chosen. Use this JSON Schema for the params field when calling the tool. The top-level tool input is { action, params }."};switch(e){case "getStorage":{let o={params:t(this.getStorageSchema,"GetStorageParams"),description:"Get data from extension storage"};return this.formatJson({...r,...o})}case "setStorage":{let o={params:t(this.setStorageSchema,"SetStorageParams"),description:"Set data in extension storage"};return this.formatJson({...r,...o})}case "removeStorage":{let o={params:t(this.removeStorageSchema,"RemoveStorageParams"),description:"Remove specific keys from extension storage"};return this.formatJson({...r,...o})}case "clearStorage":{let o={params:t(this.clearStorageSchema,"ClearStorageParams"),description:"Clear all data from a storage area"};return this.formatJson({...r,...o})}case "getBytesInUse":{let o={params:t(this.getBytesInUseSchema,"GetBytesInUseParams"),description:"Get the amount of storage space used"};return this.formatJson({...r,...o})}default:return this.formatError(new Error(`Action "${e}" is not supported`))}}catch(t){return this.formatError(t)}});}getAvailableAreas(){let e=[];return chrome.storage.sync&&e.push("sync"),chrome.storage.local&&e.push("local"),chrome.storage.session&&e.push("session"),e}async handleGetStorage(e){let{keys:t,area:r="local"}=this.getStorageSchema.parse(e),o=chrome.storage[r];if(!o||typeof o.get!="function")return this.formatError(new Error(`Storage area '${r}' is not available`));let i=await o.get(t||null),s={area:r,data:i,keyCount:Object.keys(i).length};return this.formatJson(s)}async handleSetStorage(e){let{data:t,area:r="local"}=this.setStorageSchema.parse(e),o=chrome.storage[r];return !o||typeof o.set!="function"?this.formatError(new Error(`Storage area '${r}' is not available`)):(await o.set(t),this.formatSuccess(`Stored ${Object.keys(t).length} key(s) in ${r} storage`,{keys:Object.keys(t)}))}async handleRemoveStorage(e){let{keys:t,area:r="local"}=this.removeStorageSchema.parse(e),o=chrome.storage[r];return !o||typeof o.remove!="function"?this.formatError(new Error(`Storage area '${r}' is not available`)):(await o.remove(t),this.formatSuccess(`Removed ${t.length} key(s) from ${r} storage`,{keys:t}))}async handleClearStorage(e){let{area:t,confirm:r}=this.clearStorageSchema.parse(e);if(!r)return this.formatError(new Error("Clear operation requires confirm=true to prevent accidental data loss"));let o=chrome.storage[t];return !o||typeof o.clear!="function"?this.formatError(new Error(`Storage area '${t}' is not available`)):(await o.clear(),this.formatSuccess(`Cleared all data from ${t} storage`))}async handleGetBytesInUse(e){let{keys:t,area:r="local"}=this.getBytesInUseSchema.parse(e),o=chrome.storage[r];if(!o)return this.formatError(new Error(`Storage area '${r}' is not available`));if(typeof o.getBytesInUse!="function")return this.formatError(new Error(`getBytesInUse is not supported for ${r} storage area`));let i=await o.getBytesInUse(t||null),s=null;return r==="sync"&&chrome.storage.sync.QUOTA_BYTES?s={quotaBytes:chrome.storage.sync.QUOTA_BYTES,quotaBytesPerItem:chrome.storage.sync.QUOTA_BYTES_PER_ITEM,maxItems:chrome.storage.sync.MAX_ITEMS,maxWriteOperationsPerHour:chrome.storage.sync.MAX_WRITE_OPERATIONS_PER_HOUR,maxWriteOperationsPerMinute:chrome.storage.sync.MAX_WRITE_OPERATIONS_PER_MINUTE}:r==="local"&&chrome.storage.local.QUOTA_BYTES&&(s={quotaBytes:chrome.storage.local.QUOTA_BYTES}),this.formatJson({area:r,bytesInUse:i,humanReadable:this.formatBytes(i),quota:s,percentageUsed:s?.quotaBytes?(i/s.quotaBytes*100).toFixed(2)+"%":null})}getStorageSchema=z.object({keys:z.array(z.string()).optional().describe("Specific keys to retrieve (omit for all)"),area:z.enum(this.getAvailableAreas()).optional().describe(`Storage area to use. Available: ${this.getAvailableAreas().join(", ")} (default: local)`)});setStorageSchema=z.object({data:z.record(z.any()).describe("Key-value pairs to store"),area:z.enum(this.getAvailableAreas()).optional().describe(`Storage area to use. Available: ${this.getAvailableAreas().join(", ")} (default: local)`)});removeStorageSchema=z.object({keys:z.array(z.string()).describe("Keys to remove from storage"),area:z.enum(this.getAvailableAreas()).optional().describe(`Storage area to use. Available: ${this.getAvailableAreas().join(", ")} (default: local)`)});clearStorageSchema=z.object({area:z.enum(this.getAvailableAreas()).describe(`Storage area to clear. Available: ${this.getAvailableAreas().join(", ")}`),confirm:z.boolean().describe("Confirmation flag - must be true to clear storage")});getBytesInUseSchema=z.object({keys:z.array(z.string()).optional().describe("Specific keys to check (omit for total)"),area:z.enum(this.getAvailableAreas()).optional().describe(`Storage area to check. Available: ${this.getAvailableAreas().join(", ")} (default: local)`)});formatBytes(e){if(e===0)return "0 Bytes";let t=1024,r=["Bytes","KB","MB","GB"],o=Math.floor(Math.log(e)/Math.log(t));return Number.parseFloat((e/t**o).toFixed(2))+" "+r[o]}};var Dt=class extends m{apiName="System.cpu";constructor(e,t={}){super(e,t);}checkAvailability(){try{return !chrome.system||!chrome.system.cpu?{available:!1,message:"chrome.system.cpu API is not defined",details:'This extension needs the "system.cpu" permission in its manifest.json'}:typeof chrome.system.cpu.getInfo!="function"?{available:!1,message:"chrome.system.cpu.getInfo is not available",details:"The system.cpu API appears to be partially available. Check manifest permissions."}:(chrome.system.cpu.getInfo(e=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"System.cpu API is fully available"})}catch(e){return {available:false,message:"Failed to access chrome.system.cpu API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("getInfo")&&this.registerGetInfo();}registerGetInfo(){this.server.registerTool("extension_tool_get_cpu_info",{description:"Get information about the CPU including number of processors, architecture, model, and features",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.system.cpu.getInfo(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({numOfProcessors:e.numOfProcessors,archName:e.archName,modelName:e.modelName,features:e.features,processors:e.processors.map(t=>({usage:{kernel:t.usage.kernel,user:t.usage.user,idle:t.usage.idle,total:t.usage.total}}))})}catch(e){return this.formatError(e)}});}};var Ot=class extends m{apiName="SystemLog";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.systemLog?typeof chrome.systemLog.add!="function"?{available:!1,message:"chrome.systemLog.add is not available",details:"The systemLog API appears to be partially available. Check manifest permissions and ensure running on ChromeOS."}:{available:!0,message:"SystemLog API is fully available"}:{available:!1,message:"chrome.systemLog API is not defined",details:'This extension needs the "systemLog" permission in its manifest.json and must run on ChromeOS'}}catch(e){return {available:false,message:"Failed to access chrome.systemLog API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("addLog")&&this.registerAddLog();}registerAddLog(){this.server.registerTool("extension_tool_add_log",{description:"Add a new log record to the Chrome system logs",inputSchema:{message:z.string().describe("The log message to record in the system logs")}},async({message:e})=>{try{let t={message:e};return await new Promise((r,o)=>{chrome.systemLog.add(t,()=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r();});}),this.formatSuccess("Log record added successfully",{message:e,timestamp:new Date().toISOString()})}catch(t){return this.formatError(t)}});}};var Ut=class extends m{apiName="System.memory";constructor(e,t={}){super(e,t);}checkAvailability(){try{return !chrome.system||!chrome.system.memory?{available:!1,message:"chrome.system.memory API is not defined",details:'This extension needs the "system.memory" permission in its manifest.json'}:typeof chrome.system.memory.getInfo!="function"?{available:!1,message:"chrome.system.memory.getInfo is not available",details:"The system.memory API appears to be partially available. Check manifest permissions."}:(chrome.system.memory.getInfo(e=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"System.memory API is fully available"})}catch(e){return {available:false,message:"Failed to access chrome.system.memory API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("getInfo")&&this.registerGetInfo();}registerGetInfo(){this.server.registerTool("extension_tool_get_memory_info",{description:"Get information about the system memory",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.system.memory.getInfo(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({capacity:e.capacity,capacityGB:Math.round(e.capacity/(1024*1024*1024)*100)/100,availableCapacity:e.availableCapacity,availableCapacityGB:Math.round(e.availableCapacity/(1024*1024*1024)*100)/100,usedCapacity:e.capacity-e.availableCapacity,usedCapacityGB:Math.round((e.capacity-e.availableCapacity)/(1024*1024*1024)*100)/100,usagePercentage:Math.round((e.capacity-e.availableCapacity)/e.capacity*1e4)/100})}catch(e){return this.formatError(e)}});}};var Mt=class extends m{apiName="System.storage";constructor(e,t={}){super(e,t);}checkAvailability(){try{return !chrome.system||!chrome.system.storage?{available:!1,message:"chrome.system.storage API is not defined",details:'This extension needs the "system.storage" permission in its manifest.json'}:typeof chrome.system.storage.getInfo!="function"?{available:!1,message:"chrome.system.storage.getInfo is not available",details:"The system.storage API appears to be partially available. Check manifest permissions."}:(chrome.system.storage.getInfo(e=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"System.storage API is fully available"})}catch(e){return {available:false,message:"Failed to access chrome.system.storage API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("getInfo")&&this.registerGetInfo(),this.shouldRegisterTool("ejectDevice")&&this.registerEjectDevice(),this.shouldRegisterTool("getAvailableCapacity")&&this.registerGetAvailableCapacity();}registerGetInfo(){this.server.registerTool("extension_tool_get_storage_info",{description:"Get information about all attached storage devices",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.system.storage.getInfo(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({count:e.length,devices:e.map(t=>({id:t.id,name:t.name,type:t.type,capacity:t.capacity,capacityFormatted:this.formatBytes(t.capacity)}))})}catch(e){return this.formatError(e)}});}registerEjectDevice(){this.server.registerTool("extension_tool_eject_storage_device",{description:"Eject a removable storage device",inputSchema:{id:z.string().describe("The transient device ID from getInfo")}},async({id:e})=>{try{let t=await new Promise((i,s)=>{chrome.system.storage.ejectDevice(e,n=>{chrome.runtime.lastError?s(new Error(chrome.runtime.lastError.message)):i(n);});}),r=t==="success",o=this.getEjectResultMessage(t);return r?this.formatSuccess("Device ejected successfully",{deviceId:e,result:t,message:o}):this.formatError(`Failed to eject device: ${o}`)}catch(t){return this.formatError(t)}});}registerGetAvailableCapacity(){this.server.registerTool("extension_tool_get_available_capacity",{description:"Get the available capacity of a specified storage device",inputSchema:{id:z.string().describe("The transient device ID from getInfo")}},async({id:e})=>{try{let t=await new Promise((r,o)=>{chrome.system.storage.getAvailableCapacity(e,i=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r(i);});});return this.formatJson({deviceId:e,availableCapacity:t.availableCapacity,availableCapacityFormatted:this.formatBytes(t.availableCapacity)})}catch(t){return this.formatError(t)}});}getEjectResultMessage(e){switch(e){case "success":return "Device ejected successfully";case "in_use":return "Device is currently in use and cannot be ejected";case "no_such_device":return "No such device found";case "failure":return "Failed to eject device due to unknown error";default:return `Unknown result: ${e}`}}formatBytes(e){if(e===0)return "0 Bytes";let t=1024,r=["Bytes","KB","MB","GB","TB","PB"],o=Math.floor(Math.log(e)/Math.log(t));return Number.parseFloat((e/t**o).toFixed(2))+" "+r[o]}};var Nt=class extends m{apiName="TabCapture";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.tabCapture?typeof chrome.tabCapture.getCapturedTabs!="function"?{available:!1,message:"chrome.tabCapture.getCapturedTabs is not available",details:"The tabCapture API appears to be partially available. Check manifest permissions."}:(chrome.tabCapture.getCapturedTabs(e=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"TabCapture API is fully available"}):{available:!1,message:"chrome.tabCapture API is not defined",details:'This extension needs the "tabCapture" permission in its manifest.json'}}catch(e){return {available:false,message:"Failed to access chrome.tabCapture API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("capture")&&this.registerCapture(),this.shouldRegisterTool("getCapturedTabs")&&this.registerGetCapturedTabs(),this.shouldRegisterTool("getMediaStreamId")&&this.registerGetMediaStreamId();}registerCapture(){this.server.registerTool("extension_tool_capture_tab",{description:"Captures the visible area of the currently active tab. Can only be started on the currently active tab after the extension has been invoked.",inputSchema:{audio:z.boolean().optional().describe("Whether to capture audio from the tab"),video:z.boolean().optional().describe("Whether to capture video from the tab"),audioConstraints:z.object({mandatory:z.record(z.any()).optional(),optional:z.record(z.any()).optional()}).optional().describe("Audio constraints for the media stream"),videoConstraints:z.object({mandatory:z.record(z.any()).optional(),optional:z.record(z.any()).optional()}).optional().describe("Video constraints for the media stream")}},async({audio:e,video:t,audioConstraints:r,videoConstraints:o})=>{try{let i={};e!==void 0&&(i.audio=e),t!==void 0&&(i.video=t),r!==void 0&&(i.audioConstraints=r),o!==void 0&&(i.videoConstraints=o);let s=await new Promise((c,u)=>{chrome.tabCapture.capture(i,d=>{chrome.runtime.lastError?u(new Error(chrome.runtime.lastError.message)):d?c(d):u(new Error("Failed to capture tab - no stream returned"));});}),n=s.getAudioTracks(),a=s.getVideoTracks();return this.formatSuccess("Tab capture started successfully",{streamId:s.id,audioTracks:n.length,videoTracks:a.length,audioTrackLabels:n.map(c=>c.label),videoTrackLabels:a.map(c=>c.label)})}catch(i){return this.formatError(i)}});}registerGetCapturedTabs(){this.server.registerTool("extension_tool_get_captured_tabs",{description:"Returns a list of tabs that have requested capture or are being captured",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.tabCapture.getCapturedTabs(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({count:e.length,capturedTabs:e.map(t=>({tabId:t.tabId,status:t.status,fullscreen:t.fullscreen}))})}catch(e){return this.formatError(e)}});}registerGetMediaStreamId(){this.server.registerTool("extension_tool_get_media_stream_id",{description:"Creates a stream ID to capture the target tab. Returns a media stream ID instead of a media stream.",inputSchema:{targetTabId:z.number().optional().describe("Optional tab id of the tab which will be captured. If not specified then the current active tab will be selected."),consumerTabId:z.number().optional().describe("Optional tab id of the tab which will later invoke getUserMedia() to consume the stream. If not specified then the resulting stream can be used only by the calling extension.")}},async({targetTabId:e,consumerTabId:t})=>{try{let r={};e!==void 0&&(r.targetTabId=e),t!==void 0&&(r.consumerTabId=t);let o=await new Promise((i,s)=>{chrome.tabCapture.getMediaStreamId(r,n=>{chrome.runtime.lastError?s(new Error(chrome.runtime.lastError.message)):n?i(n):s(new Error("Failed to get media stream ID"));});});return this.formatSuccess("Media stream ID created successfully",{streamId:o,targetTabId:e||"current active tab",consumerTabId:t||"calling extension only",usage:'Use this ID with navigator.mediaDevices.getUserMedia() with chromeMediaSource: "tab" and chromeMediaSourceId: streamId'})}catch(r){return this.formatError(r)}});}};var hr=["get","query","update","move"],qt=z.enum(hr),Gt=class extends m{apiName="TabGroups";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.tabGroups?typeof chrome.tabGroups.query!="function"?{available:!1,message:"chrome.tabGroups.query is not available",details:"The tabGroups API appears to be partially available. Check manifest permissions."}:(chrome.tabGroups.query({},()=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"TabGroups API is fully available"}):{available:!1,message:"chrome.tabGroups API is not defined",details:'This extension needs the "tabGroups" permission in its manifest.json and requires Chrome 89+ with Manifest V3'}}catch(e){return {available:false,message:"Failed to access chrome.tabGroups API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.server.registerTool("extension_tool_tab_group_operations",{description:"Perform operations on tab groups using Chrome TabGroups API",inputSchema:{action:qt,params:z.record(z.any()).optional().describe("Parameters for the chosen action")}},async({action:e,params:t={}})=>{try{if(!this.shouldRegisterTool(e))return this.formatError(new Error(`Action "${e}" is not supported`));switch(e){case "get":return await this.handleGetTabGroup(t);case "query":return await this.handleQueryTabGroups(t);case "update":return await this.handleUpdateTabGroup(t);case "move":return await this.handleMoveTabGroup(t);default:return this.formatError(new Error(`Action "${e}" is not supported`))}}catch(r){return this.formatError(r)}}),this.server.registerTool("extension_tool_tab_group_parameters_description",{description:"Get the parameters for extension_tool_tab_group_operations tool and the description for the associated action, this tool should be used first before extension_tool_tab_group_operations",inputSchema:{action:qt}},async({action:e})=>{try{if(!this.shouldRegisterTool(e))return this.formatError(new Error(`Action "${e}" is not supported`));let t=(o,i)=>ir(o,{name:i,$refStrategy:"none"}),r={tool:"extension_tool_tab_group_operations",action:e,note:"Use the description to double check if the correct action is chosen. Use this JSON Schema for the params field when calling the tool. The top-level tool input is { action, params }."};switch(e){case "get":{let o={params:t(this.getSchema,"GetTabGroupParams"),description:"Retrieve a tab group by its ID"};return this.formatJson({...r,...o})}case "query":{let o={params:t(this.querySchema,"QueryTabGroupsParams"),description:"Search for tab groups that match specified criteria"};return this.formatJson({...r,...o})}case "update":{let o={params:t(this.updateSchema,"UpdateTabGroupParams"),description:"Modify properties of a tab group"};return this.formatJson({...r,...o})}case "move":{let o={params:t(this.moveSchema,"MoveTabGroupParams"),description:"Move a tab group within its window or to a new window"};return this.formatJson({...r,...o})}default:return this.formatError(new Error(`Action "${e}" is not supported`))}}catch(t){return this.formatError(t)}});}async handleGetTabGroup(e){let{groupId:t}=this.getSchema.parse(e),r=await new Promise((o,i)=>{chrome.tabGroups.get(t,s=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o(s);});});return this.formatJson({id:r.id,title:r.title,color:r.color,collapsed:r.collapsed,shared:r.shared,windowId:r.windowId})}async handleQueryTabGroups(e){let{collapsed:t,color:r,shared:o,title:i,windowId:s}=this.querySchema.parse(e),n={};t!==void 0&&(n.collapsed=t),r!==void 0&&(n.color=r),o!==void 0&&(n.shared=o),i!==void 0&&(n.title=i),s!==void 0&&(n.windowId=s===-2?chrome.windows.WINDOW_ID_CURRENT:s);let a=await new Promise((c,u)=>{chrome.tabGroups.query(n,d=>{chrome.runtime.lastError?u(new Error(chrome.runtime.lastError.message)):c(d);});});return this.formatJson({count:a.length,groups:a.map(c=>({id:c.id,title:c.title,color:c.color,collapsed:c.collapsed,shared:c.shared,windowId:c.windowId}))})}async handleUpdateTabGroup(e){let{groupId:t,collapsed:r,color:o,title:i}=this.updateSchema.parse(e),s={};r!==void 0&&(s.collapsed=r),o!==void 0&&(s.color=o),i!==void 0&&(s.title=i);let n=await new Promise((a,c)=>{chrome.tabGroups.update(t,s,u=>{chrome.runtime.lastError?c(new Error(chrome.runtime.lastError.message)):a(u);});});return n?this.formatSuccess("Tab group updated successfully",{id:n.id,title:n.title,color:n.color,collapsed:n.collapsed,shared:n.shared,windowId:n.windowId}):this.formatError("Failed to update tab group")}async handleMoveTabGroup(e){let{groupId:t,index:r,windowId:o}=this.moveSchema.parse(e),i={index:r};o!==void 0&&(i.windowId=o);let s=await new Promise((n,a)=>{chrome.tabGroups.move(t,i,c=>{chrome.runtime.lastError?a(new Error(chrome.runtime.lastError.message)):n(c);});});return s?this.formatSuccess("Tab group moved successfully",{id:s.id,title:s.title,color:s.color,collapsed:s.collapsed,shared:s.shared,windowId:s.windowId,newIndex:r}):this.formatError("Failed to move tab group")}getSchema=z.object({groupId:z.number().describe("The ID of the tab group to retrieve")});querySchema=z.object({collapsed:z.boolean().optional().describe("Whether the groups are collapsed"),color:z.enum(["grey","blue","red","yellow","green","pink","purple","cyan","orange"]).optional().describe("The color of the groups"),shared:z.boolean().optional().describe("Whether the group is shared (Chrome 137+)"),title:z.string().optional().describe("Pattern to match group titles against"),windowId:z.number().optional().describe("The ID of the parent window, or use -2 for the current window")});updateSchema=z.object({groupId:z.number().describe("The ID of the group to modify"),collapsed:z.boolean().optional().describe("Whether the group should be collapsed"),color:z.enum(["grey","blue","red","yellow","green","pink","purple","cyan","orange"]).optional().describe("The color of the group"),title:z.string().optional().describe("The title of the group")});moveSchema=z.object({groupId:z.number().describe("The ID of the group to move"),index:z.number().describe("The position to move the group to. Use -1 to place at the end"),windowId:z.number().optional().describe("The window to move the group to. Defaults to current window")})};var pr=["listActiveTabs","createTab","updateTab","closeTabs","getAllTabs","navigateHistory","reloadTab","captureVisibleTab","detectLanguage","discardTab","duplicateTab","getTab","getZoom","getZoomSettings","setZoom","setZoomSettings","groupTabs","ungroupTabs","highlightTabs","moveTabs","sendMessage"],Ft=z.enum(pr),jt=class extends m{apiName="Tabs";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.tabs?typeof chrome.tabs.query!="function"?{available:!1,message:"chrome.tabs.query is not available",details:"The tabs API appears to be partially available. Check manifest permissions."}:{available:!0,message:"Tabs API is fully available"}:{available:!1,message:"chrome.tabs API is not defined",details:'This extension may not have the "tabs" permission in its manifest'}}catch(e){return {available:false,message:"Failed to access chrome.tabs API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.server.registerTool("extension_tool_tab_operations",{description:"Perform various tab operations using the Chrome Tabs API",inputSchema:{action:Ft,params:z.record(z.any()).optional().describe("Parameters for the chosen action")}},async({action:e,params:t={}})=>{try{if(!this.shouldRegisterTool(e))return this.formatError(new Error(`Action "${e}" is not supported`));switch(e){case "listActiveTabs":return await this.handleListActiveTabs();case "createTab":return await this.handleCreateTab(t);case "updateTab":return await this.handleUpdateTab(t);case "closeTabs":return await this.handleCloseTabs(t);case "getAllTabs":return await this.handleGetAllTabs(t);case "navigateHistory":return await this.handleNavigateHistory(t);case "reloadTab":return await this.handleReloadTab(t);case "captureVisibleTab":return await this.handleCaptureVisibleTab(t);case "detectLanguage":return await this.handleDetectLanguage(t);case "discardTab":return await this.handleDiscardTab(t);case "duplicateTab":return await this.handleDuplicateTab(t);case "getTab":return await this.handleGetTab(t);case "getZoom":return await this.handleGetZoom(t);case "getZoomSettings":return await this.handleGetZoomSettings(t);case "setZoom":return await this.handleSetZoom(t);case "setZoomSettings":return await this.handleSetZoomSettings(t);case "groupTabs":return await this.handleGroupTabs(t);case "ungroupTabs":return await this.handleUngroupTabs(t);case "highlightTabs":return await this.handleHighlightTabs(t);case "moveTabs":return await this.handleMoveTabs(t);case "sendMessage":return await this.handleSendMessage(t);default:return this.formatError(new Error(`Action "${e}" is not supported`))}}catch(r){return this.formatError(r)}}),this.server.registerTool("extension_tool_tab_parameters_description",{description:"Get the parameters for extension_tool_tab_operations tool and the description for the associated action, this tool should be used first before extension_tool_tab_operations",inputSchema:{action:Ft}},async({action:e})=>{try{if(!this.shouldRegisterTool(e))return this.formatError(new Error(`Action "${e}" is not supported`));let t=(o,i)=>ir(o,{name:i,$refStrategy:"none"}),r={tool:"extension_tool_tab_operations",action:e,note:"Use the description to double check if the correct action is chosen. Use this JSON Schema for the params field when calling the tool. The top-level tool input is { action, params }."};switch(e){case "listActiveTabs":{let o={params:t(this.listActiveTabsSchema,"ListActiveTabsParams"),description:"Lists all tabs grouped by domain"};return this.formatJson({...r,...o})}case "createTab":{let o={params:t(this.createTabSchema,"CreateTabParams"),description:"Create a new browser tab"};return this.formatJson({...r,...o})}case "updateTab":{let o={params:t(this.updateTabSchema,"UpdateTabParams"),description:"Update properties of an existing tab. If no tabId is specified, operates on the currently active tab"};return this.formatJson({...r,...o})}case "closeTabs":{let o={params:t(this.closeTabsSchema,"CloseTabsParams"),description:"Close one or more tabs"};return this.formatJson({...r,...o})}case "getAllTabs":{let o={params:t(this.getAllTabsSchema,"GetAllTabsParams"),description:"Get information about all open tabs"};return this.formatJson({...r,...o})}case "navigateHistory":{let o={params:t(this.navigateHistorySchema,"NavigateHistoryParams"),description:"Navigate forward or backward in a tab's history. If no tabId is specified, operates on the currently active tab"};return this.formatJson({...r,...o})}case "reloadTab":{let o={params:t(this.reloadTabSchema,"ReloadTabParams"),description:"Reload a tab. If no tabId is specified, operates on the currently active tab"};return this.formatJson({...r,...o})}case "captureVisibleTab":{let o={params:t(this.captureVisibleTabSchema,"CaptureVisibleTabParams"),description:"Take a screenshot of the visible area of the currently active tab in a window. Once the screenshot is captured"};return this.formatJson({...r,...o})}case "detectLanguage":{let o={params:t(this.detectLanguageSchema,"DetectLanguageParams"),description:"Detect the primary language of the content in a tab"};return this.formatJson({...r,...o})}case "discardTab":{let o={params:t(this.discardTabSchema,"DiscardTabParams"),description:"Discards a tab from memory. Discarded tabs are still visible but need to reload when activated"};return this.formatJson({...r,...o})}case "duplicateTab":{let o={params:t(this.duplicateTabSchema,"DuplicateTabParams"),description:"Duplicate a tab"};return this.formatJson({...r,...o})}case "getTab":{let o={params:t(this.getTabSchema,"GetTabParams"),description:"Retrieves details about a specific tab"};return this.formatJson({...r,...o})}case "getZoom":{let o={params:t(this.getZoomSchema,"GetZoomParams"),description:"Retrieves the current zoom level of a tab"};return this.formatJson({...r,...o})}case "getZoomSettings":{let o={params:t(this.getZoomSettingsSchema,"GetZoomSettingsParams"),description:"Gets the current zoom settings of a tab"};return this.formatJson({...r,...o})}case "setZoom":{let o={params:t(this.setZoomSchema,"SetZoomParams"),description:"Sets the zoom factor of a tab"};return this.formatJson({...r,...o})}case "setZoomSettings":{let o={params:t(this.setZoomSettingsSchema,"SetZoomSettingsParams"),description:"Sets zoom settings for a tab (how zoom changes are handled)"};return this.formatJson({...r,...o})}case "groupTabs":{let o={params:t(this.groupTabsSchema,"GroupTabsParams"),description:"Groups one or more tabs together"};return this.formatJson({...r,...o})}case "ungroupTabs":{let o={params:t(this.ungroupTabsSchema,"UngroupTabsParams"),description:"Removes tabs from their groups"};return this.formatJson({...r,...o})}case "highlightTabs":{let o={params:t(this.highlightTabsSchema,"HighlightTabsParams"),description:"Highlights the given tabs and focuses on the first one"};return this.formatJson({...r,...o})}case "moveTabs":{let o={params:t(this.moveTabsSchema,"MoveTabsParams"),description:"Moves tabs to a new position within their window or to another window"};return this.formatJson({...r,...o})}case "sendMessage":{let o={params:t(this.sendMessageSchema,"SendMessageParams"),description:"Sends a message to content scripts in a specific tab"};return this.formatJson({...r,...o})}default:return this.formatError(new Error(`Action "${e}" is not supported`))}}catch(t){return this.formatError(t)}});}async handleListActiveTabs(){let r=(await chrome.tabs.query({})).map(o=>{let i="unknown";if(o.url)try{i=new URL(o.url).hostname;}catch{}return {tabId:o.id,domain:i,url:o.url,title:o.title,isActive:o.active,windowId:o.windowId,index:o.index,pinned:o.pinned,audible:o.audible,mutedInfo:o.mutedInfo,status:o.status}}).reduce((o,i)=>{let s=i.domain||"unknown";return o[s]||(o[s]=[]),o[s].push(i),o},{});for(let o of Object.values(r))o.sort((i,s)=>i.windowId!==s.windowId?(i.windowId||0)-(s.windowId||0):(i.index||0)-(s.index||0));return this.formatJson(r)}async handleCreateTab(e){let{url:t,active:r,pinned:o}=this.createTabSchema.parse(e),i=await chrome.tabs.create({url:t,active:r,pinned:o});return this.formatSuccess(`Created tab ${i.id} with URL: ${i.url||"about:blank"}`)}async handleUpdateTab(e){let{tabId:t,url:r,active:o,pinned:i,muted:s}=this.updateTabSchema.parse(e);if(t===void 0){let[c]=await chrome.tabs.query({active:true,currentWindow:true});if(!c||!c.id)return this.formatError(new Error("No active tab found"));t=c.id;}let n={};r!==void 0&&(n.url=r),o!==void 0&&(n.active=o),i!==void 0&&(n.pinned=i),s!==void 0&&(n.muted=s);let a=await chrome.tabs.update(t,n);return a?this.formatSuccess(`Updated tab ${a.id}`,n):this.formatError(new Error("Tab does not exist"))}async handleCloseTabs(e){let{tabIds:t}=this.closeTabsSchema.parse(e);return await chrome.tabs.remove(t),this.formatSuccess(`Closed ${t.length} tab(s): ${t.join(", ")}`)}async handleGetAllTabs(e){let{currentWindow:t}=this.getAllTabsSchema.parse(e),o=(await chrome.tabs.query(t?{currentWindow:true}:{})).map(i=>({id:i.id,title:i.title,url:i.url,active:i.active,pinned:i.pinned,windowId:i.windowId,index:i.index}));return this.formatJson(o)}async handleNavigateHistory(e){if(typeof chrome.tabs.goBack!="function"||typeof chrome.tabs.goForward!="function")return this.formatError(new Error("\u2717 Navigation methods not available - Chrome 72+ required"));let{tabId:t,direction:r}=this.navigateHistorySchema.parse(e);if(t===void 0){let[o]=await chrome.tabs.query({active:true,currentWindow:true});if(!o||!o.id)return this.formatError(new Error("No active tab found"));t=o.id;}return r==="back"?await chrome.tabs.goBack(t):await chrome.tabs.goForward(t),this.formatSuccess(`Navigated ${r} in tab ${t}`)}async handleReloadTab(e){let{tabId:t,bypassCache:r}=this.reloadTabSchema.parse(e);if(t===void 0){let[o]=await chrome.tabs.query({active:true,currentWindow:true});if(!o||!o.id)return this.formatError(new Error("No active tab found"));t=o.id;}return await chrome.tabs.reload(t,{bypassCache:r}),this.formatSuccess(`Reloaded tab ${t}${r?" (bypassed cache)":""}`)}async handleCaptureVisibleTab(e){if(typeof chrome.tabs.captureVisibleTab!="function")return this.formatError(new Error('\u2717 Screenshot capture not available - requires "activeTab" or "<all_urls>" permission'));let{windowId:t}=this.captureVisibleTabSchema.parse(e),r=t?await chrome.tabs.captureVisibleTab(t,{}):await chrome.tabs.captureVisibleTab();return chrome.tabs.create({url:r}),this.formatSuccess(`Screenshot captured (data URL length: ${r.length} characters)`)}async handleDetectLanguage(e){let{tabId:t}=this.detectLanguageSchema.parse(e),r=await chrome.tabs.detectLanguage(t);return this.formatSuccess(`Tab language detected: ${r}`,{language:r})}async handleDiscardTab(e){let{tabId:t}=this.discardTabSchema.parse(e),r=await chrome.tabs.discard(t);return r?this.formatSuccess(`Discarded tab ${r.id}`,{tab:r}):this.formatError(new Error("Failed to discard tab"))}async handleDuplicateTab(e){let{tabId:t}=this.duplicateTabSchema.parse(e),r=await chrome.tabs.duplicate(t);return r?this.formatSuccess(`Duplicated tab ${r.id}`,{tab:r}):this.formatError(new Error("Failed to duplicate tab"))}async handleGetTab(e){let{tabId:t}=this.getTabSchema.parse(e),r=await chrome.tabs.get(t);return this.formatJson(r)}async handleGetZoom(e){let{tabId:t}=this.getZoomSchema.parse(e),r=await chrome.tabs.getZoom(t);return this.formatSuccess(`Zoom factor: ${r}`,{zoomFactor:r})}async handleGetZoomSettings(e){let{tabId:t}=this.getZoomSettingsSchema.parse(e),r=await chrome.tabs.getZoomSettings(t);return this.formatJson(r)}async handleSetZoom(e){let{tabId:t,zoomFactor:r}=this.setZoomSchema.parse(e);return await chrome.tabs.setZoom(t,r),this.formatSuccess(`Set zoom factor to ${r===0?"default":r}`)}async handleSetZoomSettings(e){let{tabId:t,mode:r,scope:o}=this.setZoomSettingsSchema.parse(e),i={};return r&&(i.mode=r),o&&(i.scope=o),await chrome.tabs.setZoomSettings(t,i),this.formatSuccess("Updated zoom settings",i)}async handleGroupTabs(e){let{tabIds:t,groupId:r,createProperties:o}=this.groupTabsSchema.parse(e),i={tabIds:t.length===1?t[0]:t};r!==void 0?i.groupId=r:o&&(i.createProperties=o);let s=await chrome.tabs.group(i);return this.formatSuccess(`Grouped ${t.length} tabs into group ${s}`,{groupId:s})}async handleUngroupTabs(e){let{tabIds:t}=this.ungroupTabsSchema.parse(e);return await chrome.tabs.ungroup(t.length===1?t[0]:t),this.formatSuccess(`Ungrouped ${t.length} tab(s)`)}async handleHighlightTabs(e){let{tabs:t,windowId:r}=this.highlightTabsSchema.parse(e),o={tabs:t.length===1?t[0]:t};r!==void 0&&(o.windowId=r);let i=await chrome.tabs.highlight(o);return this.formatSuccess(`Highlighted ${t.length} tab(s)`,{window:i})}async handleMoveTabs(e){let{tabIds:t,index:r,windowId:o}=this.moveTabsSchema.parse(e),i={index:r};o!==void 0&&(i.windowId=o);let s=chrome.tabs.move(t.length===1?t[0]:t,i);return this.formatSuccess(`Moved ${t.length} tab(s) to index ${r}`,{tabs:s})}async handleSendMessage(e){let{tabId:t,message:r,frameId:o,documentId:i}=this.sendMessageSchema.parse(e),s={};o!==void 0&&(s.frameId=o),i!==void 0&&(s.documentId=i);let n=await chrome.tabs.sendMessage(t,r,s);return this.formatSuccess("Message sent successfully",{response:n})}listActiveTabsSchema=z.object({});createTabSchema=z.object({url:z.string().optional().describe("URL to open in the new tab. Fully-qualified URLs must include a scheme (i.e., 'http://www.google.com', not 'www.google.com'). Relative URLs are relative to the current page within the extension. Defaults to the New Tab Page."),active:z.boolean().optional().describe("Whether the tab should be active"),pinned:z.boolean().optional().describe("Whether the tab should be pinned")});updateTabSchema=z.object({tabId:z.number().optional().describe("ID of the tab to update (defaults to active tab)"),url:z.string().optional().describe("New URL for the tab"),active:z.boolean().optional().describe("Whether to make the tab active"),pinned:z.boolean().optional().describe("Whether to pin/unpin the tab"),muted:z.boolean().optional().describe("Whether to mute/unmute the tab")});closeTabsSchema=z.object({tabIds:z.array(z.number()).describe("Array of tab IDs to close")});getAllTabsSchema=z.object({currentWindow:z.boolean().optional().describe("Only get tabs from current window")});navigateHistorySchema=z.object({tabId:z.number().optional().describe("Tab ID to navigate (defaults to active tab)"),direction:z.enum(["back","forward"]).describe("Navigation direction")});reloadTabSchema=z.object({tabId:z.number().optional().describe("Tab ID to reload (defaults to active tab)"),bypassCache:z.boolean().optional().describe("Bypass the cache when reloading")});captureVisibleTabSchema=z.object({windowId:z.number().optional().describe("Window ID (defaults to current window)")});detectLanguageSchema=z.object({tabId:z.number().optional().describe("Tab ID (defaults to active tab)")});discardTabSchema=z.object({tabId:z.number().optional().describe("Tab ID to discard (if omitted, browser picks least important tab)")});duplicateTabSchema=z.object({tabId:z.number().describe("ID of the tab to duplicate")});getTabSchema=z.object({tabId:z.number().describe("Tab ID")});getZoomSchema=z.object({tabId:z.number().optional().describe("Tab ID (defaults to active tab)")});getZoomSettingsSchema=z.object({tabId:z.number().optional().describe("Tab ID (defaults to active tab)")});setZoomSchema=z.object({tabId:z.number().optional().describe("Tab ID (defaults to active tab)"),zoomFactor:z.number().describe("New zoom factor (0 resets to default, >0 sets specific zoom)")});setZoomSettingsSchema=z.object({tabId:z.number().optional().describe("Tab ID (defaults to active tab)"),mode:z.enum(["automatic","manual","disabled"]).optional().describe("How zoom changes are handled"),scope:z.enum(["per-origin","per-tab"]).optional().describe("Whether zoom persists across pages")});groupTabsSchema=z.object({tabIds:z.array(z.number()).min(1).describe("Tab IDs to group"),groupId:z.number().optional().describe("Existing group ID to add tabs to"),createProperties:z.object({windowId:z.number().optional().describe("Window ID for new group")}).optional().describe("Properties for creating a new group")});ungroupTabsSchema=z.object({tabIds:z.array(z.number()).min(1).describe("Tab IDs to ungroup")});highlightTabsSchema=z.object({tabs:z.array(z.number()).min(1).describe("Tab indices to highlight"),windowId:z.number().optional().describe("Window ID containing the tabs")});moveTabsSchema=z.object({tabIds:z.array(z.number()).min(1).describe("Tab IDs to move"),index:z.number().describe("Position to move tabs to (-1 for end)"),windowId:z.number().optional().describe("Target window ID")});sendMessageSchema=z.object({tabId:z.number().describe("Tab ID to send message to"),message:z.any().describe("Message to send (must be JSON-serializable)"),frameId:z.number().optional().describe("Specific frame ID to target"),documentId:z.string().optional().describe("Specific document ID to target")})};var Bt=class extends m{apiName="TopSites";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.topSites?typeof chrome.topSites.get!="function"?{available:!1,message:"chrome.topSites.get is not available",details:"The topSites API appears to be partially available. Check manifest permissions."}:(chrome.topSites.get(e=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"TopSites API is fully available"}):{available:!1,message:"chrome.topSites API is not defined",details:'This extension needs the "topSites" permission in its manifest.json'}}catch(e){return {available:false,message:"Failed to access chrome.topSites API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("getTopSites")&&this.registerGetTopSites();}registerGetTopSites(){this.server.registerTool("extension_tool_get_top_sites",{description:"Get a list of top sites (most visited sites) that are displayed on the new tab page",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.topSites.get(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({count:e.length,topSites:e.map(t=>({title:t.title,url:t.url}))})}catch(e){return this.formatError(e)}});}};var Wt=class extends m{apiName="Tts";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.tts?typeof chrome.tts.getVoices!="function"?{available:!1,message:"chrome.tts.getVoices is not available",details:"The tts API appears to be partially available. Check manifest permissions."}:(chrome.tts.getVoices(e=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"TTS API is fully available"}):{available:!1,message:"chrome.tts API is not defined",details:'This extension needs the "tts" permission in its manifest.json'}}catch(e){return {available:false,message:"Failed to access chrome.tts API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("speak")&&this.registerSpeak(),this.shouldRegisterTool("stop")&&this.registerStop(),this.shouldRegisterTool("pause")&&this.registerPause(),this.shouldRegisterTool("resume")&&this.registerResume(),this.shouldRegisterTool("isSpeaking")&&this.registerIsSpeaking(),this.shouldRegisterTool("getVoices")&&this.registerGetVoices();}registerSpeak(){this.server.registerTool("extension_tool_speak_text",{description:"Speaks text using text-to-speech synthesis",inputSchema:{utterance:z.string().max(32768).describe("The text to speak, either plain text or a complete SSML document. Maximum length is 32,768 characters"),lang:z.string().optional().describe('The language to be used for synthesis, in the form language-region. Examples: "en", "en-US", "en-GB", "zh-CN"'),voiceName:z.string().optional().describe("The name of the voice to use for synthesis. If empty, uses any available voice"),rate:z.number().min(.1).max(10).optional().describe("Speaking rate relative to the default rate. 1.0 is default, 2.0 is twice as fast, 0.5 is half as fast"),pitch:z.number().min(0).max(2).optional().describe("Speaking pitch between 0 and 2 inclusive, with 0 being lowest and 2 being highest. 1.0 is default"),volume:z.number().min(0).max(1).optional().describe("Speaking volume between 0 and 1 inclusive, with 0 being lowest and 1 being highest. Default is 1.0"),enqueue:z.boolean().optional().describe("If true, enqueues this utterance if TTS is already in progress. If false (default), interrupts current speech"),extensionId:z.string().optional().describe("The extension ID of the speech engine to use, if known"),requiredEventTypes:z.array(z.string()).optional().describe("The TTS event types the voice must support"),desiredEventTypes:z.array(z.string()).optional().describe("The TTS event types that you are interested in listening to")}},async({utterance:e,lang:t,voiceName:r,rate:o,pitch:i,volume:s,enqueue:n,extensionId:a,requiredEventTypes:c,desiredEventTypes:u})=>{try{let d={};t!==void 0&&(d.lang=t),r!==void 0&&(d.voiceName=r),o!==void 0&&(d.rate=o),i!==void 0&&(d.pitch=i),s!==void 0&&(d.volume=s),n!==void 0&&(d.enqueue=n),a!==void 0&&(d.extensionId=a),c!==void 0&&(d.requiredEventTypes=c),u!==void 0&&(d.desiredEventTypes=u);let v=[];return d.onEvent=S=>{v.push(S);},await new Promise((S,P)=>{chrome.tts.speak(e,d,()=>{chrome.runtime.lastError?P(new Error(chrome.runtime.lastError.message)):S();});}),this.formatSuccess("Text-to-speech started successfully",{utterance:e.substring(0,100)+(e.length>100?"...":""),options:{lang:d.lang,voiceName:d.voiceName,rate:d.rate,pitch:d.pitch,volume:d.volume,enqueue:d.enqueue}})}catch(d){return this.formatError(d)}});}registerStop(){this.server.registerTool("extension_tool_stop_speech",{description:"Stops any current speech and flushes the queue of pending utterances",inputSchema:{}},async()=>{try{return chrome.tts.stop(),this.formatSuccess("Speech stopped and queue cleared")}catch(e){return this.formatError(e)}});}registerPause(){this.server.registerTool("extension_tool_pause_speech",{description:"Pauses speech synthesis, potentially in the middle of an utterance",inputSchema:{}},async()=>{try{return chrome.tts.pause(),this.formatSuccess("Speech paused")}catch(e){return this.formatError(e)}});}registerResume(){this.server.registerTool("extension_tool_resume_speech",{description:"If speech was paused, resumes speaking where it left off",inputSchema:{}},async()=>{try{return chrome.tts.resume(),this.formatSuccess("Speech resumed")}catch(e){return this.formatError(e)}});}registerIsSpeaking(){this.server.registerTool("extension_tool_is_speaking",{description:"Checks whether the engine is currently speaking",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.tts.isSpeaking(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({speaking:e,status:e?"TTS engine is currently speaking":"TTS engine is not speaking"})}catch(e){return this.formatError(e)}});}registerGetVoices(){this.server.registerTool("extension_tool_get_voices",{description:"Gets an array of all available voices for speech synthesis",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.tts.getVoices(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({count:e.length,voices:e.map(t=>({voiceName:t.voiceName,lang:t.lang,extensionId:t.extensionId,eventTypes:t.eventTypes,remote:t.remote}))})}catch(e){return this.formatError(e)}});}};var Jt=class extends m{apiName="TtsEngine";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.ttsEngine?typeof chrome.ttsEngine.updateVoices!="function"?{available:!1,message:"chrome.ttsEngine.updateVoices is not available",details:"The ttsEngine API appears to be partially available. Check manifest permissions."}:!chrome.ttsEngine.onSpeak||!chrome.ttsEngine.onStop?{available:!1,message:"chrome.ttsEngine events are not available",details:"The ttsEngine API requires event listeners to be available."}:{available:!0,message:"TtsEngine API is fully available"}:{available:!1,message:"chrome.ttsEngine API is not defined",details:'This extension needs the "ttsEngine" permission in its manifest.json'}}catch(e){return {available:false,message:"Failed to access chrome.ttsEngine API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("updateVoices")&&this.registerUpdateVoices(),this.shouldRegisterTool("updateLanguage")&&this.registerUpdateLanguage(),this.shouldRegisterTool("onSpeak")&&this.registerOnSpeak(),this.shouldRegisterTool("onStop")&&this.registerOnStop(),this.shouldRegisterTool("onPause")&&this.registerOnPause(),this.shouldRegisterTool("onResume")&&this.registerOnResume(),this.shouldRegisterTool("onSpeakWithAudioStream")&&this.registerOnSpeakWithAudioStream(),this.shouldRegisterTool("onInstallLanguageRequest")&&this.registerOnInstallLanguageRequest(),this.shouldRegisterTool("onLanguageStatusRequest")&&this.registerOnLanguageStatusRequest(),this.shouldRegisterTool("onUninstallLanguageRequest")&&this.registerOnUninstallLanguageRequest();}registerUpdateVoices(){this.server.registerTool("extension_tool_update_voices",{description:"Update the list of voices available for speech synthesis",inputSchema:{voices:z.array(z.object({voiceName:z.string().describe("The name of the voice"),lang:z.string().optional().describe("Language code (e.g., en-US)"),gender:z.enum(["male","female"]).optional().describe("Voice gender (deprecated)"),remote:z.boolean().optional().describe("Whether the voice is remote"),extensionId:z.string().optional().describe("Extension ID providing the voice"),eventTypes:z.array(z.string()).optional().describe("Supported event types")})).describe("Array of voice objects to register")}},async({voices:e})=>{try{return chrome.ttsEngine.updateVoices(e),this.formatSuccess("Voices updated successfully",{voiceCount:e.length,voices:e.map(t=>({name:t.voiceName,lang:t.lang,eventTypes:t.eventTypes}))})}catch(t){return this.formatError(t)}});}registerUpdateLanguage(){this.server.registerTool("extension_tool_update_language",{description:"Update the installation status of a language",inputSchema:{lang:z.string().describe("Language code (e.g., en-US)"),installStatus:z.enum(["notInstalled","installing","installed","failed"]).describe("Installation status"),error:z.string().optional().describe("Error message if installation failed")}},async({lang:e,installStatus:t,error:r})=>{try{let o={lang:e,installStatus:t};return r!==void 0&&(o.error=r),chrome.ttsEngine.updateLanguage(o),this.formatSuccess("Language status updated successfully",{lang:e,installStatus:t,error:r})}catch(o){return this.formatError(o)}});}registerOnSpeak(){this.server.registerTool("extension_tool_register_speak_listener",{description:"Register a listener for speak events from the TTS engine",inputSchema:{}},async()=>{try{let e=(t,r,o)=>{o({type:"start",charIndex:0}),setTimeout(()=>{o({type:"end",charIndex:t.length});},1e3);};return chrome.ttsEngine.onSpeak.addListener(e),this.formatSuccess("Speak listener registered successfully")}catch(e){return this.formatError(e)}});}registerOnStop(){this.server.registerTool("extension_tool_register_stop_listener",{description:"Register a listener for stop events from the TTS engine",inputSchema:{}},async()=>{try{let e=()=>{};return chrome.ttsEngine.onStop.addListener(e),this.formatSuccess("Stop listener registered successfully")}catch(e){return this.formatError(e)}});}registerOnPause(){this.server.registerTool("extension_tool_register_pause_listener",{description:"Register a listener for pause events from the TTS engine",inputSchema:{}},async()=>{try{let e=()=>{};return chrome.ttsEngine.onPause.addListener(e),this.formatSuccess("Pause listener registered successfully")}catch(e){return this.formatError(e)}});}registerOnResume(){this.server.registerTool("extension_tool_register_resume_listener",{description:"Register a listener for resume events from the TTS engine",inputSchema:{}},async()=>{try{let e=()=>{};return chrome.ttsEngine.onResume.addListener(e),this.formatSuccess("Resume listener registered successfully")}catch(e){return this.formatError(e)}});}registerOnSpeakWithAudioStream(){this.server.registerTool("extension_tool_register_speak_audio_stream_listener",{description:"Register a listener for speak events with audio stream support",inputSchema:{}},async()=>{try{let e=(t,r,o,i,s)=>{try{let n=o.bufferSize,a=new ArrayBuffer(n*4);i({audioBuffer:a,charIndex:0,isLastBuffer:!0});}catch(n){s(n instanceof Error?n.message:"Unknown error");}};return chrome.ttsEngine.onSpeakWithAudioStream.addListener(e),this.formatSuccess("Speak with audio stream listener registered successfully")}catch(e){return this.formatError(e)}});}registerOnInstallLanguageRequest(){this.server.registerTool("extension_tool_register_install_language_listener",{description:"Register a listener for language installation requests",inputSchema:{}},async()=>{try{let e=(t,r)=>{chrome.ttsEngine.updateLanguage({lang:r,installStatus:"installing"});};return chrome.ttsEngine.onInstallLanguageRequest.addListener(e),this.formatSuccess("Install language listener registered successfully")}catch(e){return this.formatError(e)}});}registerOnLanguageStatusRequest(){this.server.registerTool("extension_tool_register_language_status_listener",{description:"Register a listener for language status requests",inputSchema:{}},async()=>{try{let e=(t,r)=>{chrome.ttsEngine.updateLanguage({lang:r,installStatus:"installed"});};return chrome.ttsEngine.onLanguageStatusRequest.addListener(e),this.formatSuccess("Language status listener registered successfully")}catch(e){return this.formatError(e)}});}registerOnUninstallLanguageRequest(){this.server.registerTool("extension_tool_register_uninstall_language_listener",{description:"Register a listener for language uninstallation requests",inputSchema:{}},async()=>{try{let e=(t,r,o)=>{o.uninstallImmediately&&chrome.ttsEngine.updateLanguage({lang:r,installStatus:"notInstalled"});};return chrome.ttsEngine.onUninstallLanguageRequest.addListener(e),this.formatSuccess("Uninstall language listener registered successfully")}catch(e){return this.formatError(e)}});}};var Vt=class extends m{apiName="UserScripts";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.userScripts?typeof chrome.userScripts.getScripts!="function"?{available:!1,message:"chrome.userScripts.getScripts is not available",details:"The userScripts API appears to be partially available. Check manifest permissions and user toggle settings."}:(chrome.userScripts.getScripts({},()=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"UserScripts API is fully available"}):{available:!1,message:"chrome.userScripts API is not defined",details:'This extension needs the "userScripts" permission in its manifest.json and users must enable the appropriate toggle (Developer mode for Chrome <138 or Allow User Scripts for Chrome 138+)'}}catch(e){return {available:false,message:"Failed to access chrome.userScripts API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("register")&&this.registerRegister(),this.shouldRegisterTool("getScripts")&&this.registerGetScripts(),this.shouldRegisterTool("update")&&this.registerUpdate(),this.shouldRegisterTool("unregister")&&this.registerUnregister(),this.shouldRegisterTool("configureWorld")&&this.registerConfigureWorld(),this.shouldRegisterTool("getWorldConfigurations")&&this.registerGetWorldConfigurations(),this.shouldRegisterTool("resetWorldConfiguration")&&this.registerResetWorldConfiguration(),this.shouldRegisterTool("execute")&&this.registerExecute();}registerRegister(){this.server.registerTool("extension_tool_register_user_scripts",{description:"Register one or more user scripts for this extension",inputSchema:{scripts:z.array(z.object({id:z.string().describe("The ID of the user script. Must not start with underscore"),matches:z.array(z.string()).describe("Match patterns for pages this script will be injected into"),js:z.array(z.object({code:z.string().optional().describe("JavaScript code to inject"),file:z.string().optional().describe("Path to JavaScript file relative to extension root")})).optional().describe("List of script sources to inject"),allFrames:z.boolean().optional().describe("Whether to inject into all frames (default: false)"),excludeMatches:z.array(z.string()).optional().describe("Pages to exclude from injection"),includeGlobs:z.array(z.string()).optional().describe("Wildcard patterns for pages to include"),excludeGlobs:z.array(z.string()).optional().describe("Wildcard patterns for pages to exclude"),runAt:z.enum(["document_start","document_end","document_idle"]).optional().describe("When to inject the script (default: document_idle)"),world:z.enum(["MAIN","USER_SCRIPT"]).optional().describe("JavaScript execution environment (default: USER_SCRIPT)"),worldId:z.string().optional().describe("User script world ID to execute in")})).describe("Array of user scripts to register")}},async({scripts:e})=>{try{for(let t of e){if(t.id.startsWith("_"))return this.formatError("Script ID cannot start with underscore: "+t.id);if(t.js)for(let r of t.js){let o=r.code!==void 0,i=r.file!==void 0;if(o===i)return this.formatError("Exactly one of code or file must be specified for each script source")}}return await new Promise((t,r)=>{chrome.userScripts.register(e,()=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t();});}),this.formatSuccess("User scripts registered successfully",{registeredCount:e.length,scriptIds:e.map(t=>t.id)})}catch(t){return this.formatError(t)}});}registerGetScripts(){this.server.registerTool("extension_tool_get_user_scripts",{description:"Get all dynamically-registered user scripts for this extension",inputSchema:{ids:z.array(z.string()).optional().describe("Filter to only return scripts with these IDs")}},async({ids:e})=>{try{let t={};e!==void 0&&(t.ids=e);let r=await new Promise((o,i)=>{chrome.userScripts.getScripts(t,s=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o(s);});});return this.formatJson({count:r.length,scripts:r.map(o=>({id:o.id,matches:o.matches,allFrames:o.allFrames,excludeMatches:o.excludeMatches,includeGlobs:o.includeGlobs,excludeGlobs:o.excludeGlobs,runAt:o.runAt,world:o.world,worldId:o.worldId,jsSourcesCount:o.js?.length||0}))})}catch(t){return this.formatError(t)}});}registerUpdate(){this.server.registerTool("extension_tool_update_user_scripts",{description:"Update one or more user scripts for this extension",inputSchema:{scripts:z.array(z.object({id:z.string().describe("The ID of the user script to update"),matches:z.array(z.string()).optional().describe("Match patterns for pages this script will be injected into"),js:z.array(z.object({code:z.string().optional().describe("JavaScript code to inject"),file:z.string().optional().describe("Path to JavaScript file relative to extension root")})).optional().describe("List of script sources to inject"),allFrames:z.boolean().optional().describe("Whether to inject into all frames"),excludeMatches:z.array(z.string()).optional().describe("Pages to exclude from injection"),includeGlobs:z.array(z.string()).optional().describe("Wildcard patterns for pages to include"),excludeGlobs:z.array(z.string()).optional().describe("Wildcard patterns for pages to exclude"),runAt:z.enum(["document_start","document_end","document_idle"]).optional().describe("When to inject the script"),world:z.enum(["MAIN","USER_SCRIPT"]).optional().describe("JavaScript execution environment"),worldId:z.string().optional().describe("User script world ID to execute in")})).describe("Array of user scripts to update")}},async({scripts:e})=>{try{for(let t of e)if(t.js)for(let r of t.js){let o=r.code!==void 0,i=r.file!==void 0;if(o===i)return this.formatError("Exactly one of code or file must be specified for each script source")}return await new Promise((t,r)=>{chrome.userScripts.update(e,()=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t();});}),this.formatSuccess("User scripts updated successfully",{updatedCount:e.length,scriptIds:e.map(t=>t.id)})}catch(t){return this.formatError(t)}});}registerUnregister(){this.server.registerTool("extension_tool_unregister_user_scripts",{description:"Unregister dynamically-registered user scripts for this extension",inputSchema:{ids:z.array(z.string()).optional().describe("Filter to only unregister scripts with these IDs. If not specified, all scripts are unregistered")}},async({ids:e})=>{try{let t={};e!==void 0&&(t.ids=e);let r=await new Promise((o,i)=>{chrome.userScripts.getScripts(t,s=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o(s);});});return await new Promise((o,i)=>{chrome.userScripts.unregister(t,()=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o();});}),this.formatSuccess("User scripts unregistered successfully",{unregisteredCount:r.length,unregisteredScriptIds:r.map(o=>o.id)})}catch(t){return this.formatError(t)}});}registerConfigureWorld(){this.server.registerTool("extension_tool_configure_user_script_world",{description:"Configure the USER_SCRIPT execution environment",inputSchema:{csp:z.string().optional().describe("Content Security Policy for the world"),messaging:z.boolean().optional().describe("Whether messaging APIs are exposed (default: false)"),worldId:z.string().optional().describe("ID of the specific user script world to update")}},async({csp:e,messaging:t,worldId:r})=>{try{let o={};return e!==void 0&&(o.csp=e),t!==void 0&&(o.messaging=t),r!==void 0&&(o.worldId=r),await new Promise((i,s)=>{chrome.userScripts.configureWorld(o,()=>{chrome.runtime.lastError?s(new Error(chrome.runtime.lastError.message)):i();});}),this.formatSuccess("User script world configured successfully",{worldId:r||"default",csp:e,messaging:t})}catch(o){return this.formatError(o)}});}registerGetWorldConfigurations(){this.server.registerTool("extension_tool_get_world_configurations",{description:"Retrieve all registered world configurations",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.userScripts.getWorldConfigurations(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return this.formatJson({count:e.length,worlds:e.map(t=>({worldId:t.worldId,csp:t.csp,messaging:t.messaging}))})}catch(e){return this.formatError(e)}});}registerResetWorldConfiguration(){this.server.registerTool("extension_tool_reset_world_configuration",{description:"Reset the configuration for a user script world to defaults",inputSchema:{worldId:z.string().optional().describe("ID of the user script world to reset. If omitted, resets the default world")}},async({worldId:e="default"})=>{try{return await new Promise((t,r)=>{chrome.userScripts.resetWorldConfiguration(e,()=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t();});}),this.formatSuccess("World configuration reset successfully",{worldId:e||"default"})}catch(t){return this.formatError(t)}});}registerExecute(){this.server.registerTool("extension_tool_execute_user_script",{description:"Inject a script into a target context",inputSchema:{target:z.object({tabId:z.number().describe("The ID of the tab to inject into"),frameIds:z.array(z.number()).optional().describe("IDs of specific frames to inject into"),documentIds:z.array(z.string()).optional().describe("IDs of specific documents to inject into"),allFrames:z.boolean().optional().describe("Whether to inject into all frames (default: false)")}).describe("Target specification for injection"),js:z.array(z.object({code:z.string().optional().describe("JavaScript code to inject"),file:z.string().optional().describe("Path to JavaScript file relative to extension root")})).describe("List of script sources to inject"),world:z.enum(["MAIN","USER_SCRIPT"]).optional().describe("JavaScript execution environment (default: USER_SCRIPT)"),worldId:z.string().optional().describe("User script world ID to execute in"),injectImmediately:z.boolean().optional().describe("Whether to inject immediately without waiting (default: false)")}},async({target:e,js:t,world:r,worldId:o,injectImmediately:i})=>{try{for(let a of t){let c=a.code!==void 0,u=a.file!==void 0;if(c===u)return this.formatError("Exactly one of code or file must be specified for each script source")}let s={target:e,js:t};r!==void 0&&(s.world=r),o!==void 0&&(s.worldId=o),i!==void 0&&(s.injectImmediately=i);let n=await new Promise((a,c)=>{chrome.userScripts.execute(s,u=>{chrome.runtime.lastError?c(new Error(chrome.runtime.lastError.message)):a(u);});});return this.formatJson({injectionCount:n.length,results:n.map(a=>({frameId:a.frameId,documentId:a.documentId,error:a.error,hasResult:a.result!==void 0}))})}catch(s){return this.formatError(s)}});}};var zt=class extends m{apiName="VpnProvider";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.vpnProvider?typeof chrome.vpnProvider.createConfig!="function"?{available:!1,message:"chrome.vpnProvider.createConfig is not available",details:"The vpnProvider API appears to be partially available. Check manifest permissions and ensure this is running on ChromeOS."}:{available:!0,message:"VpnProvider API is fully available"}:{available:!1,message:"chrome.vpnProvider API is not defined",details:'This extension needs the "vpnProvider" permission in its manifest.json and only works on ChromeOS'}}catch(e){return {available:false,message:"Failed to access chrome.vpnProvider API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("createConfig")&&this.registerCreateConfig(),this.shouldRegisterTool("destroyConfig")&&this.registerDestroyConfig(),this.shouldRegisterTool("setParameters")&&this.registerSetParameters(),this.shouldRegisterTool("notifyConnectionStateChanged")&&this.registerNotifyConnectionStateChanged(),this.shouldRegisterTool("sendPacket")&&this.registerSendPacket();}registerCreateConfig(){this.server.registerTool("extension_tool_create_vpn_config",{description:"Create a new VPN configuration that persists across multiple login sessions",inputSchema:{name:z.string().describe("The name of the VPN configuration")}},async({name:e})=>{try{let t=await new Promise((r,o)=>{chrome.vpnProvider.createConfig(e,i=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):i?r(i):o(new Error("Failed to create VPN configuration"));});});return this.formatSuccess("VPN configuration created successfully",{id:t,name:e})}catch(t){return this.formatError(t)}});}registerDestroyConfig(){this.server.registerTool("extension_tool_destroy_vpn_config",{description:"Destroy a VPN configuration created by the extension",inputSchema:{id:z.string().describe("ID of the VPN configuration to destroy")}},async({id:e})=>{try{return await new Promise((t,r)=>{chrome.vpnProvider.destroyConfig(e,()=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t();});}),this.formatSuccess("VPN configuration destroyed successfully",{id:e})}catch(t){return this.formatError(t)}});}registerSetParameters(){this.server.registerTool("extension_tool_set_vpn_parameters",{description:'Set the parameters for the VPN session. Should be called immediately after "connected" is received',inputSchema:{address:z.string().describe("IP address for the VPN interface in CIDR notation. IPv4 is currently the only supported mode"),dnsServer:z.array(z.string()).describe("A list of IPs for the DNS servers"),inclusionList:z.array(z.string()).describe("Include network traffic to the list of IP blocks in CIDR notation to the tunnel"),exclusionList:z.array(z.string()).describe("Exclude network traffic to the list of IP blocks in CIDR notation from the tunnel"),broadcastAddress:z.string().optional().describe("Broadcast address for the VPN interface (default: deduced from IP address and mask)"),domainSearch:z.array(z.string()).optional().describe("A list of search domains (default: no search domain)"),mtu:z.string().optional().describe("MTU setting for the VPN interface (default: 1500 bytes)")}},async({address:e,dnsServer:t,inclusionList:r,exclusionList:o,broadcastAddress:i,domainSearch:s,mtu:n})=>{try{let a={address:e,dnsServer:t,inclusionList:r,exclusionList:o};return i!==void 0&&(a.broadcastAddress=i),s!==void 0&&(a.domainSearch=s),n!==void 0&&(a.mtu=n),await new Promise((c,u)=>{chrome.vpnProvider.setParameters(a,()=>{chrome.runtime.lastError?u(new Error(chrome.runtime.lastError.message)):c();});}),this.formatSuccess("VPN parameters set successfully",{parameters:a})}catch(a){return this.formatError(a)}});}registerNotifyConnectionStateChanged(){this.server.registerTool("extension_tool_notify_vpn_connection_state",{description:"Notify the VPN session state to the platform. This will succeed only when the VPN session is owned by the extension",inputSchema:{state:z.enum(["connected","failure"]).describe("The VPN session state of the VPN client")}},async({state:e})=>{try{return await new Promise((t,r)=>{chrome.vpnProvider.notifyConnectionStateChanged(e,()=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t();});}),this.formatSuccess("VPN connection state notified successfully",{state:e})}catch(t){return this.formatError(t)}});}registerSendPacket(){this.server.registerTool("extension_tool_send_vpn_packet",{description:"Send an IP packet through the tunnel created for the VPN session. This will succeed only when the VPN session is owned by the extension",inputSchema:{data:z.string().describe("The IP packet data as a base64 encoded string")}},async({data:e})=>{try{let t=atob(e),r=new Uint8Array(t.length);for(let i=0;i<t.length;i++)r[i]=t.charCodeAt(i);let o=r.buffer;return await new Promise((i,s)=>{chrome.vpnProvider.sendPacket(o,()=>{chrome.runtime.lastError?s(new Error(chrome.runtime.lastError.message)):i();});}),this.formatSuccess("VPN packet sent successfully",{packetSize:o.byteLength})}catch(t){return this.formatError(t)}});}};var Ht=class extends m{apiName="Wallpaper";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.wallpaper?typeof chrome.wallpaper.setWallpaper!="function"?{available:!1,message:"chrome.wallpaper.setWallpaper is not available",details:"The wallpaper API appears to be partially available. Check manifest permissions and ensure you are running on ChromeOS."}:{available:!0,message:"Wallpaper API is fully available"}:{available:!1,message:"chrome.wallpaper API is not defined",details:'This extension needs the "wallpaper" permission in its manifest.json and only works on ChromeOS'}}catch(e){return {available:false,message:"Failed to access chrome.wallpaper API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("setWallpaper")&&this.registerSetWallpaper();}registerSetWallpaper(){this.server.registerTool("extension_tool_set_wallpaper",{description:"Set the ChromeOS wallpaper to an image from a URL or data",inputSchema:{filename:z.string().describe("The file name of the saved wallpaper"),layout:z.enum(["STRETCH","CENTER","CENTER_CROPPED"]).describe("The wallpaper layout"),url:z.string().optional().describe("The URL of the wallpaper to be set (can be relative)"),data:z.string().optional().describe("Base64 encoded jpeg or png wallpaper image data"),thumbnail:z.boolean().optional().describe("True if a 128x60 thumbnail should be generated")}},async({filename:e,layout:t,url:r,data:o,thumbnail:i})=>{try{if(!r&&!o)return this.formatError("Either url or data must be specified to set wallpaper");if(r&&o)return this.formatError("Cannot specify both url and data. Choose one method to set wallpaper");let s={filename:e,layout:t};if(r&&(s.url=r),o)try{let c=atob(o),u=new Uint8Array(c.length);for(let d=0;d<c.length;d++)u[d]=c.charCodeAt(d);s.data=u.buffer;}catch{return this.formatError("Invalid base64 data provided")}i!==void 0&&(s.thumbnail=i);let n=await new Promise((c,u)=>{chrome.wallpaper.setWallpaper(s,d=>{chrome.runtime.lastError?u(new Error(chrome.runtime.lastError.message)):c(d);});}),a={filename:e,layout:t,success:!0};if(r&&(a.url=r),n){let c=new Uint8Array(n),u="";for(let d=0;d<c.byteLength;d++)u+=String.fromCharCode(c[d]);a.thumbnail=btoa(u),a.thumbnailSize=n.byteLength;}return this.formatSuccess("Wallpaper set successfully",a)}catch(s){return this.formatError(s)}});}};var Kt=class extends m{apiName="WebAuthenticationProxy";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.webAuthenticationProxy?typeof chrome.webAuthenticationProxy.attach!="function"?{available:!1,message:"chrome.webAuthenticationProxy.attach is not available",details:"The webAuthenticationProxy API appears to be partially available. Check manifest permissions."}:{available:!0,message:"WebAuthenticationProxy API is fully available"}:{available:!1,message:"chrome.webAuthenticationProxy API is not defined",details:'This extension needs the "webAuthenticationProxy" permission in its manifest.json'}}catch(e){return {available:false,message:"Failed to access chrome.webAuthenticationProxy API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("attach")&&this.registerAttach(),this.shouldRegisterTool("detach")&&this.registerDetach(),this.shouldRegisterTool("completeCreateRequest")&&this.registerCompleteCreateRequest(),this.shouldRegisterTool("completeGetRequest")&&this.registerCompleteGetRequest(),this.shouldRegisterTool("completeIsUvpaaRequest")&&this.registerCompleteIsUvpaaRequest(),this.shouldRegisterTool("onCreateRequest")&&this.registerOnCreateRequest(),this.shouldRegisterTool("onGetRequest")&&this.registerOnGetRequest(),this.shouldRegisterTool("onIsUvpaaRequest")&&this.registerOnIsUvpaaRequest(),this.shouldRegisterTool("onRemoteSessionStateChange")&&this.registerOnRemoteSessionStateChange(),this.shouldRegisterTool("onRequestCanceled")&&this.registerOnRequestCanceled();}registerAttach(){this.server.registerTool("extension_tool_attach_web_authentication_proxy",{description:"Makes this extension the active Web Authentication API request proxy",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.webAuthenticationProxy.attach(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return e?this.formatError(e):this.formatSuccess("Successfully attached as Web Authentication API request proxy")}catch(e){return this.formatError(e)}});}registerDetach(){this.server.registerTool("extension_tool_detach_web_authentication_proxy",{description:"Removes this extension from being the active Web Authentication API request proxy",inputSchema:{}},async()=>{try{let e=await new Promise((t,r)=>{chrome.webAuthenticationProxy.detach(o=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):t(o);});});return e?this.formatError(e):this.formatSuccess("Successfully detached from Web Authentication API request proxy")}catch(e){return this.formatError(e)}});}registerCompleteCreateRequest(){this.server.registerTool("extension_tool_complete_create_request",{description:"Reports the result of a navigator.credentials.create() call",inputSchema:{requestId:z.number().describe("The requestId of the CreateRequest"),responseJson:z.string().optional().describe("The PublicKeyCredential serialized as JSON"),error:z.object({name:z.string().describe("The DOMException name"),message:z.string().describe("The DOMException message")}).optional().describe("The DOMException yielded by the remote request, if any")}},async({requestId:e,responseJson:t,error:r})=>{try{let o={requestId:e};return t!==void 0&&(o.responseJson=t),r!==void 0&&(o.error=r),await new Promise((i,s)=>{chrome.webAuthenticationProxy.completeCreateRequest(o,()=>{chrome.runtime.lastError?s(new Error(chrome.runtime.lastError.message)):i();});}),this.formatSuccess("Create request completed successfully",{requestId:e})}catch(o){return this.formatError(o)}});}registerCompleteGetRequest(){this.server.registerTool("extension_tool_complete_get_request",{description:"Reports the result of a navigator.credentials.get() call",inputSchema:{requestId:z.number().describe("The requestId of the GetRequest"),responseJson:z.string().optional().describe("The PublicKeyCredential serialized as JSON"),error:z.object({name:z.string().describe("The DOMException name"),message:z.string().describe("The DOMException message")}).optional().describe("The DOMException yielded by the remote request, if any")}},async({requestId:e,responseJson:t,error:r})=>{try{let o={requestId:e};return t!==void 0&&(o.responseJson=t),r!==void 0&&(o.error=r),await new Promise((i,s)=>{chrome.webAuthenticationProxy.completeGetRequest(o,()=>{chrome.runtime.lastError?s(new Error(chrome.runtime.lastError.message)):i();});}),this.formatSuccess("Get request completed successfully",{requestId:e})}catch(o){return this.formatError(o)}});}registerCompleteIsUvpaaRequest(){this.server.registerTool("extension_tool_complete_is_uvpaa_request",{description:"Reports the result of a PublicKeyCredential.isUserVerifyingPlatformAuthenticator() call",inputSchema:{requestId:z.number().describe("The requestId of the IsUvpaaRequest"),isUvpaa:z.boolean().describe("Whether user verifying platform authenticator is available")}},async({requestId:e,isUvpaa:t})=>{try{let r={requestId:e,isUvpaa:t};return await new Promise((o,i)=>{chrome.webAuthenticationProxy.completeIsUvpaaRequest(r,()=>{chrome.runtime.lastError?i(new Error(chrome.runtime.lastError.message)):o();});}),this.formatSuccess("IsUvpaa request completed successfully",{requestId:e,isUvpaa:t})}catch(r){return this.formatError(r)}});}registerOnCreateRequest(){this.server.registerTool("extension_tool_listen_create_requests",{description:"Start listening for WebAuthn navigator.credentials.create() calls",inputSchema:{}},async()=>{try{let e=t=>{console.log("WebAuthn create request received:",{requestId:t.requestId,requestDetailsJson:t.requestDetailsJson});};return chrome.webAuthenticationProxy.onCreateRequest.addListener(e),this.formatSuccess("Started listening for WebAuthn create requests")}catch(e){return this.formatError(e)}});}registerOnGetRequest(){this.server.registerTool("extension_tool_listen_get_requests",{description:"Start listening for WebAuthn navigator.credentials.get() calls",inputSchema:{}},async()=>{try{let e=t=>{console.log("WebAuthn get request received:",{requestId:t.requestId,requestDetailsJson:t.requestDetailsJson});};return chrome.webAuthenticationProxy.onGetRequest.addListener(e),this.formatSuccess("Started listening for WebAuthn get requests")}catch(e){return this.formatError(e)}});}registerOnIsUvpaaRequest(){this.server.registerTool("extension_tool_listen_is_uvpaa_requests",{description:"Start listening for PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable() calls",inputSchema:{}},async()=>{try{let e=t=>{console.log("WebAuthn isUvpaa request received:",{requestId:t.requestId});};return chrome.webAuthenticationProxy.onIsUvpaaRequest.addListener(e),this.formatSuccess("Started listening for WebAuthn isUvpaa requests")}catch(e){return this.formatError(e)}});}registerOnRemoteSessionStateChange(){this.server.registerTool("extension_tool_listen_remote_session_state_changes",{description:"Start listening for remote session state changes",inputSchema:{}},async()=>{try{let e=()=>{console.log("Remote session state change detected");};return chrome.webAuthenticationProxy.onRemoteSessionStateChange.addListener(e),this.formatSuccess("Started listening for remote session state changes")}catch(e){return this.formatError(e)}});}registerOnRequestCanceled(){this.server.registerTool("extension_tool_listen_request_canceled",{description:"Start listening for canceled WebAuthn requests",inputSchema:{}},async()=>{try{let e=t=>{console.log("WebAuthn request canceled:",{requestId:t});};return chrome.webAuthenticationProxy.onRequestCanceled.addListener(e),this.formatSuccess("Started listening for canceled WebAuthn requests")}catch(e){return this.formatError(e)}});}};var $t=class extends m{apiName="WebNavigation";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.webNavigation?typeof chrome.webNavigation.getAllFrames!="function"?{available:!1,message:"chrome.webNavigation.getAllFrames is not available",details:"The webNavigation API appears to be partially available. Check manifest permissions."}:{available:!0,message:"WebNavigation API is fully available"}:{available:!1,message:"chrome.webNavigation API is not defined",details:'This extension needs the "webNavigation" permission in its manifest.json'}}catch(e){return {available:false,message:"Failed to access chrome.webNavigation API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("getAllFrames")&&this.registerGetAllFrames(),this.shouldRegisterTool("getFrame")&&this.registerGetFrame(),this.shouldRegisterTool("onBeforeNavigate")&&this.registerOnBeforeNavigate(),this.shouldRegisterTool("onCommitted")&&this.registerOnCommitted(),this.shouldRegisterTool("onCompleted")&&this.registerOnCompleted(),this.shouldRegisterTool("onCreatedNavigationTarget")&&this.registerOnCreatedNavigationTarget(),this.shouldRegisterTool("onDOMContentLoaded")&&this.registerOnDOMContentLoaded(),this.shouldRegisterTool("onErrorOccurred")&&this.registerOnErrorOccurred(),this.shouldRegisterTool("onHistoryStateUpdated")&&this.registerOnHistoryStateUpdated(),this.shouldRegisterTool("onReferenceFragmentUpdated")&&this.registerOnReferenceFragmentUpdated(),this.shouldRegisterTool("onTabReplaced")&&this.registerOnTabReplaced();}registerGetAllFrames(){this.server.registerTool("extension_tool_get_all_frames",{description:"Retrieves information about all frames of a given tab",inputSchema:{tabId:z.number().describe("The ID of the tab to retrieve all frames from")}},async({tabId:e})=>{try{let t=await new Promise((r,o)=>{chrome.webNavigation.getAllFrames({tabId:e},i=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r(i??void 0);});});return t?this.formatJson({tabId:e,frameCount:t.length,frames:t.map(r=>({frameId:r.frameId,parentFrameId:r.parentFrameId,processId:r.processId,url:r.url,errorOccurred:r.errorOccurred,documentId:r.documentId,documentLifecycle:r.documentLifecycle,frameType:r.frameType,parentDocumentId:r.parentDocumentId}))}):this.formatError("Invalid tab ID or no frames found")}catch(t){return this.formatError(t)}});}registerGetFrame(){this.server.registerTool("extension_tool_get_frame",{description:"Retrieves information about the given frame. A frame refers to an iframe or frame of a web page",inputSchema:{tabId:z.number().optional().describe("The ID of the tab in which the frame is"),frameId:z.number().optional().describe("The ID of the frame in the given tab")}},async({tabId:e,frameId:t})=>{try{let r={};e!==void 0&&(r.tabId=e),t!==void 0&&(r.frameId=t);let o=await new Promise((i,s)=>{chrome.webNavigation.getFrame(r,n=>{chrome.runtime.lastError?s(new Error(chrome.runtime.lastError.message)):i(n??void 0);});});return o?this.formatJson({parentFrameId:o.parentFrameId,url:o.url,errorOccurred:o.errorOccurred,documentId:o.documentId,documentLifecycle:o.documentLifecycle,frameType:o.frameType,parentDocumentId:o.parentDocumentId}):this.formatSuccess("No frame found with the specified parameters")}catch(r){return this.formatError(r)}});}registerOnBeforeNavigate(){this.server.registerTool("extension_tool_on_before_navigate",{description:"Sets up a listener for navigation events that are about to occur. Returns immediately after setting up the listener",inputSchema:{urlFilters:z.array(z.string()).optional().describe("URL patterns to filter navigation events. If not provided, listens to all navigations")}},async({urlFilters:e})=>{try{let t=e?{url:e.map(r=>({urlMatches:r}))}:void 0;return chrome.webNavigation.onBeforeNavigate.addListener(r=>{console.log("Navigation about to occur:",{tabId:r.tabId,frameId:r.frameId,parentFrameId:r.parentFrameId,url:r.url,timeStamp:r.timeStamp,processId:r.processId,documentLifecycle:r.documentLifecycle,frameType:r.frameType,parentDocumentId:r.parentDocumentId});},t),this.formatSuccess("onBeforeNavigate listener registered successfully",{hasFilters:!!t,filterCount:e?.length||0})}catch(t){return this.formatError(t)}});}registerOnCommitted(){this.server.registerTool("extension_tool_on_committed",{description:"Sets up a listener for navigation committed events. Fired when a navigation is committed",inputSchema:{urlFilters:z.array(z.string()).optional().describe("URL patterns to filter navigation events. If not provided, listens to all navigations")}},async({urlFilters:e})=>{try{let t=e?{url:e.map(r=>({urlMatches:r}))}:void 0;return chrome.webNavigation.onCommitted.addListener(r=>{console.log("Navigation committed:",{tabId:r.tabId,frameId:r.frameId,url:r.url,timeStamp:r.timeStamp,processId:r.processId,transitionType:r.transitionType,transitionQualifiers:r.transitionQualifiers,documentId:r.documentId,documentLifecycle:r.documentLifecycle,frameType:r.frameType,parentDocumentId:r.parentDocumentId});},t),this.formatSuccess("onCommitted listener registered successfully",{hasFilters:!!t,filterCount:e?.length||0})}catch(t){return this.formatError(t)}});}registerOnCompleted(){this.server.registerTool("extension_tool_on_completed",{description:"Sets up a listener for navigation completed events. Fired when a document and its resources are completely loaded",inputSchema:{urlFilters:z.array(z.string()).optional().describe("URL patterns to filter navigation events. If not provided, listens to all navigations")}},async({urlFilters:e})=>{try{let t=e?{url:e.map(r=>({urlMatches:r}))}:void 0;return chrome.webNavigation.onCompleted.addListener(r=>{console.log("Navigation completed:",{tabId:r.tabId,frameId:r.frameId,url:r.url,timeStamp:r.timeStamp,processId:r.processId,documentId:r.documentId,documentLifecycle:r.documentLifecycle,frameType:r.frameType,parentDocumentId:r.parentDocumentId});},t),this.formatSuccess("onCompleted listener registered successfully",{hasFilters:!!t,filterCount:e?.length||0})}catch(t){return this.formatError(t)}});}registerOnCreatedNavigationTarget(){this.server.registerTool("extension_tool_on_created_navigation_target",{description:"Sets up a listener for new navigation target creation events. Fired when a new window or tab is created to host a navigation",inputSchema:{urlFilters:z.array(z.string()).optional().describe("URL patterns to filter navigation events. If not provided, listens to all navigations")}},async({urlFilters:e})=>{try{let t=e?{url:e.map(r=>({urlMatches:r}))}:void 0;return chrome.webNavigation.onCreatedNavigationTarget.addListener(r=>{console.log("Navigation target created:",{sourceTabId:r.sourceTabId,sourceFrameId:r.sourceFrameId,sourceProcessId:r.sourceProcessId,tabId:r.tabId,url:r.url,timeStamp:r.timeStamp});},t),this.formatSuccess("onCreatedNavigationTarget listener registered successfully",{hasFilters:!!t,filterCount:e?.length||0})}catch(t){return this.formatError(t)}});}registerOnDOMContentLoaded(){this.server.registerTool("extension_tool_on_dom_content_loaded",{description:"Sets up a listener for DOM content loaded events. Fired when the page DOM is fully constructed",inputSchema:{urlFilters:z.array(z.string()).optional().describe("URL patterns to filter navigation events. If not provided, listens to all navigations")}},async({urlFilters:e})=>{try{let t=e?{url:e.map(r=>({urlMatches:r}))}:void 0;return chrome.webNavigation.onDOMContentLoaded.addListener(r=>{console.log("DOM content loaded:",{tabId:r.tabId,frameId:r.frameId,url:r.url,timeStamp:r.timeStamp,processId:r.processId,documentId:r.documentId,documentLifecycle:r.documentLifecycle,frameType:r.frameType,parentDocumentId:r.parentDocumentId});},t),this.formatSuccess("onDOMContentLoaded listener registered successfully",{hasFilters:!!t,filterCount:e?.length||0})}catch(t){return this.formatError(t)}});}registerOnErrorOccurred(){this.server.registerTool("extension_tool_on_error_occurred",{description:"Sets up a listener for navigation error events. Fired when an error occurs and navigation is aborted",inputSchema:{urlFilters:z.array(z.string()).optional().describe("URL patterns to filter navigation events. If not provided, listens to all navigations")}},async({urlFilters:e})=>{try{let t=e?{url:e.map(r=>({urlMatches:r}))}:void 0;return chrome.webNavigation.onErrorOccurred.addListener(r=>{console.log("Navigation error occurred:",{tabId:r.tabId,frameId:r.frameId,url:r.url,error:r.error,timeStamp:r.timeStamp,processId:r.processId,documentId:r.documentId,documentLifecycle:r.documentLifecycle,frameType:r.frameType,parentDocumentId:r.parentDocumentId});},t),this.formatSuccess("onErrorOccurred listener registered successfully",{hasFilters:!!t,filterCount:e?.length||0})}catch(t){return this.formatError(t)}});}registerOnHistoryStateUpdated(){this.server.registerTool("extension_tool_on_history_state_updated",{description:"Sets up a listener for history state update events. Fired when the frame history was updated to a new URL",inputSchema:{urlFilters:z.array(z.string()).optional().describe("URL patterns to filter navigation events. If not provided, listens to all navigations")}},async({urlFilters:e})=>{try{let t=e?{url:e.map(r=>({urlMatches:r}))}:void 0;return chrome.webNavigation.onHistoryStateUpdated.addListener(r=>{console.log("History state updated:",{tabId:r.tabId,frameId:r.frameId,url:r.url,timeStamp:r.timeStamp,processId:r.processId,transitionType:r.transitionType,transitionQualifiers:r.transitionQualifiers,documentId:r.documentId,documentLifecycle:r.documentLifecycle,frameType:r.frameType,parentDocumentId:r.parentDocumentId});},t),this.formatSuccess("onHistoryStateUpdated listener registered successfully",{hasFilters:!!t,filterCount:e?.length||0})}catch(t){return this.formatError(t)}});}registerOnReferenceFragmentUpdated(){this.server.registerTool("extension_tool_on_reference_fragment_updated",{description:"Sets up a listener for reference fragment update events. Fired when the reference fragment of a frame was updated",inputSchema:{urlFilters:z.array(z.string()).optional().describe("URL patterns to filter navigation events. If not provided, listens to all navigations")}},async({urlFilters:e})=>{try{let t=e?{url:e.map(r=>({urlMatches:r}))}:void 0;return chrome.webNavigation.onReferenceFragmentUpdated.addListener(r=>{console.log("Reference fragment updated:",{tabId:r.tabId,frameId:r.frameId,url:r.url,timeStamp:r.timeStamp,processId:r.processId,transitionType:r.transitionType,transitionQualifiers:r.transitionQualifiers,documentId:r.documentId,documentLifecycle:r.documentLifecycle,frameType:r.frameType,parentDocumentId:r.parentDocumentId});},t),this.formatSuccess("onReferenceFragmentUpdated listener registered successfully",{hasFilters:!!t,filterCount:e?.length||0})}catch(t){return this.formatError(t)}});}registerOnTabReplaced(){this.server.registerTool("extension_tool_on_tab_replaced",{description:"Sets up a listener for tab replacement events. Fired when the contents of a tab is replaced by a different tab",inputSchema:{}},async()=>{try{return chrome.webNavigation.onTabReplaced.addListener(e=>{console.log("Tab replaced:",{replacedTabId:e.replacedTabId,tabId:e.tabId,timeStamp:e.timeStamp});}),this.formatSuccess("onTabReplaced listener registered successfully")}catch(e){return this.formatError(e)}});}};var Zt=class extends m{apiName="WebRequest";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.webRequest?typeof chrome.webRequest.handlerBehaviorChanged!="function"?{available:!1,message:"chrome.webRequest.handlerBehaviorChanged is not available",details:"The webRequest API appears to be partially available. Check manifest permissions."}:chrome.webRequest.onBeforeRequest?{available:!0,message:"WebRequest API is fully available"}:{available:!1,message:"chrome.webRequest events are not available",details:"WebRequest events are required for this API to function properly."}:{available:!1,message:"chrome.webRequest API is not defined",details:'This extension needs the "webRequest" permission in its manifest.json'}}catch(e){return {available:false,message:"Failed to access chrome.webRequest API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.shouldRegisterTool("addListener")&&this.registerAddListener(),this.shouldRegisterTool("removeListener")&&this.registerRemoveListener(),this.shouldRegisterTool("hasListener")&&this.registerHasListener(),this.shouldRegisterTool("handlerBehaviorChanged")&&this.registerHandlerBehaviorChanged(),this.shouldRegisterTool("getActiveListeners")&&this.registerGetActiveListeners();}registerAddListener(){this.server.registerTool("extension_tool_add_webrequest_listener",{description:"Add a listener to a webRequest event to monitor or modify network requests",inputSchema:{event:z.enum(["onBeforeRequest","onBeforeSendHeaders","onSendHeaders","onHeadersReceived","onAuthRequired","onBeforeRedirect","onResponseStarted","onCompleted","onErrorOccurred"]).describe("The webRequest event to listen to"),urls:z.array(z.string()).describe('Array of URL patterns to match (e.g., ["<all_urls>", "*://example.com/*"])'),types:z.array(z.enum(["main_frame","sub_frame","stylesheet","script","image","font","object","xmlhttprequest","ping","csp_report","media","websocket","webbundle","other"])).optional().describe("Array of resource types to filter"),tabId:z.number().optional().describe("Specific tab ID to monitor"),windowId:z.number().optional().describe("Specific window ID to monitor"),extraInfoSpec:z.array(z.enum(["blocking","requestHeaders","responseHeaders","requestBody","extraHeaders","asyncBlocking"])).optional().describe("Additional information to include in the event"),blocking:z.boolean().optional().describe("Whether to block requests for modification (requires webRequestBlocking permission)")}},async({event:e,urls:t,types:r,tabId:o,windowId:i,extraInfoSpec:s,blocking:n})=>{try{let a={urls:t};r&&(a.types=r),o!==void 0&&(a.tabId=o),i!==void 0&&(a.windowId=i);let c=s||[];n&&!c.includes("blocking")&&c.push("blocking");let u=v=>(console.log(`WebRequest ${e}:`,{requestId:v.requestId,url:v.url,method:v.method,type:v.type,tabId:v.tabId,timeStamp:v.timeStamp}),n?{}:v),d=chrome.webRequest[e];return d&&typeof d.addListener=="function"?(c.length>0?d.addListener(u,a,c):d.addListener(u,a),this.formatSuccess("WebRequest listener added successfully",{event:e,filter:a,extraInfoSpec:c,blocking:n||!1})):this.formatError(`Invalid webRequest event: ${e}`)}catch(a){return this.formatError(a)}});}registerRemoveListener(){this.server.registerTool("extension_tool_remove_webrequest_listener",{description:"Remove a webRequest event listener",inputSchema:{event:z.enum(["onBeforeRequest","onBeforeSendHeaders","onSendHeaders","onHeadersReceived","onAuthRequired","onBeforeRedirect","onResponseStarted","onCompleted","onErrorOccurred"]).describe("The webRequest event to remove listener from")}},async({event:e})=>{try{let t=chrome.webRequest[e];return t&&typeof t.removeListener=="function"?this.formatSuccess("WebRequest listener removal attempted",{event:e,note:"All listeners for this event type have been targeted for removal"}):this.formatError(`Invalid webRequest event: ${e}`)}catch(t){return this.formatError(t)}});}registerHasListener(){this.server.registerTool("extension_tool_has_webrequest_listener",{description:"Check if a webRequest event has any listeners",inputSchema:{event:z.enum(["onBeforeRequest","onBeforeSendHeaders","onSendHeaders","onHeadersReceived","onAuthRequired","onBeforeRedirect","onResponseStarted","onCompleted","onErrorOccurred"]).describe("The webRequest event to check")}},async({event:e})=>{try{let t=chrome.webRequest[e];if(t&&typeof t.hasListener=="function"){let r=t.hasListener();return this.formatJson({event:e,hasListener:r})}return this.formatError(`Invalid webRequest event: ${e}`)}catch(t){return this.formatError(t)}});}registerHandlerBehaviorChanged(){this.server.registerTool("extension_tool_handler_behavior_changed",{description:"Notify that webRequest handler behavior has changed to prevent incorrect caching",inputSchema:{}},async()=>{try{return await new Promise((e,t)=>{chrome.webRequest.handlerBehaviorChanged(()=>{chrome.runtime.lastError?t(new Error(chrome.runtime.lastError.message)):e();});}),this.formatSuccess("Handler behavior change notification sent",{note:"This flushes the in-memory cache to ensure behavior changes take effect",warning:"This is an expensive operation and should not be called frequently"})}catch(e){return this.formatError(e)}});}registerGetActiveListeners(){this.server.registerTool("extension_tool_get_active_webrequest_listeners",{description:"Get information about currently active webRequest listeners",inputSchema:{}},async()=>{try{let e=["onBeforeRequest","onBeforeSendHeaders","onSendHeaders","onHeadersReceived","onAuthRequired","onBeforeRedirect","onResponseStarted","onCompleted","onErrorOccurred"],t=e.map(o=>{let i=chrome.webRequest[o],s=i&&typeof i.hasListener=="function"?i.hasListener():!1;return {event:o,hasListener:s}}),r=t.filter(o=>o.hasListener).length;return this.formatJson({totalEvents:e.length,activeListeners:r,listeners:t,maxHandlerCalls:chrome.webRequest.MAX_HANDLER_BEHAVIOR_CHANGED_CALLS_PER_10_MINUTES||20})}catch(e){return this.formatError(e)}});}};var gr=["create","get","getAll","getCurrent","getLastFocused","remove","update"],Yt=z.enum(gr),Qt=class extends m{apiName="Windows";constructor(e,t={}){super(e,t);}checkAvailability(){try{return chrome.windows?typeof chrome.windows.getAll!="function"?{available:!1,message:"chrome.windows.getAll is not available",details:"The windows API appears to be partially available. Check manifest permissions."}:(chrome.windows.getAll(e=>{if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message)}),{available:!0,message:"Windows API is fully available"}):{available:!1,message:"chrome.windows API is not defined",details:'This extension needs the "windows" permission in its manifest.json'}}catch(e){return {available:false,message:"Failed to access chrome.windows API",details:e instanceof Error?e.message:"Unknown error occurred"}}}registerTools(){this.server.registerTool("extension_tool_window_operations",{description:"Perform operations on browser windows",inputSchema:{action:Yt,params:z.record(z.any()).optional().describe("Parameters for the chosen action")}},async({action:e,params:t={}})=>{try{if(!this.shouldRegisterTool(e))return this.formatError(new Error(`Action "${e}" is not supported`));switch(e){case "create":return await this.handleCreate(t);case "get":return await this.handleGet(t);case "getAll":return await this.handleGetAll(t);case "getCurrent":return await this.handleGetCurrent(t);case "getLastFocused":return await this.handleGetLastFocused(t);case "remove":return await this.handleRemove(t);case "update":return await this.handleUpdate(t);default:return this.formatError(`Unknown action: ${String(e)}`)}}catch(r){return this.formatError(r)}}),this.server.registerTool("extension_tool_window_parameters_description",{description:"Get the parameters for extension_tool_window_operations tool and the description for the associated action, this tool should be used first before extension_tool_window_operations",inputSchema:{action:Yt}},async({action:e})=>{try{let t=(o,i)=>ir(o,{name:i,$refStrategy:"none"}),r={tool:"extension_tool_window_operations",action:e,note:"Use the description to double check if the correct action is chosen. Use this JSON Schema for the params field when calling the tool. The top-level tool input is { action, params }."};switch(e){case "create":{let o={params:t(this.createSchema,"CreateWindowSchema"),description:"Create a new browser window with optional sizing, position, or default URL"};return this.formatJson({...r,...o})}case "get":{let o={params:t(this.getSchema,"GetWindowSchema"),description:"Get details about a specific window"};return this.formatJson({...r,...o})}case "getAll":{let o={params:t(this.getAllSchema,"GetAllWindowsSchema"),description:"Get all browser windows"};return this.formatJson({...r,...o})}case "getCurrent":{let o={params:t(this.getCurrentSchema,"GetCurrentWindowSchema"),description:"Get the current window"};return this.formatJson({...r,...o})}case "getLastFocused":{let o={params:t(this.getLastFocusedSchema,"GetLastFocusedWindowSchema"),description:"Get the window that was most recently focused"};return this.formatJson({...r,...o})}case "remove":{let o={params:t(this.removeSchema,"RemoveWindowSchema"),description:"Remove (close) a window and all the tabs inside it"};return this.formatJson({...r,...o})}case "update":{let o={params:t(this.updateSchema,"UpdateWindowSchema"),description:"Update the properties of a window"};return this.formatJson({...r,...o})}default:return this.formatError(`Unknown action: ${String(e)}`)}}catch(t){return this.formatError(t)}});}createSchema=z.object({url:z.union([z.string(),z.array(z.string())]).optional().describe("A URL or array of URLs to open as tabs in the window"),focused:z.boolean().optional().describe("If true, opens an active window. If false, opens an inactive window"),height:z.number().optional().describe("The height in pixels of the new window, including the frame"),incognito:z.boolean().optional().describe("Whether the new window should be an incognito window"),left:z.number().optional().describe("The number of pixels to position the new window from the left edge of the screen"),setSelfAsOpener:z.boolean().optional().describe("If true, the newly-created window's 'window.opener' is set to the caller"),state:z.enum(["normal","minimized","maximized","fullscreen","locked-fullscreen"]).optional().describe("The initial state of the window"),tabId:z.number().optional().describe("The ID of the tab to add to the new window"),top:z.number().optional().describe("The number of pixels to position the new window from the top edge of the screen"),type:z.enum(["normal","popup","panel"]).optional().describe("Specifies what type of browser window to create"),width:z.number().optional().describe("The width in pixels of the new window, including the frame")});getSchema=z.object({windowId:z.number().describe("The ID of the window to get"),populate:z.boolean().optional().describe("If true, the window object will include a tabs property with tab details"),windowTypes:z.array(z.enum(["normal","popup","panel","app","devtools"])).optional().describe("Filter the window based on its type")});getAllSchema=z.object({populate:z.boolean().optional().describe("If true, each window object will include a tabs property with tab details"),windowTypes:z.array(z.enum(["normal","popup","panel","app","devtools"])).optional().describe("Filter windows based on their type")});getCurrentSchema=z.object({populate:z.boolean().optional().describe("If true, the window object will include a tabs property with tab details"),windowTypes:z.array(z.enum(["normal","popup","panel","app","devtools"])).optional().describe("Filter the window based on its type")});getLastFocusedSchema=z.object({populate:z.boolean().optional().describe("If true, the window object will include a tabs property with tab details"),windowTypes:z.array(z.enum(["normal","popup","panel","app","devtools"])).optional().describe("Filter the window based on its type")});removeSchema=z.object({windowId:z.number().describe("The ID of the window to remove")});updateSchema=z.object({windowId:z.number().describe("The ID of the window to update"),drawAttention:z.boolean().optional().describe("If true, causes the window to be displayed in a manner that draws the user's attention"),focused:z.boolean().optional().describe("If true, brings the window to the front"),height:z.number().optional().describe("The height to resize the window to in pixels"),left:z.number().optional().describe("The offset from the left edge of the screen to move the window to in pixels"),state:z.enum(["normal","minimized","maximized","fullscreen","locked-fullscreen"]).optional().describe("The new state of the window"),top:z.number().optional().describe("The offset from the top edge of the screen to move the window to in pixels"),width:z.number().optional().describe("The width to resize the window to in pixels")});async handleCreate(e){let{url:t,focused:r,height:o,incognito:i,left:s,setSelfAsOpener:n,state:a,tabId:c,top:u,type:d,width:v}=this.createSchema.parse(e),S={};t!==void 0&&(S.url=t),r!==void 0&&(S.focused=r),o!==void 0&&(S.height=o),i!==void 0&&(S.incognito=i),s!==void 0&&(S.left=s),n!==void 0&&(S.setSelfAsOpener=n),a!==void 0&&(S.state=a),c!==void 0&&(S.tabId=c),u!==void 0&&(S.top=u),d!==void 0&&(S.type=d),v!==void 0&&(S.width=v);let P=await new Promise((I,O)=>{chrome.windows.create(S,ne=>{chrome.runtime.lastError?O(new Error(chrome.runtime.lastError.message)):I(ne);});});return this.formatJson({id:P.id,focused:P.focused,incognito:P.incognito,alwaysOnTop:P.alwaysOnTop,state:P.state,type:P.type,left:P.left,top:P.top,width:P.width,height:P.height,tabs:P.tabs?.map(I=>({id:I.id,url:I.url,title:I.title,active:I.active}))})}async handleGet(e){let{windowId:t,populate:r,windowTypes:o}=this.getSchema.parse(e),i={};r!==void 0&&(i.populate=r),o!==void 0&&(i.windowTypes=o);let s=await new Promise((n,a)=>{chrome.windows.get(t,i,c=>{chrome.runtime.lastError?a(new Error(chrome.runtime.lastError.message)):n(c);});});return this.formatJson({id:s.id,focused:s.focused,incognito:s.incognito,alwaysOnTop:s.alwaysOnTop,state:s.state,type:s.type,left:s.left,top:s.top,width:s.width,height:s.height,sessionId:s.sessionId,tabs:s.tabs?.map(n=>({id:n.id,url:n.url,title:n.title,active:n.active,index:n.index}))})}async handleGetAll(e){let{populate:t,windowTypes:r}=this.getAllSchema.parse(e),o={};t!==void 0&&(o.populate=t),r!==void 0&&(o.windowTypes=r);let i=await new Promise((s,n)=>{chrome.windows.getAll(o,a=>{chrome.runtime.lastError?n(new Error(chrome.runtime.lastError.message)):s(a);});});return this.formatJson({count:i.length,windows:i.map(s=>({id:s.id,focused:s.focused,incognito:s.incognito,alwaysOnTop:s.alwaysOnTop,state:s.state,type:s.type,left:s.left,top:s.top,width:s.width,height:s.height,sessionId:s.sessionId,tabs:s.tabs?.map(n=>({id:n.id,url:n.url,title:n.title,active:n.active,index:n.index}))}))})}async handleGetCurrent(e){let{populate:t,windowTypes:r}=this.getCurrentSchema.parse(e),o={};t!==void 0&&(o.populate=t),r!==void 0&&(o.windowTypes=r);let i=await new Promise((s,n)=>{chrome.windows.getCurrent(o,a=>{chrome.runtime.lastError?n(new Error(chrome.runtime.lastError.message)):s(a);});});return this.formatJson({id:i.id,focused:i.focused,incognito:i.incognito,alwaysOnTop:i.alwaysOnTop,state:i.state,type:i.type,left:i.left,top:i.top,width:i.width,height:i.height,sessionId:i.sessionId,tabs:i.tabs?.map(s=>({id:s.id,url:s.url,title:s.title,active:s.active,index:s.index}))})}async handleGetLastFocused(e){let{populate:t,windowTypes:r}=this.getLastFocusedSchema.parse(e),o={};t!==void 0&&(o.populate=t),r!==void 0&&(o.windowTypes=r);let i=await new Promise((s,n)=>{chrome.windows.getLastFocused(o,a=>{chrome.runtime.lastError?n(new Error(chrome.runtime.lastError.message)):s(a);});});return this.formatJson({id:i.id,focused:i.focused,incognito:i.incognito,alwaysOnTop:i.alwaysOnTop,state:i.state,type:i.type,left:i.left,top:i.top,width:i.width,height:i.height,sessionId:i.sessionId,tabs:i.tabs?.map(s=>({id:s.id,url:s.url,title:s.title,active:s.active,index:s.index}))})}async handleRemove(e){let{windowId:t}=this.removeSchema.parse(e);return await new Promise((r,o)=>{chrome.windows.remove(t,()=>{chrome.runtime.lastError?o(new Error(chrome.runtime.lastError.message)):r();});}),this.formatSuccess("Window removed successfully",{windowId:t})}async handleUpdate(e){let{windowId:t,drawAttention:r,focused:o,height:i,left:s,state:n,top:a,width:c}=this.updateSchema.parse(e),u={};r!==void 0&&(u.drawAttention=r),o!==void 0&&(u.focused=o),i!==void 0&&(u.height=i),s!==void 0&&(u.left=s),n!==void 0&&(u.state=n),a!==void 0&&(u.top=a),c!==void 0&&(u.width=c);let d=await new Promise((v,S)=>{chrome.windows.update(t,u,P=>{chrome.runtime.lastError?S(new Error(chrome.runtime.lastError.message)):v(P);});});return this.formatJson({id:d.id,focused:d.focused,incognito:d.incognito,alwaysOnTop:d.alwaysOnTop,state:d.state,type:d.type,left:d.left,top:d.top,width:d.width,height:d.height,sessionId:d.sessionId})}};var Xt=(p=>(p.ACCESSIBILITY_FEATURES="accessibilityFeatures",p.ACTION="action",p.ALARMS="alarms",p.AUDIO="audio",p.BOOKMARKS="bookmarks",p.BROWSING_DATA="browsingData",p.CERTIFICATE_PROVIDER="certificateProvider",p.COMMANDS="commands",p.CONTENT_SETTINGS="contentSettings",p.CONTEXT_MENUS="contextMenus",p.COOKIES="cookies",p.DEBUGGER="debugger",p.DECLARATIVE_CONTENT="declarativeContent",p.DECLARATIVE_NET_REQUEST="declarativeNetRequest",p.DESKTOP_CAPTURE="desktopCapture",p.DEVTOOLS_INSPECTED_WINDOW="devtools.inspectedWindow",p.DEVTOOLS_NETWORK="devtools.network",p.DEVTOOLS_PANELS="devtools.panels",p.DEVTOOLS_PERFORMANCE="devtools.performance",p.DEVTOOLS_RECORDER="devtools.recorder",p.DNS="dns",p.DOCUMENT_SCAN="documentScan",p.DOM="dom",p.DOWNLOADS="downloads",p.ENTERPRISE_DEVICE_ATTRIBUTES="enterprise.deviceAttributes",p.ENTERPRISE_HARDWARE_PLATFORM="enterprise.hardwarePlatform",p.ENTERPRISE_NETWORKING_ATTRIBUTES="enterprise.networkingAttributes",p.ENTERPRISE_PLATFORM_KEYS="enterprise.platformKeys",p.EVENTS="events",p.EXTENSION="extension",p.EXTENSION_TYPES="extensionTypes",p.FILE_BROWSER_HANDLER="fileBrowserHandler",p.FILE_SYSTEM_PROVIDER="fileSystemProvider",p.FONT_SETTINGS="fontSettings",p.GCM="gcm",p.HISTORY="history",p.I18N="i18n",p.IDENTITY="identity",p.IDLE="idle",p.INPUT_IME="input.ime",p.INSTANCE_ID="instanceID",p.LOGIN_STATE="loginState",p.MANAGEMENT="management",p.NOTIFICATIONS="notifications",p.OFFSCREEN="offscreen",p.OMNIBOX="omnibox",p.PAGE_CAPTURE="pageCapture",p.PERMISSIONS="permissions",p.PLATFORM_KEYS="platformKeys",p.POWER="power",p.PRINTER_PROVIDER="printerProvider",p.PRINTING="printing",p.PRINTING_METRICS="printingMetrics",p.PRIVACY="privacy",p.PROCESSES="processes",p.PROXY="proxy",p.READING_LIST="readingList",p.RUNTIME="runtime",p.SCRIPTING="scripting",p.SEARCH="search",p.SESSIONS="sessions",p.SIDE_PANEL="sidePanel",p.STORAGE="storage",p.SYSTEM_CPU="system.cpu",p.SYSTEM_DISPLAY="system.display",p.SYSTEM_MEMORY="system.memory",p.SYSTEM_STORAGE="system.storage",p.SYSTEM_LOG="systemLog",p.TAB_CAPTURE="tabCapture",p.TAB_GROUPS="tabGroups",p.TABS="tabs",p.TOP_SITES="topSites",p.TTS="tts",p.TTS_ENGINE="ttsEngine",p.TYPES="types",p.USER_SCRIPTS="userScripts",p.VPN_PROVIDER="vpnProvider",p.WALLPAPER="wallpaper",p.WEB_AUTHENTICATION_PROXY="webAuthenticationProxy",p.WEB_NAVIGATION="webNavigation",p.WEB_REQUEST="webRequest",p.WINDOWS="windows",p))(Xt||{}),br=z.enum(["all","chromeos"]),vr=z.enum(["stable","dev"]),yr=z.enum(["background","content","devtools","all"]),Oa=z.object({minChromeVersion:z.number().optional(),platform:br,channel:vr,manifestVersions:z.array(z.literal(2).or(z.literal(3))),requiresPolicy:z.boolean(),foregroundOnly:z.boolean(),contexts:z.array(yr),namespace:z.string()}),er={accessibilityFeatures:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"accessibilityFeatures"},action:{minChromeVersion:88,platform:"all",channel:"stable",manifestVersions:[3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"action"},alarms:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"alarms"},audio:{minChromeVersion:59,platform:"chromeos",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"audio"},bookmarks:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background","content"],namespace:"bookmarks"},browsingData:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"browsingData"},certificateProvider:{minChromeVersion:46,platform:"chromeos",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"certificateProvider"},commands:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"commands"},contentSettings:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"contentSettings"},contextMenus:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"contextMenus"},cookies:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background","content"],namespace:"cookies"},debugger:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"debugger"},declarativeContent:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"declarativeContent"},declarativeNetRequest:{minChromeVersion:84,platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"declarativeNetRequest"},desktopCapture:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"desktopCapture"},"devtools.inspectedWindow":{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["devtools"],namespace:"devtools.inspectedWindow"},"devtools.network":{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["devtools"],namespace:"devtools.network"},"devtools.panels":{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["devtools"],namespace:"devtools.panels"},"devtools.performance":{minChromeVersion:129,platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["devtools"],namespace:"devtools.performance"},"devtools.recorder":{minChromeVersion:105,platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["devtools"],namespace:"devtools.recorder"},dns:{platform:"all",channel:"dev",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"dns"},documentScan:{minChromeVersion:44,platform:"chromeos",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"documentScan"},dom:{minChromeVersion:88,platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["content"],namespace:"dom"},downloads:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"downloads"},"enterprise.deviceAttributes":{minChromeVersion:46,platform:"chromeos",channel:"stable",manifestVersions:[2,3],requiresPolicy:true,foregroundOnly:false,contexts:["background"],namespace:"enterprise.deviceAttributes"},"enterprise.hardwarePlatform":{minChromeVersion:71,platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:true,foregroundOnly:false,contexts:["background"],namespace:"enterprise.hardwarePlatform"},"enterprise.networkingAttributes":{minChromeVersion:85,platform:"chromeos",channel:"stable",manifestVersions:[2,3],requiresPolicy:true,foregroundOnly:false,contexts:["background"],namespace:"enterprise.networkingAttributes"},"enterprise.platformKeys":{platform:"chromeos",channel:"stable",manifestVersions:[2,3],requiresPolicy:true,foregroundOnly:false,contexts:["background"],namespace:"enterprise.platformKeys"},events:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["all"],namespace:"events"},extension:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["all"],namespace:"extension"},extensionTypes:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["all"],namespace:"extensionTypes"},fileBrowserHandler:{platform:"chromeos",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:true,contexts:["background"],namespace:"fileBrowserHandler"},fileSystemProvider:{platform:"chromeos",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"fileSystemProvider"},fontSettings:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"fontSettings"},gcm:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"gcm"},history:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background","content"],namespace:"history"},i18n:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["all"],namespace:"i18n"},identity:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"identity"},idle:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"idle"},"input.ime":{platform:"chromeos",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"input.ime"},instanceID:{minChromeVersion:44,platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"instanceID"},loginState:{minChromeVersion:78,platform:"chromeos",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"loginState"},management:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"management"},notifications:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"notifications"},offscreen:{minChromeVersion:109,platform:"all",channel:"stable",manifestVersions:[3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"offscreen"},omnibox:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"omnibox"},pageCapture:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"pageCapture"},permissions:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background","content"],namespace:"permissions"},platformKeys:{minChromeVersion:45,platform:"chromeos",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"platformKeys"},power:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"power"},printerProvider:{minChromeVersion:44,platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"printerProvider"},printing:{minChromeVersion:81,platform:"chromeos",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"printing"},printingMetrics:{minChromeVersion:79,platform:"chromeos",channel:"stable",manifestVersions:[2,3],requiresPolicy:true,foregroundOnly:false,contexts:["background"],namespace:"printingMetrics"},privacy:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"privacy"},processes:{platform:"all",channel:"dev",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"processes"},proxy:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"proxy"},readingList:{minChromeVersion:120,platform:"all",channel:"stable",manifestVersions:[3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"readingList"},runtime:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["all"],namespace:"runtime"},scripting:{minChromeVersion:88,platform:"all",channel:"stable",manifestVersions:[3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"scripting"},search:{minChromeVersion:87,platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"search"},sessions:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"sessions"},sidePanel:{minChromeVersion:114,platform:"all",channel:"stable",manifestVersions:[3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"sidePanel"},storage:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["all"],namespace:"storage"},"system.cpu":{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"system.cpu"},"system.display":{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"system.display"},"system.memory":{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"system.memory"},"system.storage":{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"system.storage"},systemLog:{minChromeVersion:125,platform:"chromeos",channel:"stable",manifestVersions:[2,3],requiresPolicy:true,foregroundOnly:false,contexts:["background"],namespace:"systemLog"},tabCapture:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"tabCapture"},tabGroups:{minChromeVersion:89,platform:"all",channel:"stable",manifestVersions:[3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"tabGroups"},tabs:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background","content"],namespace:"tabs"},topSites:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"topSites"},tts:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"tts"},ttsEngine:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"ttsEngine"},types:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["all"],namespace:"types"},userScripts:{minChromeVersion:120,platform:"all",channel:"stable",manifestVersions:[3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"userScripts"},vpnProvider:{minChromeVersion:43,platform:"chromeos",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"vpnProvider"},wallpaper:{minChromeVersion:43,platform:"chromeos",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"wallpaper"},webAuthenticationProxy:{minChromeVersion:115,platform:"all",channel:"stable",manifestVersions:[3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"webAuthenticationProxy"},webNavigation:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"webNavigation"},webRequest:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"webRequest"},windows:{platform:"all",channel:"stable",manifestVersions:[2,3],requiresPolicy:false,foregroundOnly:false,contexts:["background"],namespace:"windows"}};function wr(f,e,t,r="all",o){let i=er[f];return !(!i.contexts.includes(e)&&!i.contexts.includes("all")||!i.manifestVersions.includes(t)||i.platform!=="all"&&i.platform!==r||i.minChromeVersion&&o&&o<i.minChromeVersion)}function Ua(f){let t=er[f].namespace.split("."),r=chrome;for(let o of t)if(r=r?.[o],!r)return;return r}function La(f,e,t="all",r){return Object.values(Xt).filter(o=>wr(o,f,e,t,r))}
34
+ export{xe as AlarmsApiTools,Ie as AudioApiTools,rr as BOOKMARK_ACTIONS,m as BaseApiTools,Pe as BookmarksApiTools,ke as BrowsingDataApiTools,er as CHROME_API_REGISTRY,Ce as CertificateProviderApiTools,Xt as ChromeApi,Oa as ChromeApiMetadataSchema,vr as ChromeChannelSchema,yr as ChromeContextSchema,br as ChromePlatformSchema,De as CommandsApiTools,Oe as ContentSettingsApiTools,Ue as ContextMenusApiTools,Le as CookiesApiTools,Me as DebuggerApiTools,Ne as DeclarativeContentApiTools,qe as DeclarativeNetRequestApiTools,Ge as DesktopCaptureApiTools,Fe as DevtoolsInspectedWindowApiTools,Be as DevtoolsNetworkApiTools,We as DevtoolsPanelsApiTools,Je as DocumentScanApiTools,ze as DomApiTools,He as DownloadsApiTools,Ke as EnterpriseDeviceAttributesApiTools,$e as EnterpriseHardwarePlatformApiTools,Ze as EnterpriseNetworkingAttributesApiTools,Ye as EnterprisePlatformKeysApiTools,Qe as ExtensionApiTools,Xe as FileBrowserHandlerApiTools,et as FileSystemProviderApiTools,tt as FontSettingsApiTools,rt as GcmApiTools,sr as HISTORY_ACTIONS,it as HistoryApiTools,st as I18nApiTools,nt as IdentityApiTools,ct as IdleApiTools,lt as InputImeApiTools,dt as InstanceIDApiTools,mt as LoginStateApiTools,ht as ManagementApiTools,ut as NotificationsApiTools,pt as OffscreenApiTools,gt as OmniboxApiTools,bt as PageCaptureApiTools,vt as PermissionsApiTools,yt as PlatformKeysApiTools,wt as PowerApiTools,St as PrintingApiTools,Tt as PrintingMetricsApiTools,Et as ProxyApiTools,_t as ReadingListApiTools,At as RuntimeApiTools,lr as STORAGE_ACTIONS,xt as ScriptingApiTools,It as SearchApiTools,Rt as SessionsApiTools,Pt as SidePanelApiTools,Ct as StorageApiTools,Dt as SystemCpuApiTools,Ot as SystemLogApiTools,Ut as SystemMemoryApiTools,Mt as SystemStorageApiTools,pr as TAB_ACTIONS,hr as TAB_GROUP_ACTIONS,Nt as TabCaptureApiTools,Gt as TabGroupsApiTools,jt as TabsApiTools,Bt as TopSitesApiTools,Wt as TtsApiTools,Jt as TtsEngineApiTools,Vt as UserScriptsApiTools,zt as VpnProviderApiTools,gr as WINDOW_ACTIONS,Ht as WallpaperApiTools,Kt as WebAuthenticationProxyApiTools,$t as WebNavigationApiTools,Zt as WebRequestApiTools,Qt as WindowsApiTools,La as getAvailableApis,Ua as getChromeApiReference,wr as isApiAvailable};//# sourceMappingURL=index.js.map
35
35
  //# sourceMappingURL=index.js.map