@agentstats/sdk 0.0.0-stage → 0.4.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Moshe Tanzer
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,71 @@
1
- # Temporary Holding Version
1
+ # @agentstats/sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Analytics for [WebMCP](https://webmachinelearning.github.io/webmcp/) tool calls, and privacy-friendly analytics for the people on your site (no cookies, no personal data). Framework-agnostic, zero dependencies, ~5 KB.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm i @agentstats/sdk
9
+ ```
10
+
11
+ ```ts
12
+ import { AgentStats } from '@agentstats/sdk'
13
+
14
+ AgentStats.init({ key: 'al_pub_…' })
15
+
16
+ // Register tools as usual — they are instrumented automatically.
17
+ document.modelContext.registerTool({
18
+ name: 'search_products',
19
+ description: 'Search the catalogue',
20
+ inputSchema: { type: 'object', properties: { q: { type: 'string' } } },
21
+ async execute({ q }) { /* … */ },
22
+ })
23
+ ```
24
+
25
+ Or with a script tag (no build step):
26
+
27
+ ```html
28
+ <script src="https://agentstats.io/sdk/v1.js" data-key="al_pub_…" async></script>
29
+ ```
30
+
31
+ No WebMCP tools? `lite.js` (~1.7 KB) records visitors only, and `AgentStats.track()` works the same:
32
+
33
+ ```html
34
+ <script src="https://agentstats.io/sdk/lite.js" data-key="al_pub_…" defer></script>
35
+ ```
36
+
37
+ ## What gets tracked
38
+
39
+ | Event | When |
40
+ |---|---|
41
+ | `tool_call` | every `execute()` — name, status (success / error / cancelled), duration, args |
42
+ | `tool_registered` / `tool_unregistered` | tools added or removed |
43
+ | `tools_snapshot` | the full tool surface (names, descriptions, schemas, annotations) whenever it changes |
44
+ | `custom` | anything you send with `AgentStats.track('checkout_completed', { value: 42 })` |
45
+ | pageviews (Visitors) | each page a person views, including client-side navigation; `track()` events count as goals. Sent to `/api/ingest/web` without cookies; the server keeps no IP or user agent |
46
+
47
+ ## Options
48
+
49
+ ```ts
50
+ AgentStats.init({
51
+ key: 'al_pub_…',
52
+ endpoint: 'https://agentstats.io/api/ingest', // the default; the script tag build uses the host it was loaded from
53
+ captureArgs: true, // false, or (tool, args) => value to store
54
+ captureResults: false, // true, or (tool, result) => value to store
55
+ captureErrors: true, // false, or ({ tool, message, name, code }) => text to store, or null
56
+ redactKeys: ['email'], // nothing is redacted unless listed (case-insensitive substring)
57
+ metadata: { app: 'storefront', version: '1.2.3' },
58
+ sessionTimeoutMs: 30 * 60 * 1000,
59
+ trackPageviews: true, // Visitors; ignored on localhost unless allowLocalhost
60
+ outboundLinks: false, // record clicks on links to other sites
61
+ fileDownloads: false, // true, or ['pdf', 'zip']
62
+ hashRouting: false, // count #/route as the page
63
+ debug: false,
64
+ })
65
+ ```
66
+
67
+ Manual wrapping (if you register tools before `init`, or want to be explicit):
68
+
69
+ ```ts
70
+ document.modelContext.registerTool(AgentStats.wrap(myTool))
71
+ ```
@@ -0,0 +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})({});