@agentronics/sdk 0.5.0 → 0.7.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.
Files changed (54) hide show
  1. package/README.md +96 -76
  2. package/dist/chunk-3WPDIMJP.js +18 -0
  3. package/dist/chunk-3WPDIMJP.js.map +1 -0
  4. package/dist/chunk-6QQS26AP.js +1200 -0
  5. package/dist/chunk-6QQS26AP.js.map +1 -0
  6. package/dist/chunk-BPDWJCPY.js +2 -0
  7. package/dist/chunk-BPDWJCPY.js.map +1 -0
  8. package/dist/index.cjs +8 -7
  9. package/dist/index.cjs.map +1 -1
  10. package/dist/index.d.cts +51 -12
  11. package/dist/index.d.ts +51 -12
  12. package/dist/index.global.js +8 -7
  13. package/dist/index.global.js.map +1 -1
  14. package/dist/index.js +1 -1
  15. package/dist/index.js.map +1 -1
  16. package/dist/{init-only-7f8_LQAI.d.ts → init-only-C80qhujz.d.ts} +227 -30
  17. package/dist/{init-only-Cwll8MGz.d.cts → init-only-s9E9bVC0.d.cts} +227 -30
  18. package/dist/init-only.cjs +8 -7
  19. package/dist/init-only.cjs.map +1 -1
  20. package/dist/init-only.d.cts +2 -2
  21. package/dist/init-only.d.ts +2 -2
  22. package/dist/init-only.global.js +8 -7
  23. package/dist/init-only.global.js.map +1 -1
  24. package/dist/init-only.js +1 -1
  25. package/dist/lite.cjs +1 -1
  26. package/dist/lite.cjs.map +1 -1
  27. package/dist/lite.d.cts +2 -2
  28. package/dist/lite.d.ts +2 -2
  29. package/dist/lite.global.js +1 -1
  30. package/dist/lite.global.js.map +1 -1
  31. package/dist/lite.js +1 -1
  32. package/dist/middleware-Dd2T772u.d.cts +429 -0
  33. package/dist/middleware-Dd2T772u.d.ts +429 -0
  34. package/dist/next.cjs +1137 -0
  35. package/dist/next.cjs.map +1 -0
  36. package/dist/next.d.cts +20 -0
  37. package/dist/next.d.ts +20 -0
  38. package/dist/next.js +20 -0
  39. package/dist/next.js.map +1 -0
  40. package/dist/server.cjs +1321 -0
  41. package/dist/server.cjs.map +1 -0
  42. package/dist/server.d.cts +131 -0
  43. package/dist/server.d.ts +131 -0
  44. package/dist/server.js +95 -0
  45. package/dist/server.js.map +1 -0
  46. package/dist/webmcp-BgKzHeQ3.d.cts +97 -0
  47. package/dist/webmcp-BgKzHeQ3.d.ts +97 -0
  48. package/package.json +38 -6
  49. package/dist/chunk-77VJ65X2.js +0 -17
  50. package/dist/chunk-77VJ65X2.js.map +0 -1
  51. package/dist/chunk-LLD3Y2LZ.js +0 -2
  52. package/dist/chunk-LLD3Y2LZ.js.map +0 -1
  53. package/dist/webmcp-C4ikhM4g.d.cts +0 -12
  54. package/dist/webmcp-C4ikhM4g.d.ts +0 -12
package/README.md CHANGED
@@ -1,126 +1,146 @@
1
1
  # @agentronics/sdk
2
2
 
3
- > Browser SDK for the Agentronics governance layer — detection, auth normalization, policy enforcement, site memory, and trace export for every agent class.
3
+ > Authentication for AI agents — verify every agent on your site (signed agents, API agents, crawlers, WebMCP and browser agents) with any method: Web Bot Auth, API keys, OAuth2, SSO, SPIFFE, mTLS.
4
4
 
5
- **Version:** 0.1.0
5
+ **Version:** 0.5.0
6
6
 
7
7
  <!-- generated by scripts/sync-readme.ts — edit the MDX in apps/docs/content/docs and re-run `pnpm sync-readme` -->
8
8
 
9
9
  ## Why Agentronics
10
10
 
11
- **Agentronics is a universal governance layer for agent-surfable websites.**
11
+ AI agents already visit your site: crawlers indexing it for answer engines, assistants
12
+ fetching pages on a user's behalf, browser agents clicking through checkout, and API agents
13
+ calling your endpoints. Most sites can't tell a real ChatGPT agent from a scraper wearing its
14
+ user agent — every agent looks the same.
12
15
 
13
- Modern websites are no longer browsed only by humans. AI agents — Claude, ChatGPT, Perplexity, custom in-house agents — already navigate, click, and submit forms on behalf of users. Most sites have no way to tell an agent apart from a human, no way to declare which actions are safe for an agent to take, and no way to see what agents did after they left.
16
+ **Agentronics gives every agent a verifiable identity**, the way an auth provider does for your
17
+ human users: sign agents in and see who they are. Agentronics never blocks — agents that
18
+ don't authenticate keep browsing your site as normal.
14
19
 
15
- Agentronics gives any website seven primitives, behind one SDK:
20
+ ## What you get
16
21
 
17
- 1. **Detection** — identify which agent class is on the page (WebMCP, DOM-driver, screenshot model).
18
- 2. **Authentication** — let agents present a verifiable identity, not just a user-agent string.
19
- 3. **Authorization** — declare per-tool policies based on agent class and trust level.
20
- 4. **Site Memory** — persist context across an agent's session so the user does not re-explain themselves.
21
- 5. **Observability** — stream every agent action into a dashboard your team actually reads.
22
- 6. **Tool Management** — register, version, and gate the tools an agent can call on your site.
23
- 7. **Payments** — *(deferred to v0.2)* charge agents per action, settle to your account.
22
+ - **Every kind of agent.** Signed agents, API agents, search and AI crawlers, WebMCP and
23
+ in-browser agents — one SDK, one identity model, one console.
24
+ - **Every method.** [Web Bot Auth](/docs/auth/web-bot-auth) (signed HTTP requests),
25
+ [agent API keys](/docs/auth/api-keys), [OAuth2](/docs/auth/oauth2),
26
+ [verified crawlers](/docs/auth/verified-crawlers), [SSO / OIDC](/docs/auth/sso),
27
+ [SPIFFE](/docs/auth/spiffe), [mTLS](/docs/auth/mtls) and
28
+ [browser-agent credentials](/docs/auth/browser-agents).
29
+ - **Identity in your app.** Verified agents reach your routes with their identity attached as
30
+ request headers — who they are and how they proved it.
31
+ - **[Auth logs & sessions](/docs/auth-logs).** Every sign-in and verification, with the method
32
+ and the reason it passed or failed, in the Agentronics console.
24
33
 
25
- ## Who this is for
34
+ ## Two halves, one identity
26
35
 
27
- - **Product engineers** at companies whose users are starting to ask for "agent support" on the marketing site, the dashboard, or the help center.
28
- - **Platform teams** standardizing how agents interact with internal tools across many properties.
29
- - **Indie builders** shipping agent-first products who want governance without writing it themselves.
36
+ | | Runs | Authenticates |
37
+ |---|---|---|
38
+ | **Server** — `@agentronics/sdk/server` | Middleware on your server or edge (Next.js, Express, any Fetch runtime) | Anything that sends an HTTP request: signed agents, API agents, crawlers — including agents that never run your JavaScript |
39
+ | **Browser** — `@agentronics/sdk` | In the page | WebMCP agents and browser agents operating your UI |
30
40
 
31
- ## What ships in v0.1
41
+ Most sites start with the server middleware — it sees 100% of agent traffic — and add the
42
+ browser SDK when agents interact with the page itself.
32
43
 
33
- The first release is Detection + Auth + Authz + Memory + Observability + Tool Management. Payments lands in v0.2 once the first six are stable in production for our design partners. See the [changelog](/docs/reference/changelog) for the full v0.1.0 inventory.
44
+ ## Next
34
45
 
35
- Continue to [Getting Started](/docs/getting-started) to install the SDK in under five minutes.
46
+ - **[Quickstart](/docs/getting-started)** — verify your first agent in five minutes.
47
+ - **[How it works](/docs/concepts/how-it-works)** — the request flow, trust levels and results.
48
+ - **[Authentication methods](/docs/auth/overview)** — choose methods for your agents.
36
49
 
37
- ## Getting started
50
+ ## Quickstart
38
51
 
