@agentronics/sdk 0.1.2 → 0.2.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/README.md +12 -0
- package/dist/chunk-7CJGV4LL.js +17 -0
- package/dist/chunk-7CJGV4LL.js.map +1 -0
- package/dist/chunk-LLD3Y2LZ.js +2 -0
- package/dist/chunk-LLD3Y2LZ.js.map +1 -0
- package/dist/index.cjs +3 -3
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.global.js +3 -3
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +1 -1
- package/dist/{init-only-CsMtI9lh.d.ts → init-only-4Tr5Ju9g.d.ts} +37 -1
- package/dist/{init-only-CH7e1rAO.d.cts → init-only-Czh_F-Dk.d.cts} +37 -1
- package/dist/init-only.cjs +3 -3
- package/dist/init-only.cjs.map +1 -1
- package/dist/init-only.d.cts +1 -1
- package/dist/init-only.d.ts +1 -1
- package/dist/init-only.global.js +3 -3
- package/dist/init-only.global.js.map +1 -1
- package/dist/init-only.js +1 -1
- package/dist/lite.cjs +1 -1
- package/dist/lite.cjs.map +1 -1
- package/dist/lite.global.js +1 -1
- package/dist/lite.global.js.map +1 -1
- package/dist/lite.js +1 -1
- package/package.json +4 -4
- package/dist/chunk-5BS4OAQA.js +0 -2
- package/dist/chunk-5BS4OAQA.js.map +0 -1
- package/dist/chunk-VWQY7QIL.js +0 -17
- package/dist/chunk-VWQY7QIL.js.map +0 -1
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {f,d,P}from'./chunk-
|
|
1
|
+
import {f,d,P}from'./chunk-7CJGV4LL.js';export{E as DEFAULT_GROUP,w as WELL_KNOWN_PATH,b as bundledDetectors,k as createAgentContextStore,j as createAuthEngine,M as createConsoleExporter,c as createDetectorRegistry,N as createGatewayExporter,g as createIdentityStore,s as createMemoryCache,q as createMemoryStore,n as createPolicyCache,m as createPolicyEngine,A as createProgressionStore,l as createRateLimiter,e as createSignatureLoader,r as createSiteMemoryStore,z as createToolRegistry,K as createTraceBuffer,L as createTracer,J as createWebMcpAdapter,t as createWebMcpContextTool,O as createWebhookExporter,B as decideSurfacing,d as declareAgent,h as deriveTrustLevel,f as detectAgent,a as detectDom,I as estimateBudget,H as estimateToolTokens,D as explainSurfacing,x as fetchWellKnownContext,F as groupTools,i as highestTrust,P as init,p as installDomEnforcer,v as installMemoryOverlay,u as installMetaTags,G as listGroupNames,y as serializeWellKnownContext,o as showDenyOverlay,C as surfaceTools}from'./chunk-7CJGV4LL.js';export{b as detectWebMcp}from'./chunk-LLD3Y2LZ.js';var me={init:P,declareAgent:d,detectAgent:f},ge="0.1.0";export{me as Agentronics,ge as VERSION};//# sourceMappingURL=index.js.map
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
|
@@ -270,6 +270,7 @@ interface GovernedTool<Input = unknown, Output = unknown> {
|
|
|
270
270
|
group?: string;
|
|
271
271
|
description?: string;
|
|
272
272
|
inputSchema?: Record<string, unknown>;
|
|
273
|
+
outputSchema?: Record<string, unknown>;
|
|
273
274
|
stage?: string;
|
|
274
275
|
authz?: Omit<PolicyRule, 'id' | 'tool'>;
|
|
275
276
|
rateLimit?: PolicyRule['rateLimit'];
|
|
@@ -284,6 +285,18 @@ interface ToolRegistryOptions {
|
|
|
284
285
|
setPolicies?: (rules: PolicyRule[]) => void;
|
|
285
286
|
listPolicies?: () => PolicyRule[];
|
|
286
287
|
onTrace?: (input: TraceInput) => void;
|
|
288
|
+
/**
|
|
289
|
+
* Resolves the ambient agent identity for `execute()` calls that don't pass
|
|
290
|
+
* one explicitly. The SDK wires this to the agentContext snapshot so a
|
|
291
|
+
* button-bound tool fires with the detected agent attached — without
|
|
292
|
+
* forcing every consumer to thread identity through their click handlers.
|
|
293
|
+
*
|
|
294
|
+
* Semantics:
|
|
295
|
+
* - `execute(name, input)` or `execute(name, input, undefined)` → resolver
|
|
296
|
+
* - `execute(name, input, null)` → respected (caller wants anonymous attribution)
|
|
297
|
+
* - `execute(name, input, identity)` → respected
|
|
298
|
+
*/
|
|
299
|
+
identityResolver?: () => AgentIdentity | null;
|
|
287
300
|
}
|
|
288
301
|
interface ToolRegistry {
|
|
289
302
|
register(tool: GovernedTool): () => void;
|
|
@@ -297,7 +310,7 @@ interface ToolRegistry {
|
|
|
297
310
|
get(name: string): GovernedTool | undefined;
|
|
298
311
|
execute<Input, Output>(name: string, input: Input, identity?: AgentIdentity | null): Promise<Output>;
|
|
299
312
|
}
|
|
300
|
-
declare const createToolRegistry: ({ evaluate, setPolicies, listPolicies, onTrace, }: ToolRegistryOptions) => ToolRegistry;
|
|
313
|
+
declare const createToolRegistry: ({ evaluate, setPolicies, listPolicies, onTrace, identityResolver, }: ToolRegistryOptions) => ToolRegistry;
|
|
301
314
|
|
|
302
315
|
interface ProgressionTransition {
|
|
303
316
|
on: string;
|
|
@@ -425,6 +438,19 @@ interface InitOptions {
|
|
|
425
438
|
auth?: AuthContext;
|
|
426
439
|
progression?: ProgressionConfig;
|
|
427
440
|
tools?: GovernedTool[];
|
|
441
|
+
/**
|
|
442
|
+
* Run agent detection automatically on init and keep the resulting
|
|
443
|
+
* identity in agentContext so every subsequent tools.execute() call gets
|
|
444
|
+
* attributed without the host page passing identity through. Default
|
|
445
|
+
* `true` — opt out with `false` for privacy-mode hosts, or pass
|
|
446
|
+
* DetectAgentOptions to tune the detectors (e.g. raise the DOM threshold).
|
|
447
|
+
*
|
|
448
|
+
* The first detection cycle runs synchronously where possible (DOM
|
|
449
|
+
* heuristics) and continues asynchronously for WebMCP polling, so very
|
|
450
|
+
* early click handlers may see identity=null for a single frame; the
|
|
451
|
+
* `ready` promise on the returned client resolves once the cycle finishes.
|
|
452
|
+
*/
|
|
453
|
+
autoDetect?: boolean | DetectAgentOptions;
|
|
428
454
|
trace?: {
|
|
429
455
|
enabled?: boolean;
|
|
430
456
|
bufferSize?: number;
|
|
@@ -452,6 +478,13 @@ interface AgentronicsClient {
|
|
|
452
478
|
readonly tools: ToolRegistry;
|
|
453
479
|
readonly progression: ProgressionStore | null;
|
|
454
480
|
readonly webmcp: WebMcpAdapter;
|
|
481
|
+
/**
|
|
482
|
+
* Resolves once the initial autoDetect cycle finishes. Rejects only if the
|
|
483
|
+
* autoDetect configuration itself is invalid; detection failures resolve to
|
|
484
|
+
* `null` (treated as "human or undetectable agent"). When `autoDetect` was
|
|
485
|
+
* disabled the promise resolves immediately to `null`.
|
|
486
|
+
*/
|
|
487
|
+
readonly ready: Promise<AgentIdentity | null>;
|
|
455
488
|
detect(options?: DetectAgentOptions): Promise<AgentIdentity | null>;
|
|
456
489
|
authenticate(input: AuthInput): Promise<AgentIdentity | null>;
|
|
457
490
|
presentIdentity(input: PresentIdentityOptions): PresentedIdentity;
|
|
@@ -477,6 +510,9 @@ interface AgentronicsClient {
|
|
|
477
510
|
uninstall: () => void;
|
|
478
511
|
};
|
|
479
512
|
registerTool(tool: GovernedTool): () => void;
|
|
513
|
+
/** Push the full tool registry to the gateway so the dashboard can render
|
|
514
|
+
* the page-wise view (schemas, per-tool tokens, context fullness). */
|
|
515
|
+
syncTools(): Promise<number>;
|
|
480
516
|
surfaceTools(options?: {
|
|
481
517
|
identity?: AgentIdentity | null;
|
|
482
518
|
}): GovernedTool[];
|
|
@@ -270,6 +270,7 @@ interface GovernedTool<Input = unknown, Output = unknown> {
|
|
|
270
270
|
group?: string;
|
|
271
271
|
description?: string;
|
|
272
272
|
inputSchema?: Record<string, unknown>;
|
|
273
|
+
outputSchema?: Record<string, unknown>;
|
|
273
274
|
stage?: string;
|
|
274
275
|
authz?: Omit<PolicyRule, 'id' | 'tool'>;
|
|
275
276
|
rateLimit?: PolicyRule['rateLimit'];
|
|
@@ -284,6 +285,18 @@ interface ToolRegistryOptions {
|
|
|
284
285
|
setPolicies?: (rules: PolicyRule[]) => void;
|
|
285
286
|
listPolicies?: () => PolicyRule[];
|
|
286
287
|
onTrace?: (input: TraceInput) => void;
|
|
288
|
+
/**
|
|
289
|
+
* Resolves the ambient agent identity for `execute()` calls that don't pass
|
|
290
|
+
* one explicitly. The SDK wires this to the agentContext snapshot so a
|
|
291
|
+
* button-bound tool fires with the detected agent attached — without
|
|
292
|
+
* forcing every consumer to thread identity through their click handlers.
|
|
293
|
+
*
|
|
294
|
+
* Semantics:
|
|
295
|
+
* - `execute(name, input)` or `execute(name, input, undefined)` → resolver
|
|
296
|
+
* - `execute(name, input, null)` → respected (caller wants anonymous attribution)
|
|
297
|
+
* - `execute(name, input, identity)` → respected
|
|
298
|
+
*/
|
|
299
|
+
identityResolver?: () => AgentIdentity | null;
|
|
287
300
|
}
|
|
288
301
|
interface ToolRegistry {
|
|
289
302
|
register(tool: GovernedTool): () => void;
|
|
@@ -297,7 +310,7 @@ interface ToolRegistry {
|
|
|
297
310
|
get(name: string): GovernedTool | undefined;
|
|
298
311
|
execute<Input, Output>(name: string, input: Input, identity?: AgentIdentity | null): Promise<Output>;
|
|
299
312
|
}
|
|
300
|
-
declare const createToolRegistry: ({ evaluate, setPolicies, listPolicies, onTrace, }: ToolRegistryOptions) => ToolRegistry;
|
|
313
|
+
declare const createToolRegistry: ({ evaluate, setPolicies, listPolicies, onTrace, identityResolver, }: ToolRegistryOptions) => ToolRegistry;
|
|
301
314
|
|
|
302
315
|
interface ProgressionTransition {
|
|
303
316
|
on: string;
|
|
@@ -425,6 +438,19 @@ interface InitOptions {
|
|
|
425
438
|
auth?: AuthContext;
|
|
426
439
|
progression?: ProgressionConfig;
|
|
427
440
|
tools?: GovernedTool[];
|
|
441
|
+
/**
|
|
442
|
+
* Run agent detection automatically on init and keep the resulting
|
|
443
|
+
* identity in agentContext so every subsequent tools.execute() call gets
|
|
444
|
+
* attributed without the host page passing identity through. Default
|
|
445
|
+
* `true` — opt out with `false` for privacy-mode hosts, or pass
|
|
446
|
+
* DetectAgentOptions to tune the detectors (e.g. raise the DOM threshold).
|
|
447
|
+
*
|
|
448
|
+
* The first detection cycle runs synchronously where possible (DOM
|
|
449
|
+
* heuristics) and continues asynchronously for WebMCP polling, so very
|
|
450
|
+
* early click handlers may see identity=null for a single frame; the
|
|
451
|
+
* `ready` promise on the returned client resolves once the cycle finishes.
|
|
452
|
+
*/
|
|
453
|
+
autoDetect?: boolean | DetectAgentOptions;
|
|
428
454
|
trace?: {
|
|
429
455
|
enabled?: boolean;
|
|
430
456
|
bufferSize?: number;
|
|
@@ -452,6 +478,13 @@ interface AgentronicsClient {
|
|
|
452
478
|
readonly tools: ToolRegistry;
|
|
453
479
|
readonly progression: ProgressionStore | null;
|
|
454
480
|
readonly webmcp: WebMcpAdapter;
|
|
481
|
+
/**
|
|
482
|
+
* Resolves once the initial autoDetect cycle finishes. Rejects only if the
|
|
483
|
+
* autoDetect configuration itself is invalid; detection failures resolve to
|
|
484
|
+
* `null` (treated as "human or undetectable agent"). When `autoDetect` was
|
|
485
|
+
* disabled the promise resolves immediately to `null`.
|
|
486
|
+
*/
|
|
487
|
+
readonly ready: Promise<AgentIdentity | null>;
|
|
455
488
|
detect(options?: DetectAgentOptions): Promise<AgentIdentity | null>;
|
|
456
489
|
authenticate(input: AuthInput): Promise<AgentIdentity | null>;
|
|
457
490
|
presentIdentity(input: PresentIdentityOptions): PresentedIdentity;
|
|
@@ -477,6 +510,9 @@ interface AgentronicsClient {
|
|
|
477
510
|
uninstall: () => void;
|
|
478
511
|
};
|
|
479
512
|
registerTool(tool: GovernedTool): () => void;
|
|
513
|
+
/** Push the full tool registry to the gateway so the dashboard can render
|
|
514
|
+
* the page-wise view (schemas, per-tool tokens, context fullness). */
|
|
515
|
+
syncTools(): Promise<number>;
|
|
480
516
|
surfaceTools(options?: {
|
|
481
517
|
identity?: AgentIdentity | null;
|
|
482
518
|
}): GovernedTool[];
|
package/dist/init-only.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
'use strict';var protocol=require('@agentronics/protocol');var st=()=>{if(typeof navigator>"u")return null;let e=navigator.modelContext;return e&&typeof e=="object"?e:null},C=async(e={})=>{let{pollMs:t=500}=e,n=Date.now();for(;;){let r=st();if(r)return at(r);if(Date.now()-n>=t)return null;await new Promise(o=>setTimeout(o,50));}},at=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}});var ct=[/HeadlessChrome/i,/Headless/i,/PhantomJS/i,/SlimerJS/i],lt=()=>({hit:(typeof navigator<"u"&&navigator.webdriver)===true,weight:.6,detail:"navigator.webdriver === true"}),ut=()=>{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_*"}`}},dt=()=>{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"}},pt=()=>{if(typeof navigator>"u")return {hit:false,weight:.7};let e=navigator.userAgent??"",t=ct.some(n=>n.test(e));return t?{hit:t,weight:.7,detail:`headless UA: ${e}`}:{hit:t,weight:.7}},gt=()=>{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"}},mt=()=>{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"}},yt={webdriver:lt,chromedriver:ut,headlessUa:pt,languages:gt,permissions:mt,plugins:dt},O=(e={})=>{let{threshold:t=.4}=e,n={},r=0,o=0;for(let[s,a]of Object.entries(yt)){let l=a();r+=l.weight,n[s]={hit:l.hit,weight:l.weight,detail:l.detail},l.hit&&(o+=l.weight);}let i=r===0?0:o/r;return i<t?null:{class:"dom",trust:"detected",confidence:i,vendor:null,userAgent:typeof navigator>"u"?null:navigator.userAgent,detectionVersion:"2026.04",signals:n}};var ae=()=>[{id:"webmcp.model-context",status:"stable",detect:()=>C({pollMs:0})},{id:"dom.automation-heuristics",status:"beta",detect:()=>O()}],U=(e=ae())=>{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(o=>o.status===n):r},async detectAll(n=false){for(let r of t.values()){if(r.status==="research"&&!n)continue;let o=await r.detect();if(o)return o}return null}}};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 C(e.webmcp??{});if(t)return t}if(e.dom!==false){let t=O(e.dom??{});if(t)return t}return null};var wt=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 n=protocol.IdentityClaim.safeParse(t);if(!n.success)throw new protocol.AgentronicsError("invalid_api_key",`Invalid identity claim: ${n.error.issues[0]?.message??"unknown"}`);let r={claim:n.data,identity:wt(n.data)};return e=r,r},clear(){e=null;},preferOver(t){return e?t?protocol.isHigherTrust(e.identity.trust,t.trust)?e.identity:t:e.identity:t},snapshot(){return e}}};var de=e=>{let t=null;for(let n of e)(!t||protocol.TRUST_RANK[n.trust]>protocol.TRUST_RANK[t.trust])&&(t=n);return t};var pe=()=>({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??"verified",confidence:1,vendor:n?.vendor??e.vendorHint??"bearer",userAgent:typeof navigator>"u"?null:navigator.userAgent,detectionVersion:"2026.04",signals:{bearer:true,verifiedRemotely:!!n}}}});var ge=()=>({name:"detection",async authenticate(e){return e.detected??null}});var me=()=>({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??"verified",confidence:1,vendor:n?.vendor??e.vendorHint??"browser-extension",userAgent:typeof navigator>"u"?null:navigator.userAgent,detectionVersion:"2026.04",signals:{extensionToken:true,verifiedRemotely:!!n}}}});var ye=()=>({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??"verified",confidence:1,vendor:n?.vendor??e.vendorHint??"mtls",userAgent:typeof navigator>"u"?null:navigator.userAgent,detectionVersion:"2026.04",signals:{mtls:true,subject:n?.subject??null,verifiedRemotely:!!n,...n?.signals??{}}}}});var fe=()=>({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:e.oauth2Subject?"linked":n?.trust??"verified",confidence:1,vendor:n?.vendor??e.vendorHint??"oauth2",userAgent:typeof navigator>"u"?null:navigator.userAgent,detectionVersion:"2026.04",signals:{oauth2:true,subject:e.oauth2Subject??null,verifiedRemotely:!!n}}}});var bt=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}}),he=()=>({name:"selfDeclaration",async authenticate(e){return e.declaration?bt(protocol.IdentityClaim.parse(e.declaration)):null}});var ve=()=>({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:e.linkedUserId?"linked":n?.trust??"verified",confidence:1,vendor:n?.vendor??e.vendorHint??"session-link",userAgent:typeof navigator>"u"?null:navigator.userAgent,detectionVersion:"2026.04",signals:{sessionLink:true,linkedUserId:e.linkedUserId??null,verifiedRemotely:!!n}}}});var we=()=>({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??"verified",confidence:1,vendor:n?.vendor??e.vendorHint??"sso",userAgent:typeof navigator>"u"?null:navigator.userAgent,detectionVersion:"2026.04",signals:{sso:true,subject:n?.subject??null,verifiedRemotely:!!n,...n?.signals??{}}}}});var xe=()=>({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??"verified",confidence:1,vendor:n?.vendor??e.vendorHint??"spiffe",userAgent:typeof navigator>"u"?null:navigator.userAgent,detectionVersion:"2026.04",signals:{spiffe:true,spiffeId:n?.subject??null,subject:n?.subject??null,verifiedRemotely:!!n,...r?{googleAgent:true}:{},...n?.signals??{}}}}});var be=()=>({name:"xAgentHeader",async authenticate(e){if(!e.xAgentHeader)return null;let[t="x-agent",n="dom",r]=e.xAgentHeader.split(";"),o=protocol.AgentClass.safeParse(n);return {class:o.success?o.data:"dom",trust:r?"verified":"declared",confidence:r?1:.8,vendor:t,userAgent:typeof navigator>"u"?null:navigator.userAgent,detectionVersion:"2026.04",signals:{xAgentHeader:true,hasProof:!!r}}}});var St=()=>[ge(),he(),pe(),be(),me(),ve(),fe(),we(),xe(),ye()],At={detection:"detection",selfDeclaration:"declaration",bearer:"bearer",xAgentHeader:"x-agent-header",extensionToken:"extension",sessionLink:"session-link",oauth2:"oauth2",sso:"sso",spiffe:"spiffe",mtls:"mtls"},kt=(e,t)=>e==="spiffe"&&t.signals?.googleAgent===true?"google-agent":At[e],Te=({methods:e=St(),context:t={},onTrace:n}={})=>({async authenticate(r){let o=[],i={};for(let g of e){let u=await g.authenticate(r,t);i[g.name]=!!u,u&&o.push({method:g.name,identity:u});}let s=de(o.map(g=>g.identity)),a=s?o.find(g=>g.identity===s):void 0,l=a?kt(a.method,a.identity):void 0,d=typeof s?.signals?.subject=="string"?s.signals.subject:void 0,p={type:s?"auth.identity_presented":"sdk.error",agent:s,outcome:s?"success":"error",metadata:{methods:i,...l?{protocol:l}:{},...d?{subject:d}:{}}};return s||(p.error="No auth method produced an identity."),n?.(p),s},methods(){return e.map(r=>r.name)}});var Mt={identity:null,source:"initial",updatedAt:null},Se=()=>{let e=Mt,t=new Set,n=()=>{t.size!==0&&t.forEach(r=>r(e));};return {snapshot(){return e},set(r,o){e={identity:r,source:o,updatedAt:new Date().toISOString()},n();},subscribe(r){return t.add(r),()=>{t.delete(r);}}}};var It=()=>{let e=new Map;return {read:t=>e.get(t)??null,write:(t,n)=>{e.set(t,n);}}},Pt=()=>typeof window>"u"||!window.localStorage?It():{read:e=>{try{return window.localStorage.getItem(e)}catch{return null}},write:(e,t)=>{try{window.localStorage.setItem(e,t);}catch{}}},Rt=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},Ae=(e=Pt())=>({consume(t,n,r=Date.now()){let o=`agtx:rate:${t}`,i=Rt(e.read(o)),s=i&&i.resetAt>r?i.resetAt:r+n.windowSeconds*1e3,a=i&&i.resetAt>r?i.count+1:1;return e.write(o,JSON.stringify({count:a,resetAt:s})),{allowed:a<=n.max,remaining:Math.max(0,n.max-a),resetAt:s}}});var Et=(e,t)=>e==="*"||e===t?true:e.includes("*")?new RegExp("^"+e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*")+"$").test(t):false,Ct=(e,t)=>{let n=e?protocol.TRUST_RANK[e.trust]:-1,r=protocol.TRUST_RANK[t.minTrust];return n>=r},Ot=(e,t)=>t.allowedClasses.length===0?true:e?t.allowedClasses.includes(e.class):false,Ie="review",Dt=(e,t)=>{let n=t?.class??"unknown",r=t?.vendor??"unknown",o=t?.trust??"none";return `${e}:${n}:${r}:${o}`},Pe=(e=[],t={})=>{let n=e.map(o=>protocol.PolicyRule.parse(o)),r=t.rateLimiter??Ae();return {set(o){n=o.map(i=>protocol.PolicyRule.parse(i));},list(){return [...n]},evaluate({tool:o,identity:i}){for(let s of n)if(Et(s.tool,o)){if(!Ct(i,s))return {decision:"deny",ruleId:s.id,reason:`Rule "${s.id}" requires trust >= ${s.minTrust}.`};if(!Ot(i,s))return {decision:"deny",ruleId:s.id,reason:`Rule "${s.id}" restricts to classes: ${s.allowedClasses.join(", ")}.`};if(s.rateLimit){let a=r.consume(Dt(o,i),s.rateLimit);if(!a.allowed)return {decision:"deny",ruleId:s.id,reason:`Rule "${s.id}" rate limit exceeded. Resets at ${new Date(a.resetAt).toISOString()}.`}}return {decision:s.decision,ruleId:s.id,reason:`Matched rule "${s.id}".`}}return {decision:Ie,ruleId:null,reason:`No rule matched tool "${o}". Falling back to "${Ie}".`}}}};var Re=({gatewayUrl:e,siteId:t,publishableKey:n,fetcher:r=fetch})=>{let o={policies:[],etag:null};return {snapshot(){return {policies:[...o.policies],etag:o.etag}},async sync(){let i=await r(`${e.replace(/\/$/,"")}/v1/sites/${encodeURIComponent(t)}/policies`,{headers:{authorization:`Bearer ${n}`,...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 s=await i.json();return o={policies:protocol.PolicyRule.array().parse(s.policies??[]),etag:i.headers.get("etag")},this.snapshot()}}};var Ee=({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:"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"}),n.body.appendChild(r),window.setTimeout(()=>r.remove(),t),r};var Ce=({policyEngine:e,getIdentity:t,documentRef:n=typeof document>"u"?void 0:document,selector:r="[data-agentronics-tool]"})=>{if(!n)return {uninstall:()=>{}};let o=i=>{let s=i.target instanceof Element?i.target.closest(r):null;if(!(s instanceof HTMLElement))return;let a=s.dataset.agentronicsTool;a&&Promise.resolve(t()).then(l=>{let d=e.evaluate({tool:a,identity:l});d.decision==="deny"&&(i.preventDefault(),i.stopPropagation(),Ee({message:d.reason,documentRef:n}));});};return n.addEventListener("click",o,true),{uninstall:()=>n.removeEventListener("click",o,true)}};var _=()=>{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()]}},Oe=(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 o=e.key(r);o&&o.startsWith(t)&&n.push(o.slice(t.length));}}catch{}return n}}),De="agtx:",Le=()=>{let e=typeof window<"u",t=e&&typeof window.sessionStorage<"u"?Oe(window.sessionStorage,De+"session:"):_(),n=e&&typeof window.localStorage<"u"?Oe(window.localStorage,De+"user:"):_();return {session:t,user:n,org:_()}};var je=(e,t)=>e.expiresAt!==null&&e.expiresAt<=t,We=e=>{if(!e)return null;try{let t=JSON.parse(e);return typeof t!="object"||t===null?null:t}catch{return null}},$t=e=>JSON.stringify(e),Ge=(e={})=>{let t=Le(),n=l=>{e.onTrace?.(l);};return {get:(l,d={})=>{let p=d.scope??"session",g=t[p],u=We(g.read(l));if(!u){n({type:"memory.accessed",metadata:{operation:"get",key:l,scope:p,hit:false}});return}if(je(u,Date.now())){g.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}}),u.value},set:(l,d,p={})=>{let g=p.scope??"session",u=p.ttlSeconds??null,f=Date.now(),w={value:d,expiresAt:u===null?null:f+u*1e3,updatedAt:new Date(f).toISOString()};return t[g].write(l,$t(w)),n({type:"memory.updated",metadata:{operation:"set",key:l,scope:g,ttlSeconds:u}}),protocol.MemoryEntry.parse({key:l,value:d,scope:g,ttlSeconds:u,updatedAt:w.updatedAt})},remove:(l,d={})=>{let p=d.scope??"session";t[p].remove(l),n({type:"memory.updated",metadata:{operation:"remove",key:l,scope:p}});},list:(l={})=>{let d=l.scope??"session",p=t[d],g=Date.now(),u=[];for(let f of p.keys()){let w=We(p.read(f));if(w){if(je(w,g)){p.remove(f);continue}u.push(protocol.MemoryEntry.parse({key:f,value:w.value,scope:d,ttlSeconds:w.expiresAt===null?null:Math.max(0,Math.round((w.expiresAt-g)/1e3)),updatedAt:w.updatedAt}));}}return n({type:"memory.accessed",metadata:{operation:"list",scope:d,count:u.length}}),u},clear:(l={})=>{let d=l.scope??"session",p=t[d],g=p.keys().length;for(let u of p.keys())p.remove(u);n({type:"memory.updated",metadata:{operation:"clear",scope:d,count:g}});}}};var N=e=>protocol.SiteMemory.parse(JSON.parse(JSON.stringify(e))),L=e=>({...e,updatedAt:new Date().toISOString()}),Be=(e={})=>{let t=protocol.SiteMemory.parse({...protocol.SITE_MEMORY_DEFAULT,...e.initial??{}}),n=null,r=new Set,o=m=>{e.onTrace?.(m);},i=()=>{n=null;},s=()=>{if(r.size===0)return;let m=N(t);n=m,r.forEach(h=>h(m));},a=m=>{let h=protocol.SiteMemory.parse({...t,...m,workflows:{...t.workflows,...m.workflows??{}},policies:{...t.policies,...m.policies??{}},uiGuidance:{...t.uiGuidance,...m.uiGuidance??{}},pageContexts:{...t.pageContexts,...m.pageContexts??{}}});return t=L(h),i(),o({type:"memory.updated",metadata:{kind:"site",operation:"provide",keys:Object.keys(m)}}),s(),p()},l=(m,h)=>{let v=m.split(".").filter(Boolean);if(v.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<v.length-1;M++){let T=v[M],I=k[T];(typeof I!="object"||I===null||Array.isArray(I))&&(k[T]={}),k=k[T];}return k[v[v.length-1]]=h,t=L(protocol.SiteMemory.parse(A)),i(),o({type:"memory.updated",metadata:{kind:"site",operation:"update",path:m}}),s(),p()},d=m=>{let h=protocol.SiteMemoryPageContext.parse({path:m.path,payload:m.payload,updatedAt:new Date().toISOString()});return t=L({...t,pageContexts:{...t.pageContexts,[m.path]:h}}),i(),o({type:"memory.updated",metadata:{kind:"site",operation:"provideForPage",path:m.path}}),s(),{...h,payload:{...h.payload}}},p=()=>(n||(n=N(t)),n);return {provide:a,update:l,provideForPage:d,snapshot:p,get:m=>{if(o({type:"memory.accessed",metadata:{kind:"site",operation:m?"get":"snapshot",path:m??null}}),!m)return N(t);let h=m.split(".").filter(Boolean),v=t;for(let A of h){if(typeof v!="object"||v===null)return;v=v[A];}return v},getForPage:m=>{o({type:"memory.accessed",metadata:{kind:"site",operation:"getForPage",path:m}});let h=t.pageContexts[m];return h?{...h,payload:{...h.payload}}:null},replace:m=>(t=L(protocol.SiteMemory.parse(m)),i(),s(),p()),subscribe:m=>(r.add(m),()=>{r.delete(m);})}};var _e=({gatewayUrl:e,siteId:t,publishableKey:n,fetcher:r=fetch})=>{let o={memory:null,etag:null};return {snapshot(){return {memory:o.memory?protocol.SiteMemory.parse(o.memory):null,etag:o.etag}},async sync(){let i=await r(`${e.replace(/\/$/,"")}/v1/sites/${encodeURIComponent(t)}/memory`,{headers:{authorization:`Bearer ${n}`,...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 s=await i.json();return o={memory:protocol.SiteMemory.parse(s.memory??{}),etag:i.headers.get("etag")},this.snapshot()}}};var S="agent-context-",H="agentronics-site-context",Gt=e=>{try{return JSON.stringify(e)}catch{return "{}"}},$=(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());},F=({doc:e=typeof document>"u"?null:document,snapshot:t,schemaType:n="WebSite"})=>{if(!e)return {uninstall:()=>{}};$(e,`${S}version`,t.version),$(e,`${S}updated-at`,t.updatedAt??new Date().toISOString()),t.siteMap?.navigation?.flow&&$(e,`${S}flow`,t.siteMap.navigation.flow),$(e,`${S}workflows`,Object.keys(t.workflows).join(","));let r=e.getElementById(H);return r||(r=e.createElement("script"),r.type="application/ld+json",r.id=H,e.head.appendChild(r)),r.textContent=Gt({"@context":"https://schema.org","@type":n,name:"Agentronics Site Memory",agentronics:t}),{uninstall:()=>{j(e,`${S}version`),j(e,`${S}updated-at`),j(e,`${S}flow`),j(e,`${S}workflows`),e.getElementById(H)?.remove();}}};var Ne="agentronics-memory-overlay",Bt=e=>`
|
|
1
|
+
'use strict';var protocol=require('@agentronics/protocol');var f="0.1.2";var pt=()=>{if(typeof navigator>"u")return null;let e=navigator.modelContext;return e&&typeof e=="object"?e:null},C=async(e={})=>{let{pollMs:t=500}=e,n=Date.now();for(;;){let r=pt();if(r)return mt(r);if(Date.now()-n>=t)return null;await new Promise(i=>setTimeout(i,50));}},mt=e=>({class:"webmcp",trust:"detected",confidence:1,vendor:e.vendor??e.client??null,userAgent:typeof navigator>"u"?null:navigator.userAgent,detectionVersion:f,signals:{webmcp:true,toolCount:Array.isArray(e.tools)?e.tools.length:0}});var yt=[/HeadlessChrome/i,/Headless/i,/PhantomJS/i,/SlimerJS/i],gt=()=>({hit:(typeof navigator<"u"&&navigator.webdriver)===true,weight:.6,detail:"navigator.webdriver === true"}),ft=()=>{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_*"}`}},ht=()=>{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"}},vt=()=>{if(typeof navigator>"u")return {hit:false,weight:.7};let e=navigator.userAgent??"",t=yt.some(n=>n.test(e));return t?{hit:t,weight:.7,detail:`headless UA: ${e}`}:{hit:t,weight:.7}},wt=()=>{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"}},xt=()=>{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"}},St={webdriver:gt,chromedriver:ft,headlessUa:vt,languages:wt,permissions:xt,plugins:ht},L=(e={})=>{let{threshold:t=.4}=e,n={},r=0,i=0;for(let[s,g]of Object.entries(St)){let o=g();r+=o.weight,n[s]={hit:o.hit,weight:o.weight,detail:o.detail},o.hit&&(i+=o.weight);}let a=r===0?0:i/r;return a<t?null:{class:"dom",trust:"detected",confidence:a,vendor:null,userAgent:typeof navigator>"u"?null:navigator.userAgent,detectionVersion:f,signals:n}};var le=()=>[{id:"webmcp.model-context",status:"stable",detect:()=>C({pollMs:0})},{id:"dom.automation-heuristics",status:"beta",detect:()=>L()}],U=(e=le())=>{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 ue=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 C(e.webmcp??{});if(t)return t}if(e.dom!==false){let t=L(e.dom??{});if(t)return t}return null};var kt=e=>({class:e.class,trust:"declared",confidence:1,vendor:e.vendor,userAgent:typeof navigator>"u"?null:navigator.userAgent,detectionVersion:f,signals:{declared:true,hasToken:true,tokenExpiresAt:e.expiresAt??null}}),de=()=>{let e=null;return {present(t){let n=protocol.IdentityClaim.safeParse(t);if(!n.success)throw new protocol.AgentronicsError("invalid_api_key",`Invalid identity claim: ${n.error.issues[0]?.message??"unknown"}`);let r={claim:n.data,identity:kt(n.data)};return e=r,r},clear(){e=null;},preferOver(t){return e?t?protocol.isHigherTrust(e.identity.trust,t.trust)?e.identity:t:e.identity:t},snapshot(){return e}}};var me=e=>{let t=null;for(let n of e)(!t||protocol.TRUST_RANK[n.trust]>protocol.TRUST_RANK[t.trust])&&(t=n);return t};var ye=()=>({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??"verified",confidence:1,vendor:n?.vendor??e.vendorHint??"bearer",userAgent:typeof navigator>"u"?null:navigator.userAgent,detectionVersion:f,signals:{bearer:true,verifiedRemotely:!!n}}}});var ge=()=>({name:"detection",async authenticate(e){return e.detected??null}});var fe=()=>({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??"verified",confidence:1,vendor:n?.vendor??e.vendorHint??"browser-extension",userAgent:typeof navigator>"u"?null:navigator.userAgent,detectionVersion:f,signals:{extensionToken:true,verifiedRemotely:!!n}}}});var he=()=>({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??"verified",confidence:1,vendor:n?.vendor??e.vendorHint??"mtls",userAgent:typeof navigator>"u"?null:navigator.userAgent,detectionVersion:f,signals:{mtls:true,subject:n?.subject??null,verifiedRemotely:!!n,...n?.signals??{}}}}});var ve=()=>({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:e.oauth2Subject?"linked":n?.trust??"verified",confidence:1,vendor:n?.vendor??e.vendorHint??"oauth2",userAgent:typeof navigator>"u"?null:navigator.userAgent,detectionVersion:f,signals:{oauth2:true,subject:e.oauth2Subject??null,verifiedRemotely:!!n}}}});var It=e=>({class:e.class,trust:"declared",confidence:1,vendor:e.vendor,userAgent:typeof navigator>"u"?null:navigator.userAgent,detectionVersion:f,signals:{declared:true,hasToken:true,tokenExpiresAt:e.expiresAt??null}}),we=()=>({name:"selfDeclaration",async authenticate(e){return e.declaration?It(protocol.IdentityClaim.parse(e.declaration)):null}});var xe=()=>({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:e.linkedUserId?"linked":n?.trust??"verified",confidence:1,vendor:n?.vendor??e.vendorHint??"session-link",userAgent:typeof navigator>"u"?null:navigator.userAgent,detectionVersion:f,signals:{sessionLink:true,linkedUserId:e.linkedUserId??null,verifiedRemotely:!!n}}}});var Se=()=>({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??"verified",confidence:1,vendor:n?.vendor??e.vendorHint??"sso",userAgent:typeof navigator>"u"?null:navigator.userAgent,detectionVersion:f,signals:{sso:true,subject:n?.subject??null,verifiedRemotely:!!n,...n?.signals??{}}}}});var be=()=>({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??"verified",confidence:1,vendor:n?.vendor??e.vendorHint??"spiffe",userAgent:typeof navigator>"u"?null:navigator.userAgent,detectionVersion:f,signals:{spiffe:true,spiffeId:n?.subject??null,subject:n?.subject??null,verifiedRemotely:!!n,...r?{googleAgent:true}:{},...n?.signals??{}}}}});var Te=()=>({name:"xAgentHeader",async authenticate(e){if(!e.xAgentHeader)return null;let[t="x-agent",n="dom",r]=e.xAgentHeader.split(";"),i=protocol.AgentClass.safeParse(n);return {class:i.success?i.data:"dom",trust:r?"verified":"declared",confidence:r?1:.8,vendor:t,userAgent:typeof navigator>"u"?null:navigator.userAgent,detectionVersion:f,signals:{xAgentHeader:true,hasProof:!!r}}}});var Pt=()=>[ge(),we(),ye(),Te(),fe(),xe(),ve(),Se(),be(),he()],Et={detection:"detection",selfDeclaration:"declaration",bearer:"bearer",xAgentHeader:"x-agent-header",extensionToken:"extension",sessionLink:"session-link",oauth2:"oauth2",sso:"sso",spiffe:"spiffe",mtls:"mtls"},Ot=(e,t)=>e==="spiffe"&&t.signals?.googleAgent===true?"google-agent":Et[e],Ae=({methods:e=Pt(),context:t={},onTrace:n}={})=>({async authenticate(r){let i=[],a={};for(let p of e){let d=await p.authenticate(r,t);a[p.name]=!!d,d&&i.push({method:p.name,identity:d});}let s=me(i.map(p=>p.identity)),g=s?i.find(p=>p.identity===s):void 0,o=g?Ot(g.method,g.identity):void 0,y=typeof s?.signals?.subject=="string"?s.signals.subject:void 0,u={type:s?"auth.identity_presented":"sdk.error",agent:s,outcome:s?"success":"error",metadata:{methods:a,...o?{protocol:o}:{},...y?{subject:y}:{}}};return s||(u.error="No auth method produced an identity."),n?.(u),s},methods(){return e.map(r=>r.name)}});var Dt={identity:null,source:"initial",updatedAt:null},ke=()=>{let e=Dt,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 Ct=()=>{let e=new Map;return {read:t=>e.get(t)??null,write:(t,n)=>{e.set(t,n);}}},Lt=()=>typeof window>"u"||!window.localStorage?Ct():{read:e=>{try{return window.localStorage.getItem(e)}catch{return null}},write:(e,t)=>{try{window.localStorage.setItem(e,t);}catch{}}},$t=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},Me=(e=Lt())=>({consume(t,n,r=Date.now()){let i=`agtx:rate:${t}`,a=$t(e.read(i)),s=a&&a.resetAt>r?a.resetAt:r+n.windowSeconds*1e3,g=a&&a.resetAt>r?a.count+1:1;return e.write(i,JSON.stringify({count:g,resetAt:s})),{allowed:g<=n.max,remaining:Math.max(0,n.max-g),resetAt:s}}});var jt=(e,t)=>e==="*"||e===t?true:e.includes("*")?new RegExp("^"+e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*")+"$").test(t):false,Wt=(e,t)=>{let n=e?protocol.TRUST_RANK[e.trust]:-1,r=protocol.TRUST_RANK[t.minTrust];return n>=r},Nt=(e,t)=>t.allowedClasses.length===0?true:e?t.allowedClasses.includes(e.class):false,Pe="review",_t=(e,t)=>{let n=t?.class??"unknown",r=t?.vendor??"unknown",i=t?.trust??"none";return `${e}:${n}:${r}:${i}`},Ee=(e=[],t={})=>{let n=e.map(i=>protocol.PolicyRule.parse(i)),r=t.rateLimiter??Me();return {set(i){n=i.map(a=>protocol.PolicyRule.parse(a));},list(){return [...n]},evaluate({tool:i,identity:a}){for(let s of n)if(jt(s.tool,i)){if(!Wt(a,s))return {decision:"deny",ruleId:s.id,reason:`Rule "${s.id}" requires trust >= ${s.minTrust}.`};if(!Nt(a,s))return {decision:"deny",ruleId:s.id,reason:`Rule "${s.id}" restricts to classes: ${s.allowedClasses.join(", ")}.`};if(s.rateLimit){let g=r.consume(_t(i,a),s.rateLimit);if(!g.allowed)return {decision:"deny",ruleId:s.id,reason:`Rule "${s.id}" rate limit exceeded. Resets at ${new Date(g.resetAt).toISOString()}.`}}return {decision:s.decision,ruleId:s.id,reason:`Matched rule "${s.id}".`}}return {decision:Pe,ruleId:null,reason:`No rule matched tool "${i}". Falling back to "${Pe}".`}}}};var Oe=({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 a=await r(`${e.replace(/\/$/,"")}/v1/sites/${encodeURIComponent(t)}/policies`,{headers:{authorization:`Bearer ${n}`,...i.etag?{"if-none-match":i.etag}:{}}});if(a.status===304)return this.snapshot();if(!a.ok)throw new Error(`Policy sync failed with status ${a.status}.`);let s=await a.json();return i={policies:protocol.PolicyRule.array().parse(s.policies??[]),etag:a.headers.get("etag")},this.snapshot()}}};var De=({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:"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"}),n.body.appendChild(r),window.setTimeout(()=>r.remove(),t),r};var Ce=({policyEngine:e,getIdentity:t,documentRef:n=typeof document>"u"?void 0:document,selector:r="[data-agentronics-tool]"})=>{if(!n)return {uninstall:()=>{}};let i=a=>{let s=a.target instanceof Element?a.target.closest(r):null;if(!(s instanceof HTMLElement))return;let g=s.dataset.agentronicsTool;g&&Promise.resolve(t()).then(o=>{let y=e.evaluate({tool:g,identity:o});y.decision==="deny"&&(a.preventDefault(),a.stopPropagation(),De({message:y.reason,documentRef:n}));});};return n.addEventListener("click",i,true),{uninstall:()=>n.removeEventListener("click",i,true)}};var K=()=>{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()]}},Le=(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}}),$e="agtx:",je=()=>{let e=typeof window<"u",t=e&&typeof window.sessionStorage<"u"?Le(window.sessionStorage,$e+"session:"):K(),n=e&&typeof window.localStorage<"u"?Le(window.localStorage,$e+"user:"):K();return {session:t,user:n,org:K()}};var Ne=(e,t)=>e.expiresAt!==null&&e.expiresAt<=t,_e=e=>{if(!e)return null;try{let t=JSON.parse(e);return typeof t!="object"||t===null?null:t}catch{return null}},Bt=e=>JSON.stringify(e),Ge=(e={})=>{let t=je(),n=o=>{e.onTrace?.(o);};return {get:(o,y={})=>{let u=y.scope??"session",p=t[u],d=_e(p.read(o));if(!d){n({type:"memory.accessed",metadata:{operation:"get",key:o,scope:u,hit:false}});return}if(Ne(d,Date.now())){p.remove(o),n({type:"memory.accessed",metadata:{operation:"get",key:o,scope:u,hit:false,expired:true}});return}return n({type:"memory.accessed",metadata:{operation:"get",key:o,scope:u,hit:true}}),d.value},set:(o,y,u={})=>{let p=u.scope??"session",d=u.ttlSeconds??null,h=Date.now(),w={value:y,expiresAt:d===null?null:h+d*1e3,updatedAt:new Date(h).toISOString()};return t[p].write(o,Bt(w)),n({type:"memory.updated",metadata:{operation:"set",key:o,scope:p,ttlSeconds:d}}),protocol.MemoryEntry.parse({key:o,value:y,scope:p,ttlSeconds:d,updatedAt:w.updatedAt})},remove:(o,y={})=>{let u=y.scope??"session";t[u].remove(o),n({type:"memory.updated",metadata:{operation:"remove",key:o,scope:u}});},list:(o={})=>{let y=o.scope??"session",u=t[y],p=Date.now(),d=[];for(let h of u.keys()){let w=_e(u.read(h));if(w){if(Ne(w,p)){u.remove(h);continue}d.push(protocol.MemoryEntry.parse({key:h,value:w.value,scope:y,ttlSeconds:w.expiresAt===null?null:Math.max(0,Math.round((w.expiresAt-p)/1e3)),updatedAt:w.updatedAt}));}}return n({type:"memory.accessed",metadata:{operation:"list",scope:y,count:d.length}}),d},clear:(o={})=>{let y=o.scope??"session",u=t[y],p=u.keys().length;for(let d of u.keys())u.remove(d);n({type:"memory.updated",metadata:{operation:"clear",scope:y,count:p}});}}};var H=e=>protocol.SiteMemory.parse(JSON.parse(JSON.stringify(e))),W=e=>({...e,updatedAt:new Date().toISOString()}),Be=(e={})=>{let t=protocol.SiteMemory.parse({...protocol.SITE_MEMORY_DEFAULT,...e.initial??{}}),n=null,r=new Set,i=l=>{e.onTrace?.(l);},a=()=>{n=null;},s=()=>{if(r.size===0)return;let l=H(t);n=l,r.forEach(v=>v(l));},g=l=>{let v=protocol.SiteMemory.parse({...t,...l,workflows:{...t.workflows,...l.workflows??{}},policies:{...t.policies,...l.policies??{}},uiGuidance:{...t.uiGuidance,...l.uiGuidance??{}},pageContexts:{...t.pageContexts,...l.pageContexts??{}}});return t=W(v),a(),i({type:"memory.updated",metadata:{kind:"site",operation:"provide",keys:Object.keys(l)}}),s(),u()},o=(l,v)=>{let x=l.split(".").filter(Boolean);if(x.length===0)throw new Error("siteMemory.update() requires a non-empty dot-path.");let k=JSON.parse(JSON.stringify(t)),M=k;for(let R=0;R<x.length-1;R++){let T=x[R],P=M[T];(typeof P!="object"||P===null||Array.isArray(P))&&(M[T]={}),M=M[T];}return M[x[x.length-1]]=v,t=W(protocol.SiteMemory.parse(k)),a(),i({type:"memory.updated",metadata:{kind:"site",operation:"update",path:l}}),s(),u()},y=l=>{let v=protocol.SiteMemoryPageContext.parse({path:l.path,payload:l.payload,updatedAt:new Date().toISOString()});return t=W({...t,pageContexts:{...t.pageContexts,[l.path]:v}}),a(),i({type:"memory.updated",metadata:{kind:"site",operation:"provideForPage",path:l.path}}),s(),{...v,payload:{...v.payload}}},u=()=>(n||(n=H(t)),n);return {provide:g,update:o,provideForPage:y,snapshot:u,get:l=>{if(i({type:"memory.accessed",metadata:{kind:"site",operation:l?"get":"snapshot",path:l??null}}),!l)return H(t);let v=l.split(".").filter(Boolean),x=t;for(let k of v){if(typeof x!="object"||x===null)return;x=x[k];}return x},getForPage:l=>{i({type:"memory.accessed",metadata:{kind:"site",operation:"getForPage",path:l}});let v=t.pageContexts[l];return v?{...v,payload:{...v.payload}}:null},replace:l=>(t=W(protocol.SiteMemory.parse(l)),a(),s(),u()),subscribe:l=>(r.add(l),()=>{r.delete(l);})}};var Ke=({gatewayUrl:e,siteId:t,publishableKey:n,fetcher:r=fetch})=>{let i={memory:null,etag:null};return {snapshot(){return {memory:i.memory?protocol.SiteMemory.parse(i.memory):null,etag:i.etag}},async sync(){let a=await r(`${e.replace(/\/$/,"")}/v1/sites/${encodeURIComponent(t)}/memory`,{headers:{authorization:`Bearer ${n}`,...i.etag?{"if-none-match":i.etag}:{}}});if(a.status===304)return this.snapshot();if(!a.ok)throw new Error(`Memory sync failed with status ${a.status}.`);let s=await a.json();return i={memory:protocol.SiteMemory.parse(s.memory??{}),etag:a.headers.get("etag")},this.snapshot()}}};var A="agent-context-",V="agentronics-site-context",Ht=e=>{try{return JSON.stringify(e)}catch{return "{}"}},N=(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);},_=(e,t)=>{e.querySelectorAll(`meta[name="${t}"]`).forEach(n=>n.remove());},F=({doc:e=typeof document>"u"?null:document,snapshot:t,schemaType:n="WebSite"})=>{if(!e)return {uninstall:()=>{}};N(e,`${A}version`,t.version),N(e,`${A}updated-at`,t.updatedAt??new Date().toISOString()),t.siteMap?.navigation?.flow&&N(e,`${A}flow`,t.siteMap.navigation.flow),N(e,`${A}workflows`,Object.keys(t.workflows).join(","));let r=e.getElementById(V);return r||(r=e.createElement("script"),r.type="application/ld+json",r.id=V,e.head.appendChild(r)),r.textContent=Ht({"@context":"https://schema.org","@type":n,name:"Agentronics Site Memory",agentronics:t}),{uninstall:()=>{_(e,`${A}version`),_(e,`${A}updated-at`),_(e,`${A}flow`),_(e,`${A}workflows`),e.getElementById(V)?.remove();}}};var He="agentronics-memory-overlay",Vt=e=>`
|
|
2
2
|
position: fixed;
|
|
3
3
|
bottom: 16px;
|
|
4
4
|
right: 16px;
|
|
@@ -12,6 +12,6 @@ z-index: 2147483647;
|
|
|
12
12
|
opacity: ${e?"0":"1"};
|
|
13
13
|
pointer-events: ${e?"none":"auto"};
|
|
14
14
|
box-shadow: 0 12px 32px rgba(15, 23, 42, 0.35);
|
|
15
|
-
`,He=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}`},K=({doc:e=typeof document>"u"?null:document,snapshot:t,hidden:n=false})=>{if(!e)return {uninstall:()=>{},refresh:()=>{}};let r=e.getElementById(Ne);return r||(r=e.createElement("div"),r.id=Ne,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",Bt(n)),r.textContent=He(t),{uninstall:()=>{r?.remove();},refresh:o=>{r&&(r.textContent=He(o));}}};var Fe="/.well-known/agent-context.json",z=async({origin:e,fetcher:t=fetch,signal:n}={})=>{let r=(e?e.replace(/\/$/,""):typeof window<"u"?window.location.origin:"")+Fe;if(!r.startsWith("http"))return null;let o={headers:{accept:"application/json"}};n!==void 0&&(o.signal=n);let i=await t(r,o);if(!i.ok){if(i.status===404)return null;throw new Error(`well-known agent-context fetch failed with status ${i.status}.`)}let s=await i.json();return protocol.SiteMemory.parse(s)};var Ke=({evaluate:e,setPolicies:t,listPolicies:n,onTrace:r})=>{let o=new Map,i=new Set,s=a=>{if(!a.authz||!t||!n)return;let l={id:`tool:${a.name}`,tool:a.name,...a.authz,rateLimit:a.rateLimit??a.authz.rateLimit};t([...n().filter(d=>d.id!==l.id),l]);};return {register(a){return o.set(a.name,a),i.delete(a.name),s(a),r?.({type:"tool.registered",tool:a.name,metadata:{version:a.version??null,group:a.group??null,stage:a.stage??null}}),()=>{o.delete(a.name),i.delete(a.name);}},unregister(a){o.delete(a),i.delete(a);},enable(a){!o.has(a)||!i.has(a)||(i.delete(a),r?.({type:"tool.surfaced",tool:a,metadata:{state:"enabled"}}));},disable(a){!o.has(a)||i.has(a)||(i.add(a),r?.({type:"tool.surfaced",tool:a,metadata:{state:"disabled"}}));},isEnabled:a=>o.has(a)&&!i.has(a),list({includeDisabled:a=false}={}){let l=[...o.values()];return a?l:l.filter(d=>!i.has(d.name))},get:a=>o.get(a),async execute(a,l,d=null){let p=o.get(a);if(!p)throw new Error(`Tool "${a}" is not registered.`);if(i.has(a)){let f={decision:"deny",ruleId:`tool:${a}`,reason:"Tool is disabled."};throw r?.({type:"tool.executed",tool:a,agent:d,policy:f,outcome:"blocked"}),new Error(f.reason)}let g=await e(a,{identity:d});if(g.decision==="deny")throw r?.({type:"tool.executed",tool:a,agent:d,policy:g,outcome:"blocked"}),new Error(g.reason);let u=Date.now();try{let f=await p.execute(l,{identity:d});return r?.({type:"tool.executed",tool:a,agent:d,policy:g,outcome:"success",durationMs:Date.now()-u}),f}catch(f){throw r?.({type:"tool.executed",tool:a,agent:d,policy:g,outcome:"error",durationMs:Date.now()-u,error:f instanceof Error?f.message:String(f)}),f}}}};var ze=(e,t={})=>{let n=new Map;for(let s of e.stages)n.set(s.name,s);if(!n.has(e.initial))throw new Error(`Initial stage "${e.initial}" is not declared in progression stages.`);let r=e.initial,o=()=>{let s=n.get(r);return s?.enables?[r,...s.enables]:[r]},i=(s,a)=>{let l=r;if(!n.has(s))throw new Error(`Cannot transition to unknown stage "${s}".`);return s===r?{changed:false,from:l,to:s}:(r=s,t.onTrace?.({type:"tool.progressed",metadata:{from:l,to:s,trigger:a}}),{changed:true,from:l,to:s})};return {current:()=>r,enabledStages:()=>o(),notify(s){let l=n.get(r)?.transitions?.find(d=>d.on===s);return l?i(l.to,s):{changed:false,from:r,to:r}},set(s){return i(s,"manual")},reset(){let s=r;r=e.initial,s!==r&&t.onTrace?.({type:"tool.progressed",metadata:{from:s,to:r,trigger:"reset"}});},snapshot:()=>({current:r,enabled:o()})}};var _t=(e,t)=>{let n=e.authz?.minTrust;return n?t?protocol.TRUST_RANK[t.trust]<protocol.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"}},Nt=(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("|")}`}},Ht=(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"},Ve=(e,t)=>{let n=_t(e,t.identity);if(!n.ok)return {tool:e,visible:false,reason:n.reason};let r=Nt(e,t.identity);if(!r.ok)return {tool:e,visible:false,reason:r.reason};let o=Ht(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}},qe=(e,t)=>e.filter(n=>Ve(n,t).visible),Xe=(e,t)=>e.map(n=>Ve(n,t));var Ft="default",Ye=e=>{let t=new Map;for(let n of e){let r=n.group??Ft,o=t.get(r)??[];o.push(n),t.set(r,o);}return [...t.entries()].sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>({name:n,tools:r}))};var J=e=>e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(J).join(",")}]`:`{${Object.keys(e).sort().map(n=>`${JSON.stringify(n)}:${J(e[n])}`).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},n=J(t).length;return {name:e.name,characters:n,tokens:Math.ceil(n/4)}},Qe=e=>{let t=e.map(Kt);return {total:t.reduce((r,o)=>r+o.tokens,0),perTool:t}};var Ze=e=>e.provider?e.provider:(e.doc?.defaultView??(typeof globalThis<"u"?globalThis:null))?.navigator?.modelContext??null,zt=(e,t)=>{let n={name:e.name,invoke:r=>t(e,r)};return e.description!==void 0&&(n.description=e.description),e.inputSchema!==void 0&&(n.inputSchema=e.inputSchema),n},et=(e={})=>{let t=e.invoke??(async(r,o)=>r.execute(o,{identity:null})),n=null;return {publish(r){let o=Ze(e);return o?(n?.revoke(),n=o.provideContext({tools:r.map(i=>zt(i,t))}),{revoked:true}):{revoked:false}},revoke(){n?.revoke(),n=null;},available:()=>!!Ze(e)}};var V=(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 tt=(e,t)=>e===void 0?t:Math.max(0,Math.min(1,e)),q=(e={})=>{let t=tt(e.traceRate,1),n=tt(e.errorRate,1),r=e.random??Math.random;return {shouldKeep(o){let i=o.outcome==="error"?n:t;return r()<i}}};var Jt="[REDACTED]",Vt=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[n,...r]=t;if(!n)return;if(Array.isArray(e)){for(let i of e)X(i,t);return}let o=e;if(n in o){if(r.length===0){o[n]=Jt;return}X(o[n],r);}},Y=(e,t=[])=>{if(t.length===0)return e;let n=Vt(e);for(let r of t)X(n,r.split(".").filter(Boolean));return n},Q=["metadata.password","metadata.token","metadata.authorization","metadata.cookie"];var Xt=()=>typeof location<"u"&&typeof location.pathname=="string"?location.pathname:void 0,nt=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:n=nt("ses"),scrubPaths:r=Q,exporters:o=[],onExporterError:i,pageProvider:s=Xt,...a})=>{let l=V(t),d=q(a),p=()=>{try{return s()}catch{return}};return {sessionId:n,async emit(g){let u={...g.metadata};if(u.page===void 0){let w=p();w!==void 0&&(u.page=w);}let f=protocol.TraceEvent.parse(Y({id:nt("trc"),siteId:e,sessionId:n,occurredAt:new Date().toISOString(),outcome:g.outcome??"success",...g,metadata:u},r));return d.shouldKeep(f)?(l.add(f),await Promise.all(o.map(async w=>{try{await w.export([f]);}catch(m){i?.(m,w,f);}})),f):null},list:()=>l.list(),clear:()=>l.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:n=fetch})=>({name:"gateway",async export(r){let o={publishableKey:t,events:r};await n(`${e.replace(/\/$/,"")}/v1/traces`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${t}`},body:JSON.stringify(o)});}});var Yt=e=>new Promise(t=>setTimeout(t,e)),re=({url:e,fetcher:t=fetch,maxRetries:n=2,queueLimit:r=500})=>({name:"webhook",async export(o){let s=[...Qt(e),...o].slice(-r),a=0;for(;;){let l=await t(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({events:s})});if(l.ok){rt(e,[]);return}if(a>=n)throw rt(e,s),new Error(`Webhook exporter failed with status ${l.status}.`);a+=1,await Yt(100*a);}}}),ne=e=>`agtx:webhook:${e}`,Qt=e=>{if(typeof window>"u"||!window.localStorage)return [];try{let t=window.localStorage.getItem(ne(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(ne(e));return}window.localStorage.setItem(ne(e),JSON.stringify(t));}catch{}};var it="https://gateway.agentronics.dev",tn=e=>{if(e===void 0)return it;if(e===it)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}`)},nn=e=>{let{publishableKey:t,siteId:n="default",debug:r=false,policies:o=[],trace:i={}}=e,s=tn(e.gatewayUrl),a=protocol.classifyApiKey(t);if(a==="secret")throw new protocol.AgentronicsError("wrong_key_kind","A secret key was passed to Agentronics.init(). Browser code must use a publishable key (agtx_pk_*).");if(a!=="publishable")throw new protocol.AgentronicsError("invalid_api_key",`Agentronics.init() expected a key starting with "${protocol.PUBLISHABLE_KEY_PREFIX}".`);let l=i.enabled??true,d=[...r?[ee()]:[],...i.gateway?[te({gatewayUrl:s,publishableKey:t})]:[],...i.webhookUrl?[re({url:i.webhookUrl})]:[],...i.exporters??[]],p={siteId:n,exporters:l?d:[],onExporterError:(c,y)=>{r&&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),u=c=>{l&&g.emit(c);},f=le(),w={onTrace:u};e.auth!==void 0&&(w.context=e.auth);let m=Te(w),h=Se(),v=Pe(o),A=Re({gatewayUrl:s,siteId:n,publishableKey:t}),k=Ge({onTrace:u}),M={onTrace:u};e.siteMemory!==void 0&&(M.initial=e.siteMemory);let T=Be(M),I=_e({gatewayUrl:s,siteId:n,publishableKey:t}),W=async c=>{let y=Date.now(),x=await ce(c),b=f.preferOver(x);return l&&await g.emit({type:b?"agent.detected":"agent.missed",agent:b,durationMs:Date.now()-y,metadata:{detectedClass:x?.class??null,presented:f.snapshot()!==null}}),h.set(b,"detect"),b},oe=async(c,y={})=>{let x=Date.now(),b=y.identity!==void 0?y.identity:await W(),B=v.evaluate({tool:c,identity:b});return l&&await g.emit({type:"authz.evaluated",tool:c,agent:b,policy:B,outcome:B.decision==="deny"?"blocked":"success",durationMs:Date.now()-x}),B},P=Ke({evaluate:oe,setPolicies:c=>v.set(c),listPolicies:()=>v.list(),onTrace:u});for(let c of e.tools??[])P.register(c);let R=e.progression?ze(e.progression,{onTrace:u}):null,ie=c=>{let y={identity:c};return R&&(y.stage=R.current(),y.enabledStages=R.enabledStages()),y},E=c=>qe(P.list(),ie(c)),se=c=>{if(!R)return;R.notify(c).changed&&G.publish(E(null));},G=et({invoke:async(c,y)=>{let x=await P.execute(c.name,y,null);return se(c.name),x}});return Object.freeze({publishableKey:t,siteId:n,gatewayUrl:s,debug:r,memory:k,siteMemory:T,memoryCache:I,tracer:g,auth:m,agentContext:h,authz:v,policyCache:A,tools:P,progression:R,webmcp:G,detect:W,authenticate:async c=>{let y=await m.authenticate(c);return h.set(y,"authenticate"),y},presentIdentity:c=>{let y=f.present(c);return u({type:"auth.identity_presented",agent:y.identity,metadata:{vendor:y.identity.vendor,class:y.identity.class}}),h.set(y.identity,"declare"),y},clearIdentity:()=>{f.clear(),u({type:"auth.identity_cleared"}),h.set(null,"cleared");},presentedIdentity:()=>f.snapshot(),setPolicies:c=>{v.set(c),u({type:"authz.policies_set",metadata:{count:c.length}});},listPolicies:()=>v.list(),syncPolicies:async()=>{let c=await A.sync();return v.set(c.policies),u({type:"authz.policies_set",metadata:{count:c.policies.length,synced:true}}),c.policies},syncSiteMemory:async()=>{let c=await I.sync();return c.memory&&(T.replace(c.memory),u({type:"memory.updated",metadata:{kind:"site",operation:"sync",etag:c.etag}})),c.memory},provideSiteMemory:c=>T.provide(c),provideForPage:c=>{T.provideForPage(c);},installMemoryDelivery:({metaTags:c=true,overlay:y=false}={})=>{let x=[];return c&&x.push(F({snapshot:T.snapshot()})),y&&x.push(K({snapshot:T.snapshot()})),{uninstall:()=>{x.forEach(b=>b.uninstall());}}},fetchWellKnown:async c=>{let y={};c!==void 0&&(y.origin=c);let x=await z(y);return x&&(T.replace(x),u({type:"memory.updated",metadata:{kind:"site",operation:"wellKnown",origin:c??null}})),x},installDomEnforcer:()=>Ce({policyEngine:v,getIdentity:()=>W({webmcp:{pollMs:0}})}),registerTool:c=>P.register(c),surfaceTools:({identity:c=null}={})=>E(c),explainSurfacing:({identity:c=null}={})=>Xe(P.list(),ie(c)),groupedTools:({identity:c=null}={})=>Ye(E(c)),estimateTokens:({identity:c=null}={})=>Qe(E(c)),publishToWebMcp:({identity:c=null}={})=>{let y=E(c),x=G.publish(y);return y.forEach(b=>{u({type:"tool.surfaced",tool:b.name,metadata:{state:"published",trust:c?.trust??null,group:b.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(`${s.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
|
-
exports.init=
|
|
15
|
+
`,Ve=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}`},z=({doc:e=typeof document>"u"?null:document,snapshot:t,hidden:n=false})=>{if(!e)return {uninstall:()=>{},refresh:()=>{}};let r=e.getElementById(He);return r||(r=e.createElement("div"),r.id=He,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",Vt(n)),r.textContent=Ve(t),{uninstall:()=>{r?.remove();},refresh:i=>{r&&(r.textContent=Ve(i));}}};var Fe="/.well-known/agent-context.json",J=async({origin:e,fetcher:t=fetch,signal:n}={})=>{let r=(e?e.replace(/\/$/,""):typeof window<"u"?window.location.origin:"")+Fe;if(!r.startsWith("http"))return null;let i={headers:{accept:"application/json"}};n!==void 0&&(i.signal=n);let a=await t(r,i);if(!a.ok){if(a.status===404)return null;throw new Error(`well-known agent-context fetch failed with status ${a.status}.`)}let s=await a.json();return protocol.SiteMemory.parse(s)};var ze=({evaluate:e,setPolicies:t,listPolicies:n,onTrace:r,identityResolver:i})=>{let a=new Map,s=new Set,g=o=>{if(!o.authz||!t||!n)return;let y={id:`tool:${o.name}`,tool:o.name,...o.authz,rateLimit:o.rateLimit??o.authz.rateLimit};t([...n().filter(u=>u.id!==y.id),y]);};return {register(o){return a.set(o.name,o),s.delete(o.name),g(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),s.delete(o.name);}},unregister(o){a.delete(o),s.delete(o);},enable(o){!a.has(o)||!s.has(o)||(s.delete(o),r?.({type:"tool.surfaced",tool:o,metadata:{state:"enabled"}}));},disable(o){!a.has(o)||s.has(o)||(s.add(o),r?.({type:"tool.surfaced",tool:o,metadata:{state:"disabled"}}));},isEnabled:o=>a.has(o)&&!s.has(o),list({includeDisabled:o=false}={}){let y=[...a.values()];return o?y:y.filter(u=>!s.has(u.name))},get:o=>a.get(o),async execute(o,y,u){let p=u===void 0?i?.()??null:u,d=a.get(o);if(!d)throw new Error(`Tool "${o}" is not registered.`);if(s.has(o)){let l={decision:"deny",ruleId:`tool:${o}`,reason:"Tool is disabled."};throw r?.({type:"tool.executed",tool:o,agent:p,policy:l,outcome:"blocked"}),new Error(l.reason)}let h=await e(o,{identity:p});if(h.decision==="deny")throw r?.({type:"tool.executed",tool:o,agent:p,policy:h,outcome:"blocked"}),new Error(h.reason);let w=Date.now();try{let l=await d.execute(y,{identity:p});return r?.({type:"tool.executed",tool:o,agent:p,policy:h,outcome:"success",durationMs:Date.now()-w}),l}catch(l){throw r?.({type:"tool.executed",tool:o,agent:p,policy:h,outcome:"error",durationMs:Date.now()-w,error:l instanceof Error?l.message:String(l)}),l}}}};var zt=e=>{let t={name:e.name,description:e.description??"",inputSchema:e.inputSchema??{},tokens:0};return e.group&&(t.group=e.group),e.stage&&(t.page=e.stage),e.outputSchema&&(t.outputSchema=e.outputSchema),t.tokens=Math.ceil(JSON.stringify({name:t.name,description:t.description,inputSchema:t.inputSchema,...t.outputSchema?{outputSchema:t.outputSchema}:{}}).length/4),t},Je=({gatewayUrl:e,siteId:t,publishableKey:n,fetcher:r=fetch})=>({async push(i){let a=i.map(zt),s=await r(`${e.replace(/\/$/,"")}/v1/sites/${encodeURIComponent(t)}/tools`,{method:"PUT",headers:{authorization:`Bearer ${n}`,"content-type":"application/json"},body:JSON.stringify({registry:{tools:a}})});if(!s.ok)throw new Error(`Tool sync failed with status ${s.status}.`);return a.length}});var qe=(e,t={})=>{let n=new Map;for(let s of e.stages)n.set(s.name,s);if(!n.has(e.initial))throw new Error(`Initial stage "${e.initial}" is not declared in progression stages.`);let r=e.initial,i=()=>{let s=n.get(r);return s?.enables?[r,...s.enables]:[r]},a=(s,g)=>{let o=r;if(!n.has(s))throw new Error(`Cannot transition to unknown stage "${s}".`);return s===r?{changed:false,from:o,to:s}:(r=s,t.onTrace?.({type:"tool.progressed",metadata:{from:o,to:s,trigger:g}}),{changed:true,from:o,to:s})};return {current:()=>r,enabledStages:()=>i(),notify(s){let o=n.get(r)?.transitions?.find(y=>y.on===s);return o?a(o.to,s):{changed:false,from:r,to:r}},set(s){return a(s,"manual")},reset(){let s=r;r=e.initial,s!==r&&t.onTrace?.({type:"tool.progressed",metadata:{from:s,to:r,trigger:"reset"}});},snapshot:()=>({current:r,enabled:i()})}};var Jt=(e,t)=>{let n=e.authz?.minTrust;return n?t?protocol.TRUST_RANK[t.trust]<protocol.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"}},qt=(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("|")}`}},Xt=(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"},Ye=(e,t)=>{let n=Jt(e,t.identity);if(!n.ok)return {tool:e,visible:false,reason:n.reason};let r=qt(e,t.identity);if(!r.ok)return {tool:e,visible:false,reason:r.reason};let i=Xt(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}},Qe=(e,t)=>e.filter(n=>Ye(n,t).visible),Ze=(e,t)=>e.map(n=>Ye(n,t));var Yt="default",et=e=>{let t=new Map;for(let n of e){let r=n.group??Yt,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}))};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(",")}}`,Qt=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},n=q(t).length;return {name:e.name,characters:n,tokens:Math.ceil(n/4)}},tt=e=>{let t=e.map(Qt);return {total:t.reduce((r,i)=>r+i.tokens,0),perTool:t}};var nt=e=>{if(e.provider)return e.provider;let n=(e.doc?.defaultView??(typeof globalThis<"u"?globalThis:null))?.navigator?.modelContext;return !n||typeof n.provideContext!="function"?null:n},Zt=(e,t)=>{let n={name:e.name,invoke:r=>t(e,r)};return e.description!==void 0&&(n.description=e.description),e.inputSchema!==void 0&&(n.inputSchema=e.inputSchema),n},rt=(e={})=>{let t=e.invoke??(async(r,i)=>r.execute(i,{identity:null})),n=null;return {publish(r){let i=nt(e);return i?(n?.revoke(),n=i.provideContext({tools:r.map(a=>Zt(a,t))}),{revoked:true}):{revoked:false}},revoke(){n?.revoke(),n=null;},available:()=>!!nt(e)}};var X=(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 ot=(e,t)=>e===void 0?t:Math.max(0,Math.min(1,e)),Y=(e={})=>{let t=ot(e.traceRate,1),n=ot(e.errorRate,1),r=e.random??Math.random;return {shouldKeep(i){let a=i.outcome==="error"?n:t;return r()<a}}};var en="[REDACTED]",tn=e=>{if(e!==void 0)return JSON.parse(JSON.stringify(e))},Q=(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 a of e)Q(a,t);return}let i=e;if(n in i){if(r.length===0){i[n]=en;return}Q(i[n],r);}},Z=(e,t=[])=>{if(t.length===0)return e;let n=tn(e);for(let r of t)Q(n,r.split(".").filter(Boolean));return n},ee=["metadata.password","metadata.token","metadata.authorization","metadata.cookie"];var rn=()=>typeof location<"u"&&typeof location.pathname=="string"?location.pathname:void 0,it=e=>{let t=globalThis.crypto;return t&&"randomUUID"in t?`${e}_${t.randomUUID()}`:`${e}_${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`},te=({siteId:e,bufferSize:t,sessionId:n=it("ses"),scrubPaths:r=ee,exporters:i=[],onExporterError:a,pageProvider:s=rn,...g})=>{let o=X(t),y=Y(g),u=()=>{try{return s()}catch{return}};return {sessionId:n,async emit(p){let d={...p.metadata};if(d.page===void 0){let w=u();w!==void 0&&(d.page=w);}let h=protocol.TraceEvent.parse(Z({id:it("trc"),siteId:e,sessionId:n,occurredAt:new Date().toISOString(),outcome:p.outcome??"success",...p,metadata:d},r));return y.shouldKeep(h)?(o.add(h),await Promise.all(i.map(async w=>{try{await w.export([h]);}catch(l){a?.(l,w,h);}})),h):null},list:()=>o.list(),clear:()=>o.clear()}};var ne=()=>({name:"console",export(e){for(let t of e)console.info("[agentronics:trace]",t.type,t);}});var re=({gatewayUrl:e,publishableKey:t,fetcher:n=fetch})=>({name:"gateway",async export(r){let i={publishableKey:t,events:r};await n(`${e.replace(/\/$/,"")}/v1/traces`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${t}`},body:JSON.stringify(i)});}});var on=e=>new Promise(t=>setTimeout(t,e)),ie=({url:e,fetcher:t=fetch,maxRetries:n=2,queueLimit:r=500})=>({name:"webhook",async export(i){let s=[...sn(e),...i].slice(-r),g=0;for(;;){let o=await t(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({events:s})});if(o.ok){st(e,[]);return}if(g>=n)throw st(e,s),new Error(`Webhook exporter failed with status ${o.status}.`);g+=1,await on(100*g);}}}),oe=e=>`agtx:webhook:${e}`,sn=e=>{if(typeof window>"u"||!window.localStorage)return [];try{let t=window.localStorage.getItem(oe(e));return t?JSON.parse(t):[]}catch{return []}},st=(e,t)=>{if(!(typeof window>"u"||!window.localStorage))try{if(t.length===0){window.localStorage.removeItem(oe(e));return}window.localStorage.setItem(oe(e),JSON.stringify(t));}catch{}};var ct="https://gateway.agentronics.dev",ln=e=>{if(e===void 0)return ct;if(e===ct)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}`)},un=e=>{let{publishableKey:t,siteId:n="default",debug:r=false,policies:i=[],trace:a={}}=e,s=ln(e.gatewayUrl),g=protocol.classifyApiKey(t);if(g==="secret")throw new protocol.AgentronicsError("wrong_key_kind","A secret key was passed to Agentronics.init(). Browser code must use a publishable key (agtx_pk_*).");if(g!=="publishable")throw new protocol.AgentronicsError("invalid_api_key",`Agentronics.init() expected a key starting with "${protocol.PUBLISHABLE_KEY_PREFIX}".`);let o=a.enabled??true,y=[...r?[ne()]:[],...a.gateway?[re({gatewayUrl:s,publishableKey:t})]:[],...a.webhookUrl?[ie({url:a.webhookUrl})]:[],...a.exporters??[]],u={siteId:n,exporters:o?y:[],onExporterError:(c,m)=>{r&&console.warn(`[agentronics] trace exporter "${m.name}" failed`,c);}};a.bufferSize!==void 0&&(u.bufferSize=a.bufferSize),a.traceRate!==void 0&&(u.traceRate=a.traceRate),a.errorRate!==void 0&&(u.errorRate=a.errorRate),a.scrubPaths!==void 0&&(u.scrubPaths=a.scrubPaths);let p=te(u),d=c=>{o&&p.emit(c);},h=de(),w={onTrace:d};e.auth!==void 0&&(w.context=e.auth);let l=Ae(w),v=ke(),x=Ee(i),k=Oe({gatewayUrl:s,siteId:n,publishableKey:t}),M=Ge({onTrace:d}),R={onTrace:d};e.siteMemory!==void 0&&(R.initial=e.siteMemory);let T=Be(R),P=Ke({gatewayUrl:s,siteId:n,publishableKey:t}),lt=Je({gatewayUrl:s,siteId:n,publishableKey:t}),j=async c=>{let m=Date.now(),S=await ue(c),b=h.preferOver(S);return o&&await p.emit({type:b?"agent.detected":"agent.missed",agent:b,durationMs:Date.now()-m,metadata:{detectedClass:S?.class??null,presented:h.snapshot()!==null}}),v.set(b,"detect"),b},se=async(c,m={})=>{let S=Date.now(),b=m.identity!==void 0?m.identity:await j(),B=x.evaluate({tool:c,identity:b});return o&&await p.emit({type:"authz.evaluated",tool:c,agent:b,policy:B,outcome:B.decision==="deny"?"blocked":"success",durationMs:Date.now()-S}),B},I=ze({evaluate:se,setPolicies:c=>x.set(c),listPolicies:()=>x.list(),onTrace:d,identityResolver:()=>v.snapshot().identity});for(let c of e.tools??[])I.register(c);let E=e.progression?qe(e.progression,{onTrace:d}):null,ae=c=>{let m={identity:c};return E&&(m.stage=E.current(),m.enabledStages=E.enabledStages()),m},O=c=>Qe(I.list(),ae(c)),ce=c=>{if(!E)return;E.notify(c).changed&&D.publish(O(v.snapshot().identity));},ut={class:"webmcp",trust:"detected",confidence:1,vendor:null,userAgent:typeof navigator<"u"?navigator.userAgent:null,detectionVersion:f,signals:{source:"navigator.modelContext"}},D=rt({invoke:async(c,m)=>{let S=v.snapshot().identity??ut,b=await I.execute(c.name,m,S);return ce(c.name),b}});v.subscribe(c=>{D.available()&&D.publish(O(c.identity));});let G=e.autoDetect??true,dt=G===false?Promise.resolve(null):(async()=>{let c=G===true?{}:G;try{return await j(c)}catch(m){return r&&console.warn("[agentronics] autoDetect failed:",m),null}})();return Object.freeze({publishableKey:t,siteId:n,gatewayUrl:s,debug:r,memory:M,siteMemory:T,memoryCache:P,tracer:p,auth:l,agentContext:v,authz:x,policyCache:k,tools:I,progression:E,webmcp:D,ready:dt,detect:j,authenticate:async c=>{let m=await l.authenticate(c);return v.set(m,"authenticate"),m},presentIdentity:c=>{let m=h.present(c);return d({type:"auth.identity_presented",agent:m.identity,metadata:{vendor:m.identity.vendor,class:m.identity.class}}),v.set(m.identity,"declare"),m},clearIdentity:()=>{h.clear(),d({type:"auth.identity_cleared"}),v.set(null,"cleared");},presentedIdentity:()=>h.snapshot(),setPolicies:c=>{x.set(c),d({type:"authz.policies_set",metadata:{count:c.length}});},listPolicies:()=>x.list(),syncPolicies:async()=>{let c=await k.sync();return x.set(c.policies),d({type:"authz.policies_set",metadata:{count:c.policies.length,synced:true}}),c.policies},syncSiteMemory:async()=>{let c=await P.sync();return c.memory&&(T.replace(c.memory),d({type:"memory.updated",metadata:{kind:"site",operation:"sync",etag:c.etag}})),c.memory},provideSiteMemory:c=>T.provide(c),provideForPage:c=>{T.provideForPage(c);},installMemoryDelivery:({metaTags:c=true,overlay:m=false}={})=>{let S=[];return c&&S.push(F({snapshot:T.snapshot()})),m&&S.push(z({snapshot:T.snapshot()})),{uninstall:()=>{S.forEach(b=>b.uninstall());}}},fetchWellKnown:async c=>{let m={};c!==void 0&&(m.origin=c);let S=await J(m);return S&&(T.replace(S),d({type:"memory.updated",metadata:{kind:"site",operation:"wellKnown",origin:c??null}})),S},installDomEnforcer:()=>Ce({policyEngine:x,getIdentity:()=>j({webmcp:{pollMs:0}})}),registerTool:c=>I.register(c),syncTools:async()=>{let c=I.list({includeDisabled:true}),m=await lt.push(c);return d({type:"tool.registered",metadata:{operation:"sync",count:m}}),m},surfaceTools:({identity:c=null}={})=>O(c),explainSurfacing:({identity:c=null}={})=>Ze(I.list(),ae(c)),groupedTools:({identity:c=null}={})=>et(O(c)),estimateTokens:({identity:c=null}={})=>tt(O(c)),publishToWebMcp:({identity:c=null}={})=>{let m=O(c),S=D.publish(m);return m.forEach(b=>{d({type:"tool.surfaced",tool:b.name,metadata:{state:"published",trust:c?.trust??null,group:b.group??null}});}),{revoked:S.revoked,surfaced:m.length}},notifyToolInvoked:c=>ce(c),evaluate:se,traces:()=>p.list(),clearTraces:()=>p.clear(),async ping(){try{let c=await fetch(`${s.replace(/\/$/,"")}/v1/health`,{method:"GET",headers:{authorization:`Bearer ${t}`}});if(!c.ok)return {ok:!1,status:c.status,error:`gateway returned ${c.status}`};let m=await c.json().catch(()=>null)??{};return {ok:!0,status:c.status,body:m}}catch(c){return {ok:false,status:0,error:c instanceof Error?c.message:String(c)}}}})};
|
|
16
|
+
exports.init=un;//# sourceMappingURL=init-only.cjs.map
|
|
17
17
|
//# sourceMappingURL=init-only.cjs.map
|