@agentstats/sdk 0.4.0 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser.iife.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/server.cjs +2 -1
- package/dist/server.d.cts +1 -1
- package/dist/server.d.ts +1 -1
- package/dist/server.js +2 -1
- package/package.json +1 -1
package/dist/browser.iife.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var AgentStatsSDK=(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});let t=`agentstats:locationchange`,n=Symbol.for(`agentstats.patched`),r=`pdf.xlsx.docx.txt.rtf.csv.exe.key.pps.ppt.pptx.7z.pkg.rar.gz.zip.avi.mov.mp4.mpeg.wmv.midi.mp3.wav.wma.dmg.iso.msi`.split(`.`);function i(e){try{return document.cookie.match(RegExp(`(?:^|; )${e}=([\\w-]{8,64})`))?.[1]}catch{return}}function a(){if(typeof document>`u`||typeof navigator>`u`)return null;if(document.querySelector?.(`#claude-agent-stop-container`))return{name:`claude-in-chrome`,via:`dom`};let e=String(navigator.userAgent??``);return/\bClaude\/\d/.test(e)?{name:`claude-browser`,via:`user-agent`}:i(`_al_v`)?{name:`verified-visit`,via:`visit`}:navigator.webdriver===!0||/HeadlessChrome/.test(e)?{name:`automation`,via:`webdriver`}:null}function o(){if(!(typeof history>`u`))for(let e of[`pushState`,`replaceState`]){let r=history[e];if(typeof r!=`function`||r[n])continue;let i=function(...e){let n=r.apply(this,e);return window.dispatchEvent(new Event(t)),n};Object.defineProperty(i,n,{value:!0}),history[e]=i}}function s(e){let n={pageview(){},track(){},stop(){}};if(typeof window>`u`||typeof document>`u`)return n;let i=(...t)=>e.debug&&console.debug(`[agentstats]`,...t),s=/^localhost$|^127(\.\d+){3}$|^\[::1?\]$|\.local$|^$/.test(location.hostname)||location.protocol===`file:`,c=!1;try{c=localStorage.getItem(`agentstats_ignore`)===`true`}catch{}let l=(t,n)=>{if(c)return i(`ignored: agentstats_ignore is set`);if(s&&!e.allowLocalhost)return i(`ignored on localhost:`,t);let r=JSON.stringify({k:e.key,n:t,u:location.href,r:document.referrer||null,w:window.innerWidth,p:n,a:a()?.name,h:e.hashRouting?1:void 0});i(`send`,t,n??``);try{if(navigator.sendBeacon?.(e.endpoint,r))return}catch{}fetch(e.endpoint,{method:`POST`,body:r,keepalive:!0,headers:{"Content-Type":`text/plain`}}).catch(()=>{})},u=new AbortController,d={signal:u.signal},f=``,p=()=>{if(u.signal.aborted)return;let t=location.pathname+(e.hashRouting?location.hash:``);t!==f&&(f=t,l(`pageview`))};(()=>{if(document.visibilityState!==`prerender`)return p();document.addEventListener(`visibilitychange`,function e(){document.visibilityState!==`prerender`&&(document.removeEventListener(`visibilitychange`,e),p())},d)})(),o();let m=()=>setTimeout(p,0);if(window.addEventListener(t,m,d),window.addEventListener(`popstate`,m,d),e.hashRouting&&window.addEventListener(`hashchange`,m,d),e.outboundLinks||e.fileDownloads){let t=Array.isArray(e.fileDownloads)?e.fileDownloads:e.fileDownloads?r:[],n=n=>{if(n.type===`auxclick`&&n.button!==1)return;let r=n.target?.closest?.(`a[href]`);if(!r)return;let i;try{i=new URL(r.href,location.href)}catch{return}let a=i.pathname.split(`.`).pop()?.toLowerCase()??``;t.includes(a)?l(`File Download`,{url:i.href.split(`?`)[0]}):e.outboundLinks&&/^https?:$/.test(i.protocol)&&i.host!==location.host&&l(`Outbound Link: Click`,{url:i.href.split(`?`)[0]})};document.addEventListener(`click`,n,{capture:!0,signal:u.signal}),document.addEventListener(`auxclick`,n,{capture:!0,signal:u.signal})}return{pageview:p,track:(e,t)=>l(String(e),t),stop:()=>u.abort()}}let c=`0.4.0`;function l(){let e=globalThis.crypto;return e?.randomUUID?e.randomUUID():`xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`.replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e===`x`?t:t&3|8).toString(16)})}function u(){return Date.now()}function d(){return typeof performance<`u`&&performance.now?performance.now():Date.now()}function f(e){return!!e&&typeof e==`object`&&e.name===`AbortError`}function p(e,t,n=0){if(n>6)return`[depth]`;if(Array.isArray(e))return e.slice(0,100).map(e=>p(e,t,n+1));if(e&&typeof e==`object`){let r={};for(let[i,a]of Object.entries(e)){let e=i.toLowerCase();r[i]=t.some(t=>e.includes(t))?`[redacted]`:p(a,t,n+1)}return r}return typeof e==`string`&&e.length>1e3?e.slice(0,1e3)+`…`:e}function m(e,t){let n;try{n=typeof e==`string`?e:JSON.stringify(e)}catch{n=String(e)}return n===void 0&&(n=``),n.length>t?n.slice(0,t)+`…`:n}function h(e){try{return JSON.stringify(e)?.length??0}catch{return 0}}function g(e){let t={name:String(e.name??``)};return e.title&&(t.title=String(e.title)),e.description&&(t.description=String(e.description)),e.inputSchema!==void 0&&(t.inputSchema=e.inputSchema),e.annotations&&(t.annotations={...e.annotations}),e.origin&&(t.origin=String(e.origin)),t}function _(){if(typeof document<`u`){let e=document.currentScript;if(e?.src)try{return new URL(`/api/ingest`,e.src).toString()}catch{}}return`https://agentstats.io/api/ingest`}let v=/(^|\.)(chatgpt\.com|chat\.openai\.com|perplexity\.ai|claude\.ai|gemini\.google\.com|bard\.google\.com|copilot\.microsoft\.com|copilot\.cloud\.microsoft|copilot\.com|meta\.ai|deepseek\.com|grok\.com|chat\.mistral\.ai|you\.com|phind\.com|poe\.com|duck\.ai|chat\.qwen\.ai|kimi\.com|kimi\.ai|doubao\.com)$/i,y=/[?&]utm_source=(chatgpt(\.com)?|openai|perplexity(\.ai)?|claude(\.ai)?|gemini|copilot(\.com)?|meta\.?ai|deepseek|grok|mistral|le-?chat)(&|$)/i,b=Symbol.for(`agentstats.patched`),x=Symbol.for(`agentstats.wrapped`);var S=class{constructor(e){if(this.queue=[],this.timer=null,this.snapshotTimer=null,this.pollTimer=null,this.sessionId=``,this.lastActivity=0,this.lastSnapshotHash=``,this.inflight=Promise.resolve(),this.web=null,this.agentPage=``,this.controlStarted=0,!e||!e.key)throw Error("[agentstats] `key` is required");if(this.options={endpoint:_(),captureArgs:!0,captureResults:!1,captureErrors:!0,redactKeys:[],sessionTimeoutMs:18e5,flushIntervalMs:2e3,maxBatchSize:25,autoInstrument:!0,trackAgentBrowsers:!0,trackPageviews:!0,debug:!1,disabled:!1,...Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))},this._fetch=e.fetch??(typeof fetch<`u`?fetch.bind(globalThis):(()=>Promise.reject(Error(`no fetch`)))),this.sessionId=this.loadSession(),!this.options.disabled&&(this.options.autoInstrument&&this.instrument(),this.bindLifecycle(),this.reportReferral(),this.options.trackAgentBrowsers&&this.watchAgentBrowsers(),this.options.trackPageviews)){let e=this.options;this.web=s({key:e.key,endpoint:`${e.endpoint.replace(/\/+$/,``)}/web`,hashRouting:e.hashRouting,outboundLinks:e.outboundLinks,fileDownloads:e.fileDownloads,allowLocalhost:e.allowLocalhost,debug:e.debug})}this.log(`initialised`,{endpoint:this.options.endpoint,session:this.sessionId})}wrap(e){if(!e||typeof e.execute!=`function`||e[x])return e;let t=e.execute,n=String(e.name),r=this,i=async function(e,i){let a=d(),o=i?.signal;try{let s=await t.call(this,e,i);return r.recordCall(n,`success`,d()-a,e,s,void 0,o),s}catch(t){let i=o?.aborted||f(t);throw r.recordCall(n,i?`cancelled`:`error`,d()-a,e,void 0,t,o),t}};Object.defineProperty(i,x,{value:!0});let a=Object.assign({},e,{execute:i});return Object.defineProperty(a,x,{value:!0}),a}track(e,t){let n=t?p(t,this.redactKeys()):void 0;this.enqueue({type:`custom`,id:l(),ts:u(),name:e,props:n,url:this.url()}),this.web?.track(e,n)}pageview(){this.web?.pageview()}async snapshot(){let e=this.modelContext();if(!e?.getTools)return[];let t=[];try{t=(await e.getTools()??[]).map(e=>g(e))}catch(e){return this.log(`getTools failed`,e),[]}let n=m(t.map(e=>[e.name,e.description,e.inputSchema,e.annotations]),1e7);return n!==this.lastSnapshotHash&&(this.lastSnapshotHash=n,this.enqueue({type:`tools_snapshot`,id:l(),ts:u(),tools:t,url:this.url()})),t}flush(e=!1){if(this.timer&&=(clearTimeout(this.timer),null),!this.queue.length)return this.inflight;let t=this.queue.splice(0,this.queue.length),n={key:this.options.key,sdk:`js/${c}`,session_id:this.sessionId,sent_at:u(),metadata:this.options.metadata,visit:typeof document<`u`?i(`_al_v`):void 0,client:this.clientHints(),events:t},r=JSON.stringify(n);if(this.log(`flush`,t.length,`events`),e&&typeof navigator<`u`&&navigator.sendBeacon)try{if(navigator.sendBeacon(this.options.endpoint,new Blob([r],{type:`text/plain`})))return Promise.resolve()}catch{}let a=this._fetch(this.options.endpoint,{method:`POST`,body:r,keepalive:!0,headers:{"Content-Type":`text/plain`}}).then(async e=>{e.ok||this.log(`ingest responded`,e.status)}).catch(e=>{this.log(`ingest failed`,e)});return this.inflight=a,a}destroy(){this.timer&&clearTimeout(this.timer),this.snapshotTimer&&clearTimeout(this.snapshotTimer),this.pollTimer&&clearInterval(this.pollTimer),this.timer=this.snapshotTimer=this.pollTimer=null,this.web?.stop(),this.web=null}get session(){return this.sessionId}log(...e){this.options.debug&&console.debug(`[agentstats]`,...e)}url(){return typeof location<`u`?location.href:void 0}redactKeys(){return(this.options.redactKeys??[]).map(e=>e.toLowerCase()).filter(Boolean)}modelContext(){let e=globalThis;return e.document?.modelContext??e.navigator?.modelContext}captureArgs(e,t){let n=this.options.captureArgs;if(n===!1)return;let r=typeof n==`function`?this.callOption(`captureArgs`,()=>n(e,t)):p(t,this.redactKeys());return r!==void 0&&h(r)>8192&&(r={_truncated:!0,preview:m(r,1e3)}),r}captureResult(e,t){let n=this.options.captureResults;if(!n||t===void 0)return;let r=typeof n==`function`?this.callOption(`captureResults`,()=>n(e,t)):t;return r===void 0?void 0:m(r,2048)}captureError(e,t){let n=this.options.captureErrors;if(n===!1)return;let r=t,i=typeof r?.message==`string`?r.message:m(t,1e3);if(typeof n!=`function`)return m(i,1e3);let a=typeof r?.code==`string`||typeof r?.code==`number`?r.code:null,o=this.callOption(`captureErrors`,()=>n({tool:e,message:i,name:typeof r?.name==`string`?r.name:null,code:a,error:t}));return typeof o==`string`&&o?m(o,1e3):void 0}callOption(e,t){try{return t()}catch(t){this.log(`${e} threw`,t);return}}recordCall(e,t,n,r,i,a,o){let s={type:`tool_call`,id:l(),ts:u(),tool:e,status:t,duration_ms:Math.round(n*100)/100,url:this.url()},c=this.captureArgs(e,r);c!==void 0&&(s.args=c);let d=this.captureResult(e,i);if(d!==void 0&&(s.result=d),a!==void 0){let t=this.captureError(e,a);t!==void 0&&(s.error=t);let n=a?.name;n&&(s.error_name=String(n).slice(0,100))}this.enqueue(s)}enqueue(e){this.options.disabled||(this.touchSession(),this.queue.push(e),this.log(`event`,e.type,e.tool??e.name??``),this.queue.length>=this.options.maxBatchSize?this.flush():this.timer||=setTimeout(()=>void this.flush(),this.options.flushIntervalMs))}scheduleSnapshot(e=250){this.snapshotTimer&&clearTimeout(this.snapshotTimer),this.snapshotTimer=setTimeout(()=>{this.snapshotTimer=null,this.snapshot()},e)}instrument(){let e=()=>{let e=this.modelContext();return e?(this.patch(e),!0):!1};if(e())return;let t=0;this.pollTimer=setInterval(()=>{t++,(e()||t>40)&&(this.pollTimer&&clearInterval(this.pollTimer),this.pollTimer=null)},250)}patch(e){if(e[b]){this.log(`modelContext already patched`),this.scheduleSnapshot(0);return}Object.defineProperty(e,b,{value:!0});let t=this;if(typeof e.registerTool==`function`){let n=e.registerTool;e.registerTool=function(e,r){let i=t.wrap(e);return t.enqueue({type:`tool_registered`,id:l(),ts:u(),tool:String(e?.name),descriptor:g(e),url:t.url()}),t.scheduleSnapshot(),n.call(this,i,r)}}if(typeof e.provideContext==`function`){let n=e.provideContext;e.provideContext=function(e){let r=(e?.tools??[]).map(e=>(t.enqueue({type:`tool_registered`,id:l(),ts:u(),tool:String(e?.name),descriptor:g(e),url:t.url()}),t.wrap(e)));return t.scheduleSnapshot(),n.call(this,{...e,tools:r})}}if(typeof e.unregisterTool==`function`){let n=e.unregisterTool;e.unregisterTool=function(e){return t.enqueue({type:`tool_unregistered`,id:l(),ts:u(),tool:String(e),url:t.url()}),t.scheduleSnapshot(),n.call(this,e)}}if(typeof e.clearContext==`function`){let n=e.clearContext;e.clearContext=function(){return t.scheduleSnapshot(),n.call(this)}}if(typeof e.addEventListener==`function`)try{e.addEventListener(`toolchange`,()=>t.scheduleSnapshot())}catch{}this.log(`modelContext patched`),this.scheduleSnapshot(0)}bindLifecycle(){if(typeof window>`u`||typeof window.addEventListener!=`function`)return;let e=()=>void this.flush(!0);window.addEventListener(`pagehide`,e),document.addEventListener(`visibilitychange`,()=>{document.visibilityState===`hidden`&&e()})}clientHints(){if(typeof navigator>`u`)return;let e=String(navigator.userAgent??``).slice(0,1e3),t=navigator.webdriver===!0;return e||t?{ua:e||void 0,webdriver:t||void 0}:void 0}detectAgentBrowser(){return a()}watchAgentBrowsers(){if(typeof document>`u`||typeof window>`u`)return;let e=()=>{let e=this.detectAgentBrowser(),t=this.url();e&&t!==this.agentPage&&(this.agentPage=t??``,this.enqueue({type:`agent_pageview`,id:l(),ts:u(),name:e.name,props:{via:e.via},url:t}))},n=()=>{e(),!(typeof MutationObserver>`u`||!document.body)&&new MutationObserver(()=>{let t=!!document.querySelector(`#claude-agent-stop-container`);if(t&&!this.controlStarted)this.controlStarted=d(),this.enqueue({type:`agent_control`,id:l(),ts:u(),name:`claude-in-chrome`,props:{via:`dom`,phase:`start`},url:this.url()}),e();else if(!t&&this.controlStarted){let e=Math.round(d()-this.controlStarted);this.controlStarted=0,this.enqueue({type:`agent_control`,id:l(),ts:u(),name:`claude-in-chrome`,props:{via:`dom`,phase:`stop`,duration_ms:e},url:this.url()})}}).observe(document.body,{childList:!0})};document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,n,{once:!0}):n();let r=()=>setTimeout(e,0);window.addEventListener(`popstate`,r),window.addEventListener(t,r),o()}reportReferral(){if(typeof document>`u`||typeof location>`u`)return;let e=``;try{e=document.referrer?new URL(document.referrer).hostname.replace(/^www\./,``):``}catch{}if(!(e&&v.test(e))&&!y.test(location.search))return;let t=`__agentstats_ref_${this.sessionId}`;try{if(sessionStorage.getItem(t))return;sessionStorage.setItem(t,`1`)}catch{}this.enqueue({type:`referral`,id:l(),ts:u(),url:this.url()??location.href,referrer:e?`https://${e}/`:null})}loadSession(){try{let e=sessionStorage.getItem(`__agentstats_session`);if(e){let t=JSON.parse(e);if(t?.id&&u()-t.last<this.options.sessionTimeoutMs)return this.lastActivity=t.last,t.id}}catch{}return l()}touchSession(){let e=u();this.lastActivity&&e-this.lastActivity>this.options.sessionTimeoutMs&&(this.sessionId=l(),this.lastSnapshotHash=``,this.log(`new session`,this.sessionId)),this.lastActivity=e;try{sessionStorage.setItem(`__agentstats_session`,JSON.stringify({id:this.sessionId,last:e}))}catch{}}};let C=null;function w(e){return C&&C.destroy(),C=new S(e),C}function T(){return C}function E(e,t){C?.track(e,t)}function D(e){return C?C.wrap(e):e}function O(){return C?.flush()??Promise.resolve()}function k(){return C?.snapshot()??Promise.resolve([])}function A(){C?.pageview()}let j={init:w,track:E,pageview:A,wrap:D,flush:O,snapshot:k,getClient:T,version:c};window.AgentStats=j;let M=document.currentScript,N=M?.dataset.key,P=e=>e!==void 0&&e!==`false`,F=M?.dataset.fileDownloads;return N&&j.init({key:N,endpoint:M?.dataset.endpoint,debug:M?.dataset.debug===`true`,captureArgs:M?.dataset.captureArgs!==`false`,captureErrors:M?.dataset.captureErrors!==`false`,captureResults:M?.dataset.captureResults===`true`,redactKeys:M?.dataset.redactKeys?.split(`,`).map(e=>e.trim()).filter(Boolean),trackPageviews:M?.dataset.pageviews!==`false`,hashRouting:P(M?.dataset.hashRouting),outboundLinks:P(M?.dataset.outboundLinks),fileDownloads:F&&![``,`true`,`false`].includes(F)?F.split(`,`).map(e=>e.trim()):P(F),allowLocalhost:P(M?.dataset.allowLocalhost)}),e.AgentStats=j,e})({});
|
|
1
|
+
var AgentStatsSDK=(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});let t=`agentstats:locationchange`,n=Symbol.for(`agentstats.patched`),r=`pdf.xlsx.docx.txt.rtf.csv.exe.key.pps.ppt.pptx.7z.pkg.rar.gz.zip.avi.mov.mp4.mpeg.wmv.midi.mp3.wav.wma.dmg.iso.msi`.split(`.`);function i(e){try{return document.cookie.match(RegExp(`(?:^|; )${e}=([\\w-]{8,64})`))?.[1]}catch{return}}function a(){if(typeof document>`u`||typeof navigator>`u`)return null;if(document.querySelector?.(`#claude-agent-stop-container`))return{name:`claude-in-chrome`,via:`dom`};let e=String(navigator.userAgent??``);return/\bClaude\/\d/.test(e)?{name:`claude-browser`,via:`user-agent`}:i(`_al_v`)?{name:`verified-visit`,via:`visit`}:navigator.webdriver===!0||/HeadlessChrome/.test(e)?{name:`automation`,via:`webdriver`}:null}function o(){if(!(typeof history>`u`))for(let e of[`pushState`,`replaceState`]){let r=history[e];if(typeof r!=`function`||r[n])continue;let i=function(...e){let n=r.apply(this,e);return window.dispatchEvent(new Event(t)),n};Object.defineProperty(i,n,{value:!0}),history[e]=i}}function s(e){let n={pageview(){},track(){},stop(){}};if(typeof window>`u`||typeof document>`u`)return n;let i=(...t)=>e.debug&&console.debug(`[agentstats]`,...t),s=/^localhost$|^127(\.\d+){3}$|^\[::1?\]$|\.local$|^$/.test(location.hostname)||location.protocol===`file:`,c=!1;try{c=localStorage.getItem(`agentstats_ignore`)===`true`}catch{}let l=(t,n)=>{if(c)return i(`ignored: agentstats_ignore is set`);if(s&&!e.allowLocalhost)return i(`ignored on localhost:`,t);let r=JSON.stringify({k:e.key,n:t,u:location.href,r:document.referrer||null,w:window.innerWidth,p:n,a:a()?.name,h:e.hashRouting?1:void 0});i(`send`,t,n??``);try{if(navigator.sendBeacon?.(e.endpoint,r))return}catch{}fetch(e.endpoint,{method:`POST`,body:r,keepalive:!0,headers:{"Content-Type":`text/plain`}}).catch(()=>{})},u=new AbortController,d={signal:u.signal},f=``,p=()=>{if(u.signal.aborted)return;let t=location.pathname+(e.hashRouting?location.hash:``);t!==f&&(f=t,l(`pageview`))};(()=>{if(document.visibilityState!==`prerender`)return p();document.addEventListener(`visibilitychange`,function e(){document.visibilityState!==`prerender`&&(document.removeEventListener(`visibilitychange`,e),p())},d)})(),o();let m=()=>setTimeout(p,0);if(window.addEventListener(t,m,d),window.addEventListener(`popstate`,m,d),e.hashRouting&&window.addEventListener(`hashchange`,m,d),e.outboundLinks||e.fileDownloads){let t=Array.isArray(e.fileDownloads)?e.fileDownloads:e.fileDownloads?r:[],n=n=>{if(n.type===`auxclick`&&n.button!==1)return;let r=n.target?.closest?.(`a[href]`);if(!r)return;let i;try{i=new URL(r.href,location.href)}catch{return}let a=i.pathname.split(`.`).pop()?.toLowerCase()??``;t.includes(a)?l(`File Download`,{url:i.href.split(`?`)[0]}):e.outboundLinks&&/^https?:$/.test(i.protocol)&&i.host!==location.host&&l(`Outbound Link: Click`,{url:i.href.split(`?`)[0]})};document.addEventListener(`click`,n,{capture:!0,signal:u.signal}),document.addEventListener(`auxclick`,n,{capture:!0,signal:u.signal})}return{pageview:p,track:(e,t)=>l(String(e),t),stop:()=>u.abort()}}let c=`0.4.1`;function l(){let e=globalThis.crypto;return e?.randomUUID?e.randomUUID():`xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`.replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e===`x`?t:t&3|8).toString(16)})}function u(){return Date.now()}function d(){return typeof performance<`u`&&performance.now?performance.now():Date.now()}function f(e){return!!e&&typeof e==`object`&&e.name===`AbortError`}function p(e,t,n=0){if(n>6)return`[depth]`;if(Array.isArray(e))return e.slice(0,100).map(e=>p(e,t,n+1));if(e&&typeof e==`object`){let r={};for(let[i,a]of Object.entries(e)){let e=i.toLowerCase();r[i]=t.some(t=>e.includes(t))?`[redacted]`:p(a,t,n+1)}return r}return typeof e==`string`&&e.length>1e3?e.slice(0,1e3)+`…`:e}function m(e,t){let n;try{n=typeof e==`string`?e:JSON.stringify(e)}catch{n=String(e)}return n===void 0&&(n=``),n.length>t?n.slice(0,t)+`…`:n}function h(e){try{return JSON.stringify(e)?.length??0}catch{return 0}}function g(e){let t={name:String(e.name??``)};return e.title&&(t.title=String(e.title)),e.description&&(t.description=String(e.description)),e.inputSchema!==void 0&&(t.inputSchema=e.inputSchema),e.annotations&&(t.annotations={...e.annotations}),e.origin&&(t.origin=String(e.origin)),t}function _(){if(typeof document<`u`){let e=document.currentScript;if(e?.src)try{return new URL(`/api/ingest`,e.src).toString()}catch{}}return`https://agentstats.io/api/ingest`}let v=/(^|\.)(chatgpt\.com|chat\.openai\.com|perplexity\.ai|claude\.ai|gemini\.google\.com|bard\.google\.com|copilot\.microsoft\.com|copilot\.cloud\.microsoft|copilot\.com|meta\.ai|deepseek\.com|grok\.com|chat\.mistral\.ai|you\.com|phind\.com|poe\.com|duck\.ai|chat\.qwen\.ai|kimi\.com|kimi\.ai|doubao\.com)$/i,y=/[?&]utm_source=(chatgpt(\.com)?|openai|perplexity(\.ai)?|claude(\.ai)?|gemini|copilot(\.com)?|meta\.?ai|deepseek|grok|mistral|le-?chat)(&|$)/i,b=Symbol.for(`agentstats.patched`),x=Symbol.for(`agentstats.wrapped`);var S=class{constructor(e){if(this.queue=[],this.timer=null,this.snapshotTimer=null,this.pollTimer=null,this.sessionId=``,this.lastActivity=0,this.lastSnapshotHash=``,this.inflight=Promise.resolve(),this.web=null,this.agentPage=``,this.controlStarted=0,!e||!e.key)throw Error("[agentstats] `key` is required");if(this.options={endpoint:_(),captureArgs:!0,captureResults:!1,captureErrors:!0,redactKeys:[],sessionTimeoutMs:18e5,flushIntervalMs:2e3,maxBatchSize:25,autoInstrument:!0,trackAgentBrowsers:!0,trackPageviews:!0,debug:!1,disabled:!1,...Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))},this._fetch=e.fetch??(typeof fetch<`u`?fetch.bind(globalThis):(()=>Promise.reject(Error(`no fetch`)))),this.sessionId=this.loadSession(),!this.options.disabled&&(this.options.autoInstrument&&this.instrument(),this.bindLifecycle(),this.reportReferral(),this.options.trackAgentBrowsers&&this.watchAgentBrowsers(),this.options.trackPageviews)){let e=this.options;this.web=s({key:e.key,endpoint:`${e.endpoint.replace(/\/+$/,``)}/web`,hashRouting:e.hashRouting,outboundLinks:e.outboundLinks,fileDownloads:e.fileDownloads,allowLocalhost:e.allowLocalhost,debug:e.debug})}this.log(`initialised`,{endpoint:this.options.endpoint,session:this.sessionId})}wrap(e){if(!e||typeof e.execute!=`function`||e[x])return e;let t=e.execute,n=String(e.name),r=this,i=async function(e,i){let a=d(),o=i?.signal;try{let s=await t.call(this,e,i);return r.recordCall(n,`success`,d()-a,e,s,void 0,o),s}catch(t){let i=o?.aborted||f(t);throw r.recordCall(n,i?`cancelled`:`error`,d()-a,e,void 0,t,o),t}};Object.defineProperty(i,x,{value:!0});let a=Object.assign({},e,{execute:i});return Object.defineProperty(a,x,{value:!0}),a}track(e,t){let n=t?p(t,this.redactKeys()):void 0;this.enqueue({type:`custom`,id:l(),ts:u(),name:e,props:n,url:this.url()}),this.web?.track(e,n)}pageview(){this.web?.pageview()}async snapshot(){let e=this.modelContext();if(!e?.getTools)return[];let t=[];try{t=(await e.getTools()??[]).map(e=>g(e))}catch(e){return this.log(`getTools failed`,e),[]}let n=m(t.map(e=>[e.name,e.description,e.inputSchema,e.annotations]),1e7);return n!==this.lastSnapshotHash&&(this.lastSnapshotHash=n,this.enqueue({type:`tools_snapshot`,id:l(),ts:u(),tools:t,url:this.url()})),t}flush(e=!1){if(this.timer&&=(clearTimeout(this.timer),null),!this.queue.length)return this.inflight;let t=this.queue.splice(0,this.queue.length),n={key:this.options.key,sdk:`js/${c}`,session_id:this.sessionId,sent_at:u(),metadata:this.options.metadata,visit:typeof document<`u`?i(`_al_v`):void 0,client:this.clientHints(),events:t},r=JSON.stringify(n);if(this.log(`flush`,t.length,`events`),e&&typeof navigator<`u`&&navigator.sendBeacon)try{if(navigator.sendBeacon(this.options.endpoint,new Blob([r],{type:`text/plain`})))return Promise.resolve()}catch{}let a=this._fetch(this.options.endpoint,{method:`POST`,body:r,keepalive:!0,headers:{"Content-Type":`text/plain`}}).then(async e=>{e.ok||this.log(`ingest responded`,e.status)}).catch(e=>{this.log(`ingest failed`,e)});return this.inflight=a,a}destroy(){this.timer&&clearTimeout(this.timer),this.snapshotTimer&&clearTimeout(this.snapshotTimer),this.pollTimer&&clearInterval(this.pollTimer),this.timer=this.snapshotTimer=this.pollTimer=null,this.web?.stop(),this.web=null}get session(){return this.sessionId}log(...e){this.options.debug&&console.debug(`[agentstats]`,...e)}url(){return typeof location<`u`?location.href:void 0}redactKeys(){return(this.options.redactKeys??[]).map(e=>e.toLowerCase()).filter(Boolean)}modelContext(){let e=globalThis;return e.document?.modelContext??e.navigator?.modelContext}captureArgs(e,t){let n=this.options.captureArgs;if(n===!1)return;let r=typeof n==`function`?this.callOption(`captureArgs`,()=>n(e,t)):p(t,this.redactKeys());return r!==void 0&&h(r)>8192&&(r={_truncated:!0,preview:m(r,1e3)}),r}captureResult(e,t){let n=this.options.captureResults;if(!n||t===void 0)return;let r=typeof n==`function`?this.callOption(`captureResults`,()=>n(e,t)):t;return r===void 0?void 0:m(r,2048)}captureError(e,t){let n=this.options.captureErrors;if(n===!1)return;let r=t,i=typeof r?.message==`string`?r.message:m(t,1e3);if(typeof n!=`function`)return m(i,1e3);let a=typeof r?.code==`string`||typeof r?.code==`number`?r.code:null,o=this.callOption(`captureErrors`,()=>n({tool:e,message:i,name:typeof r?.name==`string`?r.name:null,code:a,error:t}));return typeof o==`string`&&o?m(o,1e3):void 0}callOption(e,t){try{return t()}catch(t){this.log(`${e} threw`,t);return}}recordCall(e,t,n,r,i,a,o){let s={type:`tool_call`,id:l(),ts:u(),tool:e,status:t,duration_ms:Math.round(n*100)/100,url:this.url()},c=this.captureArgs(e,r);c!==void 0&&(s.args=c);let d=this.captureResult(e,i);if(d!==void 0&&(s.result=d),a!==void 0){let t=this.captureError(e,a);t!==void 0&&(s.error=t);let n=a?.name;n&&(s.error_name=String(n).slice(0,100))}this.enqueue(s)}enqueue(e){this.options.disabled||(this.touchSession(),this.queue.push(e),this.log(`event`,e.type,e.tool??e.name??``),this.queue.length>=this.options.maxBatchSize?this.flush():this.timer||=setTimeout(()=>void this.flush(),this.options.flushIntervalMs))}scheduleSnapshot(e=250){this.snapshotTimer&&clearTimeout(this.snapshotTimer),this.snapshotTimer=setTimeout(()=>{this.snapshotTimer=null,this.snapshot()},e)}instrument(){let e=()=>{let e=this.modelContext();return e?(this.patch(e),!0):!1};if(e())return;let t=0;this.pollTimer=setInterval(()=>{t++,(e()||t>40)&&(this.pollTimer&&clearInterval(this.pollTimer),this.pollTimer=null)},250)}patch(e){if(e[b]){this.log(`modelContext already patched`),this.scheduleSnapshot(0);return}Object.defineProperty(e,b,{value:!0});let t=this;if(typeof e.registerTool==`function`){let n=e.registerTool;e.registerTool=function(e,r){let i=t.wrap(e);return t.enqueue({type:`tool_registered`,id:l(),ts:u(),tool:String(e?.name),descriptor:g(e),url:t.url()}),t.scheduleSnapshot(),n.call(this,i,r)}}if(typeof e.provideContext==`function`){let n=e.provideContext;e.provideContext=function(e){let r=(e?.tools??[]).map(e=>(t.enqueue({type:`tool_registered`,id:l(),ts:u(),tool:String(e?.name),descriptor:g(e),url:t.url()}),t.wrap(e)));return t.scheduleSnapshot(),n.call(this,{...e,tools:r})}}if(typeof e.unregisterTool==`function`){let n=e.unregisterTool;e.unregisterTool=function(e){return t.enqueue({type:`tool_unregistered`,id:l(),ts:u(),tool:String(e),url:t.url()}),t.scheduleSnapshot(),n.call(this,e)}}if(typeof e.clearContext==`function`){let n=e.clearContext;e.clearContext=function(){return t.scheduleSnapshot(),n.call(this)}}if(typeof e.addEventListener==`function`)try{e.addEventListener(`toolchange`,()=>t.scheduleSnapshot())}catch{}this.log(`modelContext patched`),this.scheduleSnapshot(0)}bindLifecycle(){if(typeof window>`u`||typeof window.addEventListener!=`function`)return;let e=()=>void this.flush(!0);window.addEventListener(`pagehide`,e),document.addEventListener(`visibilitychange`,()=>{document.visibilityState===`hidden`&&e()})}clientHints(){if(typeof navigator>`u`)return;let e=String(navigator.userAgent??``).slice(0,1e3),t=navigator.webdriver===!0;return e||t?{ua:e||void 0,webdriver:t||void 0}:void 0}detectAgentBrowser(){return a()}watchAgentBrowsers(){if(typeof document>`u`||typeof window>`u`)return;let e=()=>{let e=this.detectAgentBrowser(),t=this.url();e&&t!==this.agentPage&&(this.agentPage=t??``,this.enqueue({type:`agent_pageview`,id:l(),ts:u(),name:e.name,props:{via:e.via},url:t}))},n=()=>{e(),!(typeof MutationObserver>`u`||!document.body)&&new MutationObserver(()=>{let t=!!document.querySelector(`#claude-agent-stop-container`);if(t&&!this.controlStarted)this.controlStarted=d(),this.enqueue({type:`agent_control`,id:l(),ts:u(),name:`claude-in-chrome`,props:{via:`dom`,phase:`start`},url:this.url()}),e();else if(!t&&this.controlStarted){let e=Math.round(d()-this.controlStarted);this.controlStarted=0,this.enqueue({type:`agent_control`,id:l(),ts:u(),name:`claude-in-chrome`,props:{via:`dom`,phase:`stop`,duration_ms:e},url:this.url()})}}).observe(document.body,{childList:!0})};document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,n,{once:!0}):n();let r=()=>setTimeout(e,0);window.addEventListener(`popstate`,r),window.addEventListener(t,r),o()}reportReferral(){if(typeof document>`u`||typeof location>`u`)return;let e=``;try{e=document.referrer?new URL(document.referrer).hostname.replace(/^www\./,``):``}catch{}if(!(e&&v.test(e))&&!y.test(location.search))return;let t=`__agentstats_ref_${this.sessionId}`;try{if(sessionStorage.getItem(t))return;sessionStorage.setItem(t,`1`)}catch{}this.enqueue({type:`referral`,id:l(),ts:u(),url:this.url()??location.href,referrer:e?`https://${e}/`:null})}loadSession(){try{let e=sessionStorage.getItem(`__agentstats_session`);if(e){let t=JSON.parse(e);if(t?.id&&u()-t.last<this.options.sessionTimeoutMs)return this.lastActivity=t.last,t.id}}catch{}return l()}touchSession(){let e=u();this.lastActivity&&e-this.lastActivity>this.options.sessionTimeoutMs&&(this.sessionId=l(),this.lastSnapshotHash=``,this.log(`new session`,this.sessionId)),this.lastActivity=e;try{sessionStorage.setItem(`__agentstats_session`,JSON.stringify({id:this.sessionId,last:e}))}catch{}}};let C=null;function w(e){return C&&C.destroy(),C=new S(e),C}function T(){return C}function E(e,t){C?.track(e,t)}function D(e){return C?C.wrap(e):e}function O(){return C?.flush()??Promise.resolve()}function k(){return C?.snapshot()??Promise.resolve([])}function A(){C?.pageview()}let j={init:w,track:E,pageview:A,wrap:D,flush:O,snapshot:k,getClient:T,version:c};window.AgentStats=j;let M=document.currentScript,N=M?.dataset.key,P=e=>e!==void 0&&e!==`false`,F=M?.dataset.fileDownloads;return N&&j.init({key:N,endpoint:M?.dataset.endpoint,debug:M?.dataset.debug===`true`,captureArgs:M?.dataset.captureArgs!==`false`,captureErrors:M?.dataset.captureErrors!==`false`,captureResults:M?.dataset.captureResults===`true`,redactKeys:M?.dataset.redactKeys?.split(`,`).map(e=>e.trim()).filter(Boolean),trackPageviews:M?.dataset.pageviews!==`false`,hashRouting:P(M?.dataset.hashRouting),outboundLinks:P(M?.dataset.outboundLinks),fileDownloads:F&&![``,`true`,`false`].includes(F)?F.split(`,`).map(e=>e.trim()):P(F),allowLocalhost:P(M?.dataset.allowLocalhost)}),e.AgentStats=j,e})({});
|
package/dist/index.cjs
CHANGED
|
@@ -188,7 +188,7 @@ function webAnalytics(o) {
|
|
|
188
188
|
* It also records pageviews (Visitors, see ./web.ts): no cookies, no personal data. Turn that
|
|
189
189
|
* off with `trackPageviews: false`.
|
|
190
190
|
*/
|
|
191
|
-
const SDK_VERSION = "0.4.
|
|
191
|
+
const SDK_VERSION = "0.4.1";
|
|
192
192
|
const MAX_ARG_BYTES = 8192;
|
|
193
193
|
const MAX_RESULT_CHARS = 2048;
|
|
194
194
|
function uuid() {
|
package/dist/index.d.cts
CHANGED
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
type EventProps = Record<string, string | number | boolean>;
|
|
11
11
|
//#endregion
|
|
12
12
|
//#region src/index.d.ts
|
|
13
|
-
export declare const SDK_VERSION = "0.4.
|
|
13
|
+
export declare const SDK_VERSION = "0.4.1";
|
|
14
14
|
export type ToolStatus = 'success' | 'error' | 'cancelled';
|
|
15
15
|
export interface ToolAnnotations {
|
|
16
16
|
readOnlyHint?: boolean;
|
package/dist/index.d.ts
CHANGED
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
type EventProps = Record<string, string | number | boolean>;
|
|
11
11
|
//#endregion
|
|
12
12
|
//#region src/index.d.ts
|
|
13
|
-
export declare const SDK_VERSION = "0.4.
|
|
13
|
+
export declare const SDK_VERSION = "0.4.1";
|
|
14
14
|
export type ToolStatus = 'success' | 'error' | 'cancelled';
|
|
15
15
|
export interface ToolAnnotations {
|
|
16
16
|
readOnlyHint?: boolean;
|
package/dist/index.js
CHANGED
|
@@ -184,7 +184,7 @@ function webAnalytics(o) {
|
|
|
184
184
|
* It also records pageviews (Visitors, see ./web.ts): no cookies, no personal data. Turn that
|
|
185
185
|
* off with `trackPageviews: false`.
|
|
186
186
|
*/
|
|
187
|
-
const SDK_VERSION = "0.4.
|
|
187
|
+
const SDK_VERSION = "0.4.1";
|
|
188
188
|
const MAX_ARG_BYTES = 8192;
|
|
189
189
|
const MAX_RESULT_CHARS = 2048;
|
|
190
190
|
function uuid() {
|
package/dist/server.cjs
CHANGED
|
@@ -993,7 +993,7 @@ function detectFromHeaders(header, url) {
|
|
|
993
993
|
*
|
|
994
994
|
* const lens = createAgentStats({ apiKey: process.env.AGENTSTATS_API_KEY }) // API-only server
|
|
995
995
|
*/
|
|
996
|
-
const SERVER_SDK_VERSION = "0.3.
|
|
996
|
+
const SERVER_SDK_VERSION = "0.3.1";
|
|
997
997
|
/**
|
|
998
998
|
* Words that may mean a bot the table below doesn't know yet. Deliberately broad: the server
|
|
999
999
|
* makes the final call, and its table can be newer than this SDK's.
|
|
@@ -1411,6 +1411,7 @@ var AgentStatsServer = class {
|
|
|
1411
1411
|
if (this.apiOn && this.isApiPath(path)) return this.decideApi(m, url, path, header, ip, detection);
|
|
1412
1412
|
if (!this.hitsOn) return ignore;
|
|
1413
1413
|
const ua = header("user-agent") ?? null;
|
|
1414
|
+
if (!ip && !ua?.trim()) return ignore;
|
|
1414
1415
|
const signed = detection.signed;
|
|
1415
1416
|
if (signed || detection.isBot || ua && BOT_HINT.test(ua)) {
|
|
1416
1417
|
const record = {
|
package/dist/server.d.cts
CHANGED
|
@@ -228,7 +228,7 @@ type DetectInput = Request | Headers | {
|
|
|
228
228
|
export declare function detectBot(input: DetectInput): BotDetection;
|
|
229
229
|
//#endregion
|
|
230
230
|
//#region src/server.d.ts
|
|
231
|
-
export declare const SERVER_SDK_VERSION = "0.3.
|
|
231
|
+
export declare const SERVER_SDK_VERSION = "0.3.1";
|
|
232
232
|
export interface ServerOptions {
|
|
233
233
|
/**
|
|
234
234
|
* Secret server key from Site settings (`al_srv_…`). Never expose it to browsers.
|
package/dist/server.d.ts
CHANGED
|
@@ -228,7 +228,7 @@ type DetectInput = Request | Headers | {
|
|
|
228
228
|
export declare function detectBot(input: DetectInput): BotDetection;
|
|
229
229
|
//#endregion
|
|
230
230
|
//#region src/server.d.ts
|
|
231
|
-
export declare const SERVER_SDK_VERSION = "0.3.
|
|
231
|
+
export declare const SERVER_SDK_VERSION = "0.3.1";
|
|
232
232
|
export interface ServerOptions {
|
|
233
233
|
/**
|
|
234
234
|
* Secret server key from Site settings (`al_srv_…`). Never expose it to browsers.
|
package/dist/server.js
CHANGED
|
@@ -989,7 +989,7 @@ function detectFromHeaders(header, url) {
|
|
|
989
989
|
*
|
|
990
990
|
* const lens = createAgentStats({ apiKey: process.env.AGENTSTATS_API_KEY }) // API-only server
|
|
991
991
|
*/
|
|
992
|
-
const SERVER_SDK_VERSION = "0.3.
|
|
992
|
+
const SERVER_SDK_VERSION = "0.3.1";
|
|
993
993
|
/**
|
|
994
994
|
* Words that may mean a bot the table below doesn't know yet. Deliberately broad: the server
|
|
995
995
|
* makes the final call, and its table can be newer than this SDK's.
|
|
@@ -1407,6 +1407,7 @@ var AgentStatsServer = class {
|
|
|
1407
1407
|
if (this.apiOn && this.isApiPath(path)) return this.decideApi(m, url, path, header, ip, detection);
|
|
1408
1408
|
if (!this.hitsOn) return ignore;
|
|
1409
1409
|
const ua = header("user-agent") ?? null;
|
|
1410
|
+
if (!ip && !ua?.trim()) return ignore;
|
|
1410
1411
|
const signed = detection.signed;
|
|
1411
1412
|
if (signed || detection.isBot || ua && BOT_HINT.test(ua)) {
|
|
1412
1413
|
const record = {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@agentstats/sdk",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.1",
|
|
4
4
|
"description": "Analytics for WebMCP tool calls and AI bot traffic, plus server-side AI bot detection. Framework-agnostic, zero dependencies.",
|
|
5
5
|
"homepage": "https://agentstats.io",
|
|
6
6
|
"bugs": {
|