39
- This walkthrough assumes you have a Node 18+ project and a publishable API key (`agtx_pk_...`) from the Agentronics dashboard. If you do not have a key yet, sign up at [agentronics.dev](https://agentronics.dev) — the free tier is enough to follow along.
52
+ This guide adds agent authentication to a Next.js app. You'll verify signed agents and
53
+ crawlers out of the box, then add API keys for your own agents. Using Express or another
54
+ runtime? The steps are the same — see [Express](/docs/frameworks/express) or
55
+ [any Fetch runtime](/docs/frameworks/fetch).
40
56
 
41
- ### Step 1 — Install
57
+ ## 1. Install
42
58
 
43
59
  ```bash
44
60
  npm install @agentronics/sdk
45
- # or: pnpm add @agentronics/sdk
46
- # or: yarn add @agentronics/sdk
47
61
  ```
48
62
 
49
- If you only need WebMCP detection and want the smallest possible bundle, import the `lite` entry instead:
63
+ ## 2. Add the middleware
50
64
 
51
65
  ```ts
52
- import { init } from '@agentronics/sdk/lite'
53
- ```
66
+ // middleware.ts
67
+ import { agentronicsMiddleware } from '@agentronics/sdk/next'
54
68
 
55
- ### Step 2 — Initialize in the browser
69
+ export default agentronicsMiddleware()
56
70
 
57
- Call `Agentronics.init` once, as early as possible in your app's client entry. Pass your **publishable** key — never your secret key.
71
+ export const config = {
72
+ // every page and API route; skip static assets
73
+ matcher: ['/((?!_next|.*\\..*).*)'],
74
+ // Node.js runtime so crawler claims can be checked by reverse DNS
75
+ // (on the default edge runtime they stay unverified — never wrongly verified)
76
+ runtime: 'nodejs',
77
+ }
78
+ ```
58
79
 
59
- ```ts
60
- import { Agentronics } from '@agentronics/sdk'
80
+ That's a working setup. With no options it:
61
81
 
62
- const client = Agentronics.init({
63
- publishableKey: process.env.NEXT_PUBLIC_AGENTRONICS_KEY!,
64
- siteId: 'shop-acme-com',
65
- trace: { gateway: true },
66
- })
67
- ```
82
+ - verifies **signed agents** with [Web Bot Auth](/docs/auth/web-bot-auth) — e.g. OpenAI's ChatGPT agent,
83
+ - verifies **search and AI crawlers** by [reverse DNS](/docs/auth/verified-crawlers), so a scraper
84
+ claiming to be Googlebot doesn't pass,
85
+ - lets every request through — Agentronics never blocks.
68
86
 
69
- The SDK will throw a clear error if you accidentally pass a secret key (`agtx_sk_...`), so leaks fail loud rather than silent. Setting `trace.gateway: true` wires the gateway exporter so traces show up in the dashboard's `/live` feed within ~2 seconds.
87
+ <Callout title="Authentication, not blocking">
88
+ Agentronics never blocks anything. Unverified agents browse your site exactly as they did
89
+ before, and human visitors (`status: 'none'`) are untouched. Verified agents simply arrive
90
+ with an identity your app can use.
91
+ </Callout>
70
92
 
71
- ### Step 3 — React: wrap your app
93
+ ## 3. Read the verified agent in your routes
72
94
 
73
- If you use React, install the bindings and use the provider:
95
+ The middleware forwards the result as request headers. Read them with `readAgentHeaders`:
74
96
 
75
- ```bash
76
- npm install @agentronics/react
77
- ```
97
+ ```ts
98
+ // app/api/products/route.ts
99
+ import { headers } from 'next/headers'
100
+ import { readAgentHeaders } from '@agentronics/sdk/server'
78
101
 
79
- ```tsx
80
- import { AgentronicsProvider } from '@agentronics/react'
102
+ export async function GET() {
103
+ const agent = readAgentHeaders(await headers())
81
104
 
82
- export default function App({ children }) {
83
- return (
84
- <AgentronicsProvider publishableKey={process.env.NEXT_PUBLIC_AGENTRONICS_KEY!}>
85
- {children}
86
- </AgentronicsProvider>
87
- )
105
+ if (agent.status === 'verified') {
106
+ console.log(`${agent.name} (${agent.method}) is reading products`)
107
+ }
108
+ return Response.json({ products: [] })
88
109
  }
89
110
  ```
90
111
 
91
- Then access the client from any component with `useAgentronics()`. The `useGovernedTool`, `useAgentContext`, and `useSiteMemory` hooks are also exported — see the [Next.js guide](/docs/guides/nextjs) for usage.
92
-
93
- ### Step 4 — Confirm it is live
94
-
95
- Open your site, then open the Agentronics dashboard `/live` page. You should see your first session appear within ~2 seconds. If nothing shows up, double-check that:
96
-
97
- - the key starts with `agtx_pk_`,
98
- - the script runs on the client (not only at build time),
99
- - `trace.gateway: true` is set on `Agentronics.init`,
100
- - and your domain is in the gateway's `ALLOWED_ORIGINS`.
112
+ The middleware strips any `x-agentronics-*` header the caller sent, so these values can't be
113
+ forged — as long as the route sits behind the middleware.
101
114
 
102
- ### Step 5 — Next
115
+ ## 4. Give your own agents API keys
103
116
 
104
- Once detection is working, continue to:
117
+ For agents you or your customers run, issue agent API keys:
105
118
 
106
- - **[Authorization](/docs/authorization)** — declare which agents can call which tools.
107
- - **[Site Memory](/docs/concepts/site-memory)** — give agents structured context about your site.
108
- - **[Observability](/docs/observability)** — stream events into your own analytics.
109
- - **[Plain HTML / CDN](/docs/guides/plain-html)** — drop the SDK into a static page with one script tag.
119
+ ```ts
120
+ import { agentronicsMiddleware } from '@agentronics/sdk/next'
121
+ import { staticKeyVerifier } from '@agentronics/sdk/server'
122
+
123
+ export default agentronicsMiddleware({
124
+ apiKey: {
125
+ // sha256(key) → identity; mint keys with generateAgentKey()
126
+ verify: staticKeyVerifier(JSON.parse(process.env.AGENT_KEYS ?? '{}')),
127
+ },
128
+ })
129
+ ```
110
130
 
111
- Each of those has its own guide in this docs site. Welcome to Agentronics.
131
+ Agents send `Authorization: Bearer agk_…`. See [Agent API keys](/docs/auth/api-keys).
112
132
 
113
- ## Trust levels
133
+ ## 5. See it in the console
114
134
 
115
- Every identity carries a `trust` field that policies can match on. The
116
- levels (lowest → highest) are:
135
+ Stream results to the Agentronics console to get auth logs, sessions and your
136
+ [monthly active agents](/docs/concepts/monthly-active-agents) —
137
+ see [Stream auth events to the console](/docs/guides/connect-to-dashboard).
117
138
 
118
- - `detected` — the SDK observed signals (WebMCP polyfill, `navigator.webdriver`, CDP keys) but did not verify anything cryptographically.
119
- - `declared` — the host page called `client.presentIdentity({...})`. **The browser cannot verify a declared claim, and a malicious host page can claim any identity it likes.** Treat `declared` as "the page told us it's an agent" — useful for hinting, not for authorisation.
120
- - `verified` — the gateway successfully verified a cryptographic credential (OIDC ID token, SPIFFE JWT-SVID, mTLS XFCC, etc.). This is the only level you should gate dangerous tools on.
121
- - `linked` — the agent is verified *and* matched to a server-side session.
139
+ ## Next
122
140
 
123
- If your dashboard renders agent activity, surface the trust level next to the vendor so reviewers can tell a self-declared "claude" apart from a verified one.
141
+ - **[Authentication methods](/docs/auth/overview)** — OAuth2, SSO, SPIFFE, mTLS and more.
142
+ - **[Browser agents](/docs/auth/browser-agents)** — authenticate WebMCP and in-page agents too.
143
+ - **[Server API reference](/docs/reference/server-api)** — every option and result field.
124
144
 
125
145
  ## Links
126
146
 
@@ -0,0 +1,18 @@
1
+ import {a,f,d,b,c}from'./chunk-BPDWJCPY.js';import {AgentClass,isHigherTrust,IdentityClaim,AgentronicsError,PolicyRule,MemoryEntry,SiteMemory,SITE_MEMORY_DEFAULT,TraceEvent,classifyApiKey,PUBLISHABLE_KEY_PREFIX,TRUST_RANK,SiteMemoryPageContext}from'@agentronics/protocol';var Me=[{name:"GPTBot",category:"ai",pattern:/GPTBot/i},{name:"OAI-SearchBot",category:"ai",pattern:/OAI-SearchBot/i},{name:"ChatGPT-User",category:"ai",pattern:/ChatGPT-User/i},{name:"Claude-User",category:"ai",pattern:/Claude-User/i},{name:"Claude-SearchBot",category:"ai",pattern:/Claude-SearchBot/i},{name:"ClaudeBot",category:"ai",pattern:/ClaudeBot/i},{name:"Claude-Web",category:"ai",pattern:/Claude-Web/i},{name:"anthropic-ai",category:"ai",pattern:/anthropic-ai/i},{name:"Perplexity-User",category:"ai",pattern:/Perplexity-User/i},{name:"PerplexityBot",category:"ai",pattern:/PerplexityBot/i},{name:"Google-Extended",category:"ai",pattern:/Google-Extended/i},{name:"Applebot-Extended",category:"ai",pattern:/Applebot-Extended/i},{name:"Amazonbot",category:"ai",pattern:/Amazonbot/i},{name:"Bytespider",category:"ai",pattern:/Bytespider/i},{name:"CCBot",category:"ai",pattern:/CCBot/i},{name:"Meta-ExternalAgent",category:"ai",pattern:/Meta-ExternalAgent/i},{name:"cohere-ai",category:"ai",pattern:/cohere-ai/i},{name:"Googlebot",category:"search",pattern:/Googlebot/i},{name:"Bingbot",category:"search",pattern:/bingbot/i},{name:"DuckDuckBot",category:"search",pattern:/DuckDuckBot/i},{name:"YandexBot",category:"search",pattern:/YandexBot/i},{name:"Baiduspider",category:"search",pattern:/Baiduspider/i},{name:"Applebot",category:"search",pattern:/Applebot/i}],G=(e={})=>{let{signatures:t=Me,disable:n=false,confidence:r=.9}=e;if(n||typeof navigator>"u")return null;let i=navigator.userAgent??"";if(!i)return null;for(let s of t)if(s.pattern.test(i))return {class:"crawler",trust:"detected",confidence:r,vendor:s.name,userAgent:i,detectionVersion:a,signals:{matched:s.name,category:s.category,ua:i}};return null};var Ut=[/HeadlessChrome/i,/Headless/i,/PhantomJS/i,/SlimerJS/i],Kt=()=>({hit:(typeof navigator<"u"&&navigator.webdriver)===true,weight:.6,detail:"navigator.webdriver === true"}),Vt=()=>{if(typeof window>"u")return {hit:false,weight:.5};let e=Object.keys(window).filter(t=>t.startsWith("cdc_"));return {hit:e.length>0,weight:.5,detail:`window.${e[0]??"cdc_*"}`}},Ft=["__playwright__binding__","__pwInitScripts","__puppeteer_evaluation_script__","_phantom","callPhantom","__nightmare","domAutomation","domAutomationController","__selenium_unwrapped","__webdriver_evaluate","__driver_evaluate","__fxdriver_unwrapped"],Ht=()=>{if(typeof window>"u")return {hit:false,weight:.6};let e=Ft.find(t=>t in window);return e?{hit:true,weight:.6,detail:`window.${e}`}:{hit:false,weight:.6}},zt=()=>{if(typeof navigator>"u"||!navigator.plugins)return {hit:false,weight:.2};let e=/Win|Mac|Linux/.test(navigator.userAgent??""),t=navigator.plugins.length===0;return {hit:e&&t,weight:.2,detail:"desktop UA with no plugins"}},Jt=()=>{if(typeof navigator>"u")return {hit:false,weight:.7};let e=navigator.userAgent??"",t=Ut.some(n=>n.test(e));return t?{hit:t,weight:.7,detail:`headless UA: ${e}`}:{hit:t,weight:.7}},qt=()=>{if(typeof navigator>"u")return {hit:false,weight:.15};let e=navigator.languages;return {hit:!e||e.length===0,weight:.15,detail:"navigator.languages empty"}},Yt=()=>{if(typeof navigator>"u")return {hit:false,weight:.1};let e="chrome"in window,t=navigator.userAgent??"";return {hit:/Chrome\//.test(t)&&!/Edg\//.test(t)&&!e,weight:.2,detail:"Chrome UA without window.chrome"}},Xt={webdriver:Kt,chromedriver:Vt,automationGlobals:Ht,headlessUa:Jt,languages:qt,permissions:Yt,plugins:zt},U=(e={})=>{let{threshold:t=.4}=e,n={},r=0,i=0;for(let[a,u]of Object.entries(Xt)){let l=u();r+=l.weight,n[a]={hit:l.hit,weight:l.weight,detail:l.detail},l.hit&&(i+=l.weight);}let s=r===0?0:i/r;return s<t?null:{class:"dom",trust:"detected",confidence:s,vendor:null,userAgent:typeof navigator>"u"?null:navigator.userAgent,detectionVersion:a,signals:n}};var Re=()=>[{id:"webmcp.model-context",status:"stable",detect:()=>f({pollMs:0})},{id:"crawler.user-agent",status:"beta",detect:()=>G()},{id:"dom.automation-heuristics",status:"beta",detect:()=>U()}],ee=(e=Re())=>{let t=new Map(e.map(n=>[n.id,n]));return {register(n){t.set(n.id,n);},list(n){let r=[...t.values()];return n?r.filter(i=>i.status===n):r},async detectAll(n=false){for(let r of t.values()){if(r.status==="research"&&!n)continue;let i=await r.detect();if(i)return i}return null}}};var Zt=e=>{let t=AgentClass.parse(e.class),n=e.verificationToken?"verified":"declared";return {class:t,trust:n,confidence:1,vendor:e.vendor,userAgent:typeof navigator>"u"?null:navigator.userAgent,detectionVersion:a,signals:{declared:true,hasVerificationToken:!!e.verificationToken}}};var en=({gatewayUrl:e,publishableKey:t,fetcher:n=fetch})=>{let r=null,i=[];return {snapshot(){return [...i]},async sync(){let s=await n(`${e.replace(/\/$/,"")}/v1/pub/detector-signatures`,{headers:{...t?{authorization:`Bearer ${t}`}:{},...r?{"if-none-match":r}:{}}});if(s.status===304)return this.snapshot();if(!s.ok)throw new Error(`Detector signature sync failed with status ${s.status}.`);return i=(await s.json()).signatures??[],r=s.headers.get("etag"),this.snapshot()}}};var Ee=async(e={})=>{if(e.customDetectors?.length){let t=await ee(e.customDetectors).detectAll(!!e.experimental);if(t)return t}if(e.webmcp!==false){let t=await f(e.webmcp??{});if(t)return t}if(e.crawler!==false){let t=G(e.crawler??{});if(t)return t}if(e.dom!==false){let t=U(e.dom??{});if(t)return t}return null};var tn=new Set(["1024x768","1280x800","1280x720","1280x1024","1440x900","1920x1080"]),nn=e=>{if(e.length<6)return null;let t=e.reduce((r,i)=>r+i,0)/e.length;if(t<=0)return null;let n=e.reduce((r,i)=>r+(i-t)**2,0)/e.length;return Math.sqrt(n)/t},Pe=e=>{let t=0;return e.clicks>=2&&(t+=.35*(e.teleportClicks/e.clicks),t+=.25*(e.centreClicks/e.clicks),e.pointerMoves===0&&(t+=.15)),e.keyIntervalCv!==null&&e.keyIntervalCv<.15&&(t+=.2),e.insertWithoutKeys>0&&(t+=.15),e.wheelEvents===0&&e.clicks>=3&&(t+=.05),e.vmViewport&&(t+=.1),Math.min(1,t)},Ce=(e={})=>{let{threshold:t=.6,minInteractions:n=3,onDetect:r,acceptUntrustedEvents:i=false}=e,s=b=>b.isTrusted||i,a$1=e.documentRef??(typeof document>"u"?void 0:document),u={clicks:0,teleportClicks:0,centreClicks:0,keyIntervals:0,keyIntervalCv:null,insertWithoutKeys:0,pointerMoves:0,wheelEvents:0,vmViewport:false},l=Number.NEGATIVE_INFINITY,o=0,p=0,f=[],m=0,w=null,g=a$1?.defaultView;g&&(u.vmViewport=tn.has(`${g.innerWidth}x${g.innerHeight}`));let d=b=>({class:"screenshot",trust:"detected",confidence:Number(b.toFixed(2)),vendor:null,userAgent:typeof navigator>"u"?null:navigator.userAgent,detectionVersion:a,signals:{vision:true,...u}}),v=()=>{if(w||u.clicks+m<n)return;let b=Pe(u);b>=t&&(w=d(b),r?.(w));},h=b=>{s(b)&&(u.pointerMoves+=1,l=b.timeStamp);},F=[["pointermove",h],["mousemove",h],["wheel",b=>{s(b)&&(u.wheelEvents+=1);}],["click",b=>{if(!s(b))return;let T=b;u.clicks+=1,b.timeStamp-l>400&&(u.teleportClicks+=1);let B=T.target instanceof Element?T.target:null;if(B&&typeof B.getBoundingClientRect=="function"){let C=B.getBoundingClientRect();if(C.width>8&&C.height>8){let D=Math.abs(T.clientX-(C.left+C.width/2)),O=Math.abs(T.clientY-(C.top+C.height/2));D<=1.5&&O<=1.5&&(u.centreClicks+=1);}}v();}],["keydown",b=>{if(!s(b))return;let T=b.timeStamp;o&&T-o<1500?(f.push(T-o),f.length>60&&f.shift(),u.keyIntervals=f.length,u.keyIntervalCv=nn(f)):m+=1,o=T,p=T;}],["keyup",()=>v()],["input",b=>{if(!s(b))return;let T=b;T.inputType==="insertText"&&T.data&&T.data.length>1&&b.timeStamp-p>200&&(u.insertWithoutKeys+=1,m+=1,v());}]];for(let[b,T]of F)a$1?.addEventListener(b,T,{capture:true,passive:true});return {signals:()=>({...u}),score:()=>Pe(u),detected:()=>w,stop:()=>{for(let[b,T]of F)a$1?.removeEventListener(b,T,{capture:true});}}};var an=e=>({class:e.class,trust:"declared",confidence:1,vendor:e.vendor,userAgent:typeof navigator>"u"?null:navigator.userAgent,detectionVersion:a,signals:{declared:true,hasToken:true,tokenExpiresAt:e.expiresAt??null}}),De=()=>{let e=null;return {present(t){let n=IdentityClaim.safeParse(t);if(!n.success)throw new AgentronicsError("invalid_api_key",`Invalid identity claim: ${n.error.issues[0]?.message??"unknown"}`);let r={claim:n.data,identity:an(n.data)};return e=r,r},clear(){e=null;},preferOver(t){return e?t?isHigherTrust(e.identity.trust,t.trust)?e.identity:t:e.identity:t},snapshot(){return e}}};var Mr=({detected:e,declared:t,verified:n,linked:r})=>r?"linked":n?"verified":t?"declared":"detected",Le=e=>{let t=null;for(let n of e)(!t||TRUST_RANK[n.trust]>TRUST_RANK[t.trust])&&(t=n);return t};var $e=()=>({name:"bearer",async authenticate(e,t){if(!e.bearerToken)return null;let n=await t.verifyToken?.("bearer",e.bearerToken);return {class:e.classHint??"dom",trust:n?.trust??"declared",confidence:1,vendor:n?.vendor??e.vendorHint??"bearer",userAgent:typeof navigator>"u"?null:navigator.userAgent,detectionVersion:a,signals:{bearer:true,verifiedRemotely:!!n}}}});var je=()=>({name:"detection",async authenticate(e){return e.detected??null}});var _e=()=>({name:"extensionToken",async authenticate(e,t){if(!e.extensionToken)return null;let n=await t.verifyToken?.("extensionToken",e.extensionToken);return {class:"dom",trust:n?.trust??"declared",confidence:1,vendor:n?.vendor??e.vendorHint??"browser-extension",userAgent:typeof navigator>"u"?null:navigator.userAgent,detectionVersion:a,signals:{extensionToken:true,verifiedRemotely:!!n}}}});var Be=()=>({name:"mtls",async authenticate(e,t){if(!e.xfccHeader)return null;let n=await t.verifyToken?.("mtls",e.xfccHeader);return {class:e.classHint??"webmcp",trust:n?.trust??"declared",confidence:1,vendor:n?.vendor??e.vendorHint??"mtls",userAgent:typeof navigator>"u"?null:navigator.userAgent,detectionVersion:a,signals:{mtls:true,subject:n?.subject??null,verifiedRemotely:!!n,...n?.signals??{}}}}});var We=()=>({name:"oauth2",async authenticate(e,t){if(!e.oauth2AccessToken)return null;let n=await t.verifyToken?.("oauth2",e.oauth2AccessToken);return {class:e.classHint??"webmcp",trust:n?e.oauth2Subject&&n.trust!=="detected"&&n.trust!=="declared"?"linked":n.trust:"declared",confidence:1,vendor:n?.vendor??e.vendorHint??"oauth2",userAgent:typeof navigator>"u"?null:navigator.userAgent,detectionVersion:a,signals:{oauth2:true,subject:e.oauth2Subject??null,verifiedRemotely:!!n}}}});var ln=e=>({class:e.class,trust:"declared",confidence:1,vendor:e.vendor,userAgent:typeof navigator>"u"?null:navigator.userAgent,detectionVersion:a,signals:{declared:true,hasToken:true,tokenExpiresAt:e.expiresAt??null}}),Ne=()=>({name:"selfDeclaration",async authenticate(e){return e.declaration?ln(IdentityClaim.parse(e.declaration)):null}});var Ge=()=>({name:"sessionLink",async authenticate(e,t){if(!e.sessionLinkToken)return null;let n=await t.verifyToken?.("sessionLink",e.sessionLinkToken);return {class:e.classHint??"screenshot",trust:n?e.linkedUserId&&n.trust!=="detected"&&n.trust!=="declared"?"linked":n.trust:"declared",confidence:1,vendor:n?.vendor??e.vendorHint??"session-link",userAgent:typeof navigator>"u"?null:navigator.userAgent,detectionVersion:a,signals:{sessionLink:true,linkedUserId:e.linkedUserId??null,verifiedRemotely:!!n}}}});var Ue=()=>({name:"sso",async authenticate(e,t){if(!e.ssoIdToken)return null;let n=await t.verifyToken?.("sso",e.ssoIdToken);return {class:e.classHint??"dom",trust:n?.trust??"declared",confidence:1,vendor:n?.vendor??e.vendorHint??"sso",userAgent:typeof navigator>"u"?null:navigator.userAgent,detectionVersion:a,signals:{sso:true,subject:n?.subject??null,verifiedRemotely:!!n,...n?.signals??{}}}}});var Ke=()=>({name:"spiffe",async authenticate(e,t){if(!e.spiffeJwt)return null;let n=await t.verifyToken?.("spiffe",e.spiffeJwt),r=n?.vendor==="google";return {class:e.classHint??"webmcp",trust:n?.trust??"declared",confidence:1,vendor:n?.vendor??e.vendorHint??"spiffe",userAgent:typeof navigator>"u"?null:navigator.userAgent,detectionVersion:a,signals:{spiffe:true,spiffeId:n?.subject??null,subject:n?.subject??null,verifiedRemotely:!!n,...r?{googleAgent:true}:{},...n?.signals??{}}}}});var Ve=()=>({name:"xAgentHeader",async authenticate(e){if(!e.xAgentHeader)return null;let[t="x-agent",n="dom",r]=e.xAgentHeader.split(";"),i=AgentClass.safeParse(n);return {class:i.success?i.data:"dom",trust:"declared",confidence:r?1:.8,vendor:t,userAgent:typeof navigator>"u"?null:navigator.userAgent,detectionVersion:a,signals:{xAgentHeader:true,hasProof:!!r}}}});var He=new Set(["bearer","extensionToken","sessionLink","oauth2","sso","spiffe","mtls"]),dn=(e,t,n)=>{if(He.has(e)&&t.signals?.verifiedRemotely===false){let r=e==="oauth2"&&n.oauth2Subject||e==="sessionLink"&&n.linkedUserId;return {...t,trust:r?"linked":"verified",signals:{...t.signals,compat:"0.6"}}}return e==="xAgentHeader"&&t.signals?.hasProof===true?{...t,trust:"verified",confidence:1,signals:{...t.signals,compat:"0.6"}}:t},Fe=()=>[je(),Ne(),$e(),Ve(),_e(),Ge(),We()],pn=()=>[Ue(),Ke(),Be()],mn={detection:"detection",selfDeclaration:"declaration",bearer:"bearer",xAgentHeader:"x-agent-header",extensionToken:"extension",sessionLink:"session-link",oauth2:"oauth2",sso:"sso",spiffe:"spiffe",mtls:"mtls"},gn=(e,t)=>e==="spiffe"&&t.signals?.googleAgent===true?"google-agent":mn[e],ze=({compat:e,methods:t=e==="0.6"?[...Fe(),...pn()]:Fe(),context:n={},onTrace:r,onUnverifiedToken:i}={})=>{let s=false;return {async authenticate(a){let u=[],l={};for(let g of t){let d=await g.authenticate(a,n);l[g.name]=!!d,d&&(He.has(g.name)&&d.signals?.verifiedRemotely===false&&!n.verifyToken&&!s&&(s=true,i?.(g.name)),e==="0.6"&&(d=dn(g.name,d,a)),u.push({method:g.name,identity:d}));}let o=Le(u.map(g=>g.identity)),p=o?u.find(g=>g.identity===o):void 0,f=p?gn(p.method,p.identity):void 0,m=typeof o?.signals?.subject=="string"?o.signals.subject:void 0,w={type:o?"auth.identity_presented":"sdk.error",agent:o,outcome:o?"success":"error",metadata:{methods:l,...f?{protocol:f}:{},...m?{subject:m}:{}}};return o||(w.error="No auth method produced an identity."),r?.(w),o},methods(){return t.map(a=>a.name)}}};var yn={identity:null,source:"initial",updatedAt:null},Je=()=>{let e=yn,t=new Set,n=()=>{t.size!==0&&t.forEach(r=>r(e));};return {snapshot(){return e},set(r,i){e={identity:r,source:i,updatedAt:new Date().toISOString()},n();},subscribe(r){return t.add(r),()=>{t.delete(r);}}}};var fn=()=>{let e=new Map;return {read:t=>e.get(t)??null,write:(t,n)=>{e.set(t,n);}}},hn=()=>typeof window>"u"||!window.localStorage?fn():{read:e=>{try{return window.localStorage.getItem(e)}catch{return null}},write:(e,t)=>{try{window.localStorage.setItem(e,t);}catch{}}},vn=e=>{if(!e)return null;try{let t=JSON.parse(e);if(typeof t=="object"&&t!==null&&Number.isFinite(t.count)&&Number.isFinite(t.resetAt))return t}catch{return null}return null},qe=(e=hn())=>({consume(t,n,r=Date.now()){let i=`agtx:rate:${t}`,s=vn(e.read(i)),a=s&&s.resetAt>r?s.resetAt:r+n.windowSeconds*1e3,u=s&&s.resetAt>r?s.count+1:1;return e.write(i,JSON.stringify({count:u,resetAt:a})),{allowed:u<=n.max,remaining:Math.max(0,n.max-u),resetAt:a}}});var wn=(e,t)=>e==="*"||e===t?true:e.includes("*")?new RegExp("^"+e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*")+"$").test(t):false,bn=(e,t)=>{let n=e?TRUST_RANK[e.trust]:-1,r=TRUST_RANK[t.minTrust];return n>=r},xn=(e,t)=>t.allowedClasses.length===0?true:e?t.allowedClasses.includes(e.class):false,Qe="allow",Sn=(e,t)=>{let n=t?.class??"unknown",r=t?.vendor??"unknown",i=t?.trust??"none";return `${e}:${n}:${r}:${i}`},Ze=(e=[],t={})=>{let n=e.map(i=>PolicyRule.parse(i)),r=t.rateLimiter??qe();return {set(i){n=i.map(s=>PolicyRule.parse(s));},list(){return [...n]},evaluate({tool:i,identity:s}){for(let a of n)if(wn(a.tool,i)){if(!bn(s,a))return {decision:"deny",ruleId:a.id,reason:`Rule "${a.id}" requires trust >= ${a.minTrust}.`};if(!xn(s,a))return {decision:"deny",ruleId:a.id,reason:`Rule "${a.id}" restricts to classes: ${a.allowedClasses.join(", ")}.`};if(a.rateLimit){let u=r.consume(Sn(i,s),a.rateLimit);if(!u.allowed)return {decision:"deny",ruleId:a.id,reason:`Rule "${a.id}" rate limit exceeded. Resets at ${new Date(u.resetAt).toISOString()}.`}}return {decision:a.decision,ruleId:a.id,reason:`Matched rule "${a.id}".`}}return {decision:Qe,ruleId:null,reason:`No rule matched tool "${i}". Falling back to "${Qe}".`}}}};var et=({gatewayUrl:e,siteId:t,publishableKey:n,fetcher:r=fetch})=>{let i={policies:[],etag:null};return {snapshot(){return {policies:[...i.policies],etag:i.etag}},async sync(){let s=await r(`${e.replace(/\/$/,"")}/v1/pub/sites/${encodeURIComponent(t)}/policies`,{headers:{authorization:`Bearer ${n}`,...i.etag?{"if-none-match":i.etag}:{}}});if(s.status===304)return this.snapshot();if(!s.ok)throw new Error(`Policy sync failed with status ${s.status}.`);let a=await s.json();return i={policies:PolicyRule.array().parse(a.policies??[]),etag:s.headers.get("etag")},this.snapshot()}}};var tt=({message:e="Agent action blocked by site policy.",durationMs:t=2400,documentRef:n=typeof document>"u"?void 0:document}={})=>{if(!n?.body)return null;let r=n.createElement("div");return r.setAttribute("role","status"),r.setAttribute("data-agentronics-deny-overlay","true"),r.textContent=e,Object.assign(r.style,{position:"fixed",zIndex:"2147483647",left:"50%",bottom:"24px",transform:"translateX(-50%)",maxWidth:"min(520px, calc(100vw - 32px))",padding:"12px 16px",borderRadius:"12px",background:"#0B0B0C",color:"#FFFFFF",border:"2px solid #FF4D1F",font:"13px/1.45 ui-monospace, SFMono-Regular, Menlo, monospace"}),n.body.appendChild(r),window.setTimeout(()=>r.remove(),t),r};var nt=({policyEngine:e,getIdentity:t,documentRef:n=typeof document>"u"?void 0:document,selector:r="[data-agentronics-tool]"})=>{if(!n)return {uninstall:()=>{}};let i=s=>{let a=s.target instanceof Element?s.target.closest(r):null;if(!(a instanceof HTMLElement))return;let u=a.dataset.agentronicsTool;u&&Promise.resolve(t()).then(l=>{let o=e.evaluate({tool:u,identity:l});o.decision==="deny"&&(s.preventDefault(),s.stopPropagation(),tt({message:o.reason,documentRef:n}));});};return n.addEventListener("click",i,true),{uninstall:()=>n.removeEventListener("click",i,true)}};var te=()=>{let e=new Map;return {read:t=>e.get(t)??null,write:(t,n)=>{e.set(t,n);},remove:t=>{e.delete(t);},keys:()=>[...e.keys()]}},rt=(e,t)=>({read:n=>{try{return e.getItem(t+n)}catch{return null}},write:(n,r)=>{try{e.setItem(t+n,r);}catch{}},remove:n=>{try{e.removeItem(t+n);}catch{}},keys:()=>{let n=[];try{for(let r=0;r<e.length;r++){let i=e.key(r);i&&i.startsWith(t)&&n.push(i.slice(t.length));}}catch{}return n}}),ot="agtx:",it=()=>{let e=typeof window<"u",t=e&&typeof window.sessionStorage<"u"?rt(window.sessionStorage,ot+"session:"):te(),n=e&&typeof window.localStorage<"u"?rt(window.localStorage,ot+"user:"):te();return {session:t,user:n,org:te()}};var at=(e,t)=>e.expiresAt!==null&&e.expiresAt<=t,ct=e=>{if(!e)return null;try{let t=JSON.parse(e);return typeof t!="object"||t===null?null:t}catch{return null}},An=e=>JSON.stringify(e),lt=(e={})=>{let t=it(),n=l=>{e.onTrace?.(l);};return {get:(l,o={})=>{let p=o.scope??"session",f=t[p],m=ct(f.read(l));if(!m){n({type:"memory.accessed",metadata:{operation:"get",key:l,scope:p,hit:false}});return}if(at(m,Date.now())){f.remove(l),n({type:"memory.accessed",metadata:{operation:"get",key:l,scope:p,hit:false,expired:true}});return}return n({type:"memory.accessed",metadata:{operation:"get",key:l,scope:p,hit:true}}),m.value},set:(l,o,p={})=>{let f=p.scope??"session",m=p.ttlSeconds??null,w=Date.now(),g={value:o,expiresAt:m===null?null:w+m*1e3,updatedAt:new Date(w).toISOString()};return t[f].write(l,An(g)),n({type:"memory.updated",metadata:{operation:"set",key:l,scope:f,ttlSeconds:m}}),MemoryEntry.parse({key:l,value:o,scope:f,ttlSeconds:m,updatedAt:g.updatedAt})},remove:(l,o={})=>{let p=o.scope??"session";t[p].remove(l),n({type:"memory.updated",metadata:{operation:"remove",key:l,scope:p}});},list:(l={})=>{let o=l.scope??"session",p=t[o],f=Date.now(),m=[];for(let w of p.keys()){let g=ct(p.read(w));if(g){if(at(g,f)){p.remove(w);continue}m.push(MemoryEntry.parse({key:w,value:g.value,scope:o,ttlSeconds:g.expiresAt===null?null:Math.max(0,Math.round((g.expiresAt-f)/1e3)),updatedAt:g.updatedAt}));}}return n({type:"memory.accessed",metadata:{operation:"list",scope:o,count:m.length}}),m},clear:(l={})=>{let o=l.scope??"session",p=t[o],f=p.keys().length;for(let m of p.keys())p.remove(m);n({type:"memory.updated",metadata:{operation:"clear",scope:o,count:f}});}}};var ne=e=>SiteMemory.parse(JSON.parse(JSON.stringify(e))),H=e=>({...e,updatedAt:new Date().toISOString()}),ut=(e={})=>{let t=SiteMemory.parse({...SITE_MEMORY_DEFAULT,...e.initial??{}}),n=null,r=new Set,i=d=>{e.onTrace?.(d);},s=()=>{n=null;},a=()=>{if(r.size===0)return;let d=ne(t);n=d,r.forEach(v=>v(d));},u=d=>{let v=SiteMemory.parse({...t,...d,workflows:{...t.workflows,...d.workflows??{}},policies:{...t.policies,...d.policies??{}},uiGuidance:{...t.uiGuidance,...d.uiGuidance??{}},pageContexts:{...t.pageContexts,...d.pageContexts??{}}});return t=H(v),s(),i({type:"memory.updated",metadata:{kind:"site",operation:"provide",keys:Object.keys(d)}}),a(),p()},l=(d,v)=>{let h=d.split(".").filter(Boolean);if(h.length===0)throw new Error("siteMemory.update() requires a non-empty dot-path.");let A=JSON.parse(JSON.stringify(t)),M=A;for(let R=0;R<h.length-1;R++){let k=h[R],E=M[k];(typeof E!="object"||E===null||Array.isArray(E))&&(M[k]={}),M=M[k];}return M[h[h.length-1]]=v,t=H(SiteMemory.parse(A)),s(),i({type:"memory.updated",metadata:{kind:"site",operation:"update",path:d}}),a(),p()},o=d=>{let v=SiteMemoryPageContext.parse({path:d.path,payload:d.payload,updatedAt:new Date().toISOString()});return t=H({...t,pageContexts:{...t.pageContexts,[d.path]:v}}),s(),i({type:"memory.updated",metadata:{kind:"site",operation:"provideForPage",path:d.path}}),a(),{...v,payload:{...v.payload}}},p=()=>(n||(n=ne(t)),n);return {provide:u,update:l,provideForPage:o,snapshot:p,get:d=>{if(i({type:"memory.accessed",metadata:{kind:"site",operation:d?"get":"snapshot",path:d??null}}),!d)return ne(t);let v=d.split(".").filter(Boolean),h=t;for(let A of v){if(typeof h!="object"||h===null)return;h=h[A];}return h},getForPage:d=>{i({type:"memory.accessed",metadata:{kind:"site",operation:"getForPage",path:d}});let v=t.pageContexts[d];return v?{...v,payload:{...v.payload}}:null},replace:d=>(t=H(SiteMemory.parse(d)),s(),a(),p()),subscribe:d=>(r.add(d),()=>{r.delete(d);})}};var pt=({gatewayUrl:e,siteId:t,publishableKey:n,fetcher:r=fetch})=>{let i={memory:null,etag:null};return {snapshot(){return {memory:i.memory?SiteMemory.parse(i.memory):null,etag:i.etag}},async sync(){let s=await r(`${e.replace(/\/$/,"")}/v1/pub/sites/${encodeURIComponent(t)}/memory`,{headers:{authorization:`Bearer ${n}`,...i.etag?{"if-none-match":i.etag}:{}}});if(s.status===304)return this.snapshot();if(!s.ok)throw new Error(`Memory sync failed with status ${s.status}.`);let a=await s.json();return i={memory:SiteMemory.parse(a.memory??{}),etag:s.headers.get("etag")},this.snapshot()}}};var Mn=({toolName:e="getSiteContext",description:t="Returns Agentronics site memory: page map, workflows, policies, UI guidance.",getSnapshot:n,onAccess:r})=>({name:e,description:t,inputSchema:{type:"object",properties:{path:{type:"string",description:'Optional dot-path into the site memory (e.g. "workflows.purchase").'}},required:[]},invoke(i={}){let s=n(),a=i.path??null;if(r?.(a),!a)return {content:s};let u=a.split(".").filter(Boolean),l=s;for(let o of u){if(typeof l!="object"||l===null)return {content:void 0};l=l[o];}return {content:l}}});var L="agent-context-",re="agentronics-site-context",Rn=e=>{try{return JSON.stringify(e)}catch{return "{}"}},z=(e,t,n)=>{let r=e.querySelector(`meta[name="${t}"]`);r||(r=e.createElement("meta"),r.setAttribute("name",t),e.head.appendChild(r)),r.setAttribute("content",n);},J=(e,t)=>{e.querySelectorAll(`meta[name="${t}"]`).forEach(n=>n.remove());},oe=({doc:e=typeof document>"u"?null:document,snapshot:t,schemaType:n="WebSite"})=>{if(!e)return {uninstall:()=>{}};z(e,`${L}version`,t.version),z(e,`${L}updated-at`,t.updatedAt??new Date().toISOString()),t.siteMap?.navigation?.flow&&z(e,`${L}flow`,t.siteMap.navigation.flow),z(e,`${L}workflows`,Object.keys(t.workflows).join(","));let r=e.getElementById(re);return r||(r=e.createElement("script"),r.type="application/ld+json",r.id=re,e.head.appendChild(r)),r.textContent=Rn({"@context":"https://schema.org","@type":n,name:"Agentronics Site Memory",agentronics:t}),{uninstall:()=>{J(e,`${L}version`),J(e,`${L}updated-at`),J(e,`${L}flow`),J(e,`${L}workflows`),e.getElementById(re)?.remove();}}};var mt="agentronics-memory-overlay",En=e=>`
2
+ position: fixed;
3
+ bottom: 16px;
4
+ right: 16px;
5
+ max-width: 320px;
6
+ padding: 10px 12px;
7
+ background: rgba(11, 11, 12, 0.92);
8
+ color: #ffffff;
9
+ font: 12px/1.45 ui-monospace, SFMono-Regular, Menlo, monospace;
10
+ border: 1px solid rgba(255, 255, 255, 0.15);
11
+ border-radius: 10px;
12
+ z-index: 2147483647;
13
+ opacity: ${e?"0":"1"};
14
+ pointer-events: ${e?"none":"auto"};
15
+ `,gt=e=>{let t=e.siteMap?.pages?.length??0,n=Object.keys(e.workflows).length,r=Object.keys(e.uiGuidance).length;return `Agentronics site memory \xB7 pages:${t} \xB7 workflows:${n} \xB7 ui-hints:${r}`},ie=({doc:e=typeof document>"u"?null:document,snapshot:t,hidden:n=false})=>{if(!e)return {uninstall:()=>{},refresh:()=>{}};let r=e.getElementById(mt);return r||(r=e.createElement("div"),r.id=mt,r.setAttribute("role","note"),r.setAttribute("aria-label","Agentronics site memory summary"),r.setAttribute("data-agent-context","overlay"),e.body.appendChild(r)),r.setAttribute("style",En(n)),r.textContent=gt(t),{uninstall:()=>{r?.remove();},refresh:i=>{r&&(r.textContent=gt(i));}}};var ft="/.well-known/agent-context.json",se=async({origin:e,fetcher:t=fetch,signal:n}={})=>{let r=(e?e.replace(/\/$/,""):typeof window<"u"?window.location.origin:"")+ft;if(!r.startsWith("http"))return null;let i={headers:{accept:"application/json"}};n!==void 0&&(i.signal=n);let s=await t(r,i);if(!s.ok){if(s.status===404)return null;throw new Error(`well-known agent-context fetch failed with status ${s.status}.`)}let a=await s.json();return SiteMemory.parse(a)},Pn=({snapshot:e})=>JSON.stringify(SiteMemory.parse(e));var ht=({evaluate:e,setPolicies:t,listPolicies:n,onTrace:r,identityResolver:i,reviewer:s})=>{let a=new Map,u=new Set,l=o=>{if(!o.authz||!t||!n)return;let p={id:`tool:${o.name}`,tool:o.name,...o.authz,rateLimit:o.rateLimit??o.authz.rateLimit};t([...n().filter(f=>f.id!==p.id),p]);};return {register(o){return a.set(o.name,o),u.delete(o.name),l(o),r?.({type:"tool.registered",tool:o.name,metadata:{version:o.version??null,group:o.group??null,stage:o.stage??null}}),()=>{a.delete(o.name),u.delete(o.name);}},unregister(o){a.delete(o),u.delete(o);},enable(o){!a.has(o)||!u.has(o)||(u.delete(o),r?.({type:"tool.surfaced",tool:o,metadata:{state:"enabled"}}));},disable(o){!a.has(o)||u.has(o)||(u.add(o),r?.({type:"tool.surfaced",tool:o,metadata:{state:"disabled"}}));},isEnabled:o=>a.has(o)&&!u.has(o),list({includeDisabled:o=false}={}){let p=[...a.values()];return o?p:p.filter(f=>!u.has(f.name))},get:o=>a.get(o),async execute(o,p,f,m={}){let w=f===void 0?i?.()??null:f,g=a.get(o);if(!g)throw new Error(`Tool "${o}" is not registered.`);if(u.has(o)){let h={decision:"deny",ruleId:`tool:${o}`,reason:"Tool is disabled."};throw r?.({type:"tool.executed",tool:o,agent:w,policy:h,outcome:"blocked"}),new Error(h.reason)}let d=await e(o,{identity:w});if(d.decision==="deny")throw r?.({type:"tool.executed",tool:o,agent:w,policy:d,outcome:"blocked"}),new Error(d.reason);if(d.decision==="review"){let h={tool:o,input:p,identity:w,reason:d.reason};g.title!==void 0&&(h.title=g.title),g.description!==void 0&&(h.description=g.description);let A=s?await s(h).catch(()=>false):false;if(r?.({type:"authz.evaluated",tool:o,agent:w,policy:d,outcome:A?"success":"blocked",metadata:{review:true,approved:A,reviewer:s?"configured":"none"}}),!A){let M={...d,decision:"deny",reason:s?"The person on the page did not approve this action.":"This action needs review and no reviewer is configured."};throw r?.({type:"tool.executed",tool:o,agent:w,policy:M,outcome:"blocked"}),new Error(M.reason)}d={...d,reason:`${d.reason} Approved by the person on the page.`};}let v=Date.now();try{let h={identity:w};m.signal&&(h.signal=m.signal);let A=await g.execute(p,h);return r?.({type:"tool.executed",tool:o,agent:w,policy:d,outcome:"success",durationMs:Date.now()-v}),A}catch(h){throw r?.({type:"tool.executed",tool:o,agent:w,policy:d,outcome:"error",durationMs:Date.now()-v,error:h instanceof Error?h.message:String(h)}),h}}}};var q=e=>e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(q).join(",")}]`:`{${Object.keys(e).sort().map(n=>`${JSON.stringify(n)}:${q(e[n])}`).join(",")}}`,vt=e=>({name:e.name,...e.title?{title:e.title}:{},description:e.description??e.name,...e.inputSchema?{inputSchema:e.inputSchema}:{},...e.annotations?{annotations:e.annotations}:{}}),wt=e=>Math.ceil(q(vt(e)).length/4),Cn=e=>{let t=q(vt(e)).length;return {name:e.name,characters:t,tokens:Math.ceil(t/4)}},bt=e=>{let t=e.map(Cn);return {total:t.reduce((r,i)=>r+i.tokens,0),perTool:t}};var xt=(e,t={})=>{let n=new Map;for(let a of e.stages)n.set(a.name,a);if(!n.has(e.initial))throw new Error(`Initial stage "${e.initial}" is not declared in progression stages.`);let r=e.initial,i=()=>{let a=n.get(r);return a?.enables?[r,...a.enables]:[r]},s=(a,u)=>{let l=r;if(!n.has(a))throw new Error(`Cannot transition to unknown stage "${a}".`);return a===r?{changed:false,from:l,to:a}:(r=a,t.onTrace?.({type:"tool.progressed",metadata:{from:l,to:a,trigger:u}}),{changed:true,from:l,to:a})};return {current:()=>r,enabledStages:()=>i(),notify(a){let l=n.get(r)?.transitions?.find(o=>o.on===a);return l?s(l.to,a):{changed:false,from:r,to:r}},set(a){return s(a,"manual")},reset(){let a=r;r=e.initial,a!==r&&t.onTrace?.({type:"tool.progressed",metadata:{from:a,to:r,trigger:"reset"}});},snapshot:()=>({current:r,enabled:i()})}};var Dn=(e,t)=>{let n=e.authz?.minTrust;return n?t?TRUST_RANK[t.trust]<TRUST_RANK[n]?{ok:false,reason:`trust-too-low:${t.trust}<${n}`}:{ok:true,reason:"trust-ok"}:{ok:false,reason:`requires-trust:${n}`}:{ok:true,reason:"no-trust-floor"}},On=(e,t)=>{let n=e.authz?.allowedClasses??[];return n.length===0?{ok:true,reason:"no-class-restriction"}:t?n.includes(t.class)?{ok:true,reason:"class-ok"}:{ok:false,reason:`class-not-allowed:${t.class}`}:{ok:false,reason:`requires-class:${n.join("|")}`}},Ln=(e,t)=>e.stage?t.enabledStages&&t.enabledStages.includes(e.stage)?{ok:true,reason:`stage-enabled:${e.stage}`}:t.stage===e.stage?{ok:true,reason:`stage-active:${e.stage}`}:{ok:false,reason:`stage-locked:${e.stage}`}:{ok:true,reason:"no-stage"},Tt=(e,t)=>{let n=Dn(e,t.identity);if(!n.ok)return {tool:e,visible:false,reason:n.reason};let r=On(e,t.identity);if(!r.ok)return {tool:e,visible:false,reason:r.reason};let i=Ln(e,t);return i.ok?e.authz?.decision==="deny"?{tool:e,visible:false,reason:"authz-deny"}:{tool:e,visible:true,reason:"visible"}:{tool:e,visible:false,reason:i.reason}},At=(e,t)=>e.filter(n=>Tt(n,t).visible),kt=(e,t)=>e.map(n=>Tt(n,t));var It="default",Mt=e=>{let t=new Map;for(let n of e){let r=n.group??It,i=t.get(r)??[];i.push(n),t.set(r,i);}return [...t.entries()].sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>({name:n,tools:r}))},Uo=e=>[...new Set(e.map(t=>t.group??It))].sort();var $n=(e,t)=>e==="legacy",jn=(e,t)=>{let n={name:e.name,description:e.description??e.name,execute:(r,{signal:i})=>t(e,r??{},i)};return e.title!==void 0&&(n.title=e.title),e.inputSchema!==void 0&&(n.inputSchema=e.inputSchema),e.annotations!==void 0&&(n.annotations={...e.annotations}),n},Rt=(e={})=>{let t=e.invoke??(async(o,p)=>o.execute(p,{identity:null})),n=null,r=null,i=null,s=[],a=()=>{let o=e.modelContext??e.provider;return o?{source:typeof o.registerTool=="function"?"document":"legacy",context:o}:b(e.host)},u=()=>{n?.abort(),n=null,r?.revoke(),r=null;},l=o=>{if(i||typeof o.addEventListener!="function")return;let p=m=>c("activated",m.toolName??""),f=m=>c("cancelled",m.toolName??"");o.addEventListener("toolactivated",p),o.addEventListener("toolcancel",f),i=()=>{o.removeEventListener?.("toolactivated",p),o.removeEventListener?.("toolcancel",f),i=null;};};return {publish(o){let p=a();if(!p)return {revoked:false,registrations:Promise.resolve([])};if(u(),$n(p.source,p.context))return r=p.context.provideContext({tools:o.map(g=>{let d={name:g.name,invoke:v=>t(g,v)};return g.description!==void 0&&(d.description=g.description),g.inputSchema!==void 0&&(d.inputSchema=g.inputSchema),d})}),s=o.map(g=>({name:g.name,status:"callable"})),{revoked:true,registrations:Promise.resolve(s)};let f=p.context;l(f);let m=new AbortController;return n=m,{revoked:true,registrations:Promise.all(o.map(async g=>{try{let d={signal:m.signal};return g.exposedTo?.length&&(d.exposedTo=g.exposedTo),await f.registerTool(jn(g,t),d),{name:g.name,status:"callable"}}catch(d){return {name:g.name,status:"failed",error:d instanceof Error?`${d.name}: ${d.message}`:String(d)}}})).then(g=>(n===m&&(s=g),g))}},revoke(){u(),i?.(),s=[];},available:()=>!!a(),source:()=>a()?.source??null,status:()=>[...s]}};var _n=e=>e===null||typeof e!="object"?"":Object.entries(e).slice(0,6).map(([n,r])=>`${n}: ${typeof r=="string"?r:JSON.stringify(r)}`.slice(0,90)).join(`
16
+ `),Et=({documentRef:e=typeof document>"u"?void 0:document,timeoutMs:t=12e4}={})=>n=>new Promise(r=>{if(!e?.body)return r(false);let i=e,s=i.createElement("div");s.setAttribute("data-agentronics-review","true"),Object.assign(s.style,{position:"fixed",inset:"0",zIndex:"2147483647",background:"rgba(11,11,12,0.45)",display:"flex",alignItems:"center",justifyContent:"center",padding:"16px"});let a=i.createElement("div");a.setAttribute("role","dialog"),a.setAttribute("aria-modal","true"),a.setAttribute("aria-label","Approve agent action"),Object.assign(a.style,{width:"min(440px, 100%)",background:"#FFFFFF",color:"#0B0B0C",border:"2px solid #0B0B0C",borderRadius:"16px",padding:"20px",boxShadow:"8px 8px 0 #0B0B0C",font:"14px/1.5 system-ui, -apple-system, 'Segoe UI', sans-serif"});let u=i.createElement("div");u.style.fontWeight="700",u.style.fontSize="16px";let l=n.identity?.vendor??"An AI agent";u.textContent=`${l} wants to ${n.title??n.tool}`;let o=i.createElement("div");o.style.margin="8px 0 0",o.style.color="rgba(11,11,12,0.65)",o.textContent=n.description??"Allow this action on your behalf?";let p=i.createElement("pre"),f=_n(n.input);Object.assign(p.style,{display:f?"block":"none",margin:"12px 0 0",padding:"10px 12px",background:"rgba(11,11,12,0.06)",borderRadius:"10px",fontSize:"12px",fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",overflowWrap:"anywhere"}),p.textContent=f;let m=i.createElement("div");Object.assign(m.style,{display:"flex",gap:"8px",justifyContent:"flex-end",marginTop:"16px"});let w=(R,k)=>{let E=i.createElement("button");return E.type="button",E.textContent=R,Object.assign(E.style,{padding:"9px 16px",borderRadius:"10px",border:"2px solid #0B0B0C",background:k?"#D4FF3A":"#FFFFFF",color:"#0B0B0C",boxShadow:k?"3px 3px 0 #0B0B0C":"none",font:"inherit",fontWeight:"650",cursor:"pointer"}),E},g=w("Not now",false),d=w("Allow",true);m.append(g,d),a.append(u,o,p,m),s.append(a);let v=false,h=R=>{v||(v=true,clearTimeout(M),i.removeEventListener("keydown",A,true),s.remove(),r(R));},A=R=>{R.key==="Escape"&&h(false);},M=setTimeout(()=>h(false),t);d.addEventListener("click",()=>h(true)),g.addEventListener("click",()=>h(false)),i.addEventListener("keydown",A,true),i.body.appendChild(s),d.focus();});var ae=(e=500)=>{let t=[];return {add(n){t.push(n),t.length>e&&t.splice(0,t.length-e);},list(){return [...t]},clear(){t.length=0;}}};var Pt=(e,t)=>e===void 0?t:Math.max(0,Math.min(1,e)),ce=(e={})=>{let t=Pt(e.traceRate,1),n=Pt(e.errorRate,1),r=e.random??Math.random;return {shouldKeep(i){let s=i.outcome==="error"?n:t;return r()<s}}};var Bn="[REDACTED]",Wn=e=>{if(e!==void 0)return JSON.parse(JSON.stringify(e))},le=(e,t)=>{if(t.length===0||typeof e!="object"||e===null)return;let[n,...r]=t;if(!n)return;if(Array.isArray(e)){for(let s of e)le(s,t);return}let i=e;if(n in i){if(r.length===0){i[n]=Bn;return}le(i[n],r);}},ue=(e,t=[])=>{if(t.length===0)return e;let n=Wn(e);for(let r of t)le(n,r.split(".").filter(Boolean));return n},de=["metadata.password","metadata.token","metadata.authorization","metadata.cookie"];var Gn=()=>typeof location<"u"&&typeof location.pathname=="string"?location.pathname:void 0,Ct=e=>{let t=globalThis.crypto;return t&&"randomUUID"in t?`${e}_${t.randomUUID()}`:`${e}_${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`},pe=({siteId:e,bufferSize:t,sessionId:n=Ct("ses"),scrubPaths:r=de,exporters:i=[],onExporterError:s,pageProvider:a=Gn,...u})=>{let l=ae(t),o=ce(u),p=()=>{try{return a()}catch{return}};return {sessionId:n,async emit(f){let m={...f.metadata};if(m.page===void 0){let g=p();g!==void 0&&(m.page=g);}let w=TraceEvent.parse(ue({id:Ct("trc"),siteId:e,sessionId:n,occurredAt:new Date().toISOString(),outcome:f.outcome??"success",...f,metadata:m},r));return o.shouldKeep(w)?(l.add(w),await Promise.all(i.map(async g=>{try{await g.export([w]);}catch(d){s?.(d,g,w);}})),w):null},list:()=>l.list(),clear:()=>l.clear()}};var me=()=>({name:"console",export(e){for(let t of e)console.info("[agentronics:trace]",t.type,t);}});var ge=({gatewayUrl:e,publishableKey:t,fetcher:n=fetch})=>({name:"gateway",async export(r){let i={publishableKey:t,events:r};await n(`${e.replace(/\/$/,"")}/v1/pub/traces`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${t}`},body:JSON.stringify(i)});}});var Un=e=>new Promise(t=>setTimeout(t,e)),fe=({url:e,fetcher:t=fetch,maxRetries:n=2,queueLimit:r=500})=>({name:"webhook",async export(i){let a=[...Kn(e),...i].slice(-r),u=0;for(;;){let l=await t(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({events:a})});if(l.ok){Dt(e,[]);return}if(u>=n)throw Dt(e,a),new Error(`Webhook exporter failed with status ${l.status}.`);u+=1,await Un(100*u);}}}),ye=e=>`agtx:webhook:${e}`,Kn=e=>{if(typeof window>"u"||!window.localStorage)return [];try{let t=window.localStorage.getItem(ye(e));return t?JSON.parse(t):[]}catch{return []}},Dt=(e,t)=>{if(!(typeof window>"u"||!window.localStorage))try{if(t.length===0){window.localStorage.removeItem(ye(e));return}window.localStorage.setItem(ye(e),JSON.stringify(t));}catch{}};var he=e=>{let t={name:e.name,description:e.description??"",inputSchema:e.inputSchema??{},tokens:0};return e.title&&(t.title=e.title),e.annotations&&(t.annotations={...e.annotations}),e.group&&(t.group=e.group),e.stage&&(t.page=e.stage),e.outputSchema&&(t.outputSchema=e.outputSchema),t.tokens=wt(e),t},Ot=({gatewayUrl:e,siteId:t,publishableKey:n,fetcher:r=fetch})=>({async push(i){let s=i.map(he),a=await r(`${e.replace(/\/$/,"")}/v1/pub/sites/${encodeURIComponent(t)}/tools`,{method:"PUT",headers:{authorization:`Bearer ${n}`,"content-type":"application/json"},body:JSON.stringify({registry:{tools:s}})});if(!a.ok)throw new Error(`Tool sync failed with status ${a.status}.`);return s.length}});var Lt="/v1/sdk/events",$t=({url:e,ingestKey:t,fetcher:n=fetch})=>{let r=e.replace(/\/$/,""),i=r.endsWith(Lt)?r:`${r}${Lt}`;return {name:"intel",async export(s){let a={events:s},u=await n(i,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${t}`},body:JSON.stringify(a)});if(!u.ok)throw new Error(`Intel exporter failed with status ${u.status}.`)}}},jt=({url:e,ingestKey:t,siteId:n,fetcher:r=fetch})=>{let i=e.replace(/\/$/,""),s=async(l,o)=>{let p=await r(`${i}${l}`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${t}`},body:JSON.stringify(o)});if(!p.ok)throw new Error(`Intel sync ${l} failed with status ${p.status}.`);return p},a=async(l,o)=>{await s(l,o);},u=new Map;return {async pushTools(l){let o=l.map(he);return await a("/v1/sdk/tools",{siteId:n,tools:o}),o.length},async pushMemory(l,o){await a("/v1/sdk/memory",{siteId:n,snapshot:l,...typeof o=="number"?{score:o}:{}});},async pullConfig(){let l=await(await s("/v1/sdk/config",{siteId:n})).json();return {policies:Array.isArray(l.policies)?l.policies:[],toolDescriptions:l.toolDescriptions&&typeof l.toolDescriptions=="object"?l.toolDescriptions:{},siteMemory:l.siteMemory&&typeof l.siteMemory=="object"?l.siteMemory:null,fetchedAt:typeof l.fetchedAt=="string"?l.fetchedAt:new Date().toISOString()}},keyVerifier({cacheSeconds:l=60}={}){return async o=>{let p=u.get(o);if(p&&p.until>Date.now())return p.value;let f=null;try{let m=await(await s("/v1/sdk/agent-keys/verify",{key:o})).json();m.valid&&m.agentId&&(f={agentId:m.agentId},m.name&&(f.name=m.name),m.vendor&&(f.vendor=m.vendor));}catch{return p?p.value:null}return u.size>5e3&&u.delete(u.keys().next().value),u.set(o,{value:f,until:Date.now()+l*1e3}),f}}}},Vn=$t,Fn=jt;var V="https://api.agentronics.dev",Yn="https://gateway.agentronics.dev",Xn=e=>{if(e===void 0||e.replace(/\/$/,"")===V||e.replace(/\/$/,"")===Yn)return V;let t;try{t=new URL(e);}catch{throw new Error(`Agentronics SDK: \`gatewayUrl\` is not a valid URL: ${e}`)}if(t.hostname==="localhost"||t.hostname==="127.0.0.1")return e;throw new Error(`Agentronics SDK does not support custom API URLs. Omit \`gatewayUrl\` to use the canonical ${V}. The only accepted override is a localhost / 127.0.0.1 URL for local development. Got: ${e}`)},Gi=e=>{let{publishableKey:t,siteId:n="default",debug:r=false,policies:i=[],trace:s={}}=e,a$1=Xn(e.gatewayUrl),u=classifyApiKey(t);if(u==="secret")throw new AgentronicsError("wrong_key_kind","A secret key was passed to Agentronics.init(). Browser code must use a publishable key (agtx_pk_*).");if(u!=="publishable")throw new AgentronicsError("invalid_api_key",`Agentronics.init() expected a key starting with "${PUBLISHABLE_KEY_PREFIX}".`);let l=s.enabled??true,o=[...r?[me()]:[],...s.gateway?[ge({gatewayUrl:a$1,publishableKey:t})]:[],...s.webhookUrl?[fe({url:s.webhookUrl})]:[],...s.exporters??[]],p={siteId:n,exporters:l?o:[],onExporterError:(c,y)=>{r&&console.warn(`[agentronics] trace exporter "${y.name}" failed`,c);}};s.bufferSize!==void 0&&(p.bufferSize=s.bufferSize),s.traceRate!==void 0&&(p.traceRate=s.traceRate),s.errorRate!==void 0&&(p.errorRate=s.errorRate),s.scrubPaths!==void 0&&(p.scrubPaths=s.scrubPaths);let f=pe(p),m=c=>{l&&f.emit(c);},w=De(),g={onTrace:m};e.auth!==void 0&&(g.context=e.auth),e.compat==="0.6"&&(g.compat="0.6",console.warn("[agentronics] compat: '0.6' is on \u2014 unverified tokens are trusted and review rules run without asking. Remove it once you have upgraded: https://agentronics.dev/docs/guides/upgrade-0-7")),g.onUnverifiedToken=c=>{e.compat!=="0.6"&&console.warn(`[agentronics] A ${c} credential was presented but nothing verifies it, so the agent is 'declared', not 'verified'. Wire auth.verifyToken to your backend: https://agentronics.dev/docs/auth/overview#in-the-browser`);};let d$1=ze(g),v=Je(),h=Ze(i),A=et({gatewayUrl:a$1,siteId:n,publishableKey:t}),M=lt({onTrace:m}),R={onTrace:m};e.siteMemory!==void 0&&(R.initial=e.siteMemory);let k=ut(R),E=pt({gatewayUrl:a$1,siteId:n,publishableKey:t}),F=Ot({gatewayUrl:a$1,siteId:n,publishableKey:t}),b=async c=>{let y=Date.now(),S=await Ee(c),I=w.preferOver(S);return l&&await f.emit({type:I?"agent.detected":"agent.missed",agent:I,durationMs:Date.now()-y,metadata:{detectedClass:S?.class??null,presented:w.snapshot()!==null}}),v.set(I,"detect"),I},T=async(c,y={})=>{let S=Date.now(),I=y.identity!==void 0?y.identity:await b(),P=h.evaluate({tool:c,identity:I});return l&&await f.emit({type:"authz.evaluated",tool:c,agent:I,policy:P,outcome:P.decision==="deny"?"blocked":"success",durationMs:Date.now()-S}),P},B=async()=>true,C=e.review===false?void 0:e.review??(e.compat==="0.6"?B:typeof document>"u"?void 0:Et()),D=ht({evaluate:T,...C?{reviewer:C}:{},setPolicies:c=>h.set(c),listPolicies:()=>h.list(),onTrace:m,identityResolver:()=>v.snapshot().identity});for(let c of e.tools??[])D.register(c);let O=e.progression?xt(e.progression,{onTrace:m}):null,ve=c=>{let y={identity:c};return O&&(y.stage=O.current(),y.enabledStages=O.enabledStages()),y},we={...e.toolDescriptions??{}},Bt=c=>c.map(y=>{let S=we[y.name];return S?{...y,description:S}:y}),$=c=>Bt(At(D.list(),ve(c))),be=c=>{we={...c},j!==null&&(j=null,Y($(v.snapshot().identity)));},j=null,xe=c=>c.map(y=>y.name).sort().join(`
17
+ `),Y=c=>{let y=xe(c);return y===j?null:(j=y,_.publish(c))},Se=c=>{if(!O)return;O.notify(c).changed&&j!==null&&Y($(v.snapshot().identity));},Te={class:"webmcp",trust:"detected",confidence:1,vendor:null,userAgent:typeof navigator<"u"?navigator.userAgent:null,detectionVersion:a,signals:{source:"navigator.modelContext"}},_=Rt({invoke:async(c,y,S)=>{Wt(c.name);let I=v.snapshot().identity??Te,P=await D.execute(c.name,y,I,S?{signal:S}:{});return Se(c.name),P}}),Ae=c=>{let y=v.snapshot().identity;if(y&&y.trust!=="detected"||y?.class==="webmcp")return;let S={...Te,signals:{source:_.source()??"document",tool:c}};v.set(S,"detect"),m({type:"agent.detected",agent:S,metadata:{detectedClass:"webmcp",via:"webmcp-activity"}});},Wt=c=>Ae(c);d(c=>{c.type==="activated"&&Ae(c.toolName);}),v.subscribe(c=>{j===null||!_.available()||Y($(c.identity));});let X=e.visionDetection??e.autoDetect!==false,Nt=X===false||typeof document>"u"?null:Ce({...X===true?{}:X,onDetect:c=>{let y=v.snapshot().identity;y&&(y.trust!=="detected"||y.class==="webmcp")||(v.set(c,"detect"),m({type:"agent.detected",agent:c,metadata:{detectedClass:"screenshot",via:"vision-behaviour"}}));}}),Q=e.autoDetect??true,Gt=Q===false?Promise.resolve(null):(async()=>{let c=Q===true?{}:Q;try{return await b(c)}catch(y){return r&&console.warn("[agentronics] autoDetect failed:",y),null}})();return Object.freeze({publishableKey:t,siteId:n,gatewayUrl:a$1,debug:r,memory:M,siteMemory:k,memoryCache:E,tracer:f,auth:d$1,agentContext:v,authz:h,policyCache:A,tools:D,progression:O,webmcp:_,vision:Nt,ready:Gt,detect:b,authenticate:async c=>{let y=await d$1.authenticate(c);return v.set(y,"authenticate"),y},presentIdentity:c=>{let y=w.present(c);return m({type:"auth.identity_presented",agent:y.identity,metadata:{vendor:y.identity.vendor,class:y.identity.class}}),v.set(y.identity,"declare"),y},clearIdentity:()=>{w.clear(),m({type:"auth.identity_cleared"}),v.set(null,"cleared");},presentedIdentity:()=>w.snapshot(),setPolicies:c=>{h.set(c),m({type:"authz.policies_set",metadata:{count:c.length}});},listPolicies:()=>h.list(),syncPolicies:async()=>{let c=await A.sync();return h.set(c.policies),m({type:"authz.policies_set",metadata:{count:c.policies.length,synced:true}}),c.policies},syncSiteMemory:async()=>{let c=await E.sync();return c.memory&&(k.replace(c.memory),m({type:"memory.updated",metadata:{kind:"site",operation:"sync",etag:c.etag}})),c.memory},syncConfig:async()=>{let c=await fetch(`${a$1.replace(/\/$/,"")}/v1/pub/sites/${encodeURIComponent(n)}/config`,{headers:{authorization:`Bearer ${t}`}});if(!c.ok)throw new Error(`Config sync failed with status ${c.status}.`);let y=await c.json(),S=PolicyRule.array().parse(y.policies??[]);h.set(S),m({type:"authz.policies_set",metadata:{count:S.length,synced:true}});let I=y.siteMemory&&typeof y.siteMemory=="object"&&Object.keys(y.siteMemory).length?k.replace(SiteMemory.parse(y.siteMemory)):null,P=y.toolDescriptions&&typeof y.toolDescriptions=="object"?y.toolDescriptions:{};return be(P),{policies:S,toolDescriptions:P,siteMemory:I}},provideSiteMemory:c=>k.provide(c),provideForPage:c=>{k.provideForPage(c);},installMemoryDelivery:({metaTags:c=true,overlay:y=false}={})=>{let S=[];return c&&S.push(oe({snapshot:k.snapshot()})),y&&S.push(ie({snapshot:k.snapshot()})),{uninstall:()=>{S.forEach(I=>I.uninstall());}}},fetchWellKnown:async c=>{let y={};c!==void 0&&(y.origin=c);let S=await se(y);return S&&(k.replace(S),m({type:"memory.updated",metadata:{kind:"site",operation:"wellKnown",origin:c??null}})),S},installDomEnforcer:()=>nt({policyEngine:h,getIdentity:()=>b({webmcp:{pollMs:0}})}),registerTool:c=>D.register(c),setToolDescriptions:c=>be(c),syncTools:async()=>{let c=D.list({includeDisabled:true}),y=await F.push(c);return m({type:"tool.registered",metadata:{operation:"sync",count:y}}),y},surfaceTools:({identity:c=null}={})=>$(c),explainSurfacing:({identity:c=null}={})=>kt(D.list(),ve(c)),groupedTools:({identity:c=null}={})=>Mt($(c)),estimateTokens:({identity:c=null}={})=>bt($(c)),publishToWebMcp:({identity:c=null}={})=>{let y=$(c);j=xe(y);let S=_.publish(y),I=S.registrations.then(P=>(P.forEach(W=>{m({type:"tool.surfaced",tool:W.name,outcome:W.status==="callable"?"success":"error",...W.error?{error:W.error}:{},metadata:{state:W.status==="callable"?"published":"failed",source:_.source(),trust:c?.trust??null}});}),P));return {revoked:S.revoked,surfaced:y.length,registrations:I}},notifyToolInvoked:c=>Se(c),evaluate:T,traces:()=>f.list(),clearTraces:()=>f.clear(),async ping(){try{let c=await fetch(`${a$1.replace(/\/$/,"")}/v1/pub/health`,{method:"GET",headers:{authorization:`Bearer ${t}`}});if(!c.ok)return {ok:!1,status:c.status,error:`gateway returned ${c.status}`};let y=await c.json().catch(()=>null)??{};return {ok:!0,status:c.status,body:y}}catch(c){return {ok:false,status:0,error:c instanceof Error?c.message:String(c)}}}})};export{Fn as $,oe as A,ie as B,ft as C,se as D,Pn as E,ht as F,vt as G,wt as H,Cn as I,bt as J,xt as K,Tt as L,At as M,kt as N,It as O,Mt as P,Uo as Q,Rt as R,Et as S,ae as T,pe as U,me as V,ge as W,fe as X,$t as Y,jt as Z,Vn as _,Me as a,Gi as aa,G as b,U as c,Re as d,ee as e,Zt as f,en as g,Ee as h,Pe as i,Ce as j,De as k,Mr as l,Le as m,Fe as n,pn as o,ze as p,Je as q,qe as r,Ze as s,et as t,tt as u,nt as v,lt as w,ut as x,pt as y,Mn as z};//# sourceMappingURL=chunk-3WPDIMJP.js.map
18
+ //# sourceMappingURL=chunk-3WPDIMJP.js.map