@agentronics/sdk 0.1.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,190 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for describing the origin of the Work and
141
+ reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may accept and charge a
167
+ fee for the acceptance of support, warranty, indemnity, or other
168
+ liability obligations and/or rights consistent with this License.
169
+ However, in accepting such obligations, You may act only on Your
170
+ own behalf and on Your sole responsibility, not on behalf of any
171
+ other Contributor, and only if You agree to indemnify, defend, and
172
+ hold each Contributor harmless for any liability incurred by, or
173
+ claims asserted against, such Contributor by reason of your accepting
174
+ any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2026 Agentronics
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,121 @@
1
+ # @agentronics/sdk
2
+
3
+ > Browser SDK for the Agentronics governance layer — detection, auth normalization, policy enforcement, site memory, and trace export for every agent class.
4
+
5
+ **Version:** 0.1.0
6
+
7
+ <!-- generated by scripts/sync-readme.ts — edit the MDX in apps/docs/content/docs and re-run `pnpm sync-readme` -->
8
+
9
+ ## Why Agentronics
10
+
11
+ **Agentronics is a universal governance layer for agent-surfable websites.**
12
+
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.
14
+
15
+ Agentronics gives any website seven primitives, behind one SDK:
16
+
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.
24
+
25
+ ## Who this is for
26
+
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.
30
+
31
+ ## What ships in v0.1
32
+
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.
34
+
35
+ Continue to [Getting Started](/docs/getting-started) to install the SDK in under five minutes.
36
+
37
+ ## Getting started
38
+
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.
40
+
41
+ ### Step 1 — Install
42
+
43
+ ```bash
44
+ npm install @agentronics/sdk
45
+ # or: pnpm add @agentronics/sdk
46
+ # or: yarn add @agentronics/sdk
47
+ ```
48
+
49
+ If you only need WebMCP detection and want the smallest possible bundle, import the `lite` entry instead:
50
+
51
+ ```ts
52
+ import { init } from '@agentronics/sdk/lite'
53
+ ```
54
+
55
+ ### Step 2 — Initialize in the browser
56
+
57
+ Call `Agentronics.init` once, as early as possible in your app's client entry. Pass your **publishable** key — never your secret key.
58
+
59
+ ```ts
60
+ import { Agentronics } from '@agentronics/sdk'
61
+
62
+ const client = Agentronics.init({
63
+ publishableKey: process.env.NEXT_PUBLIC_AGENTRONICS_KEY!,
64
+ siteId: 'shop-acme-com',
65
+ trace: { gateway: true },
66
+ })
67
+ ```
68
+
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.
70
+
71
+ ### Step 3 — React: wrap your app
72
+
73
+ If you use React, install the bindings and use the provider:
74
+
75
+ ```bash
76
+ npm install @agentronics/react
77
+ ```
78
+
79
+ ```tsx
80
+ import { AgentronicsProvider } from '@agentronics/react'
81
+
82
+ export default function App({ children }) {
83
+ return (
84
+ <AgentronicsProvider publishableKey={process.env.NEXT_PUBLIC_AGENTRONICS_KEY!}>
85
+ {children}
86
+ </AgentronicsProvider>
87
+ )
88
+ }
89
+ ```
90
+
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`.
101
+
102
+ ### Step 5 — Next
103
+
104
+ Once detection is working, continue to:
105
+
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.
110
+
111
+ Each of those has its own guide in this docs site. Welcome to Agentronics.
112
+
113
+ ## Links
114
+
115
+ - [Documentation](https://docs.agentronics.dev)
116
+ - [Dashboard](https://dashboard.agentronics.dev)
117
+ - [Changelog](https://docs.agentronics.dev/docs/reference/changelog)
118
+
119
+ ## License
120
+
121
+ MIT — © Agentronics.
@@ -0,0 +1,2 @@
1
+ var i=()=>{if(typeof navigator>"u")return null;let e=navigator.modelContext;return e&&typeof e=="object"?e:null},s=async(e={})=>{let{pollMs:n=500}=e,o=Date.now();for(;;){let t=i();if(t)return l(t);if(Date.now()-o>=n)return null;await new Promise(r=>setTimeout(r,50));}},l=e=>({class:"webmcp",trust:"detected",confidence:1,vendor:e.vendor??e.client??null,userAgent:typeof navigator>"u"?null:navigator.userAgent,detectionVersion:"2026.04",signals:{webmcp:true,toolCount:Array.isArray(e.tools)?e.tools.length:0}});export{s as a};//# sourceMappingURL=chunk-5BS4OAQA.js.map
2
+ //# sourceMappingURL=chunk-5BS4OAQA.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/detection/webmcp.ts"],"names":["readModelContext","value","detectWebMcp","options","pollMs","start","ctx","buildIdentity","resolve"],"mappings":"AAQA,IAAMA,CAAAA,CAAmB,IAA+B,CACtD,GAAI,OAAO,SAAA,CAAc,GAAA,CAAa,OAAO,IAAA,CAC7C,IAAMC,CAAAA,CAAS,UAA6D,YAAA,CAC5E,OAAOA,CAAAA,EAAS,OAAOA,CAAAA,EAAU,QAAA,CAAWA,EAAQ,IACtD,CAAA,CAUaC,CAAAA,CAAe,MAC1BC,CAAAA,CAA+B,KACG,CAClC,GAAM,CAAE,MAAA,CAAAC,CAAAA,CAAS,GAAI,EAAID,CAAAA,CACnBE,CAAAA,CAAQ,IAAA,CAAK,GAAA,EAAI,CAEvB,OAAa,CACX,IAAMC,CAAAA,CAAMN,CAAAA,EAAiB,CAC7B,GAAIM,CAAAA,CAAK,OAAOC,CAAAA,CAAcD,CAAG,CAAA,CACjC,GAAI,IAAA,CAAK,GAAA,GAAQD,CAAAA,EAASD,CAAAA,CAAQ,OAAO,IAAA,CACzC,MAAM,IAAI,QAASI,CAAAA,EAAY,UAAA,CAAWA,CAAAA,CAAS,EAAE,CAAC,EACxD,CACF,CAAA,CAEMD,CAAAA,CAAiBD,CAAAA,GAA0C,CAC/D,KAAA,CAAO,QAAA,CACP,MAAO,UAAA,CACP,UAAA,CAAY,CAAA,CACZ,MAAA,CAAQA,CAAAA,CAAI,MAAA,EAAUA,EAAI,MAAA,EAAU,IAAA,CACpC,SAAA,CAAW,OAAO,SAAA,CAAc,GAAA,CAAc,KAAO,SAAA,CAAU,SAAA,CAC/D,gBAAA,CAAkB,SAAA,CAClB,OAAA,CAAS,CACP,OAAQ,IAAA,CACR,SAAA,CAAW,KAAA,CAAM,OAAA,CAAQA,CAAAA,CAAI,KAAK,EAAIA,CAAAA,CAAI,KAAA,CAAM,MAAA,CAAS,CAC3D,CACF,CAAA","file":"chunk-5BS4OAQA.js","sourcesContent":["import type { AgentIdentity } from '@agentronics/protocol'\n\ninterface ModelContextLike {\n client?: string\n vendor?: string\n tools?: unknown[]\n}\n\nconst readModelContext = (): ModelContextLike | null => {\n if (typeof navigator === 'undefined') return null\n const value = (navigator as unknown as { modelContext?: ModelContextLike }).modelContext\n return value && typeof value === 'object' ? value : null\n}\n\nexport interface DetectWebMcpOptions {\n /**\n * Some extensions inject `navigator.modelContext` after first paint. Poll for this many\n * milliseconds before giving up. Set to 0 to read synchronously and return immediately.\n */\n pollMs?: number\n}\n\nexport const detectWebMcp = async (\n options: DetectWebMcpOptions = {}\n): Promise<AgentIdentity | null> => {\n const { pollMs = 500 } = options\n const start = Date.now()\n\n while (true) {\n const ctx = readModelContext()\n if (ctx) return buildIdentity(ctx)\n if (Date.now() - start >= pollMs) return null\n await new Promise((resolve) => setTimeout(resolve, 50))\n }\n}\n\nconst buildIdentity = (ctx: ModelContextLike): AgentIdentity => ({\n class: 'webmcp',\n trust: 'detected',\n confidence: 1,\n vendor: ctx.vendor ?? ctx.client ?? null,\n userAgent: typeof navigator === 'undefined' ? null : navigator.userAgent,\n detectionVersion: '2026.04',\n signals: {\n webmcp: true,\n toolCount: Array.isArray(ctx.tools) ? ctx.tools.length : 0,\n },\n})\n"]}
@@ -0,0 +1,17 @@
1
+ import {a}from'./chunk-5BS4OAQA.js';import {AgentClass,isHigherTrust,IdentityClaim,AgentronicsError,PolicyRule,MemoryEntry,SiteMemory,SITE_MEMORY_DEFAULT,TraceEvent,classifyApiKey,PUBLISHABLE_KEY_PREFIX,TRUST_RANK,SiteMemoryPageContext}from'@agentronics/protocol';var it=[/HeadlessChrome/i,/Headless/i,/PhantomJS/i,/SlimerJS/i],st=()=>({hit:(typeof navigator<"u"&&navigator.webdriver)===true,weight:.6,detail:"navigator.webdriver === true"}),at=()=>{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_*"}`}},ct=()=>{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"}},lt=()=>{if(typeof navigator>"u")return {hit:false,weight:.7};let e=navigator.userAgent??"",t=it.some(r=>r.test(e));return t?{hit:t,weight:.7,detail:`headless UA: ${e}`}:{hit:t,weight:.7}},ut=()=>{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"}},pt=()=>{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"}},dt={webdriver:st,chromedriver:at,headlessUa:lt,languages:ut,permissions:pt,plugins:ct},C=(e={})=>{let{threshold:t=.4}=e,r={},n=0,o=0;for(let[a,s]of Object.entries(dt)){let l=s();n+=l.weight,r[a]={hit:l.hit,weight:l.weight,detail:l.detail},l.hit&&(o+=l.weight);}let i=n===0?0:o/n;return i<t?null:{class:"dom",trust:"detected",confidence:i,vendor:null,userAgent:typeof navigator>"u"?null:navigator.userAgent,detectionVersion:"2026.04",signals:r}};var ae=()=>[{id:"webmcp.model-context",status:"stable",detect:()=>a({pollMs:0})},{id:"dom.automation-heuristics",status:"beta",detect:()=>C()}],U=(e=ae())=>{let t=new Map(e.map(r=>[r.id,r]));return {register(r){t.set(r.id,r);},list(r){let n=[...t.values()];return r?n.filter(o=>o.status===r):n},async detectAll(r=false){for(let n of t.values()){if(n.status==="research"&&!r)continue;let o=await n.detect();if(o)return o}return null}}};var mt=e=>{let t=AgentClass.parse(e.class),r=e.verificationToken?"verified":"declared";return {class:t,trust:r,confidence:1,vendor:e.vendor,userAgent:typeof navigator>"u"?null:navigator.userAgent,detectionVersion:"2026.04",signals:{declared:true,hasVerificationToken:!!e.verificationToken}}};var gt=({gatewayUrl:e,fetcher:t=fetch})=>{let r=null,n=[];return {snapshot(){return [...n]},async sync(){let o=await t(`${e.replace(/\/$/,"")}/v1/detector-signatures`,{headers:r?{"if-none-match":r}:{}});if(o.status===304)return this.snapshot();if(!o.ok)throw new Error(`Detector signature sync failed with status ${o.status}.`);return n=(await o.json()).signatures??[],r=o.headers.get("etag"),this.snapshot()}}};var ce=async(e={})=>{if(e.customDetectors?.length){let t=await U(e.customDetectors).detectAll(!!e.experimental);if(t)return t}if(e.webmcp!==false){let t=await a(e.webmcp??{});if(t)return t}if(e.dom!==false){let t=C(e.dom??{});if(t)return t}return null};var xt=e=>({class:e.class,trust:"declared",confidence:1,vendor:e.vendor,userAgent:typeof navigator>"u"?null:navigator.userAgent,detectionVersion:"2026.04",signals:{declared:true,hasToken:true,tokenExpiresAt:e.expiresAt??null}}),le=()=>{let e=null;return {present(t){let r=IdentityClaim.safeParse(t);if(!r.success)throw new AgentronicsError("invalid_api_key",`Invalid identity claim: ${r.error.issues[0]?.message??"unknown"}`);let n={claim:r.data,identity:xt(r.data)};return e=n,n},clear(){e=null;},preferOver(t){return e?t?isHigherTrust(e.identity.trust,t.trust)?e.identity:t:e.identity:t},snapshot(){return e}}};var vr=({detected:e,declared:t,verified:r,linked:n})=>n?"linked":r?"verified":t?"declared":"detected",pe=e=>{let t=null;for(let r of e)(!t||TRUST_RANK[r.trust]>TRUST_RANK[t.trust])&&(t=r);return t};var de=()=>({name:"bearer",async authenticate(e,t){if(!e.bearerToken)return null;let r=await t.verifyToken?.("bearer",e.bearerToken);return {class:e.classHint??"dom",trust:r?.trust??"verified",confidence:1,vendor:r?.vendor??e.vendorHint??"bearer",userAgent:typeof navigator>"u"?null:navigator.userAgent,detectionVersion:"2026.04",signals:{bearer:true,verifiedRemotely:!!r}}}});var ye=()=>({name:"detection",async authenticate(e){return e.detected??null}});var me=()=>({name:"extensionToken",async authenticate(e,t){if(!e.extensionToken)return null;let r=await t.verifyToken?.("extensionToken",e.extensionToken);return {class:"dom",trust:r?.trust??"verified",confidence:1,vendor:r?.vendor??e.vendorHint??"browser-extension",userAgent:typeof navigator>"u"?null:navigator.userAgent,detectionVersion:"2026.04",signals:{extensionToken:true,verifiedRemotely:!!r}}}});var ge=()=>({name:"oauth2",async authenticate(e,t){if(!e.oauth2AccessToken)return null;let r=await t.verifyToken?.("oauth2",e.oauth2AccessToken);return {class:e.classHint??"webmcp",trust:e.oauth2Subject?"linked":r?.trust??"verified",confidence:1,vendor:r?.vendor??e.vendorHint??"oauth2",userAgent:typeof navigator>"u"?null:navigator.userAgent,detectionVersion:"2026.04",signals:{oauth2:true,subject:e.oauth2Subject??null,verifiedRemotely:!!r}}}});var St=e=>({class:e.class,trust:"declared",confidence:1,vendor:e.vendor,userAgent:typeof navigator>"u"?null:navigator.userAgent,detectionVersion:"2026.04",signals:{declared:true,hasToken:true,tokenExpiresAt:e.expiresAt??null}}),fe=()=>({name:"selfDeclaration",async authenticate(e){return e.declaration?St(IdentityClaim.parse(e.declaration)):null}});var he=()=>({name:"sessionLink",async authenticate(e,t){if(!e.sessionLinkToken)return null;let r=await t.verifyToken?.("sessionLink",e.sessionLinkToken);return {class:e.classHint??"screenshot",trust:e.linkedUserId?"linked":r?.trust??"verified",confidence:1,vendor:r?.vendor??e.vendorHint??"session-link",userAgent:typeof navigator>"u"?null:navigator.userAgent,detectionVersion:"2026.04",signals:{sessionLink:true,linkedUserId:e.linkedUserId??null,verifiedRemotely:!!r}}}});var ve=()=>({name:"xAgentHeader",async authenticate(e){if(!e.xAgentHeader)return null;let[t="x-agent",r="dom",n]=e.xAgentHeader.split(";"),o=AgentClass.safeParse(r);return {class:o.success?o.data:"dom",trust:n?"verified":"declared",confidence:n?1:.8,vendor:t,userAgent:typeof navigator>"u"?null:navigator.userAgent,detectionVersion:"2026.04",signals:{xAgentHeader:true,hasProof:!!n}}}});var Tt=()=>[ye(),fe(),de(),ve(),me(),he(),ge()],xe=({methods:e=Tt(),context:t={},onTrace:r}={})=>({async authenticate(n){let o=[],i={};for(let l of e){let u=await l.authenticate(n,t);i[l.name]=!!u,u&&o.push(u);}let a=pe(o),s={type:a?"auth.identity_presented":"sdk.error",agent:a,outcome:a?"success":"error",metadata:{methods:i}};return a||(s.error="No auth method produced an identity."),r?.(s),a},methods(){return e.map(n=>n.name)}});var At={identity:null,source:"initial",updatedAt:null},we=()=>{let e=At,t=new Set,r=()=>{t.size!==0&&t.forEach(n=>n(e));};return {snapshot(){return e},set(n,o){e={identity:n,source:o,updatedAt:new Date().toISOString()},r();},subscribe(n){return t.add(n),()=>{t.delete(n);}}}};var kt=()=>{let e=new Map;return {read:t=>e.get(t)??null,write:(t,r)=>{e.set(t,r);}}},Mt=()=>typeof window>"u"||!window.localStorage?kt():{read:e=>{try{return window.localStorage.getItem(e)}catch{return null}},write:(e,t)=>{try{window.localStorage.setItem(e,t);}catch{}}},It=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},Se=(e=Mt())=>({consume(t,r,n=Date.now()){let o=`agtx:rate:${t}`,i=It(e.read(o)),a=i&&i.resetAt>n?i.resetAt:n+r.windowSeconds*1e3,s=i&&i.resetAt>n?i.count+1:1;return e.write(o,JSON.stringify({count:s,resetAt:a})),{allowed:s<=r.max,remaining:Math.max(0,r.max-s),resetAt:a}}});var Pt=(e,t)=>e==="*"||e===t?true:e.includes("*")?new RegExp("^"+e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*")+"$").test(t):false,Rt=(e,t)=>{let r=e?TRUST_RANK[e.trust]:-1,n=TRUST_RANK[t.minTrust];return r>=n},Et=(e,t)=>t.allowedClasses.length===0?true:e?t.allowedClasses.includes(e.class):false,Ae="review",Ot=(e,t)=>{let r=t?.class??"unknown",n=t?.vendor??"unknown",o=t?.trust??"none";return `${e}:${r}:${n}:${o}`},ke=(e=[],t={})=>{let r=e.map(o=>PolicyRule.parse(o)),n=t.rateLimiter??Se();return {set(o){r=o.map(i=>PolicyRule.parse(i));},list(){return [...r]},evaluate({tool:o,identity:i}){for(let a of r)if(Pt(a.tool,o)){if(!Rt(i,a))return {decision:"deny",ruleId:a.id,reason:`Rule "${a.id}" requires trust >= ${a.minTrust}.`};if(!Et(i,a))return {decision:"deny",ruleId:a.id,reason:`Rule "${a.id}" restricts to classes: ${a.allowedClasses.join(", ")}.`};if(a.rateLimit){let s=n.consume(Ot(o,i),a.rateLimit);if(!s.allowed)return {decision:"deny",ruleId:a.id,reason:`Rule "${a.id}" rate limit exceeded. Resets at ${new Date(s.resetAt).toISOString()}.`}}return {decision:a.decision,ruleId:a.id,reason:`Matched rule "${a.id}".`}}return {decision:Ae,ruleId:null,reason:`No rule matched tool "${o}". Falling back to "${Ae}".`}}}};var Me=({gatewayUrl:e,siteId:t,publishableKey:r,fetcher:n=fetch})=>{let o={policies:[],etag:null};return {snapshot(){return {policies:[...o.policies],etag:o.etag}},async sync(){let i=await n(`${e.replace(/\/$/,"")}/v1/sites/${encodeURIComponent(t)}/policies`,{headers:{authorization:`Bearer ${r}`,...o.etag?{"if-none-match":o.etag}:{}}});if(i.status===304)return this.snapshot();if(!i.ok)throw new Error(`Policy sync failed with status ${i.status}.`);let a=await i.json();return o={policies:PolicyRule.array().parse(a.policies??[]),etag:i.headers.get("etag")},this.snapshot()}}};var Ie=({message:e="Agent action blocked by site policy.",durationMs:t=2400,documentRef:r=typeof document>"u"?void 0:document}={})=>{if(!r?.body)return null;let n=r.createElement("div");return n.setAttribute("role","status"),n.setAttribute("data-agentronics-deny-overlay","true"),n.textContent=e,Object.assign(n.style,{position:"fixed",zIndex:"2147483647",left:"50%",bottom:"24px",transform:"translateX(-50%)",maxWidth:"min(520px, calc(100vw - 32px))",padding:"12px 16px",borderRadius:"8px",background:"#07091A",color:"#F4F4F5",border:"1px solid #6366F1",boxShadow:"0 20px 48px -16px rgba(7,9,26,0.55)",font:"13px/1.45 'Space Mono', ui-monospace, SFMono-Regular, Menlo, monospace"}),r.body.appendChild(n),window.setTimeout(()=>n.remove(),t),n};var Pe=({policyEngine:e,getIdentity:t,documentRef:r=typeof document>"u"?void 0:document,selector:n="[data-agentronics-tool]"})=>{if(!r)return {uninstall:()=>{}};let o=i=>{let a=i.target instanceof Element?i.target.closest(n):null;if(!(a instanceof HTMLElement))return;let s=a.dataset.agentronicsTool;s&&Promise.resolve(t()).then(l=>{let u=e.evaluate({tool:s,identity:l});u.decision==="deny"&&(i.preventDefault(),i.stopPropagation(),Ie({message:u.reason,documentRef:r}));});};return r.addEventListener("click",o,true),{uninstall:()=>r.removeEventListener("click",o,true)}};var _=()=>{let e=new Map;return {read:t=>e.get(t)??null,write:(t,r)=>{e.set(t,r);},remove:t=>{e.delete(t);},keys:()=>[...e.keys()]}},Re=(e,t)=>({read:r=>{try{return e.getItem(t+r)}catch{return null}},write:(r,n)=>{try{e.setItem(t+r,n);}catch{}},remove:r=>{try{e.removeItem(t+r);}catch{}},keys:()=>{let r=[];try{for(let n=0;n<e.length;n++){let o=e.key(n);o&&o.startsWith(t)&&r.push(o.slice(t.length));}}catch{}return r}}),Ee="agtx:",Oe=()=>{let e=typeof window<"u",t=e&&typeof window.sessionStorage<"u"?Re(window.sessionStorage,Ee+"session:"):_(),r=e&&typeof window.localStorage<"u"?Re(window.localStorage,Ee+"user:"):_();return {session:t,user:r,org:_()}};var De=(e,t)=>e.expiresAt!==null&&e.expiresAt<=t,Le=e=>{if(!e)return null;try{let t=JSON.parse(e);return typeof t!="object"||t===null?null:t}catch{return null}},Dt=e=>JSON.stringify(e),$e=(e={})=>{let t=Oe(),r=l=>{e.onTrace?.(l);};return {get:(l,u={})=>{let p=u.scope??"session",g=t[p],m=Le(g.read(l));if(!m){r({type:"memory.accessed",metadata:{operation:"get",key:l,scope:p,hit:false}});return}if(De(m,Date.now())){g.remove(l),r({type:"memory.accessed",metadata:{operation:"get",key:l,scope:p,hit:false,expired:true}});return}return r({type:"memory.accessed",metadata:{operation:"get",key:l,scope:p,hit:true}}),m.value},set:(l,u,p={})=>{let g=p.scope??"session",m=p.ttlSeconds??null,v=Date.now(),w={value:u,expiresAt:m===null?null:v+m*1e3,updatedAt:new Date(v).toISOString()};return t[g].write(l,Dt(w)),r({type:"memory.updated",metadata:{operation:"set",key:l,scope:g,ttlSeconds:m}}),MemoryEntry.parse({key:l,value:u,scope:g,ttlSeconds:m,updatedAt:w.updatedAt})},remove:(l,u={})=>{let p=u.scope??"session";t[p].remove(l),r({type:"memory.updated",metadata:{operation:"remove",key:l,scope:p}});},list:(l={})=>{let u=l.scope??"session",p=t[u],g=Date.now(),m=[];for(let v of p.keys()){let w=Le(p.read(v));if(w){if(De(w,g)){p.remove(v);continue}m.push(MemoryEntry.parse({key:v,value:w.value,scope:u,ttlSeconds:w.expiresAt===null?null:Math.max(0,Math.round((w.expiresAt-g)/1e3)),updatedAt:w.updatedAt}));}}return r({type:"memory.accessed",metadata:{operation:"list",scope:u,count:m.length}}),m},clear:(l={})=>{let u=l.scope??"session",p=t[u],g=p.keys().length;for(let m of p.keys())p.remove(m);r({type:"memory.updated",metadata:{operation:"clear",scope:u,count:g}});}}};var N=e=>SiteMemory.parse(JSON.parse(JSON.stringify(e))),L=e=>({...e,updatedAt:new Date().toISOString()}),We=(e={})=>{let t=SiteMemory.parse({...SITE_MEMORY_DEFAULT,...e.initial??{}}),r=null,n=new Set,o=d=>{e.onTrace?.(d);},i=()=>{r=null;},a=()=>{if(n.size===0)return;let d=N(t);r=d,n.forEach(f=>f(d));},s=d=>{let f=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=L(f),i(),o({type:"memory.updated",metadata:{kind:"site",operation:"provide",keys:Object.keys(d)}}),a(),p()},l=(d,f)=>{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)),k=A;for(let M=0;M<h.length-1;M++){let b=h[M],I=k[b];(typeof I!="object"||I===null||Array.isArray(I))&&(k[b]={}),k=k[b];}return k[h[h.length-1]]=f,t=L(SiteMemory.parse(A)),i(),o({type:"memory.updated",metadata:{kind:"site",operation:"update",path:d}}),a(),p()},u=d=>{let f=SiteMemoryPageContext.parse({path:d.path,payload:d.payload,updatedAt:new Date().toISOString()});return t=L({...t,pageContexts:{...t.pageContexts,[d.path]:f}}),i(),o({type:"memory.updated",metadata:{kind:"site",operation:"provideForPage",path:d.path}}),a(),{...f,payload:{...f.payload}}},p=()=>(r||(r=N(t)),r);return {provide:s,update:l,provideForPage:u,snapshot:p,get:d=>{if(o({type:"memory.accessed",metadata:{kind:"site",operation:d?"get":"snapshot",path:d??null}}),!d)return N(t);let f=d.split(".").filter(Boolean),h=t;for(let A of f){if(typeof h!="object"||h===null)return;h=h[A];}return h},getForPage:d=>{o({type:"memory.accessed",metadata:{kind:"site",operation:"getForPage",path:d}});let f=t.pageContexts[d];return f?{...f,payload:{...f.payload}}:null},replace:d=>(t=L(SiteMemory.parse(d)),i(),a(),p()),subscribe:d=>(n.add(d),()=>{n.delete(d);})}};var Ge=({gatewayUrl:e,siteId:t,publishableKey:r,fetcher:n=fetch})=>{let o={memory:null,etag:null};return {snapshot(){return {memory:o.memory?SiteMemory.parse(o.memory):null,etag:o.etag}},async sync(){let i=await n(`${e.replace(/\/$/,"")}/v1/sites/${encodeURIComponent(t)}/memory`,{headers:{authorization:`Bearer ${r}`,...o.etag?{"if-none-match":o.etag}:{}}});if(i.status===304)return this.snapshot();if(!i.ok)throw new Error(`Memory sync failed with status ${i.status}.`);let a=await i.json();return o={memory:SiteMemory.parse(a.memory??{}),etag:i.headers.get("etag")},this.snapshot()}}};var Wt=({toolName:e="getSiteContext",description:t="Returns Agentronics site memory: page map, workflows, policies, UI guidance.",getSnapshot:r,onAccess:n})=>({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(o={}){let i=r(),a=o.path??null;if(n?.(a),!a)return {content:i};let s=a.split(".").filter(Boolean),l=i;for(let u of s){if(typeof l!="object"||l===null)return {content:void 0};l=l[u];}return {content:l}}});var T="agent-context-",K="agentronics-site-context",jt=e=>{try{return JSON.stringify(e)}catch{return "{}"}},$=(e,t,r)=>{let n=e.querySelector(`meta[name="${t}"]`);n||(n=e.createElement("meta"),n.setAttribute("name",t),e.head.appendChild(n)),n.setAttribute("content",r);},W=(e,t)=>{e.querySelectorAll(`meta[name="${t}"]`).forEach(r=>r.remove());},F=({doc:e=typeof document>"u"?null:document,snapshot:t,schemaType:r="WebSite"})=>{if(!e)return {uninstall:()=>{}};$(e,`${T}version`,t.version),$(e,`${T}updated-at`,t.updatedAt??new Date().toISOString()),t.siteMap?.navigation?.flow&&$(e,`${T}flow`,t.siteMap.navigation.flow),$(e,`${T}workflows`,Object.keys(t.workflows).join(","));let n=e.getElementById(K);return n||(n=e.createElement("script"),n.type="application/ld+json",n.id=K,e.head.appendChild(n)),n.textContent=jt({"@context":"https://schema.org","@type":r,name:"Agentronics Site Memory",agentronics:t}),{uninstall:()=>{W(e,`${T}version`),W(e,`${T}updated-at`),W(e,`${T}flow`),W(e,`${T}workflows`),e.getElementById(K)?.remove();}}};var Be="agentronics-memory-overlay",Gt=e=>`
2
+ position: fixed;
3
+ bottom: 16px;
4
+ right: 16px;
5
+ max-width: 320px;
6
+ padding: 10px 12px;
7
+ background: rgba(17, 24, 39, 0.92);
8
+ color: #f9fafb;
9
+ font: 12px/1.45 ui-monospace, SFMono-Regular, Menlo, monospace;
10
+ border-radius: 8px;
11
+ z-index: 2147483647;
12
+ opacity: ${e?"0":"1"};
13
+ pointer-events: ${e?"none":"auto"};
14
+ box-shadow: 0 12px 32px rgba(15, 23, 42, 0.35);
15
+ `,Ue=e=>{let t=e.siteMap?.pages?.length??0,r=Object.keys(e.workflows).length,n=Object.keys(e.uiGuidance).length;return `Agentronics site memory \xB7 pages:${t} \xB7 workflows:${r} \xB7 ui-hints:${n}`},H=({doc:e=typeof document>"u"?null:document,snapshot:t,hidden:r=false})=>{if(!e)return {uninstall:()=>{},refresh:()=>{}};let n=e.getElementById(Be);return n||(n=e.createElement("div"),n.id=Be,n.setAttribute("role","note"),n.setAttribute("aria-label","Agentronics site memory summary"),n.setAttribute("data-agent-context","overlay"),e.body.appendChild(n)),n.setAttribute("style",Gt(r)),n.textContent=Ue(t),{uninstall:()=>{n?.remove();},refresh:o=>{n&&(n.textContent=Ue(o));}}};var Ne="/.well-known/agent-context.json",z=async({origin:e,fetcher:t=fetch,signal:r}={})=>{let n=(e?e.replace(/\/$/,""):typeof window<"u"?window.location.origin:"")+Ne;if(!n.startsWith("http"))return null;let o={headers:{accept:"application/json"}};r!==void 0&&(o.signal=r);let i=await t(n,o);if(!i.ok){if(i.status===404)return null;throw new Error(`well-known agent-context fetch failed with status ${i.status}.`)}let a=await i.json();return SiteMemory.parse(a)},Bt=({snapshot:e})=>JSON.stringify(SiteMemory.parse(e));var Ke=({evaluate:e,setPolicies:t,listPolicies:r,onTrace:n})=>{let o=new Map,i=new Set,a=s=>{if(!s.authz||!t||!r)return;let l={id:`tool:${s.name}`,tool:s.name,...s.authz,rateLimit:s.rateLimit??s.authz.rateLimit};t([...r().filter(u=>u.id!==l.id),l]);};return {register(s){return o.set(s.name,s),i.delete(s.name),a(s),n?.({type:"tool.registered",tool:s.name,metadata:{version:s.version??null,group:s.group??null,stage:s.stage??null}}),()=>{o.delete(s.name),i.delete(s.name);}},unregister(s){o.delete(s),i.delete(s);},enable(s){!o.has(s)||!i.has(s)||(i.delete(s),n?.({type:"tool.surfaced",tool:s,metadata:{state:"enabled"}}));},disable(s){!o.has(s)||i.has(s)||(i.add(s),n?.({type:"tool.surfaced",tool:s,metadata:{state:"disabled"}}));},isEnabled:s=>o.has(s)&&!i.has(s),list({includeDisabled:s=false}={}){let l=[...o.values()];return s?l:l.filter(u=>!i.has(u.name))},get:s=>o.get(s),async execute(s,l,u=null){let p=o.get(s);if(!p)throw new Error(`Tool "${s}" is not registered.`);if(i.has(s)){let v={decision:"deny",ruleId:`tool:${s}`,reason:"Tool is disabled."};throw n?.({type:"tool.executed",tool:s,agent:u,policy:v,outcome:"blocked"}),new Error(v.reason)}let g=await e(s,{identity:u});if(g.decision==="deny")throw n?.({type:"tool.executed",tool:s,agent:u,policy:g,outcome:"blocked"}),new Error(g.reason);let m=await p.execute(l,{identity:u});return n?.({type:"tool.executed",tool:s,agent:u,policy:g,outcome:"success"}),m}}};var Fe=(e,t={})=>{let r=new Map;for(let a of e.stages)r.set(a.name,a);if(!r.has(e.initial))throw new Error(`Initial stage "${e.initial}" is not declared in progression stages.`);let n=e.initial,o=()=>{let a=r.get(n);return a?.enables?[n,...a.enables]:[n]},i=(a,s)=>{let l=n;if(!r.has(a))throw new Error(`Cannot transition to unknown stage "${a}".`);return a===n?{changed:false,from:l,to:a}:(n=a,t.onTrace?.({type:"tool.progressed",metadata:{from:l,to:a,trigger:s}}),{changed:true,from:l,to:a})};return {current:()=>n,enabledStages:()=>o(),notify(a){let l=r.get(n)?.transitions?.find(u=>u.on===a);return l?i(l.to,a):{changed:false,from:n,to:n}},set(a){return i(a,"manual")},reset(){let a=n;n=e.initial,a!==n&&t.onTrace?.({type:"tool.progressed",metadata:{from:a,to:n,trigger:"reset"}});},snapshot:()=>({current:n,enabled:o()})}};var Ut=(e,t)=>{let r=e.authz?.minTrust;return r?t?TRUST_RANK[t.trust]<TRUST_RANK[r]?{ok:false,reason:`trust-too-low:${t.trust}<${r}`}:{ok:true,reason:"trust-ok"}:{ok:false,reason:`requires-trust:${r}`}:{ok:true,reason:"no-trust-floor"}},_t=(e,t)=>{let r=e.authz?.allowedClasses??[];return r.length===0?{ok:true,reason:"no-class-restriction"}:t?r.includes(t.class)?{ok:true,reason:"class-ok"}:{ok:false,reason:`class-not-allowed:${t.class}`}:{ok:false,reason:`requires-class:${r.join("|")}`}},Nt=(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"},ze=(e,t)=>{let r=Ut(e,t.identity);if(!r.ok)return {tool:e,visible:false,reason:r.reason};let n=_t(e,t.identity);if(!n.ok)return {tool:e,visible:false,reason:n.reason};let o=Nt(e,t);return o.ok?e.authz?.decision==="deny"?{tool:e,visible:false,reason:"authz-deny"}:{tool:e,visible:true,reason:"visible"}:{tool:e,visible:false,reason:o.reason}},Je=(e,t)=>e.filter(r=>ze(r,t).visible),Ve=(e,t)=>e.map(r=>ze(r,t));var qe="default",Xe=e=>{let t=new Map;for(let r of e){let n=r.group??qe,o=t.get(n)??[];o.push(r),t.set(n,o);}return [...t.entries()].sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>({name:r,tools:n}))},hn=e=>[...new Set(e.map(t=>t.group??qe))].sort();var J=e=>e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(J).join(",")}]`:`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${J(e[r])}`).join(",")}}`,Kt=e=>{let t={name:e.name,version:e.version??null,group:e.group??null,description:e.description??null,inputSchema:e.inputSchema??null,authz:e.authz??null,rateLimit:e.rateLimit??null},r=J(t).length;return {name:e.name,characters:r,tokens:Math.ceil(r/4)}},Ye=e=>{let t=e.map(Kt);return {total:t.reduce((n,o)=>n+o.tokens,0),perTool:t}};var Qe=e=>e.provider?e.provider:(e.doc?.defaultView??(typeof globalThis<"u"?globalThis:null))?.navigator?.modelContext??null,Ft=(e,t)=>{let r={name:e.name,invoke:n=>t(e,n)};return e.description!==void 0&&(r.description=e.description),e.inputSchema!==void 0&&(r.inputSchema=e.inputSchema),r},Ze=(e={})=>{let t=e.invoke??(async(n,o)=>n.execute(o,{identity:null})),r=null;return {publish(n){let o=Qe(e);return o?(r?.revoke(),r=o.provideContext({tools:n.map(i=>Ft(i,t))}),{revoked:true}):{revoked:false}},revoke(){r?.revoke(),r=null;},available:()=>!!Qe(e)}};var V=(e=500)=>{let t=[];return {add(r){t.push(r),t.length>e&&t.splice(0,t.length-e);},list(){return [...t]},clear(){t.length=0;}}};var et=(e,t)=>e===void 0?t:Math.max(0,Math.min(1,e)),q=(e={})=>{let t=et(e.traceRate,1),r=et(e.errorRate,1),n=e.random??Math.random;return {shouldKeep(o){let i=o.outcome==="error"?r:t;return n()<i}}};var Ht="[REDACTED]",zt=e=>{if(e!==void 0)return JSON.parse(JSON.stringify(e))},X=(e,t)=>{if(t.length===0||typeof e!="object"||e===null)return;let[r,...n]=t;if(!r)return;if(Array.isArray(e)){for(let i of e)X(i,t);return}let o=e;if(r in o){if(n.length===0){o[r]=Ht;return}X(o[r],n);}},Y=(e,t=[])=>{if(t.length===0)return e;let r=zt(e);for(let n of t)X(r,n.split(".").filter(Boolean));return r},Q=["metadata.password","metadata.token","metadata.authorization","metadata.cookie"];var tt=e=>{let t=globalThis.crypto;return t&&"randomUUID"in t?`${e}_${t.randomUUID()}`:`${e}_${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`},Z=({siteId:e,bufferSize:t,sessionId:r=tt("ses"),scrubPaths:n=Q,exporters:o=[],onExporterError:i,...a})=>{let s=V(t),l=q(a);return {sessionId:r,async emit(u){let p=TraceEvent.parse(Y({id:tt("trc"),siteId:e,sessionId:r,occurredAt:new Date().toISOString(),outcome:u.outcome??"success",metadata:{},...u},n));return l.shouldKeep(p)?(s.add(p),await Promise.all(o.map(async g=>{try{await g.export([p]);}catch(m){i?.(m,g,p);}})),p):null},list:()=>s.list(),clear:()=>s.clear()}};var ee=()=>({name:"console",export(e){for(let t of e)console.info("[agentronics:trace]",t.type,t);}});var te=({gatewayUrl:e,publishableKey:t,fetcher:r=fetch})=>({name:"gateway",async export(n){let o={publishableKey:t,events:n};await r(`${e.replace(/\/$/,"")}/v1/traces`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${t}`},body:JSON.stringify(o)});}});var Vt=e=>new Promise(t=>setTimeout(t,e)),ne=({url:e,fetcher:t=fetch,maxRetries:r=2,queueLimit:n=500})=>({name:"webhook",async export(o){let a=[...qt(e),...o].slice(-n),s=0;for(;;){let l=await t(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({events:a})});if(l.ok){rt(e,[]);return}if(s>=r)throw rt(e,a),new Error(`Webhook exporter failed with status ${l.status}.`);s+=1,await Vt(100*s);}}}),re=e=>`agtx:webhook:${e}`,qt=e=>{if(typeof window>"u"||!window.localStorage)return [];try{let t=window.localStorage.getItem(re(e));return t?JSON.parse(t):[]}catch{return []}},rt=(e,t)=>{if(!(typeof window>"u"||!window.localStorage))try{if(t.length===0){window.localStorage.removeItem(re(e));return}window.localStorage.setItem(re(e),JSON.stringify(t));}catch{}};var ot="https://gateway.agentronics.dev",Qt=e=>{if(e===void 0)return ot;if(e===ot)return e;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 gateway URLs. Omit \`gatewayUrl\` to use the canonical https://gateway.agentronics.dev. The only accepted override is a localhost / 127.0.0.1 URL for local development. Got: ${e}`)},io=e=>{let{publishableKey:t,siteId:r="default",debug:n=false,policies:o=[],trace:i={}}=e,a=Qt(e.gatewayUrl),s=classifyApiKey(t);if(s==="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(s!=="publishable")throw new AgentronicsError("invalid_api_key",`Agentronics.init() expected a key starting with "${PUBLISHABLE_KEY_PREFIX}".`);let l=i.enabled??true,u=[...n?[ee()]:[],...i.gateway?[te({gatewayUrl:a,publishableKey:t})]:[],...i.webhookUrl?[ne({url:i.webhookUrl})]:[],...i.exporters??[]],p={siteId:r,exporters:l?u:[],onExporterError:(c,y)=>{n&&console.warn(`[agentronics] trace exporter "${y.name}" failed`,c);}};i.bufferSize!==void 0&&(p.bufferSize=i.bufferSize),i.traceRate!==void 0&&(p.traceRate=i.traceRate),i.errorRate!==void 0&&(p.errorRate=i.errorRate),i.scrubPaths!==void 0&&(p.scrubPaths=i.scrubPaths);let g=Z(p),m=c=>{l&&g.emit(c);},v=le(),w={onTrace:m};e.auth!==void 0&&(w.context=e.auth);let d=xe(w),f=we(),h=ke(o),A=Me({gatewayUrl:a,siteId:r,publishableKey:t}),k=$e({onTrace:m}),M={onTrace:m};e.siteMemory!==void 0&&(M.initial=e.siteMemory);let b=We(M),I=Ge({gatewayUrl:a,siteId:r,publishableKey:t}),j=async c=>{let y=Date.now(),x=await ce(c),S=v.preferOver(x);return l&&await g.emit({type:S?"agent.detected":"agent.missed",agent:S,durationMs:Date.now()-y,metadata:{detectedClass:x?.class??null,presented:v.snapshot()!==null}}),f.set(S,"detect"),S},oe=async(c,y={})=>{let x=Date.now(),S=y.identity!==void 0?y.identity:await j(),B=h.evaluate({tool:c,identity:S});return l&&await g.emit({type:"authz.evaluated",tool:c,agent:S,policy:B,outcome:B.decision==="deny"?"blocked":"success",durationMs:Date.now()-x}),B},P=Ke({evaluate:oe,setPolicies:c=>h.set(c),listPolicies:()=>h.list(),onTrace:m});for(let c of e.tools??[])P.register(c);let R=e.progression?Fe(e.progression,{onTrace:m}):null,ie=c=>{let y={identity:c};return R&&(y.stage=R.current(),y.enabledStages=R.enabledStages()),y},E=c=>Je(P.list(),ie(c)),se=c=>{if(!R)return;R.notify(c).changed&&G.publish(E(null));},G=Ze({invoke:async(c,y)=>{let x=await P.execute(c.name,y,null);return se(c.name),x}});return Object.freeze({publishableKey:t,siteId:r,gatewayUrl:a,debug:n,memory:k,siteMemory:b,memoryCache:I,tracer:g,auth:d,agentContext:f,authz:h,policyCache:A,tools:P,progression:R,webmcp:G,detect:j,authenticate:async c=>{let y=await d.authenticate(c);return f.set(y,"authenticate"),y},presentIdentity:c=>{let y=v.present(c);return m({type:"auth.identity_presented",agent:y.identity,metadata:{vendor:y.identity.vendor,class:y.identity.class}}),f.set(y.identity,"declare"),y},clearIdentity:()=>{v.clear(),m({type:"auth.identity_cleared"}),f.set(null,"cleared");},presentedIdentity:()=>v.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 I.sync();return c.memory&&(b.replace(c.memory),m({type:"memory.updated",metadata:{kind:"site",operation:"sync",etag:c.etag}})),c.memory},provideSiteMemory:c=>b.provide(c),provideForPage:c=>{b.provideForPage(c);},installMemoryDelivery:({metaTags:c=true,overlay:y=false}={})=>{let x=[];return c&&x.push(F({snapshot:b.snapshot()})),y&&x.push(H({snapshot:b.snapshot()})),{uninstall:()=>{x.forEach(S=>S.uninstall());}}},fetchWellKnown:async c=>{let y={};c!==void 0&&(y.origin=c);let x=await z(y);return x&&(b.replace(x),m({type:"memory.updated",metadata:{kind:"site",operation:"wellKnown",origin:c??null}})),x},installDomEnforcer:()=>Pe({policyEngine:h,getIdentity:()=>j({webmcp:{pollMs:0}})}),registerTool:c=>P.register(c),surfaceTools:({identity:c=null}={})=>E(c),explainSurfacing:({identity:c=null}={})=>Ve(P.list(),ie(c)),groupedTools:({identity:c=null}={})=>Xe(E(c)),estimateTokens:({identity:c=null}={})=>Ye(E(c)),publishToWebMcp:({identity:c=null}={})=>{let y=E(c),x=G.publish(y);return y.forEach(S=>{m({type:"tool.surfaced",tool:S.name,metadata:{state:"published",trust:c?.trust??null,group:S.group??null}});}),{revoked:x.revoked,surfaced:y.length}},notifyToolInvoked:c=>se(c),evaluate:oe,traces:()=>g.list(),clearTraces:()=>g.clear(),async ping(){try{let c=await fetch(`${a.replace(/\/$/,"")}/v1/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)}}}})};
16
+ export{Fe as A,ze as B,Je as C,Ve as D,qe as E,Xe as F,hn as G,Kt as H,Ye as I,Ze as J,V as K,Z as L,ee as M,te as N,ne as O,io as P,C as a,ae as b,U as c,mt as d,gt as e,ce as f,le as g,vr as h,pe as i,xe as j,we as k,Se as l,ke as m,Me as n,Ie as o,Pe as p,$e as q,We as r,Ge as s,Wt as t,F as u,H as v,Ne as w,z as x,Bt as y,Ke as z};//# sourceMappingURL=chunk-DKDVADEU.js.map
17
+ //# sourceMappingURL=chunk-DKDVADEU.js.map