@techdigger/humanode-agentlink 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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/index.ts","../../src/types.ts","../../src/schema.ts","../../src/declare.ts","../../src/server.ts","../../src/parse.ts","../../src/validate.ts","../../src/evm.ts","../../src/viem-client.ts","../../src/verify.ts","../../src/biomapper-registry.ts","../../src/biomapper.ts","../../src/biomapper-query.ts","../../src/link-consent.ts","../../src/storage.ts","../../src/hooks.ts","../../src/link-session.ts","../../src/biomapper-link.ts","../../src/webhooks.ts","../../src/hono.ts","../../src/next.ts"],"sourcesContent":["// Constants\nexport { AGENTLINK, AgentLinkPayloadSchema } from './types'\n\n// Types\nexport type {\n\tAgentLinkEntitlement,\n\tAgentLinkExtension,\n\tAgentLinkExtensionInfo,\n\tAgentLinkExtensionSchema,\n\tAgentLinkMode,\n\tAgentLinkPayload,\n\tAgentLinkUsageContext,\n\tCompleteAgentLinkInfo,\n\tDeclareAgentLinkOptions,\n\tSignatureScheme,\n\tSignatureType,\n\tAgentLinkValidationResult,\n\tAgentLinkValidationOptions,\n\tAgentLinkVerifyResult,\n\tSupportedChain,\n} from './types'\n\n// Server\nexport { declareAgentLinkExtension } from './declare'\nexport { agentlinkResourceServerExtension } from './server'\nexport { parseAgentLinkHeader } from './parse'\nexport { validateAgentLinkMessage } from './validate'\nexport { verifyAgentLinkSignature } from './verify'\nexport { buildAgentLinkSchema } from './schema'\n\n// Chain utilities - EVM\nexport { formatSIWEMessage, verifyEVMSignature, extractEVMChainId } from './evm'\n\n// Biomapper registry\nexport {\n\tcreateBiomapperRegistryVerifier,\n\ttype BiomapperAgentStatus,\n\ttype BiomapperRegistryOptions,\n\ttype BiomapperRegistryNetwork,\n\ttype BiomapperRegistryVerifier,\n\tBIOMAPPER_AGENT_REGISTRY_ABI,\n} from './biomapper-registry'\n\n// Biomapper network metadata\nexport {\n\tBIOMAPPER_APP_URLS,\n\tBRIDGED_BIOMAPPER_ADDRESSES,\n\tBRIDGED_BIOMAPPER_READ_ABI,\n\ttype BiomapperBridgeNetwork,\n} from './biomapper'\n\n// Biomapper read-only query client\nexport {\n\tBiomapperNetworkSchema,\n\tBiomapperQueryError,\n\tCHECK_AGENT_STATUS_TOOL_DESCRIPTION,\n\tCHECK_AGENT_STATUS_TOOL_NAME,\n\tCheckAgentStatusInputSchema,\n\tCheckAgentStatusResultSchema,\n\tGET_BIOMAPPER_INFO_TOOL_DESCRIPTION,\n\tGET_BIOMAPPER_INFO_TOOL_NAME,\n\tGET_CURRENT_GENERATION_TOOL_DESCRIPTION,\n\tGET_CURRENT_GENERATION_TOOL_NAME,\n\tGetBiomapperInfoInputSchema,\n\tGetBiomapperInfoResultSchema,\n\tGetCurrentGenerationInputSchema,\n\tGetCurrentGenerationResultSchema,\n\tcreateBiomapperQueryClient,\n\ttype BiomapperNetworkInfo,\n\ttype BiomapperQueryClient,\n\ttype BiomapperQueryErrorCode,\n\ttype BiomapperQueryNetwork,\n\ttype CheckAgentStatusInput,\n\ttype CheckAgentStatusResult,\n\ttype CreateBiomapperQueryClientOptions,\n\ttype GetBiomapperInfoInput,\n\ttype GetBiomapperInfoResult,\n\ttype GetCurrentGenerationInput,\n\ttype GetCurrentGenerationResult,\n} from './biomapper-query'\n\n// Link consent\nexport {\n\tAGENT_LINK_TYPES,\n\tBIOMAPPER_AGENT_REGISTRY_NAME,\n\tBIOMAPPER_AGENT_REGISTRY_VERSION,\n\tbuildAgentLinkTypedData,\n\tcreateAgentLinkConsent,\n\ttype AgentLinkAuthorization,\n\ttype AgentLinkConsentClient,\n\ttype AgentLinkConsentOutput,\n\ttype AgentLinkConsentSigner,\n\ttype CreateAgentLinkConsentOptions,\n} from './link-consent'\n\n// Storage\nexport { InMemoryAgentLinkStorage, buildAgentLinkUsageKey, type AgentLinkStorage } from './storage'\n\n// Hooks\nexport {\n\tcreateAgentLinkHooks,\n\ttype AgentLinkEntitlementContext,\n\ttype AgentLinkEntitlementResolver,\n\ttype AgentLinkHookEvent,\n\ttype CreateAgentLinkHooksOptions,\n\ttype ResolveAgentLinkEntitlementInput,\n} from './hooks'\n\n// Link sessions\nexport {\n\tbuildEmbeddedHostedLinkUrl,\n\tInMemoryLinkSessionStore,\n\tbuildHostedLinkUrl,\n\tcreateLinkSession,\n\tdecodeLinkSession,\n\tencodeLinkSession,\n\tgetLinkSession,\n\tvalidateLinkSession,\n\ttype AgentLinkSession,\n\ttype AgentLinkSessionBranding,\n\ttype AgentLinkSessionStore,\n\ttype CreateLinkSessionInput,\n\ttype CreateLinkSessionOptions,\n\ttype LinkSessionValidationOptions,\n\ttype LinkSessionValidationResult,\n} from './link-session'\n\n// High-level facade\nexport {\n\tcreateBiomapperLink,\n\ttype AgentLinkMiddleware,\n\ttype BiomapperLink,\n\ttype BiomapperLinkControlSurface,\n\ttype BiomapperLinkOptions,\n\ttype BiomapperLinkProtectedRoute,\n\ttype BiomapperLinkSchemeRegistration,\n} from './biomapper-link'\n\n// Framework adapters\nexport { createNextPaymentHandlerFromHTTPServer, type NextPaymentMiddleware, type NextRouteHandler } from './next'\nexport { createHonoPaymentMiddlewareFromHTTPServer, type HonoLikeMiddleware, type HonoPaymentMiddleware } from './hono'\n\n// Events and webhooks\nexport type { AgentLinkEvent, AgentLinkEventHandler, AgentLinkSessionEvent } from './events'\nexport {\n\tcreateAgentLinkWebhookDispatcher,\n\tcreateAgentLinkWebhookEnvelope,\n\tdispatchAgentLinkWebhook,\n\tverifyAgentLinkWebhookSignature,\n\ttype AgentLinkWebhookDispatcherOptions,\n\ttype AgentLinkWebhookEnvelope,\n\ttype AgentLinkWebhookSignatureVerificationResult,\n\ttype VerifyAgentLinkWebhookSignatureOptions,\n} from './webhooks'\n","import { z } from 'zod'\n\nexport const AGENTLINK = 'agentlink'\n\nexport type SignatureScheme = 'eip191' | 'eip1271'\n\nexport type SignatureType = 'eip191' | 'eip1271'\n\nexport interface SupportedChain {\n\tchainId: string\n\ttype: SignatureType\n\tsignatureScheme?: SignatureScheme\n}\n\nexport interface AgentLinkExtensionInfo {\n\tdomain: string\n\turi: string\n\tstatement?: string\n\tversion: string\n\tnonce: string\n\tissuedAt: string\n\texpirationTime?: string\n\tnotBefore?: string\n\trequestId?: string\n\tresources?: string[]\n}\n\nexport interface AgentLinkExtensionSchema {\n\t$schema: string\n\ttype: 'object'\n\tproperties: {\n\t\tdomain: { type: 'string' }\n\t\taddress: { type: 'string' }\n\t\tstatement?: { type: 'string' }\n\t\turi: { type: 'string'; format: 'uri' }\n\t\tversion: { type: 'string' }\n\t\tchainId: { type: 'string' }\n\t\ttype: { type: 'string' }\n\t\tnonce: { type: 'string' }\n\t\tissuedAt: { type: 'string'; format: 'date-time' }\n\t\texpirationTime?: { type: 'string'; format: 'date-time' }\n\t\tnotBefore?: { type: 'string'; format: 'date-time' }\n\t\trequestId?: { type: 'string' }\n\t\tresources?: { type: 'array'; items: { type: 'string'; format: 'uri' } }\n\t\tsignature: { type: 'string' }\n\t}\n\trequired: string[]\n}\n\nexport interface AgentLinkExtension {\n\tinfo: AgentLinkExtensionInfo\n\tsupportedChains: SupportedChain[]\n\tschema: AgentLinkExtensionSchema\n\tmode?: AgentLinkMode\n}\n\nexport interface AgentLinkUsageContext {\n\tplatformAccountId?: string\n\tworkspaceId?: string\n}\n\nexport interface AgentLinkEntitlement extends AgentLinkUsageContext {\n\tendpoint: string\n\towner: string\n\tgenerationPtr: bigint\n}\n\nexport const AgentLinkPayloadSchema = z.object({\n\tdomain: z.string(),\n\taddress: z.string(),\n\tstatement: z.string().optional(),\n\turi: z.string(),\n\tversion: z.string(),\n\tchainId: z.string(),\n\ttype: z.enum(['eip191', 'eip1271']),\n\tnonce: z.string(),\n\tissuedAt: z.string(),\n\texpirationTime: z.string().optional(),\n\tnotBefore: z.string().optional(),\n\trequestId: z.string().optional(),\n\tresources: z.array(z.string()).optional(),\n\tsignatureScheme: z.enum(['eip191', 'eip1271']).optional(),\n\tsignature: z.string(),\n})\n\nexport type AgentLinkPayload = z.infer<typeof AgentLinkPayloadSchema>\n\nexport type AgentLinkMode =\n\t| { type: 'linked-only'; reason?: string }\n\t| { type: 'free' }\n\t| { type: 'free-trial'; uses?: number }\n\t| { type: 'discount'; percent: number; uses?: number }\n\nexport interface DeclareAgentLinkOptions {\n\tdomain?: string\n\tresourceUri?: string\n\tstatement?: string\n\tversion?: string\n\tnetwork?: string | string[]\n\texpirationSeconds?: number\n\tmode?: AgentLinkMode\n}\n\nexport interface AgentLinkValidationResult {\n\tvalid: boolean\n\terror?: string\n}\n\nexport interface AgentLinkValidationOptions {\n\tmaxAge?: number\n\tcheckNonce?: (nonce: string) => boolean | Promise<boolean>\n}\n\nexport interface AgentLinkVerifyResult {\n\tvalid: boolean\n\taddress?: string\n\terror?: string\n}\n\nexport type CompleteAgentLinkInfo = AgentLinkExtensionInfo & {\n\tchainId: string\n\ttype: SignatureType\n\tsignatureScheme?: SignatureScheme\n}\n","import type { AgentLinkExtensionSchema } from './types'\n\nexport function buildAgentLinkSchema(): AgentLinkExtensionSchema {\n\treturn {\n\t\t$schema: 'https://json-schema.org/draft/2020-12/schema',\n\t\ttype: 'object',\n\t\tproperties: {\n\t\t\tdomain: { type: 'string' },\n\t\t\taddress: { type: 'string' },\n\t\t\tstatement: { type: 'string' },\n\t\t\turi: { type: 'string', format: 'uri' },\n\t\t\tversion: { type: 'string' },\n\t\t\tchainId: { type: 'string' },\n\t\t\ttype: { type: 'string' },\n\t\t\tnonce: { type: 'string' },\n\t\t\tissuedAt: { type: 'string', format: 'date-time' },\n\t\t\texpirationTime: { type: 'string', format: 'date-time' },\n\t\t\tnotBefore: { type: 'string', format: 'date-time' },\n\t\t\trequestId: { type: 'string' },\n\t\t\tresources: { type: 'array', items: { type: 'string', format: 'uri' } },\n\t\t\tsignature: { type: 'string' },\n\t\t},\n\t\trequired: ['domain', 'address', 'uri', 'version', 'chainId', 'type', 'nonce', 'issuedAt', 'signature'],\n\t}\n}\n","import { AGENTLINK } from './types'\nimport { buildAgentLinkSchema } from './schema'\nimport type { AgentLinkExtension, AgentLinkExtensionInfo, DeclareAgentLinkOptions, SupportedChain } from './types'\n\nexport function getSignatureTypes(network: string) {\n\tif (!network.startsWith('eip155:')) {\n\t\tthrow new Error(`Biomapper-backed AgentLink only supports EVM networks. Received \"${network}\".`)\n\t}\n\treturn ['eip191', 'eip1271'] as const\n}\n\nexport interface AgentLinkDeclaration extends AgentLinkExtension {\n\t_options: DeclareAgentLinkOptions\n}\n\nexport function declareAgentLinkExtension(options: DeclareAgentLinkOptions = {}): Record<string, AgentLinkDeclaration> {\n\tconst info: Partial<AgentLinkExtensionInfo> & { version: string } = {\n\t\tversion: options.version ?? '1',\n\t}\n\n\tif (options.domain) {\n\t\tinfo.domain = options.domain\n\t}\n\tif (options.resourceUri) {\n\t\tinfo.uri = options.resourceUri\n\t\tinfo.resources = [options.resourceUri]\n\t}\n\tif (options.statement) {\n\t\tinfo.statement = options.statement\n\t}\n\n\tlet supportedChains: SupportedChain[] = []\n\tif (options.network) {\n\t\tconst networks = Array.isArray(options.network) ? options.network : [options.network]\n\t\tsupportedChains = networks.flatMap(network =>\n\t\t\tgetSignatureTypes(network).map(type => ({\n\t\t\t\tchainId: network,\n\t\t\t\ttype,\n\t\t\t}))\n\t\t)\n\t}\n\n\tconst declaration: AgentLinkDeclaration = {\n\t\tinfo: info as AgentLinkExtensionInfo,\n\t\tsupportedChains,\n\t\tschema: buildAgentLinkSchema(),\n\t\t_options: options,\n\t}\n\n\treturn { [AGENTLINK]: declaration }\n}\n","import { AGENTLINK } from './types'\nimport { randomBytes } from 'crypto'\nimport { buildAgentLinkSchema } from './schema'\nimport { getSignatureTypes, type AgentLinkDeclaration } from './declare'\nimport type { ResourceServerExtension, PaymentRequiredContext } from '@x402/core/types'\nimport type { AgentLinkExtension, AgentLinkExtensionInfo, SupportedChain, DeclareAgentLinkOptions } from './types'\n\nexport const agentlinkResourceServerExtension: ResourceServerExtension = {\n\tkey: AGENTLINK,\n\n\tenrichPaymentRequiredResponse: async (\n\t\tdeclaration: unknown,\n\t\tcontext: PaymentRequiredContext\n\t): Promise<AgentLinkExtension> => {\n\t\tconst decl = declaration as AgentLinkDeclaration\n\t\tconst opts: DeclareAgentLinkOptions = decl._options ?? {}\n\n\t\tconst resourceUri = opts.resourceUri ?? context.resourceInfo.url\n\n\t\tlet domain = opts.domain\n\t\tif (!domain && resourceUri) {\n\t\t\ttry {\n\t\t\t\tdomain = new URL(resourceUri).hostname\n\t\t\t} catch {\n\t\t\t\t// leave domain undefined\n\t\t\t}\n\t\t}\n\n\t\tlet networks: string[]\n\t\tif (opts.network) {\n\t\t\tnetworks = Array.isArray(opts.network) ? opts.network : [opts.network]\n\t\t} else {\n\t\t\tnetworks = [...new Set(context.requirements.map(r => r.network))]\n\t\t}\n\n\t\tconst nonce = randomBytes(16).toString('hex')\n\t\tconst issuedAt = new Date().toISOString()\n\n\t\tconst expirationSeconds = opts.expirationSeconds\n\t\tconst expirationTime =\n\t\t\texpirationSeconds !== undefined ? new Date(Date.now() + expirationSeconds * 1000).toISOString() : undefined\n\n\t\tconst info: AgentLinkExtensionInfo = {\n\t\t\tdomain: domain ?? '',\n\t\t\turi: resourceUri,\n\t\t\tversion: opts.version ?? '1',\n\t\t\tnonce,\n\t\t\tissuedAt,\n\t\t\tresources: [resourceUri],\n\t\t}\n\n\t\tif (expirationTime) {\n\t\t\tinfo.expirationTime = expirationTime\n\t\t}\n\t\tif (opts.statement) {\n\t\t\tinfo.statement = opts.statement\n\t\t}\n\n\t\tconst supportedChains: SupportedChain[] = networks.flatMap(network =>\n\t\t\tgetSignatureTypes(network).map(type => ({\n\t\t\t\tchainId: network,\n\t\t\t\ttype,\n\t\t\t}))\n\t\t)\n\n\t\treturn {\n\t\t\tinfo,\n\t\t\tsupportedChains,\n\t\t\tschema: buildAgentLinkSchema(),\n\t\t\t...(opts.mode ? { mode: opts.mode } : {}),\n\t\t}\n\t},\n}\n","import { AgentLinkPayloadSchema, type AgentLinkPayload } from './types'\nimport { Base64EncodedRegex, safeBase64Decode } from '@x402/core/utils'\n\nexport function parseAgentLinkHeader(header: string): AgentLinkPayload {\n\tif (!Base64EncodedRegex.test(header)) {\n\t\tthrow new Error('Invalid agentlink header: not valid base64')\n\t}\n\n\tconst jsonStr = safeBase64Decode(header)\n\n\tlet rawPayload: unknown\n\ttry {\n\t\trawPayload = JSON.parse(jsonStr)\n\t} catch (error) {\n\t\tif (error instanceof SyntaxError) {\n\t\t\tthrow new Error('Invalid agentlink header: not valid JSON')\n\t\t}\n\t\tthrow error\n\t}\n\n\tconst parsed = AgentLinkPayloadSchema.safeParse(rawPayload)\n\n\tif (!parsed.success) {\n\t\tconst issues = parsed.error.issues.map(i => `${i.path.join('.')}: ${i.message}`).join(', ')\n\t\tthrow new Error(`Invalid agentlink header: ${issues}`)\n\t}\n\n\treturn parsed.data\n}\n","import type { AgentLinkPayload, AgentLinkValidationResult, AgentLinkValidationOptions } from './types'\n\nconst DEFAULT_MAX_AGE_MS = 5 * 60 * 1000\n\nfunction normalizeComparableUrl(input: string): { host: string; pathname: string; search: string } {\n\tconst url = new URL(input)\n\treturn {\n\t\thost: url.host,\n\t\tpathname: url.pathname,\n\t\tsearch: url.search,\n\t}\n}\n\nexport async function validateAgentLinkMessage(\n\tmessage: AgentLinkPayload,\n\texpectedResourceUri: string,\n\toptions: AgentLinkValidationOptions = {}\n): Promise<AgentLinkValidationResult> {\n\tconst expectedUrl = new URL(expectedResourceUri)\n\tconst expectedResource = normalizeComparableUrl(expectedResourceUri)\n\tconst maxAge = options.maxAge ?? DEFAULT_MAX_AGE_MS\n\n\tif (message.domain !== expectedUrl.hostname) {\n\t\treturn {\n\t\t\tvalid: false,\n\t\t\terror: `Domain mismatch: expected \"${expectedUrl.hostname}\", got \"${message.domain}\"`,\n\t\t}\n\t}\n\n\tlet messageResource: { host: string; pathname: string; search: string }\n\ttry {\n\t\tmessageResource = normalizeComparableUrl(message.uri)\n\t} catch {\n\t\treturn { valid: false, error: `Invalid URI: \"${message.uri}\"` }\n\t}\n\n\tif (messageResource.host !== expectedResource.host) {\n\t\treturn {\n\t\t\tvalid: false,\n\t\t\terror: `URI host mismatch: expected \"${expectedResource.host}\", got \"${messageResource.host}\"`,\n\t\t}\n\t}\n\n\tif (messageResource.pathname !== expectedResource.pathname) {\n\t\treturn {\n\t\t\tvalid: false,\n\t\t\terror: `URI path mismatch: expected \"${expectedResource.pathname}\", got \"${messageResource.pathname}\"`,\n\t\t}\n\t}\n\n\tif (messageResource.search !== expectedResource.search) {\n\t\treturn {\n\t\t\tvalid: false,\n\t\t\terror: `URI query mismatch: expected \"${expectedResource.search}\", got \"${messageResource.search}\"`,\n\t\t}\n\t}\n\n\tconst issuedAt = new Date(message.issuedAt)\n\tif (isNaN(issuedAt.getTime())) {\n\t\treturn { valid: false, error: 'Invalid issuedAt timestamp' }\n\t}\n\n\tconst age = Date.now() - issuedAt.getTime()\n\tif (age > maxAge) {\n\t\treturn {\n\t\t\tvalid: false,\n\t\t\terror: `Message too old: ${Math.round(age / 1000)}s exceeds ${maxAge / 1000}s limit`,\n\t\t}\n\t}\n\tif (age < 0) {\n\t\treturn { valid: false, error: 'issuedAt is in the future' }\n\t}\n\n\tif (message.expirationTime) {\n\t\tconst expiration = new Date(message.expirationTime)\n\t\tif (isNaN(expiration.getTime())) {\n\t\t\treturn { valid: false, error: 'Invalid expirationTime timestamp' }\n\t\t}\n\t\tif (expiration < new Date()) {\n\t\t\treturn { valid: false, error: 'Message expired' }\n\t\t}\n\t}\n\n\tif (message.notBefore) {\n\t\tconst notBefore = new Date(message.notBefore)\n\t\tif (isNaN(notBefore.getTime())) {\n\t\t\treturn { valid: false, error: 'Invalid notBefore timestamp' }\n\t\t}\n\t\tif (new Date() < notBefore) {\n\t\t\treturn { valid: false, error: 'Message not yet valid (notBefore is in the future)' }\n\t\t}\n\t}\n\n\tif (options.checkNonce) {\n\t\tconst nonceValid = await options.checkNonce(message.nonce)\n\t\tif (!nonceValid) {\n\t\t\treturn { valid: false, error: 'Nonce validation failed (possible replay attack)' }\n\t\t}\n\t}\n\n\treturn { valid: true }\n}\n","import { SiweMessage } from 'siwe'\nimport { getPublicClient } from './viem-client'\nimport type { CompleteAgentLinkInfo } from './types'\n\nexport function extractEVMChainId(chainId: string): number {\n\tconst match = /^eip155:(\\d+)$/.exec(chainId)\n\tif (!match) {\n\t\tthrow new Error(`Invalid EVM chainId format: ${chainId}. Expected eip155:<number>`)\n\t}\n\treturn parseInt(match[1], 10)\n}\n\nexport function formatSIWEMessage(info: CompleteAgentLinkInfo, address: string): string {\n\tconst numericChainId = extractEVMChainId(info.chainId)\n\n\tconst siweMessage = new SiweMessage({\n\t\tdomain: info.domain,\n\t\taddress,\n\t\tstatement: info.statement,\n\t\turi: info.uri,\n\t\tversion: info.version,\n\t\tchainId: numericChainId,\n\t\tnonce: info.nonce,\n\t\tissuedAt: info.issuedAt,\n\t\texpirationTime: info.expirationTime,\n\t\tnotBefore: info.notBefore,\n\t\trequestId: info.requestId,\n\t\tresources: info.resources,\n\t})\n\n\treturn siweMessage.prepareMessage()\n}\n\n/**\n * Verify an EVM signature using ERC-1271 (smart wallets) with ecrecover fallback (EOA).\n * Uses viem's publicClient.verifyMessage which handles both automatically.\n */\nexport async function verifyEVMSignature(\n\tmessage: string,\n\taddress: string,\n\tsignature: string,\n\tchainId: string,\n\trpcUrl?: string\n): Promise<boolean> {\n\tconst numericChainId = extractEVMChainId(chainId)\n\tconst client = getPublicClient(numericChainId, rpcUrl)\n\n\treturn client.verifyMessage({\n\t\taddress: address as `0x${string}`,\n\t\tmessage,\n\t\tsignature: signature as `0x${string}`,\n\t})\n}\n","import * as chains from 'viem/chains'\nimport { createPublicClient, extractChain, http, type PublicClient } from 'viem'\n\nconst allChains = Object.values(chains)\nconst clientCache = new Map<string, PublicClient>()\n\nexport function getPublicClient(numericChainId: number, rpcUrl?: string): PublicClient {\n\tconst cacheKey = `${numericChainId}:${rpcUrl ?? ''}`\n\tlet cached = clientCache.get(cacheKey)\n\tif (cached) return cached\n\n\tlet chain: chains.Chain\n\tif (rpcUrl) {\n\t\tchain = { id: numericChainId } as chains.Chain\n\t} else {\n\t\tchain = extractChain({ chains: allChains, id: numericChainId as (typeof allChains)[number]['id'] })\n\t}\n\n\tcached = createPublicClient({ chain, transport: http(rpcUrl) }) as PublicClient\n\tclientCache.set(cacheKey, cached)\n\treturn cached\n}\n","import { formatSIWEMessage, verifyEVMSignature } from './evm'\nimport type { AgentLinkPayload, AgentLinkVerifyResult } from './types'\n\nexport async function verifyAgentLinkSignature(\n\tpayload: AgentLinkPayload,\n\trpcUrl?: string\n): Promise<AgentLinkVerifyResult> {\n\ttry {\n\t\tif (payload.chainId.startsWith('eip155:')) {\n\t\t\treturn verifyEVMPayload(payload, rpcUrl)\n\t\t}\n\n\t\treturn {\n\t\t\tvalid: false,\n\t\t\terror: `Unsupported chain namespace: ${payload.chainId}. Biomapper-backed AgentLink currently supports EVM chains only.`,\n\t\t}\n\t} catch (error) {\n\t\treturn {\n\t\t\tvalid: false,\n\t\t\terror: error instanceof Error ? error.message : 'Verification failed',\n\t\t}\n\t}\n}\n\nasync function verifyEVMPayload(payload: AgentLinkPayload, rpcUrl?: string): Promise<AgentLinkVerifyResult> {\n\tconst message = formatSIWEMessage(\n\t\t{\n\t\t\tdomain: payload.domain,\n\t\t\turi: payload.uri,\n\t\t\tstatement: payload.statement,\n\t\t\tversion: payload.version,\n\t\t\tchainId: payload.chainId,\n\t\t\ttype: payload.type,\n\t\t\tnonce: payload.nonce,\n\t\t\tissuedAt: payload.issuedAt,\n\t\t\texpirationTime: payload.expirationTime,\n\t\t\tnotBefore: payload.notBefore,\n\t\t\trequestId: payload.requestId,\n\t\t\tresources: payload.resources,\n\t\t},\n\t\tpayload.address\n\t)\n\n\ttry {\n\t\tconst valid = await verifyEVMSignature(message, payload.address, payload.signature, payload.chainId, rpcUrl)\n\n\t\tif (!valid) {\n\t\t\treturn {\n\t\t\t\tvalid: false,\n\t\t\t\terror: `Signature verification failed. The signature does not match the reconstructed SIWE message. Ensure your agent signs exactly this message using EIP-191 (EOA) or ERC-1271 (smart wallet):\\n\\n${message}`,\n\t\t\t}\n\t\t}\n\n\t\treturn { valid: true, address: payload.address }\n\t} catch (error) {\n\t\tconst reason = error instanceof Error ? error.message : 'Unknown error'\n\t\treturn {\n\t\t\tvalid: false,\n\t\t\terror: `Signature verification error: ${reason}. The SIWE message the server reconstructed from your payload:\\n\\n${message}`,\n\t\t}\n\t}\n}\n","import { extractEVMChainId } from './evm'\nimport { getPublicClient } from './viem-client'\nimport { zeroAddress, type PublicClient } from 'viem'\n\nconst BASE_MAINNET = 'eip155:8453' as const\nconst BASE_SEPOLIA = 'eip155:84532' as const\n\ntype KnownChainId = typeof BASE_MAINNET | typeof BASE_SEPOLIA\n\n/**\n * Local-first development intentionally leaves built-in registry deployments\n * empty until contracts are deployed. Pass `contractAddress` explicitly.\n */\nconst KNOWN_DEPLOYMENTS: Partial<Record<KnownChainId, `0x${string}`>> = {}\n\nexport type BiomapperRegistryNetwork = 'base' | 'base-sepolia'\n\nexport interface BiomapperAgentStatus {\n\towner: `0x${string}` | null\n\tgenerationPtr: bigint\n\tactive: boolean\n}\n\nexport const BIOMAPPER_AGENT_REGISTRY_ABI = [\n\t{\n\t\tinputs: [{ internalType: 'address', name: 'agent', type: 'address' }],\n\t\tname: 'agentNonce',\n\t\toutputs: [{ internalType: 'uint256', name: 'nonce', type: 'uint256' }],\n\t\tstateMutability: 'view',\n\t\ttype: 'function',\n\t},\n\t{\n\t\tinputs: [{ internalType: 'address', name: 'agent', type: 'address' }],\n\t\tname: 'getAgentStatus',\n\t\toutputs: [\n\t\t\t{ internalType: 'address', name: 'owner', type: 'address' },\n\t\t\t{ internalType: 'uint256', name: 'generationPtr', type: 'uint256' },\n\t\t\t{ internalType: 'bool', name: 'active', type: 'bool' },\n\t\t],\n\t\tstateMutability: 'view',\n\t\ttype: 'function',\n\t},\n\t{\n\t\tinputs: [{ internalType: 'address', name: 'agent', type: 'address' }],\n\t\tname: 'linkedOwner',\n\t\toutputs: [{ internalType: 'address', name: 'owner', type: 'address' }],\n\t\tstateMutability: 'view',\n\t\ttype: 'function',\n\t},\n\t{\n\t\tinputs: [\n\t\t\t{ internalType: 'address', name: 'agent', type: 'address' },\n\t\t\t{ internalType: 'uint256', name: 'deadline', type: 'uint256' },\n\t\t\t{ internalType: 'bytes', name: 'signature', type: 'bytes' },\n\t\t],\n\t\tname: 'linkAgent',\n\t\toutputs: [],\n\t\tstateMutability: 'nonpayable',\n\t\ttype: 'function',\n\t},\n] as const\n\nexport interface BiomapperRegistryOptions {\n\tclient?: PublicClient\n\tcontractAddress?: `0x${string}`\n\trpcUrl?: string\n\tnetwork?: BiomapperRegistryNetwork\n}\n\nexport function createBiomapperRegistryVerifier(options: BiomapperRegistryOptions = {}) {\n\tfunction resolveLookupChainId(chainId: string): KnownChainId {\n\t\tif (options.network === 'base') return BASE_MAINNET\n\t\tif (options.network === 'base-sepolia') return BASE_SEPOLIA\n\t\tif (chainId === BASE_SEPOLIA) return BASE_SEPOLIA\n\t\treturn BASE_MAINNET\n\t}\n\n\tfunction getClient(chainId: string): PublicClient {\n\t\tif (options.client) return options.client\n\n\t\tconst lookupChainId =\n\t\t\toptions.contractAddress && options.rpcUrl && !options.network ? chainId : resolveLookupChainId(chainId)\n\n\t\treturn getPublicClient(extractEVMChainId(lookupChainId), options.rpcUrl)\n\t}\n\n\tfunction getContractAddress(chainId: string): `0x${string}` | null {\n\t\tif (options.contractAddress) return options.contractAddress\n\t\treturn KNOWN_DEPLOYMENTS[resolveLookupChainId(chainId)] ?? null\n\t}\n\n\treturn {\n\t\tasync getAgentStatus(address: string, chainId: string): Promise<BiomapperAgentStatus | null> {\n\t\t\tif (!chainId.startsWith('eip155:')) return null\n\n\t\t\tconst contractAddress = getContractAddress(chainId)\n\t\t\tif (!contractAddress) return null\n\n\t\t\tconst client = getClient(chainId)\n\n\t\t\ttry {\n\t\t\t\tconst [owner, generationPtr, active] = await client.readContract({\n\t\t\t\t\taddress: contractAddress,\n\t\t\t\t\tabi: BIOMAPPER_AGENT_REGISTRY_ABI,\n\t\t\t\t\tfunctionName: 'getAgentStatus',\n\t\t\t\t\targs: [address as `0x${string}`],\n\t\t\t\t})\n\n\t\t\t\treturn {\n\t\t\t\t\towner: owner === zeroAddress ? null : owner,\n\t\t\t\t\tgenerationPtr,\n\t\t\t\t\tactive,\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\treturn null\n\t\t\t}\n\t\t},\n\t}\n}\n\nexport type BiomapperRegistryVerifier = ReturnType<typeof createBiomapperRegistryVerifier>\n","export type BiomapperBridgeNetwork = 'base' | 'base-sepolia'\n\nexport const BRIDGED_BIOMAPPER_ADDRESSES: Record<BiomapperBridgeNetwork, `0x${string}`> = {\n\tbase: '0x31e98F489ad65dF5Ee43CBe06e4f35557Cd0abb2',\n\t'base-sepolia': '0x16F2a7AC67B6aC1E57dD5528A24b1fC689902Be2',\n}\n\nexport const BIOMAPPER_APP_URLS: Record<BiomapperBridgeNetwork, string> = {\n\tbase: 'https://mainnet.biomapper.hmnd.app/',\n\t'base-sepolia': 'https://testnet5.biomapper.hmnd.app/',\n}\n\nexport const BRIDGED_BIOMAPPER_READ_ABI = [\n\t{\n\t\tinputs: [],\n\t\tname: 'generationsHead',\n\t\toutputs: [{ internalType: 'uint256', name: '', type: 'uint256' }],\n\t\tstateMutability: 'view',\n\t\ttype: 'function',\n\t},\n\t{\n\t\tinputs: [\n\t\t\t{ internalType: 'address', name: 'owner', type: 'address' },\n\t\t\t{ internalType: 'uint256', name: 'generationPtr', type: 'uint256' },\n\t\t],\n\t\tname: 'lookupBiomappingPtr',\n\t\toutputs: [{ internalType: 'uint256', name: '', type: 'uint256' }],\n\t\tstateMutability: 'view',\n\t\ttype: 'function',\n\t},\n] as const\n","import { z } from 'zod'\nimport { getPublicClient } from './viem-client'\nimport { zeroAddress, type PublicClient } from 'viem'\nimport { BIOMAPPER_AGENT_REGISTRY_ABI } from './biomapper-registry'\nimport {\n\tBIOMAPPER_APP_URLS,\n\tBRIDGED_BIOMAPPER_ADDRESSES,\n\tBRIDGED_BIOMAPPER_READ_ABI,\n\ttype BiomapperBridgeNetwork,\n} from './biomapper'\n\nexport const BiomapperNetworkSchema = z.enum(['base', 'base-sepolia'])\nexport type BiomapperQueryNetwork = z.infer<typeof BiomapperNetworkSchema>\n\nconst BiomapperAddressSchema = z.string().regex(/^0x[a-fA-F0-9]{40}$/, 'Expected a 20-byte EVM address.')\n\nconst BiomapperRpcUrlSchema = z.string().url()\n\nconst NETWORK_CHAIN_IDS: Record<BiomapperQueryNetwork, number> = {\n\tbase: 8453,\n\t'base-sepolia': 84532,\n}\n\nconst NETWORK_CAIP2_IDS: Record<BiomapperQueryNetwork, `eip155:${number}`> = {\n\tbase: 'eip155:8453',\n\t'base-sepolia': 'eip155:84532',\n}\n\nexport const CHECK_AGENT_STATUS_TOOL_NAME = 'check_agent_status'\nexport const GET_CURRENT_GENERATION_TOOL_NAME = 'get_current_generation'\nexport const GET_BIOMAPPER_INFO_TOOL_NAME = 'get_biomapper_info'\n\nexport const CHECK_AGENT_STATUS_TOOL_DESCRIPTION =\n\t'Check if an agent wallet is linked to a biomapped human and whether the link is currently active. Returns the owner address, current Biomapper generation pointer, and active status.'\n\nexport const GET_CURRENT_GENERATION_TOOL_DESCRIPTION =\n\t'Get the current Biomapper generation pointer from the Bridged Biomapper contract. Generations represent verification periods — when a generation ends, usage quotas reset.'\n\nexport const GET_BIOMAPPER_INFO_TOOL_DESCRIPTION =\n\t'Get Biomapper network metadata — contract addresses, app URLs, and supported networks. Useful for discovering where to point registry queries or where users can verify their identity.'\n\nexport const CheckAgentStatusInputSchema = z.object({\n\tagentAddress: BiomapperAddressSchema.describe('The agent wallet address (0x...)'),\n\tnetwork: BiomapperNetworkSchema.optional().describe('The network to query'),\n\tregistryAddress: BiomapperAddressSchema.optional().describe('The BiomapperAgentRegistry contract address (0x...)'),\n\trpcUrl: BiomapperRpcUrlSchema.optional().describe('Custom RPC URL (uses public RPC if omitted)'),\n})\n\nexport const GetCurrentGenerationInputSchema = z.object({\n\tnetwork: BiomapperNetworkSchema.optional().describe('The network to query'),\n\trpcUrl: BiomapperRpcUrlSchema.optional().describe('Custom RPC URL (uses public RPC if omitted)'),\n})\n\nexport const GetBiomapperInfoInputSchema = z.object({\n\tnetwork: BiomapperNetworkSchema.optional().describe('Specific network (returns all if omitted)'),\n})\n\nexport const BiomapperNetworkInfoSchema = z.object({\n\tnetwork: BiomapperNetworkSchema,\n\tbridgedBiomapper: BiomapperAddressSchema,\n\tbiomapperAppUrl: z.string().url(),\n\tchainId: z.number().int().positive(),\n\tcaip2: z.string(),\n})\n\nexport const CheckAgentStatusResultSchema = z.object({\n\tlinked: z.boolean(),\n\tactive: z.boolean(),\n\tagentAddress: BiomapperAddressSchema,\n\towner: BiomapperAddressSchema.nullable(),\n\tgenerationPtr: z.string().nullable(),\n\tnetwork: BiomapperNetworkSchema,\n\tmessage: z.string(),\n})\n\nexport const GetCurrentGenerationResultSchema = z.object({\n\tgenerationsHead: z.string(),\n\tnetwork: BiomapperNetworkSchema,\n\tbridgedBiomapper: BiomapperAddressSchema,\n\tbiomapperAppUrl: z.string().url(),\n})\n\nexport const GetBiomapperInfoResultSchema = z.object({\n\tnetworks: z.array(BiomapperNetworkInfoSchema),\n})\n\nexport type CheckAgentStatusInput = z.infer<typeof CheckAgentStatusInputSchema>\nexport type GetCurrentGenerationInput = z.infer<typeof GetCurrentGenerationInputSchema>\nexport type GetBiomapperInfoInput = z.infer<typeof GetBiomapperInfoInputSchema>\nexport type BiomapperNetworkInfo = z.infer<typeof BiomapperNetworkInfoSchema>\nexport type CheckAgentStatusResult = z.infer<typeof CheckAgentStatusResultSchema>\nexport type GetCurrentGenerationResult = z.infer<typeof GetCurrentGenerationResultSchema>\nexport type GetBiomapperInfoResult = z.infer<typeof GetBiomapperInfoResultSchema>\n\nexport type BiomapperQueryErrorCode = 'invalid_input' | 'missing_network' | 'missing_registry' | 'query_failed'\n\nexport class BiomapperQueryError extends Error {\n\treadonly code: BiomapperQueryErrorCode\n\n\tconstructor(code: BiomapperQueryErrorCode, message: string, options?: { cause?: unknown }) {\n\t\tsuper(message)\n\t\tthis.code = code\n\t\tthis.name = 'BiomapperQueryError'\n\t\tif (options?.cause !== undefined) {\n\t\t\t;(this as Error & { cause?: unknown }).cause = options.cause\n\t\t}\n\t}\n}\n\nexport interface CreateBiomapperQueryClientOptions {\n\tclient?: PublicClient\n\tnetwork?: BiomapperQueryNetwork\n\tregistryAddress?: `0x${string}`\n\trpcUrl?: string\n}\n\nfunction getErrorMessage(error: unknown) {\n\treturn error instanceof Error ? error.message : String(error)\n}\n\nfunction createValidationError(method: string, result: z.SafeParseError<unknown>) {\n\treturn new BiomapperQueryError('invalid_input', `${method} received invalid input: ${result.error.message}`, {\n\t\tcause: result.error,\n\t})\n}\n\nfunction resolveNetworkInfo(network: BiomapperBridgeNetwork): BiomapperNetworkInfo {\n\treturn {\n\t\tnetwork,\n\t\tbridgedBiomapper: BRIDGED_BIOMAPPER_ADDRESSES[network],\n\t\tbiomapperAppUrl: BIOMAPPER_APP_URLS[network],\n\t\tchainId: NETWORK_CHAIN_IDS[network],\n\t\tcaip2: NETWORK_CAIP2_IDS[network],\n\t}\n}\n\nexport function createBiomapperQueryClient(defaults: CreateBiomapperQueryClientOptions = {}) {\n\tconst parsedDefaults = z\n\t\t.object({\n\t\t\tnetwork: BiomapperNetworkSchema.optional(),\n\t\t\tregistryAddress: BiomapperAddressSchema.optional(),\n\t\t\trpcUrl: BiomapperRpcUrlSchema.optional(),\n\t\t})\n\t\t.safeParse({\n\t\t\tnetwork: defaults.network,\n\t\t\tregistryAddress: defaults.registryAddress,\n\t\t\trpcUrl: defaults.rpcUrl,\n\t\t})\n\n\tif (!parsedDefaults.success) {\n\t\tthrow createValidationError('createBiomapperQueryClient', parsedDefaults)\n\t}\n\n\tfunction getClient(network: BiomapperQueryNetwork, rpcUrl?: string) {\n\t\tif (defaults.client) return defaults.client\n\t\treturn getPublicClient(NETWORK_CHAIN_IDS[network], rpcUrl ?? defaults.rpcUrl)\n\t}\n\n\tfunction resolveRequiredNetwork(network: BiomapperQueryNetwork | undefined) {\n\t\tconst resolvedNetwork = network ?? defaults.network\n\t\tif (!resolvedNetwork) {\n\t\t\tthrow new BiomapperQueryError(\n\t\t\t\t'missing_network',\n\t\t\t\t'Biomapper network is required. Pass `network` to this call or set a default in createBiomapperQueryClient(...).'\n\t\t\t)\n\t\t}\n\n\t\treturn resolvedNetwork\n\t}\n\n\tfunction resolveRegistryAddress(registryAddress: `0x${string}` | undefined) {\n\t\tconst resolvedRegistryAddress = registryAddress ?? defaults.registryAddress\n\t\tif (!resolvedRegistryAddress) {\n\t\t\tthrow new BiomapperQueryError(\n\t\t\t\t'missing_registry',\n\t\t\t\t'Biomapper registry address is required for agent status queries. Pass `registryAddress` to this call or set a default in createBiomapperQueryClient(...).'\n\t\t\t)\n\t\t}\n\n\t\treturn resolvedRegistryAddress\n\t}\n\n\treturn {\n\t\tasync checkAgentStatus(input: CheckAgentStatusInput): Promise<CheckAgentStatusResult> {\n\t\t\tconst parsed = CheckAgentStatusInputSchema.safeParse(input)\n\t\t\tif (!parsed.success) {\n\t\t\t\tthrow createValidationError('checkAgentStatus', parsed)\n\t\t\t}\n\n\t\t\tconst network = resolveRequiredNetwork(parsed.data.network)\n\t\t\tconst registryAddress = resolveRegistryAddress(parsed.data.registryAddress as `0x${string}` | undefined)\n\t\t\tconst client = getClient(network, parsed.data.rpcUrl)\n\n\t\t\ttry {\n\t\t\t\tconst [owner, generationPtr, active] = await client.readContract({\n\t\t\t\t\taddress: registryAddress,\n\t\t\t\t\tabi: BIOMAPPER_AGENT_REGISTRY_ABI,\n\t\t\t\t\tfunctionName: 'getAgentStatus',\n\t\t\t\t\targs: [parsed.data.agentAddress as `0x${string}`],\n\t\t\t\t})\n\n\t\t\t\tif (owner === zeroAddress) {\n\t\t\t\t\treturn CheckAgentStatusResultSchema.parse({\n\t\t\t\t\t\tlinked: false,\n\t\t\t\t\t\tactive: false,\n\t\t\t\t\t\tagentAddress: parsed.data.agentAddress,\n\t\t\t\t\t\towner: null,\n\t\t\t\t\t\tgenerationPtr: null,\n\t\t\t\t\t\tnetwork,\n\t\t\t\t\t\tmessage: 'This agent is not linked to any owner.',\n\t\t\t\t\t})\n\t\t\t\t}\n\n\t\t\t\treturn CheckAgentStatusResultSchema.parse({\n\t\t\t\t\tlinked: true,\n\t\t\t\t\tactive,\n\t\t\t\t\tagentAddress: parsed.data.agentAddress,\n\t\t\t\t\towner,\n\t\t\t\t\tgenerationPtr: generationPtr.toString(),\n\t\t\t\t\tnetwork,\n\t\t\t\t\tmessage: active\n\t\t\t\t\t\t? 'Agent is linked and active — the owner is biomapped in the current generation.'\n\t\t\t\t\t\t: 'Agent is linked but inactive — the owner needs to re-verify with Biomapper for the current generation.',\n\t\t\t\t})\n\t\t\t} catch (error) {\n\t\t\t\tthrow new BiomapperQueryError(\n\t\t\t\t\t'query_failed',\n\t\t\t\t\t`Failed to query Biomapper agent status: ${getErrorMessage(error)}`,\n\t\t\t\t\t{ cause: error }\n\t\t\t\t)\n\t\t\t}\n\t\t},\n\n\t\tasync getCurrentGeneration(input: GetCurrentGenerationInput = {}): Promise<GetCurrentGenerationResult> {\n\t\t\tconst parsed = GetCurrentGenerationInputSchema.safeParse(input)\n\t\t\tif (!parsed.success) {\n\t\t\t\tthrow createValidationError('getCurrentGeneration', parsed)\n\t\t\t}\n\n\t\t\tconst network = resolveRequiredNetwork(parsed.data.network)\n\t\t\tconst client = getClient(network, parsed.data.rpcUrl)\n\t\t\tconst info = resolveNetworkInfo(network)\n\n\t\t\ttry {\n\t\t\t\tconst generationsHead = await client.readContract({\n\t\t\t\t\taddress: info.bridgedBiomapper as `0x${string}`,\n\t\t\t\t\tabi: BRIDGED_BIOMAPPER_READ_ABI,\n\t\t\t\t\tfunctionName: 'generationsHead',\n\t\t\t\t})\n\n\t\t\t\treturn GetCurrentGenerationResultSchema.parse({\n\t\t\t\t\tgenerationsHead: generationsHead.toString(),\n\t\t\t\t\tnetwork,\n\t\t\t\t\tbridgedBiomapper: info.bridgedBiomapper,\n\t\t\t\t\tbiomapperAppUrl: info.biomapperAppUrl,\n\t\t\t\t})\n\t\t\t} catch (error) {\n\t\t\t\tthrow new BiomapperQueryError(\n\t\t\t\t\t'query_failed',\n\t\t\t\t\t`Failed to query Biomapper generation: ${getErrorMessage(error)}`,\n\t\t\t\t\t{ cause: error }\n\t\t\t\t)\n\t\t\t}\n\t\t},\n\n\t\tasync getBiomapperInfo(input: GetBiomapperInfoInput = {}): Promise<GetBiomapperInfoResult> {\n\t\t\tconst parsed = GetBiomapperInfoInputSchema.safeParse(input)\n\t\t\tif (!parsed.success) {\n\t\t\t\tthrow createValidationError('getBiomapperInfo', parsed)\n\t\t\t}\n\n\t\t\tconst resolvedNetwork = parsed.data.network ?? defaults.network\n\t\t\tconst networks = resolvedNetwork ? [resolvedNetwork] : [...BiomapperNetworkSchema.options]\n\n\t\t\treturn GetBiomapperInfoResultSchema.parse({\n\t\t\t\tnetworks: networks.map(network => resolveNetworkInfo(network)),\n\t\t\t})\n\t\t},\n\t}\n}\n\nexport type BiomapperQueryClient = ReturnType<typeof createBiomapperQueryClient>\n","import { base, baseSepolia } from 'viem/chains'\nimport { privateKeyToAccount } from 'viem/accounts'\nimport { createPublicClient, http, type Hex, type TypedData, type TypedDataDomain } from 'viem'\n\nimport type { BiomapperBridgeNetwork } from './biomapper'\n\nexport const BIOMAPPER_AGENT_REGISTRY_NAME = 'BiomapperAgentRegistry'\nexport const BIOMAPPER_AGENT_REGISTRY_VERSION = '1'\n\nexport const AGENT_LINK_TYPES = {\n\tAgentLink: [\n\t\t{ name: 'agent', type: 'address' },\n\t\t{ name: 'owner', type: 'address' },\n\t\t{ name: 'nonce', type: 'uint256' },\n\t\t{ name: 'deadline', type: 'uint256' },\n\t],\n} as const satisfies TypedData\n\nexport interface AgentLinkAuthorization {\n\tagent: `0x${string}`\n\towner: `0x${string}`\n\tregistry: `0x${string}`\n\tchainId: number\n\tnonce: bigint\n\tdeadline: bigint\n\tsignature?: `0x${string}`\n}\n\nexport interface AgentLinkConsentOutput {\n\ttype: 'biomapper-agent-link'\n\tnetwork: BiomapperBridgeNetwork\n\tchainId: number\n\tagent: `0x${string}`\n\towner: `0x${string}`\n\tregistry: `0x${string}`\n\tnonce: string\n\tdeadline: string\n\ttypedData: {\n\t\tdomain: {\n\t\t\tname: string\n\t\t\tversion: string\n\t\t\tchainId: number\n\t\t\tverifyingContract: `0x${string}`\n\t\t}\n\t\ttypes: typeof AGENT_LINK_TYPES\n\t\tprimaryType: 'AgentLink'\n\t\tmessage: {\n\t\t\tagent: `0x${string}`\n\t\t\towner: `0x${string}`\n\t\t\tnonce: string\n\t\t\tdeadline: string\n\t\t}\n\t}\n\tsignature: `0x${string}`\n}\n\nexport interface AgentLinkConsentSigner {\n\taddress: `0x${string}`\n\tsignTypedData(input: ReturnType<typeof buildAgentLinkTypedData>): Promise<`0x${string}`>\n}\n\nexport interface CreateAgentLinkConsentOptions {\n\towner: `0x${string}`\n\tregistry: `0x${string}`\n\tdeadline: bigint\n\tnetwork: BiomapperBridgeNetwork\n\tprivateKey?: Hex\n\tsigner?: AgentLinkConsentSigner\n\tclient?: AgentLinkConsentClient\n\trpcUrl?: string\n}\n\nexport interface AgentLinkConsentClient {\n\tgetChainId?(): Promise<number>\n\treadContract(input: {\n\t\taddress: `0x${string}`\n\t\tabi: typeof BIOMAPPER_AGENT_REGISTRY_ABI\n\t\tfunctionName: 'agentNonce'\n\t\targs: [`0x${string}`]\n\t}): Promise<bigint>\n}\n\nconst LINK_CONSENT_NETWORKS = {\n\tbase: base,\n\t'base-sepolia': baseSepolia,\n} as const satisfies Record<BiomapperBridgeNetwork, typeof base | typeof baseSepolia>\n\nconst BIOMAPPER_AGENT_REGISTRY_ABI = [\n\t{\n\t\tinputs: [{ internalType: 'address', name: 'agent', type: 'address' }],\n\t\tname: 'agentNonce',\n\t\toutputs: [{ internalType: 'uint256', name: 'nonce', type: 'uint256' }],\n\t\tstateMutability: 'view',\n\t\ttype: 'function',\n\t},\n] as const\n\nexport function buildAgentLinkTypedData(input: AgentLinkAuthorization): {\n\tdomain: TypedDataDomain\n\ttypes: typeof AGENT_LINK_TYPES\n\tprimaryType: 'AgentLink'\n\tmessage: {\n\t\tagent: `0x${string}`\n\t\towner: `0x${string}`\n\t\tnonce: bigint\n\t\tdeadline: bigint\n\t}\n} {\n\treturn {\n\t\tdomain: {\n\t\t\tname: BIOMAPPER_AGENT_REGISTRY_NAME,\n\t\t\tversion: BIOMAPPER_AGENT_REGISTRY_VERSION,\n\t\t\tchainId: input.chainId,\n\t\t\tverifyingContract: input.registry,\n\t\t},\n\t\ttypes: AGENT_LINK_TYPES,\n\t\tprimaryType: 'AgentLink',\n\t\tmessage: {\n\t\t\tagent: input.agent,\n\t\t\towner: input.owner,\n\t\t\tnonce: input.nonce,\n\t\t\tdeadline: input.deadline,\n\t\t},\n\t}\n}\n\nfunction resolveSigner(options: CreateAgentLinkConsentOptions): AgentLinkConsentSigner {\n\tif (options.signer) return options.signer\n\tif (options.privateKey) return privateKeyToAccount(options.privateKey)\n\n\tthrow new Error('Missing link consent signer. Pass signer or privateKey.')\n}\n\nfunction getClient(options: CreateAgentLinkConsentOptions): AgentLinkConsentClient {\n\tif (options.client) return options.client\n\n\tconst chain = LINK_CONSENT_NETWORKS[options.network]\n\treturn createPublicClient({\n\t\tchain,\n\t\ttransport: http(options.rpcUrl),\n\t})\n}\n\nexport async function createAgentLinkConsent(options: CreateAgentLinkConsentOptions): Promise<AgentLinkConsentOutput> {\n\tconst signer = resolveSigner(options)\n\tconst chain = LINK_CONSENT_NETWORKS[options.network]\n\tconst client = getClient(options)\n\n\tif (options.rpcUrl && !options.client) {\n\t\tconst remoteChainId = await client.getChainId?.()\n\t\tif (remoteChainId === undefined) {\n\t\t\tthrow new Error('The configured consent client cannot report its chain id.')\n\t\t}\n\t\tif (remoteChainId !== chain.id) {\n\t\t\tthrow new Error(\n\t\t\t\t`RPC chain mismatch. ${options.network} expects chain id ${chain.id}, but ${options.rpcUrl} returned ${remoteChainId}.`\n\t\t\t)\n\t\t}\n\t}\n\n\tconst nonce = await client.readContract({\n\t\taddress: options.registry,\n\t\tabi: BIOMAPPER_AGENT_REGISTRY_ABI,\n\t\tfunctionName: 'agentNonce',\n\t\targs: [signer.address],\n\t})\n\n\tconst typedData = buildAgentLinkTypedData({\n\t\tagent: signer.address,\n\t\towner: options.owner,\n\t\tregistry: options.registry,\n\t\tchainId: chain.id,\n\t\tnonce,\n\t\tdeadline: options.deadline,\n\t})\n\n\tconst signature = await signer.signTypedData(typedData)\n\n\treturn {\n\t\ttype: 'biomapper-agent-link',\n\t\tnetwork: options.network,\n\t\tchainId: chain.id,\n\t\tagent: signer.address,\n\t\towner: options.owner,\n\t\tregistry: options.registry,\n\t\tnonce: nonce.toString(),\n\t\tdeadline: options.deadline.toString(),\n\t\ttypedData: {\n\t\t\tdomain: {\n\t\t\t\tname: typedData.domain.name ?? BIOMAPPER_AGENT_REGISTRY_NAME,\n\t\t\t\tversion: typedData.domain.version ?? BIOMAPPER_AGENT_REGISTRY_VERSION,\n\t\t\t\tchainId: typedData.domain.chainId as number,\n\t\t\t\tverifyingContract: typedData.domain.verifyingContract as `0x${string}`,\n\t\t\t},\n\t\t\ttypes: typedData.types,\n\t\t\tprimaryType: typedData.primaryType,\n\t\t\tmessage: {\n\t\t\t\tagent: typedData.message.agent,\n\t\t\t\towner: typedData.message.owner,\n\t\t\t\tnonce: typedData.message.nonce.toString(),\n\t\t\t\tdeadline: typedData.message.deadline.toString(),\n\t\t\t},\n\t\t},\n\t\tsignature,\n\t}\n}\n","import type { AgentLinkEntitlement, AgentLinkUsageContext } from './types'\n\nexport interface AgentLinkStorage {\n\thasUsedNonce(nonce: string): Promise<boolean>\n\trecordNonce(nonce: string): Promise<void>\n\tgetUsageCount?(\n\t\tendpoint: string,\n\t\towner: string,\n\t\tgenerationPtr: bigint,\n\t\tcontext?: AgentLinkUsageContext\n\t): Promise<number>\n\tincrementUsage?(\n\t\tendpoint: string,\n\t\towner: string,\n\t\tgenerationPtr: bigint,\n\t\tcontext?: AgentLinkUsageContext\n\t): Promise<void>\n}\n\nexport function buildAgentLinkUsageKey(input: AgentLinkEntitlement): string {\n\treturn [\n\t\tinput.endpoint,\n\t\tinput.generationPtr.toString(),\n\t\tinput.owner.toLowerCase(),\n\t\tinput.platformAccountId ?? '*',\n\t\tinput.workspaceId ?? '*',\n\t].join(':')\n}\n\nexport class InMemoryAgentLinkStorage implements AgentLinkStorage {\n\tprivate usage = new Map<string, number>()\n\tprivate nonces = new Set<string>()\n\n\tasync getUsageCount(\n\t\tendpoint: string,\n\t\towner: string,\n\t\tgenerationPtr: bigint,\n\t\tcontext?: AgentLinkUsageContext\n\t): Promise<number> {\n\t\treturn (\n\t\t\tthis.usage.get(\n\t\t\t\tbuildAgentLinkUsageKey({\n\t\t\t\t\tendpoint,\n\t\t\t\t\towner,\n\t\t\t\t\tgenerationPtr,\n\t\t\t\t\tplatformAccountId: context?.platformAccountId,\n\t\t\t\t\tworkspaceId: context?.workspaceId,\n\t\t\t\t})\n\t\t\t) ?? 0\n\t\t)\n\t}\n\n\tasync incrementUsage(\n\t\tendpoint: string,\n\t\towner: string,\n\t\tgenerationPtr: bigint,\n\t\tcontext?: AgentLinkUsageContext\n\t): Promise<void> {\n\t\tconst key = buildAgentLinkUsageKey({\n\t\t\tendpoint,\n\t\t\towner,\n\t\t\tgenerationPtr,\n\t\t\tplatformAccountId: context?.platformAccountId,\n\t\t\tworkspaceId: context?.workspaceId,\n\t\t})\n\t\tthis.usage.set(key, (this.usage.get(key) ?? 0) + 1)\n\t}\n\n\tasync hasUsedNonce(nonce: string): Promise<boolean> {\n\t\treturn this.nonces.has(nonce)\n\t}\n\n\tasync recordNonce(nonce: string): Promise<void> {\n\t\tthis.nonces.add(nonce)\n\t}\n}\n","import { parseAgentLinkHeader } from './parse'\nimport type { AgentLinkStorage } from './storage'\nimport { verifyAgentLinkSignature } from './verify'\nimport { validateAgentLinkMessage } from './validate'\nimport type { BiomapperRegistryVerifier } from './biomapper-registry'\nimport { AGENTLINK, type AgentLinkMode, type AgentLinkUsageContext } from './types'\nimport type {\n\tAgentLinkEntitlementContext,\n\tAgentLinkEntitlementResolver,\n\tAgentLinkHookEvent,\n\tResolveAgentLinkEntitlementInput,\n} from './events'\n\nexport type {\n\tAgentLinkEntitlementContext,\n\tAgentLinkEntitlementResolver,\n\tAgentLinkHookEvent,\n\tResolveAgentLinkEntitlementInput,\n} from './events'\n\nexport interface CreateAgentLinkHooksOptions {\n\tregistry: BiomapperRegistryVerifier\n\tmode?: AgentLinkMode\n\t/** Required in all modes so replayed nonces are rejected. */\n\tstorage: AgentLinkStorage\n\t/** Custom RPC URL for EVM signature verification. Uses the chain's default public RPC if omitted. */\n\trpcUrl?: string\n\tonEvent?: (event: AgentLinkHookEvent) => void | Promise<void>\n\tentitlements?: AgentLinkEntitlementContext | AgentLinkEntitlementResolver\n\tusageThresholds?: number[]\n}\n\ninterface ScopedEventContext extends AgentLinkUsageContext {\n\tresource: string\n\tendpoint: string\n}\n\ninterface PendingDiscount {\n\taddress: string\n\towner: string\n\tgenerationPtr: bigint\n\tresource: string\n\tendpoint: string\n\tusageContext: AgentLinkUsageContext\n\tcreatedAt: number\n}\n\ninterface ObservedLinkStatus {\n\towner: string | null\n\tgenerationPtr: bigint\n\tactive: boolean\n}\n\nexport function createAgentLinkHooks(options: CreateAgentLinkHooksOptions) {\n\tconst { registry, onEvent } = options\n\tconst mode: AgentLinkMode = options.mode ?? { type: 'free' }\n\tconst storage = options.storage\n\tconst usageThresholds = normalizeThresholds(options.usageThresholds)\n\n\tassertReplayStorage(storage)\n\tif (mode.type === 'free-trial' || mode.type === 'discount') {\n\t\tassertUsageStorage(storage, mode.type)\n\t}\n\n\tif (mode.type === 'discount' && (!Number.isInteger(mode.percent) || mode.percent <= 0 || mode.percent > 100)) {\n\t\tthrow new Error(`Discount percent must be an integer between 1 and 100, got ${mode.percent}`)\n\t}\n\n\tconst PENDING_TTL_MS = 5 * 60 * 1000\n\tconst pendingDiscounts = new Map<string, PendingDiscount[]>()\n\tconst observedLinks = new Map<string, ObservedLinkStatus>()\n\n\tasync function emit(event: AgentLinkHookEvent) {\n\t\tif (!onEvent) return\n\t\ttry {\n\t\t\tawait onEvent(event)\n\t\t} catch {}\n\t}\n\n\tfunction getLinkedOnlyAbort() {\n\t\treturn {\n\t\t\tabort: true as const,\n\t\t\treason:\n\t\t\t\tmode.type === 'linked-only'\n\t\t\t\t\t? (mode.reason ?? 'Linked agent access is required for this resource.')\n\t\t\t\t\t: '',\n\t\t}\n\t}\n\n\tasync function resolveEntitlements(\n\t\tinput: ResolveAgentLinkEntitlementInput\n\t): Promise<AgentLinkEntitlementContext & { endpoint: string }> {\n\t\tconst resolved =\n\t\t\ttypeof options.entitlements === 'function'\n\t\t\t\t? await options.entitlements(input)\n\t\t\t\t: (options.entitlements ?? {})\n\n\t\treturn {\n\t\t\tendpoint: resolved?.endpoint ?? input.request.path,\n\t\t\tplatformAccountId: resolved?.platformAccountId,\n\t\t\tworkspaceId: resolved?.workspaceId,\n\t\t}\n\t}\n\n\tfunction buildScopedContext(\n\t\tresource: string,\n\t\tentitlements: AgentLinkEntitlementContext & { endpoint: string }\n\t): ScopedEventContext {\n\t\treturn {\n\t\t\tresource,\n\t\t\tendpoint: entitlements.endpoint,\n\t\t\tplatformAccountId: entitlements.platformAccountId,\n\t\t\tworkspaceId: entitlements.workspaceId,\n\t\t}\n\t}\n\n\tasync function observeLinkStatus(\n\t\taddress: string,\n\t\tstatus: Awaited<ReturnType<BiomapperRegistryVerifier['getAgentStatus']>>,\n\t\tscoped: ScopedEventContext\n\t) {\n\t\tif (!status) return\n\n\t\tconst key = [address.toLowerCase(), scoped.platformAccountId ?? '*', scoped.workspaceId ?? '*'].join(':')\n\t\tconst previous = observedLinks.get(key)\n\t\tconst owner = status.owner ? status.owner.toLowerCase() : null\n\n\t\tif (status.owner && status.active) {\n\t\t\tif (\n\t\t\t\t!previous ||\n\t\t\t\t!previous.active ||\n\t\t\t\tprevious.owner?.toLowerCase() !== owner ||\n\t\t\t\tprevious.generationPtr !== status.generationPtr\n\t\t\t) {\n\t\t\t\tawait emit({\n\t\t\t\t\ttype: 'link.activated',\n\t\t\t\t\taddress,\n\t\t\t\t\towner: status.owner,\n\t\t\t\t\tgenerationPtr: status.generationPtr,\n\t\t\t\t\t...scoped,\n\t\t\t\t})\n\t\t\t}\n\t\t} else if (!status.owner) {\n\t\t\tif (previous?.owner) {\n\t\t\t\tawait emit({\n\t\t\t\t\ttype: 'link.unlinked',\n\t\t\t\t\taddress,\n\t\t\t\t\tpreviousOwner: previous.owner,\n\t\t\t\t\tgenerationPtr: previous.generationPtr,\n\t\t\t\t\t...scoped,\n\t\t\t\t})\n\t\t\t}\n\t\t} else if (previous?.owner && previous.active && !status.active) {\n\t\t\tawait emit({\n\t\t\t\ttype: 'link.deactivated',\n\t\t\t\taddress,\n\t\t\t\towner: status.owner,\n\t\t\t\tgenerationPtr: status.generationPtr,\n\t\t\t\treason: 'inactive',\n\t\t\t\t...scoped,\n\t\t\t})\n\t\t\tawait emit({\n\t\t\t\ttype: 'relink.required',\n\t\t\t\taddress,\n\t\t\t\towner: status.owner,\n\t\t\t\tgenerationPtr: status.generationPtr,\n\t\t\t\treason: 'inactive_owner',\n\t\t\t\t...scoped,\n\t\t\t})\n\t\t}\n\n\t\tobservedLinks.set(key, {\n\t\t\towner: status.owner,\n\t\t\tgenerationPtr: status.generationPtr,\n\t\t\tactive: status.active,\n\t\t})\n\t}\n\n\tasync function maybeEmitThresholdEvent(input: {\n\t\tresource: string\n\t\tendpoint: string\n\t\taddress: string\n\t\towner: string\n\t\tgenerationPtr: bigint\n\t\tmode: Extract<AgentLinkMode['type'], 'free-trial' | 'discount'>\n\t\tusageContext: AgentLinkUsageContext\n\t\tcount: number\n\t\tdefaultThreshold?: number\n\t}) {\n\t\tconst thresholds = new Set<number>(usageThresholds)\n\t\tif (input.defaultThreshold && input.defaultThreshold > 0) {\n\t\t\tthresholds.add(input.defaultThreshold)\n\t\t}\n\n\t\tif (!thresholds.has(input.count)) return\n\n\t\tawait emit({\n\t\t\ttype: 'usage.threshold_reached',\n\t\t\tresource: input.resource,\n\t\t\tendpoint: input.endpoint,\n\t\t\taddress: input.address,\n\t\t\towner: input.owner,\n\t\t\tgenerationPtr: input.generationPtr,\n\t\t\tcount: input.count,\n\t\t\tthreshold: input.count,\n\t\t\tmode: input.mode,\n\t\t\tplatformAccountId: input.usageContext.platformAccountId,\n\t\t\tworkspaceId: input.usageContext.workspaceId,\n\t\t})\n\t}\n\n\tfunction prunePendingDiscounts(now: number) {\n\t\tfor (const [address, entries] of pendingDiscounts) {\n\t\t\tconst activeEntries = entries.filter(entry => now - entry.createdAt <= PENDING_TTL_MS)\n\t\t\tif (activeEntries.length > 0) {\n\t\t\t\tpendingDiscounts.set(address, activeEntries)\n\t\t\t} else {\n\t\t\t\tpendingDiscounts.delete(address)\n\t\t\t}\n\t\t}\n\t}\n\n\tconst requestHook = async (context: {\n\t\tadapter: { getHeader(name: string): string | undefined; getUrl(): string }\n\t\tpath: string\n\t}): Promise<void | { grantAccess: true } | { abort: true; reason: string }> => {\n\t\tconst header = context.adapter.getHeader(AGENTLINK) || context.adapter.getHeader(AGENTLINK.toLowerCase())\n\t\tif (!header) {\n\t\t\tif (mode.type === 'linked-only') {\n\t\t\t\treturn getLinkedOnlyAbort()\n\t\t\t}\n\t\t\treturn\n\t\t}\n\n\t\ttry {\n\t\t\tconst payload = parseAgentLinkHeader(header)\n\t\t\tconst resourceUri = context.adapter.getUrl()\n\n\t\t\tconst checkNonce = async (nonce: string) => !(await storage.hasUsedNonce(nonce))\n\t\t\tconst validation = await validateAgentLinkMessage(payload, resourceUri, {\n\t\t\t\tcheckNonce,\n\t\t\t})\n\t\t\tif (!validation.valid) {\n\t\t\t\tawait emit({\n\t\t\t\t\ttype: 'validation_failed',\n\t\t\t\t\tresource: context.path,\n\t\t\t\t\tendpoint: context.path,\n\t\t\t\t\terror: validation.error,\n\t\t\t\t})\n\t\t\t\tif (mode.type === 'linked-only') {\n\t\t\t\t\treturn getLinkedOnlyAbort()\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tconst verification = await verifyAgentLinkSignature(payload, options.rpcUrl)\n\t\t\tif (!verification.valid || !verification.address) {\n\t\t\t\tawait emit({\n\t\t\t\t\ttype: 'validation_failed',\n\t\t\t\t\tresource: context.path,\n\t\t\t\t\tendpoint: context.path,\n\t\t\t\t\terror: verification.error,\n\t\t\t\t})\n\t\t\t\tif (mode.type === 'linked-only') {\n\t\t\t\t\treturn getLinkedOnlyAbort()\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tawait storage.recordNonce(payload.nonce)\n\n\t\t\tconst status = await registry.getAgentStatus(verification.address, payload.chainId)\n\t\t\tconst entitlements = await resolveEntitlements({\n\t\t\t\trequest: context,\n\t\t\t\tpayload,\n\t\t\t\taddress: verification.address,\n\t\t\t\tstatus,\n\t\t\t})\n\t\t\tconst scoped = buildScopedContext(context.path, entitlements)\n\t\t\tconst usageContext = {\n\t\t\t\tplatformAccountId: entitlements.platformAccountId,\n\t\t\t\tworkspaceId: entitlements.workspaceId,\n\t\t\t}\n\n\t\t\tawait observeLinkStatus(verification.address, status, scoped)\n\n\t\t\tif (!status?.owner || !status.active) {\n\t\t\t\tawait emit({\n\t\t\t\t\ttype: 'agent_not_verified',\n\t\t\t\t\tresource: context.path,\n\t\t\t\t\tendpoint: entitlements.endpoint,\n\t\t\t\t\taddress: verification.address,\n\t\t\t\t\tplatformAccountId: entitlements.platformAccountId,\n\t\t\t\t\tworkspaceId: entitlements.workspaceId,\n\t\t\t\t})\n\t\t\t\tif (mode.type === 'linked-only') {\n\t\t\t\t\treturn getLinkedOnlyAbort()\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif (mode.type === 'linked-only' || mode.type === 'free') {\n\t\t\t\tawait emit({\n\t\t\t\t\ttype: 'agent_verified',\n\t\t\t\t\tresource: context.path,\n\t\t\t\t\tendpoint: entitlements.endpoint,\n\t\t\t\t\taddress: verification.address,\n\t\t\t\t\towner: status.owner,\n\t\t\t\t\tgenerationPtr: status.generationPtr,\n\t\t\t\t\tplatformAccountId: entitlements.platformAccountId,\n\t\t\t\t\tworkspaceId: entitlements.workspaceId,\n\t\t\t\t})\n\t\t\t\treturn { grantAccess: true }\n\t\t\t}\n\n\t\t\tif (mode.type === 'free-trial') {\n\t\t\t\tconst usageStorage = assertUsageStorage(storage, mode.type)\n\t\t\t\tconst uses = mode.uses ?? 1\n\t\t\t\tconst count = await usageStorage.getUsageCount(\n\t\t\t\t\tentitlements.endpoint,\n\t\t\t\t\tstatus.owner,\n\t\t\t\t\tstatus.generationPtr,\n\t\t\t\t\tusageContext\n\t\t\t\t)\n\t\t\t\tif (count < uses) {\n\t\t\t\t\tconst nextCount = count + 1\n\t\t\t\t\tawait usageStorage.incrementUsage(\n\t\t\t\t\t\tentitlements.endpoint,\n\t\t\t\t\t\tstatus.owner,\n\t\t\t\t\t\tstatus.generationPtr,\n\t\t\t\t\t\tusageContext\n\t\t\t\t\t)\n\t\t\t\t\tawait emit({\n\t\t\t\t\t\ttype: 'agent_verified',\n\t\t\t\t\t\tresource: context.path,\n\t\t\t\t\t\tendpoint: entitlements.endpoint,\n\t\t\t\t\t\taddress: verification.address,\n\t\t\t\t\t\towner: status.owner,\n\t\t\t\t\t\tgenerationPtr: status.generationPtr,\n\t\t\t\t\t\tplatformAccountId: entitlements.platformAccountId,\n\t\t\t\t\t\tworkspaceId: entitlements.workspaceId,\n\t\t\t\t\t})\n\t\t\t\t\tawait maybeEmitThresholdEvent({\n\t\t\t\t\t\tresource: context.path,\n\t\t\t\t\t\tendpoint: entitlements.endpoint,\n\t\t\t\t\t\taddress: verification.address,\n\t\t\t\t\t\towner: status.owner,\n\t\t\t\t\t\tgenerationPtr: status.generationPtr,\n\t\t\t\t\t\tmode: 'free-trial',\n\t\t\t\t\t\tusageContext,\n\t\t\t\t\t\tcount: nextCount,\n\t\t\t\t\t\tdefaultThreshold: uses,\n\t\t\t\t\t})\n\t\t\t\t\treturn { grantAccess: true }\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif (mode.type === 'discount') {\n\t\t\t\tconst now = Date.now()\n\t\t\t\tprunePendingDiscounts(now)\n\n\t\t\t\tconst pendingEntries = pendingDiscounts.get(verification.address) ?? []\n\t\t\t\tconst nextEntries = pendingEntries.filter(entry => entry.resource !== context.path)\n\t\t\t\tnextEntries.push({\n\t\t\t\t\taddress: verification.address,\n\t\t\t\t\towner: status.owner,\n\t\t\t\t\tgenerationPtr: status.generationPtr,\n\t\t\t\t\tresource: context.path,\n\t\t\t\t\tendpoint: entitlements.endpoint,\n\t\t\t\t\tusageContext,\n\t\t\t\t\tcreatedAt: now,\n\t\t\t\t})\n\t\t\t\tpendingDiscounts.set(verification.address, nextEntries)\n\t\t\t\treturn\n\t\t\t}\n\t\t} catch (err) {\n\t\t\tawait emit({\n\t\t\t\ttype: 'validation_failed',\n\t\t\t\tresource: context.path,\n\t\t\t\tendpoint: context.path,\n\t\t\t\terror: err instanceof Error ? err.message : 'Unknown error',\n\t\t\t})\n\t\t\tif (mode.type === 'linked-only') {\n\t\t\t\treturn getLinkedOnlyAbort()\n\t\t\t}\n\t\t}\n\t}\n\n\tconst verifyFailureHook =\n\t\tmode.type === 'discount'\n\t\t\t? async (context: {\n\t\t\t\t\tpaymentPayload: {\n\t\t\t\t\t\tresource: { url: string }\n\t\t\t\t\t\tpayload: Record<string, unknown>\n\t\t\t\t\t}\n\t\t\t\t\trequirements: { amount: string }\n\t\t\t\t\terror: Error\n\t\t\t\t}): Promise<void | {\n\t\t\t\t\trecovered: true\n\t\t\t\t\tresult: { isValid: boolean; payer?: string }\n\t\t\t\t}> => {\n\t\t\t\t\tconst usageStorage = assertUsageStorage(storage, mode.type)\n\t\t\t\t\tconst resourcePath = new URL(context.paymentPayload.resource.url).pathname\n\t\t\t\t\tconst payer = extractPayer(context.paymentPayload.payload)\n\t\t\t\t\tconst now = Date.now()\n\n\t\t\t\t\tprunePendingDiscounts(now)\n\t\t\t\t\tconst pendingEntries = payer ? (pendingDiscounts.get(payer) ?? []) : []\n\t\t\t\t\tconst pendingIndex = pendingEntries.findIndex(entry => entry.resource === resourcePath)\n\t\t\t\t\tconst pending = pendingIndex >= 0 ? pendingEntries[pendingIndex] : undefined\n\n\t\t\t\t\tif (pendingIndex >= 0) {\n\t\t\t\t\t\tpendingEntries.splice(pendingIndex, 1)\n\t\t\t\t\t\tif (pendingEntries.length > 0) {\n\t\t\t\t\t\t\tpendingDiscounts.set(payer!, pendingEntries)\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tpendingDiscounts.delete(payer!)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (!pending) return\n\t\t\t\t\tif (!isUnderpaymentError(context.error)) return\n\n\t\t\t\t\tconst uses = mode.uses ?? Infinity\n\t\t\t\t\tconst count = await usageStorage.getUsageCount(\n\t\t\t\t\t\tpending.endpoint,\n\t\t\t\t\t\tpending.owner,\n\t\t\t\t\t\tpending.generationPtr,\n\t\t\t\t\t\tpending.usageContext\n\t\t\t\t\t)\n\n\t\t\t\t\tif (count >= uses) {\n\t\t\t\t\t\tawait emit({\n\t\t\t\t\t\t\ttype: 'discount_exhausted',\n\t\t\t\t\t\t\tresource: resourcePath,\n\t\t\t\t\t\t\tendpoint: pending.endpoint,\n\t\t\t\t\t\t\taddress: pending.address,\n\t\t\t\t\t\t\towner: pending.owner,\n\t\t\t\t\t\t\tgenerationPtr: pending.generationPtr,\n\t\t\t\t\t\t\tplatformAccountId: pending.usageContext.platformAccountId,\n\t\t\t\t\t\t\tworkspaceId: pending.usageContext.workspaceId,\n\t\t\t\t\t\t})\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\n\t\t\t\t\tconst requiredAmount = BigInt(context.requirements.amount)\n\t\t\t\t\tconst discountedAmount = (requiredAmount * BigInt(100 - mode.percent)) / 100n\n\n\t\t\t\t\tconst paidAmount = extractPaidAmount(context.paymentPayload.payload)\n\t\t\t\t\tif (paidAmount === null || paidAmount < discountedAmount) return\n\t\t\t\t\tif (paidAmount >= requiredAmount) return\n\n\t\t\t\t\tconst nextCount = count + 1\n\t\t\t\t\tawait usageStorage.incrementUsage(\n\t\t\t\t\t\tpending.endpoint,\n\t\t\t\t\t\tpending.owner,\n\t\t\t\t\t\tpending.generationPtr,\n\t\t\t\t\t\tpending.usageContext\n\t\t\t\t\t)\n\t\t\t\t\tawait emit({\n\t\t\t\t\t\ttype: 'discount_applied',\n\t\t\t\t\t\tresource: resourcePath,\n\t\t\t\t\t\tendpoint: pending.endpoint,\n\t\t\t\t\t\taddress: pending.address,\n\t\t\t\t\t\towner: pending.owner,\n\t\t\t\t\t\tgenerationPtr: pending.generationPtr,\n\t\t\t\t\t\tplatformAccountId: pending.usageContext.platformAccountId,\n\t\t\t\t\t\tworkspaceId: pending.usageContext.workspaceId,\n\t\t\t\t\t})\n\t\t\t\t\tawait maybeEmitThresholdEvent({\n\t\t\t\t\t\tresource: resourcePath,\n\t\t\t\t\t\tendpoint: pending.endpoint,\n\t\t\t\t\t\taddress: pending.address,\n\t\t\t\t\t\towner: pending.owner,\n\t\t\t\t\t\tgenerationPtr: pending.generationPtr,\n\t\t\t\t\t\tmode: 'discount',\n\t\t\t\t\t\tusageContext: pending.usageContext,\n\t\t\t\t\t\tcount: nextCount,\n\t\t\t\t\t\tdefaultThreshold: Number.isFinite(uses) ? uses : undefined,\n\t\t\t\t\t})\n\n\t\t\t\t\tcontext.requirements.amount = String(paidAmount)\n\n\t\t\t\t\treturn {\n\t\t\t\t\t\trecovered: true,\n\t\t\t\t\t\tresult: { isValid: true, payer: pending.address },\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t: undefined\n\n\treturn { requestHook, verifyFailureHook }\n}\n\nfunction assertReplayStorage(storage: AgentLinkStorage | undefined): asserts storage is AgentLinkStorage {\n\tif (!storage) {\n\t\tthrow new Error('AgentLink hooks require a storage instance with nonce replay protection')\n\t}\n\n\tif (typeof storage.hasUsedNonce !== 'function' || typeof storage.recordNonce !== 'function') {\n\t\tthrow new Error('AgentLink storage must implement hasUsedNonce and recordNonce to prevent replay attacks')\n\t}\n}\n\nfunction assertUsageStorage(\n\tstorage: AgentLinkStorage,\n\tmodeType: Exclude<AgentLinkMode['type'], 'free' | 'linked-only'>\n): {\n\tgetUsageCount(\n\t\tendpoint: string,\n\t\towner: string,\n\t\tgenerationPtr: bigint,\n\t\tcontext?: AgentLinkUsageContext\n\t): Promise<number>\n\tincrementUsage(\n\t\tendpoint: string,\n\t\towner: string,\n\t\tgenerationPtr: bigint,\n\t\tcontext?: AgentLinkUsageContext\n\t): Promise<void>\n} {\n\tif (typeof storage.getUsageCount !== 'function' || typeof storage.incrementUsage !== 'function') {\n\t\tthrow new Error(`AgentLink mode \"${modeType}\" requires storage methods getUsageCount and incrementUsage`)\n\t}\n\n\treturn {\n\t\tgetUsageCount: storage.getUsageCount.bind(storage),\n\t\tincrementUsage: storage.incrementUsage.bind(storage),\n\t}\n}\n\nfunction normalizeThresholds(thresholds: number[] | undefined): number[] {\n\treturn (thresholds ?? []).filter(value => Number.isInteger(value) && value > 0)\n}\n\nfunction extractFromPayload<T>(\n\tpayload: Record<string, unknown>,\n\tfromAuth: (auth: Record<string, unknown>) => T,\n\tfromPermit2Auth: (auth: Record<string, unknown>) => T\n): T | null {\n\ttry {\n\t\tif ('authorization' in payload) {\n\t\t\treturn fromAuth(payload.authorization as Record<string, unknown>)\n\t\t}\n\t\tif ('permit2Authorization' in payload) {\n\t\t\treturn fromPermit2Auth(payload.permit2Authorization as Record<string, unknown>)\n\t\t}\n\t\treturn null\n\t} catch {\n\t\treturn null\n\t}\n}\n\nfunction extractPayer(payload: Record<string, unknown>): string | null {\n\tconst getFrom = (auth: Record<string, unknown>) => auth.from as string\n\treturn extractFromPayload(payload, getFrom, getFrom)\n}\n\nconst UNDERPAYMENT_REASONS = [\n\t'invalid_exact_evm_payload_authorization_value',\n\t'permit2_insufficient_amount',\n\t'insufficient_funds',\n]\n\nfunction isUnderpaymentError(error: Error): boolean {\n\tconst reason = error.message.split(':')[0]\n\treturn UNDERPAYMENT_REASONS.includes(reason)\n}\n\nfunction extractPaidAmount(payload: Record<string, unknown>): bigint | null {\n\treturn extractFromPayload(\n\t\tpayload,\n\t\tauth => BigInt(auth.value as string),\n\t\tauth => BigInt((auth.permitted as Record<string, unknown>).amount as string)\n\t)\n}\n","import { isAddress } from 'viem'\nimport type { BiomapperBridgeNetwork } from './biomapper'\nimport type { AgentLinkConsentOutput } from './link-consent'\nimport type { AgentLinkEventHandler, AgentLinkSessionEvent } from './events'\n\nexport interface AgentLinkSessionBranding {\n\tplatformName?: string\n\tlogoUrl?: string\n\taccentColor?: string\n\tsupportUrl?: string\n}\n\nexport interface AgentLinkSession {\n\tid: string\n\tcreatedAt: string\n\tplatformAccountId: string\n\tworkspaceId?: string\n\tnetwork: BiomapperBridgeNetwork\n\tregistry: `0x${string}`\n\tredirectUrl?: string\n\tconsent: AgentLinkConsentOutput\n\tbranding?: AgentLinkSessionBranding\n\tmetadata?: Record<string, string>\n\texpiresAt?: string\n}\n\nexport interface CreateLinkSessionInput {\n\tplatformAccountId: string\n\tworkspaceId?: string\n\tnetwork: BiomapperBridgeNetwork\n\tregistry: `0x${string}`\n\tredirectUrl?: string\n\tconsent: AgentLinkConsentOutput\n\tbranding?: AgentLinkSessionBranding\n\tmetadata?: Record<string, string>\n\texpiresAt?: string\n}\n\nexport interface AgentLinkSessionStore {\n\tset(session: AgentLinkSession): Promise<void>\n\tget(id: string): Promise<AgentLinkSession | null>\n}\n\nexport interface CreateLinkSessionOptions {\n\tid?: string\n\tnow?: Date\n\tstore?: AgentLinkSessionStore\n\tonEvent?: AgentLinkEventHandler<AgentLinkSessionEvent>\n\tallowedRedirectOrigins?: readonly string[]\n}\n\nexport interface LinkSessionValidationOptions {\n\tnow?: Date\n\tallowedRedirectOrigins?: readonly string[]\n}\n\nexport type LinkSessionValidationResult = { valid: true; session: AgentLinkSession } | { valid: false; error: string }\n\nexport class InMemoryLinkSessionStore implements AgentLinkSessionStore {\n\tprivate sessions = new Map<string, AgentLinkSession>()\n\n\tasync set(session: AgentLinkSession): Promise<void> {\n\t\tthis.sessions.set(session.id, session)\n\t}\n\n\tasync get(id: string): Promise<AgentLinkSession | null> {\n\t\treturn this.sessions.get(id) ?? null\n\t}\n}\n\nfunction createSessionId(): string {\n\tif (typeof globalThis.crypto?.randomUUID === 'function') {\n\t\treturn `als_${globalThis.crypto.randomUUID()}`\n\t}\n\tif (typeof globalThis.crypto?.getRandomValues === 'function') {\n\t\tconst bytes = new Uint8Array(8)\n\t\tglobalThis.crypto.getRandomValues(bytes)\n\t\tconst randomStr = Array.from(bytes, b => b.toString(16).padStart(2, '0')).join('')\n\t\treturn `als_${Date.now().toString(36)}_${randomStr}`\n\t}\n\n\tthrow new Error('crypto.getRandomValues is not available in this environment')\n}\n\nconst NETWORK_CHAIN_IDS: Record<BiomapperBridgeNetwork, number> = {\n\tbase: 8453,\n\t'base-sepolia': 84532,\n}\n\nfunction isNetworkName(value: unknown): value is BiomapperBridgeNetwork {\n\treturn value === 'base' || value === 'base-sepolia'\n}\n\nfunction parseOptionalStringRecord(input: unknown): Record<string, string> | undefined {\n\tif (!input || typeof input !== 'object' || Array.isArray(input)) {\n\t\treturn undefined\n\t}\n\n\tconst entries = Object.entries(input)\n\tif (entries.some(([, value]) => typeof value !== 'string')) {\n\t\treturn undefined\n\t}\n\n\treturn Object.fromEntries(entries) as Record<string, string>\n}\n\nfunction normalizeHttpsBrandingUrl(\n\tvalue: unknown,\n\tlabel: 'logoUrl' | 'supportUrl'\n): { valid: true; value?: string } | { valid: false; error: string } {\n\tif (value === undefined) {\n\t\treturn { valid: true }\n\t}\n\tif (typeof value !== 'string') {\n\t\treturn { valid: false, error: `Hosted link sessions must use a string branding.${label}.` }\n\t}\n\n\tlet parsed: URL\n\ttry {\n\t\tparsed = new URL(value)\n\t} catch {\n\t\treturn { valid: false, error: `Hosted link sessions must use an absolute branding.${label}.` }\n\t}\n\n\tif (parsed.protocol !== 'https:') {\n\t\treturn { valid: false, error: `Hosted link sessions only allow https branding.${label} values.` }\n\t}\n\n\treturn { valid: true, value: parsed.toString() }\n}\n\nfunction parseBranding(\n\tinput: unknown\n): { valid: true; branding?: AgentLinkSessionBranding } | { valid: false; error: string } {\n\tif (!input || typeof input !== 'object' || Array.isArray(input)) {\n\t\treturn { valid: true }\n\t}\n\n\tconst parsed = input as Partial<AgentLinkSessionBranding>\n\tconst branding: AgentLinkSessionBranding = {}\n\tif (typeof parsed.platformName === 'string') branding.platformName = parsed.platformName\n\tif (typeof parsed.accentColor === 'string') branding.accentColor = parsed.accentColor\n\n\tconst logoUrl = normalizeHttpsBrandingUrl(parsed.logoUrl, 'logoUrl')\n\tif (!logoUrl.valid) {\n\t\treturn logoUrl\n\t}\n\tif (logoUrl.value) branding.logoUrl = logoUrl.value\n\n\tconst supportUrl = normalizeHttpsBrandingUrl(parsed.supportUrl, 'supportUrl')\n\tif (!supportUrl.valid) {\n\t\treturn supportUrl\n\t}\n\tif (supportUrl.value) branding.supportUrl = supportUrl.value\n\n\treturn Object.keys(branding).length > 0 ? { valid: true, branding } : { valid: true }\n}\n\nfunction normalizeAllowedRedirectOrigins(allowedRedirectOrigins?: readonly string[]): Set<string> | undefined {\n\tif (!allowedRedirectOrigins?.length) {\n\t\treturn undefined\n\t}\n\n\tconst origins = new Set<string>()\n\tfor (const value of allowedRedirectOrigins) {\n\t\tlet parsed: URL\n\t\ttry {\n\t\t\tparsed = new URL(value)\n\t\t} catch {\n\t\t\tthrow new Error(`Invalid allowed redirect origin \"${value}\". Expected an absolute URL origin.`)\n\t\t}\n\n\t\tif (parsed.protocol !== 'https:') {\n\t\t\tthrow new Error(`Invalid allowed redirect origin \"${value}\". Redirect origins must use https.`)\n\t\t}\n\n\t\torigins.add(parsed.origin)\n\t}\n\n\treturn origins\n}\n\nfunction validateRedirectUrl(\n\tvalue: unknown,\n\tallowedOrigins: Set<string> | undefined\n): { valid: true; redirectUrl?: string } | { valid: false; error: string } {\n\tif (value === undefined) {\n\t\treturn { valid: true }\n\t}\n\tif (typeof value !== 'string') {\n\t\treturn { valid: false, error: 'Hosted link sessions must use a string redirectUrl.' }\n\t}\n\n\tlet redirectUrl: URL\n\ttry {\n\t\tredirectUrl = new URL(value)\n\t} catch {\n\t\treturn { valid: false, error: 'Hosted link sessions must use an absolute redirectUrl.' }\n\t}\n\n\tif (redirectUrl.protocol !== 'https:') {\n\t\treturn { valid: false, error: 'Hosted link sessions only allow https redirect URLs.' }\n\t}\n\n\tif (allowedOrigins && !allowedOrigins.has(redirectUrl.origin)) {\n\t\treturn {\n\t\t\tvalid: false,\n\t\t\terror: `Hosted link sessions only allow redirects to these origins: ${Array.from(allowedOrigins).join(', ')}`,\n\t\t}\n\t}\n\n\treturn { valid: true, redirectUrl: redirectUrl.toString() }\n}\n\nfunction parseConsentBlob(\n\tinput: unknown\n): { valid: true; consent: AgentLinkConsentOutput } | { valid: false; error: string } {\n\tif (!input || typeof input !== 'object' || Array.isArray(input)) {\n\t\treturn { valid: false, error: 'Hosted link sessions require an embedded agent consent payload.' }\n\t}\n\n\tconst parsed = input as Partial<AgentLinkConsentOutput>\n\tif (parsed.type !== 'biomapper-agent-link') {\n\t\treturn { valid: false, error: 'Hosted link sessions require a biomapper-agent-link consent payload.' }\n\t}\n\tif (!isNetworkName(parsed.network)) {\n\t\treturn { valid: false, error: 'Hosted link sessions must use a valid consent network.' }\n\t}\n\tif (typeof parsed.chainId !== 'number') {\n\t\treturn { valid: false, error: 'Hosted link sessions must include a valid consent chain id.' }\n\t}\n\tif (!parsed.agent || !isAddress(parsed.agent)) {\n\t\treturn { valid: false, error: 'Hosted link sessions must include a valid consent agent wallet.' }\n\t}\n\tif (!parsed.owner || !isAddress(parsed.owner)) {\n\t\treturn { valid: false, error: 'Hosted link sessions must include a valid consent owner wallet.' }\n\t}\n\tif (!parsed.registry || !isAddress(parsed.registry)) {\n\t\treturn { valid: false, error: 'Hosted link sessions must include a valid consent registry address.' }\n\t}\n\tif (!parsed.signature || !/^0x[0-9a-fA-F]+$/u.test(parsed.signature)) {\n\t\treturn { valid: false, error: 'Hosted link sessions must include a valid consent signature.' }\n\t}\n\tif (!parsed.deadline || !/^\\d+$/u.test(parsed.deadline)) {\n\t\treturn { valid: false, error: 'Hosted link sessions must include a valid consent expiry.' }\n\t}\n\tif (!parsed.nonce || !/^\\d+$/u.test(parsed.nonce)) {\n\t\treturn { valid: false, error: 'Hosted link sessions must include a valid consent nonce.' }\n\t}\n\tif (!parsed.typedData || typeof parsed.typedData !== 'object' || Array.isArray(parsed.typedData)) {\n\t\treturn { valid: false, error: 'Hosted link sessions must include consent typed data.' }\n\t}\n\tif (\n\t\t!parsed.typedData.domain ||\n\t\ttypeof parsed.typedData.domain !== 'object' ||\n\t\tArray.isArray(parsed.typedData.domain) ||\n\t\tparsed.typedData.domain.chainId !== parsed.chainId ||\n\t\ttypeof parsed.typedData.domain.verifyingContract !== 'string' ||\n\t\tparsed.typedData.domain.verifyingContract.toLowerCase() !== parsed.registry.toLowerCase()\n\t) {\n\t\treturn { valid: false, error: 'Hosted link sessions have mismatched consent typed data.' }\n\t}\n\tif (\n\t\t!parsed.typedData.message ||\n\t\ttypeof parsed.typedData.message !== 'object' ||\n\t\tArray.isArray(parsed.typedData.message) ||\n\t\ttypeof parsed.typedData.message.agent !== 'string' ||\n\t\tparsed.typedData.message.agent.toLowerCase() !== parsed.agent.toLowerCase() ||\n\t\ttypeof parsed.typedData.message.owner !== 'string' ||\n\t\tparsed.typedData.message.owner.toLowerCase() !== parsed.owner.toLowerCase() ||\n\t\tparsed.typedData.message.nonce !== parsed.nonce ||\n\t\tparsed.typedData.message.deadline !== parsed.deadline\n\t) {\n\t\treturn { valid: false, error: 'Hosted link sessions have mismatched consent message details.' }\n\t}\n\n\treturn {\n\t\tvalid: true,\n\t\tconsent: parsed as AgentLinkConsentOutput,\n\t}\n}\n\nexport function validateLinkSession(\n\tsession: unknown,\n\toptions: LinkSessionValidationOptions = {}\n): LinkSessionValidationResult {\n\tif (!session || typeof session !== 'object' || Array.isArray(session)) {\n\t\treturn { valid: false, error: 'Hosted link sessions must be objects.' }\n\t}\n\n\tconst parsed = session as Partial<AgentLinkSession>\n\tif (!parsed.id || typeof parsed.id !== 'string') {\n\t\treturn { valid: false, error: 'Hosted link sessions must include an id.' }\n\t}\n\tif (!parsed.createdAt || typeof parsed.createdAt !== 'string' || !Number.isFinite(Date.parse(parsed.createdAt))) {\n\t\treturn { valid: false, error: 'Hosted link sessions must include a valid createdAt timestamp.' }\n\t}\n\tif (!parsed.platformAccountId || typeof parsed.platformAccountId !== 'string') {\n\t\treturn { valid: false, error: 'Hosted link sessions must include a platformAccountId.' }\n\t}\n\tif (!isNetworkName(parsed.network)) {\n\t\treturn { valid: false, error: 'Hosted link sessions must use a valid network.' }\n\t}\n\tif (!parsed.registry || !isAddress(parsed.registry)) {\n\t\treturn { valid: false, error: 'Hosted link sessions must include a valid registry address.' }\n\t}\n\tif (parsed.workspaceId !== undefined && typeof parsed.workspaceId !== 'string') {\n\t\treturn { valid: false, error: 'Hosted link sessions must use a string workspaceId when provided.' }\n\t}\n\tif (parsed.expiresAt !== undefined) {\n\t\tif (typeof parsed.expiresAt !== 'string' || !Number.isFinite(Date.parse(parsed.expiresAt))) {\n\t\t\treturn { valid: false, error: 'Hosted link sessions must use a valid expiresAt timestamp.' }\n\t\t}\n\t}\n\n\tconst allowedOrigins = normalizeAllowedRedirectOrigins(options.allowedRedirectOrigins)\n\tconst redirectValidation = validateRedirectUrl(parsed.redirectUrl, allowedOrigins)\n\tif (!redirectValidation.valid) {\n\t\treturn redirectValidation\n\t}\n\n\tconst consentValidation = parseConsentBlob(parsed.consent)\n\tif (!consentValidation.valid) {\n\t\treturn consentValidation\n\t}\n\n\tconst consent = consentValidation.consent\n\tif (consent.network !== parsed.network) {\n\t\treturn { valid: false, error: 'Hosted link sessions have mismatched network details.' }\n\t}\n\tif (consent.chainId !== NETWORK_CHAIN_IDS[parsed.network]) {\n\t\treturn { valid: false, error: 'Hosted link sessions have mismatched chain details.' }\n\t}\n\tif (consent.registry.toLowerCase() !== parsed.registry.toLowerCase()) {\n\t\treturn { valid: false, error: 'Hosted link sessions have mismatched registry details.' }\n\t}\n\n\tconst now = options.now ?? new Date()\n\tif (BigInt(consent.deadline) <= BigInt(Math.floor(now.getTime() / 1000))) {\n\t\treturn { valid: false, error: 'Hosted link sessions have expired embedded consent.' }\n\t}\n\tif (parsed.expiresAt && Date.parse(parsed.expiresAt) <= now.getTime()) {\n\t\treturn { valid: false, error: 'Hosted link sessions have expired.' }\n\t}\n\n\tconst branding = parseBranding(parsed.branding)\n\tif (!branding.valid) {\n\t\treturn branding\n\t}\n\tconst metadata = parseOptionalStringRecord(parsed.metadata)\n\n\treturn {\n\t\tvalid: true,\n\t\tsession: {\n\t\t\tid: parsed.id,\n\t\t\tcreatedAt: parsed.createdAt,\n\t\t\tplatformAccountId: parsed.platformAccountId,\n\t\t\t...(parsed.workspaceId ? { workspaceId: parsed.workspaceId } : {}),\n\t\t\tnetwork: parsed.network,\n\t\t\tregistry: parsed.registry,\n\t\t\t...(redirectValidation.redirectUrl ? { redirectUrl: redirectValidation.redirectUrl } : {}),\n\t\t\tconsent,\n\t\t\t...(branding.branding ? { branding: branding.branding } : {}),\n\t\t\t...(metadata ? { metadata } : {}),\n\t\t\t...(parsed.expiresAt ? { expiresAt: parsed.expiresAt } : {}),\n\t\t},\n\t}\n}\n\nexport async function createLinkSession(\n\tinput: CreateLinkSessionInput,\n\toptions: CreateLinkSessionOptions = {}\n): Promise<AgentLinkSession> {\n\tif (!input.registry) {\n\t\tthrow new Error('Hosted link sessions require a registry address.')\n\t}\n\n\tif (!input.consent) {\n\t\tthrow new Error('Hosted link sessions require an embedded agent consent payload.')\n\t}\n\n\tconst createdAt = (options.now ?? new Date()).toISOString()\n\tconst session: AgentLinkSession = {\n\t\tid: options.id ?? createSessionId(),\n\t\tcreatedAt,\n\t\tplatformAccountId: input.platformAccountId,\n\t\tworkspaceId: input.workspaceId,\n\t\tnetwork: input.network,\n\t\tregistry: input.registry,\n\t\tredirectUrl: input.redirectUrl,\n\t\tconsent: input.consent,\n\t\tbranding: input.branding,\n\t\tmetadata: input.metadata,\n\t\texpiresAt: input.expiresAt,\n\t}\n\n\tconst validation = validateLinkSession(session, {\n\t\tnow: options.now,\n\t\tallowedRedirectOrigins: options.allowedRedirectOrigins,\n\t})\n\tif (!validation.valid) {\n\t\tthrow new Error(validation.error)\n\t}\n\n\tif (options.store) {\n\t\tawait options.store.set(validation.session)\n\t}\n\n\tawait options.onEvent?.({\n\t\ttype: 'link.created',\n\t\tsessionId: validation.session.id,\n\t\tplatformAccountId: validation.session.platformAccountId,\n\t\tworkspaceId: validation.session.workspaceId,\n\t\tnetwork: validation.session.network,\n\t\tredirectUrl: validation.session.redirectUrl,\n\t\tregistry: validation.session.registry,\n\t\tplatformName: validation.session.branding?.platformName,\n\t})\n\n\treturn validation.session\n}\n\nexport async function getLinkSession(\n\tid: string,\n\toptions: { store: AgentLinkSessionStore }\n): Promise<AgentLinkSession | null> {\n\treturn options.store.get(id)\n}\n\nexport function encodeLinkSession(session: AgentLinkSession): string {\n\treturn Buffer.from(JSON.stringify(session), 'utf8').toString('base64url')\n}\n\nexport function decodeLinkSession(value: string): AgentLinkSession {\n\treturn JSON.parse(Buffer.from(value, 'base64url').toString('utf8')) as AgentLinkSession\n}\n\nexport function buildHostedLinkUrl(baseUrl: string, session: AgentLinkSession): string {\n\tconst url = new URL(baseUrl)\n\turl.searchParams.set('sessionId', session.id)\n\treturn url.toString()\n}\n\nexport function buildEmbeddedHostedLinkUrl(baseUrl: string, session: AgentLinkSession): string {\n\tconst url = new URL(baseUrl)\n\turl.searchParams.set('sessionId', session.id)\n\turl.searchParams.set('session', encodeLinkSession(session))\n\treturn url.toString()\n}\n","import { registerExactEvmScheme } from '@x402/evm/exact/server'\nimport type { Network, Price, SchemeNetworkServer } from '@x402/core/types'\nimport { HTTPFacilitatorClient, x402ResourceServer, type FacilitatorClient } from '@x402/core/server'\nimport {\n\tx402HTTPResourceServer,\n\ttype DynamicPayTo,\n\ttype DynamicPrice,\n\ttype PaymentOption,\n\ttype PaywallConfig,\n\ttype PaywallProvider,\n\ttype RouteConfig,\n\ttype RoutesConfig,\n} from '@x402/core/http'\n\nimport { createAgentLinkHooks } from './hooks'\nimport { declareAgentLinkExtension } from './declare'\nimport { agentlinkResourceServerExtension } from './server'\nimport { createAgentLinkWebhookDispatcher } from './webhooks'\nimport { createHonoPaymentMiddlewareFromHTTPServer } from './hono'\nimport type { AgentLinkMode, DeclareAgentLinkOptions } from './types'\nimport type { AgentLinkEvent, AgentLinkEventHandler } from './events'\nimport { InMemoryAgentLinkStorage, type AgentLinkStorage } from './storage'\nimport type { AgentLinkEntitlementContext, AgentLinkEntitlementResolver } from './events'\nimport { createBiomapperRegistryVerifier, type BiomapperRegistryNetwork } from './biomapper-registry'\n\nconst NETWORK_TO_CHAIN_ID: Record<BiomapperRegistryNetwork, Network> = {\n\tbase: 'eip155:8453',\n\t'base-sepolia': 'eip155:84532',\n}\n\nconst DEFAULT_X402_FACILITATOR_URL = 'https://x402.org/facilitator'\nlet hasWarnedAboutInMemoryStorageDefault = false\n\nexport interface BiomapperLinkProtectedRoute extends Omit<RouteConfig, 'accepts'> {\n\tprice: Price | DynamicPrice\n\tpayTo: string | DynamicPayTo\n\tnetwork?: Network\n\tscheme?: 'exact'\n\tmaxTimeoutSeconds?: number\n\textra?: Record<string, unknown>\n}\n\nexport interface BiomapperLinkSchemeRegistration {\n\tnetwork: Network\n\tserver: SchemeNetworkServer\n}\n\n/** Generic middleware signature compatible with Hono and similar frameworks. */\nexport type AgentLinkMiddleware<TContext = unknown> = (\n\tcontext: TContext,\n\tnext: () => Promise<void>\n) => Promise<Response | void>\n\nexport interface BiomapperLinkCallable {\n\t<TContext = unknown>(context: TContext, next: () => Promise<void>): Promise<Response | void>\n}\n\nexport interface BiomapperLinkOptions {\n\t/** \"base\" or \"base-sepolia\" */\n\tnetwork: BiomapperRegistryNetwork\n\t/** Deployed BiomapperAgentRegistry contract address. */\n\tregistry: `0x${string}`\n\t/** Access mode for linked agents. Defaults to \"free\". */\n\tmode?: AgentLinkMode\n\t/** Storage backend for nonce replay protection and usage tracking. In production, this must be explicit. */\n\tstorage?: AgentLinkStorage\n\t/** Event handler for hook events (agent_verified, link.activated, etc.) */\n\tonEvent?: AgentLinkEventHandler\n\t/** Usage count thresholds that trigger usage.threshold_reached events. */\n\tusageThresholds?: number[]\n\t/** Custom RPC URL for contract reads and signature verification. */\n\trpcUrl?: string\n\t/** Static or dynamic entitlement resolver for multi-tenant usage scoping. */\n\tentitlements?: AgentLinkEntitlementContext | AgentLinkEntitlementResolver\n\t/** Forward hook events to a webhook endpoint. */\n\twebhook?: {\n\t\turl: string | string[]\n\t\tsecret?: string\n\t\theaders?: Record<string, string>\n\t}\n\t/** Statement shown in the agent's SIWE signing prompt. */\n\tstatement?: string\n\t/** Domain for the SIWE message. Derived from request URL if omitted. */\n\tdomain?: string\n\t/** Simplified x402 route config for the ready-to-use middleware path. */\n\tprotect?: Record<string, BiomapperLinkProtectedRoute>\n\t/** Full x402 routes config for the ready-to-use middleware path. */\n\troutes?: RoutesConfig\n\t/** Custom facilitator client(s) for the ready-to-use middleware path. */\n\tfacilitator?: FacilitatorClient | FacilitatorClient[]\n\t/** Override the default x402 facilitator URL for the ready-to-use middleware path. */\n\tfacilitatorUrl?: string\n\t/** Override automatic exact-EVM scheme registration for the ready-to-use middleware path. */\n\tschemes?: BiomapperLinkSchemeRegistration[]\n\t/** Built-in paywall config for the ready-to-use middleware path. */\n\tpaywallConfig?: PaywallConfig\n\t/** Custom paywall provider for the ready-to-use middleware path. */\n\tpaywall?: PaywallProvider\n}\n\nexport interface BiomapperLinkControlSurface {\n\textension: typeof agentlinkResourceServerExtension\n\tdeclare(overrides?: Partial<DeclareAgentLinkOptions>): ReturnType<typeof declareAgentLinkExtension>\n\trequestHook: ReturnType<typeof createAgentLinkHooks>['requestHook']\n\tverifyFailureHook: ReturnType<typeof createAgentLinkHooks>['verifyFailureHook']\n\tmiddleware: AgentLinkMiddleware\n\tinitialize(): Promise<void>\n\tresourceServer?: x402ResourceServer\n\thttpServer?: x402HTTPResourceServer\n}\n\n/**\n * One-call setup for Biomapper Link.\n *\n * Collapses registry verifier, storage, hooks, extension declaration,\n * and webhook wiring into a single factory. When `protect` or `routes`\n * is provided, the returned value is also a ready-to-use middleware.\n *\n * @example\n * ```ts\n * const link = createBiomapperLink({\n * network: \"base-sepolia\",\n * registry: \"0xYourRegistry\",\n * protect: {\n * \"GET /data\": {\n * price: \"$0.01\",\n * payTo: \"0xYourPayoutAddress\",\n * },\n * },\n * });\n *\n * app.use(link);\n * ```\n */\nexport function createBiomapperLink(options: BiomapperLinkOptions): BiomapperLink {\n\tconst chainId = NETWORK_TO_CHAIN_ID[options.network]\n\tconst storage = options.storage ?? resolveDefaultStorage()\n\n\tconst registry = createBiomapperRegistryVerifier({\n\t\tcontractAddress: options.registry,\n\t\tnetwork: options.network,\n\t\trpcUrl: options.rpcUrl,\n\t})\n\n\tlet onEvent: AgentLinkEventHandler | undefined = options.onEvent\n\tif (options.webhook) {\n\t\tconst webhookDispatcher = createAgentLinkWebhookDispatcher({\n\t\t\turl: options.webhook.url,\n\t\t\tsecret: options.webhook.secret,\n\t\t\theaders: options.webhook.headers,\n\t\t})\n\t\tconst userOnEvent = onEvent\n\t\tonEvent = async (event: AgentLinkEvent) => {\n\t\t\tawait webhookDispatcher(event)\n\t\t\tawait userOnEvent?.(event)\n\t\t}\n\t}\n\n\tconst hooks = createAgentLinkHooks({\n\t\tregistry,\n\t\tstorage,\n\t\tmode: options.mode,\n\t\trpcUrl: options.rpcUrl,\n\t\tonEvent,\n\t\tentitlements: options.entitlements,\n\t\tusageThresholds: options.usageThresholds,\n\t})\n\n\tconst declare = (overrides?: Partial<DeclareAgentLinkOptions>) =>\n\t\tdeclareAgentLinkExtension({\n\t\t\tnetwork: chainId,\n\t\t\tmode: options.mode,\n\t\t\tstatement: options.statement,\n\t\t\tdomain: options.domain,\n\t\t\t...overrides,\n\t\t})\n\n\tlet resourceServer: x402ResourceServer | undefined\n\tlet httpServer: x402HTTPResourceServer | undefined\n\tlet middleware: AgentLinkMiddleware = async () => {\n\t\tthrow new Error(\n\t\t\t'createBiomapperLink was used as middleware without x402 route configuration. Pass `protect` or `routes` to enable the one-call middleware path.'\n\t\t)\n\t}\n\tlet initialize = async () => {}\n\n\tconst routes = buildRoutes(options, declare(), chainId)\n\tif (routes) {\n\t\tresourceServer = new x402ResourceServer(resolveFacilitatorClients(options))\n\t\tresourceServer.registerExtension(agentlinkResourceServerExtension)\n\t\tif (hooks.verifyFailureHook) {\n\t\t\tresourceServer.onVerifyFailure(async context => {\n\t\t\t\tconst url = context.paymentPayload.resource?.url\n\t\t\t\tif (!url) return\n\n\t\t\t\treturn hooks.verifyFailureHook?.({\n\t\t\t\t\tpaymentPayload: {\n\t\t\t\t\t\tresource: { url },\n\t\t\t\t\t\tpayload: context.paymentPayload.payload as Record<string, unknown>,\n\t\t\t\t\t},\n\t\t\t\t\trequirements: {\n\t\t\t\t\t\tamount: context.requirements.amount,\n\t\t\t\t\t},\n\t\t\t\t\terror: context.error,\n\t\t\t\t})\n\t\t\t})\n\t\t}\n\n\t\tif (options.schemes?.length) {\n\t\t\tfor (const scheme of options.schemes) {\n\t\t\t\tresourceServer.register(scheme.network, scheme.server)\n\t\t\t}\n\t\t} else {\n\t\t\tregisterExactEvmScheme(resourceServer, {\n\t\t\t\tnetworks: collectExactEvmNetworks(routes),\n\t\t\t})\n\t\t}\n\n\t\thttpServer = new x402HTTPResourceServer(resourceServer, routes).onProtectedRequest(hooks.requestHook)\n\t\tconst hono = createHonoPaymentMiddlewareFromHTTPServer(httpServer, options.paywallConfig, options.paywall)\n\t\tmiddleware = hono.middleware\n\t\tinitialize = hono.initialize\n\t}\n\n\treturn Object.assign(middleware as BiomapperLinkCallable, {\n\t\textension: agentlinkResourceServerExtension,\n\t\tdeclare,\n\t\trequestHook: hooks.requestHook,\n\t\tverifyFailureHook: hooks.verifyFailureHook,\n\t\tmiddleware,\n\t\tinitialize,\n\t\tresourceServer,\n\t\thttpServer,\n\t})\n}\n\nfunction resolveDefaultStorage(): AgentLinkStorage {\n\tif (process.env.NODE_ENV === 'production') {\n\t\tthrow new Error(\n\t\t\t'createBiomapperLink requires an explicit storage backend in production. Pass persistent/shared storage instead of relying on the in-memory development default.'\n\t\t)\n\t}\n\n\tif (!hasWarnedAboutInMemoryStorageDefault) {\n\t\thasWarnedAboutInMemoryStorageDefault = true\n\t\tconsole.warn(\n\t\t\t'[agentlink] createBiomapperLink is using InMemoryAgentLinkStorage because no storage backend was provided. This is only safe for local development and tests.'\n\t\t)\n\t}\n\n\treturn new InMemoryAgentLinkStorage()\n}\n\nfunction buildRoutes(\n\toptions: BiomapperLinkOptions,\n\tagentlinkExtensions: ReturnType<typeof declareAgentLinkExtension>,\n\tdefaultNetwork: Network\n): RoutesConfig | undefined {\n\tif (options.routes && options.protect) {\n\t\tthrow new Error('Pass either `routes` or `protect` to createBiomapperLink, not both.')\n\t}\n\n\tif (options.routes) {\n\t\treturn mergeAgentLinkExtensions(options.routes, agentlinkExtensions)\n\t}\n\n\tif (!options.protect) return undefined\n\n\treturn Object.fromEntries(\n\t\tObject.entries(options.protect).map(([pattern, config]) => [\n\t\t\tpattern,\n\t\t\t{\n\t\t\t\tresource: config.resource,\n\t\t\t\tdescription: config.description,\n\t\t\t\tmimeType: config.mimeType,\n\t\t\t\tcustomPaywallHtml: config.customPaywallHtml,\n\t\t\t\tunpaidResponseBody: config.unpaidResponseBody,\n\t\t\t\tsettlementFailedResponseBody: config.settlementFailedResponseBody,\n\t\t\t\textensions: {\n\t\t\t\t\t...agentlinkExtensions,\n\t\t\t\t\t...(config.extensions ?? {}),\n\t\t\t\t},\n\t\t\t\taccepts: {\n\t\t\t\t\tscheme: config.scheme ?? 'exact',\n\t\t\t\t\tnetwork: config.network ?? defaultNetwork,\n\t\t\t\t\tpayTo: config.payTo,\n\t\t\t\t\tprice: config.price,\n\t\t\t\t\tmaxTimeoutSeconds: config.maxTimeoutSeconds,\n\t\t\t\t\textra: config.extra,\n\t\t\t\t},\n\t\t\t} satisfies RouteConfig,\n\t\t])\n\t)\n}\n\nfunction mergeAgentLinkExtensions(\n\troutes: RoutesConfig,\n\tagentlinkExtensions: ReturnType<typeof declareAgentLinkExtension>\n): RoutesConfig {\n\tif (isRouteConfig(routes)) {\n\t\treturn {\n\t\t\t...routes,\n\t\t\textensions: {\n\t\t\t\t...agentlinkExtensions,\n\t\t\t\t...(routes.extensions ?? {}),\n\t\t\t},\n\t\t}\n\t}\n\n\treturn Object.fromEntries(\n\t\tObject.entries(routes).map(([pattern, route]) => [\n\t\t\tpattern,\n\t\t\t{\n\t\t\t\t...route,\n\t\t\t\textensions: {\n\t\t\t\t\t...agentlinkExtensions,\n\t\t\t\t\t...(route.extensions ?? {}),\n\t\t\t\t},\n\t\t\t},\n\t\t])\n\t)\n}\n\nfunction collectExactEvmNetworks(routes: RoutesConfig): Network[] {\n\tconst routeList = isRouteConfig(routes) ? [routes] : Object.values(routes)\n\tconst networks = new Set<Network>()\n\n\tfor (const route of routeList) {\n\t\tconst accepts = normalizePaymentOptions(route)\n\t\tfor (const option of accepts) {\n\t\t\tif (option.scheme !== 'exact') {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Auto-registration only supports the x402 \"exact\" scheme. Register custom schemes via \\`schemes\\` for \"${option.scheme}\".`\n\t\t\t\t)\n\t\t\t}\n\t\t\tif (!option.network.startsWith('eip155:')) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Auto-registration only supports EVM payment networks. Register custom schemes via \\`schemes\\` for \"${option.network}\".`\n\t\t\t\t)\n\t\t\t}\n\t\t\tnetworks.add(option.network)\n\t\t}\n\t}\n\n\treturn [...networks]\n}\n\nfunction isRouteConfig(routes: RoutesConfig): routes is RouteConfig {\n\treturn 'accepts' in routes\n}\n\nfunction normalizePaymentOptions(route: RouteConfig): PaymentOption[] {\n\treturn Array.isArray(route.accepts) ? route.accepts : [route.accepts]\n}\n\nfunction resolveFacilitatorClients(options: BiomapperLinkOptions): FacilitatorClient | FacilitatorClient[] {\n\treturn (\n\t\toptions.facilitator ??\n\t\tnew HTTPFacilitatorClient({ url: options.facilitatorUrl ?? DEFAULT_X402_FACILITATOR_URL })\n\t)\n}\n\nexport type BiomapperLink = BiomapperLinkCallable & BiomapperLinkControlSurface\n","import type { AgentLinkEvent, AgentLinkEventHandler } from './events'\n\nexport interface AgentLinkWebhookEnvelope<TEvent extends AgentLinkEvent = AgentLinkEvent> {\n\tid: string\n\tcreatedAt: string\n\ttype: TEvent['type']\n\tevent: TEvent\n}\n\nexport interface AgentLinkWebhookDispatcherOptions {\n\turl: string | string[]\n\theaders?: Record<string, string>\n\tsecret?: string\n\tincludeLegacySecretHeader?: boolean\n\tfetchImpl?: typeof fetch\n}\n\nexport interface VerifyAgentLinkWebhookSignatureOptions {\n\tsecret: string\n\ttimestamp: string\n\tsignature: string\n\tbody: string | Uint8Array | ArrayBuffer | ArrayBufferView\n\tnow?: Date\n\ttoleranceSeconds?: number\n}\n\nexport interface AgentLinkWebhookSignatureVerificationResult {\n\tvalid: boolean\n\terror?: string\n}\n\nconst WEBHOOK_SIGNATURE_VERSION = 'v1'\nconst DEFAULT_WEBHOOK_TOLERANCE_SECONDS = 5 * 60\n\nfunction createWebhookId(): string {\n\tif (typeof globalThis.crypto?.randomUUID === 'function') {\n\t\treturn globalThis.crypto.randomUUID()\n\t}\n\tif (typeof globalThis.crypto?.getRandomValues === 'function') {\n\t\tconst bytes = new Uint8Array(8)\n\t\tglobalThis.crypto.getRandomValues(bytes)\n\t\tconst randomStr = Array.from(bytes, b => b.toString(16).padStart(2, '0')).join('')\n\t\treturn `evt_${Date.now().toString(36)}_${randomStr}`\n\t}\n\n\tthrow new Error('crypto.getRandomValues is not available in this environment')\n}\n\nfunction resolveFetch(fetchImpl?: typeof fetch): typeof fetch {\n\tif (fetchImpl) return fetchImpl\n\tif (typeof fetch !== 'function') {\n\t\tthrow new Error('No fetch implementation is available. Pass fetchImpl to dispatch AgentLink webhooks.')\n\t}\n\n\treturn fetch\n}\n\nexport function createAgentLinkWebhookEnvelope<TEvent extends AgentLinkEvent>(\n\tevent: TEvent\n): AgentLinkWebhookEnvelope<TEvent> {\n\treturn {\n\t\tid: createWebhookId(),\n\t\tcreatedAt: new Date().toISOString(),\n\t\ttype: event.type,\n\t\tevent,\n\t}\n}\n\nfunction stringifyWebhookEnvelope(envelope: AgentLinkWebhookEnvelope): string {\n\treturn JSON.stringify(envelope, (_key, value) => (typeof value === 'bigint' ? value.toString() : value))\n}\n\nfunction normalizeWebhookBody(body: string | Uint8Array | ArrayBuffer | ArrayBufferView): Uint8Array {\n\tif (typeof body === 'string') {\n\t\treturn new TextEncoder().encode(body)\n\t}\n\tif (body instanceof Uint8Array) {\n\t\treturn body\n\t}\n\tif (body instanceof ArrayBuffer) {\n\t\treturn new Uint8Array(body)\n\t}\n\n\treturn new Uint8Array(body.buffer, body.byteOffset, body.byteLength)\n}\n\nfunction encodeHex(bytes: Uint8Array): string {\n\treturn Array.from(bytes, byte => byte.toString(16).padStart(2, '0')).join('')\n}\n\nfunction constantTimeEqual(left: string, right: string): boolean {\n\tif (left.length !== right.length) return false\n\n\tlet mismatch = 0\n\tfor (let index = 0; index < left.length; index += 1) {\n\t\tmismatch |= left.charCodeAt(index) ^ right.charCodeAt(index)\n\t}\n\n\treturn mismatch === 0\n}\n\nfunction parseSignatureValue(signature: string): string | null {\n\tfor (const part of signature.split(',')) {\n\t\tconst trimmed = part.trim()\n\t\tif (trimmed.startsWith(`${WEBHOOK_SIGNATURE_VERSION}=`)) {\n\t\t\treturn trimmed.slice(WEBHOOK_SIGNATURE_VERSION.length + 1)\n\t\t}\n\t}\n\n\treturn null\n}\n\nasync function createHmacSignature(\n\tsecret: string,\n\ttimestamp: string,\n\tbody: string | Uint8Array | ArrayBuffer | ArrayBufferView\n): Promise<string> {\n\tif (!globalThis.crypto?.subtle) {\n\t\tthrow new Error('Web Crypto is required to sign AgentLink webhooks in this runtime.')\n\t}\n\n\tconst encoder = new TextEncoder()\n\tconst key = await globalThis.crypto.subtle.importKey(\n\t\t'raw',\n\t\tencoder.encode(secret),\n\t\t{ name: 'HMAC', hash: 'SHA-256' },\n\t\tfalse,\n\t\t['sign']\n\t)\n\tconst payload = new Uint8Array([...encoder.encode(`${timestamp}.`), ...normalizeWebhookBody(body)])\n\tconst signature = await globalThis.crypto.subtle.sign('HMAC', key, payload)\n\treturn `${WEBHOOK_SIGNATURE_VERSION}=${encodeHex(new Uint8Array(signature))}`\n}\n\nexport async function verifyAgentLinkWebhookSignature(\n\toptions: VerifyAgentLinkWebhookSignatureOptions\n): Promise<AgentLinkWebhookSignatureVerificationResult> {\n\tif (!/^\\d+$/u.test(options.timestamp)) {\n\t\treturn { valid: false, error: 'Invalid webhook timestamp.' }\n\t}\n\n\tconst timestampSeconds = Number(options.timestamp)\n\tconst nowSeconds = Math.floor((options.now ?? new Date()).getTime() / 1000)\n\tconst toleranceSeconds = options.toleranceSeconds ?? DEFAULT_WEBHOOK_TOLERANCE_SECONDS\n\tif (Math.abs(nowSeconds - timestampSeconds) > toleranceSeconds) {\n\t\treturn { valid: false, error: 'Webhook timestamp is outside the allowed tolerance.' }\n\t}\n\n\tconst providedSignature = parseSignatureValue(options.signature)\n\tif (!providedSignature) {\n\t\treturn { valid: false, error: 'Invalid webhook signature format.' }\n\t}\n\n\tconst expectedSignature = parseSignatureValue(\n\t\tawait createHmacSignature(options.secret, options.timestamp, options.body)\n\t)\n\tif (!expectedSignature || !constantTimeEqual(providedSignature, expectedSignature)) {\n\t\treturn { valid: false, error: 'Webhook signature mismatch.' }\n\t}\n\n\treturn { valid: true }\n}\n\nexport async function dispatchAgentLinkWebhook<TEvent extends AgentLinkEvent>(\n\tevent: TEvent,\n\toptions: AgentLinkWebhookDispatcherOptions\n): Promise<AgentLinkWebhookEnvelope<TEvent>> {\n\tconst fetchImpl = resolveFetch(options.fetchImpl)\n\tconst envelope = createAgentLinkWebhookEnvelope(event)\n\tconst urls = Array.isArray(options.url) ? options.url : [options.url]\n\tconst body = stringifyWebhookEnvelope(envelope)\n\tconst timestamp = Math.floor(Date.now() / 1000).toString()\n\tconst signature = options.secret ? await createHmacSignature(options.secret, timestamp, body) : undefined\n\n\tfor (const url of urls) {\n\t\tconst includeLegacySecretHeader = options.includeLegacySecretHeader ?? true\n\t\tconst response = await fetchImpl(url, {\n\t\t\tmethod: 'POST',\n\t\t\theaders: {\n\t\t\t\t'content-type': 'application/json',\n\t\t\t\t...(options.secret\n\t\t\t\t\t? {\n\t\t\t\t\t\t\t'x-agentlink-webhook-timestamp': timestamp,\n\t\t\t\t\t\t\t'x-agentlink-webhook-signature': signature!,\n\t\t\t\t\t\t\t...(includeLegacySecretHeader ? { 'x-agentlink-webhook-secret': options.secret } : {}),\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t\t...options.headers,\n\t\t\t},\n\t\t\tbody,\n\t\t})\n\n\t\tif (!response.ok) {\n\t\t\tthrow new Error(`AgentLink webhook delivery failed for ${url} with status ${response.status}`)\n\t\t}\n\t}\n\n\treturn envelope\n}\n\nexport function createAgentLinkWebhookDispatcher(options: AgentLinkWebhookDispatcherOptions): AgentLinkEventHandler {\n\treturn async event => {\n\t\tawait dispatchAgentLinkWebhook(event, options)\n\t}\n}\n","import type {\n\tHTTPAdapter,\n\tHTTPRequestContext,\n\tPaywallConfig,\n\tPaywallProvider,\n\tx402HTTPResourceServer,\n} from '@x402/core/server'\n\nexport type HonoLikeMiddleware<TContext = unknown> = (\n\tcontext: TContext,\n\tnext: () => Promise<void>\n) => Promise<Response | void>\n\nexport interface MinimalHonoContext {\n\treq: {\n\t\theader(name: string): string | undefined\n\t\tmethod: string\n\t\tpath: string\n\t\turl: string\n\t\tquery(): Record<string, string | string[]>\n\t\tquery(name: string): string | string[] | undefined\n\t\tjson(): Promise<unknown>\n\t}\n\tres?: Response\n\theader(name: string, value: string): void\n\thtml(body: string, status?: number): Response\n\tjson(body: unknown, status?: number): Response\n}\n\nclass HonoAdapter implements HTTPAdapter {\n\tconstructor(private context: MinimalHonoContext) {}\n\n\tgetHeader(name: string): string | undefined {\n\t\treturn this.context.req.header(name)\n\t}\n\n\tgetMethod(): string {\n\t\treturn this.context.req.method\n\t}\n\n\tgetPath(): string {\n\t\treturn this.context.req.path\n\t}\n\n\tgetUrl(): string {\n\t\treturn this.context.req.url\n\t}\n\n\tgetAcceptHeader(): string {\n\t\treturn this.context.req.header('Accept') ?? ''\n\t}\n\n\tgetUserAgent(): string {\n\t\treturn this.context.req.header('User-Agent') ?? ''\n\t}\n\n\tgetQueryParams(): Record<string, string | string[]> {\n\t\treturn this.context.req.query()\n\t}\n\n\tgetQueryParam(name: string): string | string[] | undefined {\n\t\treturn this.context.req.query(name)\n\t}\n\n\tasync getBody(): Promise<unknown> {\n\t\treturn await this.context.req.json()\n\t}\n}\n\nexport interface HonoPaymentMiddleware {\n\tmiddleware: HonoLikeMiddleware\n\tinitialize(): Promise<void>\n}\n\nexport function createHonoPaymentMiddlewareFromHTTPServer(\n\thttpServer: x402HTTPResourceServer,\n\tpaywallConfig?: PaywallConfig,\n\tpaywall?: PaywallProvider\n): HonoPaymentMiddleware {\n\tif (paywall) {\n\t\thttpServer.registerPaywallProvider(paywall)\n\t}\n\n\tlet initialized = false\n\tlet initializePromise: Promise<void> | null = null\n\n\tasync function initialize() {\n\t\tif (initialized) return\n\t\tif (!initializePromise) {\n\t\t\tinitializePromise = httpServer\n\t\t\t\t.initialize()\n\t\t\t\t.then(() => {\n\t\t\t\t\tinitialized = true\n\t\t\t\t})\n\t\t\t\t.catch(error => {\n\t\t\t\t\tinitializePromise = null\n\t\t\t\t\tthrow error\n\t\t\t\t})\n\t\t}\n\n\t\tawait initializePromise\n\t}\n\n\tconst middleware: HonoLikeMiddleware = async (context, next) => {\n\t\tconst typedContext = context as MinimalHonoContext\n\t\tconst adapter = new HonoAdapter(typedContext)\n\t\tconst requestContext: HTTPRequestContext = {\n\t\t\tadapter,\n\t\t\tpath: typedContext.req.path,\n\t\t\tmethod: typedContext.req.method,\n\t\t\tpaymentHeader: adapter.getHeader('payment-signature') || adapter.getHeader('x-payment'),\n\t\t}\n\n\t\tif (!httpServer.requiresPayment(requestContext)) {\n\t\t\treturn next()\n\t\t}\n\n\t\tawait initialize()\n\n\t\tconst result = await httpServer.processHTTPRequest(requestContext, paywallConfig)\n\t\tswitch (result.type) {\n\t\t\tcase 'no-payment-required':\n\t\t\t\treturn next()\n\t\t\tcase 'payment-error': {\n\t\t\t\tconst { response } = result\n\t\t\t\tfor (const [key, value] of Object.entries(response.headers)) {\n\t\t\t\t\ttypedContext.header(key, value)\n\t\t\t\t}\n\n\t\t\t\tif (response.isHtml) {\n\t\t\t\t\treturn typedContext.html(String(response.body ?? ''), response.status)\n\t\t\t\t}\n\n\t\t\t\treturn typedContext.json(response.body ?? {}, response.status)\n\t\t\t}\n\t\t\tcase 'payment-verified': {\n\t\t\t\tconst { paymentPayload, paymentRequirements, declaredExtensions } = result\n\t\t\t\tawait next()\n\n\t\t\t\tlet response: Response | undefined = typedContext.res\n\t\t\t\tif (!response || response.status >= 400) {\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tconst responseBody = Buffer.from(await response.clone().arrayBuffer())\n\t\t\t\ttypedContext.res = undefined\n\n\t\t\t\tconst settlement = await httpServer.processSettlement(\n\t\t\t\t\tpaymentPayload,\n\t\t\t\t\tpaymentRequirements,\n\t\t\t\t\tdeclaredExtensions,\n\t\t\t\t\t{\n\t\t\t\t\t\trequest: requestContext,\n\t\t\t\t\t\tresponseBody,\n\t\t\t\t\t}\n\t\t\t\t)\n\n\t\t\t\tif (!settlement.success) {\n\t\t\t\t\tconst { response: errorResponse } = settlement\n\t\t\t\t\tconst body = errorResponse.isHtml\n\t\t\t\t\t\t? String(errorResponse.body ?? '')\n\t\t\t\t\t\t: JSON.stringify(errorResponse.body ?? {})\n\n\t\t\t\t\tresponse = new Response(body, {\n\t\t\t\t\t\tstatus: errorResponse.status,\n\t\t\t\t\t\theaders: errorResponse.headers,\n\t\t\t\t\t})\n\t\t\t\t} else {\n\t\t\t\t\tfor (const [key, value] of Object.entries(settlement.headers)) {\n\t\t\t\t\t\tresponse.headers.set(key, value)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\ttypedContext.res = response\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\treturn { middleware, initialize }\n}\n","import type {\n\tHTTPAdapter,\n\tHTTPRequestContext,\n\tPaywallConfig,\n\tPaywallProvider,\n\tx402HTTPResourceServer,\n} from '@x402/core/server'\n\nclass NextAdapter implements HTTPAdapter {\n\tconstructor(private request: Request) {}\n\n\tgetHeader(name: string): string | undefined {\n\t\treturn this.request.headers.get(name) ?? undefined\n\t}\n\n\tgetMethod(): string {\n\t\treturn this.request.method\n\t}\n\n\tgetPath(): string {\n\t\treturn new URL(this.request.url).pathname\n\t}\n\n\tgetUrl(): string {\n\t\treturn this.request.url\n\t}\n\n\tgetAcceptHeader(): string {\n\t\treturn this.request.headers.get('Accept') ?? ''\n\t}\n\n\tgetUserAgent(): string {\n\t\treturn this.request.headers.get('User-Agent') ?? ''\n\t}\n\n\tgetQueryParams(): Record<string, string | string[]> {\n\t\tconst params: Record<string, string | string[]> = {}\n\t\tfor (const [key, value] of new URL(this.request.url).searchParams.entries()) {\n\t\t\tconst existing = params[key]\n\t\t\tif (existing === undefined) {\n\t\t\t\tparams[key] = value\n\t\t\t} else if (Array.isArray(existing)) {\n\t\t\t\texisting.push(value)\n\t\t\t} else {\n\t\t\t\tparams[key] = [existing, value]\n\t\t\t}\n\t\t}\n\t\treturn params\n\t}\n\n\tgetQueryParam(name: string): string | string[] | undefined {\n\t\tconst values = new URL(this.request.url).searchParams.getAll(name)\n\t\tif (values.length === 0) return undefined\n\t\treturn values.length === 1 ? values[0] : values\n\t}\n\n\tasync getBody(): Promise<unknown> {\n\t\ttry {\n\t\t\treturn await this.request.clone().json()\n\t\t} catch {\n\t\t\treturn undefined\n\t\t}\n\t}\n}\n\n/** A Next.js App Router route handler: `(request: Request) => Promise<Response>` */\nexport type NextRouteHandler = (request: Request) => Promise<Response>\n\nexport interface NextPaymentMiddleware {\n\t/**\n\t * Wraps a Next.js route handler with x402 payment protection.\n\t *\n\t * @example\n\t * ```ts\n\t * export const GET = payment.wrap(async (req) => Response.json({ ok: true }))\n\t * ```\n\t */\n\twrap(handler: NextRouteHandler): NextRouteHandler\n\tinitialize(): Promise<void>\n}\n\nexport function createNextPaymentHandlerFromHTTPServer(\n\thttpServer: x402HTTPResourceServer,\n\tpaywallConfig?: PaywallConfig,\n\tpaywall?: PaywallProvider\n): NextPaymentMiddleware {\n\tif (paywall) {\n\t\thttpServer.registerPaywallProvider(paywall)\n\t}\n\n\tlet initialized = false\n\tlet initializePromise: Promise<void> | null = null\n\n\tasync function initialize() {\n\t\tif (initialized) return\n\t\tif (!initializePromise) {\n\t\t\tinitializePromise = httpServer\n\t\t\t\t.initialize()\n\t\t\t\t.then(() => {\n\t\t\t\t\tinitialized = true\n\t\t\t\t})\n\t\t\t\t.catch(error => {\n\t\t\t\t\tinitializePromise = null\n\t\t\t\t\tthrow error\n\t\t\t\t})\n\t\t}\n\n\t\tawait initializePromise\n\t}\n\n\tfunction wrap(handler: NextRouteHandler): NextRouteHandler {\n\t\treturn async (request: Request): Promise<Response> => {\n\t\t\tconst adapter = new NextAdapter(request)\n\t\t\tconst requestContext: HTTPRequestContext = {\n\t\t\t\tadapter,\n\t\t\t\tpath: new URL(request.url).pathname,\n\t\t\t\tmethod: request.method,\n\t\t\t\tpaymentHeader: adapter.getHeader('payment-signature') || adapter.getHeader('x-payment'),\n\t\t\t}\n\n\t\t\tif (!httpServer.requiresPayment(requestContext)) {\n\t\t\t\treturn handler(request)\n\t\t\t}\n\n\t\t\tawait initialize()\n\n\t\t\tconst result = await httpServer.processHTTPRequest(requestContext, paywallConfig)\n\t\t\tswitch (result.type) {\n\t\t\t\tcase 'no-payment-required':\n\t\t\t\t\treturn handler(request)\n\n\t\t\t\tcase 'payment-error': {\n\t\t\t\t\tconst { response } = result\n\t\t\t\t\tconst body = response.isHtml ? String(response.body ?? '') : JSON.stringify(response.body ?? {})\n\t\t\t\t\treturn new Response(body, {\n\t\t\t\t\t\tstatus: response.status,\n\t\t\t\t\t\theaders: response.headers,\n\t\t\t\t\t})\n\t\t\t\t}\n\n\t\t\t\tcase 'payment-verified': {\n\t\t\t\t\tconst { paymentPayload, paymentRequirements, declaredExtensions } = result\n\t\t\t\t\tconst handlerResponse = await handler(request)\n\n\t\t\t\t\tif (handlerResponse.status >= 400) {\n\t\t\t\t\t\treturn handlerResponse\n\t\t\t\t\t}\n\n\t\t\t\t\tconst responseBody = Buffer.from(await handlerResponse.clone().arrayBuffer())\n\n\t\t\t\t\tconst settlement = await httpServer.processSettlement(\n\t\t\t\t\t\tpaymentPayload,\n\t\t\t\t\t\tpaymentRequirements,\n\t\t\t\t\t\tdeclaredExtensions,\n\t\t\t\t\t\t{ request: requestContext, responseBody }\n\t\t\t\t\t)\n\n\t\t\t\t\tif (!settlement.success) {\n\t\t\t\t\t\tconst { response: errorResponse } = settlement\n\t\t\t\t\t\tconst body = errorResponse.isHtml\n\t\t\t\t\t\t\t? String(errorResponse.body ?? '')\n\t\t\t\t\t\t\t: JSON.stringify(errorResponse.body ?? {})\n\t\t\t\t\t\treturn new Response(body, {\n\t\t\t\t\t\t\tstatus: errorResponse.status,\n\t\t\t\t\t\t\theaders: errorResponse.headers,\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\n\t\t\t\t\tconst headers = new Headers(handlerResponse.headers)\n\t\t\t\t\tfor (const [key, value] of Object.entries(settlement.headers)) {\n\t\t\t\t\t\theaders.set(key, value)\n\t\t\t\t\t}\n\t\t\t\t\treturn new Response(handlerResponse.body, {\n\t\t\t\t\t\tstatus: handlerResponse.status,\n\t\t\t\t\t\theaders,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn { wrap, initialize }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,iBAAkB;AAEX,IAAM,YAAY;AAiElB,IAAM,yBAAyB,aAAE,OAAO;AAAA,EAC9C,QAAQ,aAAE,OAAO;AAAA,EACjB,SAAS,aAAE,OAAO;AAAA,EAClB,WAAW,aAAE,OAAO,EAAE,SAAS;AAAA,EAC/B,KAAK,aAAE,OAAO;AAAA,EACd,SAAS,aAAE,OAAO;AAAA,EAClB,SAAS,aAAE,OAAO;AAAA,EAClB,MAAM,aAAE,KAAK,CAAC,UAAU,SAAS,CAAC;AAAA,EAClC,OAAO,aAAE,OAAO;AAAA,EAChB,UAAU,aAAE,OAAO;AAAA,EACnB,gBAAgB,aAAE,OAAO,EAAE,SAAS;AAAA,EACpC,WAAW,aAAE,OAAO,EAAE,SAAS;AAAA,EAC/B,WAAW,aAAE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AAK,UAAU,cAAc,QAAQ,CAAC,CAAC;AAC1C,mBAAO,IAAI,SAAS,MAAM;AAAA,cACzB,QAAQ,cAAc;AAAA,cACtB,SAAS,cAAc;AAAA,YACxB,CAAC;AAAA,UACF;AAEA,gBAAM,UAAU,IAAI,QAAQ,gBAAgB,OAAO;AACnD,qBAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,WAAW,OAAO,GAAG;AAC9D,oBAAQ,IAAI,KAAK,KAAK;AAAA,UACvB;AACA,iBAAO,IAAI,SAAS,gBAAgB,MAAM;AAAA,YACzC,QAAQ,gBAAgB;AAAA,YACxB;AAAA,UACD,CAAC;AAAA,QACF;AAAA,MACD;AAAA,IACD;AAAA,EACD;AAEA,SAAO,EAAE,MAAM,WAAW;AAC3B;","names":["import_viem","getClient","import_zod","import_viem","getClient","import_viem","BIOMAPPER_AGENT_REGISTRY_ABI","import_viem","NETWORK_CHAIN_IDS","import_server"]}