@hanzo/browser-extension 1.9.56 → 1.9.59
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -0
- package/chrome/background.js +527 -0
- package/chrome/content-script.js +550 -0
- package/{src → chrome}/manifest.json +2 -12
- package/chrome/newtab.js +230 -0
- package/chrome/onboarding.js +31 -0
- package/chrome/page.js +35 -0
- package/{src → chrome}/popup.html +8 -0
- package/chrome/popup.js +48 -0
- package/chrome/sidebar.js +291 -0
- package/firefox/ai-worker.js +571 -0
- package/firefox/background.js +235 -0
- package/firefox/callback.html +17 -0
- package/firefox/content-script.js +550 -0
- package/firefox/icon128.png +0 -0
- package/firefox/icon16.png +0 -0
- package/firefox/icon48.png +0 -0
- package/{src/manifest-firefox.json → firefox/manifest.json} +2 -3
- package/firefox/newtab.css +543 -0
- package/firefox/newtab.html +13 -0
- package/firefox/newtab.js +230 -0
- package/firefox/onboarding.css +78 -0
- package/firefox/onboarding.html +45 -0
- package/firefox/onboarding.js +31 -0
- package/firefox/page.js +35 -0
- package/firefox/popup.css +761 -0
- package/firefox/popup.html +413 -0
- package/firefox/popup.js +48 -0
- package/firefox/sidebar.css +1350 -0
- package/firefox/sidebar.html +388 -0
- package/firefox/sidebar.js +291 -0
- package/package.json +4 -53
- package/manifest.json +0 -34
- package/src/Chat.tsx +0 -164
- package/src/answer/AnswerEngine.tsx +0 -410
- package/src/answer/Mark.tsx +0 -14
- package/src/answer/Rail.tsx +0 -95
- package/src/answer/Stories.tsx +0 -27
- package/src/answer/Toolbar.tsx +0 -93
- package/src/answer/WidgetView.tsx +0 -136
- package/src/icon128.png +0 -0
- package/src/icon16.png +0 -0
- package/src/icon32.png +0 -0
- package/src/icon48.png +0 -0
- package/src/package.json +0 -41
- package/src/safari/SafariWebExtensionHandler.swift +0 -153
- package/src/shared/Prose.tsx +0 -29
- package/src/webgpu.d.ts +0 -131
- /package/{src → chrome}/ai-worker.js +0 -0
- /package/{src → chrome}/callback.html +0 -0
- /package/{images → chrome}/icon128.png +0 -0
- /package/{images → chrome}/icon16.png +0 -0
- /package/{images → chrome}/icon48.png +0 -0
- /package/{src → chrome}/newtab.css +0 -0
- /package/{src → chrome}/newtab.html +0 -0
- /package/{src → chrome}/onboarding.css +0 -0
- /package/{src → chrome}/onboarding.html +0 -0
- /package/{src → chrome}/popup.css +0 -0
- /package/{src → chrome}/sidebar.css +0 -0
- /package/{src → chrome}/sidebar.html +0 -0
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
"use strict";(()=>{var or=Object.create;var qe=Object.defineProperty;var sr=Object.getOwnPropertyDescriptor;var ar=Object.getOwnPropertyNames;var ir=Object.getPrototypeOf,cr=Object.prototype.hasOwnProperty;var lr=(e,n)=>()=>{try{return n||e((n={exports:{}}).exports,n),n.exports}catch(t){throw n=0,t}};var ur=(e,n,t,r)=>{if(n&&typeof n=="object"||typeof n=="function")for(let o of ar(n))!cr.call(e,o)&&o!==t&&qe(e,o,{get:()=>n[o],enumerable:!(r=sr(n,o))||r.enumerable});return e};var dr=(e,n,t)=>(t=e!=null?or(ir(e)):{},ur(n||!e||!e.__esModule?qe(t,"default",{value:e,enumerable:!0}):t,e));var Ze=lr((ke,We)=>{(function(e,n){if(typeof define=="function"&&define.amd)define("webextension-polyfill",["module"],n);else if(typeof ke<"u")n(We);else{var t={exports:{}};n(t),e.browser=t.exports}})(typeof globalThis<"u"?globalThis:typeof self<"u"?self:ke,function(e){"use strict";if(!(globalThis.chrome&&globalThis.chrome.runtime&&globalThis.chrome.runtime.id))throw new Error("This script should only be loaded in a browser extension.");if(globalThis.browser&&globalThis.browser.runtime&&globalThis.browser.runtime.id)e.exports=globalThis.browser;else{let n="The message port closed before a response was received.",t=r=>{let o={alarms:{clear:{minArgs:0,maxArgs:1},clearAll:{minArgs:0,maxArgs:0},get:{minArgs:0,maxArgs:1},getAll:{minArgs:0,maxArgs:0}},bookmarks:{create:{minArgs:1,maxArgs:1},get:{minArgs:1,maxArgs:1},getChildren:{minArgs:1,maxArgs:1},getRecent:{minArgs:1,maxArgs:1},getSubTree:{minArgs:1,maxArgs:1},getTree:{minArgs:0,maxArgs:0},move:{minArgs:2,maxArgs:2},remove:{minArgs:1,maxArgs:1},removeTree:{minArgs:1,maxArgs:1},search:{minArgs:1,maxArgs:1},update:{minArgs:2,maxArgs:2}},browserAction:{disable:{minArgs:0,maxArgs:1,fallbackToNoCallback:!0},enable:{minArgs:0,maxArgs:1,fallbackToNoCallback:!0},getBadgeBackgroundColor:{minArgs:1,maxArgs:1},getBadgeText:{minArgs:1,maxArgs:1},getPopup:{minArgs:1,maxArgs:1},getTitle:{minArgs:1,maxArgs:1},openPopup:{minArgs:0,maxArgs:0},setBadgeBackgroundColor:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},setBadgeText:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},setIcon:{minArgs:1,maxArgs:1},setPopup:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},setTitle:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0}},browsingData:{remove:{minArgs:2,maxArgs:2},removeCache:{minArgs:1,maxArgs:1},removeCookies:{minArgs:1,maxArgs:1},removeDownloads:{minArgs:1,maxArgs:1},removeFormData:{minArgs:1,maxArgs:1},removeHistory:{minArgs:1,maxArgs:1},removeLocalStorage:{minArgs:1,maxArgs:1},removePasswords:{minArgs:1,maxArgs:1},removePluginData:{minArgs:1,maxArgs:1},settings:{minArgs:0,maxArgs:0}},commands:{getAll:{minArgs:0,maxArgs:0}},contextMenus:{remove:{minArgs:1,maxArgs:1},removeAll:{minArgs:0,maxArgs:0},update:{minArgs:2,maxArgs:2}},cookies:{get:{minArgs:1,maxArgs:1},getAll:{minArgs:1,maxArgs:1},getAllCookieStores:{minArgs:0,maxArgs:0},remove:{minArgs:1,maxArgs:1},set:{minArgs:1,maxArgs:1}},devtools:{inspectedWindow:{eval:{minArgs:1,maxArgs:2,singleCallbackArg:!1}},panels:{create:{minArgs:3,maxArgs:3,singleCallbackArg:!0},elements:{createSidebarPane:{minArgs:1,maxArgs:1}}}},downloads:{cancel:{minArgs:1,maxArgs:1},download:{minArgs:1,maxArgs:1},erase:{minArgs:1,maxArgs:1},getFileIcon:{minArgs:1,maxArgs:2},open:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},pause:{minArgs:1,maxArgs:1},removeFile:{minArgs:1,maxArgs:1},resume:{minArgs:1,maxArgs:1},search:{minArgs:1,maxArgs:1},show:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0}},extension:{isAllowedFileSchemeAccess:{minArgs:0,maxArgs:0},isAllowedIncognitoAccess:{minArgs:0,maxArgs:0}},history:{addUrl:{minArgs:1,maxArgs:1},deleteAll:{minArgs:0,maxArgs:0},deleteRange:{minArgs:1,maxArgs:1},deleteUrl:{minArgs:1,maxArgs:1},getVisits:{minArgs:1,maxArgs:1},search:{minArgs:1,maxArgs:1}},i18n:{detectLanguage:{minArgs:1,maxArgs:1},getAcceptLanguages:{minArgs:0,maxArgs:0}},identity:{launchWebAuthFlow:{minArgs:1,maxArgs:1}},idle:{queryState:{minArgs:1,maxArgs:1}},management:{get:{minArgs:1,maxArgs:1},getAll:{minArgs:0,maxArgs:0},getSelf:{minArgs:0,maxArgs:0},setEnabled:{minArgs:2,maxArgs:2},uninstallSelf:{minArgs:0,maxArgs:1}},notifications:{clear:{minArgs:1,maxArgs:1},create:{minArgs:1,maxArgs:2},getAll:{minArgs:0,maxArgs:0},getPermissionLevel:{minArgs:0,maxArgs:0},update:{minArgs:2,maxArgs:2}},pageAction:{getPopup:{minArgs:1,maxArgs:1},getTitle:{minArgs:1,maxArgs:1},hide:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},setIcon:{minArgs:1,maxArgs:1},setPopup:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},setTitle:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},show:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0}},permissions:{contains:{minArgs:1,maxArgs:1},getAll:{minArgs:0,maxArgs:0},remove:{minArgs:1,maxArgs:1},request:{minArgs:1,maxArgs:1}},runtime:{getBackgroundPage:{minArgs:0,maxArgs:0},getPlatformInfo:{minArgs:0,maxArgs:0},openOptionsPage:{minArgs:0,maxArgs:0},requestUpdateCheck:{minArgs:0,maxArgs:0},sendMessage:{minArgs:1,maxArgs:3},sendNativeMessage:{minArgs:2,maxArgs:2},setUninstallURL:{minArgs:1,maxArgs:1}},sessions:{getDevices:{minArgs:0,maxArgs:1},getRecentlyClosed:{minArgs:0,maxArgs:1},restore:{minArgs:0,maxArgs:1}},storage:{local:{clear:{minArgs:0,maxArgs:0},get:{minArgs:0,maxArgs:1},getBytesInUse:{minArgs:0,maxArgs:1},remove:{minArgs:1,maxArgs:1},set:{minArgs:1,maxArgs:1}},managed:{get:{minArgs:0,maxArgs:1},getBytesInUse:{minArgs:0,maxArgs:1}},sync:{clear:{minArgs:0,maxArgs:0},get:{minArgs:0,maxArgs:1},getBytesInUse:{minArgs:0,maxArgs:1},remove:{minArgs:1,maxArgs:1},set:{minArgs:1,maxArgs:1}}},tabs:{captureVisibleTab:{minArgs:0,maxArgs:2},create:{minArgs:1,maxArgs:1},detectLanguage:{minArgs:0,maxArgs:1},discard:{minArgs:0,maxArgs:1},duplicate:{minArgs:1,maxArgs:1},executeScript:{minArgs:1,maxArgs:2},get:{minArgs:1,maxArgs:1},getCurrent:{minArgs:0,maxArgs:0},getZoom:{minArgs:0,maxArgs:1},getZoomSettings:{minArgs:0,maxArgs:1},goBack:{minArgs:0,maxArgs:1},goForward:{minArgs:0,maxArgs:1},highlight:{minArgs:1,maxArgs:1},insertCSS:{minArgs:1,maxArgs:2},move:{minArgs:2,maxArgs:2},query:{minArgs:1,maxArgs:1},reload:{minArgs:0,maxArgs:2},remove:{minArgs:1,maxArgs:1},removeCSS:{minArgs:1,maxArgs:2},sendMessage:{minArgs:2,maxArgs:3},setZoom:{minArgs:1,maxArgs:2},setZoomSettings:{minArgs:1,maxArgs:2},update:{minArgs:1,maxArgs:2}},topSites:{get:{minArgs:0,maxArgs:0}},webNavigation:{getAllFrames:{minArgs:1,maxArgs:1},getFrame:{minArgs:1,maxArgs:1}},webRequest:{handlerBehaviorChanged:{minArgs:0,maxArgs:0}},windows:{create:{minArgs:0,maxArgs:1},get:{minArgs:1,maxArgs:2},getAll:{minArgs:0,maxArgs:1},getCurrent:{minArgs:0,maxArgs:1},getLastFocused:{minArgs:0,maxArgs:1},remove:{minArgs:1,maxArgs:1},update:{minArgs:2,maxArgs:2}}};if(Object.keys(o).length===0)throw new Error("api-metadata.json has not been included in browser-polyfill");class s extends WeakMap{constructor(b,w=void 0){super(w),this.createItem=b}get(b){return this.has(b)||this.set(b,this.createItem(b)),super.get(b)}}let a=f=>f&&typeof f=="object"&&typeof f.then=="function",i=(f,b)=>(...w)=>{r.runtime.lastError?f.reject(new Error(r.runtime.lastError.message)):b.singleCallbackArg||w.length<=1&&b.singleCallbackArg!==!1?f.resolve(w[0]):f.resolve(w)},c=f=>f==1?"argument":"arguments",l=(f,b)=>function(A,...T){if(T.length<b.minArgs)throw new Error(`Expected at least ${b.minArgs} ${c(b.minArgs)} for ${f}(), got ${T.length}`);if(T.length>b.maxArgs)throw new Error(`Expected at most ${b.maxArgs} ${c(b.maxArgs)} for ${f}(), got ${T.length}`);return new Promise((U,N)=>{if(b.fallbackToNoCallback)try{A[f](...T,i({resolve:U,reject:N},b))}catch(v){console.warn(`${f} API method doesn't seem to support the callback parameter, falling back to call it without a callback: `,v),A[f](...T),b.fallbackToNoCallback=!1,b.noCallback=!0,U()}else b.noCallback?(A[f](...T),U()):A[f](...T,i({resolve:U,reject:N},b))})},u=(f,b,w)=>new Proxy(b,{apply(A,T,U){return w.call(T,f,...U)}}),g=Function.call.bind(Object.prototype.hasOwnProperty),d=(f,b={},w={})=>{let A=Object.create(null),T={has(N,v){return v in f||v in A},get(N,v,O){if(v in A)return A[v];if(!(v in f))return;let S=f[v];if(typeof S=="function")if(typeof b[v]=="function")S=u(f,f[v],b[v]);else if(g(w,v)){let Y=l(v,w[v]);S=u(f,f[v],Y)}else S=S.bind(f);else if(typeof S=="object"&&S!==null&&(g(b,v)||g(w,v)))S=d(S,b[v],w[v]);else if(g(w,"*"))S=d(S,b[v],w["*"]);else return Object.defineProperty(A,v,{configurable:!0,enumerable:!0,get(){return f[v]},set(Y){f[v]=Y}}),S;return A[v]=S,S},set(N,v,O,S){return v in A?A[v]=O:f[v]=O,!0},defineProperty(N,v,O){return Reflect.defineProperty(A,v,O)},deleteProperty(N,v){return Reflect.deleteProperty(A,v)}},U=Object.create(f);return new Proxy(U,T)},m=f=>({addListener(b,w,...A){b.addListener(f.get(w),...A)},hasListener(b,w){return b.hasListener(f.get(w))},removeListener(b,w){b.removeListener(f.get(w))}}),h=new s(f=>typeof f!="function"?f:function(w){let A=d(w,{},{getContent:{minArgs:0,maxArgs:0}});f(A)}),p=new s(f=>typeof f!="function"?f:function(w,A,T){let U=!1,N,v=new Promise(re=>{N=function(R){U=!0,re(R)}}),O;try{O=f(w,A,N)}catch(re){O=Promise.reject(re)}let S=O!==!0&&a(O);if(O!==!0&&!S&&!U)return!1;let Y=re=>{re.then(R=>{T(R)},R=>{let Ae;R&&(R instanceof Error||typeof R.message=="string")?Ae=R.message:Ae="An unexpected error occurred",T({__mozWebExtensionPolyfillReject__:!0,message:Ae})}).catch(R=>{console.error("Failed to send onMessage rejected reply",R)})};return Y(S?O:v),!0}),I=({reject:f,resolve:b},w)=>{r.runtime.lastError?r.runtime.lastError.message===n?b():f(new Error(r.runtime.lastError.message)):w&&w.__mozWebExtensionPolyfillReject__?f(new Error(w.message)):b(w)},P=(f,b,w,...A)=>{if(A.length<b.minArgs)throw new Error(`Expected at least ${b.minArgs} ${c(b.minArgs)} for ${f}(), got ${A.length}`);if(A.length>b.maxArgs)throw new Error(`Expected at most ${b.maxArgs} ${c(b.maxArgs)} for ${f}(), got ${A.length}`);return new Promise((T,U)=>{let N=I.bind(null,{resolve:T,reject:U});A.push(N),w.sendMessage(...A)})},V={devtools:{network:{onRequestFinished:m(h)}},runtime:{onMessage:m(p),onMessageExternal:m(p),sendMessage:P.bind(null,"sendMessage",{minArgs:1,maxArgs:3})},tabs:{sendMessage:P.bind(null,"sendMessage",{minArgs:2,maxArgs:3})}},B={clear:{minArgs:1,maxArgs:1},get:{minArgs:1,maxArgs:1},set:{minArgs:1,maxArgs:1}};return o.privacy={network:{"*":B},services:{"*":B},websites:{"*":B}},d(r,V,o)};e.exports=t(chrome)}})});var Ko=dr(Ze());var J=new TextEncoder,q=new TextDecoder;function gr(e,n,t,r=new Uint8Array(0)){let o=J.encode(n),s=J.encode(t),a=11+o.length+s.length+r.length,i=new Uint8Array(4+a),c=new DataView(i.buffer);return c.setUint32(0,a,!0),c.setUint8(4,e),c.setUint16(5,0,!0),c.setUint16(7,o.length,!0),c.setUint16(9,s.length,!0),c.setUint32(11,r.length,!0),i.set(o,15),i.set(s,15+o.length),i.set(r,15+o.length+s.length),i}function Je(e){let n=new DataView(e.buffer,e.byteOffset,e.byteLength);if(e.length<15||n.getUint32(0,!0)!==e.length-4)throw new Error("not one whole frame");let t=n.getUint16(7,!0),r=n.getUint16(9,!0),o=n.getUint32(11,!0);if(15+t+r+o!==e.length)throw new Error("frame length disagrees with its fields");return{t:n.getUint8(4),flags:n.getUint16(5,!0),from:q.decode(e.subarray(15,15+t)),to:q.decode(e.subarray(15+t,15+t+r)),payload:e.slice(15+t+r)}}function _e(e,n){e.push(n&255,n>>8&255)}function Ye(e,n){let t=J.encode(n);_e(e,t.length);for(let r=0;r<t.length;r++)e.push(t[r])}function Ee(e,n,t){let r=[e];Ye(r,n),_e(r,t.length);for(let o of t)Ye(r,o);return _e(r,0),new Uint8Array(r)}function mr(e){let n=new DataView(e.buffer,e.byteOffset,e.byteLength),t=0,r=n.getUint16(t,!0);t+=2;let o=q.decode(e.subarray(t,t+r));t+=r;let s=n.getUint16(t,!0);t+=2;let a={};for(let i=0;i<s;i++){let c=n.getUint16(t,!0);t+=2;let l=q.decode(e.subarray(t,t+c));t+=c;let u=n.getUint32(t,!0);t+=4,a[l]=q.decode(e.subarray(t,t+u)),t+=u}return{method:o,params:a}}function hr(e){let n=new DataView(e.buffer,e.byteOffset,e.byteLength),t=0,r=()=>{let a=n.getUint16(t,!0);t+=2;let i=q.decode(e.subarray(t,t+a));return t+=a,i},o=n.getUint16(t,!0);t+=2;let s=[];for(let a=0;a<o;a++){let i=r(),c=n.getUint8(t);t+=1;let l=r(),u=n.getUint16(t,!0);t+=2;let g=[];for(let h=0;h<u;h++)g.push(r());let d=n.getUint16(t,!0);t+=2;let m={};for(let h=0;h<d;h++){let p=r();m[p]=r()}s.push({id:i,role:c,brand:l,caps:g,attrs:m})}return s}function Se(e){let n=/^ws:\/\/127\.0\.0\.1:(\d{1,5})\/#([0-9a-f]{64})$/.exec(e.trim());if(!n)return null;let t=Number(n[1]);if(t<1||t>65535)return null;let r=new Uint8Array(32);for(let o=0;o<32;o++)r[o]=parseInt(n[2].slice(2*o,2*o+2),16);return{url:`ws://127.0.0.1:${t}/`,key:r}}async function Ge(e,n){return crypto.subtle.importKey("raw",e,{name:"HMAC",hash:"SHA-256"},!1,[n])}function Xe(e,n,t){let r=J.encode(e),o=new Uint8Array(r.length+n.length+t.length);return o.set(r,0),o.set(n,r.length),o.set(t,r.length+n.length),o}async function fr(e,n,t,r){return new Uint8Array(await crypto.subtle.sign("HMAC",await Ge(e,"sign"),Xe(n,t,r)))}async function pr(e,n,t,r,o){return crypto.subtle.verify("HMAC",await Ge(e,"verify"),new Uint8Array(o),Xe(n,t,r))}var br="ai.hanzo.zap";function Qe(e){return{connected:!1,socket:null,authed:!1,since:0,providerId:e,caps:[],probedAt:0,pairing:null,native:null,error:"",timer:null,backoff:250}}function K(e,n,t,r,o=""){e.send(gr(n,o,t,r))}function Te(e){e.connected=!1,e.caps=[]}function F(e){let n=e.socket;if(e.socket=null,e.authed=!1,e.probedAt=0,Te(e),n)try{n.close()}catch{}}function ne(e,n,t){e.timer&&clearTimeout(e.timer),e.timer=setTimeout(()=>{e.timer=null,W(e,n)},t)}function Pe(e,n,t){e.pairing=n,e.error="",e.backoff=250,F(e),W(e,t)}function et(e,n,t,r){switch(t.t){case 2:t.to&&(e.providerId=t.to),e.error="",e.backoff=250,e.probedAt=Date.now(),K(n,3,"");break;case 4:{e.probedAt=0;let o=hr(t.payload).find(s=>s.id===e.providerId);!!o!==e.connected&&r.log(`[Hanzo/ZAP] ${o?"registered":"dropped by router"} (${n.kind}): ${e.providerId}`),e.connected=!!o,e.caps=o?o.caps:[];break}case 7:r.log("[Hanzo/ZAP] "+q.decode(t.payload));break;case 16:_r(e,n,t,r);break;default:break}}function xe(e,n,t){F(e),n.log(`[Hanzo/ZAP] ${t}; retrying in ${e.backoff} ms`),ne(e,n,e.backoff),e.backoff=Math.min(e.backoff*2,3e4)}function yr(e){let n="";for(let t=0;t<e.length;t+=32768)n+=String.fromCharCode(...e.subarray(t,t+32768));return btoa(n)}function wr(e){let n=atob(e),t=new Uint8Array(n.length);for(let r=0;r<n.length;r++)t[r]=n.charCodeAt(r);return t}function vr(){let e=globalThis.chrome?.runtime;return e&&typeof e.connectNative=="function"?e.connectNative.bind(e):null}function Ar(e,n){let t=vr();if(!t)return e.native=!1,!1;let r;try{r=t(br)}catch(a){return e.native=!1,n.log("[Hanzo/ZAP] no native host: "+(a?.message||a)),!1}let o={kind:"native",send:a=>r.postMessage({z:yr(a)}),close:()=>{try{r.disconnect()}catch{}}};e.socket=o,e.since=Date.now(),e.authed=!0,e.probedAt=0,Te(e);let s=!1;return r.onMessage.addListener(a=>{if(e.socket!==o||typeof a?.z!="string")return;s=!0,e.native=!0;let i;try{i=Je(wr(a.z))}catch{xe(e,n,"native host sent a malformed frame");return}et(e,o,i,n)}),r.onDisconnect.addListener(()=>{if(e.socket!==o)return;let a=String(globalThis.chrome?.runtime?.lastError?.message||"");if(!s&&/not found|forbidden|not allowed|native messaging host/i.test(a)){e.native=!1,e.error=e.pairing?"":"no-router",F(e),n.log("[Hanzo/ZAP] native host unavailable ("+a+")"+(e.pairing?" \u2014 using the paired door":"")),W(e,n);return}xe(e,n,"native host exited"+(a?": "+a:""))}),K(o,1,"",Ee(1,n.brand,n.caps),e.providerId),!0}function kr(e,n,t){let r;try{r=new WebSocket(t.url)}catch(c){n.log("[Hanzo/ZAP] cannot open "+t.url+": "+(c?.message||c));return}r.binaryType="arraybuffer";let o={kind:"door",send:c=>r.send(c),close:()=>r.close()};e.socket=o,e.since=Date.now(),e.authed=!1,e.probedAt=0,Te(e);let s=crypto.getRandomValues(new Uint8Array(32)),a=!1,i=!1;r.onopen=()=>{a=!0,K(o,8,"",s)},r.onmessage=async c=>{if(e.socket!==o)return;let l;try{l=Je(new Uint8Array(c.data))}catch{F(e);return}if(!e.authed){if(l.t!==8||l.payload.length!==64){F(e);return}let u=l.payload.slice(0,32);if(!await pr(t.key,"zap router",s,u,l.payload.slice(32))){e.error="mismatch",n.log("[Hanzo/ZAP] the router on "+t.url+" does not hold our pairing token \u2014 pair again"),F(e);return}if(e.socket!==o)return;i=!0,K(o,8,"",await fr(t.key,"zap client",s,u)),e.authed=!0,K(o,1,"",Ee(1,n.brand,n.caps),e.providerId);return}et(e,o,l,n)},r.onclose=()=>{e.socket===o&&(!i&&e.error!=="mismatch"&&(e.error=a?"refused":"no-router"),xe(e,n,"door closed"))}}async function _r(e,n,t,r){let o;try{let{method:s,params:a}=mr(t.payload),i=await r.dispatch(s,a);o=J.encode(typeof i=="string"?i:JSON.stringify(i??null))}catch(s){o=J.encode("ERR:"+(s?.message||String(s)))}if(e.socket===n)try{K(n,17,t.from,o)}catch{}}function W(e,n){let t=e.socket;if(!t){if(e.native!==!1&&Ar(e,n)){ne(e,n,2e4);return}if(e.pairing){kr(e,n,e.pairing),ne(e,n,2e4);return}e.timer&&(clearTimeout(e.timer),e.timer=null);return}let r=Date.now();if(!e.authed&&r-e.since>5e3||e.probedAt&&r-e.probedAt>5e3){n.log("[Hanzo/ZAP] router is not answering \u2014 reconnecting"),F(e),W(e,n);return}if(!e.authed){ne(e,n,5e3);return}try{e.connected||K(t,1,"",Ee(1,n.brand,n.caps),e.providerId),e.probedAt||(e.probedAt=Date.now()),K(t,3,"")}catch{F(e)}ne(e,n,2e4)}var xr="Only for a browser that cannot start a native host (snap, Flatpak): run `hanzo-mcp pair` on this computer and paste the code it prints.";function tt(e){let n=Qe(""),t=!1,r=(async()=>{let o=await e.storage.get(["zapPairing","zapName"]),s=o.zapName;if(!s){let a=crypto.getRandomValues(new Uint8Array(2));s=`${e.engine}-${Array.from(a,i=>i.toString(16).padStart(2,"0")).join("")}`,await e.storage.set({zapName:s})}n.providerId=`browser/${s}`,n.pairing=typeof o.zapPairing=="string"?Se(o.zapPairing):null,t=!0,W(n,e)})();return{state:n,tick(){t&&W(n,e)},handle(o,s,a){switch(o){case"zap.status":return a({success:!0,zap:{connected:n.connected,transport:n.socket?.kind??"",native:n.native,paired:!!n.pairing,providerId:n.providerId,caps:n.caps,error:n.error}}),!0;case"zap.pair":{let i=String(s?.code??"").trim(),c=Se(i);return c?(r.then(()=>e.storage.set({zapPairing:i})).then(()=>{Pe(n,c,e),a({success:!0})}),!0):(a({success:!1,error:`Not a pairing code. ${xr}`}),!0)}case"zap.unpair":return r.then(()=>e.storage.remove("zapPairing")).then(()=>{Pe(n,null,e),a({success:!0})}),!0;default:return!1}}}}var G=(e,n)=>n.startsWith("~/")?`${e.homeDir()}/${n.slice(2)}`:n,oe=async(e,n)=>{let t=await e.readTextFile(G(e,n));if(t!==void 0)try{return JSON.parse(t)}catch{return}};var Er=(e,n)=>n==="auto"?!0:n==="web"?e==="web":n==="cli"?e==="cli"||e==="localProbe":n==="oauth"?e==="oauth":e==="apiToken",C=(e,n)=>e.filter(t=>Er(t.kind,n)),rt=async(e,n)=>{let t=[],r;for(let o of e.strategies(n.sourceMode)){if(!await o.isAvailable(n)){t.push({strategyId:o.id,ok:!1,skipped:!0});continue}try{let s=await o.fetch(n);return t.push({strategyId:o.id,ok:!0}),{result:s,attempts:t}}catch(s){if(t.push({strategyId:o.id,ok:!1,error:s instanceof Error?s.message:String(s)}),r=s,!(o.shouldFallback?.(s,n)??!0))break}}return{error:r??new Error(`${e.id}: no strategy available`),attempts:t}};var nt=e=>e.host.env("CODEX_HOME")??G(e.host,"~/.codex"),Ie=e=>{if(!(!e||typeof e.used_percent!="number"))return{usedPercent:e.used_percent,windowMinutes:e.limit_window_seconds?Math.round(e.limit_window_seconds/60):void 0,resetsAt:e.reset_at?new Date(e.reset_at*1e3).toISOString():void 0}},Sr={id:"codex.oauth",kind:"oauth",async isAvailable(e){return!!(await oe(e.host,`${nt(e)}/auth.json`))?.tokens?.access_token},async fetch(e){let n=await oe(e.host,`${nt(e)}/auth.json`),t=n?.tokens?.access_token;if(!t)throw new Error("codex: no access token in auth.json");let r={Authorization:`Bearer ${t}`,Accept:"application/json","User-Agent":"HanzoUsage"};n?.tokens?.account_id&&(r["ChatGPT-Account-Id"]=n.tokens.account_id);let o=await e.host.http({url:"https://chatgpt.com/backend-api/wham/usage",headers:r,timeoutMs:3e4});if(o.status!==200)throw new Error(`codex usage HTTP ${o.status}`);let s=JSON.parse(o.text),a=e.host.now().toISOString(),i={providerId:"codex",primary:Ie(s.rate_limit?.primary_window),secondary:Ie(s.rate_limit?.secondary_window),extraRateWindows:(s.additional_rate_limits??[]).map(l=>{let u=Ie(l.rate_limit?.primary_window);if(!(!u||!l.limit_name))return{id:l.limit_name,title:l.limit_name,window:u,usageKnown:!0}}).filter(l=>!!l),identity:{providerId:"codex",plan:s.plan_type,loginMethod:"oauth"},dataConfidence:"percentOnly",updatedAt:a},c;return s.credits?.has_credits&&(c={remaining:s.credits.balance??0,unlimited:s.credits.unlimited,updatedAt:a}),{usage:i,credits:c,sourceLabel:"OpenAI OAuth",strategyId:this.id,strategyKind:this.kind}}},se={id:"codex",metadata:{displayName:"Codex",sessionLabel:"5h limit",weeklyLabel:"Weekly limit",supportsCredits:!0,defaultEnabled:!0,dashboardUrl:"https://chatgpt.com/codex/settings/usage",statusPageUrl:"https://status.openai.com",color:"#10a37f"},strategies:e=>C([Sr],e)};var Tr={five_hour:300,seven_day:10080,seven_day_sonnet:10080,seven_day_opus:10080},Le=(e,n)=>{let t=n?.utilization??n?.used_percent;if(typeof t=="number")return{usedPercent:t,windowMinutes:Tr[e],resetsAt:n?.resets_at}},st=(e,n,t,r)=>{let o=[];for(let[s,a]of[["seven_day_sonnet","Sonnet weekly"],["seven_day_opus","Opus weekly"]]){let i=Le(s,e[s]);i&&o.push({id:s,title:a,window:i,usageKnown:!0})}return{providerId:"claude",primary:Le("five_hour",e.five_hour),secondary:Le("seven_day",e.seven_day),extraRateWindows:o.length?o:void 0,identity:{providerId:"claude",plan:r??e.subscriptionType??e.rate_limit_tier,loginMethod:t},providerCost:e.extra_usage&&typeof e.extra_usage.used_cents=="number"?{used:e.extra_usage.used_cents/100,limit:typeof e.extra_usage.limit_cents=="number"?e.extra_usage.limit_cents/100:void 0,currencyCode:"USD",period:"monthly",updatedAt:n}:void 0,dataConfidence:"percentOnly",updatedAt:n}},Pr=["~/.claude/.credentials.json","~/.config/claude/.credentials.json"],ot=async e=>{for(let n of Pr){let t=await oe(e.host,n);if(t?.claudeAiOauth?.accessToken)return t.claudeAiOauth}},Ir={id:"claude.oauth",kind:"oauth",async isAvailable(e){return!!await ot(e)},async fetch(e){let n=await ot(e);if(!n?.accessToken)throw new Error("claude: no OAuth credentials");let t=await e.host.http({url:"https://api.anthropic.com/api/oauth/usage",headers:{Authorization:`Bearer ${n.accessToken}`,"anthropic-beta":"oauth-2025-04-20",Accept:"application/json"},timeoutMs:3e4});if(t.status!==200)throw new Error(`claude usage HTTP ${t.status}`);let r=JSON.parse(t.text);return{usage:st(r,e.host.now().toISOString(),"oauth",n.subscriptionType),sourceLabel:"Claude OAuth",strategyId:this.id,strategyKind:this.kind}}},Lr={id:"claude.web",kind:"web",async isAvailable(e){return typeof e.settings?.cookieHeader=="string"},async fetch(e){let n=String(e.settings?.cookieHeader),t=async a=>{let i=await e.host.http({url:`https://claude.ai/api${a}`,headers:{Cookie:n,Accept:"application/json"},timeoutMs:3e4});if(i.status!==200)throw new Error(`claude.ai${a} HTTP ${i.status}`);return JSON.parse(i.text)},o=(await t("/organizations"))[0]?.uuid;if(!o)throw new Error("claude: no organization for session");let s=await t(`/organizations/${o}/usage`);return{usage:st(s,e.host.now().toISOString(),"web"),sourceLabel:"claude.ai session",strategyId:this.id,strategyKind:this.kind}}},X={id:"claude",metadata:{displayName:"Claude",sessionLabel:"Session (5h)",weeklyLabel:"Weekly limit",defaultEnabled:!0,dashboardUrl:"https://claude.ai/settings/usage",statusPageUrl:"https://status.anthropic.com",color:"#d97757"},strategies:e=>C([Ir,Lr],e)};var Q=e=>typeof e=="number"&&Number.isFinite(e)?e:0,Mr={id:"hanzo.cloud",kind:"apiToken",async isAvailable(e){return!!(e.settings?.getToken||e.settings?.apiKey)},async fetch(e){let n=e.settings?.baseUrl??"https://api.hanzo.ai",t=await e.settings?.getToken?.()??e.settings?.apiKey;if(!t)throw new Error("hanzo: no token for cloud usage");let r=await e.host.http({url:`${n}/v1/billing/usage`,headers:{Authorization:`Bearer ${t}`,Accept:"application/json"},timeoutMs:3e4});if(r.status!==200)throw new Error(`hanzo billing usage HTTP ${r.status}`);let o=JSON.parse(r.text),s=Array.isArray(o.usage)?o.usage:Array.isArray(o.data)?o.data:[],a=Q(o.total_tokens??o.totalTokens),i=Q(o.spend_cents??o.spendCents),c=Q(o.total_requests??o.requests);for(let g of s)a+=Q(g.total_tokens??g.totalTokens??g.tokens),i+=Q(g.spend_cents??g.spendCents??g.cost_cents),c+=Q(g.requests??g.request_count??1)-(g.requests===void 0&&g.request_count===void 0?1:0);let l=e.host.now().toISOString();return{usage:{providerId:"hanzo",identity:{providerId:"hanzo",loginMethod:"iam"},providerCost:{used:i/100,currencyCode:"USD",period:"monthly",updatedAt:l},totals:{tokens:a,requests:c},dataConfidence:"exact",updatedAt:l},sourceLabel:"Hanzo Cloud",strategyId:this.id,strategyKind:this.kind}}},at=async e=>{let n=[e.host.env("HANZO_HOME"),e.host.env("CODEX_HOME"),G(e.host,"~/.hanzo"),G(e.host,"~/.codex")].filter(t=>!!t);for(let t of n)if((await e.host.listDir(`${t}/sessions`)).length>0)return t},Me=e=>e.filter(n=>/^\d+$/.test(n)).sort().at(-1),it=(e,n)=>{if(!(!e||typeof e.used_percent!="number"))return{usedPercent:e.used_percent,windowMinutes:e.window_minutes,resetsAt:typeof e.resets_in_seconds=="number"?new Date(n.getTime()+e.resets_in_seconds*1e3).toISOString():void 0}},Cr={id:"hanzo.dev",kind:"localProbe",async isAvailable(e){return!!await at(e)},async fetch(e){let n=await at(e);if(!n)throw new Error("hanzo: no dev CLI home with sessions");let t=`${n}/sessions`,r=Me(await e.host.listDir(t)),o=r&&Me(await e.host.listDir(`${t}/${r}`)),s=o&&Me(await e.host.listDir(`${t}/${r}/${o}`));if(!s)throw new Error("hanzo: no dev sessions found");let a=`${t}/${r}/${o}/${s}`,c=(await e.host.listDir(a)).filter(h=>h.endsWith(".jsonl")).sort().at(-1);if(!c)throw new Error("hanzo: no rollout files today");let l=await e.host.readTextFile(`${a}/${c}`)??"",u;for(let h of l.split(`
|
|
2
|
+
`))if(h.includes('"token_count"'))try{let p=JSON.parse(h);p.payload?.type==="token_count"&&(u=p.payload)}catch{}let g=e.host.now(),d=u?.info?.total_token_usage;return{usage:{providerId:"hanzo",primary:it(u?.rate_limits?.primary,g),secondary:it(u?.rate_limits?.secondary,g),identity:{providerId:"hanzo",loginMethod:"dev-cli"},totals:d?{tokens:d.total_tokens??0,inputTokens:d.input_tokens??0,outputTokens:d.output_tokens??0,cachedInputTokens:d.cached_input_tokens??0}:void 0,dataConfidence:d?"exact":"unknown",updatedAt:g.toISOString()},sourceLabel:"Hanzo Dev CLI",strategyId:this.id,strategyKind:this.kind}}},ct={id:"hanzo",metadata:{displayName:"Hanzo",sessionLabel:"5h limit",weeklyLabel:"Weekly limit",defaultEnabled:!0,dashboardUrl:"https://console.hanzo.ai/billing/usage",color:"#ff2d55"},strategies:e=>C([Mr,Cr],e)};var ae=(e,n=[])=>{let t=e.settings?.baseUrl;if(typeof t=="string"&&t.length>0)return t;for(let r of n){let o=e.host.env(r);if(o)return o}},$=(e,n=[])=>{let t=e.settings?.apiKey;if(typeof t=="string"&&t.length>0)return t;for(let r of n){let o=e.host.env(r);if(o)return o}},Ur=e=>{let n=e.sourceLabel??e.metadata.displayName;return{id:`${e.id}.apiToken`,kind:"apiToken",async isAvailable(t){return!(!$(t,e.envKeys)||e.requireBaseUrl&&!ae(t,e.baseUrlEnv))},async fetch(t){let r=$(t,e.envKeys);if(!r)throw new Error(`${e.id}: no API key`);let o=ae(t,e.baseUrlEnv);if(e.requireBaseUrl&&!o)throw new Error(`${e.id}: no base URL`);let s={...t.settings,apiKey:r,...o?{baseUrl:o}:{}},a=e.request(s,t),i=await t.host.http({method:"GET",timeoutMs:3e4,...a});if(i.status!==200)throw new Error(`${e.id} HTTP ${i.status}`);let c;try{c=JSON.parse(i.text)}catch{throw new Error(`${e.id}: invalid JSON body`)}let l=t.host.now(),u=l.toISOString(),{usage:g,credits:d}=e.map(c,l,s);return{usage:{...g,providerId:e.id,updatedAt:u},credits:d?{...d,updatedAt:u}:void 0,sourceLabel:n,strategyId:`${e.id}.apiToken`,strategyKind:"apiToken"}},shouldFallback(){return!1}}},L=e=>{let n=Ur(e);return{id:e.id,metadata:e.metadata,strategies:t=>C([n],t)}},ie=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,x=e=>({Authorization:`Bearer ${e}`,Accept:"application/json"});var lt=["GROQ_API_KEY"],Nr="GROQ_API_URL",Or="https://api.groq.com/v1",Ce={requests:"sum(model_project_id_status_code:requests:rate5m)",tokensIn:"sum(model_project_id:tokens_in:rate5m)",tokensOut:"sum(model_project_id:tokens_out:rate5m)"},Ue=e=>{if(e.status!=="success")return 0;let n=0;for(let t of e.data?.result??[]){let r=t.value?.[1],o=typeof r=="number"?r:Number(r);Number.isFinite(o)&&(n+=o)}return n},zr={id:"groq.apiToken",kind:"apiToken",async isAvailable(e){return!!$(e,lt)},async fetch(e){let n=$(e,lt);if(!n)throw new Error("groq: no API key");let t=e.settings?.baseUrl??e.host.env(Nr)??Or,r=async g=>{let d=await e.host.http({url:`${t}/metrics/prometheus/api/v1/query?query=${encodeURIComponent(g)}`,headers:x(n),timeoutMs:3e4});if(d.status!==200)throw new Error(`groq metrics HTTP ${d.status}`);return JSON.parse(d.text)},[o,s,a]=await Promise.all([r(Ce.requests),r(Ce.tokensIn),r(Ce.tokensOut)]),i=Math.round(Ue(o)*60),c=Math.round((Ue(s)+Ue(a))*60),l=e.host.now().toISOString();return{usage:{providerId:"groq",identity:{providerId:"groq",loginMethod:"api"},totals:{tokens:c,requests:i},dataConfidence:"estimated",updatedAt:l},sourceLabel:"Groq metrics",strategyId:this.id,strategyKind:this.kind}},shouldFallback(){return!1}},ut={id:"groq",metadata:{displayName:"Groq",sessionLabel:"Throughput (req/min)",weeklyLabel:"Tokens/min",dashboardUrl:"https://console.groq.com/metrics",color:"#f55036"},strategies:e=>C([zr],e)};var dt=["DEEPGRAM_API_KEY"],$r="DEEPGRAM_API_URL",Dr="DEEPGRAM_PROJECT_ID",Rr="https://api.deepgram.com/v1",ue=e=>typeof e=="number"&&Number.isFinite(e)?e:0,Br={id:"deepgram.apiToken",kind:"apiToken",async isAvailable(e){return!!$(e,dt)},async fetch(e){let n=$(e,dt);if(!n)throw new Error("deepgram: no API key");let t=e.settings?.baseUrl??e.host.env($r)??Rr,r={Authorization:`Token ${n}`,Accept:"application/json"},o=async d=>{let m=await e.host.http({url:`${t}${d}`,headers:r,timeoutMs:3e4});if(m.status!==200)throw new Error(`deepgram ${d} HTTP ${m.status}`);return JSON.parse(m.text)},s=(typeof e.settings?.projectId=="string"?e.settings.projectId:void 0)??e.host.env(Dr),a;if(s)a=[s];else{let d=await o("/projects");a=(Array.isArray(d.projects)?d.projects:[]).map(h=>h.project_id).filter(h=>!!h)}let i=0,c=0,l=0;for(let d of a){let m=await o(`/projects/${d}/usage/breakdown`);for(let h of Array.isArray(m.results)?m.results:[])i+=ue(h.total_hours),c+=ue(h.tokens_in)+ue(h.tokens_out),l+=ue(h.requests)}let u=e.host.now().toISOString();return{usage:{providerId:"deepgram",identity:{providerId:"deepgram",loginMethod:"api",accountOrganization:a.length===1?a[0]:`${a.length} projects`},totals:{tokens:c,requests:l},dataConfidence:c>0||l>0||i>0?"exact":"unknown",updatedAt:u},sourceLabel:"Deepgram usage",strategyId:this.id,strategyKind:this.kind}},shouldFallback(){return!1}},gt={id:"deepgram",metadata:{displayName:"Deepgram",sessionLabel:"Usage",weeklyLabel:"Requests",dashboardUrl:"https://console.deepgram.com/usage",color:"#13ef93"},strategies:e=>C([Br],e)};var mt=["BYO_API_KEY"],ht=["BYO_BASE_URL"],Kr=e=>typeof e=="number"&&Number.isFinite(e)?e:0,Ne=e=>e&&typeof e=="object"?e:{},ft=e=>e.replace(/\/v1\/?$/,"").replace(/\/$/,""),Fr=async(e,n,t,r)=>{let o=await e.host.http({url:`${ft(n)}/key/info`,headers:x(t),timeoutMs:15e3});if(o.status!==200)return;let s;try{s=Ne(Ne(JSON.parse(o.text)).info)}catch{return}if(Object.keys(s).length===0)return;let a=Kr(s.spend);return{providerId:"byo",identity:{providerId:"byo",loginMethod:"api",accountEmail:typeof s.user_id=="string"?s.user_id:void 0,accountOrganization:typeof s.team_id=="string"?s.team_id:void 0,plan:typeof s.key_name=="string"?s.key_name:void 0},providerCost:{used:a,currencyCode:"USD",period:"key",updatedAt:r.toISOString()},subscriptionExpiresAt:typeof s.expires=="string"?s.expires:void 0,dataConfidence:"exact",updatedAt:r.toISOString()}},Hr=async(e,n,t,r)=>{let o=ft(n),s=await e.host.http({url:`${o}/v1/models`,headers:x(t),timeoutMs:15e3});if(s.status!==200)throw new Error(`byo: /v1/models HTTP ${s.status}`);let a;try{let i=Ne(JSON.parse(s.text)).data;Array.isArray(i)&&(a=i.length)}catch{}return{providerId:"byo",identity:{providerId:"byo",loginMethod:"api",accountOrganization:a!==void 0?`${a} models`:void 0},dataConfidence:"unknown",updatedAt:r.toISOString()}},jr={id:"byo.apiToken",kind:"apiToken",async isAvailable(e){return!!($(e,mt)&&ae(e,ht))},async fetch(e){let n=$(e,mt),t=ae(e,ht);if(!n||!t)throw new Error("byo: baseUrl and apiKey are required");let r=e.host.now(),o=await Fr(e,t,n,r);return o?{usage:o,sourceLabel:"BYO /key/info",strategyId:this.id,strategyKind:this.kind}:{usage:await Hr(e,t,n,r),sourceLabel:"BYO liveness",strategyId:this.id,strategyKind:this.kind}},shouldFallback(){return!1}},pt={id:"byo",metadata:{displayName:"BYO endpoint",sessionLabel:"Key spend",weeklyLabel:"Liveness",dashboardUrl:"https://docs.hanzo.ai/docs/gateway",color:"#64748b"},strategies:e=>C([jr],e)};var M=e=>typeof e=="number"&&Number.isFinite(e)?e:0,_=e=>{if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let n=Number(e);return Number.isFinite(n)?n:void 0}},H=(e,n)=>n>0?Math.min(100,Math.max(0,e/n*100)):0,y=e=>e&&typeof e=="object"?e:{},wt=L({id:"openrouter",metadata:{displayName:"OpenRouter",sessionLabel:"Credits used",weeklyLabel:"Credit limit",supportsCredits:!0,dashboardUrl:"https://openrouter.ai/settings/credits",color:"#6467f2"},envKeys:["OPENROUTER_API_KEY"],request:(e,n)=>({url:`${e.baseUrl??n.host.env("OPENROUTER_API_URL")??"https://openrouter.ai/api/v1"}/credits`,headers:x(e.apiKey)}),map:(e,n)=>{let t=y(y(e).data),r=M(t.total_credits),o=M(t.total_usage);return{usage:{identity:{providerId:"openrouter",loginMethod:"api"},providerCost:{used:o,limit:r,currencyCode:"USD",period:"total",updatedAt:n.toISOString()},dataConfidence:"exact"},credits:{remaining:Math.max(0,r-o)}}}}),vt=L({id:"deepseek",metadata:{displayName:"DeepSeek",sessionLabel:"Balance",weeklyLabel:"Balance",supportsCredits:!0,dashboardUrl:"https://platform.deepseek.com/usage",color:"#527df0"},envKeys:["DEEPSEEK_API_KEY","DEEPSEEK_KEY"],request:e=>({url:"https://api.deepseek.com/user/balance",headers:x(e.apiKey)}),map:e=>{let n=Array.isArray(y(e).balance_infos)?y(e).balance_infos:[],t=o=>_(o.total_balance)??0,r=n.find(o=>o.currency==="USD"&&t(o)>0)??n.find(o=>t(o)>0)??n.find(o=>o.currency==="USD")??n[0];return{usage:{identity:{providerId:"deepseek",loginMethod:"api",plan:typeof r?.currency=="string"?r.currency:void 0},dataConfidence:"exact"},credits:{remaining:r?t(r):0}}}}),At=L({id:"elevenlabs",metadata:{displayName:"ElevenLabs",sessionLabel:"Characters",weeklyLabel:"Character limit",dashboardUrl:"https://elevenlabs.io/app/subscription",color:"#ebebe6"},envKeys:["ELEVENLABS_API_KEY","XI_API_KEY"],request:(e,n)=>({url:`${e.baseUrl??n.host.env("ELEVENLABS_API_URL")??"https://api.elevenlabs.io"}/v1/user/subscription`,headers:{"xi-api-key":e.apiKey,Accept:"application/json"}}),map:(e,n)=>{let t=y(e),r=M(t.character_count),o=M(t.character_limit),s=ie(t.next_character_count_reset_unix),a=s!==void 0?new Date(s*1e3).toISOString():void 0,i=y(t.current_overage),c=_(i.amount);return{usage:{primary:{usedPercent:H(r,o),resetsAt:a},identity:{providerId:"elevenlabs",loginMethod:"api",plan:typeof t.tier=="string"?t.tier:void 0},subscriptionRenewsAt:a,providerCost:c!==void 0&&c>0?{used:c,currencyCode:typeof i.currency=="string"?i.currency:"USD",period:"overage",updatedAt:n.toISOString()}:void 0,dataConfidence:"exact"}}}}),kt=L({id:"poe",metadata:{displayName:"Poe",sessionLabel:"Points",weeklyLabel:"Points",supportsCredits:!0,dashboardUrl:"https://poe.com/api/keys",color:"#5d5cde"},envKeys:["POE_API_KEY"],request:e=>({url:"https://api.poe.com/usage/current_balance",headers:x(e.apiKey)}),map:e=>({usage:{identity:{providerId:"poe",loginMethod:"api"},dataConfidence:"exact"},credits:{remaining:M(y(e).current_point_balance)}})}),_t=L({id:"venice",metadata:{displayName:"Venice",sessionLabel:"Balance",weeklyLabel:"DIEM allocation",supportsCredits:!0,dashboardUrl:"https://venice.ai/settings/api",color:"#3399ff"},envKeys:["VENICE_API_KEY","VENICE_KEY"],request:e=>({url:"https://api.venice.ai/api/v1/billing/balance",headers:x(e.apiKey)}),map:e=>{let n=y(e),t=y(n.balances),r=n.canConsume!==!1,o=(typeof n.consumptionCurrency=="string"?n.consumptionCurrency:"USD").toUpperCase(),s=_(t.usd),a=_(t.diem),i=_(n.diemEpochAllocation),c=o==="DIEM",l=(c?a:s)??0,u=0;return r?c&&i&&i>0&&(u=H(Math.max(0,i-l),i)):u=100,{usage:{primary:{usedPercent:u},identity:{providerId:"venice",loginMethod:"api",plan:o},dataConfidence:"exact"},credits:{remaining:l}}}}),ee=(e,n)=>{let t=y(e),r=g=>{for(let d of g){let m=_(t[d]);if(m!==void 0)return m}},o=r(["percent_used","usage_percent","used_percent","utilization","utilization_percent"]),s=r(["percent_remaining","remaining_percent"]),a=r(["used","usage","consumed","current","requests","tokens","monthly_usage"]),i=r(["limit","cap","max","maximum","quota","quota_limit","monthly_limit","total"]),c=r(["remaining","available","balance","left"]),l=o;if(l===void 0&&s!==void 0&&(l=100-s),l!==void 0&&l<=1&&l>=0&&(l*=100),l===void 0&&i!==void 0){let g=a??(c!==void 0?i-c:void 0);g!==void 0&&(l=H(g,i))}if(l===void 0)return;let u=r(["reset_at","resets_at","next_reset_at","period_end","current_period_end","expires_at","window_end"]);return{usedPercent:Math.min(100,Math.max(0,l)),windowMinutes:n,resetsAt:u!==void 0?new Date(u*1e3).toISOString():void 0}},xt=L({id:"chutes",metadata:{displayName:"Chutes",sessionLabel:"4h quota",weeklyLabel:"Monthly quota",dashboardUrl:"https://chutes.ai",color:"#eab308"},envKeys:["CHUTES_API_KEY"],request:(e,n)=>({url:`${e.baseUrl??n.host.env("CHUTES_API_URL")??"https://api.chutes.ai"}/users/me/subscription_usage`,headers:x(e.apiKey)}),map:e=>{let n=y(e),t=ee(n.rolling,240)??ee(n.rolling_window,240)??ee(n.four_hour,240),r=ee(n.monthly,43200)??ee(n.subscription,43200)??ee(n.subscription_usage,43200),o=n.plan_name??n.plan??n.tier;return{usage:{primary:t,secondary:r,identity:{providerId:"chutes",loginMethod:"api",plan:typeof o=="string"?o:void 0},dataConfidence:t||r?"percentOnly":"unknown"}}}}),Vr=e=>e==="china"?"https://api.moonshot.cn":"https://api.moonshot.ai",Et=L({id:"moonshot",metadata:{displayName:"Moonshot",sessionLabel:"Balance",weeklyLabel:"Balance",supportsCredits:!0,dashboardUrl:"https://platform.moonshot.ai/console/info",color:"#16a34a"},envKeys:["MOONSHOT_API_KEY","MOONSHOT_KEY"],request:(e,n)=>({url:`${e.baseUrl??Vr(e.region??n.host.env("MOONSHOT_REGION"))}/v1/users/me/balance`,headers:x(e.apiKey)}),map:e=>{let n=y(y(e).data);return{usage:{identity:{providerId:"moonshot",loginMethod:"api"},dataConfidence:"exact"},credits:{remaining:M(n.available_balance)}}}}),St=L({id:"kimi",metadata:{displayName:"Kimi",sessionLabel:"Weekly",weeklyLabel:"Rate (5h)",dashboardUrl:"https://www.kimi.com/code/console",color:"#111111"},envKeys:["KIMI_CODE_API_KEY"],request:(e,n)=>({url:`${e.baseUrl??n.host.env("KIMI_CODE_BASE_URL")??"https://api.kimi.com"}/coding/v1/usages`,headers:x(e.apiKey)}),map:e=>{let n=y(e),t=y(n.usage),r=_(t.limit)??0,o=_(t.used)??(r&&_(t.remaining)!==void 0?r-_(t.remaining):0),s=t.resetTime??t.resetAt??t.reset_time,a=y(y(Array.isArray(n.limits)?n.limits[0]:void 0).detail),i=_(a.limit),c=_(a.used),l=i!==void 0?{usedPercent:H(c??0,i),windowMinutes:300}:void 0;return{usage:{primary:{usedPercent:H(o,r),resetsAt:typeof s=="string"?s:void 0},secondary:l,identity:{providerId:"kimi",loginMethod:"api"},dataConfidence:"percentOnly"}}}}),Tt=L({id:"kimik2",metadata:{displayName:"Kimi K2",sessionLabel:"Credits",weeklyLabel:"Credits",supportsCredits:!0,dashboardUrl:"https://kimi-k2.ai",color:"#111111"},envKeys:["KIMI_K2_API_KEY","KIMI_API_KEY","KIMI_KEY"],request:e=>({url:"https://kimi-k2.ai/api/user/credits",headers:x(e.apiKey)}),map:e=>{let n=y(e),t={...y(n.data),...y(n.result),...y(n.usage),...y(n.credits)},o=(s=>{for(let a of s){let i=_(n[a])??_(t[a]);if(i!==void 0)return i}})(["credits_remaining","creditsRemaining","remaining_credits","remainingCredits","available_credits","availableCredits","credits_left","creditsLeft","remaining"])??0;return{usage:{identity:{providerId:"kimik2",loginMethod:"api"},dataConfidence:"exact"},credits:{remaining:o}}}}),qr=e=>e==="bigmodel-cn"?"https://open.bigmodel.cn":"https://api.z.ai",Wr={1:1440,3:60,5:1,6:10080},bt=e=>{let n=_(e.usage)??0,t=_(e.currentValue),r=_(e.remaining),o=t??(r!==void 0?Math.max(0,n-r):void 0),s=_(e.percentage),a=o!==void 0&&n>0?H(o,n):s??0,i=_(e.unit),c=_(e.number),l=_(e.nextResetTime);return{usedPercent:a,windowMinutes:i!==void 0&&c!==void 0?(Wr[i]??0)*c:void 0,resetsAt:l!==void 0?new Date(l).toISOString():void 0}},Pt=L({id:"zai",metadata:{displayName:"z.ai",sessionLabel:"Token quota",weeklyLabel:"Time quota",dashboardUrl:"https://z.ai/manage-apikey/coding-plan/personal/my-plan",color:"#3b82f6"},envKeys:["Z_AI_API_KEY"],baseUrlEnv:["Z_AI_API_HOST"],request:(e,n)=>({url:`${Zr(e,n.host.env("Z_AI_API_HOST"))}/api/monitor/usage/quota/limit`,headers:{...x(e.apiKey),accept:"application/json"}}),map:e=>{let n=y(y(e).data),t=Array.isArray(n.limits)?n.limits:[],r=t.filter(a=>a.type==="TOKENS_LIMIT").map(bt),o=t.find(a=>a.type==="TIME_LIMIT"),s=n.planName??n.plan??n.planType??n.packageName;return{usage:{primary:r[0],secondary:o?bt(o):void 0,tertiary:r[1],identity:{providerId:"zai",loginMethod:"api",plan:typeof s=="string"?s:void 0},dataConfidence:r.length||o?"percentOnly":"unknown"}}}}),Zr=(e,n)=>e.baseUrl??n??qr(e.region),It=L({id:"openai",metadata:{displayName:"OpenAI",sessionLabel:"Credits used",weeklyLabel:"Credit grant",supportsCredits:!0,dashboardUrl:"https://platform.openai.com/usage",statusPageUrl:"https://status.openai.com",color:"#0f826e"},envKeys:["OPENAI_ADMIN_KEY","OPENAI_API_KEY"],request:e=>({url:"https://api.openai.com/v1/dashboard/billing/credit_grants",headers:x(e.apiKey)}),map:(e,n)=>{let t=y(e),r=M(t.total_granted),o=M(t.total_used),s=M(t.total_available);return{usage:{primary:{usedPercent:H(o,r)},identity:{providerId:"openai",loginMethod:"api"},providerCost:{used:o,limit:r,currencyCode:"USD",period:"grant",updatedAt:n.toISOString()},dataConfidence:"exact"},credits:{remaining:s}}}}),Yr=e=>e.replace(/\/v1\/?$/,""),Lt=L({id:"litellm",metadata:{displayName:"LiteLLM",sessionLabel:"Key spend",weeklyLabel:"Budget",dashboardUrl:"https://docs.litellm.ai/docs/proxy/cost_tracking",color:"#22c55e"},envKeys:["LITELLM_API_KEY"],baseUrlEnv:["LITELLM_BASE_URL"],requireBaseUrl:!0,request:e=>({url:`${Yr(e.baseUrl)}/key/info`,headers:x(e.apiKey)}),map:(e,n)=>{let t=y(y(e).info),r=M(t.spend);return{usage:{identity:{providerId:"litellm",loginMethod:"api",accountOrganization:typeof t.team_id=="string"?t.team_id:void 0,accountEmail:typeof t.user_id=="string"?t.user_id:void 0,plan:typeof t.key_name=="string"?t.key_name:void 0},providerCost:{used:r,currencyCode:"USD",period:"key",updatedAt:n.toISOString()},subscriptionExpiresAt:typeof t.expires=="string"?t.expires:void 0,dataConfidence:"exact"}}}}),Jr=e=>/\/v1\/?$/.test(e)?e.replace(/\/$/,""):`${e.replace(/\/$/,"")}/v1`,Mt=L({id:"llmproxy",metadata:{displayName:"LLM Proxy",sessionLabel:"Quota used",weeklyLabel:"Approx. spend",dashboardUrl:"https://github.com/hzruo/LLM-API-Key-Proxy",color:"#8b5cf6"},envKeys:["LLM_PROXY_API_KEY"],baseUrlEnv:["LLM_PROXY_BASE_URL"],requireBaseUrl:!0,request:e=>({url:`${Jr(e.baseUrl)}/quota-stats`,headers:x(e.apiKey)}),map:(e,n)=>{let t=y(e),r=y(t.providers),o=y(t.summary),s=100,a,i=0,c=0,l=0;for(let m of Object.values(r)){let h=y(m);c+=M(h.total_requests),l+=M(h.approx_cost);let p=y(h.tokens);i+=M(p.input_cached)+M(p.input_uncached)+M(p.output);let I=Array.isArray(h.quota_groups)?h.quota_groups:Object.values(y(h.quota_groups));for(let P of I){let V=y(P),B=_(V.remaining_percent);B!==void 0&&B<s&&(s=B);let f=typeof V.reset_time=="string"?V.reset_time:void 0;f&&(!a||f<a)&&(a=f)}}let u=ie(o.total_requests)??c,g=ie(o.total_tokens)??i,d=ie(o.approx_cost)??l;return{usage:{primary:{usedPercent:Math.min(100,Math.max(0,100-s)),resetsAt:a},identity:{providerId:"llmproxy",loginMethod:"api"},totals:{tokens:g,requests:u},providerCost:d>0?{used:d,currencyCode:"USD",period:"approx",updatedAt:n.toISOString()}:void 0,dataConfidence:"exact"}}}}),Gr=e=>e==="cn"||e==="china"?"https://api.minimaxi.com":"https://api.minimax.io",yt=(e,n,t)=>{let r=_(e[`${n}_remaining_percent`]),o=_(e[`${n}_total_count`]),s=_(e[`${n}_usage_count`]),a;if(r!==void 0?a=100-r:o!==void 0&&s!==void 0&&(a=H(s,o)),a!==void 0)return{usedPercent:Math.min(100,Math.max(0,a)),windowMinutes:t}},Ct=L({id:"minimax",metadata:{displayName:"MiniMax",sessionLabel:"Interval",weeklyLabel:"Weekly",dashboardUrl:"https://platform.minimax.io/user-center/payment/coding-plan",color:"#f43f5e"},envKeys:["MINIMAX_CODING_API_KEY","MINIMAX_API_KEY"],request:(e,n)=>({url:`${e.baseUrl??Gr(e.region??n.host.env("MINIMAX_REGION"))}/v1/api/openplatform/coding_plan/remains`,headers:{...x(e.apiKey),accept:"application/json","MM-API-Source":"HanzoUsage"}}),map:e=>{let n=y(y(e).data),t=Array.isArray(n.model_remains)?n.model_remains:[],r=y(t[0]),o=n.plan_name??n.current_plan_title??n.current_subscribe_title,s=_(n.points_balance)??_(n.balance);return{usage:{primary:yt(r,"current_interval",0),secondary:yt(r,"current_weekly",10080),identity:{providerId:"minimax",loginMethod:"api",plan:typeof o=="string"?o:void 0},dataConfidence:t.length?"percentOnly":"unknown"},credits:s!==void 0?{remaining:s}:void 0}}});var Ut={hanzo:ct,codex:se,claude:X,openai:It,openrouter:wt,deepseek:vt,elevenlabs:At,deepgram:gt,groq:ut,poe:kt,venice:_t,chutes:xt,moonshot:Et,kimi:St,kimik2:Tt,zai:Pt,litellm:Lt,llmproxy:Mt,minimax:Ct,byo:pt},io=Object.values(Ut),co=Object.keys(Ut);var Ot=async e=>{let n=new AbortController,t=e.timeoutMs?setTimeout(()=>n.abort(),e.timeoutMs):void 0;try{let r=await fetch(e.url,{method:e.method??"GET",headers:e.headers,body:e.body,credentials:"include",signal:n.signal}),o={};return r.headers.forEach((s,a)=>{o[a]=s}),{status:r.status,headers:o,text:await r.text()}}finally{t&&clearTimeout(t)}},zt={readTextFile:async()=>{},listDir:async()=>[],writeTextFile:async()=>{},http:Ot,env:()=>{},homeDir:()=>"",now:()=>new Date},$t=e=>/\b(401|403)\b/.test(e),Xr=(e,n)=>{let r=[...n.attempts].reverse().find(o=>o.error)?.error??"no data";return $t(r)?`Open ${e} to sign in`:r},Qr=async()=>{let{displayName:e,color:n,dashboardUrl:t}=X.metadata,r={providerId:"claude",displayName:e,color:n,dashboardUrl:t};try{let o=await rt(X,{host:zt,sourceMode:"web",settings:{cookieHeader:""}});return o.result?{...r,snapshot:o.result.usage}:{...r,error:Xr("claude.ai",o)}}catch(o){return{...r,error:o instanceof Error?o.message:String(o)}}},Nt=e=>{if(!(!e||typeof e.used_percent!="number"))return{usedPercent:e.used_percent,windowMinutes:e.limit_window_seconds?Math.round(e.limit_window_seconds/60):void 0,resetsAt:e.reset_at?new Date(e.reset_at*1e3).toISOString():void 0}},en=async()=>{let{displayName:e,color:n,dashboardUrl:t}=se.metadata,r={providerId:"codex",displayName:e,color:n,dashboardUrl:t};try{let o=await Ot({url:"https://chatgpt.com/backend-api/wham/usage",headers:{Accept:"application/json"},timeoutMs:3e4});if(o.status!==200)return{...r,error:$t(String(o.status))?"Open chatgpt.com to sign in":`HTTP ${o.status}`};let s=JSON.parse(o.text),a={providerId:"codex",primary:Nt(s.rate_limit?.primary_window),secondary:Nt(s.rate_limit?.secondary_window),identity:{providerId:"codex",plan:s.plan_type,loginMethod:"web"},dataConfidence:"percentOnly",updatedAt:zt.now().toISOString()};return{...r,snapshot:a}}catch(o){return{...r,error:o instanceof Error?o.message:String(o)}}},Dt=async()=>Promise.all([Qr(),en()]);function Rt(e){let n=e??{},t=n.expression??n.code??n.script??n.function??n.js??"";return typeof t=="string"?t:String(t)}function Bt(e){let n=(e??"").trim();if(!n)return"undefined";if(/^(\(?\s*(async\s+)?function\b|\(?\s*\([^)]*\)\s*=>|\(\s*async\b)/.test(n)||!(/[;\n]/.test(n)||/^(const|let|var|if|for|while|switch|return|throw|await|try)\b/.test(n)))return n;let r=n.replace(/;\s*$/,""),o=Math.max(r.lastIndexOf(";"),r.lastIndexOf(`
|
|
3
|
+
`)),s=o>=0?r.slice(0,o+1):"",a=(o>=0?r.slice(o+1):r).trim();return a&&!/^(return|const|let|var|if|for|while|switch|throw|}|\/\/)/.test(a)&&(r=s+" return "+a),`(async()=>{ ${r} })()`}async function Kt(e){return new Promise(n=>{e.get(["hanzo_rag_endpoint","hanzo_rag_api_key","hanzo_rag_kb","hanzo_rag_top_k","hanzo_rag_include_tab_context"],t=>{let r=Number.parseInt(String(t.hanzo_rag_top_k??5),10);n({endpoint:String(t.hanzo_rag_endpoint||"").trim(),apiKey:String(t.hanzo_rag_api_key||"").trim(),knowledgeBase:String(t.hanzo_rag_kb||"").trim(),topK:Number.isFinite(r)?Math.max(1,Math.min(r,20)):5,includeTabContext:t.hanzo_rag_include_tab_context!==!1})})})}function tn(e){if(!e)return[];let n=[];return Array.isArray(e)&&n.push(...e),Array.isArray(e?.snippets)&&n.push(...e.snippets),Array.isArray(e?.documents)&&n.push(...e.documents),Array.isArray(e?.items)&&n.push(...e.items),Array.isArray(e?.results)&&n.push(...e.results),Array.isArray(e?.memories)&&n.push(...e.memories),Array.isArray(e?.matches)&&n.push(...e.matches),!n.length&&typeof e?.content=="string"&&n.push({content:e.content,source:e.source||"memory"}),n.map(r=>{let o=String(r?.content??r?.text??r?.snippet??r?.body??r?.value??"").trim();return o?{content:o,title:r?.title?String(r.title):void 0,source:r?.source?String(r.source):void 0,score:typeof r?.score=="number"?r.score:void 0,url:r?.url?String(r.url):void 0}:null}).filter(r=>!!r).slice(0,20)}async function Ft(e){if(!e.endpoint)return[];let n={"Content-Type":"application/json"};e.apiKey&&(n.Authorization=`Bearer ${e.apiKey}`);let t=await fetch(e.endpoint,{method:"POST",headers:n,body:JSON.stringify({query:e.query,top_k:e.topK,knowledge_base:e.knowledgeBase||void 0,page_context:e.includeTabContext?e.pageContext:void 0,source:"hanzo-browser-extension"})});if(!t.ok){let o=await t.text();throw new Error(`RAG endpoint error ${t.status}: ${o||"Unknown error"}`)}let r=await t.json();return tn(r).map(o=>({...o,source:o.source||"rag-endpoint"}))}var rn="https://hanzo.id",Oe="https://api.hanzo.ai",Z="/v1/iam",nn="hanzo-browser",on="openid profile email",sn="https://hanzo.ai/callback",E={accessToken:"hanzo_iam_access_token",refreshToken:"hanzo_iam_refresh_token",idToken:"hanzo_iam_id_token",expiresAt:"hanzo_iam_expires_at",user:"hanzo_iam_user"},te="https://api.hanzo.ai";var To=typeof __EVENT_INGEST_KEY__=="string"&&__EVENT_INGEST_KEY__?__EVENT_INGEST_KEY__:void 0,an="https://kms.hanzo.ai",j={ollama:{name:"Ollama",url:"http://localhost:11434",probePorts:[11434]},lmstudio:{name:"LM Studio",url:"http://localhost:1234/v1",probePorts:[1234]},"hanzo-desktop":{name:"Hanzo Desktop",url:"http://localhost:11435",probePorts:[11435,9550]},"hanzo-node":{name:"Hanzo Node",url:"http://localhost:3690",probePorts:[3690,8080]}};var cn=9224;var Po=60*1e3;var Ht={iamLoginUrl:{key:"hanzo_config_iam_login_url",fallback:rn},iamApiUrl:{key:"hanzo_config_iam_api_url",fallback:Oe},apiBaseUrl:{key:"hanzo_config_api_base",fallback:te},kmsApiUrl:{key:"hanzo_config_kms_url",fallback:an},clientId:{key:"hanzo_config_client_id",fallback:nn},scopes:{key:"hanzo_config_scopes",fallback:on},redirectUri:{key:"hanzo_config_redirect_uri",fallback:sn},cdpBridgePort:{key:"hanzo_config_cdp_bridge_port",fallback:cn}};async function jt(e){let n=Object.values(Ht).map(o=>o.key),t=await e.get(n),r={};for(let[o,{key:s,fallback:a}]of Object.entries(Ht)){let i=t[s];i!=null&&i!==""?r[o]=typeof a=="number"?Number(i):String(i):r[o]=a}return r}function Vt(e){let n=new Uint8Array(e);return crypto.getRandomValues(n),Array.from(n,t=>t.toString(36).padStart(2,"0")).join("").slice(0,e)}async function ln(e){return crypto.subtle.digest("SHA-256",new TextEncoder().encode(e))}function un(e){let n=new Uint8Array(e),t="";for(let r of n)t+=String.fromCharCode(r);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function dn(){let e=Vt(64),n=await ln(e),t=un(n);return{codeVerifier:e,codeChallenge:t}}var ze=null;async function ge(e){return ze||(ze=await jt(e)),ze}async function $e(e,n){let t={[E.accessToken]:n.access_token};n.refresh_token&&(t[E.refreshToken]=n.refresh_token),n.id_token&&(t[E.idToken]=n.id_token),n.expires_in&&(t[E.expiresAt]=Date.now()+n.expires_in*1e3),await e.set(t)}async function qt(e){let n=await e.get([E.accessToken,E.refreshToken,E.expiresAt]);return{accessToken:n[E.accessToken]||null,refreshToken:n[E.refreshToken]||null,expiresAt:n[E.expiresAt]||null}}function gn(e,n,t){return new Promise((r,o)=>{let s,a=setTimeout(()=>{i(),o(new Error("Login timed out"))},3e5);function i(){clearTimeout(a),e.onUpdated.removeListener(c),e.onRemoved.removeListener(l)}function c(u,g){u!==s||!g.url||g.url.startsWith(t)&&(i(),e.remove(u).catch(()=>{}),r(g.url))}function l(u){u===s&&(i(),o(new Error("Login cancelled")))}e.onUpdated.addListener(c),e.onRemoved.addListener(l),e.create({url:n}).then(u=>{s=u.id}).catch(u=>{i(),o(u)})})}async function Wt(e){let n=await ge(e.storage),{codeVerifier:t,codeChallenge:r}=await dn(),o=Vt(32),s=n.redirectUri,a=new URL(`${n.iamLoginUrl}${Z}/oauth/authorize`);a.searchParams.set("client_id",n.clientId),a.searchParams.set("response_type","code"),a.searchParams.set("redirect_uri",s),a.searchParams.set("code_challenge",r),a.searchParams.set("code_challenge_method","S256"),a.searchParams.set("scope",n.scopes),a.searchParams.set("state",o);let i=await gn(e.tabs,a.toString(),s),c=new URL(i);if(c.searchParams.get("state")!==o)throw new Error("State mismatch \u2014 possible CSRF");let l=c.searchParams.get("code"),u=c.searchParams.get("access_token");if(u)await $e(e.storage,{access_token:u,refresh_token:c.searchParams.get("refresh_token")||void 0,token_type:"Bearer"});else if(l){let m=await fetch(`${n.iamApiUrl}${Z}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",client_id:n.clientId,code:l,redirect_uri:s,code_verifier:t}).toString()});if(!m.ok)throw new Error(`Token exchange failed: ${await m.text()}`);await $e(e.storage,await m.json())}else{let m=c.searchParams.get("error_description")||c.searchParams.get("error")||"No authorization code or token";throw new Error(m)}let{accessToken:g}=await qt(e.storage);if(!g)throw new Error("Login succeeded but no token was stored");let d=await hn(e.storage,g);return await e.storage.set({[E.user]:d}),d}async function Zt(e){let n=await ge(e.storage);await e.tabs.create({url:`${n.iamLoginUrl}/signup`})}async function de(e){await e.remove(Object.values(E))}async function De(e){let{accessToken:n,refreshToken:t,expiresAt:r}=await qt(e);if(!n)return null;if(r&&Date.now()<r-6e4)return n;if(t)try{return await mn(e,t)}catch{return await de(e),null}return r?(await de(e),null):n}async function mn(e,n){let t=await ge(e),r=await fetch(`${t.iamApiUrl}${Z}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",client_id:t.clientId,refresh_token:n}).toString()});if(!r.ok)throw new Error("Token refresh failed");let o=await r.json();return await $e(e,o),o.access_token}async function hn(e,n){let t=await ge(e),r={Authorization:`Bearer ${n}`},o=await fetch(`${t.iamApiUrl}${Z}/oauth/userinfo`,{headers:r});if(!o.ok)throw new Error("Failed to fetch user info");return o.json()}async function fn(e){return(await e.get([E.user]))[E.user]||null}async function Yt(e){return await De(e)?{authenticated:!0,user:await fn(e)}:{authenticated:!1,user:null}}function pn(){return globalThis.browser??globalThis.chrome}function bn(){let e=pn();return{storage:{get:n=>Promise.resolve(e.storage.local.get(n)),set:n=>Promise.resolve(e.storage.local.set(n)),remove:n=>Promise.resolve(e.storage.local.remove(n))},tabs:{create:n=>Promise.resolve(e.tabs.create(n)),remove:n=>Promise.resolve(e.tabs.remove(n)),onUpdated:e.tabs.onUpdated,onRemoved:e.tabs.onRemoved}}}function Jt(){return bn()}function me(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e!="string"||e==="")return null;let n=e.match(/^(?:tab-)?(\d+)$/);if(!n)return null;let t=Number(n[1]);return Number.isFinite(t)?t:null}function Re(e,n){let t=atob(e),r=new Uint8Array(t.length);for(let o=0;o<t.length;o++)r[o]=t.charCodeAt(o);return new Blob([r],{type:n})}async function Be(e){let n=new Uint8Array(await e.arrayBuffer()),t="";for(let r=0;r<n.length;r+=32768)t+=String.fromCharCode(...n.subarray(r,r+32768));return btoa(t)}async function he(e,n,t,r="image/png"){if(!e||!(n>0))return e;try{let o=await createImageBitmap(Re(e,r)),s=Math.min(1,n/Math.max(o.width,o.height));if(s>=1&&r==="image/jpeg")return o.close(),e;let a=Math.max(1,Math.round(o.width*s)),i=Math.max(1,Math.round(o.height*s)),c=new OffscreenCanvas(a,i),l=c.getContext("2d");return l?(l.drawImage(o,0,0,a,i),o.close(),await Be(await c.convertToBlob({type:"image/jpeg",quality:Math.min(100,Math.max(1,t))/100}))):e}catch{return e}}function fe(e={}){let n=e.format==="png"?"png":"jpeg",t=Number(e.quality)||(n==="jpeg"?70:0),r=Number(e.maxWidth)||0;return{format:n,quality:t,max:r}}var Fe=new Set(["hanzo.navigate","hanzo.snapshot","hanzo.act","hanzo.read","hanzo.wait","hanzo.annotate"]),ye=class extends Error{},D=e=>e==null||e===""?void 0:String(e),pe=e=>e===!0||e===1||typeof e=="string"&&/^(true|1)$/i.test(e),be=e=>{let n=e==null||e===""?NaN:Number(e);return Number.isFinite(n)?n:void 0},He=e=>new Promise(n=>setTimeout(n,e)),we=new Map;async function Qt(e,n,t,r){switch(t){case"hanzo.navigate":return yn(e,n,D(r.url));case"hanzo.snapshot":{let{last:o,...s}=await ce(e,n,{op:"snapshot",interactive:pe(r.interactive),compact:pe(r.compact),depth:be(r.depth),selector:D(r.selector),urls:pe(r.urls),base:we.get(n)});return we.set(n,o),s}case"hanzo.act":return ce(e,n,{op:D(r.op),selector:D(r.selector),text:r.text===void 0?void 0:String(r.text),key:D(r.key),value:D(r.value),attribute:D(r.attribute),dx:be(r.dx),dy:be(r.dy)});case"hanzo.read":return ce(e,n,{op:"read",outline:pe(r.outline),filter:D(r.filter)});case"hanzo.wait":return wn(e,n,r);case"hanzo.annotate":return An(e,n,r)}throw new Error(`drive: unknown method ${t}`)}async function Ke(e,n,t=5e3){let r=Date.now()+t;for(;(await e.tabs.get(n)).status!=="complete"&&Date.now()<r;)await He(100)}async function Gt(e,n,t){let[r]=await e.scripting.executeScript({target:{tabId:n},func:o=>{let s=globalThis.__hanzoPage;return s?s(o):null},args:[JSON.parse(JSON.stringify(t))]});if(r?.error)throw new Error(String(r.error));return r?.result??null}async function ce(e,n,t){await Ke(e,n);let r=async()=>{let c=await Gt(e,n,t);return c||(await e.scripting.executeScript({target:{tabId:n},files:["page.js"]}),Gt(e,n,t))},o;try{o=await r()}catch{await Ke(e,n),o=await r()}if(!o)throw new Error("The page did not answer: browser pages (chrome://, about:, the extension store) cannot be scripted.");let{ok:s,error:a,...i}=o;if(!s)throw new ye(a);return i}async function yn(e,n,t){if(!t)throw new Error("url required");let r=await e.tabs.get(n),o=new URL(t,r.url||void 0);if(r.url&&o.hash&&o.href.split("#")[0]===String(r.url).split("#")[0])await e.tabs.update(n,{url:o.href});else{let i=new Promise(c=>{let l=()=>{clearTimeout(g),e.tabs.onUpdated.removeListener(u),c()},u=(d,m)=>{d===n&&m.status==="complete"&&l()},g=setTimeout(l,3e4);e.tabs.onUpdated.addListener(u)});await e.tabs.update(n,{url:o.href}),await i}let a=await e.tabs.get(n);return{url:a.url,title:a.title,loaded:a.status==="complete"}}async function wn(e,n,t){let r=be(t.timeout)??1e4,o=Date.now(),s={op:"probe",selector:D(t.selector),text:D(t.text),state:D(t.state)};if(!s.selector&&!s.text)return await Ke(e,n,r),{loaded:(await e.tabs.get(n)).status==="complete",waited:Date.now()-o};let a=s.text?`text ${JSON.stringify(s.text)}`:s.selector;for(;;){try{if((await ce(e,n,s)).met)return{met:!0,waited:Date.now()-o}}catch(i){if(i instanceof ye)throw i}if(Date.now()-o>r)throw new Error(`Timed out after ${r}ms waiting for ${a} to be ${s.state==="hidden"?"hidden":"visible"}.`);await He(100)}}async function vn(e,n){let t=await e.tabs.get(n),r;if(!t.active){let[o]=await e.tabs.query({active:!0,windowId:t.windowId});r=o?.id,await e.tabs.update(n,{active:!0}),await He(100)}try{let o=await e.tabs.captureVisibleTab(t.windowId,{format:"png"});if(!o)throw new Error("captureVisibleTab returned nothing");return o.replace(/^data:image\/\w+;base64,/,"")}finally{r!==void 0&&await e.tabs.update(r,{active:!0}).catch(()=>{})}}var Xt="#e11d48";async function An(e,n,t){let{last:r,boxes:o,width:s}=await ce(e,n,{op:"boxes",base:we.get(n)});we.set(n,r);let a=await vn(e,n),i=await createImageBitmap(Re(a,"image/png")),c=i.width/s,l=new OffscreenCanvas(i.width,i.height),u=l.getContext("2d");u.drawImage(i,0,0),i.close(),u.lineWidth=Math.max(1,2*c),u.font=`bold ${Math.round(11*c)}px sans-serif`,u.textBaseline="top";for(let p of o){let[I,P,V,B]=[p.x*c,p.y*c,p.w*c,p.h*c],f=p.ref.slice(1),b=u.measureText(f).width+6*c,w=15*c,A=P>=w?P-w:P;u.strokeStyle=Xt,u.strokeRect(I,P,V,B),u.fillStyle=Xt,u.fillRect(I,A,b,w),u.fillStyle="#fff",u.fillText(f,I+3*c,A+2*c)}let g=await Be(await l.convertToBlob({type:"image/png"})),{quality:d,max:m}=fe(t);return{data:m>0?await he(g,m,d||70):g,format:m>0?"jpeg":"png",legend:o.map(p=>`[${p.ref.slice(1)}] @${p.ref} ${p.label}`)}}async function er(e,n,t,r){if(!String(n?.url||"").startsWith(e.runtime.getURL("")))return{success:!1,error:"drive answers extension pages only"};if(!t.method||!Fe.has(t.method))return{success:!1,error:`drive: unknown method ${t.method}`};try{return{success:!0,result:await r(t.method,t.params||{})}}catch(o){return{success:!1,error:o instanceof Error?o.message:String(o)}}}var kn="firefox",Xo=typeof browser<"u"?browser.runtime.getManifest().version:"0",_n=[/^about:/i,/^moz-extension:/i,/^chrome:/i,/^view-source:/i,/^resource:/i,/^file:/i,/^https?:\/\/addons\.mozilla\.org\b/i];function tr(e){if(!e)return!1;let n=e.url||e.pendingUrl||"";return n?_n.some(t=>t.test(n)):!0}var k={active:!1,tabId:null,task:null,startedAt:null},je=class{constructor(){console.log("[Hanzo] Firefox extension initializing...")}executeScriptWithTimeout(n,t,r=1e4){let o=(async()=>{let s=browser.scripting;if(s?.executeScript){let i=async u=>{let g=await s.executeScript({target:{tabId:n},world:u,args:[t],func:d=>{try{return Function(d)()}catch(m){return{__hanzo_error:m?.message||String(m)}}}});return Array.isArray(g)?g.map(d=>d?.result):[g]},c=await i("MAIN");return c.length>0&&c.every(u=>u&&typeof u=="object"&&u.__hanzo_error&&/CSP|unsafe-eval|Content Security|Function|eval/i.test(String(u.__hanzo_error)))?i("ISOLATED"):c}let a=browser.tabs?.executeScript;if(a)return a.call(browser.tabs,n,{code:t});throw new Error("No executeScript API available (need MV3 scripting permission)")})();return Promise.race([o,new Promise((s,a)=>setTimeout(()=>a(new Error("executeScript timeout")),r))])}async resolveTab(n){let t=n.tabId??n.targetId;if(t!=null){let o=me(t);if(o!==null)try{return await browser.tabs.get(o)}catch{}}if(typeof n.tabIndex=="number"){let s=(await browser.tabs.query({currentWindow:!0}))[n.tabIndex];if(s)return s}let[r]=await browser.tabs.query({active:!0,currentWindow:!0});if(r)return r;throw new Error("No active tab")}async runInPage(n,t,r=1e4){let o;try{o=await browser.tabs.get(n)}catch{}if(o&&tr(o))throw new Error(`Cannot run JS in privileged tab ${n} (${o.url}). Activate a regular http(s) tab via tabId/tab_id parameter.`);let s=`
|
|
4
|
+
try {
|
|
5
|
+
var __r = (function() { ${t} })();
|
|
6
|
+
return __r === undefined ? null : __r;
|
|
7
|
+
} catch(__e) {
|
|
8
|
+
return { __hanzo_error: __e.message || String(__e) };
|
|
9
|
+
}
|
|
10
|
+
`,a=await this.executeScriptWithTimeout(n,s,r);if(!Array.isArray(a)||a.length===0)throw new Error(`executeScript returned no frames for tab ${n} \u2014 page may be privileged, in a process the extension can't access, or unloaded.`);let i=a[0];if(i===void 0)throw new Error(`executeScript ran but returned no value (frame errored outside the wrapped try/catch \u2014 most often page CSP blocking Function()). Tab ${n}.`);if(i&&typeof i=="object"&&i.__hanzo_error)throw new Error(i.__hanzo_error);return i}async runFunc(n,t,r=[],o=1e4){let s;try{s=await browser.tabs.get(n)}catch{}if(s&&tr(s))throw new Error(`Cannot run JS in privileged tab ${n} (${s.url}).`);let a=browser.scripting;if(!a?.executeScript)throw new Error("scripting.executeScript not available (need MV3 scripting permission)");let i=(async()=>{let c=async d=>{let m=await a.executeScript({target:{tabId:n},world:d,args:r,func:t});return Array.isArray(m)?m:[m]},l;try{l=await c("MAIN")}catch{l=await c("ISOLATED")}if(!Array.isArray(l)||l.length===0)throw new Error(`runFunc returned no frames for tab ${n} \u2014 page may be privileged or unloaded.`);let u=l[0]||{};if(u.error)throw new Error(`runFunc page-side error: ${u.error}`);let g=u.result;if(g&&typeof g=="object"&&g.__hanzo_error)throw new Error(g.__hanzo_error);return g===void 0?null:g})();return Promise.race([i,new Promise((c,l)=>setTimeout(()=>l(new Error("runFunc timeout")),o))])}async dispatchMethod(n,t){let r=await this.executeMethod(n,t||{});if(r&&typeof r=="object"&&"error"in r&&r.error)throw new Error(String(r.error));return r}async executeMethod(n,t){let r;try{r=await this.resolveTab(t)}catch{r=null}let o=r?.id??void 0;if(Fe.has(n)){if(!o)throw new Error("No active tab");return Qt(browser,o,n,t)}switch(n){case"Target.getTargets":return{targetInfos:(await browser.tabs.query({})).map(a=>({targetId:`tab-${a.id}`,type:"page",title:a.title||"",url:a.url||""}))};case"Target.createTarget":{let s=await browser.tabs.create({url:t.url||"about:blank"});return{targetId:`tab-${s.id}`,tabId:s.id}}case"Target.closeTarget":{let s=me(t.targetId??t.tabId);return s!==null&&await browser.tabs.remove(s),{success:!0}}case"Target.activateTarget":{let s=me(t.targetId??t.tabId);return s!==null&&await browser.tabs.update(s,{active:!0}),{success:!0}}case"hanzo.url":return{result:{value:r?.url||""}};case"hanzo.title":return{result:{value:r?.title||""}};case"hanzo.tabInfo":return{result:{value:{id:r?.id,url:r?.url,title:r?.title,status:r?.status,favIconUrl:r?.favIconUrl}}};case"hanzo.getTabs":case"hanzo.listTabs":return{tabs:(await browser.tabs.query({})).map(a=>({id:a.id,url:a.url,title:a.title,active:a.active}))};case"hanzo.getHistory":{let s=t.maxResults||25;try{return{history:(await browser.history.search({text:"",maxResults:s,startTime:0})).map(i=>({url:i.url,title:i.title,lastVisitTime:i.lastVisitTime}))}}catch{return{history:[],error:"history API not available"}}}case"Page.navigate":{if(!o)throw new Error("No active tab");return this.notifyOverlay(o,"ai.control.status",{text:`Navigating to ${t.url}`}),await browser.tabs.update(o,{url:t.url}),{frameId:"main"}}case"Page.reload":{if(!o)throw new Error("No active tab");return await browser.tabs.reload(o),{success:!0}}case"Page.goBack":{if(!o)throw new Error("No active tab");return await browser.tabs.goBack(o),{success:!0}}case"Page.goForward":{if(!o)throw new Error("No active tab");return await browser.tabs.goForward(o),{success:!0}}case"hanzo.waitForNavigation":{if(!o)throw new Error("No active tab");let s=t.timeout||3e4;return new Promise(a=>{let i=!1,c=setTimeout(()=>{i||(i=!0,browser.webNavigation.onCompleted.removeListener(l),a({success:!1,error:"timeout"}))},s);function l(u){u.tabId===o&&u.frameId===0&&(i=!0,clearTimeout(c),browser.webNavigation.onCompleted.removeListener(l),a({success:!0,url:u.url}))}browser.webNavigation.onCompleted.addListener(l)})}case"Page.waitForLoadState":{if(!o)throw new Error("No active tab");let s=t.timeout||3e4,a=Date.now();for(;Date.now()-a<s;){if((await browser.tabs.get(o)).status==="complete")return{success:!0};await new Promise(c=>setTimeout(c,200))}return{success:!1,error:"timeout"}}case"Runtime.evaluate":case"evaluate":{if(!o)throw new Error("No active tab");let s=t.timeout||3e4,a=`
|
|
11
|
+
return Promise.resolve(${Bt(Rt(t))}).then(function(__v){
|
|
12
|
+
if (__v === undefined || __v === null) return null;
|
|
13
|
+
try { return JSON.parse(JSON.stringify(__v)); } catch(e) { return String(__v); }
|
|
14
|
+
}, function(__e){
|
|
15
|
+
return { __hanzo_error: (__e && __e.message) || String(__e) };
|
|
16
|
+
});
|
|
17
|
+
`,i,c=null;try{i=await this.runInPage(o,a,s)}catch(d){c=d?.message||String(d),i=null}let l=i===void 0?null:i,g={result:{type:l===null||Array.isArray(l)?"object":typeof l,value:l},value:l};return c!==null&&(g.error=c,g.result={type:"object",value:null,subtype:"error",description:c},g.exceptionDetails={text:c}),g}case"Page.captureScreenshot":case"hanzo.screenshot":{let{format:s,quality:a,max:i}=fe(t),c={format:s};s==="jpeg"&&(c.quality=a);let l=null,u;if(r&&!r.active){let[h]=await browser.tabs.query({active:!0,windowId:r.windowId});u=h?.id,await browser.tabs.update(r.id,{active:!0}),l=r.id??null,await new Promise(p=>setTimeout(p,50))}let g;try{g=await browser.tabs.captureVisibleTab(r?.windowId??null,c)}finally{l!==null&&u&&await browser.tabs.update(u,{active:!0}).catch(()=>{})}if(!g)throw new Error("captureVisibleTab returned empty result");let d=g.replace(/^data:image\/\w+;base64,/,""),m=await he(d,i,a,`image/${s}`);return{data:m,format:i>0?"jpeg":s,size:m.length}}case"Accessibility.getFullAXTree":{if(!o)throw new Error("No active tab");return{tree:await this.runInPage(o,`
|
|
18
|
+
function buildTree(el, depth) {
|
|
19
|
+
if (depth > 5 || !el) return null;
|
|
20
|
+
var role = el.getAttribute && el.getAttribute('role') || el.tagName?.toLowerCase() || '';
|
|
21
|
+
var name = el.getAttribute && (el.getAttribute('aria-label') || el.getAttribute('alt') || el.getAttribute('title') || el.textContent?.trim()?.slice(0, 80)) || '';
|
|
22
|
+
var node = { role: role, name: name };
|
|
23
|
+
if (el.children && el.children.length > 0 && depth < 5) {
|
|
24
|
+
node.children = [];
|
|
25
|
+
for (var i = 0; i < Math.min(el.children.length, 50); i++) {
|
|
26
|
+
var child = buildTree(el.children[i], depth + 1);
|
|
27
|
+
if (child) node.children.push(child);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
return node;
|
|
31
|
+
}
|
|
32
|
+
return buildTree(document.body, 0);
|
|
33
|
+
`)}}case"hanzo.click":{if(!o||!t.selector)throw new Error("No active tab or selector");this.notifyOverlay(o,"ai.control.highlight",{selector:t.selector}),this.notifyOverlay(o,"ai.control.status",{text:`Clicking ${t.selector}`});let s=await this.runFunc(o,a=>{let i=document.querySelector(a);if(!i)return{clicked:!1,reason:"not-found"};try{i.scrollIntoView({block:"center",behavior:"instant"})}catch{}let c=i.getBoundingClientRect(),l=c.left+c.width/2,u=c.top+c.height/2,g={bubbles:!0,cancelable:!0,composed:!0,view:window,button:0,buttons:1,clientX:l,clientY:u,screenX:l,screenY:u,detail:1};try{i.dispatchEvent(new MouseEvent("mouseover",g)),i.dispatchEvent(new MouseEvent("mouseenter",g)),i.dispatchEvent(new MouseEvent("mousemove",g)),i.dispatchEvent(new MouseEvent("mousedown",g));try{i.focus({preventScroll:!0})}catch{}return i.dispatchEvent(new MouseEvent("mouseup",{...g,buttons:0})),i.dispatchEvent(new MouseEvent("click",{...g,buttons:0})),{clicked:!0,tag:i.tagName,x:l,y:u,isTrusted:!1}}catch{try{return i.click(),{clicked:!0,fallback:"el.click()",isTrusted:!1}}catch(m){return{clicked:!1,error:String(m)}}}},[t.selector]);return{success:!!(s&&s.clicked),detail:s}}case"hanzo.dblclick":{if(!o||!t.selector)throw new Error("No active tab or selector");let s=this.escapeSelector(t.selector);return this.notifyOverlay(o,"ai.control.highlight",{selector:t.selector}),await this.runInPage(o,`
|
|
34
|
+
var el = document.querySelector('${s}');
|
|
35
|
+
if (el) {
|
|
36
|
+
el.dispatchEvent(new MouseEvent('dblclick', {bubbles: true, cancelable: true}));
|
|
37
|
+
}
|
|
38
|
+
`),{success:!0}}case"hanzo.hover":{if(!o||!t.selector)throw new Error("No active tab or selector");let s=this.escapeSelector(t.selector);return this.notifyOverlay(o,"ai.control.highlight",{selector:t.selector}),await this.runInPage(o,`
|
|
39
|
+
var el = document.querySelector('${s}');
|
|
40
|
+
if (el) {
|
|
41
|
+
el.dispatchEvent(new MouseEvent('mouseenter', {bubbles: true}));
|
|
42
|
+
el.dispatchEvent(new MouseEvent('mouseover', {bubbles: true}));
|
|
43
|
+
el.dispatchEvent(new MouseEvent('mousemove', {bubbles: true}));
|
|
44
|
+
}
|
|
45
|
+
`),{success:!0}}case"hanzo.fill":{if(!o||!t.selector)throw new Error("No active tab or selector");return this.notifyOverlay(o,"ai.control.highlight",{selector:t.selector}),this.notifyOverlay(o,"ai.control.status",{text:`Filling ${t.selector}`}),{success:!!await this.runFunc(o,(a,i)=>{let c=document.querySelector(a);if(!c)return!1;try{c.scrollIntoView({block:"center",behavior:"instant"})}catch{}try{c.focus()}catch{}let l=c.tagName;if(l==="INPUT"||l==="TEXTAREA"||l==="SELECT"){let u=null;try{l==="TEXTAREA"?u=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value")?.set:l==="INPUT"?u=Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype,"value")?.set:l==="SELECT"&&(u=Object.getOwnPropertyDescriptor(window.HTMLSelectElement.prototype,"value")?.set)}catch{u=null}try{u?u.call(c,i):c.value=i}catch{c.value=i}return c.dispatchEvent(new Event("input",{bubbles:!0})),c.dispatchEvent(new Event("change",{bubbles:!0})),!0}return c.isContentEditable?(c.textContent=i,c.dispatchEvent(new Event("input",{bubbles:!0})),!0):!1},[t.selector,t.value||""])}}case"hanzo.type":{if(!o)throw new Error("No active tab");let s=this.escapeValue(t.text||""),a=t.selector?this.escapeSelector(t.selector):null;return await this.runInPage(o,`
|
|
46
|
+
var el = ${a?`document.querySelector('${a}')`:"document.activeElement"};
|
|
47
|
+
if (el && (el.tagName === 'INPUT' || el.tagName === 'TEXTAREA' || el.isContentEditable)) {
|
|
48
|
+
el.focus();
|
|
49
|
+
if (el.isContentEditable) {
|
|
50
|
+
document.execCommand('insertText', false, '${s}');
|
|
51
|
+
} else {
|
|
52
|
+
el.value += '${s}';
|
|
53
|
+
el.dispatchEvent(new Event('input', {bubbles: true}));
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
`),{success:!0}}case"hanzo.clear":{if(!o||!t.selector)throw new Error("No active tab or selector");return{success:!!await this.runFunc(o,a=>{let i=document.querySelector(a);if(!i)return!1;let c=Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype,"value")?.set||Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value")?.set;return c?c.call(i,""):i.value="",i.dispatchEvent(new Event("input",{bubbles:!0})),i.dispatchEvent(new Event("change",{bubbles:!0})),!0},[t.selector])}}case"hanzo.select":{if(!o||!t.selector)throw new Error("No active tab or selector");let s=this.escapeSelector(t.selector),a=this.escapeValue(t.value||"");return await this.runInPage(o,`
|
|
57
|
+
var el = document.querySelector('${s}');
|
|
58
|
+
if (el && el.tagName === 'SELECT') {
|
|
59
|
+
el.value = '${a}';
|
|
60
|
+
el.dispatchEvent(new Event('change', {bubbles: true}));
|
|
61
|
+
}
|
|
62
|
+
`),{success:!0}}case"hanzo.check":{if(!o||!t.selector)throw new Error("No active tab or selector");return{success:!!await this.runFunc(o,a=>{let i=document.querySelector(a);if(!i)return!1;try{i.scrollIntoView({block:"center",behavior:"instant"})}catch{}return i.checked||i.click(),!0},[t.selector])}}case"hanzo.uncheck":{if(!o||!t.selector)throw new Error("No active tab or selector");return{success:!!await this.runFunc(o,a=>{let i=document.querySelector(a);if(!i)return!1;try{i.scrollIntoView({block:"center",behavior:"instant"})}catch{}return i.checked&&i.click(),!0},[t.selector])}}case"Input.dispatchKeyEvent":{if(!o)throw new Error("No active tab");let s=t.key||"",a=t.type||"keyDown";return await this.runInPage(o,`
|
|
63
|
+
var el = document.activeElement || document.body;
|
|
64
|
+
el.dispatchEvent(new KeyboardEvent('${a}', {key: '${this.escapeValue(s)}', bubbles: true}));
|
|
65
|
+
if ('${a}' === 'keyDown') {
|
|
66
|
+
el.dispatchEvent(new KeyboardEvent('keypress', {key: '${this.escapeValue(s)}', bubbles: true}));
|
|
67
|
+
el.dispatchEvent(new KeyboardEvent('keyup', {key: '${this.escapeValue(s)}', bubbles: true}));
|
|
68
|
+
}
|
|
69
|
+
`),{success:!0}}case"hanzo.getText":{if(!o||!t.selector)throw new Error("No active tab or selector");return{result:{value:await this.runFunc(o,a=>{let i=document.querySelector(a);return i?i.textContent||"":null},[t.selector])}}}case"hanzo.getHTML":{if(!o||!t.selector)throw new Error("No active tab or selector");let s=t.outer!==!1;return{result:{value:await this.runFunc(o,(i,c)=>{let l=document.querySelector(i);return l?c?l.outerHTML:l.innerHTML:null},[t.selector,s])}}}case"hanzo.getAttribute":{if(!o||!t.selector||!t.attr)throw new Error("Missing params");let s=this.escapeSelector(t.selector),a=this.escapeValue(t.attr);return{result:{value:await this.runInPage(o,`
|
|
70
|
+
var el = document.querySelector('${s}');
|
|
71
|
+
return el ? el.getAttribute('${a}') : null;
|
|
72
|
+
`)}}}case"hanzo.getElementInfo":{if(!o||!t.selector)throw new Error("No active tab or selector");let s=this.escapeSelector(t.selector);return{result:{value:await this.runInPage(o,`
|
|
73
|
+
var el = document.querySelector('${s}');
|
|
74
|
+
if (!el) return null;
|
|
75
|
+
var rect = el.getBoundingClientRect();
|
|
76
|
+
return {
|
|
77
|
+
tagName: el.tagName, id: el.id, className: el.className,
|
|
78
|
+
textContent: (el.textContent || '').trim().slice(0, 200),
|
|
79
|
+
value: el.value, type: el.type, href: el.href, src: el.src,
|
|
80
|
+
checked: el.checked, disabled: el.disabled,
|
|
81
|
+
visible: !!(rect.width && rect.height),
|
|
82
|
+
rect: { x: rect.x, y: rect.y, width: rect.width, height: rect.height }
|
|
83
|
+
};
|
|
84
|
+
`)}}}case"hanzo.getPageInfo":{if(!o)throw new Error("No active tab");return{result:{value:await this.runInPage(o,`
|
|
85
|
+
return {
|
|
86
|
+
title: document.title,
|
|
87
|
+
url: location.href,
|
|
88
|
+
readyState: document.readyState,
|
|
89
|
+
contentType: document.contentType,
|
|
90
|
+
characterSet: document.characterSet,
|
|
91
|
+
documentElement: { scrollWidth: document.documentElement.scrollWidth, scrollHeight: document.documentElement.scrollHeight },
|
|
92
|
+
body: { scrollWidth: document.body?.scrollWidth, scrollHeight: document.body?.scrollHeight },
|
|
93
|
+
viewport: { width: window.innerWidth, height: window.innerHeight }
|
|
94
|
+
};
|
|
95
|
+
`)}}}case"hanzo.querySelectorAll":{if(!o||!t.selector)throw new Error("No active tab or selector");return{elements:await this.runFunc(o,(a,i)=>{let c=document.querySelectorAll(a),l=[],u=Math.min(c.length,i);for(let g=0;g<u;g++){let d=c[g],m=d.getBoundingClientRect();l.push({index:g,tagName:d.tagName,id:d.id||"",className:typeof d.className=="string"?d.className:"",name:d.getAttribute("name")||"",type:d.getAttribute("type")||"",role:d.getAttribute("role")||"",ariaLabel:d.getAttribute("aria-label")||"",value:d.value||"",href:d.href||"",textContent:(d.textContent||"").trim().slice(0,200),visible:!!(m.width&&m.height)})}return l},[t.selector,t.limit||100])||[]}}case"Input.dispatchMouseEvent":{if(!o)throw new Error("No active tab");return await this.runFunc(o,a=>{let{type:i,x:c,y:l,button:u=0,clickCount:g=1,modifiers:d=0}=a,m=document.elementFromPoint(c,l);if(!m)return{delivered:!1,reason:"no element at point"};let h={altKey:!!(d&1),ctrlKey:!!(d&2),metaKey:!!(d&4),shiftKey:!!(d&8)},p={bubbles:!0,cancelable:!0,view:window,button:u,buttons:i==="mousePressed"?1:0,clientX:c,clientY:l,screenX:c,screenY:l,detail:g,...h},I={mouseMoved:"mousemove",mousePressed:"mousedown",mouseReleased:"mouseup"};return m.dispatchEvent(new MouseEvent(I[i]||i.toLowerCase(),p)),i==="mousePressed"&&g>=1&&m.dispatchEvent(new MouseEvent("click",p)),{delivered:!0,target:m.tagName,x:c,y:l}},[t])}case"Input.scrollWheel":{if(!o)throw new Error("No active tab");return await this.runFunc(o,a=>{let{x:i=0,y:c=0,deltaX:l=0,deltaY:u=0}=a,g=i||c?document.elementFromPoint(i,c):document.scrollingElement||document.body;return g?(g.dispatchEvent(new WheelEvent("wheel",{bubbles:!0,cancelable:!0,deltaX:l,deltaY:u,clientX:i,clientY:c})),(g===document.scrollingElement||g===document.body)&&window.scrollBy({left:l,top:u,behavior:"instant"}),{delivered:!0}):{delivered:!1}},[t])}case"Page.printToPDF":{if(!o)throw new Error("No active tab");return await this.runFunc(o,()=>(window.print(),!0),[]),{opened:!0,note:"Firefox extension cannot programmatically save PDF. For headless PDF export use Page.captureScreenshot with fullPage=true and convert PNG\u2192PDF on the client side."}}case"DOM.querySelector":{if(!o||!t.selector)throw new Error("No active tab or selector");return{element:await this.runFunc(o,a=>{let i=document.querySelector(a);if(!i)return null;let c=i.getBoundingClientRect();return{tagName:i.tagName,id:i.id||"",className:typeof i.className=="string"?i.className:"",textContent:(i.textContent||"").trim().slice(0,200),value:i.value||"",visible:!!(c.width&&c.height),rect:{x:c.x,y:c.y,w:c.width,h:c.height}}},[t.selector])}}case"DOM.scrollIntoView":{if(!o||!t.selector)throw new Error("No active tab or selector");return{success:!!await this.runFunc(o,a=>{let i=document.querySelector(a);return i?(i.scrollIntoView({block:"center",behavior:"smooth"}),!0):!1},[t.selector])}}case"DOM.focus":{if(!o||!t.selector)throw new Error("No active tab or selector");return{success:!!await this.runFunc(o,a=>{let i=document.querySelector(a);return i?(i.focus(),!0):!1},[t.selector])}}case"hanzo.clickByText":{if(!o||!t.text)throw new Error("No active tab or text");return await this.runFunc(o,(a,i)=>{let c=h=>(h||"").replace(/\s+/g," ").trim().toLowerCase(),l=c(a),u=i==="all"?"button, a, input[type=button], input[type=submit], input[type=radio], input[type=checkbox], label, [role=button], [role=radio], [role=checkbox], [role=tab], [role=menuitem]":"button, a, label, [role=button], [role=radio], [role=checkbox], [role=tab], [role=menuitem]",d=Array.from(document.querySelectorAll(u)).filter(h=>{let p=c(h.innerText||h.value||h.getAttribute("aria-label")||"");return p===l||p.includes(l)}),m=d.find(h=>c(h.innerText||h.value||h.getAttribute("aria-label")||"")===l)||d[0];if(!m)return{clicked:!1,candidates:d.length};try{m.scrollIntoView({block:"center",behavior:"instant"})}catch{}return m.click(),{clicked:!0,tag:m.tagName,text:(m.innerText||m.value||"").slice(0,100)}},[t.text,t.scope||"default"])||{clicked:!1}}case"hanzo.fillByLabel":{if(!o||!t.label)throw new Error("No active tab or label");return await this.runFunc(o,(a,i)=>{let c=h=>(h||"").replace(/\s+/g," ").trim().toLowerCase(),l=c(a),u=Array.from(document.querySelectorAll("label")),g=u.find(h=>c(h.innerText)===l)||u.find(h=>c(h.innerText).includes(l)),d=null;if(g){let h=g.getAttribute("for");h&&(d=document.getElementById(h)),d||(d=g.querySelector("input, textarea, select"))}if(d||(d=Array.from(document.querySelectorAll("input, textarea, select")).find(p=>c(p.getAttribute("aria-label")||"")===l||c(p.getAttribute("placeholder")||"")===l||c(p.getAttribute("name")||"")===l||c(p.getAttribute("id")||"")===l)||null),!d)return{filled:!1};try{d.scrollIntoView({block:"center",behavior:"instant"})}catch{}d.focus();let m=d.tagName;if(m==="INPUT"||m==="TEXTAREA"){let h=Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype,"value")?.set||Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value")?.set;return h?h.call(d,i):d.value=i,d.dispatchEvent(new Event("input",{bubbles:!0})),d.dispatchEvent(new Event("change",{bubbles:!0})),{filled:!0,name:d.name||d.id}}return m==="SELECT"?(d.value=i,d.dispatchEvent(new Event("change",{bubbles:!0})),{filled:!0,name:d.name||d.id}):{filled:!1}},[t.label,t.value||""])||{filled:!1}}case"hanzo.findByText":{if(!o||!t.text)throw new Error("Missing text");return{matches:await this.runFunc(o,(a,i,c)=>{let l=h=>(h||"").replace(/\s+/g," ").trim().toLowerCase(),u=l(a),g=i==="all"?"*":"button, a, label, input, select, textarea, [role=button], [role=radio], [role=checkbox], [role=tab], [role=menuitem], h1, h2, h3, h4, h5, h6, p, span, li, td",d=Array.from(document.querySelectorAll(g)),m=[];for(let h=0;h<d.length&&m.length<c;h++){let p=d[h],I=l(p.innerText||p.value||p.getAttribute("aria-label")||"");if(I&&(I===u||I.includes(u))){let P=p.getBoundingClientRect();m.push({index:h,tag:p.tagName,id:p.id||"",className:typeof p.className=="string"?p.className:"",text:I.slice(0,200),exact:I===u,rect:{x:P.x,y:P.y,w:P.width,h:P.height},visible:!!(P.width&&P.height)})}}return m.sort((h,p)=>(p.exact?1:0)-(h.exact?1:0)),m},[t.text,t.scope||"default",t.limit||50])||[]}}case"hanzo.listForm":{if(!o)throw new Error("No active tab");return{inputs:await this.runFunc(o,()=>Array.from(document.querySelectorAll("input, textarea, select, button, label, [role=radio], [role=checkbox], [role=button]")).slice(0,200).map((i,c)=>{let l=i.getBoundingClientRect(),u=i.id?document.querySelector(`label[for="${i.id}"]`):null;return{i:c,tag:i.tagName,type:i.getAttribute("type")||"",name:i.getAttribute("name")||"",id:i.id||"",role:i.getAttribute("role")||"",ariaLabel:i.getAttribute("aria-label")||"",placeholder:i.getAttribute("placeholder")||"",value:i.value||"",checked:!!i.checked,labelText:(u?.innerText||"").trim().slice(0,200),innerText:(i.innerText||"").trim().slice(0,200),visible:!!(l.width&&l.height)}}),[])||[]}}case"hanzo.press":{if(!o||!t.key)throw new Error("Missing key");return await this.runFunc(o,(a,i)=>{let c=document.activeElement||document.body,l={altKey:!!i?.alt,ctrlKey:!!i?.ctrl,metaKey:!!i?.meta,shiftKey:!!i?.shift},g={Enter:13,Tab:9,Escape:27,Backspace:8,Delete:46,ArrowUp:38,ArrowDown:40,ArrowLeft:37,ArrowRight:39,Home:36,End:35,PageUp:33,PageDown:34," ":32}[a]??(a.length===1?a.toUpperCase().charCodeAt(0):0),d={key:a,code:a,keyCode:g,which:g,bubbles:!0,cancelable:!0,...l};if(c.dispatchEvent(new KeyboardEvent("keydown",d)),a.length===1&&c.dispatchEvent(new KeyboardEvent("keypress",d)),c.dispatchEvent(new KeyboardEvent("keyup",d)),a==="Enter"&&c.tagName==="INPUT"){let m=c.form;if(m)try{m.requestSubmit?.()||m.submit?.()}catch{}}return{delivered:!0,target:c.tagName,keyCode:g}},[t.key,t.modifiers||{}])}case"hanzo.scroll":{if(!o)throw new Error("No active tab");return await this.runFunc(o,(a,i)=>{if(a==="top")return window.scrollTo({top:0,behavior:"smooth"}),{scrolled:"top"};if(a==="bottom")return window.scrollTo({top:document.body?.scrollHeight||0,behavior:"smooth"}),{scrolled:"bottom"};if(typeof a=="string"&&a){let c=document.querySelector(a);return c?(c.scrollIntoView({behavior:"smooth",block:"center"}),{scrolled:"into-view",selector:a}):{scrolled:null,error:"selector not found",selector:a}}return i&&(i.x||i.y)?(window.scrollBy({left:i.x||0,top:i.y||0,behavior:"smooth"}),{scrolled:"by",...i}):{scrolled:null,error:"no target or amount"}},[t.target||t.selector||null,t.amount||null])}case"hanzo.waitForText":{if(!o||!t.text)throw new Error("Missing text");let s=t.timeout||15e3,a=t.interval||250,i=Date.now();for(;Date.now()-i<s;){if(await this.runFunc(o,l=>{let u=g=>(g||"").replace(/\s+/g," ").trim().toLowerCase();return u(document.body?.innerText||"").includes(u(l))},[t.text]))return{found:!0,elapsed:Date.now()-i};await new Promise(l=>setTimeout(l,a))}return{found:!1,timedOut:!0,elapsed:Date.now()-i}}case"hanzo.waitForMutation":{if(!o||!t.selector)throw new Error("Missing selector");let s=t.timeout||15e3;return await this.runFunc(o,(i,c)=>new Promise(l=>{if(document.querySelector(i)){l({found:!0,immediate:!0});return}let g=new MutationObserver(()=>{document.querySelector(i)&&(g.disconnect(),l({found:!0,immediate:!1}))});g.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0}),setTimeout(()=>{g.disconnect(),l({found:!1,timedOut:!0})},c)}),[t.selector,s])}case"hanzo.submitForm":{if(!o)throw new Error("No active tab");return await this.runFunc(o,a=>{let i=g=>(g||"").replace(/\s+/g," ").trim().toLowerCase(),c=a?[a]:["submit","continue","next","save","send","agree","accept","ok"],l=c.map(i),u=Array.from(document.querySelectorAll("button, input[type=submit], input[type=button], a[role=button], [role=button], a.btn"));for(let g of l){for(let d of u){let m=i(d.innerText||d.value||d.getAttribute("aria-label")||"");if(m===g){try{d.scrollIntoView({block:"center"})}catch{}return d.click(),{submitted:!0,intent:g,tag:d.tagName,text:m.slice(0,100),exact:!0}}}for(let d of u){let m=i(d.innerText||d.value||d.getAttribute("aria-label")||"");if(m.includes(g)){try{d.scrollIntoView({block:"center"})}catch{}return d.click(),{submitted:!0,intent:g,tag:d.tagName,text:m.slice(0,100),exact:!1}}}}return{submitted:!1,candidates:u.length,intents:c}},[t.intent||null])}case"hanzo.uploadFile":{if(!o||!t.selector||!t.content||!t.name)throw new Error("Need selector, name, content (base64)");return await this.runFunc(o,(a,i,c,l)=>{let u=document.querySelector(a);if(!u)return{uploaded:!1,error:"selector not found"};if(u.tagName!=="INPUT"||u.type!=="file")return{uploaded:!1,error:"not a file input"};let g=atob(l),d=new Uint8Array(g.length);for(let p=0;p<g.length;p++)d[p]=g.charCodeAt(p);let m=new File([d],i,{type:c}),h=new DataTransfer;return h.items.add(m),u.files=h.files,u.dispatchEvent(new Event("input",{bubbles:!0})),u.dispatchEvent(new Event("change",{bubbles:!0})),{uploaded:!0,name:i,size:d.byteLength}},[t.selector,t.name,t.mimeType||"application/octet-stream",t.content])}case"hanzo.dialogAccept":{if(!o)throw new Error("No active tab");return await this.runFunc(o,s=>{let a=window;return a.__hanzo_dialogText=s||"",a.alert=()=>!0,a.confirm=()=>!0,a.prompt=()=>a.__hanzo_dialogText||"",!0},[t.text||""]),{armed:!0}}case"hanzo.observe":{if(!o||!t.name)throw new Error("Missing name");return await this.runFunc(o,(s,a,i)=>{let c=window;c.__hanzo_obs=c.__hanzo_obs||{},c.__hanzo_obs[s]?.observer&&c.__hanzo_obs[s].observer.disconnect(),c.__hanzo_obs[s]={events:[],observer:null};let l=a?document.querySelector(a):document.documentElement;if(!l)return!1;let u=new MutationObserver(g=>{for(let d of g)c.__hanzo_obs[s].events.push({type:d.type,target:d.target?.tagName||"",added:d.addedNodes?.length||0,removed:d.removedNodes?.length||0,attr:d.attributeName||null,ts:Date.now()}),c.__hanzo_obs[s].events.length>500&&c.__hanzo_obs[s].events.shift()});return u.observe(l,i||{childList:!0,subtree:!0,attributes:!0}),c.__hanzo_obs[s].observer=u,!0},[t.name,t.selector||null,t.options||null]),{started:!0,name:t.name}}case"hanzo.observeRead":{if(!o||!t.name)throw new Error("Missing name");return{events:await this.runFunc(o,(a,i)=>{let l=window.__hanzo_obs?.[a];if(!l)return[];let u=l.events.slice();return i!==!1&&(l.events.length=0),u},[t.name,t.clear!==!1])||[]}}case"hanzo.observeStop":{if(!o||!t.name)throw new Error("Missing name");return await this.runFunc(o,s=>{let a=window,i=a.__hanzo_obs?.[s];return i?.observer&&i.observer.disconnect(),a.__hanzo_obs&&delete a.__hanzo_obs[s],!0},[t.name]),{stopped:!0,name:t.name}}case"hanzo.getComputedStyles":{if(!o||!t.selector)throw new Error("No active tab or selector");let s=this.escapeSelector(t.selector),a=t.properties||["display","visibility","opacity","position","color","backgroundColor","fontSize"],i=JSON.stringify(a);return{result:{value:await this.runInPage(o,`
|
|
96
|
+
var el = document.querySelector('${s}');
|
|
97
|
+
if (!el) return null;
|
|
98
|
+
var cs = window.getComputedStyle(el);
|
|
99
|
+
var props = ${i};
|
|
100
|
+
var result = {};
|
|
101
|
+
props.forEach(function(p) { result[p] = cs.getPropertyValue(p) || cs[p]; });
|
|
102
|
+
return result;
|
|
103
|
+
`)}}}case"hanzo.getBoundingRects":{if(!o||!t.selector)throw new Error("No active tab or selector");let s=this.escapeSelector(t.selector);return{result:{value:await this.runInPage(o,`
|
|
104
|
+
var el = document.querySelector('${s}');
|
|
105
|
+
if (!el) return null;
|
|
106
|
+
var r = el.getBoundingClientRect();
|
|
107
|
+
return { x: r.x, y: r.y, width: r.width, height: r.height, top: r.top, right: r.right, bottom: r.bottom, left: r.left };
|
|
108
|
+
`)}}}case"hanzo.setText":{if(!o||!t.selector)throw new Error("No active tab or selector");let s=this.escapeSelector(t.selector),a=this.escapeValue(t.text||"");return await this.runInPage(o,`
|
|
109
|
+
var el = document.querySelector('${s}');
|
|
110
|
+
if (el) el.textContent = '${a}';
|
|
111
|
+
`),{success:!0}}case"hanzo.setHTML":{if(!o||!t.selector)throw new Error("No active tab or selector");let s=this.escapeSelector(t.selector),a=this.escapeValue(t.html||""),i=t.outer===!0;return await this.runInPage(o,`
|
|
112
|
+
var el = document.querySelector('${s}');
|
|
113
|
+
if (el) ${i?`el.outerHTML = '${a}'`:`el.innerHTML = '${a}'`};
|
|
114
|
+
`),{success:!0}}case"hanzo.setAttribute":{if(!o||!t.selector||!t.attr)throw new Error("Missing params");let s=this.escapeSelector(t.selector),a=this.escapeValue(t.attr),i=this.escapeValue(t.value||"");return await this.runInPage(o,`
|
|
115
|
+
var el = document.querySelector('${s}');
|
|
116
|
+
if (el) el.setAttribute('${a}', '${i}');
|
|
117
|
+
`),{success:!0}}case"hanzo.removeAttribute":{if(!o||!t.selector||!t.attr)throw new Error("Missing params");let s=this.escapeSelector(t.selector),a=this.escapeValue(t.attr);return await this.runInPage(o,`
|
|
118
|
+
var el = document.querySelector('${s}');
|
|
119
|
+
if (el) el.removeAttribute('${a}');
|
|
120
|
+
`),{success:!0}}case"hanzo.setStyle":{if(!o||!t.selector||!t.styles)throw new Error("Missing params");let s=this.escapeSelector(t.selector),a=JSON.stringify(t.styles);return await this.runInPage(o,`
|
|
121
|
+
var el = document.querySelector('${s}');
|
|
122
|
+
if (el) {
|
|
123
|
+
var styles = ${a};
|
|
124
|
+
for (var k in styles) { if (styles.hasOwnProperty(k)) el.style[k] = styles[k]; }
|
|
125
|
+
}
|
|
126
|
+
`),{success:!0}}case"hanzo.addClass":{if(!o||!t.selector||!t.classNames)throw new Error("Missing params");let s=this.escapeSelector(t.selector),a=Array.isArray(t.classNames)?t.classNames:[t.classNames],i=JSON.stringify(a);return await this.runInPage(o,`
|
|
127
|
+
var el = document.querySelector('${s}');
|
|
128
|
+
if (el) el.classList.add.apply(el.classList, ${i});
|
|
129
|
+
`),{success:!0}}case"hanzo.removeClass":{if(!o||!t.selector||!t.classNames)throw new Error("Missing params");let s=this.escapeSelector(t.selector),a=Array.isArray(t.classNames)?t.classNames:[t.classNames],i=JSON.stringify(a);return await this.runInPage(o,`
|
|
130
|
+
var el = document.querySelector('${s}');
|
|
131
|
+
if (el) el.classList.remove.apply(el.classList, ${i});
|
|
132
|
+
`),{success:!0}}case"hanzo.insertElement":{if(!o||!t.selector||!t.html)throw new Error("Missing params");let s=this.escapeSelector(t.selector),a=this.escapeValue(t.html),i=t.position||"beforeend";return await this.runInPage(o,`
|
|
133
|
+
var el = document.querySelector('${s}');
|
|
134
|
+
if (el) el.insertAdjacentHTML('${i}', '${a}');
|
|
135
|
+
`),{success:!0}}case"hanzo.removeElement":{if(!o||!t.selector)throw new Error("No active tab or selector");let s=this.escapeSelector(t.selector);return await this.runInPage(o,`
|
|
136
|
+
var el = document.querySelector('${s}');
|
|
137
|
+
if (el) el.remove();
|
|
138
|
+
`),{success:!0}}case"hanzo.observeMutations":{if(!o||!t.selector)throw new Error("No active tab or selector");let s=this.escapeSelector(t.selector),a=t.duration||3e3;return{mutations:await this.runInPage(o,`
|
|
139
|
+
return new Promise(function(resolve) {
|
|
140
|
+
var el = document.querySelector('${s}') || document.body;
|
|
141
|
+
var records = [];
|
|
142
|
+
var obs = new MutationObserver(function(muts) {
|
|
143
|
+
muts.forEach(function(m) {
|
|
144
|
+
records.push({
|
|
145
|
+
type: m.type,
|
|
146
|
+
target: m.target.tagName + (m.target.id ? '#' + m.target.id : ''),
|
|
147
|
+
addedNodes: m.addedNodes.length,
|
|
148
|
+
removedNodes: m.removedNodes.length,
|
|
149
|
+
attributeName: m.attributeName
|
|
150
|
+
});
|
|
151
|
+
});
|
|
152
|
+
});
|
|
153
|
+
obs.observe(el, { childList: true, attributes: true, subtree: true, characterData: true });
|
|
154
|
+
setTimeout(function() { obs.disconnect(); resolve(records.slice(0, 50)); }, ${Math.min(a,1e4)});
|
|
155
|
+
});
|
|
156
|
+
`,a+2e3)||[]}}case"hanzo.waitForSelector":{if(!o||!t.selector)throw new Error("No active tab or selector");let s=this.escapeSelector(t.selector),a=t.timeout||1e4;return{found:!!await this.runInPage(o,`
|
|
157
|
+
return new Promise(function(resolve) {
|
|
158
|
+
var el = document.querySelector('${s}');
|
|
159
|
+
if (el) { resolve(true); return; }
|
|
160
|
+
var obs = new MutationObserver(function() {
|
|
161
|
+
var el = document.querySelector('${s}');
|
|
162
|
+
if (el) { obs.disconnect(); resolve(true); }
|
|
163
|
+
});
|
|
164
|
+
obs.observe(document.body, { childList: true, subtree: true });
|
|
165
|
+
setTimeout(function() { obs.disconnect(); resolve(false); }, ${Math.min(a,3e4)});
|
|
166
|
+
});
|
|
167
|
+
`,a+2e3)}}case"hanzo.injectScript":{if(!o||!t.url)throw new Error("No active tab or url");let s=this.escapeValue(t.url);return await this.runInPage(o,`
|
|
168
|
+
return new Promise(function(resolve) {
|
|
169
|
+
var s = document.createElement('script');
|
|
170
|
+
s.src = '${s}';
|
|
171
|
+
s.onload = function() { resolve(true); };
|
|
172
|
+
s.onerror = function() { resolve(false); };
|
|
173
|
+
document.head.appendChild(s);
|
|
174
|
+
});
|
|
175
|
+
`,15e3),{success:!0}}case"hanzo.injectCSS":{if(!o||!t.css)throw new Error("No active tab or css");let s=this.escapeValue(t.css);return await this.runInPage(o,`
|
|
176
|
+
var style = document.createElement('style');
|
|
177
|
+
style.textContent = '${s}';
|
|
178
|
+
document.head.appendChild(style);
|
|
179
|
+
`),{success:!0}}case"hanzo.getLocalStorage":{if(!o)throw new Error("No active tab");let s=t.key?this.escapeValue(t.key):null;return{result:{value:await this.runInPage(o,s?`return localStorage.getItem('${s}');`:`
|
|
180
|
+
var result = {};
|
|
181
|
+
for (var i = 0; i < localStorage.length; i++) {
|
|
182
|
+
var k = localStorage.key(i);
|
|
183
|
+
result[k] = localStorage.getItem(k);
|
|
184
|
+
}
|
|
185
|
+
return result;
|
|
186
|
+
`)}}}case"hanzo.setLocalStorage":{if(!o||!t.key)throw new Error("No active tab or key");let s=this.escapeValue(t.key),a=this.escapeValue(t.value||"");return await this.runInPage(o,`localStorage.setItem('${s}', '${a}');`),{success:!0}}case"hanzo.getCookies":try{let s=r?.url||"";return{cookies:(await browser.cookies.getAll({url:s})).map(i=>({name:i.name,value:i.value,domain:i.domain,path:i.path,secure:i.secure,httpOnly:i.httpOnly}))}}catch{return{cookies:[],error:"cookies API not available"}}case"hanzo.fetch":{if(!o||!t.url)throw new Error("No active tab or url");let s=this.escapeValue(t.url),a=t.options||{},i=JSON.stringify(a);return await this.runInPage(o,`
|
|
187
|
+
return fetch('${s}', ${i}).then(function(r) {
|
|
188
|
+
return r.text().then(function(body) {
|
|
189
|
+
return { status: r.status, statusText: r.statusText, ok: r.ok, body: body.slice(0, 50000) };
|
|
190
|
+
});
|
|
191
|
+
});
|
|
192
|
+
`,3e4)||{error:"fetch failed"}}case"hanzo.control.start":{let s=await this.resolveControlTabId(t.tabId);if(s)return await this.startControlSession(s,t.task),{success:!0};throw new Error("No active tab")}case"hanzo.control.stop":return await this.stopControlSession(),{success:!0};case"Browser.getVersion":return{protocolVersion:"1.3",product:"Hanzo Firefox Extension",userAgent:navigator.userAgent};default:return console.warn("[Hanzo] Unknown method:",n),{error:`Unknown method: ${n}`}}}async handleExtensionRequest(n,t){let r=t.tabId||await this.getActiveTabId()||void 0;if(n.startsWith("monitor.")){if(!r)return{error:"No active tab for monitoring"};switch(n){case"monitor.consoleLogs":return this.runInPage(r,`
|
|
193
|
+
return (window.__hanzo_console_logs || []).slice(-50);
|
|
194
|
+
`).then(o=>({logs:o||[]})).catch(()=>({logs:[]}));case"monitor.consoleErrors":return this.runInPage(r,`
|
|
195
|
+
return (window.__hanzo_console_errors || []).slice(-50);
|
|
196
|
+
`).then(o=>({errors:o||[]})).catch(()=>({errors:[]}));case"monitor.networkLogs":case"monitor.networkErrors":case"monitor.networkSuccess":return{logs:[],note:"Network monitoring requires devtools API (not available in MV3 extensions)"};case"monitor.wipeLogs":return this.runInPage(r,`
|
|
197
|
+
window.__hanzo_console_logs = [];
|
|
198
|
+
window.__hanzo_console_errors = [];
|
|
199
|
+
`).then(()=>({success:!0})).catch(()=>({success:!1}));case"monitor.start":return this.runInPage(r,`
|
|
200
|
+
if (!window.__hanzo_monitor_active) {
|
|
201
|
+
window.__hanzo_console_logs = [];
|
|
202
|
+
window.__hanzo_console_errors = [];
|
|
203
|
+
var origLog = console.log, origErr = console.error, origWarn = console.warn;
|
|
204
|
+
console.log = function() { window.__hanzo_console_logs.push({type:'log', args: Array.from(arguments).map(String), ts: Date.now()}); origLog.apply(console, arguments); };
|
|
205
|
+
console.error = function() { window.__hanzo_console_errors.push({type:'error', args: Array.from(arguments).map(String), ts: Date.now()}); origErr.apply(console, arguments); };
|
|
206
|
+
console.warn = function() { window.__hanzo_console_logs.push({type:'warn', args: Array.from(arguments).map(String), ts: Date.now()}); origWarn.apply(console, arguments); };
|
|
207
|
+
window.__hanzo_monitor_active = true;
|
|
208
|
+
}
|
|
209
|
+
`).then(()=>({success:!0})).catch(()=>({success:!1}));case"monitor.stop":return{success:!0};case"monitor.status":return{active:!1};default:return{error:`Unknown monitor action: ${n}`}}}if(n.startsWith("audit.")){if(!r)return{error:"No active tab for audit"};switch(n){case"audit.accessibility":return this.runInPage(r,`
|
|
210
|
+
var issues = [];
|
|
211
|
+
document.querySelectorAll('img').forEach(function(img) { if (!img.alt) issues.push({type:'missing-alt', el:img.tagName, src:img.src?.slice(0,80)}); });
|
|
212
|
+
document.querySelectorAll('a').forEach(function(a) { if (!a.textContent?.trim() && !a.getAttribute('aria-label')) issues.push({type:'empty-link', href:a.href?.slice(0,80)}); });
|
|
213
|
+
document.querySelectorAll('input,textarea,select').forEach(function(el) {
|
|
214
|
+
if (!el.getAttribute('aria-label') && !el.labels?.length && !el.placeholder) issues.push({type:'unlabeled-input', name:el.name, id:el.id});
|
|
215
|
+
});
|
|
216
|
+
return { issues: issues.slice(0, 50), total: issues.length };
|
|
217
|
+
`).then(o=>({audit:o})).catch(o=>({error:o.message}));case"audit.performance":return this.runInPage(r,`
|
|
218
|
+
var p = performance;
|
|
219
|
+
var nav = p.getEntriesByType('navigation')[0] || {};
|
|
220
|
+
return {
|
|
221
|
+
domContentLoaded: nav.domContentLoadedEventEnd,
|
|
222
|
+
load: nav.loadEventEnd,
|
|
223
|
+
resources: p.getEntriesByType('resource').length,
|
|
224
|
+
domNodes: document.querySelectorAll('*').length
|
|
225
|
+
};
|
|
226
|
+
`).then(o=>({audit:o})).catch(o=>({error:o.message}));case"audit.seo":return this.runInPage(r,`
|
|
227
|
+
return {
|
|
228
|
+
title: document.title,
|
|
229
|
+
metaDescription: document.querySelector('meta[name="description"]')?.content || null,
|
|
230
|
+
h1Count: document.querySelectorAll('h1').length,
|
|
231
|
+
canonical: document.querySelector('link[rel="canonical"]')?.href || null,
|
|
232
|
+
ogTitle: document.querySelector('meta[property="og:title"]')?.content || null,
|
|
233
|
+
ogDescription: document.querySelector('meta[property="og:description"]')?.content || null
|
|
234
|
+
};
|
|
235
|
+
`).then(o=>({audit:o})).catch(o=>({error:o.message}));default:return{error:`Audit type not implemented: ${n}`}}}if(n==="debugger.mode")return{error:"Debugger mode requires devtools API (not available in MV3)"};if(n.startsWith("ollama.")||n.startsWith("local.")||n.startsWith("hub."))return{error:`${n} not yet implemented in Firefox extension`};try{return await this.executeMethod(n,t||{})}catch(o){return{error:o&&o.message||String(o)}}}notifyOverlay(n,t,r){browser.tabs.sendMessage(n,{action:t,...r}).catch(()=>{})}async getActiveTabId(){let[n]=await browser.tabs.query({active:!0,currentWindow:!0});return n?.id??null}async resolveControlTabId(n){return typeof n=="number"?n:k.active&&k.tabId!==null?k.tabId:this.getActiveTabId()}async startControlSession(n,t){k.active&&k.tabId!==null&&k.tabId!==n&&this.notifyOverlay(k.tabId,"ai.control.stop",{}),k.active=!0,k.tabId=n,k.task=t||"AI is controlling this page",k.startedAt=Date.now(),this.notifyOverlay(n,"ai.control.start",{task:k.task})}async stopControlSession(){k.active&&k.tabId!==null&&this.notifyOverlay(k.tabId,"ai.control.stop",{}),k.active=!1,k.tabId=null,k.task=null,k.startedAt=null}escapeSelector(n){return n.replace(/'/g,"\\'")}escapeValue(n){return n.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n")}},rr=`${Oe}${Z}`,le=Jt();async function ve(){return De(le.storage)}browser.runtime.onMessage.addListener((e,n,t)=>((async()=>{if(!(typeof e.action=="string"&&Ve.handle(e.action,e,t)))switch(e.action){case"drive":t(await er(browser,n,e,(r,o)=>z.dispatchMethod(r,o)));break;case"auth.login":try{let r=await Wt(le);t({success:!0,user:r})}catch(r){t({success:!1,error:r.message})}break;case"auth.signup":try{await Zt(le),t({success:!0})}catch(r){t({success:!1,error:r.message})}break;case"auth.logout":await de(le.storage),t({success:!0});break;case"auth.status":{let r=await Yt(le.storage);t({success:!0,authenticated:r.authenticated,user:r.user});break}case"auth.getToken":{let r=await browser.storage.local.get([E.accessToken]);t({success:!!r[E.accessToken],token:r[E.accessToken]||null});break}case"rag.query":{try{let r=await Kt(browser.storage.local),o=Number.parseInt(String(e.topK??r.topK),10),s={query:String(e.query||"").trim(),topK:Number.isFinite(o)?Math.max(1,Math.min(o,20)):5,knowledgeBase:String(e.knowledgeBase??r.knowledgeBase??"").trim(),includeTabContext:e.includeTabContext!==void 0?!!e.includeTabContext:r.includeTabContext,endpoint:String(e.endpoint??r.endpoint??"").trim(),apiKey:String(e.apiKey??r.apiKey??"").trim(),pageContext:e.pageContext&&typeof e.pageContext=="object"?{url:e.pageContext.url?String(e.pageContext.url):void 0,title:e.pageContext.title?String(e.pageContext.title):void 0}:void 0};if(!s.query){t({success:!1,error:"Query is required"});break}let a=s.endpoint?await Ft(s):[],i=a.length?"rag-endpoint":"none";t({success:!0,source:i,snippets:a.slice(0,s.topK)})}catch(r){t({success:!1,error:r.message})}break}case"chat.listModels":{try{let r=await ve();if(!r){t({success:!1,error:"Not authenticated"});break}let s=await(await fetch(`${te}/v1/models`,{headers:{Authorization:`Bearer ${r}`},signal:AbortSignal.timeout(1e4)})).json();t({success:!0,models:s.data||s.models||s||[]})}catch(r){t({success:!1,error:r.message})}break}case"chat.complete":{try{let r=await ve();if(!r){t({success:!1,error:"Not authenticated"});break}let o=(Array.isArray(e.messages)?e.messages:[]).filter(u=>u&&typeof u.content=="string"&&typeof u.role=="string").map(u=>({role:u.role==="system"||u.role==="assistant"?u.role:"user",content:String(u.content)}));if(!o.length){t({success:!1,error:"messages are required"});break}let s=String(e.model||"auto"),a={model:s,messages:o,stream:!1};typeof e.temperature=="number"&&(a.temperature=e.temperature),typeof e.max_tokens=="number"&&(a.max_tokens=Math.max(64,Math.min(e.max_tokens,16384)));let i=await fetch(`${te}/v1/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify(a),signal:AbortSignal.timeout(12e4)});if(!i.ok){let u=await i.text();throw new Error(`Chat API error ${i.status}: ${u}`)}let c=await i.json(),l=c.choices?.[0]?.message?.content||"";t({success:!0,content:l,model:c.model||s})}catch(r){t({success:!1,error:r.message})}break}case"chat.cancel":t({success:!0});break;case"models.list":{try{let r=await ve();if(!r){try{let i=await(await fetch(`${te}/v1/models`,{signal:AbortSignal.timeout(5e3)})).json();t({success:!0,models:i.data||[],authenticated:!1})}catch{t({success:!0,models:[],authenticated:!1})}break}let s=await(await fetch(`${te}/v1/models`,{headers:{Authorization:`Bearer ${r}`},signal:AbortSignal.timeout(1e4)})).json();t({success:!0,models:s.data||s.models||[],authenticated:!0})}catch(r){t({success:!1,error:r.message})}break}case"checkWebGPU":{try{if(typeof navigator>"u"||!navigator.gpu){t({available:!1});break}let r=await navigator.gpu.requestAdapter();t({available:!!r,adapter:r?.name||"Unknown GPU",models:[]})}catch{t({available:!1})}break}case"runLocalAI":t({success:!1,error:"WebGPU inference not available in Firefox background"});break;case"listAgents":t({success:!0,agents:[]});break;case"stopAgent":t({success:!1,error:"Agent workers are not available in Firefox background mode"});break;case"launchAIWorker":t({success:!1,error:"launchAIWorker not implemented in Firefox background mode"});break;case"ollama.discover":{try{let r=["http://localhost:11434","http://127.0.0.1:11434"],o=!1,s="";for(let a of r)try{if((await fetch(a,{signal:AbortSignal.timeout(2e3)})).ok){o=!0,s=a;break}}catch{}t({success:!0,discovered:o,url:s,available:o})}catch(r){t({success:!1,error:r.message})}break}case"ollama.health":{try{let o=(await browser.storage.local.get(["ollamaUrl"])).ollamaUrl||"http://localhost:11434",s=await fetch(o,{signal:AbortSignal.timeout(3e3)});t({success:!0,available:s.ok,url:o})}catch(r){t({success:!1,available:!1,error:r.message})}break}case"ollama.models":{try{let o=(await browser.storage.local.get(["ollamaUrl"])).ollamaUrl||"http://localhost:11434",s=await fetch(`${o}/api/tags`,{signal:AbortSignal.timeout(5e3)});if(!s.ok)throw new Error(`HTTP ${s.status}`);let a=await s.json();t({success:!0,models:a.models||[]})}catch(r){t({success:!1,error:r.message})}break}case"ollama.chat":{try{let o=(await browser.storage.local.get(["ollamaUrl"])).ollamaUrl||"http://localhost:11434",s=await fetch(`${o}/api/chat`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:e.model,messages:e.messages,stream:!1,...e.options||{}}),signal:AbortSignal.timeout(12e4)});if(!s.ok)throw new Error(`Ollama ${s.status}`);let a=await s.json();t({success:!0,content:a.message?.content||""})}catch(r){t({success:!1,error:r.message})}break}case"ollama.generate":{try{let o=(await browser.storage.local.get(["ollamaUrl"])).ollamaUrl||"http://localhost:11434",s=await fetch(`${o}/api/generate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:e.model,prompt:e.prompt,stream:!1,...e.options||{}}),signal:AbortSignal.timeout(12e4)});if(!s.ok)throw new Error(`Ollama ${s.status}`);let a=await s.json();t({success:!0,content:a.response||""})}catch(r){t({success:!1,error:r.message})}break}case"ollama.embed":{try{let o=(await browser.storage.local.get(["ollamaUrl"])).ollamaUrl||"http://localhost:11434",s=await fetch(`${o}/api/embeddings`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:e.model,prompt:e.input}),signal:AbortSignal.timeout(3e4)});if(!s.ok)throw new Error(`Ollama ${s.status}`);let a=await s.json();t({success:!0,embedding:a.embedding||[]})}catch(r){t({success:!1,error:r.message})}break}case"ollama.status":{let r=await browser.storage.local.get(["ollamaUrl"]);t({success:!0,url:r.ollamaUrl||"http://localhost:11434",available:!1});break}case"ollama.setUrl":{await browser.storage.local.set({ollamaUrl:e.url}),t({success:!0});break}case"ollama.pull":{try{let o=(await browser.storage.local.get(["ollamaUrl"])).ollamaUrl||"http://localhost:11434";fetch(`${o}/api/pull`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e.model,stream:!1})}).then(()=>{browser.storage.local.set({"ollama.pull.progress":{model:e.model,status:"done",timestamp:Date.now()}})}).catch(s=>{browser.storage.local.set({"ollama.pull.progress":{model:e.model,status:"error",error:s.message,timestamp:Date.now()}})}),t({success:!0,started:!0})}catch(r){t({success:!1,error:r.message})}break}case"ollama.delete":{try{let o=(await browser.storage.local.get(["ollamaUrl"])).ollamaUrl||"http://localhost:11434";await fetch(`${o}/api/delete`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e.model})}),t({success:!0})}catch(r){t({success:!1,error:r.message})}break}case"local.chat":{try{let r=e.provider||"ollama",o=e.endpoint,s=e.model,a=e.messages,i=e.options||{},c;if(r==="ollama"&&!o){let u=(await browser.storage.local.get(["ollamaUrl"])).ollamaUrl||"http://localhost:11434",g=await fetch(`${u}/api/chat`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:s,messages:a,stream:!1,...i}),signal:AbortSignal.timeout(12e4)});if(!g.ok)throw new Error(`Ollama ${g.status}`);c=(await g.json()).message?.content||""}else if(r==="anthropic"){let l=o||"https://api.anthropic.com",u=a.find(p=>p.role==="system"),g=a.filter(p=>p.role!=="system"),d={model:s,max_tokens:i.num_predict||4096,messages:g,stream:!1};u&&(d.system=u.content),i.temperature!==void 0&&(d.temperature=i.temperature);let m=await fetch(`${l}/v1/messages`,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":e.apiKey||"","anthropic-version":"2023-06-01"},body:JSON.stringify(d),signal:AbortSignal.timeout(12e4)});if(!m.ok)throw new Error(`Anthropic: ${m.status} ${await m.text()}`);c=(await m.json()).content?.[0]?.text||""}else{let l=j[r],u=o||(l?`${l.url}/v1`:"http://localhost:8080/v1"),g={"Content-Type":"application/json"};e.apiKey&&(g.Authorization=`Bearer ${e.apiKey}`);let d={model:s,messages:a,stream:!1};i.temperature!==void 0&&(d.temperature=i.temperature),i.num_predict!==void 0&&(d.max_tokens=i.num_predict);let m=await fetch(`${u}/chat/completions`,{method:"POST",headers:g,body:JSON.stringify(d),signal:AbortSignal.timeout(12e4)});if(!m.ok)throw new Error(`${r}: ${m.status} ${await m.text()}`);c=(await m.json()).choices?.[0]?.message?.content||""}t({success:!0,content:c})}catch(r){t({success:!1,error:r.message})}break}case"local.models":{try{let r=j[e.provider],o=e.endpoint||(e.provider==="ollama"?null:r?`${r.url}/v1`:e.endpoint||"http://localhost:8080/v1");if(!o){let l=(await browser.storage.local.get(["ollamaUrl"])).ollamaUrl||j.ollama.url,u=await fetch(`${l}/api/tags`,{signal:AbortSignal.timeout(5e3)});if(!u.ok)throw new Error(`HTTP ${u.status}`);let g=await u.json();t({success:!0,models:(g.models||[]).map(d=>({id:d.name,name:d.name,size:d.size,details:d.details}))});break}let s={};e.apiKey&&(s.Authorization=`Bearer ${e.apiKey}`);let a=await fetch(`${o}/models`,{headers:s,signal:AbortSignal.timeout(5e3)});if(!a.ok)throw new Error(`HTTP ${a.status}`);let i=await a.json();t({success:!0,models:i.data||i.models||[]})}catch(r){t({success:!1,error:r.message})}break}case"local.discover":{let r=[];try{let i=(await browser.storage.local.get(["ollamaUrl"])).ollamaUrl||j.ollama.url,c=await fetch(`${i}/api/tags`,{signal:AbortSignal.timeout(2e3)});if(c.ok){let l=await c.json();r.push({name:"ollama",url:i,available:!0,models:(l.models||[]).map(u=>u.name)})}else r.push({name:"ollama",url:i,available:!1})}catch{r.push({name:"ollama",url:j.ollama.url,available:!1})}{let a=j.lmstudio;try{let i=await fetch(`${a.url}/models`,{signal:AbortSignal.timeout(2e3)});if(i.ok){let c=await i.json();r.push({name:"lmstudio",url:a.url,available:!0,models:(c.data||[]).map(l=>l.id)})}else r.push({name:"lmstudio",url:a.url,available:!1})}catch{r.push({name:"lmstudio",url:a.url,available:!1})}}{let a=j["hanzo-desktop"];for(let i of a.probePorts)try{let c=await fetch(`http://localhost:${i}/api/tags`,{signal:AbortSignal.timeout(2e3)});if(c.ok){let l=await c.json();r.push({name:"hanzo-desktop",url:`http://localhost:${i}`,available:!0,models:(l.models||[]).map(u=>u.name)});break}}catch{}r.find(i=>i.name==="hanzo-desktop")||r.push({name:"hanzo-desktop",url:a.url,available:!1})}let s=(await browser.storage.local.get(["customLLMEndpoints"])).customLLMEndpoints||[];for(let a of s)try{let i={};a.apiKey&&(i.Authorization=`Bearer ${a.apiKey}`);let c=await fetch(`${a.url}/models`,{headers:i,signal:AbortSignal.timeout(3e3)});if(c.ok){let l=await c.json();r.push({name:a.name||"custom",url:a.url,available:!0,models:(l.data||l.models||[]).map(u=>u.id||u.name)})}else r.push({name:a.name||"custom",url:a.url,available:!1})}catch{r.push({name:a.name||"custom",url:a.url,available:!1})}t({success:!0,providers:r});break}case"provider.save":{try{let o=(await browser.storage.local.get(["customLLMEndpoints"])).customLLMEndpoints||[],s=o.findIndex(i=>i.name===e.name||i.url===e.url),a={name:e.name,url:e.url,apiKey:e.apiKey};s>=0?o[s]=a:o.push(a),await browser.storage.local.set({customLLMEndpoints:o}),t({success:!0})}catch(r){t({success:!1,error:r.message})}break}case"provider.remove":{try{let o=((await browser.storage.local.get(["customLLMEndpoints"])).customLLMEndpoints||[]).filter(s=>s.name!==e.name&&s.url!==e.url);await browser.storage.local.set({customLLMEndpoints:o}),t({success:!0})}catch(r){t({success:!1,error:r.message})}break}case"provider.test":{try{let r={};e.apiKey&&(r.Authorization=`Bearer ${e.apiKey}`);let o=await fetch(`${e.url}/models`,{headers:r,signal:AbortSignal.timeout(5e3)});if(!o.ok)throw new Error(`HTTP ${o.status}`);let s=await o.json();t({success:!0,models:(s.data||s.models||[]).map(a=>a.id||a.name)})}catch(r){t({success:!1,error:r.message})}break}case"settings.get":{try{let r=e.keys||["selectedProvider","selectedModel","customLLMEndpoints","ollamaUrl","anthropicApiKey","openaiApiKey","hanzoApiKey","mcpPort","cdpPort","activeOrgId","browserBackend"],o=await browser.storage.local.get(r);t({success:!0,settings:o})}catch(r){t({success:!1,error:r.message})}break}case"settings.set":{try{await browser.storage.local.set(e.settings),t({success:!0})}catch(r){t({success:!1,error:r.message})}break}case"settings.export":{try{let r=await browser.storage.local.get(null),o={};for(let[s,a]of Object.entries(r))s.startsWith("hanzo_iam_")||(o[s]=a);t({success:!0,settings:o})}catch(r){t({success:!1,error:r.message})}break}case"settings.import":{try{let r=e.settings||{};delete r.hanzo_iam_access_token,delete r.hanzo_iam_refresh_token,delete r.hanzo_iam_id_token,await browser.storage.local.set(r),t({success:!0})}catch(r){t({success:!1,error:r.message})}break}case"settings.sync":t({success:!0});break;case"config.save":{try{e.key&&await browser.storage.local.set({[e.key]:e.value}),t({success:!0})}catch(r){t({success:!1,error:r.message})}break}case"apikey.save":{try{await browser.storage.local.set({[`apikey_${e.provider}`]:e.apiKey}),t({success:!0})}catch(r){t({success:!1,error:r.message})}break}case"apikey.get":{try{let r=`apikey_${e.provider}`,o=await browser.storage.local.get([r]);t({success:!0,apiKey:o[r]||null})}catch(r){t({success:!1,error:r.message})}break}case"apikey.list":{try{let r=await browser.storage.local.get(null),o=[];for(let[s]of Object.entries(r))s.startsWith("apikey_")&&o.push({provider:s.replace("apikey_",""),hasKey:!0});t({success:!0,keys:o})}catch(r){t({success:!1,error:r.message})}break}case"org.list":{try{let r=await ve();if(!r){t({success:!1,error:"Not authenticated"});break}let o=await fetch(`${rr}/account`,{headers:{Authorization:`Bearer ${r}`},signal:AbortSignal.timeout(5e3)});if(!o.ok)throw new Error(`IAM: ${o.status}`);let s=await o.json(),a=s.data||s,i=[];a.owner&&i.push({id:a.owner,name:a.owner,displayName:a.owner});try{let l=await fetch(`${rr}/organizations`,{headers:{Authorization:`Bearer ${r}`},signal:AbortSignal.timeout(5e3)});if(l.ok){let u=await l.json();for(let g of u.organizations||[])i.find(d=>d.id===g.name)||i.push({id:g.name,name:g.name,displayName:g.displayName||g.name})}}catch{}let c=await browser.storage.local.get(["activeOrgId"]);t({success:!0,orgs:i,activeOrgId:c.activeOrgId||i[0]?.id||null,user:{name:a.displayName||a.name,email:a.email,avatar:a.avatar}})}catch(r){t({success:!1,error:r.message})}break}case"org.switch":{try{await browser.storage.local.set({activeOrgId:e.orgId}),t({success:!0,activeOrgId:e.orgId})}catch(r){t({success:!1,error:r.message})}break}case"hub.search":{try{let r=encodeURIComponent(e.query||""),o=e.limit||10,s=await fetch(`https://huggingface.co/api/models?search=${r}&limit=${o}&sort=downloads&direction=-1`,{signal:AbortSignal.timeout(1e4)});if(!s.ok)throw new Error(`HuggingFace ${s.status}`);t({success:!0,models:await s.json()})}catch(r){t({success:!1,error:r.message})}break}case"hub.model":{try{let r=await fetch(`https://huggingface.co/api/models/${e.modelId}`,{signal:AbortSignal.timeout(1e4)});if(!r.ok)throw new Error(`HuggingFace ${r.status}`);t({success:!0,model:await r.json()})}catch(r){t({success:!1,error:r.message})}break}case"hub.recommended":t({success:!0,models:[]});break;case"hub.searchOllama":{try{let r=await fetch(`https://ollama.com/api/tags?q=${encodeURIComponent(e.query||"")}`,{signal:AbortSignal.timeout(1e4)});r.ok?t({success:!0,models:await r.json()}):t({success:!0,models:[]})}catch{t({success:!0,models:[]})}break}case"hub.searchGGUF":case"hub.searchMLX":case"hub.modelCard":case"hub.modelStats":case"hub.allModels":t({success:!0,models:[],card:null,stats:null,cloud:[],local:[],recommended:[]});break;case"hub.downloadOllama":{try{let o=(await browser.storage.local.get(["ollamaUrl"])).ollamaUrl||"http://localhost:11434";fetch(`${o}/api/pull`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e.modelName,stream:!1})}).catch(()=>{}),t({success:!0})}catch(r){t({success:!1,error:r.message})}break}case"elementSelected":t({success:!0});break;case"page.overlay.toggle":case"page.overlay.show":case"page.overlay.hide":case"page.overlay.status":{try{let r=typeof e.tabId=="number"?e.tabId:n?.tab?.id??await z.getActiveTabId();if(!r){t({success:!1,error:"No target tab found"});break}let o=await browser.tabs.sendMessage(r,{action:e.action}).catch(()=>({}));t({success:!0,tabId:r,...o||{}})}catch(r){t({success:!1,error:r.message})}break}case"hanzo.takeover.start":{let r=e.tabId||k.tabId||await z.getActiveTabId();if(!r){t({success:!1,error:"No target tab found"});break}await z.startControlSession(r,e.task),t({success:!0});break}case"hanzo.takeover.end":{await z.stopControlSession(),t({success:!0});break}case"hanzo.takeover.cursor":{let r=k.tabId||await z.getActiveTabId();r&&browser.tabs.sendMessage(r,{action:"ai.control.cursor",x:e.x,y:e.y}).catch(()=>{}),t({success:!0});break}case"bridge.status":{let r=Ve.state.connected;t({success:!0,connected:r,browsers:r?["firefox"]:[]});break}case"usage.metrics":t({success:!0,metrics:{chatRequests:0,inputTokens:0,outputTokens:0,dedupeHits:0,canceledRequests:0}});break;case"inspector.pickResult":t({success:!0});break;case"ai.control.start":case"ai.control.cursor":case"ai.control.highlight":case"ai.control.status":{let r=e.tabId||k.tabId||await z.getActiveTabId();if(!r){t({success:!1,error:"No target tab found"});break}if(e.action!=="ai.control.start"&&k.active&&k.tabId&&r!==k.tabId){t({success:!1,error:`Control locked to tab ${k.tabId}`});break}e.action==="ai.control.start"?await z.startControlSession(r,e.task):browser.tabs.sendMessage(r,e).catch(()=>{}),t({success:!0,tabId:r});break}case"ai.control.stop":await z.stopControlSession(),t({success:!0});break;case"ai.control.cancel":await z.stopControlSession(),t({success:!0});break;case"cdp.attach":case"cdp.detach":case"cdp.send":case"cdp.screenshot":case"cdp.click":case"cdp.fill":case"cdp.navigate":case"cdp.evaluate":t({success:!1,error:"CDP debugger is not available in Firefox. Use browser automation methods instead."});break;case"monitor.start":case"monitor.stop":case"monitor.consoleLogs":case"monitor.consoleErrors":case"monitor.networkLogs":case"monitor.networkErrors":case"monitor.networkSuccess":case"monitor.allNetwork":case"monitor.wipeLogs":case"monitor.config":case"monitor.status":t({success:!1,error:"Page monitoring requires CDP (Chrome DevTools Protocol) which is not available in Firefox."});break;case"audit.accessibility":case"audit.performance":case"audit.seo":case"audit.bestPractices":case"audit.full":case"audit.nextjs":case"audit.debugger":case"debugger.mode":t({success:!1,error:"Page audits require CDP which is not available in Firefox."});break;case"readTabFS":case"writeTabFS":case"listTabFS":t({success:!1,error:"Tab filesystem requires CDP bridge."});break;case"usage.fetch":{try{let r=await Dt();t({success:!0,providers:r})}catch(r){t({success:!1,error:r.message})}break}default:t({success:!1,error:`Unknown action: ${e.action}`});break}})(),!0));var z=new je,xn=["browser.tabs","browser.navigate","browser.dom","browser.screenshot","browser.input"],En=(e,n)=>z.dispatchMethod(e,n||{}),Ve=tt({brand:"hanzo",caps:xn,engine:kn,dispatch:En,log:console.log,storage:browser.storage.local});browser.runtime.onConnect.addListener(e=>{e.name==="zap-keepalive"&&e.onMessage.addListener(()=>{})});var nr="hanzo-zap-keepalive";try{browser.alarms.create(nr,{periodInMinutes:.5}),browser.alarms.onAlarm.addListener(e=>{e.name===nr&&Ve.tick()})}catch(e){console.warn("[Hanzo] alarms unavailable:",e)}browser.tabs.onRemoved.addListener(e=>{k.active&&k.tabId===e&&z.stopControlSession()});try{let e=browser.omnibox;e&&(e.setDefaultSuggestion({description:"Search Hanzo AI \u2014 AI answers with sources and realtime news"}),e.onInputEntered.addListener((n,t)=>{let r=browser.runtime.getURL("newtab.html")+"?q="+encodeURIComponent(n);t==="newForegroundTab"?browser.tabs.create({url:r}):t==="newBackgroundTab"?browser.tabs.create({url:r,active:!1}):browser.tabs.update({url:r})}))}catch(e){console.warn("[Hanzo] omnibox unavailable:",e)}console.log("[Hanzo] Firefox background script loaded");})();
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
<!DOCTYPE html>
|
|
2
|
+
<html>
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="UTF-8">
|
|
5
|
+
<title>Hanzo AI — Signing in...</title>
|
|
6
|
+
<style>
|
|
7
|
+
body { background: #000; color: #fff; font-family: system-ui, sans-serif; display: flex; align-items: center; justify-content: center; height: 100vh; margin: 0; }
|
|
8
|
+
.msg { text-align: center; opacity: 0.7; }
|
|
9
|
+
</style>
|
|
10
|
+
</head>
|
|
11
|
+
<body>
|
|
12
|
+
<div class="msg">
|
|
13
|
+
<p>Signing in to Hanzo AI...</p>
|
|
14
|
+
<p><small>This tab will close automatically.</small></p>
|
|
15
|
+
</div>
|
|
16
|
+
</body>
|
|
17
|
+
</html>
|